From: Andreas Gerler Date: Wed, 14 Nov 2018 13:03:58 +0000 (+0100) Subject: initial commit. X-Git-Url: http://git.bundesbrandschatzamt.de/?a=commitdiff_plain;h=b43d1cc61196f1d505ef6071019f11d8809ff9de;p=emacsconfig.git initial commit. Signed-off-by: Andreas Gerler --- b43d1cc61196f1d505ef6071019f11d8809ff9de diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b12419d1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +/README.el +/bookmarks +*.elc +archive-contents +/ac-comphist.dat +/elpa/archives/* +/eshell/* +/history +/mthesaur.txt.cache +/org-clock-save.el* +/tramp +/url/* +/tldr +/recentf +/ido.last diff --git a/README.org b/README.org new file mode 100644 index 00000000..1457d342 --- /dev/null +++ b/README.org @@ -0,0 +1,203 @@ + +* Keybindings + +Just a few Keybindings to make your life easier. + +| key | command | +|-------------------------+-------------------| +| -c m | magit-status | +| -c - | jump to word | +| -g g | goto line | +| - | open config file. | + + +#+BEGIN_SRC emacs-lisp :tangle yes + (define-key global-map "\C-cm" 'magit-status) + (define-key global-map (kbd "C-c C-SPC") 'avy-goto-word-1) + (define-key global-map (kbd "M-g g") 'avy-goto-line) + (global-set-key (kbd "C-c ") '(lambda() (interactive) (find-file "~/.emacs.d/README.org"))) + (global-set-key (kbd "C-s") 'isearch-forward-regexp) + (global-set-key (kbd "C-r") 'isearch-backward-regexp) + (global-set-key (kbd "C-M-s") 'isearch-forward) + (global-set-key (kbd "C-M-r") 'isearch-backward) + +#+END_SRC + +* guide-key + +This helps you to remember keybindings. +Just start typing and wait a second or two. + +#+BEGIN_SRC emacs-lisp :tangle yes + (require 'guide-key) + (setq guide-key/guide-key-sequence '("C-x" "C-x C-k" "C-x 4" "C-c" "C-h" "C-x l" "" "")) + (setq guide-key/recursive-key-sequence-flag t) + (setq guide-key/idle-delay 3) + (guide-key-mode 1) +#+END_SRC + +* [[http://editorconfig.org/][editorconfig]] +[2017-01-06 Fri 14:27] + +Set default indentation, end of line, trailing whitespaces etc for the +whole team. No matter what editor gets used. + +#+BEGIN_SRC emacs-lisp :tangle yes + (editorconfig-mode '1) + +#+END_SRC + +* helm + +#+BEGIN_SRC emacs-lisp :tangle yes + (require 'helm) + (helm-mode 1) + (setq helm-mini-defaults-sources '(helm-source-buffers-list + helm-source-recentf + helm-source-bookmarks + helm-source-buffer-not-found)) + (define-key global-map "\C-xb" 'helm-mini) + (global-set-key "\C-cr" 'helm-recentf) + (define-key global-map "\C-x\C-k\C-h" 'helm-execute-kmacro) + (define-key global-map (kbd "C-x C-f") 'helm-find-files) + (global-set-key (kbd "M-y") 'helm-show-kill-ring) +#+END_SRC + +* [[http://www.emacswiki.org/emacs/RecentFiles][RecentFiles]] + +#+BEGIN_SRC emacs-lisp :tangle yes + (require 'recentf) + (recentf-mode 1) + (setq recentf-max-saved-items 200 + recentf-max-menu-items 142) + (global-set-key "\C-cr" 'recentf-open-files) +#+END_SRC + +* smartparens-mode + +Enable smart parens in all modes. +See [[https://github.com/toctan/smartparens][Smartparens on github]]. +Some key bindings taken from [[https://ebzzry.github.io/emacs-pairs.html][emacs-pairs]]. + +#+BEGIN_SRC emacs-lisp :tangle yes + (require 'smartparens) + (smartparens-global-mode 1) + (defmacro def-pairs (pairs) + `(progn + ,@(cl-loop for (key . val) in pairs + collect + `(defun ,(read (concat + "wrap-with-" + (prin1-to-string key) + "s")) + (&optional arg) + (interactive "p") + (sp-wrap-with-pair ,val))))) + + (def-pairs ((paren . "(") + (bracket . "[") + (brace . "{") + (single-quote . "'") + (double-quote . "\"") + (back-quote . "`"))) + + (define-key smartparens-mode-map (kbd "C-'") 'sp-rewrap-sexp) + (define-key smartparens-mode-map (kbd "C-c (") 'wrap-with-parens) + (define-key smartparens-mode-map (kbd "C-c ]") 'sp-backward-unwrap-sexp) + (define-key smartparens-mode-map (kbd "C-c )") 'sp-unwrap-sexp) + (define-key smartparens-mode-map (kbd "C-c [") 'wrap-with-brackets) + (define-key smartparens-mode-map (kbd "C-c {") 'wrap-with-braces) + (define-key smartparens-mode-map (kbd "") 'sp-beginning-of-sexp) + (define-key smartparens-mode-map (kbd "") 'sp-end-of-sexp) + (define-key smartparens-mode-map (kbd "") 'sp-up-sexp) + (define-key smartparens-mode-map (kbd "") 'sp-down-sexp) + (show-paren-mode 1) + (setq show-paren-style 'expression) + (setq blink-matching-paren-distance nil) +#+END_SRC + +* goto-match-paren +#+BEGIN_SRC emacs-lisp :tangle yes + (defun goto-match-paren (arg) + "Go to the matching parenthesis if on parenthesis, otherwise insert %. + vi style of % jumping to matching brace." + (interactive "p") + (cond ((looking-at "\\s\(") (forward-list 1) (backward-char 1)) + ((looking-at "\\s\)") (forward-char 1) (backward-list 1)) + (t (self-insert-command (or arg 1))))) + (global-set-key "%" 'goto-match-paren) + +#+END_SRC + +* save hash bang files executable +save files with #! in first line as user executable. + +#+BEGIN_SRC emacs-lisp :tangle yes + (add-hook `after-save-hook + #'(lambda () + (if (not + (or + (string-match ".htm" buffer-file-name) + (string-match ".org" buffer-file-name)) + ) + (check-parens)) + + (and (save-excursion + (save-restriction + (widen) + (goto-char (point-min)) + (save-match-data + (looking-at "^#!")))) + (if (file-remote-p buffer-file-name) + (progn + (not (file-executable-p buffer-file-name)) + (shell-command (concat "chmod u+x " (file-name-nondirectory buffer-file-name))) + (message + (concat "Saved as script via tramp: " buffer-file-name)) + ) + (progn + (not (file-executable-p buffer-file-name)) + (shell-command (concat "chmod u+x " buffer-file-name)) + (message + (concat "Saved as script: " buffer-file-name))))))) + +#+END_SRC + +* save history + [2015-04-05 Sun 12:57] + +Write a history of your emacs into your org git repository. +You have it available on every system and it's still private at it's +not in the public git emacs configuration. + +- kill ring +- search ring +- regexp-search-ring +- last-kbd-macro +- kmacro-ring +- shell-command-history + +all in your history. + +#+BEGIN_SRC emacs-lisp :tangle yes + (setq savehist-additional-variables '(kill-ring search-ring regexp-search-ring last-kbd-macro kmacro-ring shell-command-history)) + (setq kmacro-ring-max 42) + (setq history-delete-duplicates t) + (setq savehist-file "~/.emacshistory") + (if (file-exists-p savehist-file) + (load-file savehist-file)) + (savehist-mode 1) +#+END_SRC + +Confirm quit to avoid hitting C-x C-c by accident. + +#+BEGIN_SRC emacs-lisp :tangle yes + (setq confirm-kill-emacs 'yes-or-no-p) +#+END_SRC + +* syntax-highlighting +#+BEGIN_SRC emacs-lisp :tangle yes + (font-lock-mode) + (global-font-lock-mode 1) + +#+END_SRC diff --git a/elpa/async-20180527.1730/async-autoloads.el b/elpa/async-20180527.1730/async-autoloads.el new file mode 100644 index 00000000..addfab1a --- /dev/null +++ b/elpa/async-20180527.1730/async-autoloads.el @@ -0,0 +1,174 @@ +;;; async-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "async" "async.el" (0 0 0 0)) +;;; Generated autoloads from async.el + +(autoload 'async-start-process "async" "\ +Start the executable PROGRAM asynchronously. See `async-start'. +PROGRAM is passed PROGRAM-ARGS, calling FINISH-FUNC with the +process object when done. If FINISH-FUNC is nil, the future +object will return the process object when the program is +finished. Set DEFAULT-DIRECTORY to change PROGRAM's current +working directory. + +\(fn NAME PROGRAM FINISH-FUNC &rest PROGRAM-ARGS)" nil nil) + +(autoload 'async-start "async" "\ +Execute START-FUNC (often a lambda) in a subordinate Emacs process. +When done, the return value is passed to FINISH-FUNC. Example: + + (async-start + ;; What to do in the child process + (lambda () + (message \"This is a test\") + (sleep-for 3) + 222) + + ;; What to do when it finishes + (lambda (result) + (message \"Async process done, result should be 222: %s\" + result))) + +If FINISH-FUNC is nil or missing, a future is returned that can +be inspected using `async-get', blocking until the value is +ready. Example: + + (let ((proc (async-start + ;; What to do in the child process + (lambda () + (message \"This is a test\") + (sleep-for 3) + 222)))) + + (message \"I'm going to do some work here\") ;; .... + + (message \"Waiting on async process, result should be 222: %s\" + (async-get proc))) + +If you don't want to use a callback, and you don't care about any +return value from the child process, pass the `ignore' symbol as +the second argument (if you don't, and never call `async-get', it +will leave *emacs* process buffers hanging around): + + (async-start + (lambda () + (delete-file \"a remote file on a slow link\" nil)) + 'ignore) + +Note: Even when FINISH-FUNC is present, a future is still +returned except that it yields no value (since the value is +passed to FINISH-FUNC). Call `async-get' on such a future always +returns nil. It can still be useful, however, as an argument to +`async-ready' or `async-wait'. + +\(fn START-FUNC &optional FINISH-FUNC)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "async" '("async-"))) + +;;;*** + +;;;### (autoloads nil "async-bytecomp" "async-bytecomp.el" (0 0 0 +;;;;;; 0)) +;;; Generated autoloads from async-bytecomp.el + +(autoload 'async-byte-recompile-directory "async-bytecomp" "\ +Compile all *.el files in DIRECTORY asynchronously. +All *.elc files are systematically deleted before proceeding. + +\(fn DIRECTORY &optional QUIET)" nil nil) + +(defvar async-bytecomp-package-mode nil "\ +Non-nil if Async-Bytecomp-Package mode is enabled. +See the `async-bytecomp-package-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `async-bytecomp-package-mode'.") + +(custom-autoload 'async-bytecomp-package-mode "async-bytecomp" nil) + +(autoload 'async-bytecomp-package-mode "async-bytecomp" "\ +Byte compile asynchronously packages installed with package.el. +Async compilation of packages can be controlled by +`async-bytecomp-allowed-packages'. + +\(fn &optional ARG)" t nil) + +(autoload 'async-byte-compile-file "async-bytecomp" "\ +Byte compile Lisp code FILE asynchronously. + +Same as `byte-compile-file' but asynchronous. + +\(fn FILE)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "async-bytecomp" '("async-byte"))) + +;;;*** + +;;;### (autoloads nil "dired-async" "dired-async.el" (0 0 0 0)) +;;; Generated autoloads from dired-async.el + +(defvar dired-async-mode nil "\ +Non-nil if Dired-Async mode is enabled. +See the `dired-async-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `dired-async-mode'.") + +(custom-autoload 'dired-async-mode "dired-async" nil) + +(autoload 'dired-async-mode "dired-async" "\ +Do dired actions asynchronously. + +\(fn &optional ARG)" t nil) + +(autoload 'dired-async-do-copy "dired-async" "\ +Run ‘dired-do-copy’ asynchronously. + +\(fn &optional ARG)" t nil) + +(autoload 'dired-async-do-symlink "dired-async" "\ +Run ‘dired-do-symlink’ asynchronously. + +\(fn &optional ARG)" t nil) + +(autoload 'dired-async-do-hardlink "dired-async" "\ +Run ‘dired-do-hardlink’ asynchronously. + +\(fn &optional ARG)" t nil) + +(autoload 'dired-async-do-rename "dired-async" "\ +Run ‘dired-do-rename’ asynchronously. + +\(fn &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "dired-async" '("dired-async-"))) + +;;;*** + +;;;### (autoloads nil "smtpmail-async" "smtpmail-async.el" (0 0 0 +;;;;;; 0)) +;;; Generated autoloads from smtpmail-async.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "smtpmail-async" '("async-smtpmail-"))) + +;;;*** + +;;;### (autoloads nil nil ("async-pkg.el") (0 0 0 0)) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; async-autoloads.el ends here diff --git a/elpa/async-20180527.1730/async-bytecomp.el b/elpa/async-20180527.1730/async-bytecomp.el new file mode 100644 index 00000000..7bb2d46a --- /dev/null +++ b/elpa/async-20180527.1730/async-bytecomp.el @@ -0,0 +1,219 @@ +;;; async-bytecomp.el --- Compile elisp files asynchronously -*- lexical-binding: t -*- + +;; Copyright (C) 2014-2016 Free Software Foundation, Inc. + +;; Authors: John Wiegley +;; Thierry Volpiatto + +;; Keywords: dired async byte-compile +;; X-URL: https://github.com/jwiegley/dired-async + +;; 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; see the file COPYING. If not, write to the +;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, +;; Boston, MA 02111-1307, USA. + +;;; Commentary: +;; +;; This package provide the `async-byte-recompile-directory' function +;; which allows, as the name says to recompile a directory outside of +;; your running emacs. +;; The benefit is your files will be compiled in a clean environment without +;; the old *.el files loaded. +;; Among other things, this fix a bug in package.el which recompile +;; the new files in the current environment with the old files loaded, creating +;; errors in most packages after upgrades. +;; +;; NB: This package is advicing the function `package--compile'. + +;;; Code: + +(require 'cl-lib) +(require 'async) + +(defcustom async-bytecomp-allowed-packages + '(async helm helm-core helm-ls-git helm-ls-hg magit) + "Packages in this list will be compiled asynchronously by `package--compile'. +All the dependencies of these packages will be compiled async too, +so no need to add dependencies to this list. +The value of this variable can also be a list with a single element, +the symbol `all', in this case packages are always compiled asynchronously." + :group 'async + :type '(repeat (choice symbol))) + +(defvar async-byte-compile-log-file + (concat user-emacs-directory "async-bytecomp.log")) + +;;;###autoload +(defun async-byte-recompile-directory (directory &optional quiet) + "Compile all *.el files in DIRECTORY asynchronously. +All *.elc files are systematically deleted before proceeding." + (cl-loop with dir = (directory-files directory t "\\.elc\\'") + unless dir return nil + for f in dir + when (file-exists-p f) do (delete-file f)) + ;; Ensure async is reloaded when async.elc is deleted. + ;; This happen when recompiling its own directory. + (load "async") + (let ((call-back + (lambda (&optional _ignore) + (if (file-exists-p async-byte-compile-log-file) + (let ((buf (get-buffer-create byte-compile-log-buffer)) + (n 0)) + (with-current-buffer buf + (goto-char (point-max)) + (let ((inhibit-read-only t)) + (insert-file-contents async-byte-compile-log-file) + (compilation-mode)) + (display-buffer buf) + (delete-file async-byte-compile-log-file) + (unless quiet + (save-excursion + (goto-char (point-min)) + (while (re-search-forward "^.*:Error:" nil t) + (cl-incf n))) + (if (> n 0) + (message "Failed to compile %d files in directory `%s'" n directory) + (message "Directory `%s' compiled asynchronously with warnings" directory))))) + (unless quiet + (message "Directory `%s' compiled asynchronously with success" directory)))))) + (async-start + `(lambda () + (require 'bytecomp) + ,(async-inject-variables "\\`\\(load-path\\)\\|byte\\'") + (let ((default-directory (file-name-as-directory ,directory)) + error-data) + (add-to-list 'load-path default-directory) + (byte-recompile-directory ,directory 0 t) + (when (get-buffer byte-compile-log-buffer) + (setq error-data (with-current-buffer byte-compile-log-buffer + (buffer-substring-no-properties (point-min) (point-max)))) + (unless (string= error-data "") + (with-temp-file ,async-byte-compile-log-file + (erase-buffer) + (insert error-data)))))) + call-back) + (unless quiet (message "Started compiling asynchronously directory %s" directory)))) + +(defvar package-archive-contents) +(defvar package-alist) +(declare-function package-desc-reqs "package.el" (cl-x)) + +(defun async-bytecomp--get-package-deps (pkg &optional only) + ;; Same as `package--get-deps' but parse instead `package-archive-contents' + ;; because PKG is not already installed and not present in `package-alist'. + ;; However fallback to `package-alist' in case PKG no more present + ;; in `package-archive-contents' due to modification to `package-archives'. + ;; See issue #58. + (let* ((pkg-desc (cadr (or (assq pkg package-archive-contents) + (assq pkg package-alist)))) + (direct-deps (cl-loop for p in (package-desc-reqs pkg-desc) + for name = (car p) + when (or (assq name package-archive-contents) + (assq name package-alist)) + collect name)) + (indirect-deps (unless (eq only 'direct) + (delete-dups + (cl-loop for p in direct-deps append + (async-bytecomp--get-package-deps p)))))) + (cl-case only + (direct direct-deps) + (separate (list direct-deps indirect-deps)) + (indirect indirect-deps) + (t (delete-dups (append direct-deps indirect-deps)))))) + +(defun async-bytecomp-get-allowed-pkgs () + (when (and async-bytecomp-allowed-packages + (listp async-bytecomp-allowed-packages)) + (if package-archive-contents + (cl-loop for p in async-bytecomp-allowed-packages + when (assq p package-archive-contents) + append (async-bytecomp--get-package-deps p) into reqs + finally return + (delete-dups + (append async-bytecomp-allowed-packages reqs))) + async-bytecomp-allowed-packages))) + +(defadvice package--compile (around byte-compile-async) + (let ((cur-package (package-desc-name pkg-desc)) + (pkg-dir (package-desc-dir pkg-desc))) + (if (or (equal async-bytecomp-allowed-packages '(all)) + (memq cur-package (async-bytecomp-get-allowed-pkgs))) + (progn + (when (eq cur-package 'async) + (fmakunbound 'async-byte-recompile-directory)) + ;; Add to `load-path' the latest version of async and + ;; reload it when reinstalling async. + (when (string= cur-package "async") + (cl-pushnew pkg-dir load-path) + (load "async-bytecomp")) + ;; `async-byte-recompile-directory' will add directory + ;; as needed to `load-path'. + (async-byte-recompile-directory (package-desc-dir pkg-desc) t)) + ad-do-it))) + +;;;###autoload +(define-minor-mode async-bytecomp-package-mode + "Byte compile asynchronously packages installed with package.el. +Async compilation of packages can be controlled by +`async-bytecomp-allowed-packages'." + :group 'async + :global t + (if async-bytecomp-package-mode + (ad-activate 'package--compile) + (ad-deactivate 'package--compile))) + +;;;###autoload +(defun async-byte-compile-file (file) + "Byte compile Lisp code FILE asynchronously. + +Same as `byte-compile-file' but asynchronous." + (interactive "fFile: ") + (let ((call-back + (lambda (&optional _ignore) + (let ((bn (file-name-nondirectory file))) + (if (file-exists-p async-byte-compile-log-file) + (let ((buf (get-buffer-create byte-compile-log-buffer)) + start) + (with-current-buffer buf + (goto-char (setq start (point-max))) + (let ((inhibit-read-only t)) + (insert-file-contents async-byte-compile-log-file) + (compilation-mode)) + (display-buffer buf) + (delete-file async-byte-compile-log-file) + (save-excursion + (goto-char start) + (if (re-search-forward "^.*:Error:" nil t) + (message "Failed to compile `%s'" bn) + (message "`%s' compiled asynchronously with warnings" bn))))) + (message "`%s' compiled asynchronously with success" bn)))))) + (async-start + `(lambda () + (require 'bytecomp) + ,(async-inject-variables "\\`load-path\\'") + (let ((default-directory ,(file-name-directory file))) + (add-to-list 'load-path default-directory) + (byte-compile-file ,file) + (when (get-buffer byte-compile-log-buffer) + (setq error-data (with-current-buffer byte-compile-log-buffer + (buffer-substring-no-properties (point-min) (point-max)))) + (unless (string= error-data "") + (with-temp-file ,async-byte-compile-log-file + (erase-buffer) + (insert error-data)))))) + call-back))) + +(provide 'async-bytecomp) + +;;; async-bytecomp.el ends here diff --git a/elpa/async-20180527.1730/async-pkg.el b/elpa/async-20180527.1730/async-pkg.el new file mode 100644 index 00000000..507e0666 --- /dev/null +++ b/elpa/async-20180527.1730/async-pkg.el @@ -0,0 +1,6 @@ +(define-package "async" "20180527.1730" "Asynchronous processing in Emacs" 'nil :keywords + '("async") + :url "https://github.com/jwiegley/emacs-async") +;; Local Variables: +;; no-byte-compile: t +;; End: diff --git a/elpa/async-20180527.1730/async.el b/elpa/async-20180527.1730/async.el new file mode 100644 index 00000000..771e6410 --- /dev/null +++ b/elpa/async-20180527.1730/async.el @@ -0,0 +1,392 @@ +;;; async.el --- Asynchronous processing in Emacs -*- lexical-binding: t -*- + +;; Copyright (C) 2012-2016 Free Software Foundation, Inc. + +;; Author: John Wiegley +;; Created: 18 Jun 2012 +;; Version: 1.9.3 + +;; Keywords: async +;; X-URL: https://github.com/jwiegley/emacs-async + +;; 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; see the file COPYING. If not, write to the +;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, +;; Boston, MA 02111-1307, USA. + +;;; Commentary: + +;; Adds the ability to call asynchronous functions and process with ease. See +;; the documentation for `async-start' and `async-start-process'. + +;;; Code: + +(eval-when-compile (require 'cl-lib)) + +(defgroup async nil + "Simple asynchronous processing in Emacs" + :group 'emacs) + +(defcustom async-variables-noprops-function #'async-variables-noprops + "Default function to remove text properties in variables." + :group 'async + :type 'function) + +(defvar async-debug nil) +(defvar async-send-over-pipe t) +(defvar async-in-child-emacs nil) +(defvar async-callback nil) +(defvar async-callback-for-process nil) +(defvar async-callback-value nil) +(defvar async-callback-value-set nil) +(defvar async-current-process nil) +(defvar async--procvar nil) + +(defun async-variables-noprops (sequence) + "Remove text properties in SEQUENCE. + +Argument SEQUENCE may be a list or a string, if anything else it +is returned unmodified. + +Note that this is a naive function that doesn't remove text properties +in SEQUENCE recursively, only at the first level which suffice in most +cases." + (cond ((stringp sequence) + (substring-no-properties sequence)) + ((listp sequence) + (cl-loop for elm in sequence + if (stringp elm) + collect (substring-no-properties elm) + else collect elm)) + (t sequence))) + +(defun async-inject-variables + (include-regexp &optional predicate exclude-regexp noprops) + "Return a `setq' form that replicates part of the calling environment. + +It sets the value for every variable matching INCLUDE-REGEXP and +also PREDICATE. It will not perform injection for any variable +matching EXCLUDE-REGEXP (if present) or representing a syntax-table +i.e. ending by \"-syntax-table\". +When NOPROPS is non nil it tries to strip out text properties of each +variable's value with `async-variables-noprops-function'. + +It is intended to be used as follows: + + (async-start + `(lambda () + (require 'smtpmail) + (with-temp-buffer + (insert ,(buffer-substring-no-properties (point-min) (point-max))) + ;; Pass in the variable environment for smtpmail + ,(async-inject-variables \"\\`\\(smtpmail\\|\\(user-\\)?mail\\)-\") + (smtpmail-send-it))) + 'ignore)" + `(setq + ,@(let (bindings) + (mapatoms + (lambda (sym) + (let* ((sname (and (boundp sym) (symbol-name sym))) + (value (and sname (symbol-value sym)))) + (when (and sname + (or (null include-regexp) + (string-match include-regexp sname)) + (or (null exclude-regexp) + (not (string-match exclude-regexp sname))) + (not (string-match "-syntax-table\\'" sname))) + (unless (or (stringp value) + (memq value '(nil t)) + (numberp value) + (vectorp value)) + (setq value `(quote ,value))) + (when noprops + (setq value (funcall async-variables-noprops-function + value))) + (when (or (null predicate) + (funcall predicate sym)) + (setq bindings (cons value bindings) + bindings (cons sym bindings))))))) + bindings))) + +(defalias 'async-inject-environment 'async-inject-variables) + +(defun async-handle-result (func result buf) + (if (null func) + (progn + (set (make-local-variable 'async-callback-value) result) + (set (make-local-variable 'async-callback-value-set) t)) + (unwind-protect + (if (and (listp result) + (eq 'async-signal (nth 0 result))) + (signal (car (nth 1 result)) + (cdr (nth 1 result))) + (funcall func result)) + (unless async-debug + (kill-buffer buf))))) + +(defun async-when-done (proc &optional _change) + "Process sentinel used to retrieve the value from the child process." + (when (eq 'exit (process-status proc)) + (with-current-buffer (process-buffer proc) + (let ((async-current-process proc)) + (if (= 0 (process-exit-status proc)) + (if async-callback-for-process + (if async-callback + (prog1 + (funcall async-callback proc) + (unless async-debug + (kill-buffer (current-buffer)))) + (set (make-local-variable 'async-callback-value) proc) + (set (make-local-variable 'async-callback-value-set) t)) + (goto-char (point-max)) + (backward-sexp) + (async-handle-result async-callback (read (current-buffer)) + (current-buffer))) + (set (make-local-variable 'async-callback-value) + (list 'error + (format "Async process '%s' failed with exit code %d" + (process-name proc) (process-exit-status proc)))) + (set (make-local-variable 'async-callback-value-set) t)))))) + +(defun async--receive-sexp (&optional stream) + (let ((sexp (decode-coding-string (base64-decode-string + (read stream)) 'utf-8-auto)) + ;; Parent expects UTF-8 encoded text. + (coding-system-for-write 'utf-8-auto)) + (if async-debug + (message "Received sexp {{{%s}}}" (pp-to-string sexp))) + (setq sexp (read sexp)) + (if async-debug + (message "Read sexp {{{%s}}}" (pp-to-string sexp))) + (eval sexp))) + +(defun async--insert-sexp (sexp) + (let (print-level + print-length + (print-escape-nonascii t) + (print-circle t)) + (prin1 sexp (current-buffer)) + ;; Just in case the string we're sending might contain EOF + (encode-coding-region (point-min) (point-max) 'utf-8-auto) + (base64-encode-region (point-min) (point-max) t) + (goto-char (point-min)) (insert ?\") + (goto-char (point-max)) (insert ?\" ?\n))) + +(defun async--transmit-sexp (process sexp) + (with-temp-buffer + (if async-debug + (message "Transmitting sexp {{{%s}}}" (pp-to-string sexp))) + (async--insert-sexp sexp) + (process-send-region process (point-min) (point-max)))) + +(defun async-batch-invoke () + "Called from the child Emacs process' command-line." + ;; Make sure 'message' and 'prin1' encode stuff in UTF-8, as parent + ;; process expects. + (let ((coding-system-for-write 'utf-8-auto)) + (setq async-in-child-emacs t + debug-on-error async-debug) + (if debug-on-error + (prin1 (funcall + (async--receive-sexp (unless async-send-over-pipe + command-line-args-left)))) + (condition-case err + (prin1 (funcall + (async--receive-sexp (unless async-send-over-pipe + command-line-args-left)))) + (error + (prin1 (list 'async-signal err))))))) + +(defun async-ready (future) + "Query a FUTURE to see if it is ready. + +I.e., if no blocking +would result from a call to `async-get' on that FUTURE." + (and (memq (process-status future) '(exit signal)) + (let ((buf (process-buffer future))) + (if (buffer-live-p buf) + (with-current-buffer buf + async-callback-value-set) + t)))) + +(defun async-wait (future) + "Wait for FUTURE to become ready." + (while (not (async-ready future)) + (sleep-for 0.05))) + +(defun async-get (future) + "Get the value from process FUTURE when it is ready. +FUTURE is returned by `async-start' or `async-start-process' when +its FINISH-FUNC is nil." + (and future (async-wait future)) + (let ((buf (process-buffer future))) + (when (buffer-live-p buf) + (with-current-buffer buf + (async-handle-result + #'identity async-callback-value (current-buffer)))))) + +(defun async-message-p (value) + "Return true of VALUE is an async.el message packet." + (and (listp value) + (plist-get value :async-message))) + +(defun async-send (&rest args) + "Send the given messages to the asychronous Emacs PROCESS." + (let ((args (append args '(:async-message t)))) + (if async-in-child-emacs + (if async-callback + (funcall async-callback args)) + (async--transmit-sexp (car args) (list 'quote (cdr args)))))) + +(defun async-receive () + "Send the given messages to the asychronous Emacs PROCESS." + (async--receive-sexp)) + +;;;###autoload +(defun async-start-process (name program finish-func &rest program-args) + "Start the executable PROGRAM asynchronously. See `async-start'. +PROGRAM is passed PROGRAM-ARGS, calling FINISH-FUNC with the +process object when done. If FINISH-FUNC is nil, the future +object will return the process object when the program is +finished. Set DEFAULT-DIRECTORY to change PROGRAM's current +working directory." + (let* ((buf (generate-new-buffer (concat "*" name "*"))) + (proc (let ((process-connection-type nil)) + (apply #'start-process name buf program program-args)))) + (with-current-buffer buf + (set (make-local-variable 'async-callback) finish-func) + (set-process-sentinel proc #'async-when-done) + (unless (string= name "emacs") + (set (make-local-variable 'async-callback-for-process) t)) + proc))) + +(defvar async-quiet-switch "-Q" + "The Emacs parameter to use to call emacs without config. +Can be one of \"-Q\" or \"-q\". +Default is \"-Q\" but it is sometimes useful to use \"-q\" to have a +enhanced config or some more variables loaded.") + +;;;###autoload +(defun async-start (start-func &optional finish-func) + "Execute START-FUNC (often a lambda) in a subordinate Emacs process. +When done, the return value is passed to FINISH-FUNC. Example: + + (async-start + ;; What to do in the child process + (lambda () + (message \"This is a test\") + (sleep-for 3) + 222) + + ;; What to do when it finishes + (lambda (result) + (message \"Async process done, result should be 222: %s\" + result))) + +If FINISH-FUNC is nil or missing, a future is returned that can +be inspected using `async-get', blocking until the value is +ready. Example: + + (let ((proc (async-start + ;; What to do in the child process + (lambda () + (message \"This is a test\") + (sleep-for 3) + 222)))) + + (message \"I'm going to do some work here\") ;; .... + + (message \"Waiting on async process, result should be 222: %s\" + (async-get proc))) + +If you don't want to use a callback, and you don't care about any +return value from the child process, pass the `ignore' symbol as +the second argument (if you don't, and never call `async-get', it +will leave *emacs* process buffers hanging around): + + (async-start + (lambda () + (delete-file \"a remote file on a slow link\" nil)) + 'ignore) + +Note: Even when FINISH-FUNC is present, a future is still +returned except that it yields no value (since the value is +passed to FINISH-FUNC). Call `async-get' on such a future always +returns nil. It can still be useful, however, as an argument to +`async-ready' or `async-wait'." + (let ((sexp start-func) + ;; Subordinate Emacs will send text encoded in UTF-8. + (coding-system-for-read 'utf-8-auto)) + (setq async--procvar + (async-start-process + "emacs" (file-truename + (expand-file-name invocation-name + invocation-directory)) + finish-func + async-quiet-switch "-l" + ;; Using `locate-library' ensure we use the right file + ;; when the .elc have been deleted. + (locate-library "async") + "-batch" "-f" "async-batch-invoke" + (if async-send-over-pipe + "" + (with-temp-buffer + (async--insert-sexp (list 'quote sexp)) + (buffer-string))))) + (if async-send-over-pipe + (async--transmit-sexp async--procvar (list 'quote sexp))) + async--procvar)) + +(defmacro async-sandbox(func) + "Evaluate FUNC in a separate Emacs process, synchronously." + `(async-get (async-start ,func))) + +(defun async--fold-left (fn forms bindings) + (let ((res forms)) + (dolist (binding bindings) + (setq res (funcall fn res + (if (listp binding) + binding + (list binding))))) + res)) + +(defmacro async-let (bindings &rest forms) + "Implements `let', but each binding is established asynchronously. +For example: + + (async-let ((x (foo)) + (y (bar))) + (message \"%s %s\" x y)) + + expands to ==> + + (async-start (foo) + (lambda (x) + (async-start (bar) + (lambda (y) + (message \"%s %s\" x y)))))" + (declare (indent 1)) + (async--fold-left + (lambda (acc binding) + (let ((fun (pcase (cadr binding) + ((and (pred functionp) f) f) + (f `(lambda () ,f))))) + `(async-start ,fun + (lambda (,(car binding)) + ,acc)))) + `(progn ,@forms) + (reverse bindings))) + +(provide 'async) + +;;; async.el ends here diff --git a/elpa/async-20180527.1730/dired-async.el b/elpa/async-20180527.1730/dired-async.el new file mode 100644 index 00000000..bc406b39 --- /dev/null +++ b/elpa/async-20180527.1730/dired-async.el @@ -0,0 +1,405 @@ +;;; dired-async.el --- Asynchronous dired actions -*- lexical-binding: t -*- + +;; Copyright (C) 2012-2016 Free Software Foundation, Inc. + +;; Authors: John Wiegley +;; Thierry Volpiatto + +;; Keywords: dired async network +;; X-URL: https://github.com/jwiegley/dired-async + +;; 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; see the file COPYING. If not, write to the +;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, +;; Boston, MA 02111-1307, USA. + +;;; Commentary: + +;; This file provide a redefinition of `dired-create-file' function, +;; performs copies, moves and all what is handled by `dired-create-file' +;; in the background using a slave Emacs process, +;; by means of the async.el module. +;; To use it, put this in your .emacs: + +;; (dired-async-mode 1) + +;; This will enable async copy/rename etc... +;; in dired and helm. + +;;; Code: + +(require 'cl-lib) +(require 'dired-aux) +(require 'async) + +(eval-when-compile + (defvar async-callback)) + +(defgroup dired-async nil + "Copy rename files asynchronously from dired." + :group 'dired) + +(defcustom dired-async-env-variables-regexp + "\\`\\(tramp-\\(default\\|connection\\|remote\\)\\|ange-ftp\\)-.*" + "Variables matching this regexp will be loaded on Child Emacs." + :type 'regexp + :group 'dired-async) + +(defcustom dired-async-message-function 'dired-async-mode-line-message + "Function to use to notify result when operation finish. +Should take same args as `message'." + :group 'dired-async + :type 'function) + +(defcustom dired-async-log-file "/tmp/dired-async.log" + "File use to communicate errors from Child Emacs to host Emacs." + :group 'dired-async + :type 'string) + +(defcustom dired-async-mode-lighter '(:eval + (when (eq major-mode 'dired-mode) + " Async")) + "Mode line lighter used for `dired-async-mode'." + :group 'dired-async + :risky t + :type 'sexp) + +(defface dired-async-message + '((t (:foreground "yellow"))) + "Face used for mode-line message." + :group 'dired-async) + +(defface dired-async-failures + '((t (:foreground "red"))) + "Face used for mode-line message." + :group 'dired-async) + +(defface dired-async-mode-message + '((t (:foreground "Gold"))) + "Face used for `dired-async--modeline-mode' lighter." + :group 'dired-async) + +(define-minor-mode dired-async--modeline-mode + "Notify mode-line that an async process run." + :group 'dired-async + :global t + :lighter (:eval (propertize (format " [%s Async job(s) running]" + (length (dired-async-processes))) + 'face 'dired-async-mode-message)) + (unless dired-async--modeline-mode + (let ((visible-bell t)) (ding)))) + +(defun dired-async-mode-line-message (text face &rest args) + "Notify end of operation in `mode-line'." + (message nil) + (let ((mode-line-format (concat + " " (propertize + (if args + (apply #'format text args) + text) + 'face face)))) + (force-mode-line-update) + (sit-for 3) + (force-mode-line-update))) + +(defun dired-async-processes () + (cl-loop for p in (process-list) + when (cl-loop for c in (process-command p) thereis + (string= "async-batch-invoke" c)) + collect p)) + +(defun dired-async-kill-process () + (interactive) + (let* ((processes (dired-async-processes)) + (proc (car (last processes)))) + (and proc (delete-process proc)) + (unless (> (length processes) 1) + (dired-async--modeline-mode -1)))) + +(defun dired-async-after-file-create (total operation failures skipped) + "Callback function used for operation handled by `dired-create-file'." + (unless (dired-async-processes) + ;; Turn off mode-line notification + ;; only when last process end. + (dired-async--modeline-mode -1)) + (when operation + (if (file-exists-p dired-async-log-file) + (progn + (pop-to-buffer (get-buffer-create dired-log-buffer)) + (goto-char (point-max)) + (setq inhibit-read-only t) + (insert "Error: ") + (insert-file-contents dired-async-log-file) + (special-mode) + (shrink-window-if-larger-than-buffer) + (delete-file dired-async-log-file)) + (run-with-timer + 0.1 nil + (lambda () + ;; First send error messages. + (cond (failures + (funcall dired-async-message-function + "%s failed for %d of %d file%s -- See *Dired log* buffer" + 'dired-async-failures + (car operation) (length failures) + total (dired-plural-s total))) + (skipped + (funcall dired-async-message-function + "%s: %d of %d file%s skipped -- See *Dired log* buffer" + 'dired-async-failures + (car operation) (length skipped) total + (dired-plural-s total)))) + (when dired-buffers + (cl-loop for (_f . b) in dired-buffers + when (buffer-live-p b) + do (with-current-buffer b (revert-buffer nil t)))) + ;; Finally send the success message. + (funcall dired-async-message-function + "Asynchronous %s of %s on %s file%s done" + 'dired-async-message + (car operation) (cadr operation) + total (dired-plural-s total))))))) + +(defun dired-async-maybe-kill-ftp () + "Return a form to kill ftp process in child emacs." + (quote + (progn + (require 'cl-lib) + (let ((buf (cl-loop for b in (buffer-list) + thereis (and (string-match + "\\`\\*ftp.*" + (buffer-name b)) b)))) + (when buf (kill-buffer buf)))))) + +(defvar overwrite-query) +(defun dired-async-create-files (file-creator operation fn-list name-constructor + &optional _marker-char) + "Same as `dired-create-files' but asynchronous. + +See `dired-create-files' for the behavior of arguments." + (setq overwrite-query nil) + (let ((total (length fn-list)) + failures async-fn-list skipped callback + async-quiet-switch) + (let (to) + (dolist (from fn-list) + (setq to (funcall name-constructor from)) + (if (and (equal to from) + (null (eq file-creator 'backup-file))) + (progn + (setq to nil) + (dired-log "Cannot %s to same file: %s\n" + (downcase operation) from))) + (if (not to) + (setq skipped (cons (dired-make-relative from) skipped)) + (let* ((overwrite (and (null (eq file-creator 'backup-file)) + (file-exists-p to))) + (dired-overwrite-confirmed ; for dired-handle-overwrite + (and overwrite + (let ((help-form `(format "\ +Type SPC or `y' to overwrite file `%s', +DEL or `n' to skip to next, +ESC or `q' to not overwrite any of the remaining files, +`!' to overwrite all remaining files with no more questions." ,to))) + (dired-query 'overwrite-query "Overwrite `%s'?" to))))) + ;; Handle the `dired-copy-file' file-creator specially + ;; When copying a directory to another directory or + ;; possibly to itself or one of its subdirectories. + ;; e.g "~/foo/" => "~/test/" + ;; or "~/foo/" =>"~/foo/" + ;; or "~/foo/ => ~/foo/bar/") + ;; In this case the 'name-constructor' have set the destination + ;; TO to "~/test/foo" because the old emacs23 behavior + ;; of `copy-directory' was to not create the subdirectory + ;; and instead copy the contents. + ;; With the new behavior of `copy-directory' + ;; (similar to the `cp' shell command) we don't + ;; need such a construction of the target directory, + ;; so modify the destination TO to "~/test/" instead of "~/test/foo/". + (let ((destname (file-name-directory to))) + (when (and (file-directory-p from) + (file-directory-p to) + (eq file-creator 'dired-copy-file)) + (setq to destname)) + ;; If DESTNAME is a subdirectory of FROM, not a symlink, + ;; and the method in use is copying, signal an error. + (and (eq t (car (file-attributes destname))) + (eq file-creator 'dired-copy-file) + (file-in-directory-p destname from) + (error "Cannot copy `%s' into its subdirectory `%s'" + from to))) + (if overwrite + (or (and dired-overwrite-confirmed + (push (cons from to) async-fn-list)) + (progn + (push (dired-make-relative from) failures) + (dired-log "%s `%s' to `%s' failed\n" + operation from to))) + (push (cons from to) async-fn-list))))) + ;; Fix tramp issue #80 with emacs-26, use "-q" only when needed. + (setq async-quiet-switch + (if (and (boundp 'tramp-cache-read-persistent-data) + async-fn-list + (cl-loop for (_from . to) in async-fn-list + thereis (file-remote-p to))) + "-q" "-Q")) + ;; When failures have been printed to dired log add the date at bob. + (when (or failures skipped) (dired-log t)) + ;; When async-fn-list is empty that's mean only one file + ;; had to be copied and user finally answer NO. + ;; In this case async process will never start and callback + ;; will have no chance to run, so notify failures here. + (unless async-fn-list + (cond (failures + (funcall dired-async-message-function + "%s failed for %d of %d file%s -- See *Dired log* buffer" + 'dired-async-failures + operation (length failures) + total (dired-plural-s total))) + (skipped + (funcall dired-async-message-function + "%s: %d of %d file%s skipped -- See *Dired log* buffer" + 'dired-async-failures + operation (length skipped) total + (dired-plural-s total))))) + ;; Setup callback. + (setq callback + (lambda (&optional _ignore) + (dired-async-after-file-create + total (list operation (length async-fn-list)) failures skipped) + (when (string= (downcase operation) "rename") + (cl-loop for (file . to) in async-fn-list + for bf = (get-file-buffer file) + for destp = (file-exists-p to) + do (and bf destp + (with-current-buffer bf + (set-visited-file-name to t t)))))))) + ;; Start async process. + (when async-fn-list + (async-start `(lambda () + (require 'cl-lib) (require 'dired-aux) (require 'dired-x) + ,(async-inject-variables dired-async-env-variables-regexp) + (let ((dired-recursive-copies (quote always)) + (dired-copy-preserve-time + ,dired-copy-preserve-time)) + (setq overwrite-backup-query nil) + ;; Inline `backup-file' as long as it is not + ;; available in emacs. + (defalias 'backup-file + ;; Same feature as "cp -f --backup=numbered from to" + ;; Symlinks are copied as file from source unlike + ;; `dired-copy-file' which is same as cp -d. + ;; Directories are omitted. + (lambda (from to ok) + (cond ((file-directory-p from) (ignore)) + (t (let ((count 0)) + (while (let ((attrs (file-attributes to))) + (and attrs (null (nth 0 attrs)))) + (cl-incf count) + (setq to (concat (file-name-sans-versions to) + (format ".~%s~" count))))) + (condition-case err + (copy-file from to ok dired-copy-preserve-time) + (file-date-error + (dired-log "Can't set date on %s:\n%s\n" from err))))))) + ;; Now run the FILE-CREATOR function on files. + (cl-loop with fn = (quote ,file-creator) + for (from . dest) in (quote ,async-fn-list) + do (condition-case err + (funcall fn from dest t) + (file-error + (dired-log "%s: %s\n" (car err) (cdr err))) + nil)) + (when (get-buffer dired-log-buffer) + (dired-log t) + (with-current-buffer dired-log-buffer + (write-region (point-min) (point-max) + ,dired-async-log-file)))) + ,(dired-async-maybe-kill-ftp)) + callback) + ;; Run mode-line notifications while process running. + (dired-async--modeline-mode 1) + (message "%s proceeding asynchronously..." operation)))) + +(defvar wdired-use-interactive-rename) +(defun dired-async-wdired-do-renames (old-fn &rest args) + ;; Perhaps a better fix would be to ask for renaming BEFORE starting + ;; OLD-FN when `wdired-use-interactive-rename' is non-nil. For now + ;; just bind it to nil to ensure no questions will be asked between + ;; each rename. + (let (wdired-use-interactive-rename) + (apply old-fn args))) + +(defadvice wdired-do-renames (around wdired-async) + (let (wdired-use-interactive-rename) + ad-do-it)) + +(defadvice dired-create-files (around dired-async) + (dired-async-create-files file-creator operation fn-list + name-constructor marker-char)) + +;;;###autoload +(define-minor-mode dired-async-mode + "Do dired actions asynchronously." + :group 'dired-async + :lighter dired-async-mode-lighter + :global t + (if dired-async-mode + (if (fboundp 'advice-add) + (progn (advice-add 'dired-create-files :override #'dired-async-create-files) + (advice-add 'wdired-do-renames :around #'dired-async-wdired-do-renames)) + (ad-activate 'dired-create-files) + (ad-activate 'wdired-do-renames)) + (if (fboundp 'advice-remove) + (progn (advice-remove 'dired-create-files #'dired-async-create-files) + (advice-remove 'wdired-do-renames #'dired-async-wdired-do-renames)) + (ad-deactivate 'dired-create-files) + (ad-deactivate 'wdired-do-renames)))) + +(defmacro dired-async--with-async-create-files (&rest body) + "Evaluate BODY with ‘dired-create-files’ set to ‘dired-async-create-files’." + (declare (indent 0)) + `(cl-letf (((symbol-function 'dired-create-files) #'dired-async-create-files)) + ,@body)) + +;;;###autoload +(defun dired-async-do-copy (&optional arg) + "Run ‘dired-do-copy’ asynchronously." + (interactive "P") + (dired-async--with-async-create-files + (dired-do-copy arg))) + +;;;###autoload +(defun dired-async-do-symlink (&optional arg) + "Run ‘dired-do-symlink’ asynchronously." + (interactive "P") + (dired-async--with-async-create-files + (dired-do-symlink arg))) + +;;;###autoload +(defun dired-async-do-hardlink (&optional arg) + "Run ‘dired-do-hardlink’ asynchronously." + (interactive "P") + (dired-async--with-async-create-files + (dired-do-hardlink arg))) + +;;;###autoload +(defun dired-async-do-rename (&optional arg) + "Run ‘dired-do-rename’ asynchronously." + (interactive "P") + (dired-async--with-async-create-files + (dired-do-rename arg))) + +(provide 'dired-async) + +;;; dired-async.el ends here diff --git a/elpa/async-20180527.1730/smtpmail-async.el b/elpa/async-20180527.1730/smtpmail-async.el new file mode 100644 index 00000000..ac269231 --- /dev/null +++ b/elpa/async-20180527.1730/smtpmail-async.el @@ -0,0 +1,73 @@ +;;; smtpmail-async.el --- Send e-mail with smtpmail.el asynchronously -*- lexical-binding: t -*- + +;; Copyright (C) 2012-2016 Free Software Foundation, Inc. + +;; Author: John Wiegley +;; Created: 18 Jun 2012 + +;; Keywords: email async +;; X-URL: https://github.com/jwiegley/emacs-async + +;; 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; see the file COPYING. If not, write to the +;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, +;; Boston, MA 02111-1307, USA. + +;;; Commentary: + +;; Send e-mail with smtpmail.el asynchronously. To use: +;; +;; (require 'smtpmail-async) +;; +;; (setq send-mail-function 'async-smtpmail-send-it +;; message-send-mail-function 'async-smtpmail-send-it) +;; +;; This assumes you already have smtpmail.el working. + +;;; Code: + +(defgroup smtpmail-async nil + "Send e-mail with smtpmail.el asynchronously" + :group 'smptmail) + +(require 'async) +(require 'smtpmail) +(require 'message) + +(defvar async-smtpmail-before-send-hook nil + "Hook running in the child emacs in `async-smtpmail-send-it'. +It is called just before calling `smtpmail-send-it'.") + +(defun async-smtpmail-send-it () + (let ((to (message-field-value "To")) + (buf-content (buffer-substring-no-properties + (point-min) (point-max)))) + (message "Delivering message to %s..." to) + (async-start + `(lambda () + (require 'smtpmail) + (with-temp-buffer + (insert ,buf-content) + (set-buffer-multibyte nil) + ;; Pass in the variable environment for smtpmail + ,(async-inject-variables + "\\`\\(smtpmail\\|async-smtpmail\\|\\(user-\\)?mail\\)-\\|auth-sources\\|epg\\|nsm" + nil "\\`\\(mail-header-format-function\\|smtpmail-address-buffer\\|mail-mode-abbrev-table\\)") + (run-hooks 'async-smtpmail-before-send-hook) + (smtpmail-send-it))) + (lambda (&optional _ignore) + (message "Delivering message to %s...done" to))))) + +(provide 'smtpmail-async) + +;;; smtpmail-async.el ends here diff --git a/elpa/avy-20181009.1648/avy-autoloads.el b/elpa/avy-20181009.1648/avy-autoloads.el new file mode 100644 index 00000000..e0b0fa3a --- /dev/null +++ b/elpa/avy-20181009.1648/avy-autoloads.el @@ -0,0 +1,264 @@ +;;; avy-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "avy" "avy.el" (0 0 0 0)) +;;; Generated autoloads from avy.el + +(autoload 'avy-goto-char "avy" "\ +Jump to the currently visible CHAR. +The window scope is determined by `avy-all-windows' (ARG negates it). + +\(fn CHAR &optional ARG)" t nil) + +(autoload 'avy-goto-char-in-line "avy" "\ +Jump to the currently visible CHAR in the current line. + +\(fn CHAR)" t nil) + +(autoload 'avy-goto-char-2 "avy" "\ +Jump to the currently visible CHAR1 followed by CHAR2. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. +BEG and END narrow the scope where candidates are searched. + +\(fn CHAR1 CHAR2 &optional ARG BEG END)" t nil) + +(autoload 'avy-goto-char-2-above "avy" "\ +Jump to the currently visible CHAR1 followed by CHAR2. +This is a scoped version of `avy-goto-char-2', where the scope is +the visible part of the current buffer up to point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. + +\(fn CHAR1 CHAR2 &optional ARG)" t nil) + +(autoload 'avy-goto-char-2-below "avy" "\ +Jump to the currently visible CHAR1 followed by CHAR2. +This is a scoped version of `avy-goto-char-2', where the scope is +the visible part of the current buffer following point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. + +\(fn CHAR1 CHAR2 &optional ARG)" t nil) + +(autoload 'avy-isearch "avy" "\ +Jump to one of the current isearch candidates. + +\(fn)" t nil) + +(autoload 'avy-goto-word-0 "avy" "\ +Jump to a word start. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. +BEG and END narrow the scope where candidates are searched. + +\(fn ARG &optional BEG END)" t nil) + +(autoload 'avy-goto-word-1 "avy" "\ +Jump to the currently visible CHAR at a word start. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. +BEG and END narrow the scope where candidates are searched. +When SYMBOL is non-nil, jump to symbol start instead of word start. + +\(fn CHAR &optional ARG BEG END SYMBOL)" t nil) + +(autoload 'avy-goto-word-1-above "avy" "\ +Jump to the currently visible CHAR at a word start. +This is a scoped version of `avy-goto-word-1', where the scope is +the visible part of the current buffer up to point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. + +\(fn CHAR &optional ARG)" t nil) + +(autoload 'avy-goto-word-1-below "avy" "\ +Jump to the currently visible CHAR at a word start. +This is a scoped version of `avy-goto-word-1', where the scope is +the visible part of the current buffer following point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. + +\(fn CHAR &optional ARG)" t nil) + +(autoload 'avy-goto-symbol-1 "avy" "\ +Jump to the currently visible CHAR at a symbol start. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. + +\(fn CHAR &optional ARG)" t nil) + +(autoload 'avy-goto-symbol-1-above "avy" "\ +Jump to the currently visible CHAR at a symbol start. +This is a scoped version of `avy-goto-symbol-1', where the scope is +the visible part of the current buffer up to point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. + +\(fn CHAR &optional ARG)" t nil) + +(autoload 'avy-goto-symbol-1-below "avy" "\ +Jump to the currently visible CHAR at a symbol start. +This is a scoped version of `avy-goto-symbol-1', where the scope is +the visible part of the current buffer following point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. + +\(fn CHAR &optional ARG)" t nil) + +(autoload 'avy-goto-subword-0 "avy" "\ +Jump to a word or subword start. +The window scope is determined by `avy-all-windows' (ARG negates it). + +When PREDICATE is non-nil it's a function of zero parameters that +should return true. + +BEG and END narrow the scope where candidates are searched. + +\(fn &optional ARG PREDICATE BEG END)" t nil) + +(autoload 'avy-goto-subword-1 "avy" "\ +Jump to the currently visible CHAR at a subword start. +The window scope is determined by `avy-all-windows' (ARG negates it). +The case of CHAR is ignored. + +\(fn CHAR &optional ARG)" t nil) + +(autoload 'avy-goto-word-or-subword-1 "avy" "\ +Forward to `avy-goto-subword-1' or `avy-goto-word-1'. +Which one depends on variable `subword-mode'. + +\(fn)" t nil) + +(autoload 'avy-goto-line "avy" "\ +Jump to a line start in current buffer. + +When ARG is 1, jump to lines currently visible, with the option +to cancel to `goto-line' by entering a number. + +When ARG is 4, negate the window scope determined by +`avy-all-windows'. + +Otherwise, forward to `goto-line' with ARG. + +\(fn &optional ARG)" t nil) + +(autoload 'avy-goto-line-above "avy" "\ +Goto visible line above the cursor. +OFFSET changes the distance between the closest key to the cursor and +the cursor +When BOTTOM-UP is non-nil, display avy candidates from top to bottom + +\(fn &optional OFFSET BOTTOM-UP)" t nil) + +(autoload 'avy-goto-line-below "avy" "\ +Goto visible line below the cursor. +OFFSET changes the distance between the closest key to the cursor and +the cursor +When BOTTOM-UP is non-nil, display avy candidates from top to bottom + +\(fn &optional OFFSET BOTTOM-UP)" t nil) + +(autoload 'avy-goto-end-of-line "avy" "\ +Call `avy-goto-line' and move to the end of the line. + +\(fn &optional ARG)" t nil) + +(autoload 'avy-copy-line "avy" "\ +Copy a selected line above the current line. +ARG lines can be used. + +\(fn ARG)" t nil) + +(autoload 'avy-move-line "avy" "\ +Move a selected line above the current line. +ARG lines can be used. + +\(fn ARG)" t nil) + +(autoload 'avy-copy-region "avy" "\ +Select two lines and copy the text between them to point. + +The window scope is determined by `avy-all-windows' or +`avy-all-windows-alt' when ARG is non-nil. + +\(fn ARG)" t nil) + +(autoload 'avy-move-region "avy" "\ +Select two lines and move the text between them above the current line. + +\(fn)" t nil) + +(autoload 'avy-kill-region "avy" "\ +Select two lines and kill the region between them. + +The window scope is determined by `avy-all-windows' or +`avy-all-windows-alt' when ARG is non-nil. + +\(fn ARG)" t nil) + +(autoload 'avy-kill-ring-save-region "avy" "\ +Select two lines and save the region between them to the kill ring. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. + +\(fn ARG)" t nil) + +(autoload 'avy-kill-whole-line "avy" "\ +Select line and kill the whole selected line. + +With a numerical prefix ARG, kill ARG line(s) starting from the +selected line. If ARG is negative, kill backward. + +If ARG is zero, kill the selected line but exclude the trailing +newline. + +\\[universal-argument] 3 \\[avy-kil-whole-line] kill three lines +starting from the selected line. \\[universal-argument] -3 + +\\[avy-kill-whole-line] kill three lines backward including the +selected line. + +\(fn ARG)" t nil) + +(autoload 'avy-kill-ring-save-whole-line "avy" "\ +Select line and save the whole selected line as if killed, but don’t kill it. + +This command is similar to `avy-kill-whole-line', except that it +saves the line(s) as if killed, but does not kill it(them). + +With a numerical prefix ARG, kill ARG line(s) starting from the +selected line. If ARG is negative, kill backward. + +If ARG is zero, kill the selected line but exclude the trailing +newline. + +\(fn ARG)" t nil) + +(autoload 'avy-setup-default "avy" "\ +Setup the default shortcuts. + +\(fn)" nil nil) + +(autoload 'avy-goto-char-timer "avy" "\ +Read one or many consecutive chars and jump to the first one. +The window scope is determined by `avy-all-windows' (ARG negates it). + +\(fn &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "avy" '("avy-"))) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; avy-autoloads.el ends here diff --git a/elpa/avy-20181009.1648/avy-pkg.el b/elpa/avy-20181009.1648/avy-pkg.el new file mode 100644 index 00000000..c14b2f0a --- /dev/null +++ b/elpa/avy-20181009.1648/avy-pkg.el @@ -0,0 +1,2 @@ +;;; -*- no-byte-compile: t -*- +(define-package "avy" "20181009.1648" "Jump to arbitrary positions in visible text and select text quickly." '((emacs "24.1") (cl-lib "0.5")) :commit "df4c4ac488ee59bc44f8658d9fcca0c86fb32c5c" :keywords '("point" "location") :authors '(("Oleh Krehel" . "ohwoeowho@gmail.com")) :maintainer '("Oleh Krehel" . "ohwoeowho@gmail.com") :url "https://github.com/abo-abo/avy") diff --git a/elpa/avy-20181009.1648/avy.el b/elpa/avy-20181009.1648/avy.el new file mode 100644 index 00000000..be6a9b5a --- /dev/null +++ b/elpa/avy-20181009.1648/avy.el @@ -0,0 +1,2047 @@ +;;; avy.el --- Jump to arbitrary positions in visible text and select text quickly. -*- lexical-binding: t -*- + +;; Copyright (C) 2015 Free Software Foundation, Inc. + +;; Author: Oleh Krehel +;; URL: https://github.com/abo-abo/avy +;; Package-Version: 20181009.1648 +;; Version: 0.4.0 +;; Package-Requires: ((emacs "24.1") (cl-lib "0.5")) +;; Keywords: point, location + +;; This file is 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 . + +;;; Commentary: +;; +;; With Avy, you can move point to any position in Emacs – even in a +;; different window – using very few keystrokes. For this, you look at +;; the position where you want point to be, invoke Avy, and then enter +;; the sequence of characters displayed at that position. +;; +;; If the position you want to jump to can be determined after only +;; issuing a single keystroke, point is moved to the desired position +;; immediately after that keystroke. In case this isn't possible, the +;; sequence of keystrokes you need to enter is comprised of more than +;; one character. Avy uses a decision tree where each candidate position +;; is a leaf and each edge is described by a character which is distinct +;; per level of the tree. By entering those characters, you navigate the +;; tree, quickly arriving at the desired candidate position, such that +;; Avy can move point to it. +;; +;; Note that this only makes sense for positions you are able to see +;; when invoking Avy. These kinds of positions are supported: +;; +;; * character positions +;; * word or subword start positions +;; * line beginning positions +;; * link positions +;; * window positions +;; +;; If you're familiar with the popular `ace-jump-mode' package, this +;; package does all that and more, without the implementation +;; headache. + +;;; Code: +(require 'cl-lib) +(require 'ring) + +;;* Customization +(defgroup avy nil + "Jump to things tree-style." + :group 'convenience + :prefix "avy-") + +(defcustom avy-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l) + "Default keys for jumping. +Any key is either a character representing a self-inserting +key (letters, digits, punctuation, etc.) or a symbol denoting a +non-printing key like an arrow key (left, right, up, down). For +non-printing keys, a corresponding entry in +`avy-key-to-char-alist' must exist in order to visualize the key +in the avy overlays. + +If `avy-style' is set to words, make sure there are at least three +keys different than the following: a, e, i, o, u, y" + :type '(repeat :tag "Keys" (choice + (character :tag "char") + (symbol :tag "non-printing key")))) + +(defconst avy--key-type + '(choice :tag "Command" + (const avy-goto-char) + (const avy-goto-char-2) + (const avy-isearch) + (const avy-goto-line) + (const avy-goto-subword-0) + (const avy-goto-subword-1) + (const avy-goto-word-0) + (const avy-goto-word-1) + (const avy-copy-line) + (const avy-copy-region) + (const avy-move-line) + (const avy-move-region) + (const avy-kill-whole-line) + (const avy-kill-region) + (const avy-kill-ring-save-whole-line) + (const avy-kill-ring-save-region) + (function :tag "Other command"))) + +(defcustom avy-keys-alist nil + "Alist of avy-jump commands to `avy-keys' overriding the default `avy-keys'." + :type `(alist + :key-type ,avy--key-type + :value-type (repeat :tag "Keys" character))) + +(defcustom avy-orders-alist '((avy-goto-char . avy-order-closest)) + "Alist of candidate ordering functions. +Usually, candidates appear in their point position order." + :type `(alist + :key-type ,avy--key-type + :value-type function)) + +(defcustom avy-words + '("am" "by" "if" "is" "it" "my" "ox" "up" + "ace" "act" "add" "age" "ago" "aim" "air" "ale" "all" "and" "ant" "any" + "ape" "apt" "arc" "are" "arm" "art" "ash" "ate" "awe" "axe" "bad" "bag" + "ban" "bar" "bat" "bay" "bed" "bee" "beg" "bet" "bid" "big" "bit" "bob" + "bot" "bow" "box" "boy" "but" "cab" "can" "cap" "car" "cat" "cog" "cop" + "cow" "cry" "cup" "cut" "day" "dew" "did" "die" "dig" "dim" "dip" "dog" + "dot" "dry" "dub" "dug" "dye" "ear" "eat" "eel" "egg" "ego" "elf" "eve" + "eye" "fan" "far" "fat" "fax" "fee" "few" "fin" "fit" "fix" "flu" "fly" + "foe" "fog" "for" "fox" "fry" "fun" "fur" "gag" "gap" "gas" "gel" "gem" + "get" "gig" "gin" "gnu" "god" "got" "gum" "gun" "gut" "guy" "gym" "had" + "hag" "ham" "has" "hat" "her" "hid" "him" "hip" "his" "hit" "hop" "hot" + "how" "hub" "hue" "hug" "hut" "ice" "icy" "imp" "ink" "inn" "ion" "ire" + "ivy" "jab" "jam" "jar" "jaw" "jet" "job" "jog" "joy" "key" "kid" "kit" + "lag" "lap" "lay" "let" "lid" "lie" "lip" "lit" "lob" "log" "lot" "low" + "mad" "man" "map" "mat" "may" "men" "met" "mix" "mob" "mop" "mud" "mug" + "nag" "nap" "new" "nil" "nod" "nor" "not" "now" "nun" "oak" "odd" "off" + "oil" "old" "one" "orb" "ore" "ork" "our" "out" "owl" "own" "pad" "pan" + "par" "pat" "paw" "pay" "pea" "pen" "pet" "pig" "pin" "pit" "pod" "pot" + "pry" "pub" "pun" "put" "rag" "ram" "ran" "rat" "raw" "ray" "red" "rib" + "rim" "rip" "rob" "rod" "rot" "row" "rub" "rug" "rum" "run" "sad" "sat" + "saw" "say" "sea" "see" "sew" "she" "shy" "sin" "sip" "sit" "six" "ski" + "sky" "sly" "sob" "son" "soy" "spy" "sum" "sun" "tab" "tad" "tag" "tan" + "tap" "tar" "tax" "tea" "the" "tie" "tin" "tip" "toe" "ton" "too" "top" + "toy" "try" "tub" "two" "urn" "use" "van" "war" "was" "wax" "way" "web" + "wed" "wet" "who" "why" "wig" "win" "wit" "woe" "won" "wry" "you" "zap" + "zip" "zoo") + "Words to use in case `avy-style' is set to `words'. +Every word should contain at least one vowel i.e. one of the following +characters: a, e, i, o, u, y +They do not have to be sorted but no word should be a prefix of another one." + :type '(repeat string)) + +(defcustom avy-style 'at-full + "The default method of displaying the overlays. +Use `avy-styles-alist' to customize this per-command." + :type '(choice + (const :tag "Pre" pre) + (const :tag "At" at) + (const :tag "At Full" at-full) + (const :tag "Post" post) + (const :tag "De Bruijn" de-bruijn) + (const :tag "Words" words))) + +(defcustom avy-styles-alist nil + "Alist of avy-jump commands to the style for each command. +If the commands isn't on the list, `avy-style' is used." + :type '(alist + :key-type (choice :tag "Command" + (const avy-goto-char) + (const avy-goto-char-2) + (const avy-isearch) + (const avy-goto-line) + (const avy-goto-subword-0) + (const avy-goto-subword-1) + (const avy-goto-word-0) + (const avy-goto-word-1) + (const avy-copy-line) + (const avy-copy-region) + (const avy-move-line) + (const avy-move-region) + (const avy-kill-whole-line) + (const avy-kill-region) + (const avy-kill-ring-save-whole-line) + (const avy-kill-ring-save-region) + (function :tag "Other command")) + :value-type (choice + (const :tag "Pre" pre) + (const :tag "At" at) + (const :tag "At Full" at-full) + (const :tag "Post" post) + (const :tag "De Bruijn" de-bruijn) + (const :tag "Words" words)))) + +(defcustom avy-dispatch-alist + '((?x . avy-action-kill-move) + (?X . avy-action-kill-stay) + (?t . avy-action-teleport) + (?m . avy-action-mark) + (?n . avy-action-copy) + (?y . avy-action-yank) + (?i . avy-action-ispell) + (?z . avy-action-zap-to-char)) + "List of actions for `avy-handler-default'. + +Each item is (KEY . ACTION). When KEY not on `avy-keys' is +pressed during the dispatch, ACTION is set to replace the default +`avy-action-goto' once a candidate is finally selected." + :type + '(alist + :key-type (choice (character :tag "Char")) + :value-type (choice + (const :tag "Mark" avy-action-mark) + (const :tag "Copy" avy-action-copy) + (const :tag "Kill and move point" avy-action-kill-move) + (const :tag "Kill" avy-action-kill-stay)))) + +(defcustom avy-background nil + "When non-nil, a gray background will be added during the selection." + :type 'boolean) + +(defcustom avy-all-windows t + "Determine the list of windows to consider in search of candidates." + :type + '(choice + (const :tag "All Frames" all-frames) + (const :tag "This Frame" t) + (const :tag "This Window" nil))) + +(defcustom avy-case-fold-search t + "Non-nil if searches should ignore case." + :type 'boolean) + +(defcustom avy-word-punc-regexp "[!-/:-@[-`{-~]" + "Regexp of punctuation chars that count as word starts for `avy-goto-word-1. +When nil, punctuation chars will not be matched. + +\"[!-/:-@[-`{-~]\" will match all printable punctuation chars." + :type 'regexp) + +(defcustom avy-goto-word-0-regexp "\\b\\sw" + "Regexp that determines positions for `avy-goto-word-0'." + :type '(choice + (const :tag "Default" "\\b\\sw") + (const :tag "Symbol" "\\_<\\(\\sw\\|\\s_\\)") + (const :tag "Not whitespace" "[^ \r\n\t]+") + (regexp :tag "Regex"))) + +(defcustom avy-ignored-modes '(image-mode doc-view-mode pdf-view-mode) + "List of modes to ignore when searching for candidates. +Typically, these modes don't use the text representation." + :type 'list) + +(defcustom avy-single-candidate-jump t + "In case there is only one candidate jumps directly to it." + :type 'boolean) + +(defcustom avy-del-last-char-by '(8 127) + "List of event types, i.e. key presses, that delete the last +character read. The default represents `C-h' and `DEL'. See +`event-convert-list'." + :type 'list) + +(defvar avy-ring (make-ring 20) + "Hold the window and point history.") + +(defvar avy-translate-char-function #'identity + "Function to translate user input key into another key. +For example, to make SPC do the same as ?a, use +\(lambda (c) (if (= c 32) ?a c)).") + +(defface avy-lead-face-0 + '((t (:foreground "white" :background "#4f57f9"))) + "Face used for first non-terminating leading chars.") + +(defface avy-lead-face-1 + '((t (:foreground "white" :background "gray"))) + "Face used for matched leading chars.") + +(defface avy-lead-face-2 + '((t (:foreground "white" :background "#f86bf3"))) + "Face used for leading chars.") + +(defface avy-lead-face + '((t (:foreground "white" :background "#e52b50"))) + "Face used for the leading chars.") + +(defface avy-background-face + '((t (:foreground "gray40"))) + "Face for whole window background during selection.") + +(defface avy-goto-char-timer-face + '((t (:inherit highlight))) + "Face for matches during reading chars using `avy-goto-char-timer'.") + +(defconst avy-lead-faces '(avy-lead-face + avy-lead-face-0 + avy-lead-face-2 + avy-lead-face + avy-lead-face-0 + avy-lead-face-2) + "Face sequence for `avy--overlay-at-full'.") + +(defvar avy-key-to-char-alist '((left . ?◀) + (right . ?▶) + (up . ?▲) + (down . ?▼) + (prior . ?△) + (next . ?▽)) + "An alist from non-character keys to printable chars used in avy overlays. +This alist must contain all keys used in `avy-keys' which are not +self-inserting keys and thus aren't read as characters.") + +;;* Internals +;;** Tree +(defmacro avy-multipop (lst n) + "Remove LST's first N elements and return them." + `(if (<= (length ,lst) ,n) + (prog1 ,lst + (setq ,lst nil)) + (prog1 ,lst + (setcdr + (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst)))) + nil)))) + +(defun avy--de-bruijn (keys n) + "De Bruijn sequence for alphabet KEYS and subsequences of length N." + (let* ((k (length keys)) + (a (make-list (* n k) 0)) + sequence) + (cl-labels ((db (T p) + (if (> T n) + (if (eq (% n p) 0) + (setq sequence + (append sequence + (cl-subseq a 1 (1+ p))))) + (setf (nth T a) (nth (- T p) a)) + (db (1+ T) p) + (cl-loop for j from (1+ (nth (- T p) a)) to (1- k) do + (setf (nth T a) j) + (db (1+ T) T))))) + (db 1 1) + (mapcar (lambda (n) + (nth n keys)) + sequence)))) + +(defun avy--path-alist-1 (lst seq-len keys) + "Build a De Bruin sequence from LST. +SEQ-LEN is how many elements of KEYS it takes to identify a match." + (let ((db-seq (avy--de-bruijn keys seq-len)) + prev-pos prev-seq prev-win path-alist) + ;; The De Bruijn seq is cyclic, so append the seq-len - 1 first chars to + ;; the end. + (setq db-seq (nconc db-seq (cl-subseq db-seq 0 (1- seq-len)))) + (cl-labels ((subseq-and-pop () + (when (nth (1- seq-len) db-seq) + (prog1 (cl-subseq db-seq 0 seq-len) + (pop db-seq))))) + (while lst + (let* ((cur (car lst)) + (pos (cond + ;; ace-window has matches of the form (pos . wnd) + ((integerp (car cur)) (car cur)) + ;; avy-jump have form ((start . end) . wnd) + ((consp (car cur)) (caar cur)) + (t (error "Unexpected match representation: %s" cur)))) + (win (cdr cur)) + (path (if prev-pos + (let ((diff (if (eq win prev-win) + (- pos prev-pos) + 0))) + (when (and (> diff 0) (< diff seq-len)) + (while (and (nth (1- seq-len) db-seq) + (not + (eq 0 + (cl-search + (cl-subseq prev-seq diff) + (cl-subseq db-seq 0 seq-len))))) + (pop db-seq))) + (subseq-and-pop)) + (subseq-and-pop)))) + (if (not path) + (setq lst nil + path-alist nil) + (push (cons path (car lst)) path-alist) + (setq prev-pos pos + prev-seq path + prev-win win + lst (cdr lst)))))) + (nreverse path-alist))) + +(defun avy-order-closest (x) + (abs (- (caar x) (point)))) + +(defvar avy-command nil + "Store the current command symbol. +E.g. 'avy-goto-line or 'avy-goto-char.") + +(defun avy-tree (lst keys) + "Coerce LST into a balanced tree. +The degree of the tree is the length of KEYS. +KEYS are placed appropriately on internal nodes." + (let* ((len (length keys)) + (order-fn (cdr (assq avy-command avy-orders-alist))) + (lst (if order-fn + (cl-sort lst #'< :key order-fn) + lst))) + (cl-labels + ((rd (ls) + (let ((ln (length ls))) + (if (< ln len) + (cl-pairlis keys + (mapcar (lambda (x) (cons 'leaf x)) ls)) + (let ((ks (copy-sequence keys)) + res) + (dolist (s (avy-subdiv ln len)) + (push (cons (pop ks) + (if (eq s 1) + (cons 'leaf (pop ls)) + (rd (avy-multipop ls s)))) + res)) + (nreverse res)))))) + (rd lst)))) + +(defun avy-subdiv (n b) + "Distribute N in B terms in a balanced way." + (let* ((p (1- (floor (+ (log n b) 1e-6)))) + (x1 (expt b p)) + (x2 (* b x1)) + (delta (- n x2)) + (n2 (/ delta (- x2 x1))) + (n1 (- b n2 1))) + (append + (make-list n1 x1) + (list + (- n (* n1 x1) (* n2 x2))) + (make-list n2 x2)))) + +(defun avy-traverse (tree walker &optional recur-key) + "Traverse TREE generated by `avy-tree'. +WALKER is a function that takes KEYS and LEAF. + +RECUR-KEY is used in recursion. + +LEAF is a member of LST argument of `avy-tree'. + +KEYS is the path from the root of `avy-tree' to LEAF." + (dolist (br tree) + (let ((key (cons (car br) recur-key))) + (if (eq (cadr br) 'leaf) + (funcall walker key (cddr br)) + (avy-traverse (cdr br) walker key))))) + +(defvar avy-action nil + "Function to call at the end of select.") + +(defun avy-handler-default (char) + "The default handler for a bad CHAR." + (let (dispatch) + (cond ((setq dispatch (assoc char avy-dispatch-alist)) + (setq avy-action (cdr dispatch)) + (throw 'done 'restart)) + ((memq char '(27 ?\C-g)) + ;; exit silently + (throw 'done 'exit)) + ((mouse-event-p char) + (signal 'user-error (list "Mouse event not handled" char))) + (t + (signal 'user-error (list "No such candidate" + (if (characterp char) (string char) char))) + (throw 'done nil))))) + +(defvar avy-handler-function 'avy-handler-default + "A function to call for a bad `read-key' in `avy-read'.") + +(defvar avy-current-path "" + "Store the current incomplete path during `avy-read'.") + +(defun avy-mouse-event-window (char) + "If CHAR is a mouse event, return the window of the event if any or the selected window. +Return nil if not a mouse event." + (when (mouse-event-p char) + (cond ((windowp (posn-window (event-start char))) + (posn-window (event-start char))) + ((framep (posn-window (event-start char))) + (frame-selected-window (posn-window (event-start char)))) + (t (selected-window))))) + +(defun avy-read (tree display-fn cleanup-fn) + "Select a leaf from TREE using consecutive `read-char'. + +DISPLAY-FN should take CHAR and LEAF and signify that LEAFs +associated with CHAR will be selected if CHAR is pressed. This is +commonly done by adding a CHAR overlay at LEAF position. + +CLEANUP-FN should take no arguments and remove the effects of +multiple DISPLAY-FN invocations." + (catch 'done + (setq avy-current-path "") + (while tree + (let ((avy--leafs nil)) + (avy-traverse tree + (lambda (path leaf) + (push (cons path leaf) avy--leafs))) + (dolist (x avy--leafs) + (funcall display-fn (car x) (cdr x)))) + (let ((char (funcall avy-translate-char-function (read-key))) + window + branch) + (funcall cleanup-fn) + (if (setq window (avy-mouse-event-window char)) + (throw 'done (cons char window)) + ;; Ensure avy-current-path stores the full path prior to + ;; exit so other packages can utilize its value. + (setq avy-current-path + (concat avy-current-path (string (avy--key-to-char char)))) + (if (setq branch (assoc char tree)) + (if (eq (car (setq tree (cdr branch))) 'leaf) + (throw 'done (cdr tree))) + (funcall avy-handler-function char))))))) + +(defun avy-read-de-bruijn (lst keys) + "Select from LST dispatching on KEYS." + ;; In theory, the De Bruijn sequence B(k,n) has k^n subsequences of length n + ;; (the path length) usable as paths, thus that's the lower bound. Due to + ;; partially overlapping matches, not all subsequences may be usable, so it's + ;; possible that the path-len must be incremented, e.g., if we're matching + ;; for x and a buffer contains xaxbxcx only every second subsequence is + ;; usable for the four matches. + (catch 'done + (let* ((path-len (ceiling (log (length lst) (length keys)))) + (alist (avy--path-alist-1 lst path-len keys))) + (while (not alist) + (cl-incf path-len) + (setq alist (avy--path-alist-1 lst path-len keys))) + (let* ((len (length (caar alist))) + (i 0)) + (setq avy-current-path "") + (while (< i len) + (dolist (x (reverse alist)) + (avy--overlay-at-full (reverse (car x)) (cdr x))) + (let ((char (funcall avy-translate-char-function (read-key)))) + (avy--remove-leading-chars) + (setq alist + (delq nil + (mapcar (lambda (x) + (when (eq (caar x) char) + (cons (cdr (car x)) (cdr x)))) + alist))) + (setq avy-current-path + (concat avy-current-path (string (avy--key-to-char char)))) + (cl-incf i) + (unless alist + (funcall avy-handler-function char)))) + (cdar alist))))) + +(defun avy-read-words (lst words) + "Select from LST using WORDS." + (catch 'done + (let ((num-words (length words)) + (num-entries (length lst)) + alist) + ;; If there are not enough words to cover all the candidates, + ;; we use a De Bruijn sequence to generate the remaining ones. + (when (< num-words num-entries) + (let ((keys avy-keys) + (bad-keys '(?a ?e ?i ?o ?u ?y)) + (path-len 1) + (num-remaining (- num-entries num-words)) + tmp-alist) + ;; Delete all keys which could lead to duplicates. + ;; We want at least three keys left to work with. + (dolist (x bad-keys) + (when (memq x keys) + (setq keys (delq ?a keys)))) + (when (< (length keys) 3) + (signal 'user-error + '("Please add more keys to the variable `avy-keys'."))) + ;; Generate the sequence and add the keys to the existing words. + (while (not tmp-alist) + (cl-incf path-len) + (setq tmp-alist (avy--path-alist-1 lst path-len keys))) + (while (>= (cl-decf num-remaining) 0) + (push (mapconcat 'string (caar tmp-alist) nil) (cdr (last words))) + (setq tmp-alist (cdr tmp-alist))))) + (dolist (x lst) + (push (cons (string-to-list (pop words)) x) alist)) + (setq avy-current-path "") + (while (or (> (length alist) 1) + (caar alist)) + (dolist (x (reverse alist)) + (avy--overlay-at-full (reverse (car x)) (cdr x))) + (let ((char (funcall avy-translate-char-function (read-key)))) + (avy--remove-leading-chars) + (setq alist + (delq nil + (mapcar (lambda (x) + (when (eq (caar x) char) + (cons (cdr (car x)) (cdr x)))) + alist))) + (setq avy-current-path + (concat avy-current-path (string (avy--key-to-char char)))) + (unless alist + (funcall avy-handler-function char)))) + (cdar alist)))) + +;;** Rest +(defun avy-window-list () + "Return a list of windows depending on `avy-all-windows'." + (cond ((eq avy-all-windows 'all-frames) + (cl-mapcan #'window-list (frame-list))) + + ((eq avy-all-windows t) + (window-list)) + + ((null avy-all-windows) + (list (selected-window))) + + (t + (error "Unrecognized option: %S" avy-all-windows)))) + +(defcustom avy-all-windows-alt nil + "The alternative `avy-all-windows' for use with \\[universal-argument]." + :type '(choice + (const :tag "Current window" nil) + (const :tag "All windows on the current frame" t) + (const :tag "All windows on all frames" all-frames))) + +(defmacro avy-dowindows (flip &rest body) + "Depending on FLIP and `avy-all-windows' run BODY in each or selected window." + (declare (indent 1) + (debug (form body))) + `(let ((avy-all-windows (if ,flip + avy-all-windows-alt + avy-all-windows))) + (dolist (wnd (avy-window-list)) + (with-selected-window wnd + (unless (memq major-mode avy-ignored-modes) + ,@body))))) + +(defun avy-resume () + "Stub to hold last avy command. +Commands using `avy-with' macro can be resumed." + (interactive)) + +(defmacro avy-with (command &rest body) + "Set `avy-keys' according to COMMAND and execute BODY. +Set `avy-style' according to COMMMAND as well." + (declare (indent 1) + (debug (form body))) + `(let ((avy-keys (or (cdr (assq ',command avy-keys-alist)) + avy-keys)) + (avy-style (or (cdr (assq ',command avy-styles-alist)) + avy-style)) + (avy-command ',command)) + (setq avy-action nil) + (setf (symbol-function 'avy-resume) + (lambda () + (interactive) + ,@body)) + ,@body)) + +(defun avy-action-goto (pt) + "Goto PT." + (let ((frame (window-frame (selected-window)))) + (unless (equal frame (selected-frame)) + (select-frame-set-input-focus frame) + (raise-frame frame)) + (goto-char pt))) + +(defun avy-forward-item () + (if (eq avy-command 'avy-goto-line) + (end-of-line) + (forward-sexp)) + (point)) + +(defun avy-action-mark (pt) + "Mark sexp at PT." + (goto-char pt) + (set-mark (point)) + (avy-forward-item)) + +(defun avy-action-copy (pt) + "Copy sexp starting on PT." + (save-excursion + (let (str) + (goto-char pt) + (avy-forward-item) + (setq str (buffer-substring pt (point))) + (kill-new str) + (message "Copied: %s" str))) + (let ((dat (ring-ref avy-ring 0))) + (select-frame-set-input-focus + (window-frame (cdr dat))) + (select-window (cdr dat)) + (goto-char (car dat)))) + +(defun avy-action-yank (pt) + "Yank sexp starting at PT at the current point." + (avy-action-copy pt) + (yank) + t) + +(defun avy-action-kill-move (pt) + "Kill sexp at PT and move there." + (goto-char pt) + (avy-forward-item) + (kill-region pt (point)) + (message "Killed: %s" (current-kill 0)) + (point)) + +(defun avy-action-kill-stay (pt) + "Kill sexp at PT." + (save-excursion + (goto-char pt) + (avy-forward-item) + (kill-region pt (point)) + (just-one-space)) + (message "Killed: %s" (current-kill 0)) + (select-window + (cdr + (ring-ref avy-ring 0))) + t) + +(defun avy-action-zap-to-char (pt) + "Kill from point up to PT." + (if (> pt (point)) + (kill-region (point) pt) + (kill-region pt (point)))) + +(defun avy-action-teleport (pt) + "Kill sexp starting on PT and yank into the current location." + (avy-action-kill-stay pt) + (select-window + (cdr + (ring-ref avy-ring 0))) + (save-excursion + (yank)) + t) + +(declare-function flyspell-correct-word-before-point "flyspell") + +(defun avy-action-ispell (pt) + "Auto correct word at PT." + (save-excursion + (goto-char pt) + (cond + ((eq avy-command 'avy-goto-line) + (ispell-region + (line-beginning-position) + (line-end-position))) + ((bound-and-true-p flyspell-mode) + (flyspell-correct-word-before-point)) + ((looking-at-p "\\b") + (ispell-word)) + (t + (progn + (backward-word) + (when (looking-at-p "\\b") + (ispell-word))))))) + +(defun avy--process-1 (candidates overlay-fn) + (let ((len (length candidates))) + (cond ((= len 0) + nil) + ((and (= len 1) avy-single-candidate-jump) + (car candidates)) + (t + (unwind-protect + (progn + (avy--make-backgrounds + (avy-window-list)) + (cond ((eq avy-style 'de-bruijn) + (avy-read-de-bruijn + candidates avy-keys)) + ((eq avy-style 'words) + (avy-read-words + candidates avy-words)) + (t + (avy-read (avy-tree candidates avy-keys) + overlay-fn + #'avy--remove-leading-chars)))) + (avy--done)))))) + +(defun avy--process (candidates overlay-fn) + "Select one of CANDIDATES using `avy-read'. +Use OVERLAY-FN to visualize the decision overlay." + (unless (and (consp (car candidates)) + (windowp (cdar candidates))) + (setq candidates + (mapcar (lambda (x) (cons x (selected-window))) + candidates))) + (let ((original-cands (copy-sequence candidates)) + (res (avy--process-1 candidates overlay-fn))) + (cond + ((null res) + (message "zero candidates") + t) + ((eq res 'restart) + (avy--process original-cands overlay-fn)) + ;; ignore exit from `avy-handler-function' + ((eq res 'exit)) + (t + (avy-push-mark) + (when (and (consp res) + (windowp (cdr res))) + (let* ((window (cdr res)) + (frame (window-frame window))) + (unless (equal frame (selected-frame)) + (select-frame-set-input-focus frame)) + (select-window window)) + (setq res (car res))) + + (funcall (or avy-action 'avy-action-goto) + (if (consp res) + (car res) + res)))))) + +(defvar avy--overlays-back nil + "Hold overlays for when `avy-background' is t.") + +(defun avy--make-backgrounds (wnd-list) + "Create a dim background overlay for each window on WND-LIST." + (when avy-background + (setq avy--overlays-back + (mapcar (lambda (w) + (let ((ol (make-overlay + (window-start w) + (window-end w) + (window-buffer w)))) + (overlay-put ol 'face 'avy-background-face) + (overlay-put ol 'window w) + ol)) + wnd-list)))) + +(defun avy--done () + "Clean up overlays." + (mapc #'delete-overlay avy--overlays-back) + (setq avy--overlays-back nil) + (avy--remove-leading-chars)) + +(defun avy--next-visible-point () + "Return the next closest point without 'invisible property." + (let ((s (point))) + (while (and (not (= (point-max) (setq s (next-char-property-change s)))) + (get-char-property s 'invisible))) + s)) + +(defun avy--next-invisible-point () + "Return the next closest point with 'invisible property." + (let ((s (point))) + (while (and (not (= (point-max) (setq s (next-char-property-change s)))) + (not (get-char-property s 'invisible)))) + s)) + +(defun avy--find-visible-regions (rbeg rend) + "Return a list of all visible regions between RBEG and REND." + (setq rbeg (max rbeg (point-min))) + (setq rend (min rend (point-max))) + (when (< rbeg rend) + (let (visibles beg) + (save-excursion + (save-restriction + (narrow-to-region rbeg rend) + (setq beg (goto-char (point-min))) + (while (not (= (point) (point-max))) + (goto-char (avy--next-invisible-point)) + (push (cons beg (point)) visibles) + (setq beg (goto-char (avy--next-visible-point)))) + (nreverse visibles)))))) + +(defun avy--regex-candidates (regex &optional beg end pred group) + "Return all elements that match REGEX. +Each element of the list is ((BEG . END) . WND) +When PRED is non-nil, it's a filter for matching point positions. +When GROUP is non-nil, (BEG . END) should delimit that regex group." + (setq group (or group 0)) + (let ((case-fold-search (or avy-case-fold-search + (string= regex (downcase regex)))) + candidates) + (avy-dowindows current-prefix-arg + (dolist (pair (avy--find-visible-regions + (or beg (window-start)) + (or end (window-end (selected-window) t)))) + (save-excursion + (goto-char (car pair)) + (while (re-search-forward regex (cdr pair) t) + (unless (get-char-property (1- (point)) 'invisible) + (when (or (null pred) + (funcall pred)) + (push (cons (cons (match-beginning group) + (match-end group)) + wnd) candidates))))))) + (nreverse candidates))) + +(defvar avy--overlay-offset 0 + "The offset to apply in `avy--overlay'.") + +(defvar avy--overlays-lead nil + "Hold overlays for leading chars.") + +(defun avy--remove-leading-chars () + "Remove leading char overlays." + (mapc #'delete-overlay avy--overlays-lead) + (setq avy--overlays-lead nil)) + +(defun avy--old-str (pt wnd) + "Return a one-char string at PT in WND." + (let ((old-str (with-selected-window wnd + (buffer-substring pt (1+ pt))))) + (if avy-background + (propertize old-str 'face 'avy-background-face) + old-str))) + +(defun avy--overlay (str beg end wnd &optional compose-fn) + "Create an overlay with STR from BEG to END in WND. +COMPOSE-FN is a lambda that concatenates the old string at BEG with STR." + (let ((eob (with-selected-window wnd (point-max)))) + (when (<= beg eob) + (let* ((beg (+ beg avy--overlay-offset)) + (ol (make-overlay beg (or end (1+ beg)) (window-buffer wnd))) + (old-str (if (eq beg eob) "" (avy--old-str beg wnd))) + (os-line-prefix (get-text-property 0 'line-prefix old-str)) + (os-wrap-prefix (get-text-property 0 'wrap-prefix old-str)) + other-ol) + (when os-line-prefix + (add-text-properties 0 1 `(line-prefix ,os-line-prefix) str)) + (when os-wrap-prefix + (add-text-properties 0 1 `(wrap-prefix ,os-wrap-prefix) str)) + (when (setq other-ol (cl-find-if + (lambda (o) (overlay-get o 'goto-address)) + (overlays-at beg))) + (add-text-properties + 0 (length old-str) + `(face ,(overlay-get other-ol 'face)) old-str)) + (overlay-put ol 'window wnd) + (overlay-put ol 'category 'avy) + (overlay-put ol (if (eq beg eob) + 'after-string + 'display) + (funcall + (or compose-fn #'concat) + str old-str)) + (push ol avy--overlays-lead))))) + +(defcustom avy-highlight-first nil + "When non-nil highlight the first decision char with `avy-lead-face-0'. +Do this even when the char is terminating." + :type 'boolean) + +(defun avy--key-to-char (c) + "If C is no character, translate it using `avy-key-to-char-alist'." + (cond ((characterp c) c) + ((cdr (assoc c avy-key-to-char-alist))) + ((mouse-event-p c) c) + (t + (error "Unknown key %s" c)))) + +(defun avy-candidate-beg (leaf) + "Return the start position for LEAF." + (cond ((numberp leaf) + leaf) + ((consp (car leaf)) + (caar leaf)) + (t + (car leaf)))) + +(defun avy-candidate-end (leaf) + "Return the end position for LEAF." + (cond ((numberp leaf) + leaf) + ((consp (car leaf)) + (cdar leaf)) + (t + (car leaf)))) + +(defun avy-candidate-wnd (leaf) + "Return the window for LEAF." + (if (consp leaf) + (cdr leaf) + (selected-window))) + +(defun avy--overlay-pre (path leaf) + "Create an overlay with PATH at LEAF. +PATH is a list of keys from tree root to LEAF. +LEAF is normally ((BEG . END) . WND)." + (let* ((path (mapcar #'avy--key-to-char path)) + (str (propertize (apply #'string (reverse path)) + 'face 'avy-lead-face))) + (when (or avy-highlight-first (> (length str) 1)) + (set-text-properties 0 1 '(face avy-lead-face-0) str)) + (setq str (concat + (propertize avy-current-path + 'face 'avy-lead-face-1) + str)) + (avy--overlay + str + (avy-candidate-beg leaf) nil + (avy-candidate-wnd leaf)))) + +(defun avy--overlay-at (path leaf) + "Create an overlay with PATH at LEAF. +PATH is a list of keys from tree root to LEAF. +LEAF is normally ((BEG . END) . WND)." + (let* ((path (mapcar #'avy--key-to-char path)) + (str (propertize + (string (car (last path))) + 'face 'avy-lead-face))) + (avy--overlay + str + (avy-candidate-beg leaf) nil + (avy-candidate-wnd leaf) + (lambda (str old-str) + (cond ((string= old-str "\n") + (concat str "\n")) + ;; add padding for wide-width character + ((eq (string-width old-str) 2) + (concat str " ")) + (t + str)))))) + +(defun avy--overlay-at-full (path leaf) + "Create an overlay with PATH at LEAF. +PATH is a list of keys from tree root to LEAF. +LEAF is normally ((BEG . END) . WND)." + (let* ((path (mapcar #'avy--key-to-char path)) + (str (propertize + (apply #'string (reverse path)) + 'face 'avy-lead-face)) + (len (length path)) + (beg (avy-candidate-beg leaf)) + (wnd (cdr leaf)) + end) + (dotimes (i len) + (set-text-properties (- len i 1) (- len i) + `(face ,(nth i avy-lead-faces)) + str)) + (when (eq avy-style 'de-bruijn) + (setq str (concat + (propertize avy-current-path + 'face 'avy-lead-face-1) + str)) + (setq len (length str))) + (with-selected-window wnd + (save-excursion + (goto-char beg) + (let* ((lep (if (bound-and-true-p visual-line-mode) + (save-excursion + (end-of-visual-line) + (point)) + (line-end-position))) + ;; `end-of-visual-line' is bugged sometimes + (lep (if (< lep beg) + (line-end-position) + lep)) + (len-and-str (avy--update-offset-and-str len str lep))) + (setq len (car len-and-str)) + (setq str (cdr len-and-str)) + (setq end (if (= beg lep) + (1+ beg) + (min (+ beg + (if (eq (char-after) ?\t) + 1 + len)) + lep))) + (when (and (bound-and-true-p visual-line-mode) + (> len (- end beg)) + (not (eq lep beg))) + (setq len (- end beg)) + (let ((old-str (apply #'string (reverse path)))) + (setq str + (substring + (propertize + old-str + 'face + (if (= (length old-str) 1) + 'avy-lead-face + 'avy-lead-face-0)) + 0 len))))))) + (avy--overlay + str beg end wnd + (lambda (str old-str) + (cond ((string= old-str "\n") + (concat str "\n")) + ((string= old-str "\t") + (concat str (make-string (max (- tab-width len) 0) ?\ ))) + (t + ;; add padding for wide-width character + (if (eq (string-width old-str) 2) + (concat str " ") + str))))))) + +(defun avy--overlay-post (path leaf) + "Create an overlay with PATH at LEAF. +PATH is a list of keys from tree root to LEAF. +LEAF is normally ((BEG . END) . WND)." + (let* ((path (mapcar #'avy--key-to-char path)) + (str (propertize (apply #'string (reverse path)) + 'face 'avy-lead-face))) + (when (or avy-highlight-first (> (length str) 1)) + (set-text-properties 0 1 '(face avy-lead-face-0) str)) + (setq str (concat + (propertize avy-current-path + 'face 'avy-lead-face-1) + str)) + (avy--overlay + str + (avy-candidate-end leaf) nil + (avy-candidate-wnd leaf)))) + +(defun avy--update-offset-and-str (offset str lep) + "Recalculate the length of the new overlay at point. + +OFFSET is the previous overlay length. +STR is the overlay string that we wish to add. +LEP is the line end position. + +We want to add an overlay between point and END=point+OFFSET. +When other overlays already exist between point and END, set +OFFSET to be the difference between the start of the first +overlay and point. This is equivalent to truncating our new +overlay, so that it doesn't intersect with overlays that already +exist." + (let* ((wnd (selected-window)) + (beg (point)) + (oov (delq nil + (mapcar + (lambda (o) + (and (eq (overlay-get o 'category) 'avy) + (eq (overlay-get o 'window) wnd) + (overlay-start o))) + (overlays-in beg (min (+ beg offset) lep)))))) + (when oov + (setq offset (- (apply #'min oov) beg)) + (setq str (substring str 0 offset))) + (let ((other-ov (cl-find-if + (lambda (o) + (and (eq (overlay-get o 'category) 'avy) + (eq (overlay-start o) beg) + (not (eq (overlay-get o 'window) wnd)))) + (overlays-in (point) (min (+ (point) offset) lep))))) + (when (and other-ov + (> (overlay-end other-ov) + (+ beg offset))) + (setq str (concat str (buffer-substring + (+ beg offset) + (overlay-end other-ov)))) + (setq offset (- (overlay-end other-ov) + beg)))) + (cons offset str))) + +(defun avy--style-fn (style) + "Transform STYLE symbol to a style function." + (cl-case style + (pre #'avy--overlay-pre) + (at #'avy--overlay-at) + (at-full 'avy--overlay-at-full) + (post #'avy--overlay-post) + (de-bruijn #'avy--overlay-at-full) + (words #'avy--overlay-at-full) + (t (error "Unexpected style %S" style)))) + +(defun avy--generic-jump (regex window-flip style &optional beg end) + "Jump to REGEX. +The window scope is determined by `avy-all-windows'. +When WINDOW-FLIP is non-nil, do the opposite of `avy-all-windows'. +STYLE determines the leading char overlay style. +BEG and END narrow the scope where candidates are searched." + (let ((avy-all-windows + (if window-flip + (not avy-all-windows) + avy-all-windows))) + (avy--process + (avy--regex-candidates regex beg end) + (avy--style-fn style)))) + +;;* Commands +;;;###autoload +(defun avy-goto-char (char &optional arg) + "Jump to the currently visible CHAR. +The window scope is determined by `avy-all-windows' (ARG negates it)." + (interactive (list (read-char "char: " t) + current-prefix-arg)) + (avy-with avy-goto-char + (avy--generic-jump + (if (= 13 char) + "\n" + (regexp-quote (string char))) + arg + avy-style))) + +;;;###autoload +(defun avy-goto-char-in-line (char) + "Jump to the currently visible CHAR in the current line." + (interactive (list (read-char "char: " t))) + (avy-with avy-goto-char + (avy--generic-jump + (regexp-quote (string char)) + avy-all-windows + avy-style + (line-beginning-position) + (line-end-position)))) + +;;;###autoload +(defun avy-goto-char-2 (char1 char2 &optional arg beg end) + "Jump to the currently visible CHAR1 followed by CHAR2. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. +BEG and END narrow the scope where candidates are searched." + (interactive (list (read-char "char 1: " t) + (read-char "char 2: " t) + current-prefix-arg + nil nil)) + (when (eq char1 ? ) + (setq char1 ?\n)) + (when (eq char2 ? ) + (setq char2 ?\n)) + (avy-with avy-goto-char-2 + (avy--generic-jump + (regexp-quote (string char1 char2)) + arg + avy-style + beg end))) + +;;;###autoload +(defun avy-goto-char-2-above (char1 char2 &optional arg) + "Jump to the currently visible CHAR1 followed by CHAR2. +This is a scoped version of `avy-goto-char-2', where the scope is +the visible part of the current buffer up to point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive (list (read-char "char 1: " t) + (read-char "char 2: " t) + current-prefix-arg)) + (avy-with avy-goto-char-2-above + (avy-goto-char-2 + char1 char2 arg + (window-start) (point)))) + +;;;###autoload +(defun avy-goto-char-2-below (char1 char2 &optional arg) + "Jump to the currently visible CHAR1 followed by CHAR2. +This is a scoped version of `avy-goto-char-2', where the scope is +the visible part of the current buffer following point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive (list (read-char "char 1: " t) + (read-char "char 2: " t) + current-prefix-arg)) + (avy-with avy-goto-char-2-below + (avy-goto-char-2 + char1 char2 arg + (point) (window-end (selected-window) t)))) + +;;;###autoload +(defun avy-isearch () + "Jump to one of the current isearch candidates." + (interactive) + (avy-with avy-isearch + (let ((avy-background nil)) + (avy--process + (avy--regex-candidates (if isearch-regexp + isearch-string + (regexp-quote isearch-string))) + (avy--style-fn avy-style)) + (isearch-done)))) + +;;;###autoload +(defun avy-goto-word-0 (arg &optional beg end) + "Jump to a word start. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. +BEG and END narrow the scope where candidates are searched." + (interactive "P") + (avy-with avy-goto-word-0 + (avy--generic-jump avy-goto-word-0-regexp arg avy-style beg end))) + +(defun avy-goto-word-0-above (arg) + "Jump to a word start between window start and point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive "P") + (avy-with avy-goto-word-0 + (avy-goto-word-0 arg (window-start) (point)))) + +(defun avy-goto-word-0-below (arg) + "Jump to a word start between point and window end. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive "P") + (avy-with avy-goto-word-0 + (avy-goto-word-0 arg (point) (window-end (selected-window) t)))) + +;;;###autoload +(defun avy-goto-word-1 (char &optional arg beg end symbol) + "Jump to the currently visible CHAR at a word start. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. +BEG and END narrow the scope where candidates are searched. +When SYMBOL is non-nil, jump to symbol start instead of word start." + (interactive (list (read-char "char: " t) + current-prefix-arg)) + (avy-with avy-goto-word-1 + (let* ((str (string char)) + (regex (cond ((string= str ".") + "\\.") + ((and avy-word-punc-regexp + (string-match avy-word-punc-regexp str)) + (regexp-quote str)) + ((<= char 26) + str) + (t + (concat + (if symbol "\\_<" "\\b") + str))))) + (avy--generic-jump regex arg avy-style beg end)))) + +;;;###autoload +(defun avy-goto-word-1-above (char &optional arg) + "Jump to the currently visible CHAR at a word start. +This is a scoped version of `avy-goto-word-1', where the scope is +the visible part of the current buffer up to point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive (list (read-char "char: " t) + current-prefix-arg)) + (avy-with avy-goto-word-1 + (avy-goto-word-1 char arg (window-start) (point)))) + +;;;###autoload +(defun avy-goto-word-1-below (char &optional arg) + "Jump to the currently visible CHAR at a word start. +This is a scoped version of `avy-goto-word-1', where the scope is +the visible part of the current buffer following point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive (list (read-char "char: " t) + current-prefix-arg)) + (avy-with avy-goto-word-1 + (avy-goto-word-1 char arg (point) (window-end (selected-window) t)))) + +;;;###autoload +(defun avy-goto-symbol-1 (char &optional arg) + "Jump to the currently visible CHAR at a symbol start. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive (list (read-char "char: " t) + current-prefix-arg)) + (avy-with avy-goto-symbol-1 + (avy-goto-word-1 char arg nil nil t))) + +;;;###autoload +(defun avy-goto-symbol-1-above (char &optional arg) + "Jump to the currently visible CHAR at a symbol start. +This is a scoped version of `avy-goto-symbol-1', where the scope is +the visible part of the current buffer up to point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive (list (read-char "char: " t) + current-prefix-arg)) + (avy-with avy-goto-symbol-1-above + (avy-goto-word-1 char arg (window-start) (point) t))) + +;;;###autoload +(defun avy-goto-symbol-1-below (char &optional arg) + "Jump to the currently visible CHAR at a symbol start. +This is a scoped version of `avy-goto-symbol-1', where the scope is +the visible part of the current buffer following point. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive (list (read-char "char: " t) + current-prefix-arg)) + (avy-with avy-goto-symbol-1-below + (avy-goto-word-1 char arg (point) (window-end (selected-window) t) t))) + +(declare-function subword-backward "subword") +(defvar subword-backward-regexp) + +(defcustom avy-subword-extra-word-chars '(?{ ?= ?} ?* ?: ?> ?<) + "A list of characters that should temporarily match \"\\w\". +This variable is used by `avy-goto-subword-0' and `avy-goto-subword-1'." + :type '(repeat character)) + +;;;###autoload +(defun avy-goto-subword-0 (&optional arg predicate beg end) + "Jump to a word or subword start. +The window scope is determined by `avy-all-windows' (ARG negates it). + +When PREDICATE is non-nil it's a function of zero parameters that +should return true. + +BEG and END narrow the scope where candidates are searched." + (interactive "P") + (require 'subword) + (avy-with avy-goto-subword-0 + (let ((case-fold-search nil) + (subword-backward-regexp + "\\(\\(\\W\\|[[:lower:][:digit:]]\\)\\([!-/:@`~[:upper:]]+\\W*\\)\\|\\W\\w+\\)") + candidates) + (avy-dowindows arg + (let ((syn-tbl (copy-syntax-table))) + (dolist (char avy-subword-extra-word-chars) + (modify-syntax-entry char "w" syn-tbl)) + (with-syntax-table syn-tbl + (let ((ws (or beg (window-start))) + window-cands) + (save-excursion + (goto-char (or end (window-end (selected-window) t))) + (subword-backward) + (while (> (point) ws) + (when (or (null predicate) + (and predicate (funcall predicate))) + (unless (get-char-property (point) 'invisible) + (push (cons (point) (selected-window)) window-cands))) + (subword-backward)) + (and (= (point) ws) + (or (null predicate) + (and predicate (funcall predicate))) + (not (get-char-property (point) 'invisible)) + (push (cons (point) (selected-window)) window-cands))) + (setq candidates (nconc candidates window-cands)))))) + (avy--process candidates (avy--style-fn avy-style))))) + +;;;###autoload +(defun avy-goto-subword-1 (char &optional arg) + "Jump to the currently visible CHAR at a subword start. +The window scope is determined by `avy-all-windows' (ARG negates it). +The case of CHAR is ignored." + (interactive (list (read-char "char: " t) + current-prefix-arg)) + (avy-with avy-goto-subword-1 + (let ((char (downcase char))) + (avy-goto-subword-0 + arg (lambda () + (and (char-after) + (eq (downcase (char-after)) char))))))) + +;;;###autoload +(defun avy-goto-word-or-subword-1 () + "Forward to `avy-goto-subword-1' or `avy-goto-word-1'. +Which one depends on variable `subword-mode'." + (interactive) + (if (bound-and-true-p subword-mode) + (call-interactively #'avy-goto-subword-1) + (call-interactively #'avy-goto-word-1))) + +(defvar visual-line-mode) + +(defcustom avy-indent-line-overlay nil + "When non-nil, `avy-goto-line' will display the line overlay next to the first non-whitespace character of each line." + :type 'boolean) + +(defun avy--line-cands (&optional arg beg end bottom-up) + "Get candidates for selecting a line. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. +BEG and END narrow the scope where candidates are searched. +When BOTTOM-UP is non-nil, display avy candidates from top to bottom" + (let (candidates) + (avy-dowindows arg + (let ((ws (or beg (window-start)))) + (save-excursion + (save-restriction + (narrow-to-region ws (or end (window-end (selected-window) t))) + (goto-char (point-min)) + (while (< (point) (point-max)) + (unless (get-char-property + (max (1- (point)) ws) 'invisible) + (push (cons + (if (eq avy-style 'post) + (line-end-position) + (save-excursion + (when avy-indent-line-overlay + (skip-chars-forward " \t")) + (point))) + (selected-window)) candidates)) + (if visual-line-mode + (progn + (setq temporary-goal-column 0) + (line-move-visual 1 t)) + (forward-line 1))))))) + (if bottom-up + candidates + (nreverse candidates)))) + +(defun avy--linum-strings () + "Get strings for `avy-linum-mode'." + (let* ((lines (mapcar #'car (avy--line-cands))) + (line-tree (avy-tree lines avy-keys)) + (line-list nil)) + (avy-traverse + line-tree + (lambda (path _leaf) + (let ((str (propertize (apply #'string (reverse path)) + 'face 'avy-lead-face))) + (when (> (length str) 1) + (set-text-properties 0 1 '(face avy-lead-face-0) str)) + (push str line-list)))) + (nreverse line-list))) + +(defvar linum-available) +(defvar linum-overlays) +(defvar linum-format) +(declare-function linum--face-width "linum") + +(define-minor-mode avy-linum-mode + "Minor mode that uses avy hints for `linum-mode'." + :group 'avy + (if avy-linum-mode + (progn + (require 'linum) + (advice-add 'linum-update-window :around 'avy--linum-update-window) + (linum-mode 1)) + (advice-remove 'linum-update-window 'avy--linum-update-window) + (linum-mode -1))) + +(defun avy--linum-update-window (_ win) + "Update line numbers for the portion visible in window WIN." + (goto-char (window-start win)) + (let ((line (line-number-at-pos)) + (limit (window-end win t)) + (fmt (cond ((stringp linum-format) linum-format) + ((eq linum-format 'dynamic) + (let ((w (length (number-to-string + (count-lines (point-min) (point-max)))))) + (concat "%" (number-to-string w) "d"))))) + (width 0) + (avy-strs (when avy-linum-mode + (avy--linum-strings)))) + (run-hooks 'linum-before-numbering-hook) + ;; Create an overlay (or reuse an existing one) for each + ;; line visible in this window, if necessary. + (while (and (not (eobp)) (< (point) limit)) + (let* ((str + (cond (avy-linum-mode + (pop avy-strs)) + (fmt + (propertize (format fmt line) 'face 'linum)) + (t + (funcall linum-format line)))) + (visited (catch 'visited + (dolist (o (overlays-in (point) (point))) + (when (equal-including-properties + (overlay-get o 'linum-str) str) + (unless (memq o linum-overlays) + (push o linum-overlays)) + (setq linum-available (delq o linum-available)) + (throw 'visited t)))))) + (setq width (max width (length str))) + (unless visited + (let ((ov (if (null linum-available) + (make-overlay (point) (point)) + (move-overlay (pop linum-available) (point) (point))))) + (push ov linum-overlays) + (overlay-put ov 'before-string + (propertize " " 'display `((margin left-margin) ,str))) + (overlay-put ov 'linum-str str)))) + ;; Text may contain those nasty intangible properties, but that + ;; shouldn't prevent us from counting those lines. + (let ((inhibit-point-motion-hooks t)) + (forward-line)) + (setq line (1+ line))) + (when (display-graphic-p) + (setq width (ceiling + (/ (* width 1.0 (linum--face-width 'linum)) + (frame-char-width))))) + (set-window-margins win width (cdr (window-margins win))))) + +(defun avy--line (&optional arg beg end bottom-up) + "Select a line. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'. +BEG and END narrow the scope where candidates are searched. +When BOTTOM-UP is non-nil, display avy candidates from top to bottom" + (let ((avy-action #'identity)) + (avy--process + (avy--line-cands arg beg end bottom-up) + (if avy-linum-mode + (progn (message "Goto line:") + 'ignore) + (avy--style-fn avy-style))))) + +;;;###autoload +(defun avy-goto-line (&optional arg) + "Jump to a line start in current buffer. + +When ARG is 1, jump to lines currently visible, with the option +to cancel to `goto-line' by entering a number. + +When ARG is 4, negate the window scope determined by +`avy-all-windows'. + +Otherwise, forward to `goto-line' with ARG." + (interactive "p") + (setq arg (or arg 1)) + (if (not (memq arg '(1 4))) + (progn + (goto-char (point-min)) + (forward-line (1- arg))) + (avy-with avy-goto-line + (let* ((avy-handler-old avy-handler-function) + (avy-handler-function + (lambda (char) + (if (or (< char ?0) + (> char ?9)) + (funcall avy-handler-old char) + (let ((line (read-from-minibuffer + "Goto line: " (string char)))) + (when line + (avy-push-mark) + (save-restriction + (widen) + (goto-char (point-min)) + (forward-line (1- (string-to-number line)))) + (throw 'done 'exit)))))) + (r (avy--line (eq arg 4)))) + (unless (eq r t) + (avy-action-goto r)))))) + +;;;###autoload +(defun avy-goto-line-above (&optional offset bottom-up) + "Goto visible line above the cursor. +OFFSET changes the distance between the closest key to the cursor and +the cursor +When BOTTOM-UP is non-nil, display avy candidates from top to bottom" + (interactive) + (if offset + (setq offset (+ 2 (- offset)))) + (let* ((avy-all-windows nil) + (r (avy--line nil (window-start) + (line-beginning-position (or offset 1)) + bottom-up))) + (unless (eq r t) + (avy-action-goto r)))) + +;;;###autoload +(defun avy-goto-line-below (&optional offset bottom-up) + "Goto visible line below the cursor. +OFFSET changes the distance between the closest key to the cursor and +the cursor +When BOTTOM-UP is non-nil, display avy candidates from top to bottom" + (interactive) + (if offset + (setq offset (+ offset 1))) + (let* ((avy-all-windows nil) + (r (avy--line + nil (line-beginning-position (or offset 2)) + (window-end (selected-window) t) + bottom-up))) + (unless (eq r t) + (avy-action-goto r)))) + +(defcustom avy-line-insert-style 'above + "How to insert the newly copied/cut line." + :type '(choice + (const :tag "Above" above) + (const :tag "Below" below))) + +;;;###autoload +(defun avy-goto-end-of-line (&optional arg) + "Call `avy-goto-line' and move to the end of the line." + (interactive "p") + (avy-goto-line arg) + (end-of-line)) + +;;;###autoload +(defun avy-copy-line (arg) + "Copy a selected line above the current line. +ARG lines can be used." + (interactive "p") + (let ((initial-window (selected-window))) + (avy-with avy-copy-line + (let* ((start (avy--line)) + (str (buffer-substring-no-properties + start + (save-excursion + (goto-char start) + (move-end-of-line arg) + (point))))) + (select-window initial-window) + (cond ((eq avy-line-insert-style 'above) + (beginning-of-line) + (save-excursion + (insert str "\n"))) + ((eq avy-line-insert-style 'below) + (end-of-line) + (insert "\n" str) + (beginning-of-line)) + (t + (user-error "Unexpected `avy-line-insert-style'"))))))) + +;;;###autoload +(defun avy-move-line (arg) + "Move a selected line above the current line. +ARG lines can be used." + (interactive "p") + (let ((initial-window (selected-window))) + (avy-with avy-move-line + (let ((start (avy--line))) + (save-excursion + (goto-char start) + (kill-whole-line arg)) + (select-window initial-window) + (cond ((eq avy-line-insert-style 'above) + (beginning-of-line) + (save-excursion + (insert + (current-kill 0)))) + ((eq avy-line-insert-style 'below) + (end-of-line) + (newline) + (save-excursion + (insert (substring (current-kill 0) 0 -1)))) + (t + (user-error "Unexpected `avy-line-insert-style'"))))))) + +;;;###autoload +(defun avy-copy-region (arg) + "Select two lines and copy the text between them to point. + +The window scope is determined by `avy-all-windows' or +`avy-all-windows-alt' when ARG is non-nil." + (interactive "P") + (let ((initial-window (selected-window))) + (avy-with avy-copy-region + (let* ((beg (save-selected-window + (avy--line arg))) + (end (avy--line arg)) + (str (buffer-substring-no-properties + beg + (save-excursion + (goto-char end) + (line-end-position))))) + (select-window initial-window) + (cond ((eq avy-line-insert-style 'above) + (beginning-of-line) + (save-excursion + (insert str "\n"))) + ((eq avy-line-insert-style 'below) + (end-of-line) + (newline) + (save-excursion + (insert str))) + (t + (user-error "Unexpected `avy-line-insert-style'"))))))) + +;;;###autoload +(defun avy-move-region () + "Select two lines and move the text between them above the current line." + (interactive) + (avy-with avy-move-region + (let* ((initial-window (selected-window)) + (beg (avy--line)) + (end (avy--line)) + text) + (when (> beg end) + (cl-rotatef beg end)) + (setq end (save-excursion + (goto-char end) + (1+ (line-end-position)))) + (setq text (buffer-substring beg end)) + (move-beginning-of-line nil) + (delete-region beg end) + (select-window initial-window) + (insert text)))) + +;;;###autoload +(defun avy-kill-region (arg) + "Select two lines and kill the region between them. + +The window scope is determined by `avy-all-windows' or +`avy-all-windows-alt' when ARG is non-nil." + (interactive "P") + (let ((initial-window (selected-window))) + (avy-with avy-kill-region + (let* ((beg (save-selected-window + (list (avy--line arg) (selected-window)))) + (end (list (avy--line arg) (selected-window)))) + (cond + ((not (numberp (car beg))) + (user-error "Fail to select the beginning of region")) + ((not (numberp (car end))) + (user-error "Fail to select the end of region")) + ;; Restrict operation to same window. It's better if it can be + ;; different windows but same buffer; however, then the cloned + ;; buffers with different narrowed regions might cause problem. + ((not (equal (cdr beg) (cdr end))) + (user-error "Selected points are not in the same window")) + ((< (car beg) (car end)) + (save-excursion + (kill-region + (car beg) + (progn (goto-char (car end)) (forward-visible-line 1) (point))))) + (t + (save-excursion + (kill-region + (progn (goto-char (car beg)) (forward-visible-line 1) (point)) + (car end))))))) + (select-window initial-window))) + +;;;###autoload +(defun avy-kill-ring-save-region (arg) + "Select two lines and save the region between them to the kill ring. +The window scope is determined by `avy-all-windows'. +When ARG is non-nil, do the opposite of `avy-all-windows'." + (interactive "P") + (let ((initial-window (selected-window))) + (avy-with avy-kill-ring-save-region + (let* ((beg (save-selected-window + (list (avy--line arg) (selected-window)))) + (end (list (avy--line arg) (selected-window)))) + (cond + ((not (numberp (car beg))) + (user-error "Fail to select the beginning of region")) + ((not (numberp (car end))) + (user-error "Fail to select the end of region")) + ((not (equal (cdr beg) (cdr end))) + (user-error "Selected points are not in the same window")) + ((< (car beg) (car end)) + (save-excursion + (kill-ring-save + (car beg) + (progn (goto-char (car end)) (forward-visible-line 1) (point))))) + (t + (save-excursion + (kill-ring-save + (progn (goto-char (car beg)) (forward-visible-line 1) (point)) + (car end))))))) + (select-window initial-window))) + +;;;###autoload +(defun avy-kill-whole-line (arg) + "Select line and kill the whole selected line. + +With a numerical prefix ARG, kill ARG line(s) starting from the +selected line. If ARG is negative, kill backward. + +If ARG is zero, kill the selected line but exclude the trailing +newline. + +\\[universal-argument] 3 \\[avy-kil-whole-line] kill three lines +starting from the selected line. \\[universal-argument] -3 + +\\[avy-kill-whole-line] kill three lines backward including the +selected line." + (interactive "P") + (let ((initial-window (selected-window))) + (avy-with avy-kill-whole-line + (let* ((start (avy--line))) + (if (not (numberp start)) + (user-error "Fail to select the line to kill") + (save-excursion (goto-char start) + (kill-whole-line arg))))) + (select-window initial-window))) + +;;;###autoload +(defun avy-kill-ring-save-whole-line (arg) + "Select line and save the whole selected line as if killed, but don’t kill it. + +This command is similar to `avy-kill-whole-line', except that it +saves the line(s) as if killed, but does not kill it(them). + +With a numerical prefix ARG, kill ARG line(s) starting from the +selected line. If ARG is negative, kill backward. + +If ARG is zero, kill the selected line but exclude the trailing +newline." + (interactive "P") + (let ((initial-window (selected-window))) + (avy-with avy-kill-ring-save-whole-line + (let* ((start (avy--line))) + (if (not (numberp start)) + (user-error "Fail to select the line to kill") + (save-excursion + (let ((kill-read-only-ok t) + (buffer-read-only t)) + (goto-char start) + (kill-whole-line arg)))))) + (select-window initial-window))) + +;;;###autoload +(defun avy-setup-default () + "Setup the default shortcuts." + (eval-after-load "isearch" + '(define-key isearch-mode-map (kbd "C-'") 'avy-isearch))) + +(defcustom avy-timeout-seconds 0.5 + "How many seconds to wait for the second char." + :type 'float) + +(defcustom avy-enter-times-out t + "Whether enter exits avy-goto-char-timer early. If nil it matches newline" + :type 'boolean) + +(defun avy--read-candidates (&optional re-builder) + "Read as many chars as possible and return their occurrences. +At least one char must be read, and then repeatedly one next char +may be read if it is entered before `avy-timeout-seconds'. Any +key defined in `avy-del-last-char-by' (by default `C-h' and `DEL') +deletes the last char entered, and `RET' exits with the +currently read string immediately instead of waiting for another +char for `avy-timeout-seconds'. +The format of the result is the same as that of `avy--regex-candidates'. +This function obeys `avy-all-windows' setting. +RE-BUILDER is a function that takes a string and returns a regex. +When nil, `regexp-quote' is used. +If a group is captured, the first group is highlighted. +Otherwise, the whole regex is highlighted." + (let ((str "") + (re-builder (or re-builder #'regexp-quote)) + char break overlays regex) + (unwind-protect + (progn + (while (and (not break) + (setq char + (read-char (format "%d char%s: " + (length overlays) + (if (string= str "") + str + (format " (%s)" str))) + t + (and (not (string= str "")) + avy-timeout-seconds)))) + ;; Unhighlight + (dolist (ov overlays) + (delete-overlay ov)) + (setq overlays nil) + (cond + ;; Handle RET + ((= char 13) + (if avy-enter-times-out + (setq break t) + (setq str (concat str (list ?\n))))) + ;; Handle C-h, DEL + ((memq char avy-del-last-char-by) + (let ((l (length str))) + (when (>= l 1) + (setq str (substring str 0 (1- l)))))) + ;; Handle ESC + ((= char 27) + (keyboard-quit)) + (t + (setq str (concat str (list char))))) + ;; Highlight + (when (>= (length str) 1) + (let ((case-fold-search + (or avy-case-fold-search (string= str (downcase str)))) + found) + (avy-dowindows current-prefix-arg + (dolist (pair (avy--find-visible-regions + (window-start) + (window-end (selected-window) t))) + (save-excursion + (goto-char (car pair)) + (setq regex (funcall re-builder str)) + (while (re-search-forward regex (cdr pair) t) + (unless (get-char-property (1- (point)) 'invisible) + (let* ((idx (if (= (length (match-data)) 4) 1 0)) + (ov (make-overlay + (match-beginning idx) (match-end idx)))) + (setq found t) + (push ov overlays) + (overlay-put + ov 'window (selected-window)) + (overlay-put + ov 'face 'avy-goto-char-timer-face))))))) + ;; No matches at all, so there's surely a typo in the input. + (unless found (beep))))) + (nreverse (mapcar (lambda (ov) + (cons (cons (overlay-start ov) + (overlay-end ov)) + (overlay-get ov 'window))) + overlays))) + (dolist (ov overlays) + (delete-overlay ov))))) + +;;;###autoload +(defun avy-goto-char-timer (&optional arg) + "Read one or many consecutive chars and jump to the first one. +The window scope is determined by `avy-all-windows' (ARG negates it)." + (interactive "P") + (let ((avy-all-windows (if arg + (not avy-all-windows) + avy-all-windows))) + (avy-with avy-goto-char-timer + (avy--process + (avy--read-candidates) + (avy--style-fn avy-style))))) + +(defun avy-push-mark () + "Store the current point and window." + (ring-insert avy-ring + (cons (point) (selected-window))) + (unless (region-active-p) + (push-mark))) + +(defun avy-pop-mark () + "Jump back to the last location of `avy-push-mark'." + (interactive) + (let (res) + (condition-case nil + (progn + (while (not (window-live-p + (cdr (setq res (ring-remove avy-ring 0)))))) + (let* ((window (cdr res)) + (frame (window-frame window))) + (when (and (frame-live-p frame) + (not (eq frame (selected-frame)))) + (select-frame-set-input-focus frame)) + (select-window window) + (goto-char (car res)))) + (error + (set-mark-command 4))))) + +;; ** Org-mode +(defvar org-reverse-note-order) +(declare-function org-refile "org") +(declare-function org-back-to-heading "org") + +(defun avy-org-refile-as-child () + "Refile current heading as first child of heading selected with `avy.'" + ;; Inspired by `org-teleport': http://kitchingroup.cheme.cmu.edu/blog/2016/03/18/Org-teleport-headlines/ + (interactive) + (let ((rfloc (save-excursion + (let* ((org-reverse-note-order t) + (pos (avy-with avy-goto-line + (avy--generic-jump (rx bol (1+ "*") (1+ space)) + nil avy-style) + (point))) + (filename (buffer-file-name (or (buffer-base-buffer (current-buffer)) + (current-buffer))))) + (list nil filename nil pos))))) + ;; org-refile must be called outside of the excursion + (org-refile nil nil rfloc))) + +(defun avy-org-goto-heading-timer (&optional arg) + "Read one or many characters and jump to matching Org headings. +The window scope is determined by `avy-all-windows' (ARG negates it)." + (interactive "P") + (let ((avy-all-windows (if arg + (not avy-all-windows) + avy-all-windows))) + (avy-with avy-goto-char-timer + (avy--process + (avy--read-candidates + (lambda (input) + (format "^\\*+ .*\\(%s\\)" input))) + (avy--style-fn avy-style)) + (org-back-to-heading)))) + +(provide 'avy) + +;;; avy.el ends here diff --git a/elpa/avy-readme.txt b/elpa/avy-readme.txt new file mode 100644 index 00000000..f0e8504a --- /dev/null +++ b/elpa/avy-readme.txt @@ -0,0 +1,27 @@ +With Avy, you can move point to any position in Emacs – even in a +different window – using very few keystrokes. For this, you look at +the position where you want point to be, invoke Avy, and then enter +the sequence of characters displayed at that position. + +If the position you want to jump to can be determined after only +issuing a single keystroke, point is moved to the desired position +immediately after that keystroke. In case this isn't possible, the +sequence of keystrokes you need to enter is comprised of more than +one character. Avy uses a decision tree where each candidate position +is a leaf and each edge is described by a character which is distinct +per level of the tree. By entering those characters, you navigate the +tree, quickly arriving at the desired candidate position, such that +Avy can move point to it. + +Note that this only makes sense for positions you are able to see +when invoking Avy. These kinds of positions are supported: + +* character positions +* word or subword start positions +* line beginning positions +* link positions +* window positions + +If you're familiar with the popular `ace-jump-mode' package, this +package does all that and more, without the implementation +headache. diff --git a/elpa/aws-snippets-20180410.1545/aws-snippets-autoloads.el b/elpa/aws-snippets-20180410.1545/aws-snippets-autoloads.el new file mode 100644 index 00000000..fc25375d --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/aws-snippets-autoloads.el @@ -0,0 +1,33 @@ +;;; aws-snippets-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "aws-snippets" "aws-snippets.el" (0 0 0 0)) +;;; Generated autoloads from aws-snippets.el + +(autoload 'aws-snippets-initialize "aws-snippets" "\ +Initialize package. + +\(fn)" nil nil) + +(eval-after-load 'yasnippet '(aws-snippets-initialize)) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "aws-snippets" '("aws-snippets-"))) + +;;;*** + +;;;### (autoloads nil nil ("aws-snippets-pkg.el") (0 0 0 0)) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; aws-snippets-autoloads.el ends here diff --git a/elpa/aws-snippets-20180410.1545/aws-snippets-pkg.el b/elpa/aws-snippets-20180410.1545/aws-snippets-pkg.el new file mode 100644 index 00000000..199abd06 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/aws-snippets-pkg.el @@ -0,0 +1,7 @@ +(define-package "aws-snippets" "20180410.1545" "Yasnippets for AWS" + '((yasnippet "0.8.0")) + :keywords + '("snippets")) +;; Local Variables: +;; no-byte-compile: t +;; End: diff --git a/elpa/aws-snippets-20180410.1545/aws-snippets.el b/elpa/aws-snippets-20180410.1545/aws-snippets.el new file mode 100644 index 00000000..612716e7 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/aws-snippets.el @@ -0,0 +1,206 @@ +;;; aws-snippets.el --- Yasnippets for AWS + +;; Copyright (C) 2018 Andreas Gerler +;; keywords: snippets +;; Version: 0.1.0 +;; Package-Requires: ((yasnippet "0.8.0")) + +;; Permission is hereby granted, free of charge, to any person obtaining +;; a copy of this software and associated documentation files (the +;; "Software"), to deal in the Software without restriction, including +;; without limitation the rights to use, copy, modify, merge, publish, +;; distribute, sublicense, and/or sell copies of the Software, and to +;; permit persons to whom the Software is furnished to do so, subject to +;; the following conditions: + +;; The above copyright notice and this permission notice shall be +;; included in all copies or substantial portions of the Software. + +;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +;;; Commentary: + +;; A collection of yasnippet snippets to be used with AWS CLI + +;;; Code: + +(defvar aws-snippets-dir (file-name-directory (or load-file-name + (buffer-file-name)))) + +(defcustom aws-snippets-regions '("us-east-1" "eu-west-1" "ap-southeast-1") + "List of AWS regions for selections." + :tag "regions" + :type '(choice (string :tag "Region") + (repeat :tag "List of Regions" + (string :tag "Region"))) + :set #'(lambda (symbol new) + (let ((old (and (boundp symbol) + (symbol-value symbol)))) + (set-default symbol new) + )) + :group 'aws-snippets) + +(defcustom aws-snippets-profiles '("test" "prod") + "List of AWS profiles for selections." + :tag "profiles" + :type '(choice (string :tag "Profile") + (repeat :tag "List of Profiles" + (string :tag "Profiles"))) + :set #'(lambda (symbol new) + (let ((old (and (boundp symbol) + (symbol-value symbol)))) + (set-default symbol new) + )) + :group 'aws-snippets) + +(defcustom aws-snippets-filters '("tag:Name" "tag:Project" "tag:Type" "tag:Cluster" "instance.group-id" "ip-address" "private-ip-address" "network-interface.subnet-id" "description" "name" "iam-instance-profile.arn") + "List of AWS filters for selections." + :tag "default-filters" + :type '(choice (string :tag "Filter") + (repeat :tag "List of Filters" + (string :tag "Filter"))) + :set #'(lambda (symbol new) + (let ((old (and (boundp symbol) + (symbol-value symbol)))) + (set-default symbol new) + )) + :group 'aws-snippets) + +(defcustom aws-snippets-ami-ls-query '"reverse(sort_by(Images, &CreationDate)[].{CreationDate:CreationDate,Name:Name,ImageId:ImageId,Public:Public,Description:Description})" + "Query string used for ami-ls." + :tag "ami-ls-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-autoscaling-describe-auto-scaling-groups-query '"AutoScalingGroups[].{Name: AutoScalingGroupName, Desired: DesiredCapacity,Min: MinSize, Max: MaxSize}" + "Query string used for autoscaling-describe-auto-scaling-groups." + :tag "autoscaling-describe-auto-scaling-groups" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-autoscaling-describe-launch-configurations-query '"reverse(sort_by(LaunchConfigurations &CreatedTime)[*].[LaunchConfigurationName, CreatedTime])" + "Query string used for autoscaling-describe-launch-configurations." + :tag "autoscaling-describe-launch-configurations-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-ec2-get-dns-names-query '"Reservations[].Instances[?State.Name=='running'].[InstanceId, PublicDnsName]" + "Query string used for aws-ec2-get-dns-names." + :tag "ec2-get-dns-names-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-ec2-get-instance-volumes-query '"Reservations[].Instances[].[join(\`,\`,Tags[?Key==\`Name\`].Value),join(' ', BlockDeviceMappings[].Ebs.VolumeId)]" + "Query string used for ec2-get-instance-volumes." + :tag "ec2-get-instance-volumes-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-ec2-get-securitygroups-query '"sort_by(SecurityGroups, &GroupName)[*].[GroupName, GroupId, Description]" + "Query string used for ec2-get-securitygroups." + :tag "ec2-get-securitygroups-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-ec2-get-snapshots-query '"Snapshots[].[join(\`,\`,Tags[?Key==\`Name\`].Value),StartTime,Description,SnapshotId,VolumeId,VolumeSize,Progress]" + "Query string used for ec2-get-snapshots-query." + :tag "ec2-get-snapshots-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-ec2-get-volumes-query '"Volumes[].[VolumeId,State,SnapshotId,join(\`,\`,Tags[?Key==\`Name\`].Value)]" + "Query string used for ec2-get-volumes-query." + :tag "ec2-get-volumes-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-ec2-get-volumes-unused-query '"Volumes[].[VolumeId,Size,VolumeType,CreateTime,State,SnapshotId]" + "Query string used for ec2-get-volumes-unused-query." + :tag "ec2-get-volumes-unused-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-ec2-instance-running-query '"Reservations[].Instances[].[InstanceId, State.Name]" + "Query string used for ec2-instance-running." + :tag "ec2-instance-running-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-ec2-list-instances-query '("Reservations[].Instances[].[Tags[?Key==`Name`].Value[] | [0],Tags[?Key==`Schedule`].Value[] | [0],InstanceId, State.Name, PublicDnsName, InstanceType,Placement.AvailabilityZone,LaunchTime]" + "Reservations[].Instances[].[Tags[?Key==`Name`].Value[] | [0],Tags[?Key==`Schedule`].Value[] | [0],InstanceId, State.Name, PublicDnsName, InstanceType,Placement.AvailabilityZone,LaunchTime, IamInstanceProfile.Arn]" + "Reservations[].Instances[].[Tags[?Key==`Name`].Value[] | [0],Tags[?Key==`Schedule`].Value[] | [0],InstanceId, State.Name, PublicDnsName, InstanceType,Placement.AvailabilityZone,LaunchTime, KeyName]") + "Query string used for ec2 describe-instances." + :tag "ec2-list-instances-query" + :type '(choice (string :tag "Query") + (repeat :tag "List of Queries" + (string :tag "Query"))) + :set #'(lambda (symbol new) + (let ((old (and (boundp symbol) + (symbol-value symbol)))) + (set-default symbol new) + )) + :group 'aws-snippets) + +(defcustom aws-snippets-ec2-list-subnets-query '"sort_by(sort_by(Subnets[].{VpcId:VpcId, SubnetId:SubnetId, State:State, AvailabilityZone:AvailabilityZone, CidrBlock:CidrBlock, AvailableIpAddressCount:AvailableIpAddressCount Tags:to_string(Tags[].[Key, Value])}, &SubnetId), &VpcId)" + "Query string used for ec2-list-subnets." + :tag "ec2-list-subnets-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-ec2-list-vpcs-query '"sort_by(Vpcs[].{VpcId:VpcId, State:State, AvailabilityZone:AvailabilityZone, CidrBlock:CidrBlock, AvailableIpAddressCount:AvailableIpAddressCount Tags:to_string(Tags[].[Key, Value])}, &VpcId)" + "Query string used for ec2-list-vpcs." + :tag "ec2-list-vpcs-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-elb-get-list-query '"reverse(sort_by(LoadBalancerDescriptions, &CreatedTime)[].[LoadBalancerName, CreatedTime])" + "Query string used for elb-get-list." + :tag "elb-get-list-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-emr-list-clusters-query '"Clusters[*].{ID: Id, NAME: Name}" + "Query string used for emr-list-clusters." + :tag "emr-list-clusters-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-rds-describe-instances-query '"DBInstances[*].[DBInstanceIdentifier,DbiResourceId, Endpoint.Address]" + "Query string used for rds describe-db-instances." + :tag "rds-describe-db-instances-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-route53-list-hosted-zones-query '"HostedZones[].[Id, Name]" + "Query string used for route53 list-hosted-zones." + :tag "route53-list-hosted-zones-query" + :group 'aws-snippets + :type 'string) + +(defcustom aws-snippets-aws-support-ls-query '"reverse(sort_by(cases, &timeCreated)[].[caseId, subject, timeCreated, displayId])" + "Query string used for aws support-ls-query." + :tag "aws-support-ls-query" + :group 'aws-snippets + :type 'string) + +;;;###autoload +(defun aws-snippets-initialize () + "Initialize package." + (let ((snip-dir (expand-file-name "snippets" aws-snippets-dir))) + (when (boundp 'yas-snippet-dirs)(add-to-list 'yas-snippet-dirs snip-dir t)) + (yas-load-directory snip-dir))) + +;;;###autoload +(eval-after-load 'yasnippet + '(aws-snippets-initialize)) + +(require 'yasnippet) + +(provide 'aws-snippets) +;;; aws-snippets.el ends here diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ami-ls b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ami-ls new file mode 100644 index 00000000..0d456a15 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ami-ls @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ami-ls +# key: ami-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 describe-images --owners \$`(if (string-equal major-mode "eshell-mode")(message "{")(message "("))` aws --profile=$1 ec2 describe-security-groups --group-names 'Default' --query 'SecurityGroups[0].OwnerId' --output text `(if (string-equal major-mode "eshell-mode")(message "}")(message ")"))` --query "`(print aws-snippets-ami-ls-query)`" --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-autoscaling-describe-auto-scaling-groups b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-autoscaling-describe-auto-scaling-groups new file mode 100644 index 00000000..cfe0bf8d --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-autoscaling-describe-auto-scaling-groups @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-autoscaling-describe-auto-scaling-groups +# key: asg-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} autoscaling describe-auto-scaling-groups --query '`(print aws-snippets-autoscaling-describe-auto-scaling-groups-query)`' --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-autoscaling-describe-launch-configurations b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-autoscaling-describe-launch-configurations new file mode 100644 index 00000000..b7082fc3 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-autoscaling-describe-launch-configurations @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-autoscaling-describe-launch-configurations +# key: asl-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} autoscaling describe-launch-configurations --query '`(print aws-snippets-autoscaling-describe-launch-configurations-query)`' --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-autoscaling-update-auto-scaling-group-min-max b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-autoscaling-update-auto-scaling-group-min-max new file mode 100644 index 00000000..03709394 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-autoscaling-update-auto-scaling-group-min-max @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-autoscaling-update-auto-scaling-group-min-max +# key: aws-autoscaling-update-auto-scaling-group-min-max +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} autoscaling update-auto-scaling-group --auto-scaling-group-name ${4:`(current-kill 0)`} --min-size $5 --max-size $6 $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-change-ls b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-change-ls new file mode 100644 index 00000000..825d942d --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-change-ls @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-cloudformation-change-ls +# key: cloud-change-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} cloudformation list-change-sets --stack-name ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-create-change-set b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-create-change-set new file mode 100644 index 00000000..a93de833 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-create-change-set @@ -0,0 +1,15 @@ +# -*- mode: snippet -*- +# name: aws-cloudformation-create-change-set +# key: cloud-createchange +# expand-env: ((yas/indent-line 'auto) (yas/wrap-around-region 't)) +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} \ +${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} \ +cloudformation create-change-set \ +${4:--capabilities CAPABILITY_NAMED_IAM} \ +--stack-name '$5' \ +--change-set-name '$6' \ +--description '$7' \ +--parameters ${8:file://} \ +${9:--change-set-type=${10:$$(yas-choose-value '("CREATE" "UPDATE"))}}$0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-describe-change-set b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-describe-change-set new file mode 100644 index 00000000..958515b1 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-describe-change-set @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-cloudformation-describe-change-set +# key: cloud-descchange +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} cloudformation describe-change-set --stack-name ${4:`(current-kill 0)`} --change-set-name $5 --output ${6:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-describe-stack b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-describe-stack new file mode 100644 index 00000000..143d7ed1 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-describe-stack @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-cloudformation-describe-stack +# key: cloud-desc +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} cloudformation describe-stacks --stack-name ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-describe-stack-events b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-describe-stack-events new file mode 100644 index 00000000..062be5e7 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-describe-stack-events @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-cloudformation-describe-stack-events +# key: cloud-events-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} cloudformation describe-stack-events --stack-name ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-ls b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-ls new file mode 100644 index 00000000..599058b8 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-ls @@ -0,0 +1,25 @@ +# -*- mode: snippet -*- +# name: aws-cloudformation-ls +# key: cloud-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} cloudformation list-stacks --stack-status-filter ${4:$$(yas-choose-value '( +"CREATE_COMPLETE" +"CREATE_IN_PROGRESS" +"CREATE_FAILED" +"ROLLBACK_IN_PROGRESS" +"ROLLBACK_FAILED" +"ROLLBACK_COMPLETE" +"DELETE_IN_PROGRESS" +"DELETE_FAILED" +"DELETE_COMPLETE" +"UPDATE_IN_PROGRESS" +"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS" +"UPDATE_COMPLETE" +"UPDATE_ROLLBACK_IN_PROGRESS" +"UPDATE_ROLLBACK_FAILED" +"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS" +"UPDATE_ROLLBACK_COMPLETE" +"REVIEW_IN_PROGRESS" +"CREATE_IN_PROGRESS CREATE_FAILED CREATE_COMPLETE ROLLBACK_IN_PROGRESS ROLLBACK_FAILED ROLLBACK_COMPLETE DELETE_IN_PROGRESS DELETE_FAILED UPDATE_IN_PROGRESS UPDATE_COMPLETE_CLEANUP_IN_PROGRESS UPDATE_COMPLETE UPDATE_ROLLBACK_IN_PROGRESS UPDATE_ROLLBACK_FAILED UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS UPDATE_ROLLBACK_COMPLETE REVIEW_IN_PROGRESS" +))} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-validate-template b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-validate-template new file mode 100644 index 00000000..e288e3ef --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudformation-validate-template @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-cloudformation-validate-template +# key: cloud-val-temp +# group: aws +# -- +aws --profile=test --region=us-east-1 cloudformation validate-template --template-body file://${1:`(current-kill 0)`} --output ${2:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudtrail-lookup-events b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudtrail-lookup-events new file mode 100644 index 00000000..e721a36f --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-cloudtrail-lookup-events @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-cloudtrail-lookup-events +# key: cloudtrail-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} cloudtrail lookup-events --max-items ${4:100} --lookup-attributes AttributeKey=${5:$$(yas-choose-value '("ResourceType,AttributeValue=AWS::EC2::Instance" "ResourceName,AttributeValue="))}$6 --output ${7:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-delete-snapshot b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-delete-snapshot new file mode 100644 index 00000000..be6faa84 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-delete-snapshot @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-delete-snapshot (yank) +# key: snap-del +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 delete-snapshot --snapshot-id ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-delete-volume b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-delete-volume new file mode 100644 index 00000000..62caa0cf --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-delete-volume @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-delete-volume (yank) +# key: ebs-del +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 delete-volume --volume-id ${4:`(current-kill 0)`} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-describe-instance-attribute b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-describe-instance-attribute new file mode 100644 index 00000000..57696cae --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-describe-instance-attribute @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-describe-instance-attribute (yank) +# key: ec2-attribute +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 describe-instance-attribute --instance-id ${4:`(current-kill 0)`} --attribute ${5:$$(yas-choose-value '("instanceType" "kernel" "ramdisk" "userData" "disableApiTermination" "instanceInitiatedShutdownBehavior" "rootDeviceName" "blockDeviceMapping" "productCodes" "sourceDestCheck" "groupSet" "ebsOptimized" "sriovNetSupport"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-describe-instance-status b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-describe-instance-status new file mode 100644 index 00000000..b52b723b --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-describe-instance-status @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-describe-instance-status (yank) +# key: aws-ec2-describe-instance-status +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 describe-instance-status --instance-ids ${4:`(current-kill 0)`} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-describe-userdata b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-describe-userdata new file mode 100644 index 00000000..ace7b2d1 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-describe-userdata @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-describe-userdata (yank) +# key: ec2-userdata +# group: aws +# -- +(base64-decode-string (shell-command-to-string "aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 describe-instance-attribute --instance-id ${4:`(current-kill 0)`} --attribute userData --query 'UserData.Value' --output text"))$0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-console-output b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-console-output new file mode 100644 index 00000000..597a1bed --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-console-output @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-console-output (yank) +# key: ec2-console +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 get-console-output --output text --instance-id ${4:`(current-kill 0)`} ># $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-dns-names b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-dns-names new file mode 100644 index 00000000..79ac75bf --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-dns-names @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-dns-names +# key: aws-ec2-get-dns-names +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 describe-instances --filters "Name=tag:Name,Values=$4" --query "`(print aws-snippets-ec2-get-dns-names-query)`" --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-instance-details b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-instance-details new file mode 100644 index 00000000..4d38a909 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-instance-details @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-instance-details (yank) +# key: ec2-det +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 describe-instances --instance-ids ${4:`(current-kill 0)`} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-instance-volumes b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-instance-volumes new file mode 100644 index 00000000..ccfd0c81 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-instance-volumes @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-instance-volumes +# key: ec2-vol +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-instances --query "`(print aws-snippets-ec2-get-instance-volumes-query)`" --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-securitygroup-details b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-securitygroup-details new file mode 100644 index 00000000..77062bdf --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-securitygroup-details @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-securitygroup-details (yank) +# key: sg-det +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-security-groups --group-ids ${4:`(current-kill 0)`} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-securitygroup-references b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-securitygroup-references new file mode 100644 index 00000000..17857460 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-securitygroup-references @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-securitygroup-references (yank) +# key: aws-ec2-get-securitygroup-references +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-security-group-references --group-id ${4:`(current-kill 0)`} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-securitygroups b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-securitygroups new file mode 100644 index 00000000..b71e0b71 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-securitygroups @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-securitygroups +# key: sg-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-security-groups --query "`(print aws-snippets-ec2-get-securitygroups-query)`" --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-snapshot-details b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-snapshot-details new file mode 100644 index 00000000..1f5dc2af --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-snapshot-details @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-snapshot-details (yank) +# key: snap-det +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-snapshots --snapshot-id ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-snapshots b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-snapshots new file mode 100644 index 00000000..31c47d81 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-snapshots @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-snapshots +# key: snap-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-snapshots --query '`(print aws-snippets-ec2-get-snapshots-query)`' --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-volumes b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-volumes new file mode 100644 index 00000000..546f1739 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-volumes @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-volumes +# key: ebs-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-volumes --query '`(print aws-snippets-ec2-get-volumes-query)`' --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-volumes-unused b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-volumes-unused new file mode 100644 index 00000000..65c94338 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-get-volumes-unused @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-get-volumes-unused +# key: ebs-ls-avail +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-volumes --query '`(print aws-snippets-ec2-get-volumes-unused-query)`' --filters Name=status,Values=available --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-instance-running b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-instance-running new file mode 100644 index 00000000..c2ae1028 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-instance-running @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-instance-running +# key: ec2state +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 describe-instances --instance-ids ${4:`(current-kill 0)`} --query "`(print aws-snippets-ec2-instance-running-query)`" --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-list-instances b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-list-instances new file mode 100644 index 00000000..00a8bf57 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-list-instances @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-list-instances +# key: ec2-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-instances --query '${4:$$(yas-choose-value aws-snippets-ec2-list-instances-query)}' --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-list-subnets b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-list-subnets new file mode 100644 index 00000000..9b99e144 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-list-subnets @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-list-subnets +# key: sub-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 describe-subnets --query "`(print aws-snippets-ec2-list-subnets-query)`" --output ${4:$$(yas-choose-value '("table" "text" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-list-vpcs b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-list-vpcs new file mode 100644 index 00000000..82ebfd89 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-list-vpcs @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-list-vpcs +# key: vpc-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 describe-vpcs --query "`(print aws-snippets-ec2-list-vpcs-query)`" --output ${4:$$(yas-choose-value '("table" "text" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-start-stop-instance b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-start-stop-instance new file mode 100644 index 00000000..e6d415cf --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-start-stop-instance @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-start-stop-instance (yank) +# key: ec2-start +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} ec2 ${4:$$(yas-choose-value '("start-instances" "stop-instances" "reboot-instances"))} --instance-ids ${5:`(current-kill 0)`} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-volume-details b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-volume-details new file mode 100644 index 00000000..0b1461a9 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-ec2-volume-details @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-ec2-volume-details (yank) +# key: ebs-det +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} ec2 describe-volumes --volume-ids ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-describe-instance-health b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-describe-instance-health new file mode 100644 index 00000000..07fd787f --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-describe-instance-health @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-elb-describe-instance-health (yank) +# key: aws-elb-describe-instance-health +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} elb describe-instance-health --load-balancer-name ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-describe-load-balancer b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-describe-load-balancer new file mode 100644 index 00000000..0b903d46 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-describe-load-balancer @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-elb-describe-load-balancer (yank) +# key: elb-det +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} elb describe-load-balancers --load-balancer-name ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-describe-load-balancer-attributes b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-describe-load-balancer-attributes new file mode 100644 index 00000000..113ce4e0 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-describe-load-balancer-attributes @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-elb-describe-load-balancer-attributes (yank) +# key: aws-elb-describe-load-balancer-attributes +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} elb describe-load-balancer-attributes --load-balancer-name ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-get-list b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-get-list new file mode 100644 index 00000000..a7c5b3ed --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-get-list @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-elb-get-list +# key: elb-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} elb describe-load-balancers --query "`(print aws-snippets-elb-get-list-query)`" --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-search b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-search new file mode 100644 index 00000000..3b3f9b97 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-elb-search @@ -0,0 +1,10 @@ +# -*- mode: snippet -*- +# name: aws-elb-search +# key: aws-elb-search +# group: aws +# -- +for REGION in `(mapconcat 'identity aws-snippets-regions " ")`; do + for BALANCER in \`aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} --region=\${REGION} elb describe-load-balancers --query "reverse(sort_by(LoadBalancerDescriptions, &CreatedTime)[].[LoadBalancerName])" --output text\`; do + aws --profile=$1 --region=\${REGION} elb describe-load-balancers --load-balancer-name \${BALANCER} --output text | awk "{print \\"\${REGION}:\${BALANCER}:\\"\\\$0}" + done +done $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-emr-describe-cluster b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-emr-describe-cluster new file mode 100644 index 00000000..c00cdcbc --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-emr-describe-cluster @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-emr-describe-cluster (yank) +# key: aws-emr-describe-cluster +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} --region=${2:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)} emr describe-cluster --cluster-id ${3: `(current-kill 0)`} --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-emr-list-clusters b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-emr-list-clusters new file mode 100644 index 00000000..175a66ef --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-emr-list-clusters @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-emr-list-clusters +# key: emr-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} --region=${2:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)} emr list-clusters --active --query '`(print aws-snippets-emr-list-clusters-query)`' --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-filters b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-filters new file mode 100644 index 00000000..6cdaa34c --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-filters @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-filters +# key: awsfil +# group: aws +# -- +--filters "Name=${1:$$(yas-choose-value aws-snippets-filters)},Values=$2" $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-logs-get-groups b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-logs-get-groups new file mode 100644 index 00000000..81fef5d2 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-logs-get-groups @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-logs-get-groups +# key: logs-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} logs describe-log-groups --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-logs-set-retention b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-logs-set-retention new file mode 100644 index 00000000..d071bd3a --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-logs-set-retention @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-logs-set-retention +# key: logs-set-ret +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)}} logs put-retention-policy --log-group-name ${4:`(current-kill 0)`} --retention-in-days ${5:$$(yas-choose-value '( "60" "1" "3" "5" "7" "14" "30" "90" "120" "150" "180" "365" "400" "545" "731" "1827" "3653"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-policy-ls b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-policy-ls new file mode 100644 index 00000000..e4e1c99c --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-policy-ls @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-policy-ls +# key: policy-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} iam list-policies --scope ${5:$$(yas-choose-value '("All" "AWS" "Local"))} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-db-instance-details b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-db-instance-details new file mode 100644 index 00000000..fe8b2c22 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-db-instance-details @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-rds-describe-db-instance-details (yank) +# key: rds-det +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} rds describe-db-instances --db-instance-identifier ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-db-instances b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-db-instances new file mode 100644 index 00000000..4f75830d --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-db-instances @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-rds-describe-db-instances +# key: rds-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} rds describe-db-instances --query "`(print aws-snippets-rds-describe-instances-query)`" --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-db-parameter-groups b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-db-parameter-groups new file mode 100644 index 00000000..53033528 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-db-parameter-groups @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-rds-describe-db-parameter-groups +# key: aws-rds-describe-db-parameter-groups +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} rds describe-db-parameter-groups --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-parameters b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-parameters new file mode 100644 index 00000000..48fb633e --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-rds-describe-parameters @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-rds-describe-parameters (yank) +# key: aws-rds-describe-parameters +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} rds describe-db-parameters --db-parameter-group-name ${4:`(current-kill 0)`} --query "Parameters[*][ParameterName, ParameterValue]" --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-region-loop b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-region-loop new file mode 100644 index 00000000..4ba9f532 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-region-loop @@ -0,0 +1,8 @@ +# -*- mode: snippet -*- +# name: aws-region-loop +# key: aws-region-loop +# group: aws +# -- +for REGION in `(mapconcat 'identity aws-snippets-regions " ")`; do +$0 +done diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-regions b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-regions new file mode 100644 index 00000000..72c28a0c --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-regions @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-regions +# key: awsreg +# group: aws +# -- +--region=${1:$$(yas-choose-value "\$\{REGION\}" aws-snippets-regions)} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-route53-list-hosted-zones b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-route53-list-hosted-zones new file mode 100644 index 00000000..6fbe41ef --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-route53-list-hosted-zones @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-route53-list-hosted-zones +# key: r53-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} route53 list-hosted-zones --query '`(print aws-snippets-route53-list-hosted-zones-query)`' --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-route53-list-resource-record-sets b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-route53-list-resource-record-sets new file mode 100644 index 00000000..bf70025f --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-route53-list-resource-record-sets @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-route53-list-resource-record-sets (yank) +# key: aws-route53-list-resource-record-sets +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} route53 list-resource-record-sets --hosted-zone-id ${2:`(current-kill 0)`} --query \"ResourceRecordSets[?contains(Name, '$3')]\" --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-sns-ls b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-sns-ls new file mode 100644 index 00000000..3d99d0e9 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-sns-ls @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-sns-ls +# key: sns-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} sns list-topics --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-support-describe b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-support-describe new file mode 100644 index 00000000..d8baaf78 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-support-describe @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-support-describe +# key: support-desc +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} support describe-communications --case-id ${4:`(current-kill 0)`} --output ${5:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-support-ls b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-support-ls new file mode 100644 index 00000000..7540de69 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/eshell-mode/aws-support-ls @@ -0,0 +1,6 @@ +# -*- mode: snippet -*- +# name: aws-support-ls +# key: support-ls +# group: aws +# -- +aws --profile=${1:$$(yas-choose-value aws-snippets-profiles)} ${2:--region=${3:$$(yas-choose-value aws-snippets-regions)}} support describe-cases --no-include-communications --query "`(print aws-snippets-aws-support-ls-query)`" --output ${4:$$(yas-choose-value '("text" "table" "json"))} $0 \ No newline at end of file diff --git a/elpa/aws-snippets-20180410.1545/snippets/sh-mode/.yas-parents b/elpa/aws-snippets-20180410.1545/snippets/sh-mode/.yas-parents new file mode 100644 index 00000000..bf9d9870 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/sh-mode/.yas-parents @@ -0,0 +1,2 @@ +shell-mode +eshell-mode diff --git a/elpa/aws-snippets-20180410.1545/snippets/shell-mode/.yas-parents b/elpa/aws-snippets-20180410.1545/snippets/shell-mode/.yas-parents new file mode 100644 index 00000000..2de397c8 --- /dev/null +++ b/elpa/aws-snippets-20180410.1545/snippets/shell-mode/.yas-parents @@ -0,0 +1 @@ +eshell-mode diff --git a/elpa/aws-snippets-readme.txt b/elpa/aws-snippets-readme.txt new file mode 100644 index 00000000..82ef4387 --- /dev/null +++ b/elpa/aws-snippets-readme.txt @@ -0,0 +1 @@ +A collection of yasnippet snippets to be used with AWS CLI diff --git a/elpa/dash-20180910.1856/dash-autoloads.el b/elpa/dash-20180910.1856/dash-autoloads.el new file mode 100644 index 00000000..8bacbc83 --- /dev/null +++ b/elpa/dash-20180910.1856/dash-autoloads.el @@ -0,0 +1,22 @@ +;;; dash-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "dash" "dash.el" (0 0 0 0)) +;;; Generated autoloads from dash.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "dash" '("dash-" "-keep" "-butlast" "-non" "-only-some" "-zip" "-e" "->" "-a" "-gr" "-when-let" "-d" "-l" "-s" "-p" "-r" "-m" "-i" "-f" "-u" "-value-to-list" "-t" "--" "-c" "!cons" "!cdr"))) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; dash-autoloads.el ends here diff --git a/elpa/dash-20180910.1856/dash-pkg.el b/elpa/dash-20180910.1856/dash-pkg.el new file mode 100644 index 00000000..29e71235 --- /dev/null +++ b/elpa/dash-20180910.1856/dash-pkg.el @@ -0,0 +1,2 @@ +;;; -*- no-byte-compile: t -*- +(define-package "dash" "20180910.1856" "A modern list library for Emacs" 'nil :commit "6514359b8606a6a9a94068ccd601fcd6379d6584" :keywords '("lists") :authors '(("Magnar Sveen" . "magnars@gmail.com")) :maintainer '("Magnar Sveen" . "magnars@gmail.com")) diff --git a/elpa/dash-20180910.1856/dash.el b/elpa/dash-20180910.1856/dash.el new file mode 100644 index 00000000..ee67456a --- /dev/null +++ b/elpa/dash-20180910.1856/dash.el @@ -0,0 +1,2993 @@ +;;; dash.el --- A modern list library for Emacs -*- lexical-binding: t -*- + +;; Copyright (C) 2012-2016 Free Software Foundation, Inc. + +;; Author: Magnar Sveen +;; Version: 2.14.1 +;; Package-Version: 20180910.1856 +;; Keywords: lists + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Commentary: + +;; A modern list api for Emacs. +;; +;; See documentation on https://github.com/magnars/dash.el#functions +;; +;; **Please note** The lexical binding in this file is not utilised at the +;; moment. We will take full advantage of lexical binding in an upcoming 3.0 +;; release of Dash. In the meantime, we've added the pragma to avoid a bug that +;; you can read more about in https://github.com/magnars/dash.el/issues/130. +;; + +;;; Code: + +(defgroup dash () + "Customize group for dash.el" + :group 'lisp + :prefix "dash-") + +(defun dash--enable-fontlock (symbol value) + (when value + (dash-enable-font-lock)) + (set-default symbol value)) + +(defcustom dash-enable-fontlock nil + "If non-nil, enable fontification of dash functions, macros and +special values." + :type 'boolean + :set 'dash--enable-fontlock + :group 'dash) + +(defmacro !cons (car cdr) + "Destructive: Set CDR to the cons of CAR and CDR." + `(setq ,cdr (cons ,car ,cdr))) + +(defmacro !cdr (list) + "Destructive: Set LIST to the cdr of LIST." + `(setq ,list (cdr ,list))) + +(defmacro --each (list &rest body) + "Anaphoric form of `-each'." + (declare (debug (form body)) + (indent 1)) + (let ((l (make-symbol "list"))) + `(let ((,l ,list) + (it-index 0)) + (while ,l + (let ((it (car ,l))) + ,@body) + (setq it-index (1+ it-index)) + (!cdr ,l))))) + +(defmacro -doto (eval-initial-value &rest forms) + "Eval a form, then insert that form as the 2nd argument to other forms. +The EVAL-INITIAL-VALUE form is evaluated once. Its result is +passed to FORMS, which are then evaluated sequentially. Returns +the target form." + (declare (indent 1)) + (let ((retval (make-symbol "value"))) + `(let ((,retval ,eval-initial-value)) + ,@(mapcar (lambda (form) + (if (sequencep form) + `(,(-first-item form) ,retval ,@(cdr form)) + `(funcall form ,retval))) + forms) + ,retval))) + +(defun -each (list fn) + "Call FN with every item in LIST. Return nil, used for side-effects only." + (--each list (funcall fn it))) + +(put '-each 'lisp-indent-function 1) + +(defalias '--each-indexed '--each) + +(defun -each-indexed (list fn) + "Call (FN index item) for each item in LIST. + +In the anaphoric form `--each-indexed', the index is exposed as symbol `it-index'. + +See also: `-map-indexed'." + (--each list (funcall fn it-index it))) +(put '-each-indexed 'lisp-indent-function 1) + +(defmacro --each-while (list pred &rest body) + "Anaphoric form of `-each-while'." + (declare (debug (form form body)) + (indent 2)) + (let ((l (make-symbol "list")) + (c (make-symbol "continue"))) + `(let ((,l ,list) + (,c t) + (it-index 0)) + (while (and ,l ,c) + (let ((it (car ,l))) + (if (not ,pred) (setq ,c nil) ,@body)) + (setq it-index (1+ it-index)) + (!cdr ,l))))) + +(defun -each-while (list pred fn) + "Call FN with every item in LIST while (PRED item) is non-nil. +Return nil, used for side-effects only." + (--each-while list (funcall pred it) (funcall fn it))) + +(put '-each-while 'lisp-indent-function 2) + +(defmacro --each-r (list &rest body) + "Anaphoric form of `-each-r'." + (declare (debug (form body)) + (indent 1)) + (let ((v (make-symbol "vector"))) + ;; Implementation note: building vector is considerably faster + ;; than building a reversed list (vector takes less memory, so + ;; there is less GC), plus length comes naturally. In-place + ;; 'nreverse' would be faster still, but BODY would be able to see + ;; that, even if modification was reversed before we return. + `(let* ((,v (vconcat ,list)) + (it-index (length ,v)) + it) + (while (> it-index 0) + (setq it-index (1- it-index)) + (setq it (aref ,v it-index)) + ,@body)))) + +(defun -each-r (list fn) + "Call FN with every item in LIST in reversed order. + Return nil, used for side-effects only." + (--each-r list (funcall fn it))) + +(defmacro --each-r-while (list pred &rest body) + "Anaphoric form of `-each-r-while'." + (declare (debug (form form body)) + (indent 2)) + (let ((v (make-symbol "vector"))) + `(let* ((,v (vconcat ,list)) + (it-index (length ,v)) + it) + (while (> it-index 0) + (setq it-index (1- it-index)) + (setq it (aref ,v it-index)) + (if (not ,pred) + (setq it-index -1) + ,@body))))) + +(defun -each-r-while (list pred fn) + "Call FN with every item in reversed LIST while (PRED item) is non-nil. +Return nil, used for side-effects only." + (--each-r-while list (funcall pred it) (funcall fn it))) + +(defmacro --dotimes (num &rest body) + "Repeatedly executes BODY (presumably for side-effects) with symbol `it' bound to integers from 0 through NUM-1." + (declare (debug (form body)) + (indent 1)) + (let ((n (make-symbol "num"))) + `(let ((,n ,num) + (it 0)) + (while (< it ,n) + ,@body + (setq it (1+ it)))))) + +(defun -dotimes (num fn) + "Repeatedly calls FN (presumably for side-effects) passing in integers from 0 through NUM-1." + (--dotimes num (funcall fn it))) + +(put '-dotimes 'lisp-indent-function 1) + +(defun -map (fn list) + "Return a new list consisting of the result of applying FN to the items in LIST." + (mapcar fn list)) + +(defmacro --map (form list) + "Anaphoric form of `-map'." + (declare (debug (form form))) + `(mapcar (lambda (it) ,form) ,list)) + +(defmacro --reduce-from (form initial-value list) + "Anaphoric form of `-reduce-from'." + (declare (debug (form form form))) + `(let ((acc ,initial-value)) + (--each ,list (setq acc ,form)) + acc)) + +(defun -reduce-from (fn initial-value list) + "Return the result of applying FN to INITIAL-VALUE and the +first item in LIST, then applying FN to that result and the 2nd +item, etc. If LIST contains no items, return INITIAL-VALUE and +do not call FN. + +In the anaphoric form `--reduce-from', the accumulated value is +exposed as symbol `acc'. + +See also: `-reduce', `-reduce-r'" + (--reduce-from (funcall fn acc it) initial-value list)) + +(defmacro --reduce (form list) + "Anaphoric form of `-reduce'." + (declare (debug (form form))) + (let ((lv (make-symbol "list-value"))) + `(let ((,lv ,list)) + (if ,lv + (--reduce-from ,form (car ,lv) (cdr ,lv)) + (let (acc it) ,form))))) + +(defun -reduce (fn list) + "Return the result of applying FN to the first 2 items in LIST, +then applying FN to that result and the 3rd item, etc. If LIST +contains no items, return the result of calling FN with no +arguments. If LIST contains a single item, return that item +and do not call FN. + +In the anaphoric form `--reduce', the accumulated value is +exposed as symbol `acc'. + +See also: `-reduce-from', `-reduce-r'" + (if list + (-reduce-from fn (car list) (cdr list)) + (funcall fn))) + +(defmacro --reduce-r-from (form initial-value list) + "Anaphoric version of `-reduce-r-from'." + (declare (debug (form form form))) + `(--reduce-from ,form ,initial-value (reverse ,list))) + +(defun -reduce-r-from (fn initial-value list) + "Replace conses with FN, nil with INITIAL-VALUE and evaluate +the resulting expression. If LIST is empty, INITIAL-VALUE is +returned and FN is not called. + +Note: this function works the same as `-reduce-from' but the +operation associates from right instead of from left. + +See also: `-reduce-r', `-reduce'" + (--reduce-r-from (funcall fn it acc) initial-value list)) + +(defmacro --reduce-r (form list) + "Anaphoric version of `-reduce-r'." + (declare (debug (form form))) + `(--reduce ,form (reverse ,list))) + +(defun -reduce-r (fn list) + "Replace conses with FN and evaluate the resulting expression. +The final nil is ignored. If LIST contains no items, return the +result of calling FN with no arguments. If LIST contains a single +item, return that item and do not call FN. + +The first argument of FN is the new item, the second is the +accumulated value. + +Note: this function works the same as `-reduce' but the operation +associates from right instead of from left. + +See also: `-reduce-r-from', `-reduce'" + (if list + (--reduce-r (funcall fn it acc) list) + (funcall fn))) + +(defun -reductions-from (fn init list) + "Return a list of the intermediate values of the reduction. + +See `-reduce-from' for explanation of the arguments. + +See also: `-reductions', `-reductions-r', `-reduce-r'" + (nreverse (--reduce-from (cons (funcall fn (car acc) it) acc) (list init) list))) + +(defun -reductions (fn list) + "Return a list of the intermediate values of the reduction. + +See `-reduce' for explanation of the arguments. + +See also: `-reductions-from', `-reductions-r', `-reduce-r'" + (and list (-reductions-from fn (car list) (cdr list)))) + +(defun -reductions-r-from (fn init list) + "Return a list of the intermediate values of the reduction. + +See `-reduce-r-from' for explanation of the arguments. + +See also: `-reductions-r', `-reductions', `-reduce'" + (--reduce-r-from (cons (funcall fn it (car acc)) acc) (list init) list)) + +(defun -reductions-r (fn list) + "Return a list of the intermediate values of the reduction. + +See `-reduce-r' for explanation of the arguments. + +See also: `-reductions-r-from', `-reductions', `-reduce'" + (when list + (let ((rev (reverse list))) + (--reduce-from (cons (funcall fn it (car acc)) acc) + (list (car rev)) + (cdr rev))))) + +(defmacro --filter (form list) + "Anaphoric form of `-filter'. + +See also: `--remove'." + (declare (debug (form form))) + (let ((r (make-symbol "result"))) + `(let (,r) + (--each ,list (when ,form (!cons it ,r))) + (nreverse ,r)))) + +(defun -filter (pred list) + "Return a new list of the items in LIST for which PRED returns a non-nil value. + +Alias: `-select' + +See also: `-keep', `-remove'." + (--filter (funcall pred it) list)) + +(defalias '-select '-filter) +(defalias '--select '--filter) + +(defmacro --remove (form list) + "Anaphoric form of `-remove'. + +See also `--filter'." + (declare (debug (form form))) + `(--filter (not ,form) ,list)) + +(defun -remove (pred list) + "Return a new list of the items in LIST for which PRED returns nil. + +Alias: `-reject' + +See also: `-filter'." + (--remove (funcall pred it) list)) + +(defalias '-reject '-remove) +(defalias '--reject '--remove) + +(defun -remove-first (pred list) + "Return a new list with the first item matching PRED removed. + +Alias: `-reject-first' + +See also: `-remove', `-map-first'" + (let (front) + (while (and list (not (funcall pred (car list)))) + (push (car list) front) + (!cdr list)) + (if list + (-concat (nreverse front) (cdr list)) + (nreverse front)))) + +(defmacro --remove-first (form list) + "Anaphoric form of `-remove-first'." + (declare (debug (form form))) + `(-remove-first (lambda (it) ,form) ,list)) + +(defalias '-reject-first '-remove-first) +(defalias '--reject-first '--remove-first) + +(defun -remove-last (pred list) + "Return a new list with the last item matching PRED removed. + +Alias: `-reject-last' + +See also: `-remove', `-map-last'" + (nreverse (-remove-first pred (reverse list)))) + +(defmacro --remove-last (form list) + "Anaphoric form of `-remove-last'." + (declare (debug (form form))) + `(-remove-last (lambda (it) ,form) ,list)) + +(defalias '-reject-last '-remove-last) +(defalias '--reject-last '--remove-last) + +(defun -remove-item (item list) + "Remove all occurences of ITEM from LIST. + +Comparison is done with `equal'." + (declare (pure t) (side-effect-free t)) + (--remove (equal it item) list)) + +(defmacro --keep (form list) + "Anaphoric form of `-keep'." + (declare (debug (form form))) + (let ((r (make-symbol "result")) + (m (make-symbol "mapped"))) + `(let (,r) + (--each ,list (let ((,m ,form)) (when ,m (!cons ,m ,r)))) + (nreverse ,r)))) + +(defun -keep (fn list) + "Return a new list of the non-nil results of applying FN to the items in LIST. + +If you want to select the original items satisfying a predicate use `-filter'." + (--keep (funcall fn it) list)) + +(defun -non-nil (list) + "Return all non-nil elements of LIST." + (declare (pure t) (side-effect-free t)) + (-remove 'null list)) + +(defmacro --map-indexed (form list) + "Anaphoric form of `-map-indexed'." + (declare (debug (form form))) + (let ((r (make-symbol "result"))) + `(let (,r) + (--each ,list + (!cons ,form ,r)) + (nreverse ,r)))) + +(defun -map-indexed (fn list) + "Return a new list consisting of the result of (FN index item) for each item in LIST. + +In the anaphoric form `--map-indexed', the index is exposed as symbol `it-index'. + +See also: `-each-indexed'." + (--map-indexed (funcall fn it-index it) list)) + +(defmacro --map-when (pred rep list) + "Anaphoric form of `-map-when'." + (declare (debug (form form form))) + (let ((r (make-symbol "result"))) + `(let (,r) + (--each ,list (!cons (if ,pred ,rep it) ,r)) + (nreverse ,r)))) + +(defun -map-when (pred rep list) + "Return a new list where the elements in LIST that do not match the PRED function +are unchanged, and where the elements in LIST that do match the PRED function are mapped +through the REP function. + +Alias: `-replace-where' + +See also: `-update-at'" + (--map-when (funcall pred it) (funcall rep it) list)) + +(defalias '-replace-where '-map-when) +(defalias '--replace-where '--map-when) + +(defun -map-first (pred rep list) + "Replace first item in LIST satisfying PRED with result of REP called on this item. + +See also: `-map-when', `-replace-first'" + (let (front) + (while (and list (not (funcall pred (car list)))) + (push (car list) front) + (!cdr list)) + (if list + (-concat (nreverse front) (cons (funcall rep (car list)) (cdr list))) + (nreverse front)))) + +(defmacro --map-first (pred rep list) + "Anaphoric form of `-map-first'." + `(-map-first (lambda (it) ,pred) (lambda (it) (ignore it) ,rep) ,list)) + +(defun -map-last (pred rep list) + "Replace last item in LIST satisfying PRED with result of REP called on this item. + +See also: `-map-when', `-replace-last'" + (nreverse (-map-first pred rep (reverse list)))) + +(defmacro --map-last (pred rep list) + "Anaphoric form of `-map-last'." + `(-map-last (lambda (it) ,pred) (lambda (it) (ignore it) ,rep) ,list)) + +(defun -replace (old new list) + "Replace all OLD items in LIST with NEW. + +Elements are compared using `equal'. + +See also: `-replace-at'" + (declare (pure t) (side-effect-free t)) + (--map-when (equal it old) new list)) + +(defun -replace-first (old new list) + "Replace the first occurence of OLD with NEW in LIST. + +Elements are compared using `equal'. + +See also: `-map-first'" + (declare (pure t) (side-effect-free t)) + (--map-first (equal old it) new list)) + +(defun -replace-last (old new list) + "Replace the last occurence of OLD with NEW in LIST. + +Elements are compared using `equal'. + +See also: `-map-last'" + (declare (pure t) (side-effect-free t)) + (--map-last (equal old it) new list)) + +(defmacro --mapcat (form list) + "Anaphoric form of `-mapcat'." + (declare (debug (form form))) + `(apply 'append (--map ,form ,list))) + +(defun -mapcat (fn list) + "Return the concatenation of the result of mapping FN over LIST. +Thus function FN should return a list." + (--mapcat (funcall fn it) list)) + +(defun -flatten (l) + "Take a nested list L and return its contents as a single, flat list. + +Note that because `nil' represents a list of zero elements (an +empty list), any mention of nil in L will disappear after +flattening. If you need to preserve nils, consider `-flatten-n' +or map them to some unique symbol and then map them back. + +Conses of two atoms are considered \"terminals\", that is, they +aren't flattened further. + +See also: `-flatten-n'" + (declare (pure t) (side-effect-free t)) + (if (and (listp l) (listp (cdr l))) + (-mapcat '-flatten l) + (list l))) + +(defmacro --iterate (form init n) + "Anaphoric version of `-iterate'." + (declare (debug (form form form))) + `(-iterate (lambda (it) ,form) ,init ,n)) + +(defun -flatten-n (num list) + "Flatten NUM levels of a nested LIST. + +See also: `-flatten'" + (declare (pure t) (side-effect-free t)) + (-last-item (--iterate (--mapcat (-list it) it) list (1+ num)))) + +(defun -concat (&rest lists) + "Return a new list with the concatenation of the elements in the supplied LISTS." + (declare (pure t) (side-effect-free t)) + (apply 'append lists)) + +(defalias '-copy 'copy-sequence + "Create a shallow copy of LIST. + +\(fn LIST)") + +(defun -splice (pred fun list) + "Splice lists generated by FUN in place of elements matching PRED in LIST. + +FUN takes the element matching PRED as input. + +This function can be used as replacement for `,@' in case you +need to splice several lists at marked positions (for example +with keywords). + +See also: `-splice-list', `-insert-at'" + (let (r) + (--each list + (if (funcall pred it) + (let ((new (funcall fun it))) + (--each new (!cons it r))) + (!cons it r))) + (nreverse r))) + +(defmacro --splice (pred form list) + "Anaphoric form of `-splice'." + `(-splice (lambda (it) ,pred) (lambda (it) ,form) ,list)) + +(defun -splice-list (pred new-list list) + "Splice NEW-LIST in place of elements matching PRED in LIST. + +See also: `-splice', `-insert-at'" + (-splice pred (lambda (_) new-list) list)) + +(defmacro --splice-list (pred new-list list) + "Anaphoric form of `-splice-list'." + `(-splice-list (lambda (it) ,pred) ,new-list ,list)) + +(defun -cons* (&rest args) + "Make a new list from the elements of ARGS. + +The last 2 members of ARGS are used as the final cons of the +result so if the final member of ARGS is not a list the result is +a dotted list." + (declare (pure t) (side-effect-free t)) + (-reduce-r 'cons args)) + +(defun -snoc (list elem &rest elements) + "Append ELEM to the end of the list. + +This is like `cons', but operates on the end of list. + +If ELEMENTS is non nil, append these to the list as well." + (-concat list (list elem) elements)) + +(defmacro --first (form list) + "Anaphoric form of `-first'." + (declare (debug (form form))) + (let ((n (make-symbol "needle"))) + `(let (,n) + (--each-while ,list (not ,n) + (when ,form (setq ,n it))) + ,n))) + +(defun -first (pred list) + "Return the first x in LIST where (PRED x) is non-nil, else nil. + +To get the first item in the list no questions asked, use `car'. + +Alias: `-find'" + (--first (funcall pred it) list)) + +(defalias '-find '-first) +(defalias '--find '--first) + +(defmacro --some (form list) + "Anaphoric form of `-some'." + (declare (debug (form form))) + (let ((n (make-symbol "needle"))) + `(let (,n) + (--each-while ,list (not ,n) + (setq ,n ,form)) + ,n))) + +(defun -some (pred list) + "Return (PRED x) for the first LIST item where (PRED x) is non-nil, else nil. + +Alias: `-any'" + (--some (funcall pred it) list)) + +(defalias '-any '-some) +(defalias '--any '--some) + +(defmacro --last (form list) + "Anaphoric form of `-last'." + (declare (debug (form form))) + (let ((n (make-symbol "needle"))) + `(let (,n) + (--each ,list + (when ,form (setq ,n it))) + ,n))) + +(defun -last (pred list) + "Return the last x in LIST where (PRED x) is non-nil, else nil." + (--last (funcall pred it) list)) + +(defalias '-first-item 'car + "Return the first item of LIST, or nil on an empty list. + +See also: `-second-item', `-last-item'. + +\(fn LIST)") + +;; Ensure that calls to `-first-item' are compiled to a single opcode, +;; just like `car'. +(put '-first-item 'byte-opcode 'byte-car) +(put '-first-item 'byte-compile 'byte-compile-one-arg) + +(defalias '-second-item 'cadr + "Return the second item of LIST, or nil if LIST is too short. + +See also: `-third-item'. + +\(fn LIST)") + +(defalias '-third-item 'caddr + "Return the third item of LIST, or nil if LIST is too short. + +See also: `-fourth-item'. + +\(fn LIST)") + +(defun -fourth-item (list) + "Return the fourth item of LIST, or nil if LIST is too short. + +See also: `-fifth-item'." + (declare (pure t) (side-effect-free t)) + (car (cdr (cdr (cdr list))))) + +(defun -fifth-item (list) + "Return the fifth item of LIST, or nil if LIST is too short. + +See also: `-last-item'." + (declare (pure t) (side-effect-free t)) + (car (cdr (cdr (cdr (cdr list)))))) + +;; TODO: gv was introduced in 24.3, so we can remove the if statement +;; when support for earlier versions is dropped +(eval-when-compile + (require 'cl) + (if (fboundp 'gv-define-simple-setter) + (gv-define-simple-setter -first-item setcar) + (require 'cl) + (with-no-warnings + (defsetf -first-item (x) (val) `(setcar ,x ,val))))) + +(defun -last-item (list) + "Return the last item of LIST, or nil on an empty list." + (declare (pure t) (side-effect-free t)) + (car (last list))) + +;; TODO: gv was introduced in 24.3, so we can remove the if statement +;; when support for earlier versions is dropped +(eval-when-compile + (if (fboundp 'gv-define-setter) + (gv-define-setter -last-item (val x) `(setcar (last ,x) ,val)) + (with-no-warnings + (defsetf -last-item (x) (val) `(setcar (last ,x) ,val))))) + +(defun -butlast (list) + "Return a list of all items in list except for the last." + ;; no alias as we don't want magic optional argument + (declare (pure t) (side-effect-free t)) + (butlast list)) + +(defmacro --count (pred list) + "Anaphoric form of `-count'." + (declare (debug (form form))) + (let ((r (make-symbol "result"))) + `(let ((,r 0)) + (--each ,list (when ,pred (setq ,r (1+ ,r)))) + ,r))) + +(defun -count (pred list) + "Counts the number of items in LIST where (PRED item) is non-nil." + (--count (funcall pred it) list)) + +(defun ---truthy? (val) + (declare (pure t) (side-effect-free t)) + (not (null val))) + +(defmacro --any? (form list) + "Anaphoric form of `-any?'." + (declare (debug (form form))) + `(---truthy? (--some ,form ,list))) + +(defun -any? (pred list) + "Return t if (PRED x) is non-nil for any x in LIST, else nil. + +Alias: `-any-p', `-some?', `-some-p'" + (--any? (funcall pred it) list)) + +(defalias '-some? '-any?) +(defalias '--some? '--any?) +(defalias '-any-p '-any?) +(defalias '--any-p '--any?) +(defalias '-some-p '-any?) +(defalias '--some-p '--any?) + +(defmacro --all? (form list) + "Anaphoric form of `-all?'." + (declare (debug (form form))) + (let ((a (make-symbol "all"))) + `(let ((,a t)) + (--each-while ,list ,a (setq ,a ,form)) + (---truthy? ,a)))) + +(defun -all? (pred list) + "Return t if (PRED x) is non-nil for all x in LIST, else nil. + +Alias: `-all-p', `-every?', `-every-p'" + (--all? (funcall pred it) list)) + +(defalias '-every? '-all?) +(defalias '--every? '--all?) +(defalias '-all-p '-all?) +(defalias '--all-p '--all?) +(defalias '-every-p '-all?) +(defalias '--every-p '--all?) + +(defmacro --none? (form list) + "Anaphoric form of `-none?'." + (declare (debug (form form))) + `(--all? (not ,form) ,list)) + +(defun -none? (pred list) + "Return t if (PRED x) is nil for all x in LIST, else nil. + +Alias: `-none-p'" + (--none? (funcall pred it) list)) + +(defalias '-none-p '-none?) +(defalias '--none-p '--none?) + +(defmacro --only-some? (form list) + "Anaphoric form of `-only-some?'." + (declare (debug (form form))) + (let ((y (make-symbol "yes")) + (n (make-symbol "no"))) + `(let (,y ,n) + (--each-while ,list (not (and ,y ,n)) + (if ,form (setq ,y t) (setq ,n t))) + (---truthy? (and ,y ,n))))) + +(defun -only-some? (pred list) + "Return `t` if at least one item of LIST matches PRED and at least one item of LIST does not match PRED. +Return `nil` both if all items match the predicate or if none of the items match the predicate. + +Alias: `-only-some-p'" + (--only-some? (funcall pred it) list)) + +(defalias '-only-some-p '-only-some?) +(defalias '--only-some-p '--only-some?) + +(defun -slice (list from &optional to step) + "Return copy of LIST, starting from index FROM to index TO. + +FROM or TO may be negative. These values are then interpreted +modulo the length of the list. + +If STEP is a number, only each STEPth item in the resulting +section is returned. Defaults to 1." + (declare (pure t) (side-effect-free t)) + (let ((length (length list)) + (new-list nil)) + ;; to defaults to the end of the list + (setq to (or to length)) + (setq step (or step 1)) + ;; handle negative indices + (when (< from 0) + (setq from (mod from length))) + (when (< to 0) + (setq to (mod to length))) + + ;; iterate through the list, keeping the elements we want + (--each-while list (< it-index to) + (when (and (>= it-index from) + (= (mod (- from it-index) step) 0)) + (push it new-list))) + (nreverse new-list))) + +(defun -take (n list) + "Return a new list of the first N items in LIST, or all items if there are fewer than N. + +See also: `-take-last'" + (declare (pure t) (side-effect-free t)) + (let (result) + (--dotimes n + (when list + (!cons (car list) result) + (!cdr list))) + (nreverse result))) + +(defun -take-last (n list) + "Return the last N items of LIST in order. + +See also: `-take'" + (declare (pure t) (side-effect-free t)) + (copy-sequence (last list n))) + +(defalias '-drop 'nthcdr + "Return the tail of LIST without the first N items. + +See also: `-drop-last' + +\(fn N LIST)") + +(defun -drop-last (n list) + "Remove the last N items of LIST and return a copy. + +See also: `-drop'" + ;; No alias because we don't want magic optional argument + (declare (pure t) (side-effect-free t)) + (butlast list n)) + +(defmacro --take-while (form list) + "Anaphoric form of `-take-while'." + (declare (debug (form form))) + (let ((r (make-symbol "result"))) + `(let (,r) + (--each-while ,list ,form (!cons it ,r)) + (nreverse ,r)))) + +(defun -take-while (pred list) + "Return a new list of successive items from LIST while (PRED item) returns a non-nil value." + (--take-while (funcall pred it) list)) + +(defmacro --drop-while (form list) + "Anaphoric form of `-drop-while'." + (declare (debug (form form))) + (let ((l (make-symbol "list"))) + `(let ((,l ,list)) + (while (and ,l (let ((it (car ,l))) ,form)) + (!cdr ,l)) + ,l))) + +(defun -drop-while (pred list) + "Return the tail of LIST starting from the first item for which (PRED item) returns nil." + (--drop-while (funcall pred it) list)) + +(defun -split-at (n list) + "Return a list of ((-take N LIST) (-drop N LIST)), in no more than one pass through the list." + (declare (pure t) (side-effect-free t)) + (let (result) + (--dotimes n + (when list + (!cons (car list) result) + (!cdr list))) + (list (nreverse result) list))) + +(defun -rotate (n list) + "Rotate LIST N places to the right. With N negative, rotate to the left. +The time complexity is O(n)." + (declare (pure t) (side-effect-free t)) + (if (> n 0) + (append (last list n) (butlast list n)) + (append (-drop (- n) list) (-take (- n) list)))) + +(defun -insert-at (n x list) + "Return a list with X inserted into LIST at position N. + +See also: `-splice', `-splice-list'" + (declare (pure t) (side-effect-free t)) + (let ((split-list (-split-at n list))) + (nconc (car split-list) (cons x (cadr split-list))))) + +(defun -replace-at (n x list) + "Return a list with element at Nth position in LIST replaced with X. + +See also: `-replace'" + (declare (pure t) (side-effect-free t)) + (let ((split-list (-split-at n list))) + (nconc (car split-list) (cons x (cdr (cadr split-list)))))) + +(defun -update-at (n func list) + "Return a list with element at Nth position in LIST replaced with `(func (nth n list))`. + +See also: `-map-when'" + (let ((split-list (-split-at n list))) + (nconc (car split-list) (cons (funcall func (car (cadr split-list))) (cdr (cadr split-list)))))) + +(defmacro --update-at (n form list) + "Anaphoric version of `-update-at'." + (declare (debug (form form form))) + `(-update-at ,n (lambda (it) ,form) ,list)) + +(defun -remove-at (n list) + "Return a list with element at Nth position in LIST removed. + +See also: `-remove-at-indices', `-remove'" + (declare (pure t) (side-effect-free t)) + (-remove-at-indices (list n) list)) + +(defun -remove-at-indices (indices list) + "Return a list whose elements are elements from LIST without +elements selected as `(nth i list)` for all i +from INDICES. + +See also: `-remove-at', `-remove'" + (declare (pure t) (side-effect-free t)) + (let* ((indices (-sort '< indices)) + (diffs (cons (car indices) (-map '1- (-zip-with '- (cdr indices) indices)))) + r) + (--each diffs + (let ((split (-split-at it list))) + (!cons (car split) r) + (setq list (cdr (cadr split))))) + (!cons list r) + (apply '-concat (nreverse r)))) + +(defmacro --split-with (pred list) + "Anaphoric form of `-split-with'." + (declare (debug (form form))) + (let ((l (make-symbol "list")) + (r (make-symbol "result")) + (c (make-symbol "continue"))) + `(let ((,l ,list) + (,r nil) + (,c t)) + (while (and ,l ,c) + (let ((it (car ,l))) + (if (not ,pred) + (setq ,c nil) + (!cons it ,r) + (!cdr ,l)))) + (list (nreverse ,r) ,l)))) + +(defun -split-with (pred list) + "Return a list of ((-take-while PRED LIST) (-drop-while PRED LIST)), in no more than one pass through the list." + (--split-with (funcall pred it) list)) + +(defmacro -split-on (item list) + "Split the LIST each time ITEM is found. + +Unlike `-partition-by', the ITEM is discarded from the results. +Empty lists are also removed from the result. + +Comparison is done by `equal'. + +See also `-split-when'" + (declare (debug (form form))) + `(-split-when (lambda (it) (equal it ,item)) ,list)) + +(defmacro --split-when (form list) + "Anaphoric version of `-split-when'." + (declare (debug (form form))) + `(-split-when (lambda (it) ,form) ,list)) + +(defun -split-when (fn list) + "Split the LIST on each element where FN returns non-nil. + +Unlike `-partition-by', the \"matched\" element is discarded from +the results. Empty lists are also removed from the result. + +This function can be thought of as a generalization of +`split-string'." + (let (r s) + (while list + (if (not (funcall fn (car list))) + (push (car list) s) + (when s (push (nreverse s) r)) + (setq s nil)) + (!cdr list)) + (when s (push (nreverse s) r)) + (nreverse r))) + +(defmacro --separate (form list) + "Anaphoric form of `-separate'." + (declare (debug (form form))) + (let ((y (make-symbol "yes")) + (n (make-symbol "no"))) + `(let (,y ,n) + (--each ,list (if ,form (!cons it ,y) (!cons it ,n))) + (list (nreverse ,y) (nreverse ,n))))) + +(defun -separate (pred list) + "Return a list of ((-filter PRED LIST) (-remove PRED LIST)), in one pass through the list." + (--separate (funcall pred it) list)) + +(defun ---partition-all-in-steps-reversed (n step list) + "Private: Used by -partition-all-in-steps and -partition-in-steps." + (when (< step 1) + (error "Step must be a positive number, or you're looking at some juicy infinite loops.")) + (let ((result nil)) + (while list + (!cons (-take n list) result) + (setq list (-drop step list))) + result)) + +(defun -partition-all-in-steps (n step list) + "Return a new list with the items in LIST grouped into N-sized sublists at offsets STEP apart. +The last groups may contain less than N items." + (declare (pure t) (side-effect-free t)) + (nreverse (---partition-all-in-steps-reversed n step list))) + +(defun -partition-in-steps (n step list) + "Return a new list with the items in LIST grouped into N-sized sublists at offsets STEP apart. +If there are not enough items to make the last group N-sized, +those items are discarded." + (declare (pure t) (side-effect-free t)) + (let ((result (---partition-all-in-steps-reversed n step list))) + (while (and result (< (length (car result)) n)) + (!cdr result)) + (nreverse result))) + +(defun -partition-all (n list) + "Return a new list with the items in LIST grouped into N-sized sublists. +The last group may contain less than N items." + (declare (pure t) (side-effect-free t)) + (-partition-all-in-steps n n list)) + +(defun -partition (n list) + "Return a new list with the items in LIST grouped into N-sized sublists. +If there are not enough items to make the last group N-sized, +those items are discarded." + (declare (pure t) (side-effect-free t)) + (-partition-in-steps n n list)) + +(defmacro --partition-by (form list) + "Anaphoric form of `-partition-by'." + (declare (debug (form form))) + (let ((r (make-symbol "result")) + (s (make-symbol "sublist")) + (v (make-symbol "value")) + (n (make-symbol "new-value")) + (l (make-symbol "list"))) + `(let ((,l ,list)) + (when ,l + (let* ((,r nil) + (it (car ,l)) + (,s (list it)) + (,v ,form) + (,l (cdr ,l))) + (while ,l + (let* ((it (car ,l)) + (,n ,form)) + (unless (equal ,v ,n) + (!cons (nreverse ,s) ,r) + (setq ,s nil) + (setq ,v ,n)) + (!cons it ,s) + (!cdr ,l))) + (!cons (nreverse ,s) ,r) + (nreverse ,r)))))) + +(defun -partition-by (fn list) + "Apply FN to each item in LIST, splitting it each time FN returns a new value." + (--partition-by (funcall fn it) list)) + +(defmacro --partition-by-header (form list) + "Anaphoric form of `-partition-by-header'." + (declare (debug (form form))) + (let ((r (make-symbol "result")) + (s (make-symbol "sublist")) + (h (make-symbol "header-value")) + (b (make-symbol "seen-body?")) + (n (make-symbol "new-value")) + (l (make-symbol "list"))) + `(let ((,l ,list)) + (when ,l + (let* ((,r nil) + (it (car ,l)) + (,s (list it)) + (,h ,form) + (,b nil) + (,l (cdr ,l))) + (while ,l + (let* ((it (car ,l)) + (,n ,form)) + (if (equal ,h ,n) + (when ,b + (!cons (nreverse ,s) ,r) + (setq ,s nil) + (setq ,b nil)) + (setq ,b t)) + (!cons it ,s) + (!cdr ,l))) + (!cons (nreverse ,s) ,r) + (nreverse ,r)))))) + +(defun -partition-by-header (fn list) + "Apply FN to the first item in LIST. That is the header +value. Apply FN to each item in LIST, splitting it each time FN +returns the header value, but only after seeing at least one +other value (the body)." + (--partition-by-header (funcall fn it) list)) + +(defun -partition-after-pred (pred list) + "Partition directly after each time PRED is true on an element of LIST." + (when list + (let ((rest (-partition-after-pred pred + (cdr list)))) + (if (funcall pred (car list)) + ;;split after (car list) + (cons (list (car list)) + rest) + + ;;don't split after (car list) + (cons (cons (car list) + (car rest)) + (cdr rest)))))) + +(defun -partition-before-pred (pred list) + "Partition directly before each time PRED is true on an element of LIST." + (nreverse (-map #'reverse + (-partition-after-pred pred (reverse list))))) + +(defun -partition-after-item (item list) + "Partition directly after each time ITEM appears in LIST." + (-partition-after-pred (lambda (ele) (equal ele item)) + list)) + +(defun -partition-before-item (item list) + "Partition directly before each time ITEM appears in LIST." + (-partition-before-pred (lambda (ele) (equal ele item)) + list)) + +(defmacro --group-by (form list) + "Anaphoric form of `-group-by'." + (declare (debug t)) + (let ((n (make-symbol "n")) + (k (make-symbol "k")) + (grp (make-symbol "grp"))) + `(nreverse + (-map + (lambda (,n) + (cons (car ,n) + (nreverse (cdr ,n)))) + (--reduce-from + (let* ((,k (,@form)) + (,grp (assoc ,k acc))) + (if ,grp + (setcdr ,grp (cons it (cdr ,grp))) + (push + (list ,k it) + acc)) + acc) + nil ,list))))) + +(defun -group-by (fn list) + "Separate LIST into an alist whose keys are FN applied to the +elements of LIST. Keys are compared by `equal'." + (--group-by (funcall fn it) list)) + +(defun -interpose (sep list) + "Return a new list of all elements in LIST separated by SEP." + (declare (pure t) (side-effect-free t)) + (let (result) + (when list + (!cons (car list) result) + (!cdr list)) + (while list + (setq result (cons (car list) (cons sep result))) + (!cdr list)) + (nreverse result))) + +(defun -interleave (&rest lists) + "Return a new list of the first item in each list, then the second etc." + (declare (pure t) (side-effect-free t)) + (when lists + (let (result) + (while (-none? 'null lists) + (--each lists (!cons (car it) result)) + (setq lists (-map 'cdr lists))) + (nreverse result)))) + +(defmacro --zip-with (form list1 list2) + "Anaphoric form of `-zip-with'. + +The elements in list1 are bound as symbol `it', the elements in list2 as symbol `other'." + (declare (debug (form form form))) + (let ((r (make-symbol "result")) + (l1 (make-symbol "list1")) + (l2 (make-symbol "list2"))) + `(let ((,r nil) + (,l1 ,list1) + (,l2 ,list2)) + (while (and ,l1 ,l2) + (let ((it (car ,l1)) + (other (car ,l2))) + (!cons ,form ,r) + (!cdr ,l1) + (!cdr ,l2))) + (nreverse ,r)))) + +(defun -zip-with (fn list1 list2) + "Zip the two lists LIST1 and LIST2 using a function FN. This +function is applied pairwise taking as first argument element of +LIST1 and as second argument element of LIST2 at corresponding +position. + +The anaphoric form `--zip-with' binds the elements from LIST1 as symbol `it', +and the elements from LIST2 as symbol `other'." + (--zip-with (funcall fn it other) list1 list2)) + +(defun -zip (&rest lists) + "Zip LISTS together. Group the head of each list, followed by the +second elements of each list, and so on. The lengths of the returned +groupings are equal to the length of the shortest input list. + +If two lists are provided as arguments, return the groupings as a list +of cons cells. Otherwise, return the groupings as a list of lists. + +Please note! This distinction is being removed in an upcoming 3.0 +release of Dash. If you rely on this behavior, use -zip-pair instead." + (declare (pure t) (side-effect-free t)) + (when lists + (let (results) + (while (-none? 'null lists) + (setq results (cons (mapcar 'car lists) results)) + (setq lists (mapcar 'cdr lists))) + (setq results (nreverse results)) + (if (= (length lists) 2) + ;; to support backward compatability, return + ;; a cons cell if two lists were provided + (--map (cons (car it) (cadr it)) results) + results)))) + +(defalias '-zip-pair '-zip) + +(defun -zip-fill (fill-value &rest lists) + "Zip LISTS, with FILL-VALUE padded onto the shorter lists. The +lengths of the returned groupings are equal to the length of the +longest input list." + (declare (pure t) (side-effect-free t)) + (apply '-zip (apply '-pad (cons fill-value lists)))) + +(defun -unzip (lists) + "Unzip LISTS. + +This works just like `-zip' but takes a list of lists instead of +a variable number of arguments, such that + + (-unzip (-zip L1 L2 L3 ...)) + +is identity (given that the lists are the same length). + +See also: `-zip'" + (apply '-zip lists)) + +(defun -cycle (list) + "Return an infinite copy of LIST that will cycle through the +elements and repeat from the beginning." + (declare (pure t) (side-effect-free t)) + (let ((newlist (-map 'identity list))) + (nconc newlist newlist))) + +(defun -pad (fill-value &rest lists) + "Appends FILL-VALUE to the end of each list in LISTS such that they +will all have the same length." + (let* ((annotations (-annotate 'length lists)) + (n (-max (-map 'car annotations)))) + (--map (append (cdr it) (-repeat (- n (car it)) fill-value)) annotations))) + +(defun -annotate (fn list) + "Return a list of cons cells where each cell is FN applied to each +element of LIST paired with the unmodified element of LIST." + (-zip (-map fn list) list)) + +(defmacro --annotate (form list) + "Anaphoric version of `-annotate'." + (declare (debug (form form))) + `(-annotate (lambda (it) ,form) ,list)) + +(defun dash--table-carry (lists restore-lists &optional re) + "Helper for `-table' and `-table-flat'. + +If a list overflows, carry to the right and reset the list." + (while (not (or (car lists) + (equal lists '(nil)))) + (setcar lists (car restore-lists)) + (pop (cadr lists)) + (!cdr lists) + (!cdr restore-lists) + (when re + (push (nreverse (car re)) (cadr re)) + (setcar re nil) + (!cdr re)))) + +(defun -table (fn &rest lists) + "Compute outer product of LISTS using function FN. + +The function FN should have the same arity as the number of +supplied lists. + +The outer product is computed by applying fn to all possible +combinations created by taking one element from each list in +order. The dimension of the result is (length lists). + +See also: `-table-flat'" + (let ((restore-lists (copy-sequence lists)) + (last-list (last lists)) + (re (make-list (length lists) nil))) + (while (car last-list) + (let ((item (apply fn (-map 'car lists)))) + (push item (car re)) + (setcar lists (cdar lists)) ;; silence byte compiler + (dash--table-carry lists restore-lists re))) + (nreverse (car (last re))))) + +(defun -table-flat (fn &rest lists) + "Compute flat outer product of LISTS using function FN. + +The function FN should have the same arity as the number of +supplied lists. + +The outer product is computed by applying fn to all possible +combinations created by taking one element from each list in +order. The results are flattened, ignoring the tensor structure +of the result. This is equivalent to calling: + + (-flatten-n (1- (length lists)) (apply \\='-table fn lists)) + +but the implementation here is much more efficient. + +See also: `-flatten-n', `-table'" + (let ((restore-lists (copy-sequence lists)) + (last-list (last lists)) + re) + (while (car last-list) + (let ((item (apply fn (-map 'car lists)))) + (push item re) + (setcar lists (cdar lists)) ;; silence byte compiler + (dash--table-carry lists restore-lists))) + (nreverse re))) + +(defun -partial (fn &rest args) + "Take a function FN and fewer than the normal arguments to FN, +and return a fn that takes a variable number of additional ARGS. +When called, the returned function calls FN with ARGS first and +then additional args." + (apply 'apply-partially fn args)) + +(defun -elem-index (elem list) + "Return the index of the first element in the given LIST which +is equal to the query element ELEM, or nil if there is no +such element." + (declare (pure t) (side-effect-free t)) + (car (-elem-indices elem list))) + +(defun -elem-indices (elem list) + "Return the indices of all elements in LIST equal to the query +element ELEM, in ascending order." + (declare (pure t) (side-effect-free t)) + (-find-indices (-partial 'equal elem) list)) + +(defun -find-indices (pred list) + "Return the indices of all elements in LIST satisfying the +predicate PRED, in ascending order." + (apply 'append (--map-indexed (when (funcall pred it) (list it-index)) list))) + +(defmacro --find-indices (form list) + "Anaphoric version of `-find-indices'." + (declare (debug (form form))) + `(-find-indices (lambda (it) ,form) ,list)) + +(defun -find-index (pred list) + "Take a predicate PRED and a LIST and return the index of the +first element in the list satisfying the predicate, or nil if +there is no such element. + +See also `-first'." + (car (-find-indices pred list))) + +(defmacro --find-index (form list) + "Anaphoric version of `-find-index'." + (declare (debug (form form))) + `(-find-index (lambda (it) ,form) ,list)) + +(defun -find-last-index (pred list) + "Take a predicate PRED and a LIST and return the index of the +last element in the list satisfying the predicate, or nil if +there is no such element. + +See also `-last'." + (-last-item (-find-indices pred list))) + +(defmacro --find-last-index (form list) + "Anaphoric version of `-find-last-index'." + `(-find-last-index (lambda (it) ,form) ,list)) + +(defun -select-by-indices (indices list) + "Return a list whose elements are elements from LIST selected +as `(nth i list)` for all i from INDICES." + (declare (pure t) (side-effect-free t)) + (let (r) + (--each indices + (!cons (nth it list) r)) + (nreverse r))) + +(defun -select-columns (columns table) + "Select COLUMNS from TABLE. + +TABLE is a list of lists where each element represents one row. +It is assumed each row has the same length. + +Each row is transformed such that only the specified COLUMNS are +selected. + +See also: `-select-column', `-select-by-indices'" + (declare (pure t) (side-effect-free t)) + (--map (-select-by-indices columns it) table)) + +(defun -select-column (column table) + "Select COLUMN from TABLE. + +TABLE is a list of lists where each element represents one row. +It is assumed each row has the same length. + +The single selected column is returned as a list. + +See also: `-select-columns', `-select-by-indices'" + (declare (pure t) (side-effect-free t)) + (--mapcat (-select-by-indices (list column) it) table)) + +(defmacro -> (x &optional form &rest more) + "Thread the expr through the forms. Insert X as the second item +in the first form, making a list of it if it is not a list +already. If there are more forms, insert the first form as the +second item in second form, etc." + (declare (debug (form &rest [&or symbolp (sexp &rest form)]))) + (cond + ((null form) x) + ((null more) (if (listp form) + `(,(car form) ,x ,@(cdr form)) + (list form x))) + (:else `(-> (-> ,x ,form) ,@more)))) + +(defmacro ->> (x &optional form &rest more) + "Thread the expr through the forms. Insert X as the last item +in the first form, making a list of it if it is not a list +already. If there are more forms, insert the first form as the +last item in second form, etc." + (declare (debug ->)) + (cond + ((null form) x) + ((null more) (if (listp form) + `(,@form ,x) + (list form x))) + (:else `(->> (->> ,x ,form) ,@more)))) + +(defmacro --> (x &rest forms) + "Starting with the value of X, thread each expression through FORMS. + +Insert X at the position signified by the symbol `it' in the first +form. If there are more forms, insert the first form at the position +signified by `it' in in second form, etc." + (declare (debug (form body))) + `(-as-> ,x it ,@forms)) + +(defmacro -as-> (value variable &rest forms) + "Starting with VALUE, thread VARIABLE through FORMS. + +In the first form, bind VARIABLE to VALUE. In the second form, bind +VARIABLE to the result of the first form, and so forth." + (declare (debug (form symbolp body))) + (if (null forms) + `,value + `(let ((,variable ,value)) + (-as-> ,(if (symbolp (car forms)) + (list (car forms) variable) + (car forms)) + ,variable + ,@(cdr forms))))) + +(defmacro -some-> (x &optional form &rest more) + "When expr is non-nil, thread it through the first form (via `->'), +and when that result is non-nil, through the next form, etc." + (declare (debug ->)) + (if (null form) x + (let ((result (make-symbol "result"))) + `(-some-> (-when-let (,result ,x) + (-> ,result ,form)) + ,@more)))) + +(defmacro -some->> (x &optional form &rest more) + "When expr is non-nil, thread it through the first form (via `->>'), +and when that result is non-nil, through the next form, etc." + (declare (debug ->)) + (if (null form) x + (let ((result (make-symbol "result"))) + `(-some->> (-when-let (,result ,x) + (->> ,result ,form)) + ,@more)))) + +(defmacro -some--> (x &optional form &rest more) + "When expr in non-nil, thread it through the first form (via `-->'), +and when that result is non-nil, through the next form, etc." + (declare (debug ->)) + (if (null form) x + (let ((result (make-symbol "result"))) + `(-some--> (-when-let (,result ,x) + (--> ,result ,form)) + ,@more)))) + +(defun -grade-up (comparator list) + "Grade elements of LIST using COMPARATOR relation, yielding a +permutation vector such that applying this permutation to LIST +sorts it in ascending order." + ;; ugly hack to "fix" lack of lexical scope + (let ((comp `(lambda (it other) (funcall ',comparator (car it) (car other))))) + (->> (--map-indexed (cons it it-index) list) + (-sort comp) + (-map 'cdr)))) + +(defun -grade-down (comparator list) + "Grade elements of LIST using COMPARATOR relation, yielding a +permutation vector such that applying this permutation to LIST +sorts it in descending order." + ;; ugly hack to "fix" lack of lexical scope + (let ((comp `(lambda (it other) (funcall ',comparator (car other) (car it))))) + (->> (--map-indexed (cons it it-index) list) + (-sort comp) + (-map 'cdr)))) + +(defvar dash--source-counter 0 + "Monotonic counter for generated symbols.") + +(defun dash--match-make-source-symbol () + "Generate a new dash-source symbol. + +All returned symbols are guaranteed to be unique." + (prog1 (make-symbol (format "--dash-source-%d--" dash--source-counter)) + (setq dash--source-counter (1+ dash--source-counter)))) + +(defun dash--match-ignore-place-p (symbol) + "Return non-nil if SYMBOL is a symbol and starts with _." + (and (symbolp symbol) + (eq (aref (symbol-name symbol) 0) ?_))) + +(defun dash--match-cons-skip-cdr (skip-cdr source) + "Helper function generating idiomatic shifting code." + (cond + ((= skip-cdr 0) + `(pop ,source)) + (t + `(prog1 ,(dash--match-cons-get-car skip-cdr source) + (setq ,source ,(dash--match-cons-get-cdr (1+ skip-cdr) source)))))) + +(defun dash--match-cons-get-car (skip-cdr source) + "Helper function generating idiomatic code to get nth car." + (cond + ((= skip-cdr 0) + `(car ,source)) + ((= skip-cdr 1) + `(cadr ,source)) + (t + `(nth ,skip-cdr ,source)))) + +(defun dash--match-cons-get-cdr (skip-cdr source) + "Helper function generating idiomatic code to get nth cdr." + (cond + ((= skip-cdr 0) + source) + ((= skip-cdr 1) + `(cdr ,source)) + (t + `(nthcdr ,skip-cdr ,source)))) + +(defun dash--match-cons (match-form source) + "Setup a cons matching environment and call the real matcher." + (let ((s (dash--match-make-source-symbol)) + (n 0) + (m match-form)) + (while (and (consp m) + (dash--match-ignore-place-p (car m))) + (setq n (1+ n)) (!cdr m)) + (cond + ;; when we only have one pattern in the list, we don't have to + ;; create a temporary binding (--dash-source--) for the source + ;; and just use the input directly + ((and (consp m) + (not (cdr m))) + (dash--match (car m) (dash--match-cons-get-car n source))) + ;; handle other special types + ((> n 0) + (dash--match m (dash--match-cons-get-cdr n source))) + ;; this is the only entry-point for dash--match-cons-1, that's + ;; why we can't simply use the above branch, it would produce + ;; infinite recursion + (t + (cons (list s source) (dash--match-cons-1 match-form s)))))) + +(defun dash--match-cons-1 (match-form source &optional props) + "Match MATCH-FORM against SOURCE. + +MATCH-FORM is a proper or improper list. Each element of +MATCH-FORM is either a symbol, which gets bound to the respective +value in source or another match form which gets destructured +recursively. + +If the cdr of last cons cell in the list is `nil', matching stops +there. + +SOURCE is a proper or improper list." + (let ((skip-cdr (or (plist-get props :skip-cdr) 0))) + (cond + ((consp match-form) + (cond + ((cdr match-form) + (cond + ((and (symbolp (car match-form)) + (memq (car match-form) '(&keys &plist &alist &hash))) + (dash--match-kv (dash--match-kv-normalize-match-form match-form) (dash--match-cons-get-cdr skip-cdr source))) + ((dash--match-ignore-place-p (car match-form)) + (dash--match-cons-1 (cdr match-form) source + (plist-put props :skip-cdr (1+ skip-cdr)))) + (t + (-concat (dash--match (car match-form) (dash--match-cons-skip-cdr skip-cdr source)) + (dash--match-cons-1 (cdr match-form) source))))) + (t ;; Last matching place, no need for shift + (dash--match (car match-form) (dash--match-cons-get-car skip-cdr source))))) + ((eq match-form nil) + nil) + (t ;; Handle improper lists. Last matching place, no need for shift + (dash--match match-form (dash--match-cons-get-cdr skip-cdr source)))))) + +(defun dash--vector-tail (seq start) + "Return the tail of SEQ starting at START." + (cond + ((vectorp seq) + (let* ((re-length (- (length seq) start)) + (re (make-vector re-length 0))) + (--dotimes re-length (aset re it (aref seq (+ it start)))) + re)) + ((stringp seq) + (substring seq start)))) + +(defun dash--match-vector (match-form source) + "Setup a vector matching environment and call the real matcher." + (let ((s (dash--match-make-source-symbol))) + (cond + ;; don't bind `s' if we only have one sub-pattern + ((= (length match-form) 1) + (dash--match (aref match-form 0) `(aref ,source 0))) + ;; if the source is a symbol, we don't need to re-bind it + ((symbolp source) + (dash--match-vector-1 match-form source)) + ;; don't bind `s' if we only have one sub-pattern which is not ignored + ((let* ((ignored-places (mapcar 'dash--match-ignore-place-p match-form)) + (ignored-places-n (length (-remove 'null ignored-places)))) + (when (= ignored-places-n (1- (length match-form))) + (let ((n (-find-index 'null ignored-places))) + (dash--match (aref match-form n) `(aref ,source ,n)))))) + (t + (cons (list s source) (dash--match-vector-1 match-form s)))))) + +(defun dash--match-vector-1 (match-form source) + "Match MATCH-FORM against SOURCE. + +MATCH-FORM is a vector. Each element of MATCH-FORM is either a +symbol, which gets bound to the respective value in source or +another match form which gets destructured recursively. + +If second-from-last place in MATCH-FORM is the symbol &rest, the +next element of the MATCH-FORM is matched against the tail of +SOURCE, starting at index of the &rest symbol. This is +conceptually the same as the (head . tail) match for improper +lists, where dot plays the role of &rest. + +SOURCE is a vector. + +If the MATCH-FORM vector is shorter than SOURCE vector, only +the (length MATCH-FORM) places are bound, the rest of the SOURCE +is discarded." + (let ((i 0) + (l (length match-form)) + (re)) + (while (< i l) + (let ((m (aref match-form i))) + (push (cond + ((and (symbolp m) + (eq m '&rest)) + (prog1 (dash--match + (aref match-form (1+ i)) + `(dash--vector-tail ,source ,i)) + (setq i l))) + ((and (symbolp m) + ;; do not match symbols starting with _ + (not (eq (aref (symbol-name m) 0) ?_))) + (list (list m `(aref ,source ,i)))) + ((not (symbolp m)) + (dash--match m `(aref ,source ,i)))) + re) + (setq i (1+ i)))) + (-flatten-n 1 (nreverse re)))) + +(defun dash--match-kv-normalize-match-form (pattern) + "Normalize kv PATTERN. + +This method normalizes PATTERN to the format expected by +`dash--match-kv'. See `-let' for the specification." + (let ((normalized (list (car pattern))) + (skip nil) + (fill-placeholder (make-symbol "--dash-fill-placeholder--"))) + (-each (apply '-zip (-pad fill-placeholder (cdr pattern) (cddr pattern))) + (lambda (pair) + (let ((current (car pair)) + (next (cdr pair))) + (if skip + (setq skip nil) + (if (or (eq fill-placeholder next) + (not (or (and (symbolp next) + (not (keywordp next)) + (not (eq next t)) + (not (eq next nil))) + (and (consp next) + (not (eq (car next) 'quote))) + (vectorp next)))) + (progn + (cond + ((keywordp current) + (push current normalized) + (push (intern (substring (symbol-name current) 1)) normalized)) + ((stringp current) + (push current normalized) + (push (intern current) normalized)) + ((and (consp current) + (eq (car current) 'quote)) + (push current normalized) + (push (cadr current) normalized)) + (t (error "-let: found key `%s' in kv destructuring but its pattern `%s' is invalid and can not be derived from the key" current next))) + (setq skip nil)) + (push current normalized) + (push next normalized) + (setq skip t)))))) + (nreverse normalized))) + +(defun dash--match-kv (match-form source) + "Setup a kv matching environment and call the real matcher. + +kv can be any key-value store, such as plist, alist or hash-table." + (let ((s (dash--match-make-source-symbol))) + (cond + ;; don't bind `s' if we only have one sub-pattern (&type key val) + ((= (length match-form) 3) + (dash--match-kv-1 (cdr match-form) source (car match-form))) + ;; if the source is a symbol, we don't need to re-bind it + ((symbolp source) + (dash--match-kv-1 (cdr match-form) source (car match-form))) + (t + (cons (list s source) (dash--match-kv-1 (cdr match-form) s (car match-form))))))) + +(defun dash--match-kv-1 (match-form source type) + "Match MATCH-FORM against SOURCE of type TYPE. + +MATCH-FORM is a proper list of the form (key1 place1 ... keyN +placeN). Each placeK is either a symbol, which gets bound to the +value of keyK retrieved from the key-value store, or another +match form which gets destructured recursively. + +SOURCE is a key-value store of type TYPE, which can be a plist, +an alist or a hash table. + +TYPE is a token specifying the type of the key-value store. +Valid values are &plist, &alist and &hash." + (-flatten-n 1 (-map + (lambda (kv) + (let* ((k (car kv)) + (v (cadr kv)) + (getter (cond + ((or (eq type '&plist) (eq type '&keys)) + `(plist-get ,source ,k)) + ((eq type '&alist) + `(cdr (assoc ,k ,source))) + ((eq type '&hash) + `(gethash ,k ,source))))) + (cond + ((symbolp v) + (list (list v getter))) + (t (dash--match v getter))))) + (-partition 2 match-form)))) + +(defun dash--match-symbol (match-form source) + "Bind a symbol. + +This works just like `let', there is no destructuring." + (list (list match-form source))) + +(defun dash--match (match-form source) + "Match MATCH-FORM against SOURCE. + +This function tests the MATCH-FORM and dispatches to specific +matchers based on the type of the expression. + +Key-value stores are disambiguated by placing a token &plist, +&alist or &hash as a first item in the MATCH-FORM." + (cond + ((symbolp match-form) + (dash--match-symbol match-form source)) + ((consp match-form) + (cond + ;; Handle the "x &as" bindings first. + ((and (consp (cdr match-form)) + (symbolp (car match-form)) + (eq '&as (cadr match-form))) + (let ((s (car match-form))) + (cons (list s source) + (dash--match (cddr match-form) s)))) + ((memq (car match-form) '(&keys &plist &alist &hash)) + (dash--match-kv (dash--match-kv-normalize-match-form match-form) source)) + (t (dash--match-cons match-form source)))) + ((vectorp match-form) + ;; We support the &as binding in vectors too + (cond + ((and (> (length match-form) 2) + (symbolp (aref match-form 0)) + (eq '&as (aref match-form 1))) + (let ((s (aref match-form 0))) + (cons (list s source) + (dash--match (dash--vector-tail match-form 2) s)))) + (t (dash--match-vector match-form source)))))) + +(defun dash--normalize-let-varlist (varlist) + "Normalize VARLIST so that every binding is a list. + +`let' allows specifying a binding which is not a list but simply +the place which is then automatically bound to nil, such that all +three of the following are identical and evaluate to nil. + + (let (a) a) + (let ((a)) a) + (let ((a nil)) a) + +This function normalizes all of these to the last form." + (--map (if (consp it) it (list it nil)) varlist)) + +(defmacro -let* (varlist &rest body) + "Bind variables according to VARLIST then eval BODY. + +VARLIST is a list of lists of the form (PATTERN SOURCE). Each +PATTERN is matched against the SOURCE structurally. SOURCE is +only evaluated once for each PATTERN. + +Each SOURCE can refer to the symbols already bound by this +VARLIST. This is useful if you want to destructure SOURCE +recursively but also want to name the intermediate structures. + +See `-let' for the list of all possible patterns." + (declare (debug ((&rest [&or (sexp form) sexp]) body)) + (indent 1)) + (let* ((varlist (dash--normalize-let-varlist varlist)) + (bindings (--mapcat (dash--match (car it) (cadr it)) varlist))) + `(let* ,bindings + ,@body))) + +(defmacro -let (varlist &rest body) + "Bind variables according to VARLIST then eval BODY. + +VARLIST is a list of lists of the form (PATTERN SOURCE). Each +PATTERN is matched against the SOURCE \"structurally\". SOURCE +is only evaluated once for each PATTERN. Each PATTERN is matched +recursively, and can therefore contain sub-patterns which are +matched against corresponding sub-expressions of SOURCE. + +All the SOURCEs are evalled before any symbols are +bound (i.e. \"in parallel\"). + +If VARLIST only contains one (PATTERN SOURCE) element, you can +optionally specify it using a vector and discarding the +outer-most parens. Thus + + (-let ((PATTERN SOURCE)) ..) + +becomes + + (-let [PATTERN SOURCE] ..). + +`-let' uses a convention of not binding places (symbols) starting +with _ whenever it's possible. You can use this to skip over +entries you don't care about. However, this is not *always* +possible (as a result of implementation) and these symbols might +get bound to undefined values. + +Following is the overview of supported patterns. Remember that +patterns can be matched recursively, so every a, b, aK in the +following can be a matching construct and not necessarily a +symbol/variable. + +Symbol: + + a - bind the SOURCE to A. This is just like regular `let'. + +Conses and lists: + + (a) - bind `car' of cons/list to A + + (a . b) - bind car of cons to A and `cdr' to B + + (a b) - bind car of list to A and `cadr' to B + + (a1 a2 a3 ...) - bind 0th car of list to A1, 1st to A2, 2nd to A3 ... + + (a1 a2 a3 ... aN . rest) - as above, but bind the Nth cdr to REST. + +Vectors: + + [a] - bind 0th element of a non-list sequence to A (works with + vectors, strings, bit arrays...) + + [a1 a2 a3 ...] - bind 0th element of non-list sequence to A0, 1st to + A1, 2nd to A2, ... + If the PATTERN is shorter than SOURCE, the values at + places not in PATTERN are ignored. + If the PATTERN is longer than SOURCE, an `error' is + thrown. + + [a1 a2 a3 ... &rest rest] - as above, but bind the rest of + the sequence to REST. This is + conceptually the same as improper list + matching (a1 a2 ... aN . rest) + +Key/value stores: + + (&plist key0 a0 ... keyN aN) - bind value mapped by keyK in the + SOURCE plist to aK. If the + value is not found, aK is nil. + Uses `plist-get' to fetch values. + + (&alist key0 a0 ... keyN aN) - bind value mapped by keyK in the + SOURCE alist to aK. If the + value is not found, aK is nil. + Uses `assoc' to fetch values. + + (&hash key0 a0 ... keyN aN) - bind value mapped by keyK in the + SOURCE hash table to aK. If the + value is not found, aK is nil. + Uses `gethash' to fetch values. + +Further, special keyword &keys supports \"inline\" matching of +plist-like key-value pairs, similarly to &keys keyword of +`cl-defun'. + + (a1 a2 ... aN &keys key1 b1 ... keyN bK) + +This binds N values from the list to a1 ... aN, then interprets +the cdr as a plist (see key/value matching above). + +A shorthand notation for kv-destructuring exists which allows the +patterns be optionally left out and derived from the key name in +the following fashion: + +- a key :foo is converted into `foo' pattern, +- a key 'bar is converted into `bar' pattern, +- a key \"baz\" is converted into `baz' pattern. + +That is, the entire value under the key is bound to the derived +variable without any further destructuring. + +This is possible only when the form following the key is not a +valid pattern (i.e. not a symbol, a cons cell or a vector). +Otherwise the matching proceeds as usual and in case of an +invalid spec fails with an error. + +Thus the patterns are normalized as follows: + + ;; derive all the missing patterns + (&plist :foo 'bar \"baz\") => (&plist :foo foo 'bar bar \"baz\" baz) + + ;; we can specify some but not others + (&plist :foo 'bar explicit-bar) => (&plist :foo foo 'bar explicit-bar) + + ;; nothing happens, we store :foo in x + (&plist :foo x) => (&plist :foo x) + + ;; nothing happens, we match recursively + (&plist :foo (a b c)) => (&plist :foo (a b c)) + +You can name the source using the syntax SYMBOL &as PATTERN. +This syntax works with lists (proper or improper), vectors and +all types of maps. + + (list &as a b c) (list 1 2 3) + +binds A to 1, B to 2, C to 3 and LIST to (1 2 3). + +Similarly: + + (bounds &as beg . end) (cons 1 2) + +binds BEG to 1, END to 2 and BOUNDS to (1 . 2). + + (items &as first . rest) (list 1 2 3) + +binds FIRST to 1, REST to (2 3) and ITEMS to (1 2 3) + + [vect &as _ b c] [1 2 3] + +binds B to 2, C to 3 and VECT to [1 2 3] (_ avoids binding as usual). + + (plist &as &plist :b b) (list :a 1 :b 2 :c 3) + +binds B to 2 and PLIST to (:a 1 :b 2 :c 3). Same for &alist and &hash. + +This is especially useful when we want to capture the result of a +computation and destructure at the same time. Consider the +form (function-returning-complex-structure) returning a list of +two vectors with two items each. We want to capture this entire +result and pass it to another computation, but at the same time +we want to get the second item from each vector. We can achieve +it with pattern + + (result &as [_ a] [_ b]) (function-returning-complex-structure) + +Note: Clojure programmers may know this feature as the \":as +binding\". The difference is that we put the &as at the front +because we need to support improper list binding." + (declare (debug ([&or (&rest [&or (sexp form) sexp]) + (vector [&rest [sexp form]])] + body)) + (indent 1)) + (if (vectorp varlist) + `(let* ,(dash--match (aref varlist 0) (aref varlist 1)) + ,@body) + (let* ((varlist (dash--normalize-let-varlist varlist)) + (inputs (--map-indexed (list (make-symbol (format "input%d" it-index)) (cadr it)) varlist)) + (new-varlist (--map (list (caar it) (cadr it)) (-zip varlist inputs)))) + `(let ,inputs + (-let* ,new-varlist ,@body))))) + +(defmacro -lambda (match-form &rest body) + "Return a lambda which destructures its input as MATCH-FORM and executes BODY. + +Note that you have to enclose the MATCH-FORM in a pair of parens, +such that: + + (-lambda (x) body) + (-lambda (x y ...) body) + +has the usual semantics of `lambda'. Furthermore, these get +translated into normal lambda, so there is no performance +penalty. + +See `-let' for the description of destructuring mechanism." + (declare (doc-string 2) (indent defun) + (debug (&define sexp + [&optional stringp] + [&optional ("interactive" interactive)] + def-body))) + (cond + ((not (consp match-form)) + (signal 'wrong-type-argument "match-form must be a list")) + ;; no destructuring, so just return regular lambda to make things faster + ((-all? 'symbolp match-form) + `(lambda ,match-form ,@body)) + (t + (let* ((inputs (--map-indexed (list it (make-symbol (format "input%d" it-index))) match-form))) + ;; TODO: because inputs to the lambda are evaluated only once, + ;; -let* need not to create the extra bindings to ensure that. + ;; We should find a way to optimize that. Not critical however. + `(lambda ,(--map (cadr it) inputs) + (-let* ,inputs ,@body)))))) + +(defmacro -setq (&rest forms) + "Bind each MATCH-FORM to the value of its VAL. + +MATCH-FORM destructuring is done according to the rules of `-let'. + +This macro allows you to bind multiple variables by destructuring +the value, so for example: + + (-setq (a b) x + (&plist :c c) plist) + +expands roughly speaking to the following code + + (setq a (car x) + b (cadr x) + c (plist-get plist :c)) + +Care is taken to only evaluate each VAL once so that in case of +multiple assignments it does not cause unexpected side effects. + +\(fn [MATCH-FORM VAL]...)" + (declare (debug (&rest sexp form)) + (indent 1)) + (when (= (mod (length forms) 2) 1) + (error "Odd number of arguments")) + (let* ((forms-and-sources + ;; First get all the necessary mappings with all the + ;; intermediate bindings. + (-map (lambda (x) (dash--match (car x) (cadr x))) + (-partition 2 forms))) + ;; To preserve the logic of dynamic scoping we must ensure + ;; that we `setq' the variables outside of the `let*' form + ;; which holds the destructured intermediate values. For + ;; this we generate for each variable a placeholder which is + ;; bound to (lexically) the result of the destructuring. + ;; Then outside of the helper `let*' form we bind all the + ;; original variables to their respective placeholders. + ;; TODO: There is a lot of room for possible optimization, + ;; for start playing with `special-variable-p' to eliminate + ;; unnecessary re-binding. + (variables-to-placeholders + (-mapcat + (lambda (bindings) + (-map + (lambda (binding) + (let ((var (car binding))) + (list var (make-symbol (concat "--dash-binding-" (symbol-name var) "--"))))) + (--filter (not (string-prefix-p "--" (symbol-name (car it)))) bindings))) + forms-and-sources))) + `(let ,(-map 'cadr variables-to-placeholders) + (let* ,(-flatten-n 1 forms-and-sources) + (setq ,@(-flatten (-map 'reverse variables-to-placeholders)))) + (setq ,@(-flatten variables-to-placeholders))))) + +(defmacro -if-let* (vars-vals then &rest else) + "If all VALS evaluate to true, bind them to their corresponding +VARS and do THEN, otherwise do ELSE. VARS-VALS should be a list +of (VAR VAL) pairs. + +Note: binding is done according to `-let*'. VALS are evaluated +sequentially, and evaluation stops after the first nil VAL is +encountered." + (declare (debug ((&rest (sexp form)) form body)) + (indent 2)) + (->> vars-vals + (--mapcat (dash--match (car it) (cadr it))) + (--reduce-r-from + (let ((var (car it)) + (val (cadr it))) + `(let ((,var ,val)) + (if ,var ,acc ,@else))) + then))) + +(defmacro -if-let (var-val then &rest else) + "If VAL evaluates to non-nil, bind it to VAR and do THEN, +otherwise do ELSE. + +Note: binding is done according to `-let'. + +\(fn (VAR VAL) THEN &rest ELSE)" + (declare (debug ((sexp form) form body)) + (indent 2)) + `(-if-let* (,var-val) ,then ,@else)) + +(defmacro --if-let (val then &rest else) + "If VAL evaluates to non-nil, bind it to symbol `it' and do THEN, +otherwise do ELSE." + (declare (debug (form form body)) + (indent 2)) + `(-if-let (it ,val) ,then ,@else)) + +(defmacro -when-let* (vars-vals &rest body) + "If all VALS evaluate to true, bind them to their corresponding +VARS and execute body. VARS-VALS should be a list of (VAR VAL) +pairs. + +Note: binding is done according to `-let*'. VALS are evaluated +sequentially, and evaluation stops after the first nil VAL is +encountered." + (declare (debug ((&rest (sexp form)) body)) + (indent 1)) + `(-if-let* ,vars-vals (progn ,@body))) + +(defmacro -when-let (var-val &rest body) + "If VAL evaluates to non-nil, bind it to VAR and execute body. + +Note: binding is done according to `-let'. + +\(fn (VAR VAL) &rest BODY)" + (declare (debug ((sexp form) body)) + (indent 1)) + `(-if-let ,var-val (progn ,@body))) + +(defmacro --when-let (val &rest body) + "If VAL evaluates to non-nil, bind it to symbol `it' and +execute body." + (declare (debug (form body)) + (indent 1)) + `(--if-let ,val (progn ,@body))) + +(defvar -compare-fn nil + "Tests for equality use this function or `equal' if this is nil. +It should only be set using dynamic scope with a let, like: + + (let ((-compare-fn #\\='=)) (-union numbers1 numbers2 numbers3)") + +(defun -distinct (list) + "Return a new list with all duplicates removed. +The test for equality is done with `equal', +or with `-compare-fn' if that's non-nil. + +Alias: `-uniq'" + (let (result) + (--each list (unless (-contains? result it) (!cons it result))) + (nreverse result))) + +(defalias '-uniq '-distinct) + +(defun -union (list list2) + "Return a new list containing the elements of LIST and elements of LIST2 that are not in LIST. +The test for equality is done with `equal', +or with `-compare-fn' if that's non-nil." + ;; We fall back to iteration implementation if the comparison + ;; function isn't one of `eq', `eql' or `equal'. + (let* ((result (reverse list)) + ;; TODO: get rid of this dynamic variable, pass it as an + ;; argument instead. + (-compare-fn (if (bound-and-true-p -compare-fn) + -compare-fn + 'equal))) + (if (memq -compare-fn '(eq eql equal)) + (let ((ht (make-hash-table :test -compare-fn))) + (--each list (puthash it t ht)) + (--each list2 (unless (gethash it ht) (!cons it result)))) + (--each list2 (unless (-contains? result it) (!cons it result)))) + (nreverse result))) + +(defun -intersection (list list2) + "Return a new list containing only the elements that are members of both LIST and LIST2. +The test for equality is done with `equal', +or with `-compare-fn' if that's non-nil." + (--filter (-contains? list2 it) list)) + +(defun -difference (list list2) + "Return a new list with only the members of LIST that are not in LIST2. +The test for equality is done with `equal', +or with `-compare-fn' if that's non-nil." + (--filter (not (-contains? list2 it)) list)) + +(defun -powerset (list) + "Return the power set of LIST." + (if (null list) '(()) + (let ((last (-powerset (cdr list)))) + (append (mapcar (lambda (x) (cons (car list) x)) last) + last)))) + +(defun -permutations (list) + "Return the permutations of LIST." + (if (null list) '(()) + (apply #'append + (mapcar (lambda (x) + (mapcar (lambda (perm) (cons x perm)) + (-permutations (remove x list)))) + list)))) + +(defun -inits (list) + "Return all prefixes of LIST." + (nreverse (-map 'reverse (-tails (nreverse list))))) + +(defun -tails (list) + "Return all suffixes of LIST" + (-reductions-r-from 'cons nil list)) + +(defun -common-prefix (&rest lists) + "Return the longest common prefix of LISTS." + (declare (pure t) (side-effect-free t)) + (--reduce (--take-while (and acc (equal (pop acc) it)) it) + lists)) + +(defun -common-suffix (&rest lists) + "Return the longest common suffix of LISTS." + (nreverse (apply #'-common-prefix (mapcar #'reverse lists)))) + +(defun -contains? (list element) + "Return non-nil if LIST contains ELEMENT. + +The test for equality is done with `equal', or with `-compare-fn' +if that's non-nil. + +Alias: `-contains-p'" + (not + (null + (cond + ((null -compare-fn) (member element list)) + ((eq -compare-fn 'eq) (memq element list)) + ((eq -compare-fn 'eql) (memql element list)) + (t + (let ((lst list)) + (while (and lst + (not (funcall -compare-fn element (car lst)))) + (setq lst (cdr lst))) + lst)))))) + +(defalias '-contains-p '-contains?) + +(defun -same-items? (list list2) + "Return true if LIST and LIST2 has the same items. + +The order of the elements in the lists does not matter. + +Alias: `-same-items-p'" + (let ((length-a (length list)) + (length-b (length list2))) + (and + (= length-a length-b) + (= length-a (length (-intersection list list2)))))) + +(defalias '-same-items-p '-same-items?) + +(defun -is-prefix? (prefix list) + "Return non-nil if PREFIX is prefix of LIST. + +Alias: `-is-prefix-p'" + (declare (pure t) (side-effect-free t)) + (--each-while list (equal (car prefix) it) + (!cdr prefix)) + (not prefix)) + +(defun -is-suffix? (suffix list) + "Return non-nil if SUFFIX is suffix of LIST. + +Alias: `-is-suffix-p'" + (declare (pure t) (side-effect-free t)) + (-is-prefix? (reverse suffix) (reverse list))) + +(defun -is-infix? (infix list) + "Return non-nil if INFIX is infix of LIST. + +This operation runs in O(n^2) time + +Alias: `-is-infix-p'" + (declare (pure t) (side-effect-free t)) + (let (done) + (while (and (not done) list) + (setq done (-is-prefix? infix list)) + (!cdr list)) + done)) + +(defalias '-is-prefix-p '-is-prefix?) +(defalias '-is-suffix-p '-is-suffix?) +(defalias '-is-infix-p '-is-infix?) + +(defun -sort (comparator list) + "Sort LIST, stably, comparing elements using COMPARATOR. +Return the sorted list. LIST is NOT modified by side effects. +COMPARATOR is called with two elements of LIST, and should return non-nil +if the first element should sort before the second." + (sort (copy-sequence list) comparator)) + +(defmacro --sort (form list) + "Anaphoric form of `-sort'." + (declare (debug (form form))) + `(-sort (lambda (it other) ,form) ,list)) + +(defun -list (&rest args) + "Return a list with ARGS. + +If first item of ARGS is already a list, simply return ARGS. If +not, return a list with ARGS as elements." + (declare (pure t) (side-effect-free t)) + (let ((arg (car args))) + (if (listp arg) arg args))) + +(defun -repeat (n x) + "Return a list with X repeated N times. +Return nil if N is less than 1." + (declare (pure t) (side-effect-free t)) + (let (ret) + (--dotimes n (!cons x ret)) + ret)) + +(defun -sum (list) + "Return the sum of LIST." + (declare (pure t) (side-effect-free t)) + (apply '+ list)) + +(defun -running-sum (list) + "Return a list with running sums of items in LIST. + +LIST must be non-empty." + (declare (pure t) (side-effect-free t)) + (unless (consp list) + (error "LIST must be non-empty")) + (-reductions '+ list)) + +(defun -product (list) + "Return the product of LIST." + (declare (pure t) (side-effect-free t)) + (apply '* list)) + +(defun -running-product (list) + "Return a list with running products of items in LIST. + +LIST must be non-empty." + (declare (pure t) (side-effect-free t)) + (unless (consp list) + (error "LIST must be non-empty")) + (-reductions '* list)) + +(defun -max (list) + "Return the largest value from LIST of numbers or markers." + (declare (pure t) (side-effect-free t)) + (apply 'max list)) + +(defun -min (list) + "Return the smallest value from LIST of numbers or markers." + (declare (pure t) (side-effect-free t)) + (apply 'min list)) + +(defun -max-by (comparator list) + "Take a comparison function COMPARATOR and a LIST and return +the greatest element of the list by the comparison function. + +See also combinator `-on' which can transform the values before +comparing them." + (--reduce (if (funcall comparator it acc) it acc) list)) + +(defun -min-by (comparator list) + "Take a comparison function COMPARATOR and a LIST and return +the least element of the list by the comparison function. + +See also combinator `-on' which can transform the values before +comparing them." + (--reduce (if (funcall comparator it acc) acc it) list)) + +(defmacro --max-by (form list) + "Anaphoric version of `-max-by'. + +The items for the comparator form are exposed as \"it\" and \"other\"." + (declare (debug (form form))) + `(-max-by (lambda (it other) ,form) ,list)) + +(defmacro --min-by (form list) + "Anaphoric version of `-min-by'. + +The items for the comparator form are exposed as \"it\" and \"other\"." + (declare (debug (form form))) + `(-min-by (lambda (it other) ,form) ,list)) + +(defun -iterate (fun init n) + "Return a list of iterated applications of FUN to INIT. + +This means a list of form: + + (init (fun init) (fun (fun init)) ...) + +N is the length of the returned list." + (if (= n 0) nil + (let ((r (list init))) + (--dotimes (1- n) + (push (funcall fun (car r)) r)) + (nreverse r)))) + +(defun -fix (fn list) + "Compute the (least) fixpoint of FN with initial input LIST. + +FN is called at least once, results are compared with `equal'." + (let ((re (funcall fn list))) + (while (not (equal list re)) + (setq list re) + (setq re (funcall fn re))) + re)) + +(defmacro --fix (form list) + "Anaphoric form of `-fix'." + `(-fix (lambda (it) ,form) ,list)) + +(defun -unfold (fun seed) + "Build a list from SEED using FUN. + +This is \"dual\" operation to `-reduce-r': while -reduce-r +consumes a list to produce a single value, `-unfold' takes a +seed value and builds a (potentially infinite!) list. + +FUN should return `nil' to stop the generating process, or a +cons (A . B), where A will be prepended to the result and B is +the new seed." + (let ((last (funcall fun seed)) r) + (while last + (push (car last) r) + (setq last (funcall fun (cdr last)))) + (nreverse r))) + +(defmacro --unfold (form seed) + "Anaphoric version of `-unfold'." + (declare (debug (form form))) + `(-unfold (lambda (it) ,form) ,seed)) + +(defun -cons-pair? (con) + "Return non-nil if CON is true cons pair. +That is (A . B) where B is not a list." + (declare (pure t) (side-effect-free t)) + (and (listp con) + (not (listp (cdr con))))) + +(defun -cons-to-list (con) + "Convert a cons pair to a list with `car' and `cdr' of the pair respectively." + (declare (pure t) (side-effect-free t)) + (list (car con) (cdr con))) + +(defun -value-to-list (val) + "Convert a value to a list. + +If the value is a cons pair, make a list with two elements, `car' +and `cdr' of the pair respectively. + +If the value is anything else, wrap it in a list." + (declare (pure t) (side-effect-free t)) + (cond + ((-cons-pair? val) (-cons-to-list val)) + (t (list val)))) + +(defun -tree-mapreduce-from (fn folder init-value tree) + "Apply FN to each element of TREE, and make a list of the results. +If elements of TREE are lists themselves, apply FN recursively to +elements of these nested lists. + +Then reduce the resulting lists using FOLDER and initial value +INIT-VALUE. See `-reduce-r-from'. + +This is the same as calling `-tree-reduce-from' after `-tree-map' +but is twice as fast as it only traverse the structure once." + (cond + ((not tree) nil) + ((-cons-pair? tree) (funcall fn tree)) + ((listp tree) + (-reduce-r-from folder init-value (mapcar (lambda (x) (-tree-mapreduce-from fn folder init-value x)) tree))) + (t (funcall fn tree)))) + +(defmacro --tree-mapreduce-from (form folder init-value tree) + "Anaphoric form of `-tree-mapreduce-from'." + (declare (debug (form form form form))) + `(-tree-mapreduce-from (lambda (it) ,form) (lambda (it acc) ,folder) ,init-value ,tree)) + +(defun -tree-mapreduce (fn folder tree) + "Apply FN to each element of TREE, and make a list of the results. +If elements of TREE are lists themselves, apply FN recursively to +elements of these nested lists. + +Then reduce the resulting lists using FOLDER and initial value +INIT-VALUE. See `-reduce-r-from'. + +This is the same as calling `-tree-reduce' after `-tree-map' +but is twice as fast as it only traverse the structure once." + (cond + ((not tree) nil) + ((-cons-pair? tree) (funcall fn tree)) + ((listp tree) + (-reduce-r folder (mapcar (lambda (x) (-tree-mapreduce fn folder x)) tree))) + (t (funcall fn tree)))) + +(defmacro --tree-mapreduce (form folder tree) + "Anaphoric form of `-tree-mapreduce'." + (declare (debug (form form form))) + `(-tree-mapreduce (lambda (it) ,form) (lambda (it acc) ,folder) ,tree)) + +(defun -tree-map (fn tree) + "Apply FN to each element of TREE while preserving the tree structure." + (cond + ((not tree) nil) + ((-cons-pair? tree) (funcall fn tree)) + ((listp tree) + (mapcar (lambda (x) (-tree-map fn x)) tree)) + (t (funcall fn tree)))) + +(defmacro --tree-map (form tree) + "Anaphoric form of `-tree-map'." + (declare (debug (form form))) + `(-tree-map (lambda (it) ,form) ,tree)) + +(defun -tree-reduce-from (fn init-value tree) + "Use FN to reduce elements of list TREE. +If elements of TREE are lists themselves, apply the reduction recursively. + +FN is first applied to INIT-VALUE and first element of the list, +then on this result and second element from the list etc. + +The initial value is ignored on cons pairs as they always contain +two elements." + (cond + ((not tree) nil) + ((-cons-pair? tree) tree) + ((listp tree) + (-reduce-r-from fn init-value (mapcar (lambda (x) (-tree-reduce-from fn init-value x)) tree))) + (t tree))) + +(defmacro --tree-reduce-from (form init-value tree) + "Anaphoric form of `-tree-reduce-from'." + (declare (debug (form form form))) + `(-tree-reduce-from (lambda (it acc) ,form) ,init-value ,tree)) + +(defun -tree-reduce (fn tree) + "Use FN to reduce elements of list TREE. +If elements of TREE are lists themselves, apply the reduction recursively. + +FN is first applied to first element of the list and second +element, then on this result and third element from the list etc. + +See `-reduce-r' for how exactly are lists of zero or one element handled." + (cond + ((not tree) nil) + ((-cons-pair? tree) tree) + ((listp tree) + (-reduce-r fn (mapcar (lambda (x) (-tree-reduce fn x)) tree))) + (t tree))) + +(defmacro --tree-reduce (form tree) + "Anaphoric form of `-tree-reduce'." + (declare (debug (form form))) + `(-tree-reduce (lambda (it acc) ,form) ,tree)) + +(defun -tree-map-nodes (pred fun tree) + "Call FUN on each node of TREE that satisfies PRED. + +If PRED returns nil, continue descending down this node. If PRED +returns non-nil, apply FUN to this node and do not descend +further." + (if (funcall pred tree) + (funcall fun tree) + (if (and (listp tree) + (not (-cons-pair? tree))) + (-map (lambda (x) (-tree-map-nodes pred fun x)) tree) + tree))) + +(defmacro --tree-map-nodes (pred form tree) + "Anaphoric form of `-tree-map-nodes'." + `(-tree-map-nodes (lambda (it) ,pred) (lambda (it) ,form) ,tree)) + +(defun -tree-seq (branch children tree) + "Return a sequence of the nodes in TREE, in depth-first search order. + +BRANCH is a predicate of one argument that returns non-nil if the +passed argument is a branch, that is, a node that can have children. + +CHILDREN is a function of one argument that returns the children +of the passed branch node. + +Non-branch nodes are simply copied." + (cons tree + (when (funcall branch tree) + (-mapcat (lambda (x) (-tree-seq branch children x)) + (funcall children tree))))) + +(defmacro --tree-seq (branch children tree) + "Anaphoric form of `-tree-seq'." + `(-tree-seq (lambda (it) ,branch) (lambda (it) ,children) ,tree)) + +(defun -clone (list) + "Create a deep copy of LIST. +The new list has the same elements and structure but all cons are +replaced with new ones. This is useful when you need to clone a +structure such as plist or alist." + (declare (pure t) (side-effect-free t)) + (-tree-map 'identity list)) + +(defun dash-enable-font-lock () + "Add syntax highlighting to dash functions, macros and magic values." + (eval-after-load 'lisp-mode + '(progn + (let ((new-keywords '( + "!cons" + "!cdr" + "-each" + "--each" + "-each-indexed" + "--each-indexed" + "-each-while" + "--each-while" + "-doto" + "-dotimes" + "--dotimes" + "-map" + "--map" + "-reduce-from" + "--reduce-from" + "-reduce" + "--reduce" + "-reduce-r-from" + "--reduce-r-from" + "-reduce-r" + "--reduce-r" + "-reductions-from" + "-reductions-r-from" + "-reductions" + "-reductions-r" + "-filter" + "--filter" + "-select" + "--select" + "-remove" + "--remove" + "-reject" + "--reject" + "-remove-first" + "--remove-first" + "-reject-first" + "--reject-first" + "-remove-last" + "--remove-last" + "-reject-last" + "--reject-last" + "-remove-item" + "-non-nil" + "-keep" + "--keep" + "-map-indexed" + "--map-indexed" + "-splice" + "--splice" + "-splice-list" + "--splice-list" + "-map-when" + "--map-when" + "-replace-where" + "--replace-where" + "-map-first" + "--map-first" + "-map-last" + "--map-last" + "-replace" + "-replace-first" + "-replace-last" + "-flatten" + "-flatten-n" + "-concat" + "-mapcat" + "--mapcat" + "-copy" + "-cons*" + "-snoc" + "-first" + "--first" + "-find" + "--find" + "-some" + "--some" + "-any" + "--any" + "-last" + "--last" + "-first-item" + "-second-item" + "-third-item" + "-fourth-item" + "-fifth-item" + "-last-item" + "-butlast" + "-count" + "--count" + "-any?" + "--any?" + "-some?" + "--some?" + "-any-p" + "--any-p" + "-some-p" + "--some-p" + "-some->" + "-some->>" + "-some-->" + "-all?" + "-all-p" + "--all?" + "--all-p" + "-every?" + "--every?" + "-all-p" + "--all-p" + "-every-p" + "--every-p" + "-none?" + "--none?" + "-none-p" + "--none-p" + "-only-some?" + "--only-some?" + "-only-some-p" + "--only-some-p" + "-slice" + "-take" + "-drop" + "-drop-last" + "-take-last" + "-take-while" + "--take-while" + "-drop-while" + "--drop-while" + "-split-at" + "-rotate" + "-insert-at" + "-replace-at" + "-update-at" + "--update-at" + "-remove-at" + "-remove-at-indices" + "-split-with" + "--split-with" + "-split-on" + "-split-when" + "--split-when" + "-separate" + "--separate" + "-partition-all-in-steps" + "-partition-in-steps" + "-partition-all" + "-partition" + "-partition-after-item" + "-partition-after-pred" + "-partition-before-item" + "-partition-before-pred" + "-partition-by" + "--partition-by" + "-partition-by-header" + "--partition-by-header" + "-group-by" + "--group-by" + "-interpose" + "-interleave" + "-unzip" + "-zip-with" + "--zip-with" + "-zip" + "-zip-fill" + "-zip-pair" + "-cycle" + "-pad" + "-annotate" + "--annotate" + "-table" + "-table-flat" + "-partial" + "-elem-index" + "-elem-indices" + "-find-indices" + "--find-indices" + "-find-index" + "--find-index" + "-find-last-index" + "--find-last-index" + "-select-by-indices" + "-select-columns" + "-select-column" + "-grade-up" + "-grade-down" + "->" + "->>" + "-->" + "-as->" + "-when-let" + "-when-let*" + "--when-let" + "-if-let" + "-if-let*" + "--if-let" + "-let*" + "-let" + "-lambda" + "-distinct" + "-uniq" + "-union" + "-intersection" + "-difference" + "-powerset" + "-permutations" + "-inits" + "-tails" + "-common-prefix" + "-common-suffix" + "-contains?" + "-contains-p" + "-same-items?" + "-same-items-p" + "-is-prefix-p" + "-is-prefix?" + "-is-suffix-p" + "-is-suffix?" + "-is-infix-p" + "-is-infix?" + "-sort" + "--sort" + "-list" + "-repeat" + "-sum" + "-running-sum" + "-product" + "-running-product" + "-max" + "-min" + "-max-by" + "--max-by" + "-min-by" + "--min-by" + "-iterate" + "--iterate" + "-fix" + "--fix" + "-unfold" + "--unfold" + "-cons-pair?" + "-cons-to-list" + "-value-to-list" + "-tree-mapreduce-from" + "--tree-mapreduce-from" + "-tree-mapreduce" + "--tree-mapreduce" + "-tree-map" + "--tree-map" + "-tree-reduce-from" + "--tree-reduce-from" + "-tree-reduce" + "--tree-reduce" + "-tree-seq" + "--tree-seq" + "-tree-map-nodes" + "--tree-map-nodes" + "-clone" + "-rpartial" + "-juxt" + "-applify" + "-on" + "-flip" + "-const" + "-cut" + "-orfn" + "-andfn" + "-iteratefn" + "-fixfn" + "-prodfn" + )) + (special-variables '( + "it" + "it-index" + "acc" + "other" + ))) + (font-lock-add-keywords 'emacs-lisp-mode `((,(concat "\\_<" (regexp-opt special-variables 'paren) "\\_>") + 1 font-lock-variable-name-face)) 'append) + (font-lock-add-keywords 'emacs-lisp-mode `((,(concat "(\\s-*" (regexp-opt new-keywords 'paren) "\\_>") + 1 font-lock-keyword-face)) 'append)) + (--each (buffer-list) + (with-current-buffer it + (when (and (eq major-mode 'emacs-lisp-mode) + (boundp 'font-lock-mode) + font-lock-mode) + (font-lock-refresh-defaults))))))) + +(provide 'dash) +;;; dash.el ends here diff --git a/elpa/editorconfig-20181025.421/dir b/elpa/editorconfig-20181025.421/dir new file mode 100644 index 00000000..37389027 --- /dev/null +++ b/elpa/editorconfig-20181025.421/dir @@ -0,0 +1,18 @@ +This is the file .../info/dir, which contains the +topmost node of the Info hierarchy, called (dir)Top. +The first time you invoke Info you start off looking at this node. + +File: dir, Node: Top This is the top of the INFO tree + + This (the Directory node) gives a menu of major topics. + Typing "q" exits, "H" lists all Info commands, "d" returns here, + "h" gives a primer for first-timers, + "mEmacs" visits the Emacs manual, etc. + + In Emacs, you can click mouse button 2 on a menu item or cross reference + to select it. + +* Menu: + +Emacs +* EditorConfig: (editorconfig). EditorConfig Emacs Plugin. diff --git a/elpa/editorconfig-20181025.421/editorconfig-autoloads.el b/elpa/editorconfig-20181025.421/editorconfig-autoloads.el new file mode 100644 index 00000000..2f4d561c --- /dev/null +++ b/elpa/editorconfig-20181025.421/editorconfig-autoloads.el @@ -0,0 +1,145 @@ +;;; editorconfig-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "editorconfig" "editorconfig.el" (0 0 0 0)) +;;; Generated autoloads from editorconfig.el + +(autoload 'editorconfig-find-current-editorconfig "editorconfig" "\ +Find the closest .editorconfig file for current file. + +\(fn)" t nil) + +(autoload 'editorconfig-display-current-properties "editorconfig" "\ +Display EditorConfig properties extracted for current buffer. + +\(fn)" t nil) + +(autoload 'editorconfig-apply "editorconfig" "\ +Apply EditorConfig properties for current buffer. +This function ignores `editorconfig-exclude-modes' and always +applies available properties. + +\(fn)" t nil) + +(defvar editorconfig-mode nil "\ +Non-nil if Editorconfig mode is enabled. +See the `editorconfig-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `editorconfig-mode'.") + +(custom-autoload 'editorconfig-mode "editorconfig" nil) + +(autoload 'editorconfig-mode "editorconfig" "\ +Toggle EditorConfig feature. +When enabled EditorConfig properties will be applied to buffers +when first visiting files or changing major modes if the major +mode is not listed in `editorconfig-exclude-modes'. + +\(fn &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "editorconfig" '("editorcon"))) + +;;;*** + +;;;### (autoloads nil "editorconfig-conf-mode" "editorconfig-conf-mode.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from editorconfig-conf-mode.el + +(autoload 'editorconfig-conf-mode "editorconfig-conf-mode" "\ +Major mode for editing .editorconfig files. + +\(fn)" t nil) + +(add-to-list 'auto-mode-alist '("\\.editorconfig\\'" . editorconfig-conf-mode)) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "editorconfig-conf-mode" '("editorconfig-conf-mode-syntax-table"))) + +;;;*** + +;;;### (autoloads nil "editorconfig-core" "editorconfig-core.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from editorconfig-core.el + +(autoload 'editorconfig-core-get-nearest-editorconfig "editorconfig-core" "\ +Return path to .editorconfig file that is closest to DIRECTORY. + +\(fn DIRECTORY)" nil nil) + +(autoload 'editorconfig-core-get-properties "editorconfig-core" "\ +Get EditorConfig properties for FILE. +If FILE is not given, use currently visiting file. +Give CONFNAME for basename of config file other than .editorconfig. +If need to specify config format version, give CONFVERSION. + +This functions returns alist of properties. Each element will look like +'(KEY . VALUE) . + +\(fn &optional FILE CONFNAME CONFVERSION)" nil nil) + +(autoload 'editorconfig-core-get-properties-hash "editorconfig-core" "\ +Get EditorConfig properties for FILE. +If FILE is not given, use currently visiting file. +Give CONFNAME for basename of config file other than .editorconfig. +If need to specify config format version, give CONFVERSION. + +This function is almost same as `editorconfig-core-get-properties', but returns +hash object instead. + +\(fn &optional FILE CONFNAME CONFVERSION)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "editorconfig-core" '("editorconfig-core-"))) + +;;;*** + +;;;### (autoloads nil "editorconfig-core-handle" "editorconfig-core-handle.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from editorconfig-core-handle.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "editorconfig-core-handle" '("editorconfig-core-handle"))) + +;;;*** + +;;;### (autoloads nil "editorconfig-fnmatch" "editorconfig-fnmatch.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from editorconfig-fnmatch.el + +(autoload 'editorconfig-fnmatch-p "editorconfig-fnmatch" "\ +Test whether STRING match PATTERN. + +Matching ignores case if `case-fold-search' is non-nil. + +PATTERN should be a shell glob pattern, and some zsh-like wildcard matchings can +be used: + +* Matches any string of characters, except path separators (/) +** Matches any string of characters +? Matches any single character +\[name] Matches any single character in name +\[^name] Matches any single character not in name +{s1,s2,s3} Matches any of the strings given (separated by commas) +{min..max} Matches any number between min and max + +\(fn STRING PATTERN)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "editorconfig-fnmatch" '("editorconfig-fnmatch-"))) + +;;;*** + +;;;### (autoloads nil nil ("editorconfig-pkg.el") (0 0 0 0)) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; editorconfig-autoloads.el ends here diff --git a/elpa/editorconfig-20181025.421/editorconfig-conf-mode.el b/elpa/editorconfig-20181025.421/editorconfig-conf-mode.el new file mode 100644 index 00000000..1a249d3f --- /dev/null +++ b/elpa/editorconfig-20181025.421/editorconfig-conf-mode.el @@ -0,0 +1,96 @@ +;;; editorconfig-conf-mode.el --- Major mode for editing .editorconfig files + +;; Copyright (C) 2011-2017 EditorConfig Team + +;; Author: EditorConfig Team +;; URL: https://github.com/editorconfig/editorconfig-emacs#readme + +;; See +;; https://github.com/editorconfig/editorconfig-emacs/graphs/contributors +;; or the CONTRIBUTORS file for the list of contributors. + +;; This file is part of EditorConfig Emacs Plugin. + +;; EditorConfig Emacs Plugin 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 of the License, or (at your +;; option) any later version. + +;; EditorConfig Emacs Plugin 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 +;; EditorConfig Emacs Plugin. If not, see . + +;;; Commentary: + +;; Major mode for editing .editorconfig files. + +;;; Code: + +(require 'conf-mode) + +(defvar editorconfig-conf-mode-syntax-table + (let ((table (make-syntax-table conf-unix-mode-syntax-table))) + (modify-syntax-entry ?\; "<" table) + table) + "Syntax table in use in `editorconfig-conf-mode' buffers.") + +;;;###autoload +(define-derived-mode editorconfig-conf-mode conf-unix-mode "Conf[EditorConfig]" + "Major mode for editing .editorconfig files." + (set-variable 'indent-line-function 'indent-relative) + (let ((key-property-list + '("charset" + "end_of_line" + "file_type_emacs" + "file_type_ext" + "indent_size" + "indent_style" + "insert_final_newline" + "max_line_length" + "root" + "tab_width" + "trim_trailing_whitespace")) + (key-value-list + '("unset" + "true" + "false" + "lf" + "cr" + "crlf" + "space" + "tab" + "latin1" + "utf-8" + "utf-8-bom" + "utf-16be" + "utf-16le")) + (font-lock-value + '(("^[ \t]*\\[\\(.+?\\)\\]" 1 font-lock-type-face) + ("^[ \t]*\\(.+?\\)[ \t]*[=:]" 1 font-lock-variable-name-face)))) + + ;; Highlight all key values + (dolist (key-value key-value-list) + (add-to-list + 'font-lock-value + `(,(format "[=:][ \t]*\\(%s\\)\\([ \t]\\|$\\)" key-value) + 1 font-lock-constant-face))) + ;; Highlight all key properties + (dolist (key-property key-property-list) + (add-to-list + 'font-lock-value + `(,(format "^[ \t]*\\(%s\\)[ \t]*[=:]" key-property) + 1 font-lock-builtin-face))) + + (conf-mode-initialize "#" font-lock-value))) + +;;;###autoload +(add-to-list 'auto-mode-alist + '("\\.editorconfig\\'" . editorconfig-conf-mode)) + +(provide 'editorconfig-conf-mode) + +;;; editorconfig-conf-mode.el ends here diff --git a/elpa/editorconfig-20181025.421/editorconfig-core-handle.el b/elpa/editorconfig-20181025.421/editorconfig-core-handle.el new file mode 100644 index 00000000..cb2cbb9b --- /dev/null +++ b/elpa/editorconfig-20181025.421/editorconfig-core-handle.el @@ -0,0 +1,222 @@ +;;; editorconfig-core-handle.el --- Handle Class for EditorConfig File + +;; Copyright (C) 2011-2017 EditorConfig Team + +;; Author: EditorConfig Team +;; URL: https://github.com/editorconfig/editorconfig-emacs#readme + +;; See +;; https://github.com/editorconfig/editorconfig-emacs/graphs/contributors +;; or the CONTRIBUTORS file for the list of contributors. + +;; This file is part of EditorConfig Emacs Plugin. + +;; EditorConfig Emacs Plugin 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 of the License, or (at your +;; option) any later version. + +;; EditorConfig Emacs Plugin 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 +;; EditorConfig Emacs Plugin. If not, see . + +;;; Commentary: + +;; Handle class for EditorConfig config file. This library is used internally +;; from editorconfig-core.el . + +;;; Code: + +(require 'editorconfig-fnmatch) + +;; For cl-defstruct +(require 'cl-lib) + +(defvar editorconfig-core-handle--cache-hash + (make-hash-table :test 'equal) + "Hash of EditorConfig filename and its `editorconfig-core-handle' instance.") + +(cl-defstruct editorconfig-core-handle + ;; Alist of top propetties + ;; e.g. (("root" . "true")) + (top-prop nil) + + ;; Alist of properties + ;; Key: Section name + ;; Value: Alist of properties for each section name + ;; e.g. + ;; ( + ;; ("*" ("end_of_line" . "lf") ("indent_style" . "space")) + ;; ("Makefile" ("indent_style" . "tab")) + ;; ) + (prop nil) + + ;; e.g. (22310 59113 203882 991000) + (mtime nil) + + ;; e.g. "/home/a/b/.editorconfig" + (path nil)) + + +(defun editorconfig-core-handle (conf) + "Return EditorConfig handle for CONF, which should be a file path. + +If CONF does not exist return nil." + (when (file-readable-p conf) + (let ((cached (gethash conf + editorconfig-core-handle--cache-hash)) + (mtime (nth 5 + (file-attributes conf)))) + (if (and cached + (equal (editorconfig-core-handle-mtime cached) + mtime)) + cached + (let ((parsed (editorconfig-core-handle--parse-file conf))) + (puthash conf + (make-editorconfig-core-handle :top-prop (car parsed) + :prop (cdr parsed) + :mtime mtime + :path conf) + editorconfig-core-handle--cache-hash)))))) + +(defun editorconfig-core-handle-root-p (handle) + "Return non-nil if HANDLE represent root EditorConfig file. + +If HANDLE is nil return nil." + (when handle + (string-equal "true" + (downcase (or (cdr (assoc "root" + (editorconfig-core-handle-top-prop handle))) + ""))))) + +(defun editorconfig-core-handle-get-properties (handle file) + "Return list of alist of properties from HANDLE for FILE. +The list returned will be ordered by the lines they appear. + +If HANDLE is nil return nil." + (when handle + (mapcar (lambda (prop) (copy-alist (cdr prop))) + (cl-remove-if-not (lambda (prop) + (editorconfig-core-handle--fnmatch-p file + (car prop) + (file-name-directory (editorconfig-core-handle-path handle)))) + (editorconfig-core-handle-prop handle))))) + +(defun editorconfig-core-handle--fnmatch-p (name pattern dir) + "Return non-nil if NAME match PATTERN. +If pattern has slash, pattern should be relative to DIR. + +This function is a fnmatch with a few modification for EditorConfig usage." + (if (string-match-p "/" pattern) + (let ((pattern (replace-regexp-in-string "^/" + "" + pattern)) + (dir (file-name-as-directory dir))) + (editorconfig-fnmatch-p name + (concat dir + pattern))) + (editorconfig-fnmatch-p name + (concat "**/" + pattern)))) + +(defsubst editorconfig-core-handle--string-trim (str) + "Remove leading and trailing whitespaces from STR." + (replace-regexp-in-string "[[:space:]]+\\'" + "" + (replace-regexp-in-string "\\`[[:space:]]+" + "" + str))) + +(defun editorconfig-core-handle--parse-file (conf) + "Parse EditorConfig file CONF. + +This function returns cons of its top properties alist and +alist of patterns and its properties alist. +The list returned will be ordered by the lines they appear. + +If CONF is not found return nil." + (when (file-readable-p conf) + (with-temp-buffer + ;; NOTE: Use this instead of insert-file-contents-literally to enable + ;; code conversion + (insert-file-contents conf) + (goto-char (point-min)) + (let ((point-max (point-max)) + (all-props ()) + (top-props nil) + + ;; String of current line + (line "") + ;; nil when pattern not appeared yet, "" when pattern is empty ("[]") + (pattern nil) + ;; Alist of properties for current PATTERN + (props ()) + + ;; Current line num + (current-line-number 1) + ) + (while (not (eq (point) point-max)) + (setq line + (buffer-substring-no-properties (point-at-bol) + (point-at-eol))) + (setq line + (replace-regexp-in-string "\\(^\\| \\)\\(#\\|;\\).*$" + "" + (editorconfig-core-handle--string-trim line))) + + (cond + ((string-equal "" line) + nil) + + ((string-match "^\\[\\(.*\\)\\]$" + line) + (when pattern + (setq all-props + `(,@all-props (,pattern . ,props))) + (setq props nil)) + (setq pattern (match-string 1 line))) + + (t + (let ((idx (string-match "=\\|:" + line))) + (unless idx + (error "Error while reading config file: %s:%d:\n %s\n" + conf + current-line-number + line)) + (let ( + (key (downcase (editorconfig-core-handle--string-trim + (substring line + 0 + idx)))) + (value (editorconfig-core-handle--string-trim + (substring line + (1+ idx))))) + (when (and (< (length key) 51) + (< (length value) 256)) + (if pattern + (when (< (length pattern) 4097) + (setq props + `(,@props (,key . ,value)))) + (setq top-props + `(,@top-props (,key . ,value)))))))) + ) + (setq current-line-number + (1+ current-line-number)) + ;; Use this code instead of goto-line for Lisp program + (goto-char (point-min)) + (forward-line (1- current-line-number)) + ) + (when pattern + (setq all-props + `(,@all-props (,pattern . ,props)))) + (cons top-props + all-props))))) + +(provide 'editorconfig-core-handle) + +;;; editorconfig-core-handle.el ends here diff --git a/elpa/editorconfig-20181025.421/editorconfig-core.el b/elpa/editorconfig-20181025.421/editorconfig-core.el new file mode 100644 index 00000000..9d396f18 --- /dev/null +++ b/elpa/editorconfig-20181025.421/editorconfig-core.el @@ -0,0 +1,210 @@ +;;; editorconfig-core.el --- EditorConfig Core library in Emacs Lisp + +;; Copyright (C) 2011-2017 EditorConfig Team + +;; Author: EditorConfig Team +;; URL: https://github.com/editorconfig/editorconfig-emacs#readme + +;; See +;; https://github.com/editorconfig/editorconfig-emacs/graphs/contributors +;; or the CONTRIBUTORS file for the list of contributors. + +;; This file is part of EditorConfig Emacs Plugin. + +;; EditorConfig Emacs Plugin 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 of the License, or (at your +;; option) any later version. + +;; EditorConfig Emacs Plugin 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 +;; EditorConfig Emacs Plugin. If not, see . + +;;; Commentary: + +;; This library is one implementation of EditorConfig Core, which parses +;; .editorconfig files and returns properties for given files. +;; This can be used in place of, for example, editorconfig-core-c. + + +;; Use from EditorConfig Emacs Plugin + +;; Emacs plugin (v0.5 or later) can utilize this implementation. +;; By default, the plugin first search for any EditorConfig executable, +;; and fallback to this library if not found. +;; If you always want to use this library, add following lines to your init.el: + +;; (setq editorconfig-get-properties-function +;; 'editorconfig-core-get-properties-hash) + + +;; Functions + +;; editorconfig-core-get-properties (&optional file confname confversion) + +;; Get EditorConfig properties for FILE. + +;; If FILE is not given, use currently visiting file. +;; Give CONFNAME for basename of config file other than .editorconfig. +;; If need to specify config format version, give CONFVERSION. + +;; This functions returns alist of properties. Each element will look like +;; (KEY . VALUE) . + + +;; editorconfig-core-get-properties-hash (&optional file confname confversion) + +;; Get EditorConfig properties for FILE. + +;; This function is almost same as `editorconfig-core-get-properties', but +;; returns hash object instead. + +;;; Code: + +(require 'cl-lib) + +(require 'editorconfig-core-handle) + + +(defconst editorconfig-core-version + "0.7.13" + "EditorConfig core version.") + +(defun editorconfig-core--remove-duplicate (alist) + "Remove duplicated keys in ALIST. + +If same keys are found in ALIST multiple times, the latter ones take precedence. +For example, when ALIST is + + '((a 1) (b 2) (c 3) (b 4)) + +then the result will be + + '((a 1) (b 4) (c 3)) ." + (let ((result ())) + (dolist (e alist) + (let ((pair (assoc (car e) + result))) + (if pair + (setcdr pair + (cdr e)) + (setq result + `(,@result ,e))))) + result)) + +(defun editorconfig-core--get-handles (dir confname &optional result) + "Get list of EditorConfig handlers for DIR from CONFNAME. + +In the resulting list, the handle for root config file comes first, and the +nearest comes last. +The list may contains nil when no file was found for directories. +RESULT is used internally and normally should not be used." + (setq dir (expand-file-name dir)) + (let ((handle (editorconfig-core-handle (concat (file-name-as-directory dir) + confname))) + (parent (file-name-directory (directory-file-name dir)))) + (if (or (string= parent + dir) + (and handle + (editorconfig-core-handle-root-p handle))) + (cl-remove-if-not 'identity + (cons handle result)) + (editorconfig-core--get-handles parent + confname + (cons handle + result))))) + +;;;###autoload +(defun editorconfig-core-get-nearest-editorconfig (directory) + "Return path to .editorconfig file that is closest to DIRECTORY." + (let ((handle (car (last (editorconfig-core--get-handles directory + ".editorconfig"))))) + (when handle + (editorconfig-core-handle-path handle)))) + +;;;###autoload +(defun editorconfig-core-get-properties (&optional file confname confversion) + "Get EditorConfig properties for FILE. +If FILE is not given, use currently visiting file. +Give CONFNAME for basename of config file other than .editorconfig. +If need to specify config format version, give CONFVERSION. + +This functions returns alist of properties. Each element will look like +'(KEY . VALUE) ." + (setq file (expand-file-name (or file + buffer-file-name + (error "FILE is not given and `buffer-file-name' is nil")))) + (setq confname (or confname + ".editorconfig")) + (setq confversion (or confversion + "0.12.0")) + (let ((result (editorconfig-core--remove-duplicate + (apply 'append + (mapcar (lambda (handle) + (apply 'append + (editorconfig-core-handle-get-properties handle + file))) + (editorconfig-core--get-handles (file-name-directory file) + confname)))))) + (dolist (key '("end_of_line" "indent_style" "indent_size" + "insert_final_newline" "trim_trailing_whitespace" "charset")) + (let ((pair (assoc key + result))) + (when pair + (setcdr pair + (downcase (cdr pair)))))) + + ;; Add indent_size property + (let ((p-indent-size (assoc "indent_size" result)) + (p-indent-style (assoc "indent_style" result))) + (when (and (not p-indent-size) + (string= (cdr p-indent-style) "tab") + ;; If VERSION < 0.9.0, indent_size should have no default value + (version<= "0.9.0" + confversion)) + (setq result + `(,@result ("indent_size" . "tab"))))) + ;; Add tab_width property + (let ((p-indent-size (assoc "indent_size" result)) + (p-tab-width (assoc "tab_width" result))) + (when (and p-indent-size + (not p-tab-width) + (not (string= (cdr p-indent-size) "tab"))) + (setq result + `(,@result ("tab_width" . ,(cdr p-indent-size)))))) + ;; Update indent-size property + (let ((p-indent-size (assoc "indent_size" result)) + (p-tab-width (assoc "tab_width" result))) + (when (and p-indent-size + p-tab-width + (string= (cdr p-indent-size) "tab")) + (setcdr p-indent-size (cdr p-tab-width)))) + + result)) + +;;;###autoload +(defun editorconfig-core-get-properties-hash (&optional file confname confversion) + "Get EditorConfig properties for FILE. +If FILE is not given, use currently visiting file. +Give CONFNAME for basename of config file other than .editorconfig. +If need to specify config format version, give CONFVERSION. + +This function is almost same as `editorconfig-core-get-properties', but returns +hash object instead." + (let ((result (editorconfig-core-get-properties file + confname + confversion)) + (hash (make-hash-table :test 'equal))) + (dolist (prop result) + (puthash (intern (car prop)) + (cdr prop) + hash)) + hash)) + +(provide 'editorconfig-core) + +;;; editorconfig-core.el ends here diff --git a/elpa/editorconfig-20181025.421/editorconfig-fnmatch.el b/elpa/editorconfig-20181025.421/editorconfig-fnmatch.el new file mode 100644 index 00000000..69a0c766 --- /dev/null +++ b/elpa/editorconfig-20181025.421/editorconfig-fnmatch.el @@ -0,0 +1,292 @@ +;;; editorconfig-fnmatch.el --- Glob pattern matching in Emacs lisp + +;; Copyright (C) 2011-2017 EditorConfig Team + +;; Author: EditorConfig Team +;; URL: https://github.com/editorconfig/editorconfig-emacs#readme + +;; See +;; https://github.com/editorconfig/editorconfig-emacs/graphs/contributors +;; or the CONTRIBUTORS file for the list of contributors. + +;; This file is part of EditorConfig Emacs Plugin. + +;; EditorConfig Emacs Plugin 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 of the License, or (at your +;; option) any later version. + +;; EditorConfig Emacs Plugin 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 +;; EditorConfig Emacs Plugin. If not, see . + +;;; Commentary: + +;; editorconfig-fnmatch.el provides a fnmatch implementation with a few +;; extensions. +;; The main usage of this library is glob pattern matching for EditorConfig, but +;; it can also act solely. + +;; editorconfig-fnmatch-p (name pattern) + +;; Test whether NAME match PATTERN. + +;; PATTERN should be a shell glob pattern, and some zsh-like wildcard matchings +;; can be used: + +;; * Matches any string of characters, except path separators (/) +;; ** Matches any string of characters +;; ? Matches any single character +;; [name] Matches any single character in name +;; [^name] Matches any single character not in name +;; {s1,s2,s3} Matches any of the strings given (separated by commas) +;; {min..max} Matches any number between min and max + + +;; This library is a port from editorconfig-core-py library. +;; https://github.com/editorconfig/editorconfig-core-py/blob/master/editorconfig/fnmatch.py + +;;; Code: + +(require 'cl-lib) + +(defvar editorconfig-fnmatch--cache-hashtable + nil + "Cache of shell pattern and its translation.") +;; Clear cache on file reload +(setq editorconfig-fnmatch--cache-hashtable + (make-hash-table :test 'equal)) + + +(defconst editorconfig-fnmatch--left-brace-regexp + "\\(^\\|[^\\]\\){" + "Regular expression for left brace ({).") + +(defconst editorconfig-fnmatch--right-brace-regexp + "\\(^\\|[^\\]\\)}" + "Regular expression for right brace (}).") + + +(defconst editorconfig-fnmatch--numeric-range-regexp + "\\([+-]?[0-9]+\\)\\.\\.\\([+-]?[0-9]+\\)" + "Regular expression for numaric range (like {-3..+3}).") + +(defun editorconfig-fnmatch--match-num (regexp string) + "Return how many times REGEXP is found in STRING." + (let ((num 0)) + ;; START arg does not work as expected in this case + (while (string-match regexp string) + (setq num (1+ num) + string (substring string (match-end 0)))) + num)) + +;;;###autoload +(defun editorconfig-fnmatch-p (string pattern) + "Test whether STRING match PATTERN. + +Matching ignores case if `case-fold-search' is non-nil. + +PATTERN should be a shell glob pattern, and some zsh-like wildcard matchings can +be used: + +* Matches any string of characters, except path separators (/) +** Matches any string of characters +? Matches any single character +[name] Matches any single character in name +[^name] Matches any single character not in name +{s1,s2,s3} Matches any of the strings given (separated by commas) +{min..max} Matches any number between min and max" + (string-match (editorconfig-fnmatch-translate pattern) + string)) + +;;(editorconfig-fnmatch-translate "{a,{-3..3}}.js") +;;(editorconfig-fnmatch-p "1.js" "{a,{-3..3}}.js") + +(defun editorconfig-fnmatch-translate (pattern) + "Translate a shell PATTERN to a regular expression. + +Translation result will be cached, so same translation will not be done twice." + (let ((cached (gethash pattern + editorconfig-fnmatch--cache-hashtable))) + (or cached + (puthash pattern + (editorconfig-fnmatch--do-translate pattern) + editorconfig-fnmatch--cache-hashtable)))) + + +(defun editorconfig-fnmatch--do-translate (pattern &optional nested) + "Translate a shell PATTERN to a regular expression. + +Set NESTED to t when this function is called from itself. + +This function is called from `editorconfig-fnmatch-translate', when no cached +translation is found for PATTERN." + (let ((index 0) + (length (length pattern)) + (brace-level 0) + (in-brackets nil) + ;; List of strings of resulting regexp + (result ()) + (is-escaped nil) + (matching-braces (= (editorconfig-fnmatch--match-num + editorconfig-fnmatch--left-brace-regexp + pattern) + (editorconfig-fnmatch--match-num + editorconfig-fnmatch--right-brace-regexp + pattern))) + + current-char + pos + has-slash + has-comma + num-range) + + (while (< index length) + (if (and (not is-escaped) + (string-match "[^]\\*?[{},/\\-]+" + ;;(string-match "[^]\\*?[{},/\\-]+" "?.a") + pattern + index) + (eq index (match-beginning 0))) + (setq result `(,@result ,(regexp-quote (match-string 0 pattern))) + index (match-end 0) + is-escaped nil) + + (setq current-char (aref pattern index) + index (1+ index)) + + (cl-case current-char + (?* + (setq pos index) + (if (and (< pos length) + (= (aref pattern pos) ?*)) + (setq result `(,@result ".*")) + (setq result `(,@result "[^/]*")))) + + (?? + (setq result `(,@result "."))) + + (?\[ + (if in-brackets + (setq result `(,@result "\\[")) + (if (= (aref pattern index) ?/) + ;; Slash after an half-open bracket + (setq result `(,@result "\\[/") + index (+ index 1)) + (setq pos index + has-slash nil) + (while (and (< pos length) + (not (= (aref pattern pos) ?\])) + (not has-slash)) + (if (and (= (aref pattern pos) ?/) + (not (= (aref pattern (- pos 1)) ?\\))) + (setq has-slash t) + (setq pos (1+ pos)))) + (if has-slash + (setq result `(,@result ,(concat "\\[" + (substring pattern + index + (1+ pos)) + "\\]")) + index (+ pos 2)) + (if (and (< index length) + (memq (aref pattern index) + '(?! ?^))) + (setq index (1+ index) + result `(,@result "[^")) + (setq result `(,@result "["))) + (setq in-brackets t))))) + + (?- + (if in-brackets + (setq result `(,@result "-")) + (setq result `(,@result "\\-")))) + + (?\] + (setq result `(,@result "]") + in-brackets nil)) + + (?{ + (setq pos index + has-comma nil) + (while (and (or (and (< pos length) + (not (= (aref pattern pos) + ?}))) + is-escaped) + (not has-comma)) + (if (and (eq (aref pattern pos) + ?,) + (not is-escaped)) + (setq has-comma t) + (setq is-escaped (and (eq (aref pattern pos) + ?\\) + (not is-escaped)) + pos (1+ pos)))) + (if (and (not has-comma) + (< pos length)) + (let ((pattern-sub (substring pattern index pos))) + (setq num-range (string-match editorconfig-fnmatch--numeric-range-regexp + pattern-sub)) + (if num-range + (let ((number-start (string-to-number (match-string 1 + pattern-sub))) + (number-end (string-to-number (match-string 2 + pattern-sub)))) + (setq result `(,@result ,(concat "\\(?:" + (mapconcat 'number-to-string + (cl-loop for i from number-start to number-end + collect i) + "\\|") + "\\)")))) + (let ((inner (editorconfig-fnmatch--do-translate pattern-sub t))) + (setq result `(,@result ,(format "{%s}" + inner))))) + (setq index (1+ pos))) + (if matching-braces + (setq result `(,@result "\\(?:") + brace-level (1+ brace-level)) + (setq result `(,@result "{"))))) + + (?, + (if (and (> brace-level 0) + (not is-escaped)) + (setq result `(,@result "\\|")) + (setq result `(,@result "\\,")))) + + (?} + (if (and (> brace-level 0) + (not is-escaped)) + (setq result `(,@result "\\)") + brace-level (- brace-level 1)) + (setq result `(,@result "}")))) + + (?/ + (if (and (<= (+ index 3) + (length pattern)) + (string= (substring pattern index (+ index 3)) + "**/")) + (setq result `(,@result "\\(?:/\\|/.*/\\)") + index (+ index 3)) + (setq result `(,@result "/")))) + + (t + (unless (= current-char + ?\\) + (setq result `(,@result ,(regexp-quote (char-to-string current-char))))))) + + (if (= current-char ?\\) + (progn (when is-escaped + (setq result `(,@result "\\\\"))) + (setq is-escaped (not is-escaped))) + (setq is-escaped nil)))) + (unless nested + (setq result `("^" ,@result "\\'"))) + (apply 'concat result))) + +(provide 'editorconfig-fnmatch) + +;;; editorconfig-fnmatch.el ends here diff --git a/elpa/editorconfig-20181025.421/editorconfig-pkg.el b/elpa/editorconfig-20181025.421/editorconfig-pkg.el new file mode 100644 index 00000000..0ac19b26 --- /dev/null +++ b/elpa/editorconfig-20181025.421/editorconfig-pkg.el @@ -0,0 +1,10 @@ +(define-package "editorconfig" "20181025.421" "EditorConfig Emacs Plugin" + '((cl-lib "0.5")) + :authors + '(("EditorConfig Team" . "editorconfig@googlegroups.com")) + :maintainer + '("EditorConfig Team" . "editorconfig@googlegroups.com") + :url "https://github.com/editorconfig/editorconfig-emacs#readme") +;; Local Variables: +;; no-byte-compile: t +;; End: diff --git a/elpa/editorconfig-20181025.421/editorconfig.el b/elpa/editorconfig-20181025.421/editorconfig.el new file mode 100644 index 00000000..fef26ccc --- /dev/null +++ b/elpa/editorconfig-20181025.421/editorconfig.el @@ -0,0 +1,686 @@ +;;; editorconfig.el --- EditorConfig Emacs Plugin + +;; Copyright (C) 2011-2017 EditorConfig Team + +;; Author: EditorConfig Team +;; Version: 0.7.13 +;; URL: https://github.com/editorconfig/editorconfig-emacs#readme +;; Package-Requires: ((cl-lib "0.5")) + +;; See +;; https://github.com/editorconfig/editorconfig-emacs/graphs/contributors +;; or the CONTRIBUTORS file for the list of contributors. + +;; This file is part of EditorConfig Emacs Plugin. + +;; EditorConfig Emacs Plugin 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 of the License, or (at your +;; option) any later version. + +;; EditorConfig Emacs Plugin 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 +;; EditorConfig Emacs Plugin. If not, see . + +;;; Commentary: + +;; EditorConfig helps developers define and maintain consistent +;; coding styles between different editors and IDEs. + +;; The EditorConfig project consists of a file format for defining +;; coding styles and a collection of text editor plugins that enable +;; editors to read the file format and adhere to defined styles. +;; EditorConfig files are easily readable and they work nicely with +;; version control systems. + +;;; Code: +(require 'cl-lib) +(eval-when-compile + (require 'rx) + (defvar tex-indent-basic) + (defvar tex-indent-item) + (defvar tex-indent-arg) + (defvar evil-shift-width)) + +(declare-function editorconfig-core-get-properties-hash + "editorconfig-core" + nil) + +(defgroup editorconfig nil + "EditorConfig Emacs Plugin. + +EditorConfig helps developers define and maintain consistent +coding styles between different editors and IDEs." + :tag "EditorConfig" + :prefix "editorconfig-" + :group 'tools) + +(defcustom editorconfig-exec-path + "editorconfig" + "EditorConfig executable name. + +This executable is invoked by `editorconfig-call-editorconfig-exec'." + :type 'string + :group 'editorconfig) +(define-obsolete-variable-alias + 'edconf-exec-path + 'editorconfig-exec-path + "0.5") + +(defcustom editorconfig-get-properties-function + 'editorconfig-get-properties + "A function which gets EditorConofig properties for current buffer. + +This function will be called with no argument and should return a +hash object containing properties, or nil if any core program is +not available. The hash object should have symbols of property +names as keys and strings of property values as values." + :type 'function + :group 'editorconfig) +(define-obsolete-variable-alias + 'edconf-get-properties-function + 'editorconfig-get-properties-function + "0.5") + +(defcustom editorconfig-mode-lighter " EditorConfig" + "Lighter displayed in mode line +when `editorconfig-mode' is enabled." + :type 'string + :group 'editorconfig) + +(defcustom editorconfig-after-apply-functions () + "A list of functions after loading common EditorConfig settings. + +Each element in this list is a hook function. This hook function +takes one parameter, which is a property hash table. The value +of properties can be obtained through gethash function. + +The hook does not have to be coding style related; you can add +whatever functionality you want. For example, the following is +an example to add a new property emacs_linum to decide whether to +show line numbers on the left: + + (add-hook 'editorconfig-after-apply-functions + '(lambda (props) + (let ((show-line-num (gethash 'emacs_linum props))) + (cond ((equal show-line-num \"true\") (linum-mode 1)) + ((equal show-line-num \"false\") (linum-mode 0))))))" + :type 'hook + :group 'editorconfig) +(define-obsolete-variable-alias + 'edconf-custom-hooks + 'editorconfig-after-apply-functions + "0.5") +(define-obsolete-variable-alias + 'editorconfig-custom-hooks + 'editorconfig-after-apply-functions + "0.7.14") + +(defcustom editorconfig-hack-properties-functions () + "A list of function to alter property values before applying them. + +These functions will be run after loading \".editorconfig\" files and before +applying them to current buffer, so that you can alter some properties from +\".editorconfig\" before they take effect. + +For example, Makefiles always use tab characters for indentation: you can +overwrite \"indent_style\" property when current `major-mode' is a +`makefile-mode' with following code: + + (add-hook 'editorconfig-hack-properties-functions + '(lambda (props) + (when (derived-mode-p makefile-mode) + (puthash 'indent_style \"tab\" props))))" + :type 'hook + :group 'editorconfig) + +(defcustom editorconfig-indentation-alist + ;; For contributors: Sort modes in alphabetical order, please :) + '((apache-mode apache-indent-level) + (awk-mode c-basic-offset) + (c++-mode c-basic-offset) + (c-mode c-basic-offset) + (cmake-mode cmake-tab-width) + (coffee-mode coffee-tab-width) + (cperl-mode cperl-indent-level) + (crystal-mode crystal-indent-level) + (csharp-mode c-basic-offset) + (css-mode css-indent-offset) + (emacs-lisp-mode lisp-indent-offset) + (erlang-mode erlang-indent-level) + (ess-mode ess-indent-offset) + (feature-mode feature-indent-offset + feature-indent-level) + (fsharp-mode fsharp-continuation-offset + fsharp-indent-level + fsharp-indent-offset) + (groovy-mode groovy-indent-offset) + (haskell-mode haskell-indent-spaces + haskell-indent-offset + haskell-indentation-layout-offset + haskell-indentation-left-offset + haskell-indentation-starter-offset + haskell-indentation-where-post-offset + haskell-indentation-where-pre-offset + shm-indent-spaces) + (idl-mode c-basic-offset) + (jade-mode jade-tab-width) + (java-mode c-basic-offset) + (js-mode js-indent-level) + (js-jsx-mode js-indent-level sgml-basic-offset) + (js2-mode js2-basic-offset) + (js2-jsx-mode js2-basic-offset sgml-basic-offset) + (js3-mode js3-indent-level) + (json-mode js-indent-level) + (julia-mode julia-indent-offset) + (latex-mode . editorconfig-set-indentation/latex-mode) + (lisp-mode lisp-indent-offset) + (livescript-mode livescript-tab-width) + (lua-mode lua-indent-level) + (matlab-mode matlab-indent-level) + (mustache-mode mustache-basic-offset) + (nginx-mode nginx-indent-level) + (nxml-mode nxml-child-indent (nxml-attribute-indent . 2)) + (objc-mode c-basic-offset) + (octave-mode octave-block-offset) + (perl-mode perl-indent-level) + ;; No need to change `php-mode-coding-style' value for php-mode + ;; since we run editorconfig later than it resets `c-basic-offset'. + ;; See https://github.com/editorconfig/editorconfig-emacs/issues/116 + ;; for details. + (php-mode c-basic-offset) + (pike-mode c-basic-offset) + (ps-mode ps-mode-tab) + (pug-mode pug-tab-width) + (puppet-mode puppet-indent-level) + (python-mode . editorconfig-set-indentation/python-mode) + (ruby-mode ruby-indent-level) + (rust-mode rust-indent-offset) + (scala-mode scala-indent:step) + (scss-mode css-indent-offset) + (sgml-mode sgml-basic-offset) + (sh-mode sh-basic-offset sh-indentation) + (slim-mode slim-indent-offset) + (tcl-mode tcl-indent-level + tcl-continued-indent-level) + (typescript-mode typescript-indent-level) + (verilog-mode verilog-indent-level + verilog-indent-level-behavioral + verilog-indent-level-declaration + verilog-indent-level-module + verilog-cexp-indent + verilog-case-indent) + (web-mode (web-mode-indent-style . (lambda (size) 2)) + web-mode-attr-indent-offset + web-mode-attr-value-indent-offset + web-mode-code-indent-offset + web-mode-css-indent-offset + web-mode-markup-indent-offset + web-mode-sql-indent-offset + web-mode-block-padding + web-mode-script-padding + web-mode-style-padding) + (yaml-mode yaml-indent-offset)) + "Alist of indentation setting methods by modes. + +Each element looks like (MODE . FUNCTION) or (MODE . INDENT-SPEC-LIST). + +If FUNCTION is provided, it will be called when setting the +indentation. The indent size will be passed. + +If INDENT-SPEC-LIST is provided, each element of it must have one of the +following forms: + + 1. VARIABLE + + It means (VARIABLE . 1). + + 2. (VARIABLE . SPEC) + + Setting VARIABLE according to the type of SPEC: + + - Integer + + The value is (* SPEC INDENT-SIZE); + + - Function + + The value is (funcall SPEC INDENT-SIZE); + + - Any other type. + + The value is SPEC. + +NOTE: Only the **buffer local** value of VARIABLE will be set." + :type '(alist :key-type symbol :value-type sexp) + :risky t + :group 'editorconfig) +(define-obsolete-variable-alias + 'edconf-indentation-alist + 'editorconfig-indentation-alist + "0.5") + +(defcustom editorconfig-exclude-modes () + "List of major mode symbols not to apply properties." + :type '(repeat (symbol :tag "Major Mode")) + :group 'editorconfig) + +(defcustom editorconfig-exclude-regexps + (list (eval-when-compile + (rx string-start (or "http" "https" "ftp" "sftp" "rsync") ":"))) + "List of buffer filename prefix regexp patterns not to apply +properties." + :type '(repeat string) + :group 'editorconfig) + +(defvar editorconfig-properties-hash nil + "Hash object of EditorConfig properties for current buffer. +Set by `editorconfig-apply' and nil if that is not invoked in +current buffer yet.") +(make-variable-buffer-local 'editorconfig-properties-hash) + +(defvar editorconfig-lisp-use-default-indent nil + "Selectively ignore the value of indent_sizefor Lisp files. +Prevents `lisp-indent-offset' from being set selectively. + +nil - `lisp-indent-offset' is always set normally. +t - `lisp-indent-offset' is never set normally + (always use default indent for lisps). +number - `lisp-indent-offset' is not set only if indent_size is + equal to this number. For example, if this is set to 2, + `lisp-indent-offset'will not be set only if indent_size is 2.") + +(defconst editorconfig-unset-value "unset" + "String used to unset properties in .editorconfig .") + +(defun editorconfig-string-integer-p (string) + "Return non-nil if STRING represents integer." + (and (stringp string) + (string-match-p "\\`[0-9]+\\'" string))) + +(defun editorconfig-set-indentation/python-mode (size) + "Set `python-mode' indent size to SIZE." + (set (make-local-variable (if (or (> emacs-major-version 24) + (and (= emacs-major-version 24) + (>= emacs-minor-version 3))) + 'python-indent-offset + 'python-indent)) + size) + ;; For https://launchpad.net/python-mode + (when (boundp 'py-indent-offset) + (set (make-local-variable 'py-indent-offset) size))) + +(defun editorconfig-set-indentation/latex-mode (size) + "Set `latex-mode' indent size to SIZE." + (set (make-local-variable 'tex-indent-basic) size) + (set (make-local-variable 'tex-indent-item) size) + (set (make-local-variable 'tex-indent-arg) (* 2 size)) + ;; For AUCTeX + (when (boundp 'TeX-brace-indent-level) + (set (make-local-variable 'TeX-brace-indent-level) size)) + (when (boundp 'LaTeX-indent-level) + (set (make-local-variable 'LaTeX-indent-level) size)) + (when (boundp 'LaTeX-item-indent) + (set (make-local-variable 'LaTeX-item-indent) (- size)))) + +(defun editorconfig--should-set (size symbol) + "Determines if editorconfig should set SYMBOL using SIZE." + (if (eq symbol 'lisp-indent-offset) + (cond + ((eql nil editorconfig-lisp-use-default-indent) + t) + ((eql t editorconfig-lisp-use-default-indent) + nil) + ((numberp editorconfig-lisp-use-default-indent) + (not (eql size editorconfig-lisp-use-default-indent))) + (t t)) + t)) + +(defun editorconfig-set-indentation (style &optional size tab_width) + "Set indentation type from STYLE, SIZE and TAB_WIDTH." + (make-local-variable 'indent-tabs-mode) + (make-local-variable 'tab-width) + (if (editorconfig-string-integer-p size) + (setq size (string-to-number size)) + (when (not (equal size "tab")) (setq size nil))) + (setq tab-width (cond (tab_width (string-to-number tab_width)) + ((numberp size) size) + (t tab-width))) + (when (equal size "tab") + (setq size tab-width)) + (cond ((equal style "space") + (setq indent-tabs-mode nil)) + ((equal style "tab") + (setq indent-tabs-mode t))) + (when size + (when (featurep 'evil) + (set (make-local-variable 'evil-shift-width) size)) + (let ((parent major-mode) + entry) + ;; Find the closet parent mode of `major-mode' in + ;; `editorconfig-indentation-alist'. + (while (and (not (setq entry (assoc parent editorconfig-indentation-alist))) + (setq parent (get parent 'derived-mode-parent)))) + (when entry + (let ((fn-or-list (cdr entry))) + (cond ((functionp fn-or-list) (funcall fn-or-list size)) + ((listp fn-or-list) + (dolist (elem fn-or-list) + (cond ((and (symbolp elem) + (editorconfig--should-set size elem)) + (set (make-local-variable elem) size)) + ((and (consp elem) + (editorconfig--should-set size (car elem))) + (let ((spec (cdr elem))) + (set (make-local-variable (car elem)) + (cond ((functionp spec) (funcall spec size)) + ((integerp spec) (* spec size)) + (t spec)))))))))))))) + +(defun editorconfig-set-coding-system (end-of-line charset) + "Set buffer coding system by END-OF-LINE and CHARSET." + (let ((eol (cond + ((equal end-of-line "lf") 'undecided-unix) + ((equal end-of-line "cr") 'undecided-mac) + ((equal end-of-line "crlf") 'undecided-dos) + (t 'undecided))) + (cs (cond + ((equal charset "latin1") 'iso-latin-1) + ((equal charset "utf-8") 'utf-8) + ((equal charset "utf-8-bom") 'utf-8-with-signature) + ((equal charset "utf-16be") 'utf-16be-with-signature) + ((equal charset "utf-16le") 'utf-16le-with-signature) + (t 'undecided)))) + (unless (and (eq eol 'undecided) + (eq cs 'undecided)) + (set-buffer-file-coding-system (merge-coding-systems + cs + eol) + nil t)))) + +(defun editorconfig-set-trailing-nl (final-newline) + "Set up requiring final newline (`require-final-newline' and +`mode-require-final-newline') by FINAL-NEWLINE." + (cond + ((equal final-newline "true") + ;; keep prefs around how/when the nl is added, if set - otherwise add on save + (set (make-local-variable 'require-final-newline) (or require-final-newline t)) + (set (make-local-variable 'mode-require-final-newline) (or mode-require-final-newline t))) + ((equal final-newline "false") + ;; FIXME: Add functionality for actually REMOVING any trailing newlines here! + ;; (rather than just making sure we don't automagically ADD a new one) + (set (make-local-variable 'require-final-newline) nil) + (set (make-local-variable 'mode-require-final-newline) nil)))) + +(defun editorconfig-set-trailing-ws (trim-trailing-ws) + "Set up trimming of trailing whitespace at end of lines by +TRIM-TRAILING-WS." + (make-local-variable 'write-file-functions) ;; just current buffer + (when (and (equal trim-trailing-ws "true") + (not buffer-read-only)) + ;; when true we push delete-trailing-whitespace (emacs > 21) + ;; to write-file-functions + (add-to-list + 'write-file-functions + 'delete-trailing-whitespace)) + (when (or (equal trim-trailing-ws "false") + buffer-read-only) + ;; when false we remove every delete-trailing-whitespace + ;; from write-file-functions + (setq + write-file-functions + (delete + 'delete-trailing-whitespace + write-file-functions)))) + +(defun editorconfig-set-line-length (length) + "Set the max line length (`fill-column') to LENGTH." + (when (and (editorconfig-string-integer-p length) + (> (string-to-number length) 0)) + (setq fill-column (string-to-number length)))) + +(defun editorconfig-set-major-mode-from-name (filetype) + "Set buffer `major-mode' by FILETYPE. + +FILETYPE should be s string like `\"ini\"`, if not nil or empty string." + (let ((mode (and filetype + (not (string= filetype + "")) + (intern (concat filetype + "-mode"))))) + (when mode + (if (fboundp mode) + (editorconig-apply-major-mode-safely mode) + (display-warning :error (format "Major-mode `%S' not found" + mode)) + nil)))) + +(defvar editorconfig--apply-major-mode-currently nil + "Used internally.") +(make-variable-buffer-local 'editorconfig--apply-major-mode-currently) +(put 'editorconfig--apply-major-mode-currently + 'permanent-local + t) + +(defun editorconig-apply-major-mode-safely (mode) + "Set `major-mode' to MODE. +Normally `editorconfig-apply' will be hooked so that it runs when changing +`major-mode', so there is a possibility that MODE is called infinitely if +MODE is called naively from inside of `editorconfig-apply'. +This funcion will avoid such cases and set `major-mode' safely. + +Just checking current `major-mode' value is not enough, because it can be +different from MODE value (for example, `conf-mode' will set `major-mode' to +`conf-unix-mode' or another conf mode)." + (cl-assert mode) + (when (and (not (eq mode + editorconfig--apply-major-mode-currently)) + (not (eq mode + major-mode)) + (not (derived-mode-p mode))) + (unwind-protect + (progn + (setq editorconfig--apply-major-mode-currently + mode) + (funcall mode)) + (setq editorconfig--apply-major-mode-currently + nil)))) + +(defun editorconfig--find-mode-from-ext (ext &optional filename) + "Get suitable `major-mode' from EXT and FILENAME. +If FILENAME is omitted filename of current buffer is used." + (cl-assert ext) + (cl-assert (not (string= ext ""))) + (let* ((name (concat (or filename + buffer-file-name) + "." + ext))) + (assoc-default name + auto-mode-alist + 'string-match))) + +(defun editorconfig-set-major-mode-from-ext (ext) + "Set buffer `major-mode' by EXT. + +EXT should be a string like `\"ini\"`, if not nil or empty string." + (cl-assert buffer-file-name) + (when (and ext + (not (string= ext "")) + (not (string= ext editorconfig-unset-value))) + + (let ((mode (editorconfig--find-mode-from-ext ext + buffer-file-name))) + (if mode + (editorconig-apply-major-mode-safely mode) + (display-warning :error (format "Major-mode for `%s' not found" + ext)) + nil)))) + +(defun editorconfig-call-editorconfig-exec () + "Call EditorConfig core and return output." + (let* ((filename (buffer-file-name)) + (filename (and filename (expand-file-name filename)))) + (if filename + (with-temp-buffer + (setq default-directory "/") + (if (eq 0 + (call-process editorconfig-exec-path nil t nil filename)) + (buffer-string) + (error (buffer-string)))) + ""))) + +(defun editorconfig-parse-properties (props-string) + "Create properties hash table from PROPS-STRING." + (let (props-list properties) + (setq props-list (split-string props-string "\n") + properties (make-hash-table :test 'equal)) + (dolist (prop props-list properties) + (let ((key-val (split-string prop " *= *"))) + (when (> (length key-val) 1) + (let ((key (intern (car key-val))) + (val (mapconcat 'identity (cdr key-val) ""))) + (puthash key val properties))))))) + +(defun editorconfig-get-properties-from-exec () + "Get EditorConfig properties of current buffer by calling +`editorconfig-exec-path'." + (if (executable-find editorconfig-exec-path) + (editorconfig-parse-properties (editorconfig-call-editorconfig-exec)) + (error "Unable to find editorconfig executable"))) + +(defun editorconfig-get-properties () + "Get EditorConfig properties of current buffer. + +It calls `editorconfig-get-properties-from-exec' if +`editorconfig-exec-path' is found, otherwise +`editorconfig-core-get-properties-hash'." + (if (and (executable-find editorconfig-exec-path) + (not (file-remote-p buffer-file-name))) + (editorconfig-get-properties-from-exec) + (require 'editorconfig-core) + (editorconfig-core-get-properties-hash))) + +;;;###autoload +(defun editorconfig-find-current-editorconfig () + "Find the closest .editorconfig file for current file." + (interactive) + (eval-and-compile (require 'editorconfig-core)) + (let ((file (editorconfig-core-get-nearest-editorconfig + default-directory))) + (when file + (find-file file)))) + +;;;###autoload +(defun editorconfig-display-current-properties () + "Display EditorConfig properties extracted for current buffer." + (interactive) + (if editorconfig-properties-hash + (let ( + (buf (get-buffer-create "*EditorConfig Properties*")) + (file buffer-file-name) + (props editorconfig-properties-hash)) + (with-current-buffer buf + (erase-buffer) + (insert (format "# EditorConfig for %s\n" file)) + (maphash (lambda (k v) + (insert (format "%S = %s\n" k v))) + props)) + (display-buffer buf)) + (message "Properties are not applied to current buffer yet.") + nil)) + +;;;###autoload +(defun editorconfig-apply () + "Apply EditorConfig properties for current buffer. +This function ignores `editorconfig-exclude-modes' and always +applies available properties." + (interactive) + (when buffer-file-name + (condition-case err + (progn + (unless (functionp editorconfig-get-properties-function) + (error "Invalid editorconfig-get-properties-function value")) + (let ((props (funcall editorconfig-get-properties-function))) + (progn + (condition-case err + (run-hook-with-args 'editorconfig-hack-properties-functions props) + (error + (display-warning 'editorconfig-hack-properties-functions + (concat (error-message-string err) + ". Abort running hook.") + :warning))) + (setq editorconfig-properties-hash props) + (editorconfig-set-indentation (gethash 'indent_style props) + (gethash 'indent_size props) + (gethash 'tab_width props)) + (editorconfig-set-coding-system + (gethash 'end_of_line props) + (gethash 'charset props)) + (editorconfig-set-trailing-nl (gethash 'insert_final_newline props)) + (editorconfig-set-trailing-ws (gethash 'trim_trailing_whitespace props)) + (editorconfig-set-line-length (gethash 'max_line_length props)) + (editorconfig-set-major-mode-from-name (gethash 'file_type_emacs props)) + (editorconfig-set-major-mode-from-ext (gethash 'file_type_ext props)) + (condition-case err + (run-hook-with-args 'editorconfig-after-apply-functions props) + (error + (display-warning 'editorconfig-after-apply-functions + (concat (error-message-string err) + ". Stop running hook.") + :warning)))))) + (error + (display-warning 'editorconfig + (concat (error-message-string err) + ". Styles will not be applied.") + :error))))) + +(defun editorconfig-mode-apply () + "Apply EditorConfig properties for current buffer. +This function does the job only when the major mode is not listed +in `editorconfig-exclude-modes'." + (when (and major-mode + (not (memq major-mode + editorconfig-exclude-modes)) + buffer-file-name + (not (cl-loop for regexp in editorconfig-exclude-regexps + if (string-match regexp buffer-file-name) return t + finally return nil))) + (editorconfig-apply))) + +(defun editorconfig-format-buffer() + "Format buffer according to .editorconfig indent_style and indent_width" + (interactive) + (if (string= (gethash 'indent_style editorconfig-properties-hash) "tab") + (tabify (point-min) (point-max))) + (if (string= (gethash 'indent_style editorconfig-properties-hash) "space") + (untabify (point-min) (point-max))) + (indent-region (point-min) (point-max))) + + +;;;###autoload +(define-minor-mode editorconfig-mode + "Toggle EditorConfig feature. +When enabled EditorConfig properties will be applied to buffers +when first visiting files or changing major modes if the major +mode is not listed in `editorconfig-exclude-modes'." + :global t + :lighter editorconfig-mode-lighter + ;; See https://github.com/editorconfig/editorconfig-emacs/issues/141 for why + ;; not `after-change-major-mode-hook' + (dolist (hook '(change-major-mode-after-body-hook + read-only-mode-hook)) + (if editorconfig-mode + (add-hook hook 'editorconfig-mode-apply) + (remove-hook hook 'editorconfig-mode-apply)))) + +(provide 'editorconfig) + +;;; editorconfig.el ends here + +;; Local Variables: +;; sentence-end-double-space: t +;; End: diff --git a/elpa/editorconfig-20181025.421/editorconfig.info b/elpa/editorconfig-20181025.421/editorconfig.info new file mode 100644 index 00000000..c1a009b2 --- /dev/null +++ b/elpa/editorconfig-20181025.421/editorconfig.info @@ -0,0 +1,305 @@ +This is editorconfig.info, produced by makeinfo version 6.5 from +editorconfig.texi. + +INFO-DIR-SECTION Emacs +START-INFO-DIR-ENTRY +* EditorConfig: (editorconfig). EditorConfig Emacs Plugin. +END-INFO-DIR-ENTRY + + +File: editorconfig.info, Node: Top, Next: Installation, Up: (dir) + +1 EditorConfig Emacs Plugin +*************************** + +This is an EditorConfig (https://editorconfig.org) plugin for Emacs +(https://www.gnu.org/software/emacs/). +* Menu: + +* Installation:: +* Supported properties:: +* Customize:: +* Testing:: +* Submitting Bugs and Feature Requests:: +* License:: + + +File: editorconfig.info, Node: Installation, Next: Supported properties, Prev: Top, Up: Top + +1.1 Installation +================ + +Download the EditorConfig C Core +(https://github.com/editorconfig/editorconfig-core-c) and follow the +instructions in the README and INSTALL files to install it. + + This plugin also has a built-in core library implemented in +Emacs-Lisp, and fallback to it when no core executable is found. + + In either case, copy '.el' files in this repository to +'~/.emacs.d/lisp' and add the following to your '~/.emacs' file: + +(add-to-list 'load-path "~/.emacs.d/lisp") +(require 'editorconfig) +(editorconfig-mode 1) + + Alternatively, you can find the package available on MELPA +(https://melpa.org/#/editorconfig) and MELPA Stable +(https://stable.melpa.org/#/editorconfig) (The Marmalade package +(http://marmalade-repo.org/packages/editorconfig) is deprecated). + + Or if you use *use-package* +(https://www.emacswiki.org/emacs/UsePackage): + +(use-package editorconfig + :ensure t + :config + (editorconfig-mode 1)) + + +File: editorconfig.info, Node: Supported properties, Next: Customize, Prev: Installation, Up: Top + +1.2 Supported properties +======================== + +Current Emacs plugin coverage for EditorConfig's properties +(https://editorconfig.org/#supported-properties): + + * 'indent_style' + * 'indent_size' + * 'tab_width' + * 'end_of_line' + * 'charset' + * 'trim_trailing_whitespace' + * 'insert_final_newline = true' is supported + * 'insert_final_newline = false' is not enforced (as in trailing + newlines actually being removed automagically), we just + buffer-locally override any preferences that would auto-add them to + files '.editorconfig' marks as trailing-newline-free + * 'max_line_length' + * 'file_type_ext' (Experimental) + * 'file_type_emacs' (Experimental) + * 'root' (only used by EditorConfig core) + + Not yet covered properties marked with over-strike - pull requests +implementing missing features warmly welcomed! Typically, you will want +to tie these to native functionality, or the configuration of existing +packages handling the feature. + + As several packages have their own handling of, say, indention, we +might not yet cover some mode you use, but we try to add the ones that +show up on our radar. Similarly, we don't yet hook in to all different +packages for whitespace trimming to inform them about editorconfig +settings, but aim for better coverage of things like ws-trim +(ftp://ftp.lysator.liu.se/pub/emacs/ws-trim.el). +* Menu: + +* File Type:: + + +File: editorconfig.info, Node: File Type, Up: Supported properties + +1.2.1 File Type +--------------- + +This plugin has experimental supports for 'file_type_ext' and +'file_type_emacs', which specify "file types" for files. As for Emacs, +it means 'major-mode' can be set. + + *file_type_ext* When it is set to 'md' for 'a.txt', for example, +'major-mode' will be decided as if the file name would be 'a.txt.md' +(and thus 'markdown-mode' is likely to be used). + + *file_type_emacs* When it is set to 'markdown' for 'a.txt', +'markdown-mode' will be enabled when opening 'a.txt'. + + These property are experimental and their meanings might change in +the future updates. When both are specified, 'file_type_ext' takes +precedence. + + +File: editorconfig.info, Node: Customize, Next: Testing, Prev: Supported properties, Up: Top + +1.3 Customize +============= + +* Menu: + +* editorconfig-after-apply-functions:: +* editorconfig-hack-properties-functions:: +* editorconfig-indentation-alist:: +* editorconfig-exec-path:: +* editorconfig-get-properties-function:: + + +File: editorconfig.info, Node: editorconfig-after-apply-functions, Next: editorconfig-hack-properties-functions, Up: Customize + +1.3.1 'editorconfig-after-apply-functions' +------------------------------------------ + +(Formerly 'editorconfig-custom-hooks') + + A list of functions after loading common EditorConfig settings, where +you can set some custom variables or overwrite existing properties. + + For example, 'web-mode' has several variables for indentation offset +size and EditorConfig sets them at once by 'indent_size'. You may want +to stop indenting only blocks of 'web-mode': it can be achieved by +adding following to your init.el: + +(add-hook 'editorconfig-after-apply-functions + (lambda (hash) (setq web-mode-block-padding 0))) + + You can also define your own custom properties and enable them here. + + +File: editorconfig.info, Node: editorconfig-hack-properties-functions, Next: editorconfig-indentation-alist, Prev: editorconfig-after-apply-functions, Up: Customize + +1.3.2 'editorconfig-hack-properties-functions' +---------------------------------------------- + +A list of function to alter property values before applying them. + + These functions will be run after loading ".editorconfig" files and +before applying them to current buffer, so that you can alter some +properties from ".editorconfig" before they take effect. + + For example, Makefiles always use tab characters for indentation: you +can overwrite "indent_style" property when current 'major-mode' is a +'makefile-mode' with following code: + +(add-hook 'editorconfig-hack-properties-functions + '(lambda (props) + (when (derived-mode-p makefile-mode) + (puthash 'indent_style "tab" props)))) + + +File: editorconfig.info, Node: editorconfig-indentation-alist, Next: editorconfig-exec-path, Prev: editorconfig-hack-properties-functions, Up: Customize + +1.3.3 'editorconfig-indentation-alist' +-------------------------------------- + +Alist of indentation setting methods by modes. + + For the easiest case to add a new support for a major-mode, you just +need to add a pair of major-mode symbol and its indentation variables: + +(add-to-list 'editorconfig-indentation-alist + ;; Just an example, of course EditorConfig has already included this setting! + '(c-mode c-basic-offset)) + + You can also modify this variable with the command M-x +customize-variable [RET] editorconfig-indentation-alist [RET]. For a bit +more complicated cases please take a look at the docstring of this +variable. + + +File: editorconfig.info, Node: editorconfig-exec-path, Next: editorconfig-get-properties-function, Prev: editorconfig-indentation-alist, Up: Customize + +1.3.4 'editorconfig-exec-path' +------------------------------ + +String of 'editorconfig' executable name (command name or full path to +the executable). + + +File: editorconfig.info, Node: editorconfig-get-properties-function, Prev: editorconfig-exec-path, Up: Customize + +1.3.5 'editorconfig-get-properties-function' +-------------------------------------------- + +Function to use to get EditorConfig properties. + + For example, if you always want to use built-in core library instead +of any EditorConfig executable to get properties, add following to your +init.el: + +(set-variable 'editorconfig-get-properties-function + #'editorconfig-core-get-properties-hash) + + Possible known values are: + + * 'editorconfig-get-properties' (default) + * Use 'editorconfig-get-properties-from-exec' when + 'editorconfig-exec-path' executable is found, otherwise use + 'editorconfig-core-get-properties-hash' + + * 'editorconfig-get-properties-from-exec' + * Get properties by executing EditorConfig executable specified + in 'editorconfig-exec-path' + + * 'editorconfig-core-get-properties-hash' + * Always use built-in Emacs-Lisp implementation to get + properties + + +File: editorconfig.info, Node: Testing, Next: Submitting Bugs and Feature Requests, Prev: Customize, Up: Top + +1.4 Testing +=========== + +Make and CMake (https://cmake.org) must be installed to run the tests. + + To run the tests: + +$ make test + + +File: editorconfig.info, Node: Submitting Bugs and Feature Requests, Next: License, Prev: Testing, Up: Top + +1.5 Submitting Bugs and Feature Requests +======================================== + +Bugs, feature requests, and other issues should be submitted to the +issue tracker: https://github.com/editorconfig/editorconfig-emacs/issues + + +File: editorconfig.info, Node: License, Prev: Submitting Bugs and Feature Requests, Up: Top + +1.6 License +=========== + +EditorConfig Emacs Plugin 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 of the +License, 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 this program. If not, see . + + + +Tag Table: +Node: Top208 +Ref: #editorconfig-emacs-plugin337 +Node: Installation575 +Ref: #installation709 +Node: Supported properties1613 +Ref: #supported-properties1769 +Node: File Type3113 +Ref: #file-type3218 +Node: Customize3843 +Ref: #customize3972 +Node: editorconfig-after-apply-functions4167 +Ref: #editorconfig-after-apply-functions4387 +Node: editorconfig-hack-properties-functions4986 +Ref: #editorconfig-hack-properties-functions5253 +Node: editorconfig-indentation-alist5878 +Ref: #editorconfig-indentation-alist6117 +Node: editorconfig-exec-path6672 +Ref: #editorconfig-exec-path6893 +Node: editorconfig-get-properties-function6982 +Ref: #editorconfig-get-properties-function7192 +Node: Testing8045 +Ref: #testing8186 +Node: Submitting Bugs and Feature Requests8293 +Ref: #submitting-bugs-and-feature-requests8490 +Node: License8632 +Ref: #license8755 + +End Tag Table diff --git a/elpa/editorconfig-readme.txt b/elpa/editorconfig-readme.txt new file mode 100644 index 00000000..8f22acf7 --- /dev/null +++ b/elpa/editorconfig-readme.txt @@ -0,0 +1,8 @@ +EditorConfig helps developers define and maintain consistent +coding styles between different editors and IDEs. + +The EditorConfig project consists of a file format for defining +coding styles and a collection of text editor plugins that enable +editors to read the file format and adhere to defined styles. +EditorConfig files are easily readable and they work nicely with +version control systems. diff --git a/elpa/ghub-20181112.1755/buck.el b/elpa/ghub-20181112.1755/buck.el new file mode 100644 index 00000000..141ea900 --- /dev/null +++ b/elpa/ghub-20181112.1755/buck.el @@ -0,0 +1,128 @@ +;;; buck.el --- minuscule client library for the Bitbucket API -*- lexical-binding: t -*- + +;; Copyright (C) 2016-2018 Jonas Bernoulli + +;; Author: Jonas Bernoulli +;; Homepage: https://github.com/magit/ghub +;; Keywords: tools + +;; 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 file 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 copy of the GPL see https://www.gnu.org/licenses/gpl.txt. + +;;; Commentary: + +;; Buck is a library that provides basic support for using the Bitbucket API +;; from Emacs packages. It abstracts access to API resources using only +;; a handful of functions that are not resource-specific. + +;; This library is implemented on top of Ghub. Unlike Ghub, Buck does +;; not support the guided creation of tokens because Bitbucket lacks the +;; features that would be necessary to implement that. Users have to +;; create tokens through the web interface. + +;;; Code: + +(require 'ghub) + +(defconst buck-default-host "api.bitbucket.org/2.0" + "The default host that is used if `buck.host' is not set.") + +;; HEAD and PATCH are not supported according to +;; https://developer.atlassian.com/bitbucket/api/2/reference/meta/uri-uuid + +(cl-defun buck-get (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `GET' request for RESOURCE, with optional query PARAMS. +Like calling `ghub-request' (which see) with \"GET\" as METHOD +and `bitbucket' as FORGE." + (ghub-request "GET" resource params :forge 'bitbucket + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun buck-put (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `PUT' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"PUT\" as METHOD +and `bitbucket' as FORGE." + (ghub-request "PUT" resource params :forge 'bitbucket + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun buck-post (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `POST' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"POST\" as METHOD +and `bitbucket' as FORGE." + (ghub-request "POST" resource params :forge 'bitbucket + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun buck-delete (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `DELETE' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"DELETE\" as METHOD +and `bitbucket' as FORGE." + (ghub-request "DELETE" resource params :forge 'bitbucket + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun buck-request (method resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a request for RESOURCE and return the response body. +Like calling `ghub-request' (which see) with `bitbucket' as FORGE." + (ghub-request method resource params :forge 'bitbucket + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun buck-repository-id (owner name &key username auth host) + "Return the id of the repository specified by OWNER, NAME and HOST." + (substring (cdr (assq 'uuid + (buck-get (format "/repositories/%s/%s" owner name) + nil + :username username :auth auth :host host))) + 1 -1)) + +;;; _ +(provide 'buck) +;;; buck.el ends here diff --git a/elpa/ghub-20181112.1755/dir b/elpa/ghub-20181112.1755/dir new file mode 100644 index 00000000..8392fa02 --- /dev/null +++ b/elpa/ghub-20181112.1755/dir @@ -0,0 +1,18 @@ +This is the file .../info/dir, which contains the +topmost node of the Info hierarchy, called (dir)Top. +The first time you invoke Info you start off looking at this node. + +File: dir, Node: Top This is the top of the INFO tree + + This (the Directory node) gives a menu of major topics. + Typing "q" exits, "H" lists all Info commands, "d" returns here, + "h" gives a primer for first-timers, + "mEmacs" visits the Emacs manual, etc. + + In Emacs, you can click mouse button 2 on a menu item or cross reference + to select it. + +* Menu: + +Emacs +* Ghub: (ghub). Minuscule client library for the Github API. diff --git a/elpa/ghub-20181112.1755/ghub-autoloads.el b/elpa/ghub-20181112.1755/ghub-autoloads.el new file mode 100644 index 00000000..2785cba7 --- /dev/null +++ b/elpa/ghub-20181112.1755/ghub-autoloads.el @@ -0,0 +1,90 @@ +;;; ghub-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "buck" "buck.el" (0 0 0 0)) +;;; Generated autoloads from buck.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "buck" '("buck-default-host"))) + +;;;*** + +;;;### (autoloads nil "ghub" "ghub.el" (0 0 0 0)) +;;; Generated autoloads from ghub.el + +(autoload 'ghub-create-token "ghub" "\ +Create, store and return a new token. + +HOST is the Github instance, usually \"api.github.com\". +USERNAME is the name of a user on that instance. +PACKAGE is the package that will use the token. +SCOPES are the scopes the token is given access to. + +\(fn HOST USERNAME PACKAGE SCOPES)" t nil) + +(autoload 'ghub-token-scopes "ghub" "\ +Return and echo the scopes of the specified token. +This is intended for debugging purposes only. The user +has to provide several values including their password. + +\(fn HOST USERNAME PACKAGE)" t nil) + +(autoload 'ghub-clear-caches "ghub" "\ +Clear all caches that might negatively affect Ghub. + +If a library that is used by Ghub caches incorrect information +such as a mistyped password, then that can prevent Ghub from +asking the user for the correct information again. + +Set `url-http-real-basic-auth-storage' to nil +and call `auth-source-forget+'. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ghub" '("auth-source-netrc-parse-next-interesting@save-match-data" "ghub-"))) + +;;;*** + +;;;### (autoloads nil "ghub-graphql" "ghub-graphql.el" (0 0 0 0)) +;;; Generated autoloads from ghub-graphql.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ghub-graphql" '("ghub-"))) + +;;;*** + +;;;### (autoloads nil "glab" "glab.el" (0 0 0 0)) +;;; Generated autoloads from glab.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "glab" '("glab-default-host"))) + +;;;*** + +;;;### (autoloads nil "gogs" "gogs.el" (0 0 0 0)) +;;; Generated autoloads from gogs.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "gogs" '("gogs-default-host"))) + +;;;*** + +;;;### (autoloads nil "gtea" "gtea.el" (0 0 0 0)) +;;; Generated autoloads from gtea.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "gtea" '("gtea-default-host"))) + +;;;*** + +;;;### (autoloads nil nil ("ghub-pkg.el") (0 0 0 0)) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; ghub-autoloads.el ends here diff --git a/elpa/ghub-20181112.1755/ghub-graphql.el b/elpa/ghub-20181112.1755/ghub-graphql.el new file mode 100644 index 00000000..0f907cb0 --- /dev/null +++ b/elpa/ghub-20181112.1755/ghub-graphql.el @@ -0,0 +1,442 @@ +;;; ghub-graphql.el --- access Github API using GrapthQL -*- lexical-binding: t -*- + +;; Copyright (C) 2016-2018 Jonas Bernoulli + +;; Author: Jonas Bernoulli +;; Homepage: https://github.com/magit/ghub + +;; 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 file 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 copy of the GPL see https://www.gnu.org/licenses/gpl.txt. + +;;; Code: + +(require 'dash) +(require 'ghub) +(require 'graphql) +(require 'treepy) + +(eval-when-compile + (require 'subr-x)) + +;;; Api + +(cl-defun ghub-graphql (graphql &optional variables + &key username auth host + silent + callback errorback value extra) + "Make a GraphQL request using GRAPHQL and VARIABLES. +Return the response as a JSON-like alist. Even if the response +contains `errors', do not raise an error. GRAPHQL is a GraphQL +string. VARIABLES is a JSON-like alist. The other arguments +behave as for `ghub-request' (which see)." + (cl-assert (stringp graphql)) + (cl-assert (not (stringp variables))) + (ghub-request "POST" "/graphql" nil :payload + (json-encode `(("query" . ,graphql) + ,@(and variables `(("variables" ,@variables))))) + :silent silent + :username username :auth auth :host host + :callback callback :errorback errorback + :extra extra :value value)) + +(cl-defun ghub-graphql-rate-limit (&key username auth host) + "Return rate limit information." + (let-alist (ghub-graphql + "query { rateLimit { limit cost remaining resetAt }}" + nil :username username :auth auth :host host) + .data.rateLimit)) + +(cl-defun ghub--repository-id (owner name &key username auth host) + "Return the id of the repository specified by OWNER, NAME and HOST." + (let-alist (ghub-graphql + "query ($owner:String!, $name:String!) { + repository(owner:$owner, name:$name) { id } + }" + `((owner . ,owner) + (name . ,name)) + :username username :auth auth :host host) + .data.repository.id)) + +;;; Api (drafts) + +(defconst ghub-fetch-repository + '(query + (repository + [(owner $owner String!) + (name $name String!)] + name + id + createdAt + updatedAt + nameWithOwner + description + (defaultBranchRef name) + isArchived + isFork + isLocked + isMirror + isPrivate + hasIssuesEnabled + hasWikiEnabled + (licenseInfo name) + (stargazers totalCount) + (watchers totalCount) + (assignableUsers [(:edges t)] + id + login + name) + (issues [(:edges t) + (:singular issue number) + (orderBy ((field . UPDATED_AT) (direction . DESC)))] + number + state + (author login) + title + createdAt + updatedAt + closedAt + locked + (milestone id) + body + (assignees [(:edges t)] + id) + (comments [(:edges t)] + databaseId + (author login) + createdAt + updatedAt + body) + (labels [(:edges t)] + id)) + (labels [(:edges t) + (:singular label id)] + id + name + color + description) + (pullRequests [(:edges t) + (:singular pullRequest number) + (orderBy ((field . UPDATED_AT) (direction . DESC)))] + number + state + (author login) + title + createdAt + updatedAt + closedAt + mergedAt + locked + maintainerCanModify + isCrossRepository + (milestone id) + body + (baseRef name + (repository nameWithOwner)) + (headRef name + (repository (owner login) + nameWithOwner)) + (assignees [(:edges t)] + id) + (comments [(:edges t)] + databaseId + (author login) + createdAt + updatedAt + body) + (labels [(:edges t)] + id))))) + +(cl-defun ghub-fetch-repository (owner name callback + &optional until + &key username auth host forge) + "Asynchronously fetch forge data about the specified repository. +Once all data has been collected, CALLBACK is called with the +data as the only argument." + (ghub--graphql-vacuum ghub-fetch-repository + `((owner . ,owner) + (name . ,name)) + callback until + :narrow '(repository) + :username username + :auth auth + :host host + :forge forge)) + +(cl-defun ghub-fetch-issue (owner name number callback + &optional until + &key username auth host forge) + "Asynchronously fetch forge data about the specified issue. +Once all data has been collected, CALLBACK is called with the +data as the only argument." + (ghub--graphql-vacuum (ghub--graphql-prepare-query + ghub-fetch-repository + `(repository issues (issue . ,number))) + `((owner . ,owner) + (name . ,name)) + callback until + :narrow '(repository issue) + :username username + :auth auth + :host host + :forge forge)) + +(cl-defun ghub-fetch-pullreq (owner name number callback + &optional until + &key username auth host forge) + "Asynchronously fetch forge data about the specified pull-request. +Once all data has been collected, CALLBACK is called with the +data as the only argument." + (ghub--graphql-vacuum (ghub--graphql-prepare-query + ghub-fetch-repository + `(repository pullRequests (pullRequest . ,number))) + `((owner . ,owner) + (name . ,name)) + callback until + :narrow '(repository pullRequest) + :username username + :auth auth + :host host + :forge forge)) + +;;; Internal + +(cl-defstruct (ghub--graphql-req + (:include ghub--req) + (:constructor ghub--make-graphql-req) + (:copier nil)) + (query nil :read-only t) + (variables nil :read-only t) + (until nil :read-only t) + (pages 0 :read-only nil)) + +(cl-defun ghub--graphql-vacuum (query variables callback + &optional until + &key narrow username auth host forge) + "Make a GraphQL request using QUERY and VARIABLES. +See Info node `(ghub)GraphQL Support'." + (unless host + (setq host (ghub--host forge))) + (unless (or username (stringp auth) (eq auth 'none)) + (setq username (ghub--username host forge))) + (ghub--graphql-retrieve + (ghub--make-graphql-req + :url (url-generic-parse-url (concat "https://" host "/graphql")) + :method "POST" + :headers (ghub--headers nil host auth username forge) + :handler 'ghub--graphql-handle-response + :query query + :variables variables + :until until + :callback (if narrow + (lambda (data) + (let ((path narrow) key) + (while (setq key (pop path)) + (setq data (cdr (assq key data))))) + (funcall callback data)) + callback)))) + +(cl-defun ghub--graphql-retrieve (req &optional lineage cursor) + (let ((p (cl-incf (ghub--graphql-req-pages req)))) + (when (> p 1) + (message "Fetching page %s..." p))) + (ghub--retrieve + (let ((json-false nil)) + (ghub--encode-payload + `((query . ,(ghub--graphql-encode + (ghub--graphql-prepare-query + (ghub--graphql-req-query req) + lineage cursor))) + (variables . ,(ghub--graphql-req-variables req))))) + req)) + +(defun ghub--graphql-prepare-query (query &optional lineage cursor) + (when lineage + (setq query (ghub--graphql-narrow-query query lineage cursor))) + (let ((loc (ghub--alist-zip query)) + variables) + (cl-block nil + (while t + (let ((node (treepy-node loc))) + (when (vectorp node) + (let ((alist (cl-coerce node 'list)) + vars) + (when (assq :edges alist) + (push (list 'first 100) vars) + (setq loc (treepy-up loc)) + (setq node (treepy-node loc)) + (setq loc (treepy-replace + loc `(,(car node) + ,(cadr node) + (pageInfo endCursor hasNextPage) + (edges (node ,@(cddr node)))))) + (setq loc (treepy-down loc)) + (setq loc (treepy-next loc))) + (dolist (elt alist) + (cond ((keywordp (car elt))) + ((= (length elt) 3) + (push (list (nth 0 elt) + (nth 1 elt)) vars) + (push (list (nth 1 elt) + (nth 2 elt)) variables)) + ((= (length elt) 2) + (push elt vars)))) + (setq loc (treepy-replace loc (cl-coerce vars 'vector)))))) + (if (treepy-end-p loc) + (let ((node (copy-sequence (treepy-node loc)))) + (when variables + (push (cl-coerce variables 'vector) + (cdr node))) + (cl-return node)) + (setq loc (treepy-next loc))))))) + +(defun ghub--graphql-handle-response (status req) + (let ((buffer (current-buffer))) + (unwind-protect + (progn + (set-buffer-multibyte t) + (let* ((headers (ghub--handle-response-headers status req)) + (payload (ghub--handle-response-payload req)) + (payload (ghub--handle-response-error status payload req)) + (err (plist-get status :error)) + (errors (cdr (assq 'errors payload))) + (errors (and errors + (cons 'ghub-graphql-error errors))) + (data (assq 'data payload)) + (value (ghub--req-value req))) + (setf (ghub--req-value req) value) + (if (or err errors) + (if-let ((errorback (ghub--req-errorback req))) + (funcall errorback (or err errors) headers status req) + (ghub--signal-error (or err errors))) + (ghub--graphql-walk-response value data req)))) + (when (buffer-live-p buffer) + (kill-buffer buffer))))) + +(defun ghub--graphql-walk-response (loc data req) + (if (not loc) + (setf (ghub--req-value req) + (setq loc (ghub--alist-zip data))) + (setq data (ghub--graphql-narrow-data data (ghub--graphql-lineage loc))) + (setf (alist-get 'edges data) + (append (alist-get 'edges (treepy-node loc)) + (or (alist-get 'edges data) + (error "BUG: Expected new nodes")))) + (setq loc (treepy-replace loc data))) + (cl-block nil + (while t + (when (eq (car-safe (treepy-node loc)) 'edges) + (setq loc (treepy-up loc)) + (pcase-let ((`(,key . ,val) (treepy-node loc))) + (let-alist val + (let* ((cursor (and .pageInfo.hasNextPage + .pageInfo.endCursor)) + (until (cdr (assq (intern (format "%s-until" key)) + (ghub--graphql-req-until req)))) + (nodes (mapcar #'cdar .edges)) + (nodes (if until + (--take-while + (or (string> (cdr (assq 'updatedAt it)) until) + (setq cursor nil)) + nodes) + nodes))) + (if cursor + (progn + (setf (ghub--req-value req) loc) + (ghub--graphql-retrieve req + (ghub--graphql-lineage loc) + cursor) + (cl-return)) + (setq loc (treepy-replace loc (cons key nodes)))))))) + (if (not (treepy-end-p loc)) + (setq loc (treepy-next loc)) + (funcall (ghub--req-callback req) + (treepy-root loc)) + (cl-return))))) + +(defun ghub--graphql-lineage (loc) + (let (lineage) + (while (treepy-up loc) + (push (car (treepy-node loc)) lineage) + (setq loc (treepy-up loc))) + lineage)) + +(defun ghub--graphql-narrow-data (data lineage) + (let (key) + (while (setq key (pop lineage)) + (if (consp (car lineage)) + (progn (pop lineage) + (setf data (cadr data))) + (setq data (assq key (cdr data)))))) + data) + +(defun ghub--graphql-narrow-query (query lineage cursor) + (if (consp (car lineage)) + (let* ((child (cddr query)) + (alist (cl-coerce (cadr query) 'list)) + (single (cdr (assq :singular alist)))) + `(,(car single) + ,(vector (list (cadr single) (cdr (car lineage)))) + ,@(if (cdr lineage) + (ghub--graphql-narrow-query child (cdr lineage) cursor) + child))) + (let* ((child (or (assq (car lineage) (cdr query)) + (cl-find-if (lambda (c) + (and (listp c) + (vectorp (cadr c)) + (eq (cadr (assq :singular + (cl-coerce (cadr c) + 'list))) + (car lineage)))) + (cdr query)))) + (object (car query)) + (args (and (vectorp (cadr query)) + (cadr query)))) + `(,object + ,@(and args (list args)) + ,(cond ((cdr lineage) + (ghub--graphql-narrow-query child (cdr lineage) cursor)) + (cursor + `(,(car child) + ,(vconcat `((after ,cursor)) + (cadr child)) + ,@(cddr child))) + (t + child)))))) + +(defun ghub--graphql-encode (g) + (if (symbolp g) + (symbol-name g) + (let* ((object (car g)) + (args (and (vectorp (cadr g)) + (cl-coerce (cadr g) 'list))) + (fields (if args (cddr g) (cdr g)))) + (concat + (graphql--encode-object object) + (and args + (format " (\n%s)" + (mapconcat (pcase-lambda (`(,key ,val)) + (graphql--encode-argument key val)) + args ",\n"))) + (and fields + (format " {\n%s\n}" + (mapconcat #'ghub--graphql-encode fields "\n"))))))) + +(defun ghub--alist-zip (root) + (let ((branchp (lambda (elt) (and (listp elt) (listp (cdr elt))))) + (make-node (lambda (_ children) children))) + (treepy-zipper branchp #'identity make-node root))) + +;;; _ +(provide 'ghub-graphql) +;;; ghub-graphql.el ends here diff --git a/elpa/ghub-20181112.1755/ghub-pkg.el b/elpa/ghub-20181112.1755/ghub-pkg.el new file mode 100644 index 00000000..17fdf062 --- /dev/null +++ b/elpa/ghub-20181112.1755/ghub-pkg.el @@ -0,0 +1,9 @@ +(define-package "ghub" "20181112.1755" "Minuscule client libraries for Git forge APIs." + '((emacs "25.1") + (dash "2.14.1") + (graphql "0.1.1") + (let-alist "1.0.5") + (treepy "1.0.0"))) +;; Local Variables: +;; no-byte-compile: t +;; End: diff --git a/elpa/ghub-20181112.1755/ghub.el b/elpa/ghub-20181112.1755/ghub.el new file mode 100644 index 00000000..fb27147d --- /dev/null +++ b/elpa/ghub-20181112.1755/ghub.el @@ -0,0 +1,952 @@ +;;; ghub.el --- minuscule client libraries for Git forge APIs -*- lexical-binding: t -*- + +;; Copyright (C) 2016-2018 Jonas Bernoulli + +;; Author: Jonas Bernoulli +;; Homepage: https://github.com/magit/ghub +;; Keywords: tools + +;; 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 file 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 copy of the GPL see https://www.gnu.org/licenses/gpl.txt. + +;;; Commentary: + +;; Ghub provides basic support for using the APIs of various Git forges +;; from Emacs packages. Originally it only supported the Github REST +;; API, but now it also supports the Github GraphQL API as well as the +;; REST APIs of Gitlab, Gitea, Gogs and Bitbucket. + +;; Ghub abstracts access to API resources using only a handful of basic +;; functions such as `ghub-get'. These are convenience wrappers around +;; `ghub-request'. Additional forge-specific wrappers like `glab-put', +;; `gtea-put', `gogs-post' and `buck-delete' are also available. Ghub +;; does not provide any resource-specific functions, with the exception +;; of `FORGE-repository-id'. + +;; When accessing Github, then Ghub handles the creation and storage of +;; access tokens using a setup wizard to make it easier for users to get +;; started. The tokens for other forges have to be created manually. + +;; Ghub is intentionally limited to only provide these two essential +;; features — basic request functions and guided setup — to avoid being +;; too opinionated, which would hinder wide adoption. It is assumed that +;; wide adoption would make life easier for users and maintainers alike, +;; because then all packages that talk to forge APIs could be configured +;; the same way. + +;; Please consult the manual (info "ghub") for more information. + +;;; Code: + +(require 'auth-source) +(require 'cl-lib) +(require 'json) +(require 'let-alist) +(require 'url) +(require 'url-auth) +(require 'url-http) + +(eval-when-compile + (require 'subr-x)) + +(defvar url-callback-arguments) +(defvar url-http-end-of-headers) +(defvar url-http-extra-headers) +(defvar url-http-response-status) + +;;; Settings + +(defconst ghub-default-host "api.github.com" + "The default host that is used if `ghub.host' is not set.") + +(defvar ghub-github-token-scopes '(repo) + "The Github API scopes that your private tools need. + +The token that is created based on the value of this variable +is used when `ghub-request' (or one of its wrappers) is called +without providing a value for AUTH. Packages should always +identify themselves using that argument, but when you use Ghub +directly in private tools, then that is not necessary and the +request is made on behalf of the `ghub' package itself, aka on +behalf of some private tool. + +By default the only requested scope is `repo' because that is +sufficient as well as required for most common uses. This and +other scopes are documented at URL `https://magit.vc/goto/2e586d36'. + +If your private tools need other scopes, then you have to add +them here *before* creating the token. Alternatively you can +edit the scopes of an existing token using the web interface +at URL `https://github.com/settings/tokens'.") + +(defvar ghub-override-system-name nil + "If non-nil, the string used to identify the local machine. +If this is nil, then the value returned by `system-name' is +used instead.") + +;;; Request +;;;; Object + +(cl-defstruct (ghub--req + (:constructor ghub--make-req) + (:copier nil)) + (url nil :read-only nil) + (forge nil :read-only t) + (silent nil :read-only t) + (method nil :read-only t) + (headers nil :read-only t) + (handler nil :read-only t) + (unpaginate nil :read-only nil) + (noerror nil :read-only t) + (reader nil :read-only t) + (callback nil :read-only t) + (errorback nil :read-only t) + (value nil :read-only nil) + (extra nil :read-only nil)) + +(defalias 'ghub-req-extra 'ghub--req-extra) + +;;;; API + +(define-error 'ghub-error "Ghub/Url Error" 'error) +(define-error 'ghub-http-error "HTTP Error" 'ghub-error) + +(defvar ghub-response-headers nil + "The headers returned in response to the last request. +`ghub-request' returns the response body and stores the +response headers in this variable.") + +(cl-defun ghub-head (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `HEAD' request for RESOURCE, with optional query PARAMS. +Like calling `ghub-request' (which see) with \"HEAD\" as METHOD." + (ghub-request "HEAD" resource params + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun ghub-get (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `GET' request for RESOURCE, with optional query PARAMS. +Like calling `ghub-request' (which see) with \"GET\" as METHOD." + (ghub-request "GET" resource params + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun ghub-put (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `PUT' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"PUT\" as METHOD." + (ghub-request "PUT" resource params + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun ghub-post (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `POST' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"POST\" as METHOD." + (ghub-request "POST" resource params + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun ghub-patch (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `PATCH' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"PATCH\" as METHOD." + (ghub-request "PATCH" resource params + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun ghub-delete (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `DELETE' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"DELETE\" as METHOD." + (ghub-request "DELETE" resource params + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun ghub-request (method resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host forge + callback errorback value extra) + "Make a request for RESOURCE and return the response body. + +Also place the response header in `ghub-response-headers'. + +METHOD is the HTTP method, given as a string. +RESOURCE is the resource to access, given as a string beginning + with a slash. + +PARAMS, QUERY, PAYLOAD and HEADERS are alists used to specify + data. The Github API documentation is vague on how data has + to be transmitted and for a particular resource usually just + talks about \"parameters\". Generally speaking when the METHOD + is \"HEAD\" or \"GET\", then they have to be transmitted as a + query, otherwise as a payload. +Use PARAMS to automatically transmit like QUERY or PAYLOAD would + depending on METHOD. +Use QUERY to explicitly transmit data as a query. +Use PAYLOAD to explicitly transmit data as a payload. + Instead of an alist, PAYLOAD may also be a string, in which + case it gets encoded as UTF-8 but is otherwise transmitted as-is. +Use HEADERS for those rare resources that require that the data + is transmitted as headers instead of as a query or payload. + When that is the case, then the API documentation usually + mentions it explicitly. + +If SILENT is non-nil, then don't message progress reports and + the like. + +If UNPAGINATE is t, then make as many requests as necessary to + get all values. If UNPAGINATE is a natural number, then get + at most that many pages. For any other non-nil value raise + an error. +If NOERROR is non-nil, then do not raise an error if the request + fails and return nil instead. If NOERROR is `return', then + return the error payload instead of nil. +If READER is non-nil, then it is used to read and return from the + response buffer. The default is `ghub--read-json-payload'. + For the very few resources that do not return JSON, you might + want to use `ghub--decode-payload'. + +If USERNAME is non-nil, then make a request on behalf of that + user. It is better to specify the user using the Git variable + `github.user' for \"api.github.com\", or `github.HOST.user' if + connecting to a Github Enterprise instance. + +Each package that uses `ghub' should use its own token. If AUTH + is nil, then the generic `ghub' token is used instead. This + is only acceptable for personal utilities. A packages that + is distributed to other users should always use this argument + to identify itself, using a symbol matching its name. + + Package authors who find this inconvenient should write a + wrapper around this function and possibly for the + method-specific functions as well. + + Some symbols have a special meaning. `none' means to make an + unauthorized request. `basic' means to make a password based + request. If the value is a string, then it is assumed to be + a valid token. `basic' and an explicit token string are only + intended for internal and debugging uses. + + If AUTH is a package symbol, then the scopes are specified + using the variable `AUTH-github-token-scopes'. It is an error + if that is not specified. See `ghub-github-token-scopes' for + an example. + +If HOST is non-nil, then connect to that Github instance. This + defaults to \"api.github.com\". When a repository is connected + to a Github Enterprise instance, then it is better to specify + that using the Git variable `github.host' instead of using this + argument. + +If FORGE is `gitlab', then connect to Gitlab.com or, depending + on HOST, to another Gitlab instance. This is only intended for + internal use. Instead of using this argument you should use + function `glab-request' and other `glab-*' functions. + +If CALLBACK and/or ERRORBACK is non-nil, then make one or more + asynchronous requests and call CALLBACK or ERRORBACK when + finished. If an error occurred, then call ERRORBACK, or if + that is nil, then CALLBACK. When no error occurred then call + CALLBACK. When making asynchronous requests, then no errors + are signaled, regardless of the value of NOERROR. + +Both callbacks are called with four arguments. + 1. For CALLBACK, the combined value of the retrieved pages. + For ERRORBACK, the error that occured when retrieving the + last page. + 2. The headers of the last page as an alist. + 3. Status information provided by `url-retrieve'. Its `:error' + property holds the same information as ERRORBACK's first + argument. + 4. A `ghub--req' struct, which can be passed to `ghub-continue' + (which see) to retrieve the next page, if any." + (cl-assert (or (booleanp unpaginate) (natnump unpaginate))) + (unless (string-prefix-p "/" resource) + (setq resource (concat "/" resource))) + (unless host + (setq host (ghub--host forge))) + (unless (or username (stringp auth) (eq auth 'none)) + (setq username (ghub--username host forge))) + (cond ((not params)) + ((member method '("GET" "HEAD")) + (when query + (error "PARAMS and QUERY are mutually exclusive for METHOD %S" + method)) + (setq query params)) + (t + (when payload + (error "PARAMS and PAYLOAD are mutually exclusive for METHOD %S" + method)) + (setq payload params))) + (when (or callback errorback) + (setq noerror t)) + (ghub--retrieve + (ghub--encode-payload payload) + (ghub--make-req + :url (url-generic-parse-url + (concat "https://" host resource + (and query (concat "?" (ghub--url-encode-params query))))) + :forge forge + :silent silent + ;; Encode in case caller used (symbol-name 'GET). #35 + :method (encode-coding-string method 'utf-8) + :headers (ghub--headers headers host auth username forge) + :handler 'ghub--handle-response + :unpaginate unpaginate + :noerror noerror + :reader reader + :callback callback + :errorback errorback + :value value + :extra extra))) + +(defun ghub-continue (req) + "If there is a next page, then retrieve that. + +This function is only intended to be called from callbacks. If +there is a next page, then retrieve that and return the buffer +that the result will be loaded into, or t if the process has +already completed. If there is no next page, then return nil. + +Callbacks are called with four arguments (see `ghub-request'). +The forth argument is a `ghub--req' struct, intended to be passed +to this function. A callback may use the struct's `extra' slot +to pass additional information to the callback that will be +called after the next request has finished. Use the function +`ghub-req-extra' to get and set the value of this slot." + (and (assq 'next (ghub-response-link-relations req)) + (or (ghub--retrieve nil req) t))) + +(cl-defun ghub-wait (resource &optional duration &key username auth host) + "Busy-wait up to DURATION seconds for RESOURCE to become available. + +DURATION specifies how many seconds to wait at most. It defaults +to 64 seconds. The first attempt is made immediately, the second +after two seconds, and each subsequent attempt is made after +waiting as long again as we already waited between all preceding +attempts combined. + +See `ghub-request' for information about the other arguments." + (unless duration + (setq duration 64)) + (with-local-quit + (let ((total 0)) + (while (not (ghub-get resource nil + :noerror t + :username username + :auth auth + :host host)) + (message "Waited (%3ss of %ss) for %s..." total duration resource) + (if (= total duration) + (error "Github is taking too long to create %s" resource) + (if (> total 0) + (let ((wait (min total (- duration total)))) + (sit-for wait) + (cl-incf total wait)) + (sit-for (setq total 2)))))))) + +(defun ghub-response-link-relations (req &optional headers payload) + "Return an alist of link relations in HEADERS. +If optional HEADERS is nil, then return those that were +previously stored in the variable `ghub-response-headers'. + +When accessing a Bitbucket instance then the link relations +are in PAYLOAD instead of HEADERS, making their API merely +RESTish and forcing this function to append those relations +to the value of `ghub-response-headers', for later use when +this function is called with nil for PAYLOAD." + (if (eq (ghub--req-forge req) 'bitbucket) + (if payload + (let* ((page (cl-mapcan (lambda (key) + (when-let ((elt (assq key payload))) + (list elt))) + '(size page pagelen next previous))) + (headers (cons (cons 'link-alist page) headers))) + (if (and req (or (ghub--req-callback req) + (ghub--req-errorback req))) + (setq-local ghub-response-headers headers) + (setq-default ghub-response-headers headers)) + page) + (cdr (assq 'link-alist ghub-response-headers))) + (when-let ((rels (cdr (assoc "Link" (or headers ghub-response-headers))))) + (mapcar (lambda (elt) + (pcase-let ((`(,url ,rel) (split-string elt "; "))) + (cons (intern (substring rel 5 -1)) + (substring url 1 -1)))) + (split-string rels ", "))))) + +(cl-defun ghub-repository-id (owner name &key username auth host forge) + "Return the id of the specified repository." + (let ((fn (intern (format "%s-repository-id" (or forge 'ghub))))) + (funcall (if (eq fn 'ghub-repository-id) 'ghub--repository-id fn) + owner name :username username :auth auth :host host))) + +;;;; Internal + +(cl-defun ghub--retrieve (payload req) + (let ((url-request-extra-headers + (let ((headers (ghub--req-headers req))) + (if (functionp headers) (funcall headers) headers))) + (url-request-method (ghub--req-method req)) + (url-request-data payload) + (url-show-status nil) + (url (ghub--req-url req)) + (handler (ghub--req-handler req)) + (silent (ghub--req-silent req))) + (if (or (ghub--req-callback req) + (ghub--req-errorback req)) + (url-retrieve url handler (list req) silent) + ;; When this function has already been called, then it is a + ;; no-op. Otherwise it sets `url-registered-auth-schemes' among + ;; other things. If we didn't ensure that it has been run, then + ;; `url-retrieve-synchronously' would do it, which would cause + ;; the value that we let-bind below to be overwritten, and the + ;; "default" value to be lost outside the let-binding. + (url-do-setup) + (with-current-buffer + (let ((url-registered-auth-schemes + '(("basic" ghub--basic-auth-errorback . 10)))) + (url-retrieve-synchronously url silent)) + (funcall handler (car url-callback-arguments) req))))) + +(defun ghub--handle-response (status req) + (let ((buffer (current-buffer))) + (unwind-protect + (progn + (set-buffer-multibyte t) + (let* ((unpaginate (ghub--req-unpaginate req)) + (headers (ghub--handle-response-headers status req)) + (payload (ghub--handle-response-payload req)) + (payload (ghub--handle-response-error status payload req)) + (value (ghub--handle-response-value payload req)) + (next (cdr (assq 'next (ghub-response-link-relations + req headers payload))))) + (when (numberp unpaginate) + (cl-decf unpaginate)) + (setf (ghub--req-url req) + (url-generic-parse-url next)) + (setf (ghub--req-unpaginate req) unpaginate) + (or (and next + unpaginate + (or (eq unpaginate t) + (> unpaginate 0)) + (ghub-continue req)) + (let ((callback (ghub--req-callback req)) + (errorback (ghub--req-errorback req)) + (err (plist-get status :error))) + (cond ((and err errorback) + (funcall errorback err headers status req)) + (callback + (funcall callback value headers status req)) + (t value)))))) + (when (buffer-live-p buffer) + (kill-buffer buffer))))) + +(defun ghub--handle-response-headers (status req) + (goto-char (point-min)) + (forward-line 1) + (let (headers) + (while (re-search-forward "^\\([^:]*\\): \\(.+\\)" + url-http-end-of-headers t) + (push (cons (match-string 1) + (match-string 2)) + headers)) + (setq headers (nreverse headers)) + (unless url-http-end-of-headers + (error "BUG: missing headers %s" (plist-get status :error))) + (goto-char (1+ url-http-end-of-headers)) + (if (and req (or (ghub--req-callback req) + (ghub--req-errorback req))) + (setq-local ghub-response-headers headers) + (setq-default ghub-response-headers headers)) + headers)) + +(defun ghub--handle-response-error (status payload req) + (let ((noerror (ghub--req-noerror req)) + (err (plist-get status :error))) + (if err + (if noerror + (if (eq noerror 'return) + payload + (setcdr (last err) (list payload)) + nil) + (ghub--signal-error err payload)) + payload))) + +(defun ghub--signal-error (err &optional payload) + (pcase-let ((`(,symb . ,data) err)) + (if (eq symb 'error) + (if (eq (car-safe data) 'http) + (signal 'ghub-http-error + (let ((code (car (cdr-safe data)))) + (list code + (nth 2 (assq code url-http-codes)) + payload))) + (signal 'ghub-error data)) + (signal symb data)))) + +(defun ghub--handle-response-value (payload req) + (setf (ghub--req-value req) + (nconc (ghub--req-value req) + (if-let ((nested (and (eq (ghub--req-forge req) 'bitbucket) + (assq 'values payload)))) + (cdr nested) + payload)))) + +(defun ghub--handle-response-payload (req) + (funcall (or (ghub--req-reader req) + 'ghub--read-json-payload) + url-http-response-status)) + +(defun ghub--read-json-payload (_status) + (let ((raw (ghub--decode-payload))) + (and raw + (condition-case nil + (let ((json-object-type 'alist) + (json-array-type 'list) + (json-key-type 'symbol) + (json-false nil) + (json-null nil)) + (json-read-from-string raw)) + (json-readtable-error + `((message + . ,(if (looking-at "") + (if (re-search-forward + "

\\(?:\\)?\\([^<]+\\)" nil t) + (match-string 1) + "error description missing") + (string-trim (buffer-substring (point) (point-max))))) + (documentation_url + . "https://github.com/magit/ghub/wiki/Github-Errors"))))))) + +(defun ghub--decode-payload (&optional _status) + (and (not (eobp)) + (decode-coding-string + (buffer-substring-no-properties (point) (point-max)) + 'utf-8))) + +(defun ghub--encode-payload (payload) + (and payload + (progn + (unless (stringp payload) + (setq payload (json-encode-list payload))) + (encode-coding-string payload 'utf-8)))) + +(defun ghub--url-encode-params (params) + (mapconcat (lambda (param) + (pcase-let ((`(,key . ,val) param)) + (concat (url-hexify-string (symbol-name key)) "=" + (if (integerp val) + (number-to-string val) + (url-hexify-string val))))) + params "&")) + +;;; Authentication +;;;; API + +;;;###autoload +(defun ghub-create-token (host username package scopes) + "Create, store and return a new token. + +HOST is the Github instance, usually \"api.github.com\". +USERNAME is the name of a user on that instance. +PACKAGE is the package that will use the token. +SCOPES are the scopes the token is given access to." + (interactive + (pcase-let ((`(,host ,username ,package) + (ghub--read-triplet))) + (list host username package + (split-string + (read-string + "Scopes (separated by commas): " + (mapconcat #'symbol-name + (symbol-value + (intern (format "%s-github-token-scopes" package))) + ",")) + "," t "[\s\t]+")))) + (let ((user (ghub--ident username package))) + (cl-destructuring-bind (save token) + (ghub--auth-source-get (list :save-function :secret) + :create t :host host :user user + :secret + (cdr (assq 'token + (ghub-post + "/authorizations" + `((scopes . ,scopes) + (note . ,(ghub--ident-github package))) + :username username :auth 'basic :host host)))) + ;; Build-in back-ends return a function that does the actual + ;; saving, while for some third-party back-ends ":create t" + ;; is enough. + (when (functionp save) + (funcall save)) + ;; If the Auth-Source cache contains the information that there + ;; is no value, then setting the value does not invalidate that + ;; now incorrect information. + (auth-source-forget (list :host host :user user)) + token))) + +;;;###autoload +(defun ghub-token-scopes (host username package) + "Return and echo the scopes of the specified token. +This is intended for debugging purposes only. The user +has to provide several values including their password." + (interactive (ghub--read-triplet)) + (let ((scopes + (cdr (assq 'scopes (ghub--get-token-plist host username package))))) + (when (called-interactively-p 'any) + ;; Also show the input values to make it easy for package + ;; authors to verify that the user has done it correctly. + (message "Scopes for %s@%s: %S" + (ghub--ident username package) + host scopes)) + scopes)) + +;;;###autoload +(defun ghub-clear-caches () + "Clear all caches that might negatively affect Ghub. + +If a library that is used by Ghub caches incorrect information +such as a mistyped password, then that can prevent Ghub from +asking the user for the correct information again. + +Set `url-http-real-basic-auth-storage' to nil +and call `auth-source-forget+'." + (interactive) + (setq url-http-real-basic-auth-storage nil) + (auth-source-forget+)) + +;;;; Internal + +(defun ghub--headers (headers host auth username forge) + (push (cons "Content-Type" "application/json") headers) + (if (eq auth 'none) + headers + (unless (or username (stringp auth)) + (setq username (ghub--username host forge))) + (lambda () + (if (eq auth 'basic) + (cons (cons "Authorization" (ghub--basic-auth host username)) + headers) + (cons (ghub--auth host auth username forge) headers))))) + +(defun ghub--auth (host auth &optional username forge) + (unless username + (setq username (ghub--username host))) + (if (eq auth 'basic) + (cl-ecase forge + ((nil github gitea gogs bitbucket) + (cons "Authorization" (ghub--basic-auth host username))) + (gitlab + (error "Gitlab does not support basic authentication"))) + (cons (cl-ecase forge + ((nil github gitea gogs bitbucket) + "Authorization") + (gitlab + "Private-Token")) + (concat + (and (not (eq forge 'gitlab)) "token ") + (encode-coding-string + (cl-typecase auth + (string auth) + (null (ghub--token host username 'ghub nil forge)) + (symbol (ghub--token host username auth nil forge)) + (t (signal 'wrong-type-argument + `((or stringp symbolp) ,auth)))) + 'utf-8))))) + +(defun ghub--basic-auth (host username) + (let ((url (url-generic-parse-url (concat "https://" host)))) + (setf (url-user url) username) + (url-basic-auth url t))) + +(defun ghub--basic-auth-errorback (url &optional prompt _overwrite _realm _args) + ;; This gets called twice. Do nothing the first time, + ;; when PROMPT is nil. See `url-get-authentication'. + (when prompt + (if (assoc "X-GitHub-OTP" (ghub--handle-response-headers nil nil)) + (progn + (setq url-http-extra-headers + `(("Content-Type" . "application/json") + ("X-GitHub-OTP" . ,(ghub--read-2fa-code)) + ;; Without "Content-Type" and "Authorization". + ;; The latter gets re-added from the return value. + ,@(cddr url-http-extra-headers))) + ;; Return the cached values, they are correct. + (url-basic-auth url nil nil nil)) + ;; Remove the invalid cached values and fail, which + ;; is better than the invalid values sticking around. + (setq url-http-real-basic-auth-storage + (cl-delete (format "%s:%d" (url-host url) (url-port url)) + url-http-real-basic-auth-storage + :test #'equal :key #'car)) + nil))) + +(defun ghub--token (host username package &optional nocreate forge) + (let* ((user (ghub--ident username package)) + (token + (or (car (ghub--auth-source-get (list :secret) + :host host :user user)) + (progn + ;; Auth-Source caches the information that there is no + ;; value, but in our case that is a situation that needs + ;; fixing so we want to keep trying by invalidating that + ;; information. + ;; The (:max 1) is needed and has to be placed at the + ;; end for Emacs releases before 26.1. See #24, #64. + (auth-source-forget (list :host host :user user :max 1)) + (and (not nocreate) + (cl-ecase forge + ((nil github) + (ghub--confirm-create-token host username package)) + ((gitlab gitea gogs bitbucket) + (error "Required %s token (%S for %S) does not exist. +See https://magit.vc/manual/ghub/Support-for-Other-Forges.html for instructions." + (capitalize (symbol-name forge)) + user host)))))))) + (if (functionp token) (funcall token) token))) + +(defun ghub--host (&optional forge) + (cl-ecase forge + ((nil github) + (or (ignore-errors (car (process-lines "git" "config" "github.host"))) + ghub-default-host)) + (gitlab + (or (ignore-errors (car (process-lines "git" "config" "gitlab.host"))) + (bound-and-true-p glab-default-host))) + (gitea + (or (ignore-errors (car (process-lines "git" "config" "gitea.host"))) + (bound-and-true-p gtea-default-host))) + (gogs + (or (ignore-errors (car (process-lines "git" "config" "gogs.host"))) + (bound-and-true-p gogs-default-host))) + (bitbucket + (or (ignore-errors (car (process-lines "git" "config" "bitbucket.host"))) + (bound-and-true-p buck-default-host))))) + +(defun ghub--username (host &optional forge) + (let ((var + (cl-ecase forge + ((nil github) + (if (equal host ghub-default-host) + "github.user" + (format "github.%s.user" host))) + (gitlab + (if (equal host "gitlab.com/api/v4") + "gitlab.user" + (format "gitlab.%s.user" host))) + (bitbucket + (if (equal host "api.bitbucket.org/2.0") + "bitbucket.user" + (format "bitbucket.%s.user" host))) + (gitea + (when (zerop (call-process "git" nil nil nil "config" "gitea.host")) + (error "gitea.host is set but always ignored")) + (format "gitea.%s.user" host)) + (gogs + (when (zerop (call-process "git" nil nil nil "config" "gogs.host")) + (error "gogs.host is set but always ignored")) + (format "gogs.%s.user" host))))) + (condition-case nil + (car (process-lines "git" "config" var)) + (error + (let ((user (read-string + (format "Git variable `%s' is unset. Set to: " var)))) + (or (and user (progn (call-process "git" nil nil nil + "config" "--global" var user) + user)) + (user-error "Abort"))))))) + +(defun ghub--ident (username package) + (format "%s^%s" username package)) + +(defun ghub--ident-github (package) + (format "Emacs package %s @ %s" + package + (or ghub-override-system-name (system-name)))) + +(defun ghub--package-scopes (package) + (let ((var (intern (format "%s-github-token-scopes" package)))) + (if (boundp var) + (symbol-value var) + (error "%s fails to define %s" package var)))) + +(defun ghub--confirm-create-token (host username package) + (let* ((ident (ghub--ident-github package)) + (scopes (ghub--package-scopes package)) + (max-mini-window-height 40)) + (if (let ((message-log-max nil)) + (yes-or-no-p + (format + "Such a Github API token is not available: + + Host: %s + User: %s + Package: %s + + Scopes requested in `%s-github-token-scopes':\n%s + Store on Github as:\n %S + Store locally according to option `auth-sources':\n %S +%s +If in doubt, then abort and first view the section of +the Ghub documentation called \"Interactively Creating +and Storing a Token\". + +Otherwise confirm and then provide your Github username and +password at the next two prompts. Depending on the backend +you might have to provide a passphrase and confirm that you +really want to save the token. + +Create and store such a token? " + host username package package + (mapconcat (lambda (scope) (format " %s" scope)) scopes "\n") + ident auth-sources + (if (and (stringp (car auth-sources)) + (not (string-suffix-p ".gpg" (car auth-sources)))) + (format " +WARNING: The token will be stored unencrypted in %S. + If you don't want that, you have to abort and customize + the `auth-sources' option.\n" (car auth-sources)) + "")))) + (condition-case ghub--create-token-error + ;; Naively attempt to create the token since the user told us to + (ghub-create-token host username package scopes) + ;; The API _may_ respond with the fact that a token of the name + ;; we wanted already exists. At this point we're out of luck. We + ;; don't have a token (otherwise why would we be here?) and, if + ;; the user is using SMS 2FA, we have no way of telling GitHub + ;; to send a new 2FA code to the user other than sending a POST + ;; to /authorizations which is ugly. + ;; + ;; If they are not using SMS 2FA then we could try to delete the + ;; existing token (which will require them to hand us another + ;; OTP for the delete request) and then call create again, + ;; possibly requiring _another_ OTP if they don't do things fast + ;; enough, but this is only because non-SMS 2FA doesn't require + ;; any action on GitHub's part. + ;; + ;; GitHub does hand us a header that indicates what type of 2FA + ;; is in use, but it's not currently available in this location + ;; and would make the following code which is already quite + ;; complicated even more complicated. So in the interest of + ;; simplicity it's better to error out here and ask the user to + ;; take action. This situation should almost never arise anyway. + (ghub-http-error + (if (string-equal (let-alist (nth 3 ghub--create-token-error) + (car .errors.code)) + "already_exists") + (error "\ +A token named %S already exists on Github. \ +Please visit https://github.com/settings/tokens and delete it." ident)))) + (user-error "Abort")))) + +(defun ghub--get-token-id (host username package) + (let ((ident (ghub--ident-github package))) + (cl-some (lambda (x) + (let-alist x + (and (equal .app.name ident) .id))) + (ghub-get "/authorizations" + '((per_page . 100)) + :unpaginate t + :username username :auth 'basic :host host)))) + +(defun ghub--get-token-plist (host username package) + (ghub-get (format "/authorizations/%s" + (ghub--get-token-id host username package)) + nil :username username :auth 'basic :host host)) + +(defun ghub--delete-token (host username package) + (ghub-delete (format "/authorizations/%s" + (ghub--get-token-id host username package)) + nil :username username :auth 'basic :host host)) + +(defun ghub--read-triplet () + (let ((host (read-string "Host: " (ghub--host)))) + (list host + (read-string "Username: " (ghub--username host)) + (intern (read-string "Package: " "ghub"))))) + +(defvar ghub--2fa-cache nil) + +(defun ghub--read-2fa-code () + (let ((code (read-number "Two-factor authentication code: " + (and ghub--2fa-cache + (< (float-time (time-subtract + (current-time) + (cdr ghub--2fa-cache))) + 25) + (car ghub--2fa-cache))))) + (setq ghub--2fa-cache (cons code (current-time))) + (number-to-string code))) + +(defun ghub--auth-source-get (keys &rest spec) + (declare (indent 1)) + (let ((plist (car (apply #'auth-source-search + (append spec (list :max 1)))))) + (mapcar (lambda (k) + (plist-get plist k)) + keys))) + +(advice-add 'auth-source-netrc-parse-next-interesting :around + 'auth-source-netrc-parse-next-interesting@save-match-data) +(defun auth-source-netrc-parse-next-interesting@save-match-data (fn) + "Save match-data for the benefit of caller `auth-source-netrc-parse-one'. +Without wrapping this function in `save-match-data' the caller +won't see the secret from a line that is followed by a commented +line." + (save-match-data (funcall fn))) + +;;; _ +(provide 'ghub) +(require 'ghub-graphql) +;;; ghub.el ends here diff --git a/elpa/ghub-20181112.1755/ghub.info b/elpa/ghub-20181112.1755/ghub.info new file mode 100644 index 00000000..bc69c66a --- /dev/null +++ b/elpa/ghub-20181112.1755/ghub.info @@ -0,0 +1,1312 @@ +This is ghub.info, produced by makeinfo version 6.5 from ghub.texi. + + Copyright (C) 2017-2018 Jonas Bernoulli + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document 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. + +INFO-DIR-SECTION Emacs +START-INFO-DIR-ENTRY +* Ghub: (ghub). Minuscule client library for the Github API. +END-INFO-DIR-ENTRY + + +File: ghub.info, Node: Top, Next: Introduction, Up: (dir) + +Ghub User and Developer Manual +****************************** + +Ghub provides basic support for using the APIs of various Git forges +from Emacs packages. Originally it only supported the Github REST API, +but now it also supports the Github GraphQL API as well as the REST APIs +of Gitlab, Gitea, Gogs and Bitbucket. + + Ghub abstracts access to API resources using only a handful of basic +functions such as ‘ghub-get‘. These are convenience wrappers around +‘ghub-request‘. Additional forge-specific wrappers like ‘glab-put‘, +‘gtea-put‘, ‘gogs-post‘ and ‘buck-delete‘ are also available. Ghub does +not provide any resource-specific functions, with the exception of +‘FORGE-repository-id‘. + + When accessing Github, then Ghub handles the creation and storage of +access tokens using a setup wizard to make it easier for users to get +started. The tokens for other forges have to be created manually. + + Ghub is intentionally limited to only provide these two essential +features — basic request functions and guided setup — to avoid being too +opinionated, which would hinder wide adoption. It is assumed that wide +adoption would make life easier for users and maintainers alike, because +then all packages that talk to forge APIs could be configured the same +way. + +This manual is for Ghub version 3.0.0 (v3.0.0-5-g86a17df+1). + + Copyright (C) 2017-2018 Jonas Bernoulli + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document 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. + +* Menu: + +* Introduction:: +* Getting Started:: +* Using Ghub in Personal Scripts:: +* Using Ghub in a Package:: +* API:: +* GraphQL Support:: +* Support for Other Forges:: + +— The Detailed Node Listing — + +Getting Started + +* Setting the Username:: +* Interactively Creating and Storing a Token:: +* Manually Creating and Storing a Token:: +* How Ghub uses Auth-Source:: + +API + +* Making Requests:: +* Authentication:: +* Configuration Variables:: + +Support for Other Forges + +* Forge Functions and Variables:: +* Forge Limitations and Notes:: + + + +File: ghub.info, Node: Introduction, Next: Getting Started, Prev: Top, Up: Top + +1 Introduction +************** + +Ghub provides basic support for using the APIs of various Git forges +from Emacs packages. Originally it only supported the Github REST API, +but now it also supports the Github GraphQL API as well as the REST APIs +of Gitlab, Gitea, Gogs and Bitbucket. + + Ghub abstracts access to API resources using only a handful of basic +functions such as ‘ghub-get‘. These are convenience wrappers around +‘ghub-request‘. Additional forge-specific wrappers like ‘glab-put‘, +‘gtea-put‘, ‘gogs-post‘ and ‘buck-delete‘ are also available. Ghub does +not provide any resource-specific functions, with the exception of +‘FORGE-repository-id‘. + + When accessing Github, then Ghub handles the creation and storage of +access tokens using a setup wizard to make it easier for users to get +started. The tokens for other forges have to be created manually. + + Ghub is intentionally limited to only provide these two essential +features — basic request functions and guided setup — to avoid being too +opinionated, which would hinder wide adoption. It is assumed that wide +adoption would make life easier for users and maintainers alike, because +then all packages that talk to forge APIs could be configured the same +way. + + Fancier interfaces can be implemented on top of Ghub, and one such +wrapper — named simply Ghub+ — has already been implemented. The +benefit of basing various opinionated interfaces on top of a single +library that provides only the core functionality is that choosing the +programming interface no longer dictates how access tokens are handled. +Users can then use multiple packages that access the Github API without +having to learn the various incompatible ways packages expect the +appropriate token to be made available to them. + + Ghub uses the built-in ‘auth-source’ library to store access tokens. +That library is very flexible and supports multiple backends, which +means that it is up to the user how secrets are stored. They can, among +other things, choose between storing secrets in plain text for ease of +use, or encrypted for better security. + + Previously (as in until this library is widely adopted) it was up to +package authors to decide if things should be easy or secure. (Note +that ‘auth-source’ defaults to "easy" — you have been warned.) + + Ghub expects package authors to use a dedicated access token instead +of sharing a single token between all packages that rely on it. That +means that users cannot configure Ghub once and later start using a new +package without any additional setup. But Ghub helps with that. + + When the user invokes some command that ultimately results in +‘ghub-request’ being called and the appropriate token is not available +yet, then the user is guided through the process of creating and storing +a new token, and at the end of that process the request is carried out +as if the token had been available to begin with. + + +File: ghub.info, Node: Getting Started, Next: Using Ghub in Personal Scripts, Prev: Introduction, Up: Top + +2 Getting Started +***************** + +Each package that uses Ghub uses its own token. Despite that, chances +are good that after successfully configuring one package you can just +start using another package pretty much instantly. + + If the necessary token to access a Github instance is not available +when a package makes an API request, then a setup wizard pops up, and +after answering a few questions you are good to go. Even the request +that caused the wizard to be summoned should succeed and for most users +this should be true even when configuring the very first token. + + However, in some situations some manual configuration is necessary +*before* using the wizard, or the wizard cannot be used at all: + + • If you don’t want to use the wizard then you don’t have to and can + create tokens manually as described in *note Manually Creating and + Storing a Token::. + + • Unfortunately only Github supports the creation of tokens by using + the API. If you want to access another forge, then you have to + create the token manually as describe in *note Manually Creating + and Storing a Token::. Also see *note Support for Other Forges::. + + • If you want to access a Github Enterprise instance, then you have + to tell Ghub about that before the wizard makes its appearance by + setting the Git variable ‘github.host’. You also have to tell Ghub + your username for that instance using the variable + ‘github.HOST.user’ even if it is the same as on Github.com. + + These variables are documented in *note Configuration Variables::. + Also see *note Setting the Username::. TL;DR: If your Github + Enterprise instance is hosted at ‘git.example.com’ and your + username on that instance is ‘jtribbiani’, then set ‘github.host’ + to ‘git.example.com/api/v3’ in every repository cloned from that + instance (i.e. _do not_ set it globally) and _globally_ set + ‘github.git.example.com/api/v3.user’ to ‘jtribbiani’. The latter + is necessary even if your username on Github.com is the same. + + • If the variable ‘github.user’ (or ‘github.HOST.user’ for an + Enterprise instance) is unset when the wizard is first summoned, + then you are asked to provide your username. That value is then + stored *globally* to avoid having to ask you that question once per + repository. If you have multiple accounts on Github.com (or a + Github Enterprise instance), then you have to explicitly tell Ghub + about that. This can be done by setting the repository-local + values of the appropriate variable *before* the wizard is invoked. + + • You might forget to do the above, which is why it is important to + carefully read the output of the wizard. If it turns out that you + forgot to set a variable, then you must abort, set the variable, + and repeat the request to trigger the wizard again. + + • The setup wizard should work even if you have enabled two-factor + authentication. However if your Github Enterprise instance + enforces Single Sign-On as an additional security measure, then you + are out of luck and have to create the token manually as described + in *note Manually Creating and Storing a Token::. + + The variables mentioned above — and others — are documented in *note +Configuration Variables:: and the setup wizard is documented in *note +Interactively Creating and Storing a Token::. + +* Menu: + +* Setting the Username:: +* Interactively Creating and Storing a Token:: +* Manually Creating and Storing a Token:: +* How Ghub uses Auth-Source:: + + +File: ghub.info, Node: Setting the Username, Next: Interactively Creating and Storing a Token, Up: Getting Started + +2.1 Setting the Username +======================== + +If you haven’t set the Git variable ‘github.user’ yet when making a +request, then you will be asked: + + Git variable `github.user' is unset. Set to: + + You are expected to provide your Github username here. The provided +value will be saved globally (using ‘git config --global github.user +USERNAME’). + + If you need to identify as another user in a particular repository, +then you have to set that variable locally, *before* making a request: + + cd /path/to/repo + git config github.user USERNAME + + For Github Enterprise instances you have to specify where the API can +be accessed *before* you try to access it and a different variable has +to be used to set the username. For example if the API is available at +‘https://example.com/api/v3’, then you should do this: + + # Do this once + git config --global github.example.com/api/v3.user EMPLOYEE + + # Do this for every corporate repository + cd /path/to/repo + git config github.host example.com/api/v3 + + If you do not set ‘github.example.com/api/v3.user’, then you will be +asked to provide the value when trying to make a request, but you do +have to manually set ‘github.host’, or Ghub assumes that you are trying +to access ‘api.github.com’. + + +File: ghub.info, Node: Interactively Creating and Storing a Token, Next: Manually Creating and Storing a Token, Prev: Setting the Username, Up: Getting Started + +2.2 Interactively Creating and Storing a Token +============================================== + +Ghub uses a different token for every package as well as for every +machine from which you access the Github API (and obviously also for +every Github instance and user). This allows packages to only request +the scopes that they actually need and also gives users the opportunity +to refuse access to certain scopes if they expect to not use the +features that need them. + + Usually you don’t have to worry about creating and storing a token +yourself and can just make a request. Note however that you don’t have +to use the setup wizard described below. Alternatively you can perform +the setup manually as described in the next section. + + If you make a request and the required token is not available yet, +then the setup wizard will first ask you something like this: + + Such a Github API token is not available: + + Host: api.github.com + User: USERNAME + Package: PACKAGE + + Scopes requested in `PACKAGE-github-token-scopes': + repo + Store on Github as: + "Emacs package PACKAGE @ LOCAL-MACHINE" + Store locally according to option `auth-sources': + ("~/.authinfo" "~/.authinfo.gpg" "~/.netrc") + + If in doubt, then abort and first view the section of + the Ghub documentation called "Interactively Creating + and Storing a Token". + + Create and store such a token? (yes or no) + + If you don’t have any doubts, then answer "yes". Lets address some +of the doubts that you might have: + + • ‘Host’ usually is "api.github.com" and that is usually what you + want. If you are trying to access a Github Enterprise instance, + then it should be something else and you have to set the value + manually before the setup wizard is summoned, as described in the + parent section. + + • ‘User’ should be your Github.com (or Github Enterprise instance) + username. If it is something else and it doesn’t look like a + simple typo, then you should read the parent section again. In + either case you have to abort. + + • ‘Package’ should be the name of the package you are using to access + the Github API. + + If it is ‘ghub’, then the package author disregarded that + convention and you should probably report a bug in the issue + tracker of that package. + + Or you yourself are using ‘ghub-request’ or one of its wrappers + directly, in which case this is expected and perfectly fine. In + that case you might however want to abort and change the value of + the variable ‘ghub-github-token-scopes’ before triggering the + wizard again. + + • Each ‘PACKAGE’ has to specify the tokens that it needs using a + variable named ‘PACKAGE-github-token-scopes’. The doc-string of + that variable should document why the various scopes are needed. + + The meaning of the various scopes are documented at + . + + • The value of ‘auth-sources’ is shown. The default value causes + secrets to be stored in plain text. Because this might be + unexpected, Ghub additionally displays a warning when appropriate. + + WARNING: The token will be stored unencrypted in "~/.authinfo". + If you don't want that, you have to abort and customize + the `auth-sources' option. + + Whether that is something that needs fixing, is up to you. If your + answer is yes, then you should abort and see *note How Ghub uses + Auth-Source:: for instructions on how to save the token more + securely. + + • When creating a token it is necessary to provide a token + description. Ghub uses descriptions that have the form "Emacs + package PACKAGE @ LOCAL-MACHINE". + + Github uses the token description to identify the token, not merely + as something useful to humans. Token descriptions therefore have + to be unique and in rare cases you get an additional prompt, asking + you something like: + + A token named "Emacs package PACKAGE @ LOCAL-MACHINE" + already exists on Github. Replace it? + + You might see this message when you have lost the old token and + want to replace it with a new one, in which case you should + obviously just proceed. + + Or two of your computers have the same hostname, which is bad + practice because it gains you nothing but leads to issues such as + this. Or you are dual-booting on this machine and use the same + hostname in all operating systems, which is a somewhat reasonable + thing to do, but never-the-less leads to issues like this. + + In either case you will have to use something other than the value + returned by ‘system-name’ to identify the current machine or + operating system. Or you can continue to identify different things + using the same identifier, in which case you have to manually + distribute the token. + + The former is recommended and also easier to do, using the variable + ‘ghub-override-system-name’. See *note Configuration Variables:: + for details. + + After the above prompt you are also asked for your username and +password. If you have enabled two-factor authentication, then you also +have to provide the authentication code at least twice. If you make +sure the code is still good for a while when asked for it first, then +you can just press ‘RET’ at the later prompt(s). + + +File: ghub.info, Node: Manually Creating and Storing a Token, Next: How Ghub uses Auth-Source, Prev: Interactively Creating and Storing a Token, Up: Getting Started + +2.3 Manually Creating and Storing a Token +========================================= + +If you cannot or don’t want to use the wizard then you have to (1) +figure out what scopes a package wants, (2) create such a token using +the web interface and (3) store the token where Ghub expects to find it. + + A package named ‘PACKAGE’ has to specify the scopes that it wants in +the variable named ‘PACKAGE-ghub-token-scopes’. The doc-string of such +variables should document what the various scopes are needed for. + + To create or edit a token go to . +For Gitlab.com use . + + Finally store the token in a place where Ghub looks for it, as +described in *note How Ghub uses Auth-Source::. + + If you store the token in a file like ‘~/.authinfo’, then note that +‘auth-source’’s parsing of that file is brittle. Make sure the file +ends with a newline character, that there are no empty or invalid lines, +and that all comments are prefixed with ‘#’. + + +File: ghub.info, Node: How Ghub uses Auth-Source, Prev: Manually Creating and Storing a Token, Up: Getting Started + +2.4 How Ghub uses Auth-Source +============================= + +Please see *note (auth)Top:: for all the gory details about Auth-Source. +Some Ghub-specific information and important notes follow. + + The variable ‘auth-sources’ controls how and where Auth-Source stores +new secrets and where it looks for known secrets. The default value is +‘("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")’, which means that it +looks in all of these files in order to find secrets and that it stores +new secrets in ‘~/.authinfo’ because that is the first element of the +list. It doesn’t matter which files already do or don’t exist when +storing a new secret, the first file is always used. + + Secrets are stored in ‘~/.authinfo’ in plain text. If you don’t want +that (good choice), then you have to customize ‘auth-sources’, e.g. by +flipping the positions of the first two elements. + + Auth-Source also supports storing secrets in various key-chains. +Refer to its documentation for more information. + + Some Auth-Source backends only support storing three values per +entry, the "machine", the "login" and the "password". Because Ghub uses +separate tokens for each package, it has to squeeze four values into +those three slots, and it does that by using "USERNAME^PACKAGE" as the +"login". + + Assuming your username is "ziggy",the package is named "stardust", +and you want to access *Github.com* an entry in one of the three +mentioned files would then look like this: + + machine api.github.com login ziggy^stardust password 012345abcdef... + + Assuming your username is "ziggy",the package is named "stardust", +and you want to access *Gitlab.com* an entry in one of the three +mentioned files would then look like this: + + machine gitlab.com/api/v4 login ziggy^stardust password 012345abcdef... + + +File: ghub.info, Node: Using Ghub in Personal Scripts, Next: Using Ghub in a Package, Prev: Getting Started, Up: Top + +3 Using Ghub in Personal Scripts +******************************** + +You can use ‘ghub-request’ and its wrapper functions in your personal +scripts, of course. Unlike when you use Ghub from a package that you +distribute for others to use, you don’t have to specify a package in +personal scripts. + + ;; This is perfectly acceptable in personal scripts ... + (ghub-get "/user") + + ;; ... and actually equal to + (ghub-get "/user" nil :auth 'ghub) + + ;; In packages you have to specify the package using AUTH. + (ghub-get "/user" nil :auth 'foobar) + + When you do not specify the ‘AUTH’ argument, then a request is made +on behalf of the ‘ghub’ package itself. Like for any package that uses +Ghub, ‘ghub’ has to declare what scopes it needs, using, in this case, +the variable ‘ghub-github-token-scopes’. + + The default value of that variable is ‘(repo)’ and you might want to +add additional scopes. You can later add additional scopes to an +existing token, using the web interface at +. + + If you do that, then you might want to also set the variable +accordingly, but note that Ghub only consults that when *creating* a new +token. If you want to know a token’s effective scopes use the command +‘ghub-token-scopes’, described in the next section. + + +File: ghub.info, Node: Using Ghub in a Package, Next: API, Prev: Using Ghub in Personal Scripts, Up: Top + +4 Using Ghub in a Package +************************* + +Every package should use its own token. This allows you as the author +of some package to only request access to API scopes that are actually +needed, which in turn might make it easier for users to trust your +package not to do unwanted things. + + The scopes used by ‘PACKAGE’ have to be defined using the variable +‘PACKAGE-github-token-scopes’, and you have to tell ‘ghub-request’ on +behalf of which package a request is being made by passing the symbol +‘PACKAGE’ as the value of its ‘AUTH’ argument. + + (ghub-request "GET" "/user" nil :auth 'PACKAGE) + + -- Variable: PACKAGE-github-token-scopes + + This variable defines the token scopes requested by the package + named ‘PACKAGE’. The doc-string should explain what the various + scopes are needed for to prevent users from giving ‘PACKAGE’ fewer + permissions than it absolutely needs and also to give them greater + confidence that ‘PACKAGE’ is only requesting the permissions that + it actually needs. + + The value of this variable does not necessarily correspond to the + scopes that the respective token actually gives access to. There + is nothing that prevents users from changing the value *after* + creating the token or from editing the token’s scopes later on. + + So it is pointless to check the value of this variable before + making a request. You also should not query the API to reliably + determine the supported tokens before making a query. Doing the + latter would mean that every request becomes two requests and that + the first request would have to be done using the user’s password + instead of a token. + + -- Command: ghub-token-scopes + + Because we cannot be certain that the user hasn’t messed up the + scopes, Ghub provides this command to make it easy to debug such + issues without having to rely on users being thoughtful enough to + correctly determine the used scopes manually. + + Just tell users to run ‘M-x ghub-token-scopes’ and to provide the + correct values for the ‘HOST’, ‘USERNAME’ and ‘PACKAGE’ when + prompted, and to then post the output. + + It is to be expected that users will occasionally mess that up so + this command outputs not only the scopes but also the user input so + that you can have greater confidence in the validity of the user’s + answer. + + Scopes for USERNAME^PACKAGE@HOST: (SCOPE...) + + +File: ghub.info, Node: API, Next: GraphQL Support, Prev: Using Ghub in a Package, Up: Top + +5 API +***** + +This section describes the Ghub API. In other words it describes the +public functions and variables provided by the Ghub package and not the +APIs of the supported forges, which can be accessed by using those +functions. The forge APIs are documented at: + + • Github: + + • Gitlab: + + • Gitea: and + + + • Gogs: + + • Bitbucket: + + +* Menu: + +* Making Requests:: +* Authentication:: +* Configuration Variables:: + + +File: ghub.info, Node: Making Requests, Next: Authentication, Up: API + +5.1 Making Requests +=================== + + -- Function: ghub-request method resource &optional params &key query + payload headers unpaginate noerror reader username auth host + callback errorback url value error extra method* + + This function makes a request for ‘RESOURCE’ using ‘METHOD’. + ‘PARAMS’, ‘QUERY’, ‘PAYLOAD’ and/or ‘HEADERS’ are alists holding + additional request data. The response body is returned and the + response header is stored in the variable ‘ghub-response-headers’. + + • ‘METHOD’ is the HTTP method, given as a string. + + • ‘RESOURCE’ is the resource to access, given as a string + beginning with a slash. + + • ‘PARAMS’, ‘QUERY’, ‘PAYLOAD’ and ‘HEADERS’ are alists and are + used to specify request data. All these arguments are alists + that resemble the JSON expected and returned by the Github + API. The keys are symbols and the values stored in the ‘cdr’ + (not the ‘cadr’) can be strings, integers, or lists of strings + and integers. + + The Github API documentation is vague on how data has to be + transmitted and for a particular resource usually just talks + about "parameters". Generally speaking when the ‘METHOD’ is + "HEAD" or "GET", then they have to be transmitted as a query, + otherwise as a payload. + + • Use ‘PARAMS’ to automatically transmit like ‘QUERY’ or + ‘PAYLOAD’ would depending on ‘METHOD’. + + • Use ‘QUERY’ to explicitly transmit data as a query. + + • Use ‘PAYLOAD’ to explicitly transmit data as a payload. + Instead of an alist, ‘PAYLOAD’ may also be a string, in + which case it gets encoded as UTF-8 but is otherwise + transmitted as-is. + + • Use ‘HEADERS’ for those rare resources that require that + the data is transmitted as headers instead of as a query + or payload. When that is the case, then the Github API + documentation usually mentions it explicitly. + + • If ‘SILENT’ is non-nil, then progress reports and the like are + not messaged. + + • If ‘UNPAGINATE’ is t, then this function make as many requests + as necessary to get all values. If ‘UNPAGINATE’ is a natural + number, then it gets at most that many pages. For any other + non-nil value it raises an error. + + • If ‘NOERROR’ is non-nil, then no error is raised if the + request fails and ‘nil’ is returned instead. If ‘NOERROR’ is + ‘return’, then the error payload is returned instead of ‘nil’. + + • If ‘READER’ is non-nil, then it is used to read and return + from the response buffer. The default is + ‘ghub--read-json-payload’. For the very few resources that do + not return JSON, you might want to use ‘ghub--decode-payload’. + + • If ‘USERNAME’ is non-nil, then the request is made on behalf + of that user. It is better to specify the user using the Git + variable ‘github.user’ for "api.github.com", or + ‘github.HOST.user’ if connecting to a Github Enterprise + instance. + + • Each package that uses Ghub should use its own token. If + ‘AUTH’ is ‘nil’ or unspecified, then the generic ‘ghub’ token + is used instead. This is only acceptable for personal + utilities. A packages that is distributed to other users + should always use this argument to identify itself, using a + symbol matching its name. + + Package authors who find this inconvenient should write a + wrapper around this function and possibly for the + method-specific functions as well. + + Beside ‘nil’, some other symbols have a special meaning too. + ‘none’ means to make an unauthorized request. ‘basic’ means + to make a password based request. If the value is a string, + then it is assumed to be a valid token. ‘basic’ and an + explicit token string are only intended for internal and + debugging uses. + + If ‘AUTH’ is a package symbol, then the scopes are specified + using the variable ‘AUTH-github-token-scopes’. It is an error + if that is not specified. See ‘ghub-github-token-scopes’ for + an example. + + • If ‘HOST’ is non-nil, then connect to that Github instance. + This defaults to "api.github.com". When a repository is + connected to a Github Enterprise instance, then it is better + to specify that using the Git variable ‘github.host’ instead + of using this argument. + + • If ‘FORGE’ is ‘gitlab’, then connect to Gitlab.com or, + depending on ‘HOST’, to another Gitlab instance. This is only + intended for internal use. Instead of using this argument you + should use function ‘glab-request’ and other ‘glab-*’ + functions. + + • If ‘CALLBACK’ and/or ‘ERRORBACK’ is non-nil, then this + function makes one or more asynchronous requests and calls + ‘CALLBACK’ or ‘ERRORBACK’ when finished. If an error + occurred, then it calls ‘ERRORBACK’, or if that is ‘nil’, then + ‘CALLBACK’. When no error occurred then it calls ‘CALLBACK’. + When making asynchronous requests, then no errors are + signaled, regardless of the value of ‘NOERROR’. + + Both callbacks are called with four arguments. + + • For ‘CALLBACK’, the combined value of the retrieved + pages. For ‘ERRORBACK’, the error that occured when + retrieving the last page. + + • The headers of the last page as an alist. + + • Status information provided by ‘url-retrieve’. Its + ‘:error’ property holds the same information as the first + argument to ‘ERRORBACK’. + + • A ‘ghub--req’ struct, which can be passed to + ‘ghub-continue’ (which see) to retrieve the next page, if + any. + + -- Function: ghub-continue args + + If there is a next page, then this function retrieves that. + + This function is only intended to be called from callbacks. If + there is a next page, then that is retrieve and the buffer that the + result will be loaded into is returned, or t if the process has + already completed. If there is no next page, then return nil. + + Callbacks are called with four arguments (see ‘ghub-request’). The + forth argument is a ‘ghub--req’ struct, intended to be passed to + this function. A callback may use the struct’s ‘extra’ slot to + pass additional information to the callback that will be called + after the next request. Use the function ‘ghub-req-extra’ to get + and set the value of that slot. + + As an example, using ‘ghub-continue’ in a callback like so: + + (ghub-get "/users/tarsius/repos" nil + :callback (lambda (value _headers _status req) + (unless (ghub-continue req) + (setq my-value value)))) + + is equivalent to: + + (ghub-get "/users/tarsius/repos" nil + :unpaginate t + :callback (lambda (value _headers _status _req) + (setq my-value value))) + + To demonstrate how to pass information from one callback to the + next, here we record when we start fetching each page: + + (ghub-get "/users/tarsius/repos" nil + :extra (list (current-time)) + :callback (lambda (value _headers _status req) + (push (current-time) (ghub-req-extra req)) + (unless (ghub-continue req) + (setq my-times (ghub-req-extra req)) + (setq my-value value)))) + + -- Variable: ghub-response-headers + + A select few Github API resources respond by transmitting data in + the response header instead of in the response body. Because there + are so few of these inconsistencies, ‘ghub-request’ always returns + the response body. + + To access the response headers use this variable after + ‘ghub-request’ has returned. + + -- Function: ghub-response-link-relations req headers payload + + This function returns an alist of the link relations in ‘HEADERS’, + or if optional ‘HEADERS’ is nil, then those in + ‘ghub-response-headers’. + + When accessing a Bitbucket instance then the link relations are in + ‘PAYLOAD’ instead of ‘HEADERS’, making their API merely RESTish and + forcing this function to append those relations to the value of + ‘ghub-response-headers’, for later use when this function is called + with ‘nil’ for ‘PAYLOAD’. + + -- Variable: ghub-override-system-name + + If non-nil, the value of this variable is used to override the + value returned by ‘system-name’ for the purpose of identifying the + local machine, which is necessary because Ghub uses separate tokens + for each machine. Also see *note Configuration Variables::. + + -- Variable: ghub-github-token-scopes + -- Variable: PACKAGE-github-token-scopes + + Such a variable defines the token scopes requested by the + respective package ‘PACKAGE’ given by the first word in the + variable name. ‘ghub’ itself is treated like any other package. + Also see *note Using Ghub in a Package::. + + -- Function: ghub-head resource &optional params &key query payload + headers unpaginate noerror reader username auth host callback + errorback + -- Function: ghub-get resource &optional params &key query payload + headers unpaginate noerror reader username auth host callback + errorback + + These functions are simple wrappers around ‘ghub-request’. Their + signature is identical to that of the latter, except that they do + not have an argument named ‘METHOD’. The HTTP method is instead + given by the second word in the function name. + + As described in the documentation for ‘ghub-request’, it depends on + the used method whether the value of the ‘PARAMS’ argument is used + as the query or the payload. For the "HEAD" and "GET" methods it + is used as the query. + + -- Function: ghub-put resource &optional params &key query payload + headers unpaginate noerror reader username auth host callback + errorback + -- Function: ghub-post resource &optional params &key query payload + headers unpaginate noerror reader username auth host callback + errorback + -- Function: ghub-patch resource &optional params &key query payload + headers unpaginate noerror reader username auth host callback + errorback + -- Function: ghub-delete resource &optional params &key query payload + headers unpaginate noerror reader username auth host callback + errorback + + These functions are simple wrappers around ‘ghub-request’. Their + signature is identical to that of the latter, except that they do + not have an argument named ‘METHOD’. The HTTP method is instead + given by the second word in the function name. + + As described in the documentation for ‘ghub-request’, it depends on + the used method whether the value of the ‘PARAMS’ argument is used + as the query or the payload. For the "PUT", "POST", "PATCH" and + "DELETE" methods it is used as the payload. + + -- Function: ghub-wait resource &optional duration &key username auth + host + + Some API requests result in an immediate successful response even + when the requested action has not actually been carried out yet. + An example is the request for the creation of a new repository, + which doesn’t cause the repository to immediately become available. + The Github API documentation usually mentions this when describing + an affected resource. + + If you want to do something with some resource right after making a + request for its creation, then you might have to wait for it to + actually be created. This function can be used to do so. It + repeatedly tries to access the resource until it becomes available + or until the timeout exceeds. In the latter case it signals + ‘ghub-error’. + + ‘RESOURCE’ specifies the resource that this function waits for. + + ‘DURATION’ specifies the maximum number of seconds to wait for, + defaulting to 64 seconds. Emacs will block during that time, but + the user can abort using ‘C-g’. + + The first attempt is made immediately and will often succeed. If + not, then another attempt is made after two seconds, and each + subsequent attempt is made after waiting as long as we already + waited between all preceding attempts combined. + + See ‘ghub-request’’s documentation above for information about the + other arguments. + + -- Function: ghub-graphql graphql &optional variables &key username + auth host callback + + This function makes a GraphQL request using ‘GRAPHQL’ and + ‘VARIABLES’ as inputs. ‘GRAPHQL’ is a GraphQL string. ‘VARIABLES’ + is a JSON-like alist. The other arguments behave as for + ‘ghub-request’ (which see). + + The response is returned as a JSON-like alist. Even if the + response contains ‘errors’, this function does not raise an error. + Cursor-handling is likewise left to the caller. + + +File: ghub.info, Node: Authentication, Next: Configuration Variables, Prev: Making Requests, Up: API + +5.2 Authentication +================== + + -- Command: ghub-create-token + + This command creates a new token using the values it reads from the + user and then stores it according to the variable ‘auth-sources’. + It can also be called non-interactively, but you shouldn’t do that + yourself. + + This is useful if you want to fully setup things before attempting + to make the initial request, if you want to provide fewer than the + requested scopes or customize ‘auth-sources’ first, or if something + has gone wrong when using the wizard that is used when making a + request without doing this first. (Note that instead of using this + command you can also just repeat the initial request after making + the desired adjustments — that is easier.) + + This command reads, in order, the ‘HOST’ (Github instance), the + ‘USERNAME’, the ‘PACKAGE’, and the ‘SCOPES’ in the minibuffer, + providing reasonable default choices. ‘SCOPES’ defaults to the + scopes that ‘PACKAGE’ requests using the variable + ‘PACKAGE-github-token-scopes’. + + -- Command: ghub-token-scopes + + Users are free to give a token access to fewer scopes than what the + respective package requested. That can, of course, lead to issues, + and package maintainers have to be able to quickly determine if + such a (mis-)configuration is the root cause when users report + issues. + + This command reads the required values in the minibuffer and then + shows a message containing these values along with the scopes of + the respective token. It also returns the scopes (only) when + called non-interactively. Also see *note Using Ghub in a + Package::. + + +File: ghub.info, Node: Configuration Variables, Prev: Authentication, Up: API + +5.3 Configuration Variables +=========================== + +The username and, unless you only use Github.com itself, the Github +Enterprise instance have to be configured using Git variables. In rare +cases it might also be necessary to specify the identity of the local +machine, which is done using a lisp variable. + + -- Variable: github.user + + The Github.com username. This should be set globally and if you + have multiple Github.com user accounts, then you should set this + locally only for those repositories that you want to access using + the secondary identity. + + -- Variable: github.HOST.user + + This variable serves the same purpose as ‘github.user’ but for the + Github Enterprise instance identified by ‘HOST’. + + The reason why separate variables are used is that this makes it + possible to set both values globally instead of having to set one + of the values locally in each and every repository that is + connected to the Github Enterprise instance, not Github.com. + + -- Variable: github.host + + This variable should only be set locally for a repository and + specifies the Github Enterprise edition that that repository is + connected to. You should not set this globally because then each + and every repository becomes connected to the specified Github + Enterprise instance, including those that should actually be + connected to Github.com. + + When this is undefined, then "api.github.com" is used (defined in + the constant ‘ghub-default-host’, which you should never attempt to + change.) + + -- Variable: ghub-override-system-name + + Ghub uses a different token for each quadruple ‘(USERNAME PACKAGE + HOST LOCAL-MACHINE)’. Theoretically it could reuse tokens to some + extent but that would be more difficult to implement, less + flexible, and less secure (though slightly more convenient). + + A token is identified on the respective Github instance (Github.com + or a Github Enterprise instance) using the pair ‘(PACKAGE . + LOCAL-MACHINE)’, or more precisely the string "Emacs package + PACKAGE @ LOCAL-MACHINE". ‘USERNAME’ and ‘HOST’ do not have to be + encoded because the token is stored for ‘USERNAME’ on ‘HOST’ and + cannot be used by another user and/or on another instance. + + There is one potential problem though; for any given ‘(PACKAGE . + LOCAL-MACHINE)’ there can only be one token identified by "Emacs + package PACKAGE @ LOCAL-MACHINE"; Github does not allow multiple + tokens with the same description because it uses the description as + the identifier (it could use some hash instead, but alas it does + not). + + If you have multiple machines and some of them have the same name, + then you should probably change that as this is not how things + ought to be. However if you dual-boot, then it might make sense to + give that machine the same name regardless of what operating system + you have booted into. + + You could use the same token on both operating systems, but setting + that up might be somewhat difficult because it is not possible to + download an existing token from Github. You could, of course, + locally copy the token, but that is inconvenient and would make it + harder to only revoke the token used on your infected Windows + installation without also revoking it for your totally safe *BSD + installation. + + Alternatively you can set this variable to a unique value, that + will then be used to identify the local machine instead of the + value returned by ‘system-name’. + + +File: ghub.info, Node: GraphQL Support, Next: Support for Other Forges, Prev: API, Up: Top + +6 GraphQL Support +***************** + + -- Function: ghub-graphql graphql &optional variables &key username + auth host callback silent callback errorback value extra + + This function makes a GraphQL request using ‘GRAPHQL’ and + ‘VARIABLES’ as inputs. ‘GRAPHQL’ is a GraphQL string. ‘VARIABLES’ + is a JSON-like alist. The other arguments behave as for + ‘ghub-request’ (which see). + + The response is returned as a JSON-like alist. Even if the + response contains ‘errors’, this function does not raise an error. + Cursor-handling is likewise left to the caller. + + ‘ghub-graphql’ is a thin convenience wrapper around ‘ghub-request’, +similar to ‘ghub-post’ and friends. While the latter only hard-code the +value of the ‘METHOD’ argument, the former also hard-codes ‘RESOURCE’ +and constructs ‘PAYLOAD’ from ‘GRAPHEQL’ and ‘VARIABLES’. It also drops +‘UNPAGINATE’, ‘NOERROR’, ‘READER’ (internal functions expect alist-ified +JSON) and ‘FORGE’ (only Github currently supports GraphQL). + + ‘ghub-graphql’ does not account for the fact that pagination works +differently in GraphQL than it does in REST, so users of this function +have to deal with that themselves. Likewise error handling works +differently and has to be done by the caller too. + + An early attempt at implementing automatic unpaginating for GraphQL +can be found in the ‘faithful-graphql’ branch, provided I haven’t +deleted that by now. On that branch I try to do things as intended by +the designers of GraphQL, using variables and fragments, and drowning in +a sea of boilerplate. + + The problem with that approach is that it only works for applications +that fetch specific information on demand and actually want things to be +paginated. I am convinced that GraphQL is very nice for web apps. + + However the Forge package for which I am implementing all of this has +very different needs. It wants to fetch "all the data" and "cache" it +locally, so that it is available even when there is no internet +connection. GraphQL was designed around the idea that you should be +able to "ask for what you need and get exactly that". But when that +boils down to "look, if I persist, then you are going to hand me over +all the data anyway, so just caught it up already", then things start to +fall apart. If Github’s GraphQL allowed pagination to be turned off +completely, then teaching ‘ghub-graphql’ about error handling would be +enough. + + But it doesn’t and when doing things as intended, then that leads to +huge amounts of repetitive boilerplate, which is so boring to write that +doing it without introducing bugs left and right is near impossible; so +I decided to give up on GraphQL variables, fragments and conditions, and +instead implement something more powerful, though also more opinionated. + + -- Function: ghub--graphql-vacuum query variables callback &optional + until &key narrow username auth host forge + + This function is an opinionated alternative to ‘ghub-graphql’. It + relies and dark magic to get the job done. + + It makes an initial request using ‘QUERY’. It then looks for + paginated edges in the returned data and makes more requests to + resolve them. In order to do so it automatically transforms the + initial ‘QUERY’ into another query suitable for that particular + edge. The data retrieved by subsequent requests is then injected + into the data of the original request before that is returned or + passed to the callback. If subsequently retrieved data features + new paginated edges, then those are followed recursively. + + The end result is essentially the same as using ‘ghub-graphql’, if + only it were possible to say "do not paginate anything". The + implementation is much more complicated because it is not possible + to do that. + + ‘QUERY’ is a GraphQL query expressed as an s-expression. The + ‘graphql’ package is used to turn that into a GraphQL query string, + but the format is somewhat different than as documented for that + package. Also only a subset of the GraphQL features are supported; + fragments for example are not, and magical stuff happens to + variables. This is not documented yet, I am afraid. Look at + existing callers. + + ‘VARIABLES’ is a JSON-like alist as for ‘ghub-graphql’. + + ‘UNTIL’ is an alist ‘((EDGE-until . VALUE)...)’. When unpaginating + ‘EDGE’ try not to fetch beyond the element whose first field has + the value ‘VALUE’ and remove that element as well as all "lesser" + elements from the retrieved data if necessary. Look at + ‘forge--pull-repository’ for an example. This is only useful if + you "cache" the response locally and want to avoid fetching data + again that you already have. + + Other arguments behave as for ‘ghub-graphql’ and ‘ghub-request’, + more or less. + + Using ‘ghub--graphql-vacuum’, the following resource specific +functions are implemented. These functions are not part of the public +API yet and are very much subject to change. + + -- Function: ghub-fetch-repository owner name callback &optional until + &key username auth host forge + + This function asynchronously fetches forge data about the specified + repository. Once all data has been collected, ‘CALLBACK’ is called + with the data as the only argument. + + -- Function: ghub-fetch-issue owner name callback &optional until &key + username auth host forge + + This function asynchronously fetches forge data about the specified + issue. Once all data has been collected, ‘CALLBACK’ is called with + the data as the only argument. + + -- Function: ghub-fetch-pullreq owner name callback &optional until + &key username auth host forge + + This function asynchronously fetches forge data about the specified + pull-request. Once all data has been collected, ‘CALLBACK’ is + called with the data as the only argument. + + Note that in order to avoid duplication all of these functions base +their initial query on the query stored in ‘ghub-fetch-repository’. The +latter two pass that query through ‘ghub--graphql-prepare-query’, which +then used ‘ghub--graphql-narrow-query’ to remove parts the caller is not +interested in. These two functions are also used internally, when +unpaginating, but as demonstrated here they can be useful even before +making an initial request. + + +File: ghub.info, Node: Support for Other Forges, Prev: GraphQL Support, Up: Top + +7 Support for Other Forges +************************** + +* Menu: + +* Forge Functions and Variables:: +* Forge Limitations and Notes:: + + +File: ghub.info, Node: Forge Functions and Variables, Next: Forge Limitations and Notes, Up: Support for Other Forges + +7.1 Forge Functions and Variables +================================= + +Originally Ghub supported only Github but now it also supports Gitlab, +Gitea, Gogs and Bitbucket. The function ‘ghub-request’ and all the +‘ghub-METHOD’ convenience wrappers default to acting on a Github forge +but can be told to act on another forge using their FORGE argument. + + The FORGE argument only specifies what kind of forge to act on, not +which instance. The HOST argument can be used to select the instance. +For some forges a default instance is defined: + + • Forge ‘github’ defaults to host ‘api.github.com’. + + • Forge ‘gitlab’ defaults to host ‘gitlab.com/api/v4’. + + • Forge ‘bitbucket’ defaults to host ‘api.bitbucket.org/2.0’. + + • No canonical host exists for the ‘gitea’ and ‘gogs’ forges and + ‘localhost:3000/api/v1’ is used as the default host in both cases. + + Together the FORGE and HOST arguments specify the forge type and +instance. In addition to that, it is also necessary to specify on whose +behalf the request is being made, which can be done using the USERNAME +and AUTH arguments. + + Having to specify these arguments for every request is inconvenient. +Additional variables and convenience functions can be used to make that +unnecessary in most cases. + + These variables can be set globally and/or for a specific repository +as explained in *note Configuration Variables:: with a focus on Github +instances. To summarize: + + • For the Git variable ‘github.user’ specifies + the user. + + • For another ‘github’ instance the Git variable ‘github.HOST.user’ + specifies the user. The HOST in that variable name is the same as + the value of the HOST argument of the called function. + + • Instead of specifying the HOST in every function call, the Git + variable ‘github.host’ can be used. This should only be set + locally. + +For ‘gitlab’ and ‘bitbucket’ forges similar variables are available: + + • ‘gitlab.user’ specifies the user. + + • ‘gitlab.HOST.user’ specifies the user for the HOST ‘gitlab’ + instance. + + • ‘gitlab.host’ specifies the ‘gitlab’ host, unless the HOST argument + is non-nil + + • ‘bitbucket.user’ specifies the user. + + • ‘bitbucket.HOST.user’ specifies the user for the HOST ‘bitbucket’ + instance. + + • ‘bitbucket.host’ specifies the ‘bitbucket’ host, unless the HOST + argument is non-nil. + + For ‘gitea’ and ‘gogs’ forges some similar variables are available, +however for some of the ‘ghub.*’ variables no equivalent variable exist +for these two forges: + + • ‘gitea.user’ is *not* used because no canonical ‘gitea’ instance + exists. + + • ‘gitea.HOST.user’ specifies the user for the HOST ‘gitea’ instance. + + • ‘gitea.host’ specifies the ‘gitea’ host, unless the HOST argument + is non-nil + + • ‘gogs.user’ is *not* used because no canonical ‘gitea’ instance + exists. + + • ‘gogs.HOST.user’ specifies the user for the HOST ‘gogs’ instance. + + • ‘gogs.host’ specifies the ‘gogs’ host, unless the HOST argument is + non-nil + + ‘ghub-request’ and ‘ghub-METHOD’ can be used to make a request for +any of the supported forge types, but except when making a request for a +‘github’ instance, then that requires the use of the FORGE argument. + + To avoid that, functions named ‘FORGE-request’ and ‘FORGE-METHOD’ are +also available. The following forms are equivalent, for example: + + (ghub-get ... :auth 'PACKAGE :forge 'gitlab) + (glab-get ... :auth 'PACKAGE) + + These forms would remain equivalent even if you did not specify a +value for the AUTH arguments — but you should not do that if you plan to +share your code with others (see *note Using Ghub in a Package::). If +you do omit AUTH, then the request is made on behalf of the ‘ghub’ +package, *regardless* of the symbol prefix of the function you use to do +so. + + All ‘FORGE-request’ and ‘FORGE-METHOD’ functions, including but not +limited to ‘ghub-METHOD’, are very simple wrappers around +‘ghub-request’. They take fewer arguments than ‘ghub-request’ and +instead pass constant values for the arguments METHOD and/or FORGE. + + +File: ghub.info, Node: Forge Limitations and Notes, Prev: Forge Functions and Variables, Up: Support for Other Forges + +7.2 Forge Limitations and Notes +=============================== + + • The token creation wizard is only available for ‘github’ forges, + because all other forges do not support using the API to create an + API token. As a consequence, if the user makes a request and the + necessary token cannot be found, then that results in an error. + Tokens can be created at: + + • Gitlab: + + • Bitbucket: + + + • Gitea: + + • Gogs: + + Also see *note Manually Creating and Storing a Token:: and *note + How Ghub uses Auth-Source::. + + • As mentioned in the previous node, the variables ‘gitea.host’ and + ‘gogs.host’ are not taken into account. + + • Gitea and Gogs do not support limiting a token to certain scopes. + + • The Bitbucket API is fairly broken. Some resources only work if a + slash is appended while others only work if no slash is appended. + I am unable to access any private repositories and some resources + don’t work for me at all. Also the API is only RESTish; pagination + information is part of the response body instead of the header. + Due to such issues it is possible that I will eventually have to + remove support for Bitbucket altogether. + + • The Gitlab API documentation is not always accurate, though I don’t + have an example at hand. It also isn’t structured well, making it + occationally difficult to find the information one is looking for. + + • Where one would use ‘user/repo’ when accessing another forge, one + has to use ‘user%2Frepo’ when accessing Gitlab, e.g.: + + (glab-get "/projects/python-mode-devs%2Fpython-mode") + + + +Tag Table: +Node: Top764 +Node: Introduction3279 +Node: Getting Started6321 +Node: Setting the Username10055 +Node: Interactively Creating and Storing a Token11480 +Node: Manually Creating and Storing a Token17131 +Node: How Ghub uses Auth-Source18354 +Node: Using Ghub in Personal Scripts20287 +Node: Using Ghub in a Package21743 +Node: API24361 +Node: Making Requests25158 +Node: Authentication39197 +Node: Configuration Variables41042 +Node: GraphQL Support44762 +Node: Support for Other Forges51427 +Node: Forge Functions and Variables51644 +Node: Forge Limitations and Notes56163 + +End Tag Table + + +Local Variables: +coding: utf-8 +End: diff --git a/elpa/ghub-20181112.1755/glab.el b/elpa/ghub-20181112.1755/glab.el new file mode 100644 index 00000000..fa35b351 --- /dev/null +++ b/elpa/ghub-20181112.1755/glab.el @@ -0,0 +1,153 @@ +;;; glab.el --- minuscule client library for the Gitlab API -*- lexical-binding: t -*- + +;; Copyright (C) 2016-2018 Jonas Bernoulli + +;; Author: Jonas Bernoulli +;; Homepage: https://github.com/magit/ghub +;; Keywords: tools + +;; 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 file 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 copy of the GPL see https://www.gnu.org/licenses/gpl.txt. + +;;; Commentary: + +;; Glab is a library that provides basic support for using the Gitlab API +;; from Emacs packages. It abstracts access to API resources using only +;; a handful of functions that are not resource-specific. + +;; This library is implemented on top of Ghub. Unlike Ghub, Glab does +;; not support the guided creation of tokens because Gitlab lacks the +;; features that would be necessary to implement that. Users have to +;; create tokens through the web interface. + +;;; Code: + +(require 'ghub) + +(defconst glab-default-host "gitlab.com/api/v4" + "The default host that is used if `glab.host' is not set.") + +(cl-defun glab-head (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `HEAD' request for RESOURCE, with optional query PARAMS. +Like calling `ghub-request' (which see) with \"HEAD\" as METHOD +and `gitlab' as FORGE." + (ghub-request "HEAD" resource params :forge 'gitlab + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun glab-get (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `GET' request for RESOURCE, with optional query PARAMS. +Like calling `ghub-request' (which see) with \"GET\" as METHOD +and `gitlab' as FORGE." + (ghub-request "GET" resource params :forge 'gitlab + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun glab-put (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `PUT' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"PUT\" as METHOD +and `gitlab' as FORGE." + (ghub-request "PUT" resource params :forge 'gitlab + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun glab-post (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `POST' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"POST\" as METHOD +and `gitlab' as FORGE." + (ghub-request "POST" resource params :forge 'gitlab + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun glab-patch (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `PATCH' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"PATCH\" as METHOD +and `gitlab' as FORGE." + (ghub-request "PATCH" resource params :forge 'gitlab + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun glab-delete (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `DELETE' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"DELETE\" as METHOD +and `gitlab' as FORGE." + (ghub-request "DELETE" resource params :forge 'gitlab + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun glab-request (method resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a request for RESOURCE and return the response body. +Like calling `ghub-request' (which see) with `gitlab' as FORGE." + (ghub-request method resource params :forge 'gitlab + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun glab-repository-id (owner name &key username auth host) + "Return the id of the repository specified by OWNER, NAME and HOST." + (number-to-string + (cdr (assq 'id (glab-get (format "/projects/%s%%2F%s" owner name) + nil :username username :auth auth :host host))))) + +;;; _ +(provide 'glab) +;;; glab.el ends here diff --git a/elpa/ghub-20181112.1755/gogs.el b/elpa/ghub-20181112.1755/gogs.el new file mode 100644 index 00000000..0fbac46e --- /dev/null +++ b/elpa/ghub-20181112.1755/gogs.el @@ -0,0 +1,140 @@ +;;; gogs.el --- minuscule client library for the Gogs API -*- lexical-binding: t -*- + +;; Copyright (C) 2016-2018 Jonas Bernoulli + +;; Author: Jonas Bernoulli +;; Homepage: https://github.com/magit/ghub +;; Keywords: tools + +;; 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 file 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 copy of the GPL see https://www.gnu.org/licenses/gpl.txt. + +;;; Commentary: + +;; Gogs is a library that provides basic support for using the Gogs API +;; from Emacs packages. It abstracts access to API resources using only +;; a handful of functions that are not resource-specific. + +;; This library is implemented on top of Ghub. Unlike Ghub, Gogs does +;; not support the guided creation of tokens because Gogs lacks the +;; features that would be necessary to implement that. Users have to +;; create tokens through the web interface. + +;;; Code: + +(require 'ghub) + +(defconst gogs-default-host "localhost:3000/api/v1" + "The default host that is used if `gogs.host' is not set.") + +;; HEAD does not appear to be supported. + +(cl-defun gogs-get (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `GET' request for RESOURCE, with optional query PARAMS. +Like calling `ghub-request' (which see) with \"GET\" as METHOD +and `gogs' as FORGE." + (ghub-request "GET" resource params :forge 'gogs + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gogs-put (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `PUT' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"PUT\" as METHOD +and `gogs' as FORGE." + (ghub-request "PUT" resource params :forge 'gogs + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gogs-post (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `POST' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"POST\" as METHOD +and `gogs' as FORGE." + (ghub-request "POST" resource params :forge 'gogs + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gogs-patch (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `PATCH' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"PATCH\" as METHOD +and `gogs' as FORGE." + (ghub-request "PATCH" resource params :forge 'gogs + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gogs-delete (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `DELETE' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"DELETE\" as METHOD +and `gogs' as FORGE." + (ghub-request "DELETE" resource params :forge 'gogs + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gogs-request (method resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a request for RESOURCE and return the response body. +Like calling `ghub-request' (which see) with `gogs' as FORGE." + (ghub-request method resource params :forge 'gogs + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gogs-repository-id (owner name &key username auth host) + "Return the id of the repository specified by OWNER, NAME and HOST." + (number-to-string + (cdr (assq 'id (gogs-get (format "/repos/%s/%s" owner name) + nil :username username :auth auth :host host))))) + +;;; _ +(provide 'gogs) +;;; gogs.el ends here diff --git a/elpa/ghub-20181112.1755/gtea.el b/elpa/ghub-20181112.1755/gtea.el new file mode 100644 index 00000000..07ca2909 --- /dev/null +++ b/elpa/ghub-20181112.1755/gtea.el @@ -0,0 +1,140 @@ +;;; gtea.el --- minuscule client library for the Gitea API -*- lexical-binding: t -*- + +;; Copyright (C) 2016-2018 Jonas Bernoulli + +;; Author: Jonas Bernoulli +;; Homepage: https://github.com/magit/ghub +;; Keywords: tools + +;; 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 file 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 copy of the GPL see https://www.gnu.org/licenses/gpl.txt. + +;;; Commentary: + +;; Gtea is a library that provides basic support for using the Gitea API +;; from Emacs packages. It abstracts access to API resources using only +;; a handful of functions that are not resource-specific. + +;; This library is implemented on top of Ghub. Unlike Ghub, Gtea does +;; not support the guided creation of tokens because Gitea lacks the +;; features that would be necessary to implement that. Users have to +;; create tokens through the web interface. + +;;; Code: + +(require 'ghub) + +(defconst gtea-default-host "localhost:3000/api/v1" + "The default host that is used if `gtea.host' is not set.") + +;; HEAD does not appear to be supported. + +(cl-defun gtea-get (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `GET' request for RESOURCE, with optional query PARAMS. +Like calling `ghub-request' (which see) with \"GET\" as METHOD +and `gitea' as FORGE." + (ghub-request "GET" resource params :forge 'gitea + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gtea-put (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `PUT' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"PUT\" as METHOD +and `gitea' as FORGE." + (ghub-request "PUT" resource params :forge 'gitea + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gtea-post (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `POST' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"POST\" as METHOD +and `gitea' as FORGE." + (ghub-request "POST" resource params :forge 'gitea + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gtea-patch (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `PATCH' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"PATCH\" as METHOD +and `gitea' as FORGE." + (ghub-request "PATCH" resource params :forge 'gitea + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gtea-delete (resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a `DELETE' request for RESOURCE, with optional payload PARAMS. +Like calling `ghub-request' (which see) with \"DELETE\" as METHOD +and `gitea' as FORGE." + (ghub-request "DELETE" resource params :forge 'gitea + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gtea-request (method resource &optional params + &key query payload headers + silent unpaginate noerror reader + username auth host + callback errorback extra) + "Make a request for RESOURCE and return the response body. +Like calling `ghub-request' (which see) with `gitea' as FORGE." + (ghub-request method resource params :forge 'gitea + :query query :payload payload :headers headers + :silent silent :unpaginate unpaginate + :noerror noerror :reader reader + :username username :auth auth :host host + :callback callback :errorback errorback :extra extra)) + +(cl-defun gtea-repository-id (owner name &key username auth host) + "Return the id of the repository specified by OWNER, NAME and HOST." + (number-to-string + (cdr (assq 'id (gtea-get (format "/repos/%s/%s" owner name) + nil :username username :auth auth :host host))))) + +;;; _ +(provide 'gtea) +;;; gtea.el ends here diff --git a/elpa/git-commit-20181110.1201/git-commit-autoloads.el b/elpa/git-commit-20181110.1201/git-commit-autoloads.el new file mode 100644 index 00000000..bcf53728 --- /dev/null +++ b/elpa/git-commit-20181110.1201/git-commit-autoloads.el @@ -0,0 +1,53 @@ +;;; git-commit-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "git-commit" "git-commit.el" (0 0 0 0)) +;;; Generated autoloads from git-commit.el + +(defvar global-git-commit-mode t "\ +Non-nil if Global Git-Commit mode is enabled. +See the `global-git-commit-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `global-git-commit-mode'.") + +(custom-autoload 'global-git-commit-mode "git-commit" nil) + +(autoload 'global-git-commit-mode "git-commit" "\ +Edit Git commit messages. +This global mode arranges for `git-commit-setup' to be called +when a Git commit message file is opened. That usually happens +when Git uses the Emacsclient as $GIT_EDITOR to have the user +provide such a commit message. + +\(fn &optional ARG)" t nil) + +(defconst git-commit-filename-regexp "/\\(\\(\\(COMMIT\\|NOTES\\|PULLREQ\\|TAG\\)_EDIT\\|MERGE_\\|\\)MSG\\|\\(BRANCH\\|EDIT\\)_DESCRIPTION\\)\\'") + +(autoload 'git-commit-setup-check-buffer "git-commit" "\ + + +\(fn)" nil nil) + +(autoload 'git-commit-setup "git-commit" "\ + + +\(fn)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "git-commit" '("git-commit-"))) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; git-commit-autoloads.el ends here diff --git a/elpa/git-commit-20181110.1201/git-commit-pkg.el b/elpa/git-commit-20181110.1201/git-commit-pkg.el new file mode 100644 index 00000000..492b058e --- /dev/null +++ b/elpa/git-commit-20181110.1201/git-commit-pkg.el @@ -0,0 +1,2 @@ +;;; -*- no-byte-compile: t -*- +(define-package "git-commit" "20181110.1201" "Edit Git commit messages" '((emacs "25.1") (dash "20180910") (with-editor "20181103")) :commit "aeaab802e495e3e317b6bdac387cdbaa08a3fa43" :keywords '("git" "tools" "vc") :maintainer '("Jonas Bernoulli" . "jonas@bernoul.li") :url "https://github.com/magit/magit") diff --git a/elpa/git-commit-20181110.1201/git-commit.el b/elpa/git-commit-20181110.1201/git-commit.el new file mode 100644 index 00000000..bf85ef0f --- /dev/null +++ b/elpa/git-commit-20181110.1201/git-commit.el @@ -0,0 +1,945 @@ +;;; git-commit.el --- Edit Git commit messages -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Authors: Jonas Bernoulli +;; Sebastian Wiesner +;; Florian Ragwitz +;; Marius Vollmer +;; Maintainer: Jonas Bernoulli + +;; Package-Requires: ((emacs "25.1") (dash "20180910") (with-editor "20181103")) +;; Package-Version: 20181110.1201 +;; Keywords: git tools vc +;; Homepage: https://github.com/magit/magit + +;; 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 file 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 this file. If not, see . + +;;; Commentary: + +;; This package assists the user in writing good Git commit messages. + +;; While Git allows for the message to be provided on the command +;; line, it is preferable to tell Git to create the commit without +;; actually passing it a message. Git then invokes the `$GIT_EDITOR' +;; (or if that is undefined `$EDITOR') asking the user to provide the +;; message by editing the file ".git/COMMIT_EDITMSG" (or another file +;; in that directory, e.g. ".git/MERGE_MSG" for merge commits). + +;; When `global-git-commit-mode' is enabled, which it is by default, +;; then opening such a file causes the features described below, to +;; be enabled in that buffer. Normally this would be done using a +;; major-mode but to allow the use of any major-mode, as the user sees +;; fit, it is done here by running a setup function, which among other +;; things turns on the preferred major-mode, by default `text-mode'. + +;; Git waits for the `$EDITOR' to finish and then either creates the +;; commit using the contents of the file as commit message, or, if the +;; editor process exited with a non-zero exit status, aborts without +;; creating a commit. Unfortunately Emacsclient (which is what Emacs +;; users should be using as `$EDITOR' or at least as `$GIT_EDITOR') +;; does not differentiate between "successfully" editing a file and +;; aborting; not out of the box that is. + +;; By making use of the `with-editor' package this package provides +;; both ways of finish an editing session. In either case the file +;; is saved, but Emacseditor's exit code differs. +;; +;; C-c C-c Finish the editing session successfully by returning +;; with exit code 0. Git then creates the commit using +;; the message it finds in the file. +;; +;; C-c C-k Aborts the edit editing session by returning with exit +;; code 1. Git then aborts the commit. + +;; Aborting the commit does not cause the message to be lost, but +;; relying solely on the file not being tampered with is risky. This +;; package additionally stores all aborted messages for the duration +;; of the current session (i.e. until you close Emacs). To get back +;; an aborted message use M-p and M-n while editing a message. +;; +;; M-p Replace the buffer contents with the previous message +;; from the message ring. Of course only after storing +;; the current content there too. +;; +;; M-n Replace the buffer contents with the next message from +;; the message ring, after storing the current content. + +;; Some support for pseudo headers as used in some projects is +;; provided by these commands: +;; +;; C-c C-s Insert a Signed-off-by header. +;; C-c C-a Insert a Acked-by header. +;; C-c C-m Insert a Modified-by header. +;; C-c C-t Insert a Tested-by header. +;; C-c C-r Insert a Reviewed-by header. +;; C-c C-o Insert a Cc header. +;; C-c C-p Insert a Reported-by header. +;; C-c M-s Insert a Suggested-by header. + +;; When Git requests a commit message from the user, it does so by +;; having her edit a file which initially contains some comments, +;; instructing her what to do, and providing useful information, such +;; as which files were modified. These comments, even when left +;; intact by the user, do not become part of the commit message. This +;; package ensures these comments are propertizes as such and further +;; prettifies them by using different faces for various parts, such as +;; files. + +;; Finally this package highlights style errors, like lines that are +;; too long, or when the second line is not empty. It may even nag +;; you when you attempt to finish the commit without having fixed +;; these issues. The style checks and many other settings can easily +;; be configured: +;; +;; M-x customize-group RET git-commit RET + +;;; Code: +;;;; Dependencies + +(require 'dash) +(require 'log-edit) +(require 'magit-git nil t) +(require 'magit-utils nil t) +(require 'ring) +(require 'server) +(require 'with-editor) + +(eval-when-compile (require 'recentf)) + +;;;; Declarations + +(defvar diff-default-read-only) +(defvar flyspell-generic-check-word-predicate) +(defvar font-lock-beg) +(defvar font-lock-end) + +(declare-function magit-expand-git-file-name "magit-git" (filename)) +(declare-function magit-list-local-branch-names "magit-git" ()) +(declare-function magit-list-remote-branch-names "magit-git" + (&optional remote relative)) + +;;; Options +;;;; Variables + +(defgroup git-commit nil + "Edit Git commit messages." + :prefix "git-commit-" + :link '(info-link "(magit)Editing Commit Messages") + :group 'tools) + +;;;###autoload +(define-minor-mode global-git-commit-mode + "Edit Git commit messages. +This global mode arranges for `git-commit-setup' to be called +when a Git commit message file is opened. That usually happens +when Git uses the Emacsclient as $GIT_EDITOR to have the user +provide such a commit message." + :group 'git-commit + :type 'boolean + :global t + :init-value t + :initialize (lambda (symbol exp) + (custom-initialize-default symbol exp) + (when global-git-commit-mode + (add-hook 'find-file-hook 'git-commit-setup-check-buffer))) + (if global-git-commit-mode + (add-hook 'find-file-hook 'git-commit-setup-check-buffer) + (remove-hook 'find-file-hook 'git-commit-setup-check-buffer))) + +(defcustom git-commit-major-mode 'text-mode + "Major mode used to edit Git commit messages. +The major mode configured here is turned on by the minor mode +`git-commit-mode'." + :group 'git-commit + :type '(choice (function-item text-mode) + (const :tag "No major mode"))) + +(defcustom git-commit-setup-hook + '(git-commit-save-message + git-commit-setup-changelog-support + git-commit-turn-on-auto-fill + git-commit-propertize-diff + bug-reference-mode + with-editor-usage-message) + "Hook run at the end of `git-commit-setup'." + :group 'git-commit + :type 'hook + :get (and (featurep 'magit-utils) 'magit-hook-custom-get) + :options '(git-commit-save-message + git-commit-setup-changelog-support + git-commit-turn-on-auto-fill + git-commit-turn-on-flyspell + git-commit-propertize-diff + bug-reference-mode + with-editor-usage-message)) + +(defcustom git-commit-post-finish-hook nil + "Hook run after the user finished writing a commit message. + +\\\ +This hook is only run after pressing \\[with-editor-finish] in a buffer used +to edit a commit message. If a commit is created without the +user typing a message into a buffer, then this hook is not run. + +This hook is not run until the new commit has been created. If +doing so takes Git longer than one second, then this hook isn't +run at all. For certain commands such as `magit-rebase-continue' +this hook is never run because doing so would lead to a race +condition. + +Also see `magit-post-commit-hook'." + :group 'git-commit + :type 'hook + :get (and (featurep 'magit-utils) 'magit-hook-custom-get)) + +(defcustom git-commit-finish-query-functions + '(git-commit-check-style-conventions) + "List of functions called to query before performing commit. + +The commit message buffer is current while the functions are +called. If any of them returns nil, then the commit is not +performed and the buffer is not killed. The user should then +fix the issue and try again. + +The functions are called with one argument. If it is non-nil, +then that indicates that the user used a prefix argument to +force finishing the session despite issues. Functions should +usually honor this wish and return non-nil." + :options '(git-commit-check-style-conventions) + :type 'hook + :group 'git-commit) + +(defcustom git-commit-style-convention-checks '(non-empty-second-line) + "List of checks performed by `git-commit-check-style-conventions'. +Valid members are `non-empty-second-line' and `overlong-summary-line'. +That function is a member of `git-commit-finish-query-functions'." + :options '(non-empty-second-line overlong-summary-line) + :type '(list :convert-widget custom-hook-convert-widget) + :group 'git-commit) + +(defcustom git-commit-summary-max-length 68 + "Column beyond which characters in the summary lines are highlighted. + +The highlighting indicates that the summary is getting too long +by some standards. It does in no way imply that going over the +limit a few characters or in some cases even many characters is +anything that deserves shaming. It's just a friendly reminder +that if you can make the summary shorter, then you might want +to consider doing so." + :group 'git-commit + :safe 'numberp + :type 'number) + +(defcustom git-commit-fill-column nil + "Override `fill-column' in commit message buffers. + +If this is non-nil, then it should be an integer. If that is the +case and the buffer-local value of `fill-column' is not already +set by the time `git-commit-turn-on-auto-fill' is called as a +member of `git-commit-setup-hook', then that function sets the +buffer-local value of `fill-column' to the value of this option. + +This option exists mostly for historic reasons. If you are not +already using it, then you probably shouldn't start doing so." + :group 'git-commit + :safe 'numberp + :type '(choice (const :tag "use regular fill-column") + number)) + +(make-obsolete-variable 'git-commit-fill-column 'fill-column + "Magit 2.11.0" 'set) + +(defcustom git-commit-known-pseudo-headers + '("Signed-off-by" "Acked-by" "Modified-by" "Cc" + "Suggested-by" "Reported-by" "Tested-by" "Reviewed-by") + "A list of Git pseudo headers to be highlighted." + :group 'git-commit + :safe (lambda (val) (and (listp val) (-all-p 'stringp val))) + :type '(repeat string)) + +;;;; Faces + +(defgroup git-commit-faces nil + "Faces used for highlighting Git commit messages." + :prefix "git-commit-" + :group 'git-commit + :group 'faces) + +(defface git-commit-summary + '((t :inherit font-lock-type-face)) + "Face used for the summary in commit messages." + :group 'git-commit-faces) + +(defface git-commit-overlong-summary + '((t :inherit font-lock-warning-face)) + "Face used for the tail of overlong commit message summaries." + :group 'git-commit-faces) + +(defface git-commit-nonempty-second-line + '((t :inherit font-lock-warning-face)) + "Face used for non-whitespace on the second line of commit messages." + :group 'git-commit-faces) + +(defface git-commit-note + '((t :inherit font-lock-string-face)) + "Face used for notes in commit messages." + :group 'git-commit-faces) + +(defface git-commit-pseudo-header + '((t :inherit font-lock-string-face)) + "Face used for pseudo headers in commit messages." + :group 'git-commit-faces) + +(defface git-commit-known-pseudo-header + '((t :inherit font-lock-keyword-face)) + "Face used for the keywords of known pseudo headers in commit messages." + :group 'git-commit-faces) + +(defface git-commit-comment-branch-local + (if (featurep 'magit) + '((t :inherit magit-branch-local)) + '((t :inherit font-lock-variable-name-face))) + "Face used for names of local branches in commit message comments." + :group 'git-commit-faces) + +(define-obsolete-face-alias 'git-commit-comment-branch + 'git-commit-comment-branch-local "Git-Commit 2.12.0") + +(defface git-commit-comment-branch-remote + (if (featurep 'magit) + '((t :inherit magit-branch-remote)) + '((t :inherit font-lock-variable-name-face))) + "Face used for names of remote branches in commit message comments. +This is only used if Magit is available." + :group 'git-commit-faces) + +(defface git-commit-comment-detached + '((t :inherit git-commit-comment-branch-local)) + "Face used for detached `HEAD' in commit message comments." + :group 'git-commit-faces) + +(defface git-commit-comment-heading + '((t :inherit git-commit-known-pseudo-header)) + "Face used for headings in commit message comments." + :group 'git-commit-faces) + +(defface git-commit-comment-file + '((t :inherit git-commit-pseudo-header)) + "Face used for file names in commit message comments." + :group 'git-commit-faces) + +(defface git-commit-comment-action + '((t :inherit bold)) + "Face used for actions in commit message comments." + :group 'git-commit-faces) + +;;; Keymap + +(defvar git-commit-mode-map + (let ((map (make-sparse-keymap))) + (cond ((featurep 'jkl) + (define-key map (kbd "C-M-i") 'git-commit-prev-message) + (define-key map (kbd "C-M-k") 'git-commit-next-message)) + (t + (define-key map (kbd "M-p") 'git-commit-prev-message) + (define-key map (kbd "M-n") 'git-commit-next-message) + ;; Old bindings to avoid confusion + (define-key map (kbd "C-c C-x a") 'git-commit-ack) + (define-key map (kbd "C-c C-x i") 'git-commit-suggested) + (define-key map (kbd "C-c C-x m") 'git-commit-modified) + (define-key map (kbd "C-c C-x o") 'git-commit-cc) + (define-key map (kbd "C-c C-x p") 'git-commit-reported) + (define-key map (kbd "C-c C-x r") 'git-commit-review) + (define-key map (kbd "C-c C-x s") 'git-commit-signoff) + (define-key map (kbd "C-c C-x t") 'git-commit-test))) + (define-key map (kbd "C-c C-a") 'git-commit-ack) + (define-key map (kbd "C-c C-i") 'git-commit-suggested) + (define-key map (kbd "C-c C-m") 'git-commit-modified) + (define-key map (kbd "C-c C-o") 'git-commit-cc) + (define-key map (kbd "C-c C-p") 'git-commit-reported) + (define-key map (kbd "C-c C-r") 'git-commit-review) + (define-key map (kbd "C-c C-s") 'git-commit-signoff) + (define-key map (kbd "C-c C-t") 'git-commit-test) + (define-key map (kbd "C-c M-s") 'git-commit-save-message) + map) + "Key map used by `git-commit-mode'.") + +;;; Menu + +(require 'easymenu) +(easy-menu-define git-commit-mode-menu git-commit-mode-map + "Git Commit Mode Menu" + '("Commit" + ["Previous" git-commit-prev-message t] + ["Next" git-commit-next-message t] + "-" + ["Ack" git-commit-ack :active t + :help "Insert an 'Acked-by' header"] + ["Sign-Off" git-commit-signoff :active t + :help "Insert a 'Signed-off-by' header"] + ["Modified-by" git-commit-modified :active t + :help "Insert a 'Modified-by' header"] + ["Tested-by" git-commit-test :active t + :help "Insert a 'Tested-by' header"] + ["Reviewed-by" git-commit-review :active t + :help "Insert a 'Reviewed-by' header"] + ["CC" git-commit-cc t + :help "Insert a 'Cc' header"] + ["Reported" git-commit-reported :active t + :help "Insert a 'Reported-by' header"] + ["Suggested" git-commit-suggested t + :help "Insert a 'Suggested-by' header"] + "-" + ["Save" git-commit-save-message t] + ["Cancel" with-editor-cancel t] + ["Commit" with-editor-finish t])) + +;;; Hooks + +;;;###autoload +(defconst git-commit-filename-regexp "/\\(\ +\\(\\(COMMIT\\|NOTES\\|PULLREQ\\|TAG\\)_EDIT\\|MERGE_\\|\\)MSG\ +\\|\\(BRANCH\\|EDIT\\)_DESCRIPTION\\)\\'") + +(eval-after-load 'recentf + '(add-to-list 'recentf-exclude git-commit-filename-regexp)) + +(add-to-list 'with-editor-file-name-history-exclude git-commit-filename-regexp) + +(defun git-commit-setup-font-lock-in-buffer () + (and buffer-file-name + (string-match-p git-commit-filename-regexp buffer-file-name) + (git-commit-setup-font-lock))) + +(add-hook 'after-change-major-mode-hook 'git-commit-setup-font-lock-in-buffer) + +;;;###autoload +(defun git-commit-setup-check-buffer () + (and buffer-file-name + (string-match-p git-commit-filename-regexp buffer-file-name) + (git-commit-setup))) + +(defvar git-commit-mode) + +(defun git-commit-file-not-found () + ;; cygwin git will pass a cygwin path (/cygdrive/c/foo/.git/...), + ;; try to handle this in window-nt Emacs. + (--when-let + (and (or (string-match-p git-commit-filename-regexp buffer-file-name) + (and (boundp 'git-rebase-filename-regexp) + (string-match-p git-rebase-filename-regexp + buffer-file-name))) + (not (file-accessible-directory-p + (file-name-directory buffer-file-name))) + (if (require 'magit-git nil t) + ;; Emacs prepends a "c:". + (magit-expand-git-file-name (substring buffer-file-name 2)) + ;; Fallback if we can't load `magit-git'. + (and (string-match "\\`[a-z]:/\\(cygdrive/\\)?\\([a-z]\\)/\\(.*\\)" + buffer-file-name) + (concat (match-string 2 buffer-file-name) ":/" + (match-string 3 buffer-file-name))))) + (when (file-accessible-directory-p (file-name-directory it)) + (let ((inhibit-read-only t)) + (insert-file-contents it t) + t)))) + +(when (eq system-type 'windows-nt) + (add-hook 'find-file-not-found-functions #'git-commit-file-not-found)) + +;;;###autoload +(defun git-commit-setup () + ;; Pretend that git-commit-mode is a major-mode, + ;; so that directory-local settings can be used. + (let ((default-directory + (if (or (file-exists-p ".dir-locals.el") + (not (fboundp 'magit-toplevel))) + default-directory + ;; When $GIT_DIR/.dir-locals.el doesn't exist, + ;; fallback to $GIT_WORK_TREE/.dir-locals.el, + ;; because the maintainer can use the latter + ;; to enforce conventions, while s/he has no + ;; control over the former. + (and (fboundp 'magit-toplevel) ; silence byte-compiler + (magit-toplevel))))) + (let ((buffer-file-name nil) ; trick hack-dir-local-variables + (major-mode 'git-commit-mode)) ; trick dir-locals-collect-variables + (hack-dir-local-variables) + (hack-local-variables-apply))) + (when git-commit-major-mode + (let ((auto-mode-alist (list (cons (concat "\\`" + (regexp-quote buffer-file-name) + "\\'") + git-commit-major-mode))) + ;; The major-mode hook might want to consult these minor + ;; modes, while the minor-mode hooks might want to consider + ;; the major mode. + (git-commit-mode t) + (with-editor-mode t)) + (normal-mode t))) + (setq with-editor-show-usage nil) + (unless with-editor-mode + ;; Maybe already enabled when using `shell-command' or an Emacs shell. + (with-editor-mode 1)) + (add-hook 'with-editor-finish-query-functions + 'git-commit-finish-query-functions nil t) + (add-hook 'with-editor-pre-finish-hook + 'git-commit-save-message nil t) + (add-hook 'with-editor-pre-cancel-hook + 'git-commit-save-message nil t) + (when (and (fboundp 'magit-rev-parse) + (not (memq last-command + '(magit-sequencer-continue + magit-sequencer-skip + magit-am-continue + magit-am-skip + magit-rebase-continue + magit-rebase-skip)))) + (add-hook 'with-editor-post-finish-hook + (apply-partially 'git-commit-run-post-finish-hook + (magit-rev-parse "HEAD")) + nil t) + (when (fboundp 'magit-wip-maybe-add-commit-hook) + (magit-wip-maybe-add-commit-hook))) + (setq with-editor-cancel-message + 'git-commit-cancel-message) + (make-local-variable 'log-edit-comment-ring-index) + (git-commit-mode 1) + (git-commit-setup-font-lock) + (when (boundp 'save-place) + (setq save-place nil)) + (save-excursion + (goto-char (point-min)) + (when (looking-at "\\`\\(\\'\\|\n[^\n]\\)") + (open-line 1))) + (run-hooks 'git-commit-setup-hook) + (set-buffer-modified-p nil)) + +(defun git-commit-run-post-finish-hook (previous) + (when git-commit-post-finish-hook + (cl-block nil + (let ((break (time-add (current-time) + (seconds-to-time 1)))) + (while (equal (magit-rev-parse "HEAD") previous) + (if (time-less-p (current-time) break) + (sit-for 0.01) + (message "No commit created after 1 second. Not running %s." + 'git-commit-post-finish-hook) + (cl-return)))) + (run-hooks 'git-commit-post-finish-hook)))) + +(define-minor-mode git-commit-mode + "Auxiliary minor mode used when editing Git commit messages. +This mode is only responsible for setting up some key bindings. +Don't use it directly, instead enable `global-git-commit-mode'." + :lighter "") + +(put 'git-commit-mode 'permanent-local t) + +(defun git-commit-setup-changelog-support () + "Treat ChangeLog entries as paragraphs." + (setq-local paragraph-start (concat paragraph-start "\\|\\*\\|("))) + +(defun git-commit-turn-on-auto-fill () + "Unconditionally turn on Auto Fill mode. +If `git-commit-fill-column' is non-nil, and `fill-column' +doesn't already have a buffer-local value, then set that +to `git-commit-fill-column'." + (when (and (numberp git-commit-fill-column) + (not (local-variable-p 'fill-column))) + (setq fill-column git-commit-fill-column)) + (setq-local comment-auto-fill-only-comments nil) + (turn-on-auto-fill)) + +(defun git-commit-turn-on-flyspell () + "Unconditionally turn on Flyspell mode. +Also prevent comments from being checked and +finally check current non-comment text." + (require 'flyspell) + (turn-on-flyspell) + (setq flyspell-generic-check-word-predicate + 'git-commit-flyspell-verify) + (let ((end) + (comment-start-regex (format "^\\(%s\\|$\\)" comment-start))) + (save-excursion + (goto-char (point-max)) + (while (and (not (bobp)) (looking-at comment-start-regex)) + (forward-line -1)) + (unless (looking-at comment-start-regex) + (forward-line)) + (setq end (point))) + (flyspell-region (point-min) end))) + +(defun git-commit-flyspell-verify () + (not (= (char-after (line-beginning-position)) + (aref comment-start 0)))) + +(defun git-commit-finish-query-functions (force) + (run-hook-with-args-until-failure + 'git-commit-finish-query-functions force)) + +(defun git-commit-check-style-conventions (force) + "Check for violations of certain basic style conventions. + +For each violation ask the user if she wants to proceed anyway. +Option `git-commit-check-style-conventions' controls which +conventions are checked." + (or force + (save-excursion + (goto-char (point-min)) + (re-search-forward (git-commit-summary-regexp) nil t) + (if (equal (match-string 1) "") + t ; Just try; we don't know whether --allow-empty-message was used. + (and (or (not (memq 'overlong-summary-line + git-commit-style-convention-checks)) + (equal (match-string 2) "") + (y-or-n-p "Summary line is too long. Commit anyway? ")) + (or (not (memq 'non-empty-second-line + git-commit-style-convention-checks)) + (not (match-string 3)) + (y-or-n-p "Second line is not empty. Commit anyway? "))))))) + +(defun git-commit-cancel-message () + (message + (concat "Commit canceled" + (and (memq 'git-commit-save-message with-editor-pre-cancel-hook) + ". Message saved to `log-edit-comment-ring'")))) + +;;; History + +(defun git-commit-prev-message (arg) + "Cycle backward through message history, after saving current message. +With a numeric prefix ARG, go back ARG comments." + (interactive "*p") + (when (and (git-commit-save-message) (> arg 0)) + (setq log-edit-comment-ring-index + (log-edit-new-comment-index + arg (ring-length log-edit-comment-ring)))) + (save-restriction + (goto-char (point-min)) + (narrow-to-region (point) + (if (re-search-forward (concat "^" comment-start) nil t) + (max 1 (- (point) 2)) + (point-max))) + (log-edit-previous-comment arg))) + +(defun git-commit-next-message (arg) + "Cycle forward through message history, after saving current message. +With a numeric prefix ARG, go forward ARG comments." + (interactive "*p") + (git-commit-prev-message (- arg))) + +(defun git-commit-save-message () + "Save current message to `log-edit-comment-ring'." + (interactive) + (--when-let (git-commit-buffer-message) + (unless (ring-member log-edit-comment-ring it) + (ring-insert log-edit-comment-ring it)))) + +(defun git-commit-buffer-message () + (let ((flush (concat "^" comment-start)) + (str (buffer-substring-no-properties (point-min) (point-max)))) + (with-temp-buffer + (insert str) + (goto-char (point-min)) + (when (re-search-forward (concat flush " -+ >8 -+$") nil t) + (delete-region (point-at-bol) (point-max))) + (goto-char (point-min)) + (flush-lines flush) + (goto-char (point-max)) + (unless (eq (char-before) ?\n) + (insert ?\n)) + (setq str (buffer-string))) + (unless (string-match "\\`[ \t\n\r]*\\'" str) + (when (string-match "\\`\n\\{2,\\}" str) + (setq str (replace-match "\n" t t str))) + (when (string-match "\n\\{2,\\}\\'" str) + (setq str (replace-match "\n" t t str))) + str))) + +;;; Headers + +(defun git-commit-ack (name mail) + "Insert a header acknowledging that you have looked at the commit." + (interactive (git-commit-self-ident)) + (git-commit-insert-header "Acked-by" name mail)) + +(defun git-commit-modified (name mail) + "Insert a header to signal that you have modified the commit." + (interactive (git-commit-self-ident)) + (git-commit-insert-header "Modified-by" name mail)) + +(defun git-commit-review (name mail) + "Insert a header acknowledging that you have reviewed the commit." + (interactive (git-commit-self-ident)) + (git-commit-insert-header "Reviewed-by" name mail)) + +(defun git-commit-signoff (name mail) + "Insert a header to sign off the commit." + (interactive (git-commit-self-ident)) + (git-commit-insert-header "Signed-off-by" name mail)) + +(defun git-commit-test (name mail) + "Insert a header acknowledging that you have tested the commit." + (interactive (git-commit-self-ident)) + (git-commit-insert-header "Tested-by" name mail)) + +(defun git-commit-cc (name mail) + "Insert a header mentioning someone who might be interested." + (interactive (git-commit-read-ident)) + (git-commit-insert-header "Cc" name mail)) + +(defun git-commit-reported (name mail) + "Insert a header mentioning the person who reported the issue." + (interactive (git-commit-read-ident)) + (git-commit-insert-header "Reported-by" name mail)) + +(defun git-commit-suggested (name mail) + "Insert a header mentioning the person who suggested the change." + (interactive (git-commit-read-ident)) + (git-commit-insert-header "Suggested-by" name mail)) + +(defun git-commit-self-ident () + (list (or (getenv "GIT_AUTHOR_NAME") + (getenv "GIT_COMMITTER_NAME") + (ignore-errors (car (process-lines "git" "config" "user.name"))) + user-full-name + (read-string "Name: ")) + (or (getenv "GIT_AUTHOR_EMAIL") + (getenv "GIT_COMMITTER_EMAIL") + (getenv "EMAIL") + (ignore-errors (car (process-lines "git" "config" "user.email"))) + (read-string "Email: ")))) + +(defun git-commit-read-ident () + (list (read-string "Name: ") + (read-string "Email: "))) + +(defun git-commit-insert-header (header name email) + (setq header (format "%s: %s <%s>" header name email)) + (save-excursion + (goto-char (point-max)) + (cond ((re-search-backward "^[-a-zA-Z]+: [^<]+? <[^>]+>" nil t) + (end-of-line) + (insert ?\n header) + (unless (= (char-after) ?\n) + (insert ?\n))) + (t + (while (re-search-backward (concat "^" comment-start) nil t)) + (unless (looking-back "\n\n" nil) + (insert ?\n)) + (insert header ?\n))) + (unless (or (eobp) (= (char-after) ?\n)) + (insert ?\n)))) + +;;; Font-Lock + +(defun git-commit-summary-regexp () + (concat + ;; Leading empty lines and comments + (format "\\`\\(?:^\\(?:\\s-*\\|%s.*\\)\n\\)*" comment-start) + ;; Summary line + (format "\\(.\\{0,%d\\}\\)\\(.*\\)" git-commit-summary-max-length) + ;; Non-empty non-comment second line + (format "\\(?:\n%s\\|\n\\(.+\\)\\)?" comment-start))) + +(defun git-commit-extend-region-summary-line () + "Identify the multiline summary-regexp construct. +Added to `font-lock-extend-region-functions'." + (save-excursion + (save-match-data + (goto-char (point-min)) + (when (looking-at (git-commit-summary-regexp)) + (let ((summary-beg (match-beginning 0)) + (summary-end (match-end 0))) + (when (or (< summary-beg font-lock-beg summary-end) + (< summary-beg font-lock-end summary-end)) + (setq font-lock-beg (min font-lock-beg summary-beg)) + (setq font-lock-end (max font-lock-end summary-end)))))))) + +(defvar-local git-commit--branch-name-regexp nil) + +(defconst git-commit-comment-headings + '("Changes to be committed:" + "Untracked files:" + "Changed but not updated:" + "Changes not staged for commit:" + "Unmerged paths:" + "Author:" + "Date:")) + +(defconst git-commit-font-lock-keywords-1 + '(;; Pseudo headers + (eval . `(,(format "^\\(%s:\\)\\( .*\\)" + (regexp-opt git-commit-known-pseudo-headers)) + (1 'git-commit-known-pseudo-header) + (2 'git-commit-pseudo-header))) + ("^[-a-zA-Z]+: [^<]+? <[^>]+>" + (0 'git-commit-pseudo-header)) + ;; Summary + (eval . `(,(git-commit-summary-regexp) + (1 'git-commit-summary))) + ;; - Note (overrides summary) + ("\\[.+?\\]" + (0 'git-commit-note t)) + ;; - Non-empty second line (overrides summary and note) + (eval . `(,(git-commit-summary-regexp) + (2 'git-commit-overlong-summary t t) + (3 'git-commit-nonempty-second-line t t))))) + +(defconst git-commit-font-lock-keywords-2 + `(,@git-commit-font-lock-keywords-1 + ;; Comments + (eval . `(,(format "^%s.*" comment-start) + (0 'font-lock-comment-face))) + (eval . `(,(format "^%s On branch \\(.*\\)" comment-start) + (1 'git-commit-comment-branch-local t))) + (eval . `(,(format "^%s \\(HEAD\\) detached at" comment-start) + (1 'git-commit-comment-detached t))) + (eval . `(,(format "^%s %s" comment-start + (regexp-opt git-commit-comment-headings t)) + (1 'git-commit-comment-heading t))) + (eval . `(,(format "^%s\t\\(?:\\([^:\n]+\\):\\s-+\\)?\\(.*\\)" comment-start) + (1 'git-commit-comment-action t t) + (2 'git-commit-comment-file t))))) + +(defconst git-commit-font-lock-keywords-3 + `(,@git-commit-font-lock-keywords-2 + ;; More comments + (eval + ;; Your branch is ahead of 'master' by 3 commits. + ;; Your branch is behind 'master' by 2 commits, and can be fast-forwarded. + . `(,(format + "^%s Your branch is \\(?:ahead\\|behind\\) of '%s' by \\([0-9]*\\)" + comment-start git-commit--branch-name-regexp) + (1 'git-commit-comment-branch-local t) + (2 'git-commit-comment-branch-remote t) + (3 'bold t))) + (eval + ;; Your branch is up to date with 'master'. + ;; Your branch and 'master' have diverged, + . `(,(format + "^%s Your branch \\(?:is up-to-date with\\|and\\) '%s'" + comment-start git-commit--branch-name-regexp) + (1 'git-commit-comment-branch-local t) + (2 'git-commit-comment-branch-remote t))) + (eval + ;; and have 1 and 2 different commits each, respectively. + . `(,(format + "^%s and have \\([0-9]*\\) and \\([0-9]*\\) commits each" + comment-start) + (1 'bold t) + (2 'bold t))))) + +(defvar git-commit-font-lock-keywords git-commit-font-lock-keywords-2 + "Font-Lock keywords for Git-Commit mode.") + +(defun git-commit-setup-font-lock () + (let ((table (make-syntax-table (syntax-table)))) + (when comment-start + (modify-syntax-entry (string-to-char comment-start) "." table)) + (modify-syntax-entry ?# "." table) + (modify-syntax-entry ?\" "." table) + (modify-syntax-entry ?\' "." table) + (modify-syntax-entry ?` "." table) + (set-syntax-table table)) + (setq-local comment-start + (or (ignore-errors + (car (process-lines "git" "config" "core.commentchar"))) + "#")) + (setq-local comment-start-skip (format "^%s+[\s\t]*" comment-start)) + (setq-local comment-end-skip "\n") + (setq-local comment-use-syntax nil) + (setq-local git-commit--branch-name-regexp + (if (and (featurep 'magit-git) + ;; When using cygwin git, we may end up in a + ;; non-existing directory, which would cause + ;; any git calls to signal an error. + (file-accessible-directory-p default-directory)) + (progn + ;; Make sure the below functions are available. + (require 'magit) + ;; Font-Lock wants every submatch to succeed, + ;; so also match the empty string. Do not use + ;; `regexp-quote' because that is slow if there + ;; are thousands of branches outweighing the + ;; benefit of an efficient regep. + (format "\\(\\(?:%s\\)\\|\\)\\(\\(?:%s\\)\\|\\)" + (mapconcat #'identity + (magit-list-local-branch-names) + "\\|") + (mapconcat #'identity + (magit-list-remote-branch-names) + "\\|"))) + "\\([^']*\\)")) + (setq-local font-lock-multiline t) + (add-hook 'font-lock-extend-region-functions + #'git-commit-extend-region-summary-line + t t) + (font-lock-add-keywords nil git-commit-font-lock-keywords t)) + +(defun git-commit-propertize-diff () + (require 'diff-mode) + (save-excursion + (goto-char (point-min)) + (when (re-search-forward "^diff --git" nil t) + (beginning-of-line) + (let ((buffer (current-buffer))) + (insert + (with-temp-buffer + (insert + (with-current-buffer buffer + (prog1 (buffer-substring-no-properties (point) (point-max)) + (delete-region (point) (point-max))))) + (let ((diff-default-read-only nil)) + (diff-mode)) + (let (font-lock-verbose font-lock-support-mode) + (if (fboundp 'font-lock-ensure) + (font-lock-ensure) + (with-no-warnings + (font-lock-fontify-buffer)))) + (let (next (pos (point-min))) + (while (setq next (next-single-property-change pos 'face)) + (put-text-property pos next 'font-lock-face + (get-text-property pos 'face)) + (setq pos next)) + (put-text-property pos (point-max) 'font-lock-face + (get-text-property pos 'face))) + (buffer-string))))))) + +;;; Elisp Text Mode + +(define-derived-mode git-commit-elisp-text-mode text-mode "ElText" + "Major mode for editing commit messages of elisp projects. +This is intended for use as `git-commit-major-mode' for projects +that expect `symbols' to look like this. I.e. like they look in +Elisp doc-strings, including this one. Unlike in doc-strings, +\"strings\" also look different than the other text." + (setq font-lock-defaults '(git-commit-elisp-text-mode-keywords))) + +(defvar git-commit-elisp-text-mode-keywords + `((,(concat "[`‘]\\(\\(?:\\sw\\|\\s_\\|\\\\.\\)" + lisp-mode-symbol-regexp "\\)['’]") + (1 font-lock-constant-face prepend)) + ("\"[^\"]*\"" (0 font-lock-string-face prepend)))) + +;;; _ +(provide 'git-commit) +;;; git-commit.el ends here diff --git a/elpa/gnupg/pubring.gpg b/elpa/gnupg/pubring.gpg new file mode 100644 index 00000000..e76e6852 Binary files /dev/null and b/elpa/gnupg/pubring.gpg differ diff --git a/elpa/gnupg/secring.gpg b/elpa/gnupg/secring.gpg new file mode 100644 index 00000000..e69de29b diff --git a/elpa/gnupg/trustdb.gpg b/elpa/gnupg/trustdb.gpg new file mode 100644 index 00000000..b641c773 Binary files /dev/null and b/elpa/gnupg/trustdb.gpg differ diff --git a/elpa/graphql-20180912.31/graphql-autoloads.el b/elpa/graphql-20180912.31/graphql-autoloads.el new file mode 100644 index 00000000..fd7bad3a --- /dev/null +++ b/elpa/graphql-20180912.31/graphql-autoloads.el @@ -0,0 +1,22 @@ +;;; graphql-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "graphql" "graphql.el" (0 0 0 0)) +;;; Generated autoloads from graphql.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "graphql" '("graphql-"))) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; graphql-autoloads.el ends here diff --git a/elpa/graphql-20180912.31/graphql-pkg.el b/elpa/graphql-20180912.31/graphql-pkg.el new file mode 100644 index 00000000..0ffffb1b --- /dev/null +++ b/elpa/graphql-20180912.31/graphql-pkg.el @@ -0,0 +1,2 @@ +;;; -*- no-byte-compile: t -*- +(define-package "graphql" "20180912.31" "GraphQL utilities" '((emacs "25")) :commit "e2b309689f4faf9225f290080f836e988c5a576d" :keywords '("hypermedia" "tools" "lisp") :authors '(("Sean Allred" . "code@seanallred.com")) :maintainer '("Sean Allred" . "code@seanallred.com") :url "https://github.com/vermiculus/graphql.el") diff --git a/elpa/graphql-20180912.31/graphql.el b/elpa/graphql-20180912.31/graphql.el new file mode 100644 index 00000000..75873f5e --- /dev/null +++ b/elpa/graphql-20180912.31/graphql.el @@ -0,0 +1,220 @@ +;;; graphql.el --- GraphQL utilities -*- lexical-binding: t; -*- + +;; Copyright (C) 2017 Sean Allred + +;; Author: Sean Allred +;; Keywords: hypermedia, tools, lisp +;; Homepage: https://github.com/vermiculus/graphql.el +;; Package-Version: 20180912.31 +;; Package-X-Original-Version: 0.1.1 +;; Package-Requires: ((emacs "25")) + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Commentary: + +;; GraphQL.el provides a generally-applicable domain-specific language +;; for creating and executing GraphQL queries against your favorite +;; web services. + +;;; Code: + +(require 'pcase) + +(defun graphql--encode-object (obj) + "Encode OBJ as a GraphQL string." + (cond + ((stringp obj) + obj) + ((symbolp obj) + (symbol-name obj)) + ((numberp obj) + (number-to-string obj)) + ((and (consp obj) + (not (consp (cdr obj)))) + (symbol-name (car obj))))) + +(defun graphql--encode-argument-spec (spec) + "Encode an argument spec SPEC. +SPEC is of the form..." + (graphql--encode-argument (car spec) (cdr spec))) + +(defun graphql--encode-argument (key value) + "Encode an argument KEY with value VALUE." + (format "%s:%s" key (graphql--encode-argument-value value))) + +(defun graphql--encode-argument-value (value) + "Encode an argument value VALUE. +VALUE is expected to be one of the following: + +* a symbol +* a 'variable', i.e. \\='($ variableName) +* an object (as a list) +* a string +* a vector of values (e.g., symbols) +* a number +* something encode-able by `graphql-encode'." + (cond + ((symbolp value) + (symbol-name value)) + ((eq '$ (car-safe value)) + (format "$%s" (cadr value))) + ((listp value) + (format "{%s}" (mapconcat #'graphql--encode-argument-spec value ","))) + ((stringp value) + (format "\"%s\"" value)) + ((vectorp value) + (format "[%s]" (mapconcat #'graphql-encode value ","))) + ((numberp value) + (number-to-string value)) + (t + (graphql-encode value)))) + +(defun graphql--encode-parameter-spec (spec) + "Encode a parameter SPEC. +SPEC is expected to be of the following form: + + (NAME TYPE [REQUIRED] . [DEFAULT]) + +NAME is the name of the parameter. + +TYPE is the parameter's type. + +A non-nil value for REQUIRED will indicate the parameter is +required. A value of `!' is recommended. + +A non-nil value for DEFAULT will provide a default value for the +parameter." + ;; Unfortunately can't use `pcase' here because the first DEFAULT + ;; value (in the case of a complex value) might be misunderstood as + ;; the value for REQUIRED. We need to know if the third cons is the + ;; very last one; not just that the list has at least three + ;; elements. + (if (eq (last spec) (nthcdr 2 spec)) + (graphql--encode-parameter (nth 0 spec) + (nth 1 spec) + (car (last spec)) + (cdr (last spec))) + (graphql--encode-parameter (nth 0 spec) + (nth 1 spec) + nil + (nthcdr 2 spec)))) + +(defun graphql--encode-parameter (name type &optional required default) + "Encode a GraphQL parameter with a NAME and TYPE. +If REQUIRED is non-nil, mark the parameter as required. +If DEFAULT is non-nil, is the default value of the parameter." + (format "$%s:%s%s%s" + (symbol-name name) + (symbol-name type) + (if required "!" "") + (if default + (concat "=" (graphql--encode-argument-value default)) + ""))) + +(defun graphql--get-keys (g) + "Get the keyword arguments from a graph G. +Returns a list where the first element is a plist of arguments +and the second is a 'clean' copy of G." + (or (and (not (consp g)) + (list nil g)) + (let (graph keys) + (while g + (if (keywordp (car g)) + (let* ((param (pop g)) + (value (pop g))) + (push (cons param value) keys)) + (push (pop g) graph))) + (list keys (nreverse graph))))) + +(defun graphql-encode (g) + "Encode graph G as a GraphQL string." + (pcase (graphql--get-keys g) + (`(,keys ,graph) + (let ((object (or (car-safe graph) graph)) + (name (alist-get :op-name keys)) + (params (alist-get :op-params keys)) + (arguments (alist-get :arguments keys)) + (fields (cdr-safe graph))) + (concat + (graphql--encode-object object) + (when name + (format " %S" name)) + (when arguments + ;; Format arguments "key:value,key:value,..." + (format "(%s)" + (mapconcat #'graphql--encode-argument-spec arguments ","))) + (when params + (format "(%s)" + (mapconcat #'graphql--encode-parameter-spec params ","))) + (when fields + (format "{%s}" + (mapconcat #'graphql-encode fields " ")))))))) + +(defun graphql-simplify-response-edges (data) + "Simplify DATA to collapse edges into their nodes." + (pcase data + ;; When we encounter a collection of edges, simplify those edges + ;; into their nodes + (`(,object (edges . ,edges)) + (cons object (mapcar #'graphql-simplify-response-edges + (mapcar (lambda (edge) (alist-get 'node edge)) + edges)))) + ;; When we encounter a plain cons cell (not a list), let it pass + (`(,(and key (guard (not (consp key)))) . ,(and value (guard (not (consp value))))) + (cons key value)) + ;; symbols should pass unaltered + (`,(and symbol (guard (symbolp symbol))) + symbol) + ;; everything else should be mapped + (_ (mapcar #'graphql-simplify-response-edges data)))) + +(defun graphql--genform-operation (args kind) + "Generate the Lisp form for an operation. +ARGS is is a list ([NAME [PARAMETERS]] GRAPH) where NAME is the +name of the operation, PARAMETERS are its parameters, and GRAPH +is the form of the actual operation. + +KIND can be `query' or `mutation'." + (pcase args + (`(,name ,parameters ,graph) + `(graphql-encode '(,kind :op-name ,name + :op-params ,parameters + ,@graph))) + + (`(,name ,graph) + `(graphql-encode '(,kind :op-name ,name + ,@graph))) + + (`(,graph) + `(graphql-encode '(,kind ,@graph))) + + (_ (error "Bad form")))) + +(defmacro graphql-query (&rest args) + "Construct a Query object. +ARGS is a listof the form described by `graphql--genform-operation'. + +\(fn [NAME] [(PARAMETER-SPEC...)] GRAPH)" + (graphql--genform-operation args 'query)) + +(defmacro graphql-mutation (&rest args) + "Construct a Mutation object. +ARGS is a listof the form described by `graphql--genform-operation'. + +\(fn [NAME] [(PARAMETER-SPEC...)] GRAPH)" + (graphql--genform-operation args 'mutation)) + +(provide 'graphql) +;;; graphql.el ends here diff --git a/elpa/guide-key-20150108.635/guide-key-autoloads.el b/elpa/guide-key-20150108.635/guide-key-autoloads.el new file mode 100644 index 00000000..acf1dfdc --- /dev/null +++ b/elpa/guide-key-20150108.635/guide-key-autoloads.el @@ -0,0 +1,42 @@ +;;; guide-key-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "guide-key" "guide-key.el" (0 0 0 0)) +;;; Generated autoloads from guide-key.el + +(defvar guide-key-mode nil "\ +Non-nil if Guide-Key mode is enabled. +See the `guide-key-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `guide-key-mode'.") + +(custom-autoload 'guide-key-mode "guide-key" nil) + +(autoload 'guide-key-mode "guide-key" "\ +Toggle guide key mode. + +In guide key mode, Guide following keys to an input key sequence +automatically and dynamically. +With a prefix argument ARG, enable guide key mode if ARG is +positive, otherwise disable. + +\(fn &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "guide-key" '("guide-key/"))) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; guide-key-autoloads.el ends here diff --git a/elpa/guide-key-20150108.635/guide-key-pkg.el b/elpa/guide-key-20150108.635/guide-key-pkg.el new file mode 100644 index 00000000..22c767b8 --- /dev/null +++ b/elpa/guide-key-20150108.635/guide-key-pkg.el @@ -0,0 +1,2 @@ +;;; -*- no-byte-compile: t -*- +(define-package "guide-key" "20150108.635" "Guide the following key bindings automatically and dynamically" '((dash "2.10.0") (popwin "0.3.0") (s "1.9.0")) :commit "9236d287a7272e307fb941237390a96037c8c0a2" :keywords '("help" "convenience") :authors '(("Tsunenobu Kai" . "kai2nenobu@gmail.com")) :maintainer '("Tsunenobu Kai" . "kai2nenobu@gmail.com") :url "https://github.com/kai2nenobu/guide-key") diff --git a/elpa/guide-key-20150108.635/guide-key.el b/elpa/guide-key-20150108.635/guide-key.el new file mode 100644 index 00000000..399df7a9 --- /dev/null +++ b/elpa/guide-key-20150108.635/guide-key.el @@ -0,0 +1,643 @@ +;;; guide-key.el --- Guide the following key bindings automatically and dynamically + +;; Copyright (C) 2012, 2013 Tsunenobu Kai + +;; Author: Tsunenobu Kai +;; URL: https://github.com/kai2nenobu/guide-key +;; Package-Version: 20150108.635 +;; Version: 1.2.5 +;; Package-Requires: ((dash "2.10.0") (popwin "0.3.0") (s "1.9.0")) +;; Keywords: help convenience + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Commentary: + +;; Overview: +;; +;; guide-key.el displays the available key bindings automatically and dynamically. +;; guide-key aims to be an alternative of one-key.el. +;; +;; Here are some features of this library. +;; - guide-key automatically pops up the keys following your favorite +;; prefixes. Moreover, even if you change key bindings, guide-key follows the +;; change dynamically. +;; - guide-key can highlight particular commands. This makes it easy to find a +;; command you are looking for, and to learn its key binding. +;; - guide-key doesn't overwrite existing commands and key bindings, so there +;; is no interference with `describe-key' and `describe-bindings'. +;; +;; +;; Installation: +;; +;; I added guide-key to MELPA. You can install guide-key with package.el. +;; Because guide-key depends on popwin.el, popwin.el is also installed. +;; +;; If you don't have package.el, please download popwin.el and guide-key.el +;; directly from https://github.com/m2ym/popwin-el and +;; https://github.com/kai2nenobu/guide-key, and then put them in your +;; `load-path'. +;; +;; +;; Basic usage: +;; +;; You just add your favorite prefix keys to `guide-key/guide-key-sequence' +;; as below. +;; +;; (require 'guide-key) +;; (setq guide-key/guide-key-sequence '("C-x r" "C-x 4")) +;; (guide-key-mode 1) ; Enable guide-key-mode +;; +;; When you press these prefix keys, key bindings are automatically +;; popped up after a short delay (1 second by default). +;; +;; To activate guide-key for any key sequence instead of just the ones +;; listed above then use: +;; +;; (setq guide-key/guide-key-sequence t) +;; +;; guide-key can highlight commands which match a specified regular expression. +;; Key bindings following "C-x r" are rectangle family, register family and +;; bookmark family. If you want to highlight only rectangle family +;; commands, put this setting in your init.el. +;; +;; (setq guide-key/highlight-command-regexp "rectangle") +;; +;; This feature makes it easy to find commands and learn their key bindings. +;; If you want to highlight all families, you can specify multiple regular +;; expressions and faces as below. +;; +;; (setq guide-key/highlight-command-regexp +;; '("rectangle" +;; ("register" . font-lock-type-face) +;; ("bookmark" . font-lock-warning-face))) +;; +;; If an element of `guide-key/highlight-command-regexp' is cons, its car +;; means a regular expression to highlight, and its cdr means a face put on +;; command names. +;; +;; Moreover, prefix commands are automatically highlighted. +;; +;; Depending on your level of emacs experience, you may want a shorter or +;; longer delay between pressing a key and the appearance of the guide +;; buffer. This can be controlled by setting `guide-key/idle-delay': +;; +;; (setq guide-key/idle-delay 0.1) +;; +;; The guide buffer is displayed only when you pause between keystrokes +;; for longer than this delay, so it will keep out of your way when you +;; are typing key sequences that you already know well. +;; +;; I've confirmed that guide-key works well in these environments. +;; - Emacs 24.2, Ubuntu 12.04 or Windows 7 64bit +;; - Emacs 23.3, Ubuntu 12.04 or Windows 7 64bit +;; - Emacs 22.3, Windows 7 64bit +;; - Emacs 24.3.1, OS X 10.9 +;; If popwin works, I think guide-key will work as well. You can use +;; guide-key with Emacs working in terminal. +;; +;; +;; Advanced usage: +;; +;; It is bothering to add many prefixes to `guide-key/guide-key-sequence'. +;; `guide-key/recursive-key-sequence-flag' releases you from this problem. +;; If `guide-key/recursive-key-sequence-flag' is non-nil, guide-key checks a +;; input key sequence recursively. That is, if "C-x 8 ^" is an input key +;; sequence, guide-key checks whether `guide-key/guide-key-sequence' includes +;; "C-x 8" and "C-x". +;; +;; For example, if you configure as below, +;; +;; (setq guide-key/guide-key-sequence '("C-x")) +;; (setq guide-key/recursive-key-sequence-flag t) +;; +;; the guide buffer is popped up when you input "C-x r", "C-x 8" and +;; any other prefixes following "C-x". +;; +;; +;; You can add extra settings in a particular mode. Please use +;; `guide-key/add-local-guide-key-sequence', +;; `guide-key/add-local-highlight-command-regexp' and the hook of +;; that mode. +;; +;; +;; This code is a example of org-mode. +;; +;; (defun guide-key/my-hook-function-for-org-mode () +;; (guide-key/add-local-guide-key-sequence "C-c") +;; (guide-key/add-local-guide-key-sequence "C-c C-x") +;; (guide-key/add-local-highlight-command-regexp "org-")) +;; (add-hook 'org-mode-hook 'guide-key/my-hook-function-for-org-mode) +;; +;; In respect of `guide-key/guide-key-sequence', you can add mode specific key +;; sequences without `guide-key/add-local-guide-key-sequence'. For example, +;; configure as below. +;; +;; (setq guide-key/guide-key-sequence +;; '("C-x r" "C-x 4" +;; (org-mode "C-c C-x") +;; (outline-minor-mode "C-c @"))) +;; +;; In this case, if the current major mode is `org-mode', guide key bindings +;; following "C-c C-x". If `outline-minor-mode' is enabled, guide key bindings +;; following "C-c @". +;; +;; +;; `guide-key' can work with key-chord.el. If you want to guide key bindings +;; following key chord, you need to execute +;; `guide-key/key-chord-hack-on'. Then, add your favorite key chord to +;; `guide-key/guide-key-sequence' as below. +;; +;; (key-chord-define global-map "@4" 'ctl-x-4-prefix) +;; +;; (guide-key/key-chord-hack-on) +;; (setq guide-key/guide-key-sequence '(" @ 4" " 4 @")) +;; +;; If =guide-key/recursive-key-sequence-flag= is non-nil, more simple. +;; +;; (guide-key/key-chord-hack-on) +;; (setq guide-key/recursive-key-sequence-flag t) +;; (setq guide-key/guide-key-sequence '("")) +;; +;; In this case, key bindings are popped up when you type any of key chords. +;; +;; This hack *may be dangerous* because it advices primitive functions; +;; `this-command-keys' and `this-command-keys-vector'. +;; +;; +;; Here are some functions and variables which control guide-key. +;; - `guide-key-mode': +;; guide-key-mode is implemented as a minor mode. +;; Excuting M-x guide-key-mode toggles whether guide-key is enabled or +;; not. Because guide-key-mode is a global minor mode, guide-key-mode is +;; enabled in all buffers or disabled in all buffers. +;; - `guide-key/popup-window-position': +;; This variable controls where a guide-key buffer is popped up. A value of +;; this variable is one of `right', `bottom', `left', `top'. The default +;; value is `right'. +;; - `guide-key/polling-time': +;; This variable controls a polling time. The default value is 0.1 (in seconds). +;; - `guide-key/idle-delay': +;; This variable controls the delay between starting a key sequence and +;; popping up the guide buffer. The default value is 1.0 (in seconds), +;; which means that guide-key will keep out of your way unless you hesitate +;; in the middle of a key sequence . Set this to 0.0 to revert to the old +;; default behavior. +;; - `guide-key/text-scale-amount': +;; This variable controls the size of text in guide buffer. The default +;; value is 0 (it means default size in Emacs). If you want to enlarge +;; text, set positive number. Otherwise, set negative number. +;; +;; Enjoy! + +;;; Code: + +(eval-when-compile + (require 'cl) + (require 'face-remap)) + +(require 'dash) +(require 'popwin) +(require 's) + +;;; variables +(defgroup guide-key nil + "Guide key bidings." + :group 'help + :prefix "guide-key/") + +(defcustom guide-key/guide-key-sequence nil + "*Key sequences to guide in `guide-key-mode'. +This variable is a list of string representation. +Both representations, like \"C-x r\" and \"\\C-xr\", +are allowed. + +In addition, an element of this list can be a list whose car is +the symbol for a certain mode, and whose cdr is a list of key +sequences to consider only if that mode is active. + +Set this variable to `t' to enable for any key sequence." + :type '(repeat (choice (string :tag "Prefix key sequence") + (cons :tag "Mode specific sequence" + (symbol :tag "Symbol for mode") + (repeat (string :tag "Prefix key sequence"))))) + :group 'guide-key) + +(defcustom guide-key/polling-time 0.1 + "*Polling time to check an input key sequence." + :type 'float + :group 'guide-key) + +(defcustom guide-key/idle-delay 1.0 + "*Delay in seconds before guide buffer is displayed." + :type 'float + :group 'guide-key) + +(defcustom guide-key/highlight-prefix-regexp "prefix" + "*Regexp for prefix commands." + :type 'regexp + :group 'guide-key) + +(defcustom guide-key/highlight-command-regexp nil + "*Regexp for commands to highlight. +If a command name matches this regexp, it is highlighted with +`guide-key/highlight-command-face'. + +This variable can be a list and its element is either a regexp or +a cons cell, its car is a regexp and its cdr is face symbol or +color name string. If regexp, commands which match the regexp +are highlighted with `guide-key/highlight-command-face'. If cons +cell, commands which match the car regexp are highlighted with +the cdr face or color." + :type '(choice (regexp :tag "Regexp to highlight") + (repeat (choice (regexp :tag "Regexp to highlight") + (cons (regexp :tag "Regexp to highlight") + (choice (face :tag "Face on command") + (string :tag "Color name string")))))) + :group 'guide-key) + +(defcustom guide-key/align-command-by-space-flag nil + "*If non-nil, align guide buffer by space." + :type 'boolean + :group 'guide-key) + +(defcustom guide-key/popup-window-position 'right + "*Position where guide buffer is popped up. +This variable must be one of `right', `bottom', `left' and `top'." + :type '(radio (const right) (const bottom) (const left) (const top)) + :group 'guide-key) + +(defcustom guide-key/text-scale-amount 0 + "*Amount of scaling text in guide buffer. + +If positive number, the text becomes larger. If negative number, +the text becomes smaller. Scale of the text is detemined by the +value of variable `text-scale-mode-step'." + :type 'float + :group 'guide-key) + +(defcustom guide-key/recursive-key-sequence-flag nil + "*If non-nil, check an input key sequence recursively. +For example, if `guide-key/guide-key-sequence' includes \"C-x\", +guide buffer is popped up when you input \"C-x r\", \"C-x 4\" and +any other prefixes following \"C-x\"." + :type 'boolean + :group 'guide-key) + +(defface guide-key/prefix-command-face + '((((class color) (background dark)) + (:foreground "cyan")) + (((class color) (background light)) + (:foreground "blue"))) + "Face for prefix commands to highlight" + :group 'guide-key) + +(defface guide-key/highlight-command-face + '((((class color) (background dark)) + (:foreground "yellow")) + (((class color) (background light)) + (:foreground "orange red"))) + "Face for commands to highlight" + :group 'guide-key) + +(defface guide-key/key-face + '((((class color) (background dark)) + (:foreground "red")) + (((class color) (background light)) + (:foreground "dark green"))) + "Face for keys following to a key sequence" + :group 'guide-key) + +;;; internal variables +(defvar guide-key/polling-timer nil + "Polling timer to check an input key sequence.") + +(defvar guide-key/idle-timer nil + "Idle timer to wait before popping up guide buffer.") + +(defvar guide-key/guide-buffer-name " *guide-key*" + "Buffer name of guide buffer.") + +(defvar guide-key/last-key-sequence-vector nil + "Key sequence input at the last polling operation.") + +;; or hook +;; (add-hook 'pre-command-hook 'guide-key/hook-command) +;; (setq pre-command-hook nil) +;; (add-hook 'post-command-hook 'guide-key/key-event) +;; (add-hook 'pre-command-hook 'show-this-command) + +;;; functions +;;;###autoload +(define-minor-mode guide-key-mode + "Toggle guide key mode. + +In guide key mode, Guide following keys to an input key sequence +automatically and dynamically. +With a prefix argument ARG, enable guide key mode if ARG is +positive, otherwise disable." + :global t + :lighter " Guide" + (funcall (if guide-key-mode + 'guide-key/turn-on-timer + 'guide-key/turn-off-timer))) + +(defun guide-key/popup-function (&optional input) + "Popup function called after delay of `guide-key/idle-delay' second." + (let ((key-seq (or input (this-single-command-keys))) + (regexp guide-key/highlight-command-regexp)) + (let ((dsc-buf (current-buffer)) + (max-width 0)) + (with-current-buffer (get-buffer-create guide-key/guide-buffer-name) + (unless truncate-lines (setq truncate-lines t)) ; don't fold line + (when indent-tabs-mode (setq indent-tabs-mode nil)) ; don't use tab as white space + (setq mode-line-format nil) + (text-scale-set guide-key/text-scale-amount) + (erase-buffer) + (describe-buffer-bindings dsc-buf key-seq) + (when (> (guide-key/format-guide-buffer key-seq regexp) 0) + (guide-key/close-guide-buffer) + (guide-key/popup-guide-buffer)))))) + + +;;; internal functions +(defun guide-key/polling-function () + "Polling function executed every `guide-key/polling-time' second." + (let ((key-seq (this-single-command-keys))) + (if (guide-key/popup-guide-buffer-p key-seq) + (when (guide-key/update-guide-buffer-p key-seq) + (guide-key/turn-on-idle-timer)) + (guide-key/close-guide-buffer)) + (setq guide-key/last-key-sequence-vector key-seq))) + +(defun guide-key/popup-guide-buffer () + "Pop up guide buffer at `guide-key/popup-window-position'." + (let ((last-config popwin:popup-last-config)) + (apply 'popwin:popup-buffer (get-buffer guide-key/guide-buffer-name) + :position guide-key/popup-window-position + :noselect t + (cond ((popwin:position-horizontal-p guide-key/popup-window-position) + `(:width ,(guide-key/popup-window-size 'horizontal))) + ((popwin:position-vertical-p guide-key/popup-window-position) + `(:height ,(guide-key/popup-window-size))))) + (setq popwin:popup-last-config last-config))) + +(defun guide-key/popup-window-size (&optional horizontal) + "Return an enough height or width of popup window to display +all key bindings in guide buffer. + +If HORIZONTAL is omitted or nil, return the height of popup +window. Otherwise, return the width of popup window" + (with-current-buffer (get-buffer guide-key/guide-buffer-name) + (let ((margin (if horizontal 5 1)) + (scale (expt text-scale-mode-step text-scale-mode-amount))) + (if horizontal + (ceiling (* scale (+ (guide-key/buffer-max-width) margin))) + (ceiling (* scale (+ (count-lines (point-min) (point-max)) margin)))) + ))) + +(defun guide-key/close-guide-buffer () + "Close guide buffer." + (when (eq popwin:popup-buffer (get-buffer guide-key/guide-buffer-name)) + (popwin:close-popup-window)) + (guide-key/turn-off-idle-timer) + ) + +(add-hook 'pre-command-hook 'guide-key/close-guide-buffer) + +(defun guide-key/update-guide-buffer-p (key-seq) + "Return t if guide buffer should be updated." + (not (equal guide-key/last-key-sequence-vector key-seq))) + +(defun guide-key/popup-guide-buffer-p (key-seq) + "Return t if guide buffer should be popped up." + (and (> (length key-seq) 0) + (or (eq guide-key/guide-key-sequence t) + (member key-seq (guide-key/buffer-key-sequences)) + (and guide-key/recursive-key-sequence-flag + (guide-key/popup-guide-buffer-p (guide-key/vbutlast key-seq)))))) + +(defun guide-key/buffer-key-sequences () + "Return a list of key sequences (vector representation) in current buffer." + (let (lst) + ;; global key sequences + (dolist (ks guide-key/guide-key-sequence) + (when (stringp ks) + (setq lst (cons ks lst)))) + ;; major-mode specific key sequences + (setq lst (append (assoc-default major-mode guide-key/guide-key-sequence) lst)) + ;; minor-mode specific key sequences + (dolist (mmode minor-mode-list) + (when (and (boundp mmode) (symbol-value mmode)) + (setq lst (append (assoc-default mmode guide-key/guide-key-sequence) lst)))) + ;; convert key sequences to vector representation + (mapcar 'guide-key/convert-key-sequence-to-vector lst))) + +(defun guide-key/vbutlast (vec &optional n) + "Return a copy of vector VEC with the last N elements removed." + (vconcat (butlast (append vec nil) n))) + +(defun guide-key/convert-key-sequence-to-vector (key-seq) + "Convert key sequence KEY-SEQ to vector representation. +For example, both \"C-x r\" and \"\\C-xr\" are converted to [24 114]" + (vconcat (read-kbd-macro key-seq))) + +(defun guide-key/turn-on-idle-timer () + "Turn on an idle timer for popping up guide buffer." + (when (null guide-key/idle-timer) + (setq guide-key/idle-timer + (run-with-idle-timer guide-key/idle-delay t 'guide-key/popup-function)) + )) + +(defun guide-key/turn-off-idle-timer () + "Turn off the idle timer." + (when guide-key/idle-timer + (cancel-timer guide-key/idle-timer)) + (setq guide-key/idle-timer nil)) + + +(defun guide-key/turn-on-timer () + "Turn on a polling timer." + (when (null guide-key/polling-timer) + (setq guide-key/polling-timer + (run-at-time t guide-key/polling-time 'guide-key/polling-function)))) + +(defun guide-key/turn-off-timer () + "Turn off a polling timer." + (cancel-timer guide-key/polling-timer) + (setq guide-key/polling-timer nil)) + +(defun guide-key/format-guide-buffer (key-seq &optional regexp) + "Format guide buffer. This function returns the number of following keys." + (let ((fkey-list nil) ; list of (following-key space command) + (fkey-str-list nil) ; fontified string of `fkey-list' + (fkey-list-len 0) ; length of above lists + (key-dsc (key-description key-seq))) + (untabify (point-min) (point-max)) ; replace tab to space + (goto-char (point-min)) + ;; extract following keys from buffer bindings + (while (re-search-forward + (format "^%s \\([^ \t]+\\)\\([ \t]+\\)\\(\\(?:[^ \t\n]+ ?\\)+\\)$" (regexp-quote key-dsc)) nil t) + (add-to-list 'fkey-list + (list (match-string 1) (match-string 2) (match-string 3)) t)) + (erase-buffer) + (when (> (setq fkey-list-len (length fkey-list)) 0) + ;; fontify following keys as string + (setq fkey-str-list + (loop for (key space command) in fkey-list + collect (guide-key/fontified-string key space command regexp))) + ;; insert a few following keys per line + (guide-key/insert-following-key fkey-str-list + (popwin:position-horizontal-p guide-key/popup-window-position)) + (goto-char (point-min))) + fkey-list-len)) + +(defun guide-key/insert-following-key (fkey-str-list horizontal) + "Insert a few following keys per line. + +If HORIZONTAL is omitted or nil, assume that guide buffer is +popped up at top or bottom. Otherwise, assume that guide buffer +is popped up at left or right." + (let* ((scale (expt text-scale-mode-step text-scale-mode-amount)) + ;; Calculate the number of items per line + (columns + (if horizontal + (ceiling (/ (* (length fkey-str-list) scale) + (- (frame-height) (if tool-bar-mode 2 0) (if menu-bar-mode 1 0)))) + (floor (/ (frame-width) + (* (apply 'max (mapcar 'length fkey-str-list)) scale)))))) + ;; Insert following keys by columns per line. + (loop for fkey-str in fkey-str-list + for column from 1 + do (insert fkey-str (if (= (mod column columns) 0) "\n" " "))) + (align-regexp (point-min) (point-max) "\\(\\s-*\\) \\[" 1 1 t))) + +(defun guide-key/fontified-string (key space command &optional regexp) + "Return fontified string of following key" + (let ((highlight-face (guide-key/get-highlight-face command regexp))) + (concat (propertize "[" 'face 'guide-key/key-face) + (if highlight-face (propertize key 'face highlight-face) key) + (propertize "]" 'face 'guide-key/key-face) + (if guide-key/align-command-by-space-flag space " ") ; white space + (if highlight-face (propertize command 'face highlight-face) command)))) + +(defun guide-key/get-highlight-face (string &optional regexp) + "Return an appropriate face for highlighting STRING according +to `guide-key/highlight-prefix-regexp' and +`guide-key/highlight-command-regexp'. Return nil if an +appropriate face is not found." + (let ((regexp (or regexp guide-key/highlight-command-regexp))) + ;; `guide-key/highlight-prefix-regexp' has the highest priority + (if (string-match guide-key/highlight-prefix-regexp string) + 'guide-key/prefix-command-face + ;; Else look up the first match in `guide-key/highlight-command-regexp' + (cond ((stringp regexp) + (when (string-match regexp string) + 'guide-key/highlight-command-face)) + ((listp regexp) + (loop for elm in regexp + if (cond ((stringp elm) + (when (string-match elm string) + 'guide-key/highlight-command-face)) + ((consp elm) + (when (string-match (car elm) string) + (if (stringp (cdr elm)) + ;; anonymous face, see (info "(elisp)Faces") + (list :foreground (cdr elm)) + (cdr elm))))) + return it))) + ))) + +(defun guide-key/buffer-max-width () + "Return max width in current buffer." + (let ((buf-str (buffer-substring-no-properties (point-min) (point-max)))) + (apply 'max (mapcar 'length (split-string buf-str "\n"))))) + +(defun guide-key/add-local-guide-key-sequence (key) + (add-to-list (make-local-variable 'guide-key/guide-key-sequence) key)) + +(defun guide-key/add-local-highlight-command-regexp (regexp) + (make-local-variable 'guide-key/highlight-command-regexp) + (cond ((stringp guide-key/highlight-command-regexp) + (setq guide-key/highlight-command-regexp + (list regexp guide-key/highlight-command-regexp))) + ((listp guide-key/highlight-command-regexp) + (add-to-list 'guide-key/highlight-command-regexp regexp)))) + +;;; key-chord hack +(defadvice this-command-keys (after key-chord-hack disable) + "Add key chord to the key sequence returned by `this-command-keys'. + +Original `this-command-keys' returns \"[key-chord]\" when you +type any of key chords, so it is difficult to know which key +chord is pressed. This advice enables to distinguish pressed key +chord." + (condition-case nil + (if (equal ad-return-value [key-chord]) + (let ((rkeys (recent-keys))) + (setq ad-return-value + (vector 'key-chord (aref rkeys (- (length rkeys) 2)) + (aref rkeys (- (length rkeys) 1)))))) + (error ""))) + +(defadvice this-command-keys-vector (after key-chord-hack disable) + "Add key chord to the key sequence returned by `this-command-keys-vector'. + +Original `this-command-keys-vector' returns \"[key-chord]\" when you +type any of key chords, so it is difficult to know which key +chord is pressed. This advice enables to distinguish pressed key +chord." + (condition-case nil + (if (equal ad-return-value [key-chord]) + (let ((rkeys (recent-keys))) + (setq ad-return-value + (vector 'key-chord (aref rkeys (- (length rkeys) 2)) + (aref rkeys (- (length rkeys) 1)))))) + (error []))) + +(defun guide-key/key-chord-hack-on () + "Turn on key-chord hack of guide-key. + +This hack *may be dangerous* because it advices primitive +functions; this-command-keys and this-command-keys-vector." + (interactive) + (dolist (fn '(this-command-keys this-command-keys-vector)) + (ad-enable-advice fn 'after 'key-chord-hack) + (ad-activate fn)) + (message "Turn on key-chord hack of guide-key")) + +(defun guide-key/key-chord-hack-off () + "Turn off key-chord hack of guide-key." + (interactive) + (dolist (fn '(this-command-keys this-command-keys-vector)) + (ad-disable-advice fn 'after 'key-chord-hack) + (ad-activate fn)) + (message "Turn off key-chord hack of guide-key")) + +;;; debug +(defun guide-key/message-events () + "" + (message (format "lce:%S tck:%S tckv:%S tsck:%S lie:%S uce:%S" + last-command-event + (this-command-keys) + (this-command-keys-vector) + (this-single-command-keys) + last-input-event + unread-command-events + ))) +;; (setq ttt (run-at-time t 1 'guide-key/message-events)) +;; (cancel-timer ttt) + +(provide 'guide-key) +;;; guide-key.el ends here diff --git a/elpa/guide-key-readme.txt b/elpa/guide-key-readme.txt new file mode 100644 index 00000000..9f99ece2 --- /dev/null +++ b/elpa/guide-key-readme.txt @@ -0,0 +1,176 @@ +Overview: + +guide-key.el displays the available key bindings automatically and dynamically. +guide-key aims to be an alternative of one-key.el. + +Here are some features of this library. +- guide-key automatically pops up the keys following your favorite + prefixes. Moreover, even if you change key bindings, guide-key follows the + change dynamically. +- guide-key can highlight particular commands. This makes it easy to find a + command you are looking for, and to learn its key binding. +- guide-key doesn't overwrite existing commands and key bindings, so there + is no interference with `describe-key' and `describe-bindings'. + + +Installation: + +I added guide-key to MELPA. You can install guide-key with package.el. +Because guide-key depends on popwin.el, popwin.el is also installed. + +If you don't have package.el, please download popwin.el and guide-key.el +directly from https://github.com/m2ym/popwin-el and +https://github.com/kai2nenobu/guide-key, and then put them in your +`load-path'. + + +Basic usage: + +You just add your favorite prefix keys to `guide-key/guide-key-sequence' +as below. + + (require 'guide-key) + (setq guide-key/guide-key-sequence '("C-x r" "C-x 4")) + (guide-key-mode 1) ; Enable guide-key-mode + +When you press these prefix keys, key bindings are automatically +popped up after a short delay (1 second by default). + +To activate guide-key for any key sequence instead of just the ones +listed above then use: + + (setq guide-key/guide-key-sequence t) + +guide-key can highlight commands which match a specified regular expression. +Key bindings following "C-x r" are rectangle family, register family and +bookmark family. If you want to highlight only rectangle family +commands, put this setting in your init.el. + + (setq guide-key/highlight-command-regexp "rectangle") + +This feature makes it easy to find commands and learn their key bindings. +If you want to highlight all families, you can specify multiple regular +expressions and faces as below. + + (setq guide-key/highlight-command-regexp + '("rectangle" + ("register" . font-lock-type-face) + ("bookmark" . font-lock-warning-face))) + +If an element of `guide-key/highlight-command-regexp' is cons, its car +means a regular expression to highlight, and its cdr means a face put on +command names. + +Moreover, prefix commands are automatically highlighted. + +Depending on your level of emacs experience, you may want a shorter or +longer delay between pressing a key and the appearance of the guide +buffer. This can be controlled by setting `guide-key/idle-delay': + + (setq guide-key/idle-delay 0.1) + +The guide buffer is displayed only when you pause between keystrokes +for longer than this delay, so it will keep out of your way when you +are typing key sequences that you already know well. + +I've confirmed that guide-key works well in these environments. +- Emacs 24.2, Ubuntu 12.04 or Windows 7 64bit +- Emacs 23.3, Ubuntu 12.04 or Windows 7 64bit +- Emacs 22.3, Windows 7 64bit +- Emacs 24.3.1, OS X 10.9 +If popwin works, I think guide-key will work as well. You can use +guide-key with Emacs working in terminal. + + +Advanced usage: + +It is bothering to add many prefixes to `guide-key/guide-key-sequence'. +`guide-key/recursive-key-sequence-flag' releases you from this problem. +If `guide-key/recursive-key-sequence-flag' is non-nil, guide-key checks a +input key sequence recursively. That is, if "C-x 8 ^" is an input key +sequence, guide-key checks whether `guide-key/guide-key-sequence' includes +"C-x 8" and "C-x". + +For example, if you configure as below, + + (setq guide-key/guide-key-sequence '("C-x")) + (setq guide-key/recursive-key-sequence-flag t) + +the guide buffer is popped up when you input "C-x r", "C-x 8" and +any other prefixes following "C-x". + + +You can add extra settings in a particular mode. Please use +`guide-key/add-local-guide-key-sequence', +`guide-key/add-local-highlight-command-regexp' and the hook of +that mode. + + +This code is a example of org-mode. + + (defun guide-key/my-hook-function-for-org-mode () + (guide-key/add-local-guide-key-sequence "C-c") + (guide-key/add-local-guide-key-sequence "C-c C-x") + (guide-key/add-local-highlight-command-regexp "org-")) + (add-hook 'org-mode-hook 'guide-key/my-hook-function-for-org-mode) + +In respect of `guide-key/guide-key-sequence', you can add mode specific key +sequences without `guide-key/add-local-guide-key-sequence'. For example, +configure as below. + + (setq guide-key/guide-key-sequence + '("C-x r" "C-x 4" + (org-mode "C-c C-x") + (outline-minor-mode "C-c @"))) + +In this case, if the current major mode is `org-mode', guide key bindings +following "C-c C-x". If `outline-minor-mode' is enabled, guide key bindings +following "C-c @". + + +`guide-key' can work with key-chord.el. If you want to guide key bindings +following key chord, you need to execute +`guide-key/key-chord-hack-on'. Then, add your favorite key chord to +`guide-key/guide-key-sequence' as below. + + (key-chord-define global-map "@4" 'ctl-x-4-prefix) + + (guide-key/key-chord-hack-on) + (setq guide-key/guide-key-sequence '(" @ 4" " 4 @")) + +If =guide-key/recursive-key-sequence-flag= is non-nil, more simple. + + (guide-key/key-chord-hack-on) + (setq guide-key/recursive-key-sequence-flag t) + (setq guide-key/guide-key-sequence '("")) + +In this case, key bindings are popped up when you type any of key chords. + +This hack *may be dangerous* because it advices primitive functions; +`this-command-keys' and `this-command-keys-vector'. + + +Here are some functions and variables which control guide-key. +- `guide-key-mode': + guide-key-mode is implemented as a minor mode. + Excuting M-x guide-key-mode toggles whether guide-key is enabled or + not. Because guide-key-mode is a global minor mode, guide-key-mode is + enabled in all buffers or disabled in all buffers. +- `guide-key/popup-window-position': + This variable controls where a guide-key buffer is popped up. A value of + this variable is one of `right', `bottom', `left', `top'. The default + value is `right'. +- `guide-key/polling-time': + This variable controls a polling time. The default value is 0.1 (in seconds). +- `guide-key/idle-delay': + This variable controls the delay between starting a key sequence and + popping up the guide buffer. The default value is 1.0 (in seconds), + which means that guide-key will keep out of your way unless you hesitate + in the middle of a key sequence . Set this to 0.0 to revert to the old + default behavior. +- `guide-key/text-scale-amount': + This variable controls the size of text in guide buffer. The default + value is 0 (it means default size in Emacs). If you want to enlarge + text, set positive number. Otherwise, set negative number. + +Enjoy! diff --git a/elpa/helm-20181113.923/emacs-helm.sh b/elpa/helm-20181113.923/emacs-helm.sh new file mode 100755 index 00000000..2f688eef --- /dev/null +++ b/elpa/helm-20181113.923/emacs-helm.sh @@ -0,0 +1,111 @@ +#!/bin/sh + + +## Copyright (C) 2012 ~ 2018 Thierry Volpiatto +## +## 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 3 of the License, 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 this program. If not, see . + +## Commentary: + +# Preconfigured `emacs -Q' with a basic Helm configuration. +# Run it from this directory or symlink it somewhere in your PATH. + +# If TEMP env var exists, use it, otherwise declare it. +test -z "$TEMP" && TEMP="/tmp" + +CONF_FILE="$TEMP/helm-cfg.el" +EMACS=emacs + +case $1 in + -P) + shift 1 + EMACS=$1 + shift 1 + ;; + -h) + echo "Usage: ${0##*/} [-P} Emacs path [-h} help [--] EMACS ARGS" + exit 1 + ;; +esac + +LOAD_PATH=$($EMACS -q -batch --eval "(prin1 load-path)") + +cd "${0%/*}" || exit 1 + +# Check if autoload file exists. +# It may be in a different directory if emacs-helm.sh is a symlink. +TRUENAME=$(find . -samefile "$0" -printf "%l") +if [ ! -z "$TRUENAME" ]; then + AUTO_FILE="${TRUENAME%/*}/helm-autoloads.el" +else + AUTO_FILE="helm-autoloads.el" +fi +if [ ! -e "$AUTO_FILE" ]; then + echo No autoloads found, please run make first to generate autoload file + exit 1 +fi + + +cat > $CONF_FILE <\`helm-find-files'\\n\ +;; - \`occur'(M-s o) =>\`helm-occur'\\n\ +;; - \`list-buffers'(C-x C-b) =>\`helm-buffers-list'\\n\ +;; - \`completion-at-point'(M-tab) =>\`helm-lisp-completion-at-point'[1]\\n\ +;; - \`dabbrev-expand'(M-/) =>\`helm-dabbrev'\\n\ +;; - \`execute-extended-command'(M-x) =>\`helm-M-x'\\n\\n +;; Some other Emacs commands are \"helmized\" by \`helm-mode'.\\n\ +;; [1] Coming with emacs-24.4, \`completion-at-point' is \"helmized\" by \`helm-mode'\\n\ +;; which provides Helm completion in many places like \`shell-mode'.\\n\ +;; Find context help for most Helm commands with \`C-h m'.\\n\ +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\\n\\n")) + +(setq load-path (quote $LOAD_PATH)) +(require 'package) +;; User may be using a non standard \`package-user-dir'. +;; Modify \`package-directory-list' instead of \`package-user-dir' +;; in case the user starts Helm from a non-ELPA installation. +(unless (file-equal-p package-user-dir "~/.emacs.d/elpa") + (add-to-list 'package-directory-list (directory-file-name + (file-name-directory + (directory-file-name default-directory))))) + +(setq package-load-list '((helm-core t) (helm t) (async t) (popup t))) +(package-initialize) +(add-to-list 'load-path (file-name-directory (file-truename "$0"))) +(setq default-frame-alist '((vertical-scroll-bars . nil) + (tool-bar-lines . 0) + (menu-bar-lines . 0) + (fullscreen . nil))) +(blink-cursor-mode -1) +(require 'helm-config) +(helm-mode 1) +(define-key global-map [remap find-file] 'helm-find-files) +(define-key global-map [remap occur] 'helm-occur) +(define-key global-map [remap list-buffers] 'helm-buffers-list) +(define-key global-map [remap dabbrev-expand] 'helm-dabbrev) +(define-key global-map [remap execute-extended-command] 'helm-M-x) +(unless (boundp 'completion-in-region-function) + (define-key lisp-interaction-mode-map [remap completion-at-point] 'helm-lisp-completion-at-point) + (define-key emacs-lisp-mode-map [remap completion-at-point] 'helm-lisp-completion-at-point)) +(add-hook 'kill-emacs-hook #'(lambda () (and (file-exists-p "$CONF_FILE") (delete-file "$CONF_FILE")))) +EOF + +$EMACS -Q -l "$CONF_FILE" "$@" diff --git a/elpa/helm-20181113.923/helm-adaptive.el b/elpa/helm-20181113.923/helm-adaptive.el new file mode 100644 index 00000000..0c6d255f --- /dev/null +++ b/elpa/helm-20181113.923/helm-adaptive.el @@ -0,0 +1,278 @@ +;;; helm-adaptive.el --- Adaptive Sorting of Candidates. -*- lexical-binding: t -*- + +;; Original Author: Tamas Patrovics + +;; Copyright (C) 2007 Tamas Patrovics +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) + + +(defgroup helm-adapt nil + "Adaptative sorting of candidates for Helm." + :group 'helm) + +(defcustom helm-adaptive-history-file + "~/.emacs.d/helm-adaptive-history" + "Path of file where history information is stored. +When nil history is not saved nor restored after emacs restart unless +you save/restore `helm-adaptive-history' with something else like +psession or desktop." + :type 'string + :group 'helm-adapt) + +(defcustom helm-adaptive-history-length 50 + "Maximum number of candidates stored for a source." + :type 'number + :group 'helm-adapt) + +(defcustom helm-adaptive-sort-by-frequent-recent-usage t + "Try to sort on an average of frequent and recent usage when non-nil. + +When nil sort on frequency usage only. + +Only frequency: +When candidate have low frequency, you have to hit on it many times to +make it going up on top. + +Frequency+recent: +Even with a low frequency, candidate go up on top. If a candidate +have a high frequency but it is not used since some time, it goes +down slowly, but as soon you reuse it it go up on top quickly." + :group 'helm-adapt + :type 'boolean) + +;; Internal +(defvar helm-adaptive-done nil + "nil if history information is not yet stored for the current +selection.") + +(defvar helm-adaptive-history nil + "Contains the stored history information. +Format: ((SOURCE-NAME (SELECTED-CANDIDATE (PATTERN . NUMBER-OF-USE) ...) ...) ...)") + +(defconst helm-adaptive-freq-coefficient 5) +(defconst helm-adaptive-recent-coefficient 2) + +(defun helm-adaptive-done-reset () + (setq helm-adaptive-done nil)) + +;;;###autoload +(define-minor-mode helm-adaptive-mode + "Toggle adaptive sorting in all sources." + :group 'helm-adapt + :require 'helm-adaptive + :global t + (if helm-adaptive-mode + (progn + (unless helm-adaptive-history + (helm-adaptive-maybe-load-history)) + (add-hook 'kill-emacs-hook 'helm-adaptive-save-history) + ;; Should run at beginning of `helm-initial-setup'. + (add-hook 'helm-before-initialize-hook 'helm-adaptive-done-reset) + ;; Should run at beginning of `helm-exit-minibuffer'. + (add-hook 'helm-before-action-hook 'helm-adaptive-store-selection) + ;; Should run at beginning of `helm-select-action'. + (add-hook 'helm-select-action-hook 'helm-adaptive-store-selection)) + (helm-adaptive-save-history) + (setq helm-adaptive-history nil) + (remove-hook 'kill-emacs-hook 'helm-adaptive-save-history) + (remove-hook 'helm-before-initialize-hook 'helm-adaptive-done-reset) + (remove-hook 'helm-before-action-hook 'helm-adaptive-store-selection) + (remove-hook 'helm-select-action-hook 'helm-adaptive-store-selection))) + +(defun helm-adapt-use-adaptive-p (&optional source-name) + "Return current source only if it use adaptive history, nil otherwise." + (when helm-adaptive-mode + (let* ((source (or source-name (helm-get-current-source))) + (adapt-source (or (assoc-default 'filtered-candidate-transformer source) + (assoc-default 'candidate-transformer source)))) + (if (listp adapt-source) + (and (memq 'helm-adaptive-sort adapt-source) source) + (and (eq adapt-source 'helm-adaptive-sort) source))))) + +(defun helm-adaptive-store-selection () + "Store history information for the selected candidate." + (unless helm-adaptive-done + (setq helm-adaptive-done t) + (let ((source (helm-adapt-use-adaptive-p))) + (when source + (let* ((source-name (assoc-default 'name source)) + (source-info (or (assoc source-name helm-adaptive-history) + (progn + (push (list source-name) helm-adaptive-history) + (car helm-adaptive-history)))) + (selection (helm-get-selection nil t)) + (selection-info (progn + (setcdr source-info + (cons + (let ((found (assoc selection (cdr source-info)))) + (if (not found) + ;; new entry + (list selection) + ;; move entry to the beginning of the + ;; list, so that it doesn't get + ;; trimmed when the history is + ;; truncated + (setcdr source-info + (delete found (cdr source-info))) + found)) + (cdr source-info))) + (cadr source-info))) + (pattern-info (progn + (setcdr selection-info + (cons + (let ((found (assoc helm-pattern (cdr selection-info)))) + (if (not found) + ;; new entry + (cons helm-pattern 0) + ;; move entry to the beginning of the + ;; list, so if two patterns used the + ;; same number of times then the one + ;; used last appears first in the list + (setcdr selection-info + (delete found (cdr selection-info))) + found)) + (cdr selection-info))) + (cadr selection-info))) + (timestamp-info (helm-aif (assq 'timestamp (cdr selection-info)) + it + (setcdr selection-info (cons (cons 'timestamp 0) (cdr selection-info))) + (cadr selection-info)))) + ;; Increase usage count. + (setcdr pattern-info (1+ (cdr pattern-info))) + ;; Update timestamp. + (setcdr timestamp-info (float-time)) + ;; Truncate history if needed. + (if (> (length (cdr selection-info)) helm-adaptive-history-length) + (setcdr selection-info + (cl-subseq (cdr selection-info) 0 helm-adaptive-history-length)))))))) + +(defun helm-adaptive-maybe-load-history () + "Load `helm-adaptive-history-file' which contain `helm-adaptive-history'. +Returns nil if `helm-adaptive-history-file' doesn't exist." + (when (and helm-adaptive-history-file + (file-readable-p helm-adaptive-history-file)) + (load-file helm-adaptive-history-file))) + +(defun helm-adaptive-save-history (&optional arg) + "Save history information to file given by `helm-adaptive-history-file'." + (interactive "p") + (when helm-adaptive-history-file + (with-temp-buffer + (insert + ";; -*- mode: emacs-lisp -*-\n" + ";; History entries used for helm adaptive display.\n") + (let (print-length print-level) + (prin1 `(setq helm-adaptive-history ',helm-adaptive-history) + (current-buffer))) + (insert ?\n) + (write-region (point-min) (point-max) helm-adaptive-history-file nil + (unless arg 'quiet))))) + +(defun helm-adaptive-sort (candidates source) + "Sort the CANDIDATES for SOURCE by usage frequency. +This is a filtered candidate transformer you can use with the +`filtered-candidate-transformer' attribute." + (let* ((source-name (assoc-default 'name source)) + (source-info (assoc source-name helm-adaptive-history))) + (if source-info + (let ((usage + ;; Loop in the SOURCE entry of `helm-adaptive-history' + ;; and assemble a list containing the (CANDIDATE + ;; . USAGE-COUNT) pairs. + (cl-loop with cf = (if helm-adaptive-sort-by-frequent-recent-usage + helm-adaptive-freq-coefficient 1) + with cr = helm-adaptive-recent-coefficient + for (src-cand . infos) in (cdr source-info) + for count-freq = 0 + for count-rec = + (helm-aif (and helm-adaptive-sort-by-frequent-recent-usage + (assq 'timestamp infos)) + (* cr (+ (float-time) (cdr it))) + 0) + do (cl-loop for (pattern . score) in + (remove (assq 'timestamp infos) infos) + ;; If current pattern is equal to + ;; the previously used one then + ;; this candidate has priority + ;; (that's why its count-freq is + ;; boosted by 10000) and it only + ;; has to compete with other + ;; candidates which were also + ;; selected with the same pattern. + if (equal pattern helm-pattern) + return (setq count-freq (+ 10000 score)) + else do (cl-incf count-freq score)) + and collect (cons src-cand (+ (* count-freq cf) count-rec)) + into results + ;; Sort the list in descending order, so + ;; candidates with highest priority come + ;; first. + finally return + (sort results (lambda (first second) + (> (cdr first) (cdr second))))))) + (if (consp usage) + ;; Put those candidates first which have the highest usage count. + (cl-loop for (cand . _freq) in usage + for info = (or (and (assq 'multiline source) + (replace-regexp-in-string + "\n\\'" "" cand)) + cand) + when (cl-member info candidates + :test 'helm-adaptive-compare) + collect (car it) into sorted + and do (setq candidates + (cl-remove info candidates + :test 'helm-adaptive-compare)) + finally return (append sorted candidates)) + (message "Your `%s' is maybe corrupted or too old, \ +you should reinitialize it with `helm-reset-adaptive-history'" + helm-adaptive-history-file) + (sit-for 1) + candidates)) + ;; if there is no information stored for this source then do nothing + candidates))) + +;;;###autoload +(defun helm-reset-adaptive-history () + "Delete all `helm-adaptive-history' and his file. +Useful when you have a old or corrupted `helm-adaptive-history-file'." + (interactive) + (when (y-or-n-p "Really delete all your `helm-adaptive-history'? ") + (setq helm-adaptive-history nil) + (delete-file helm-adaptive-history-file))) + +(defun helm-adaptive-compare (x y) + "Compare display parts if some of candidates X and Y. + +Arguments X and Y are cons cell in (DISPLAY . REAL) format or atoms." + (equal (if (listp x) (car x) x) + (if (listp y) (car y) y))) + + +(provide 'helm-adaptive) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-adaptive.el ends here diff --git a/elpa/helm-20181113.923/helm-autoloads.el b/elpa/helm-20181113.923/helm-autoloads.el new file mode 100644 index 00000000..6e4a3959 --- /dev/null +++ b/elpa/helm-20181113.923/helm-autoloads.el @@ -0,0 +1,1103 @@ +;;; helm-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "helm-adaptive" "helm-adaptive.el" (0 0 0 0)) +;;; Generated autoloads from helm-adaptive.el + +(defvar helm-adaptive-mode nil "\ +Non-nil if Helm-Adaptive mode is enabled. +See the `helm-adaptive-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `helm-adaptive-mode'.") + +(custom-autoload 'helm-adaptive-mode "helm-adaptive" nil) + +(autoload 'helm-adaptive-mode "helm-adaptive" "\ +Toggle adaptive sorting in all sources. + +\(fn &optional ARG)" t nil) + +(autoload 'helm-reset-adaptive-history "helm-adaptive" "\ +Delete all `helm-adaptive-history' and his file. +Useful when you have a old or corrupted `helm-adaptive-history-file'. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-adaptive" '("helm-adapt"))) + +;;;*** + +;;;### (autoloads nil "helm-bookmark" "helm-bookmark.el" (0 0 0 0)) +;;; Generated autoloads from helm-bookmark.el + +(autoload 'helm-bookmarks "helm-bookmark" "\ +Preconfigured `helm' for bookmarks. + +\(fn)" t nil) + +(autoload 'helm-filtered-bookmarks "helm-bookmark" "\ +Preconfigured helm for bookmarks (filtered by category). +Optional source `helm-source-bookmark-addressbook' is loaded +only if external addressbook-bookmark package is installed. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-bookmark" '("helm-" "bmkext-jump-" "bookmark"))) + +;;;*** + +;;;### (autoloads nil "helm-buffers" "helm-buffers.el" (0 0 0 0)) +;;; Generated autoloads from helm-buffers.el + +(autoload 'helm-buffers-list "helm-buffers" "\ +Preconfigured `helm' to list buffers. + +\(fn)" t nil) + +(autoload 'helm-mini "helm-buffers" "\ +Preconfigured `helm' lightweight version (buffer -> recentf). + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-buffers" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-color" "helm-color.el" (0 0 0 0)) +;;; Generated autoloads from helm-color.el + +(autoload 'helm-colors "helm-color" "\ +Preconfigured `helm' for color. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-color" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-command" "helm-command.el" (0 0 0 0)) +;;; Generated autoloads from helm-command.el + +(autoload 'helm-M-x "helm-command" "\ +Preconfigured `helm' for Emacs commands. +It is `helm' replacement of regular `M-x' `execute-extended-command'. + +Unlike regular `M-x' emacs vanilla `execute-extended-command' command, +the prefix args if needed, can be passed AFTER starting `helm-M-x'. +When a prefix arg is passed BEFORE starting `helm-M-x', the first `C-u' +while in `helm-M-x' session will disable it. + +You can get help on each command by persistent action. + +\(fn ARG &optional COMMAND-NAME)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-command" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-config" "helm-config.el" (0 0 0 0)) +;;; Generated autoloads from helm-config.el + +(autoload 'helm-configuration "helm-config" "\ +Customize `helm'. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-config" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-dabbrev" "helm-dabbrev.el" (0 0 0 0)) +;;; Generated autoloads from helm-dabbrev.el + +(autoload 'helm-dabbrev "helm-dabbrev" "\ +Preconfigured helm for dynamic abbreviations. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-dabbrev" '("helm-dabbrev-"))) + +;;;*** + +;;;### (autoloads nil "helm-elisp" "helm-elisp.el" (0 0 0 0)) +;;; Generated autoloads from helm-elisp.el + +(autoload 'helm-lisp-completion-at-point "helm-elisp" "\ +Preconfigured helm for lisp symbol completion at point. + +\(fn)" t nil) + +(autoload 'helm-complete-file-name-at-point "helm-elisp" "\ +Preconfigured helm to complete file name at point. + +\(fn &optional FORCE)" t nil) + +(autoload 'helm-lisp-indent "helm-elisp" "\ + + +\(fn)" t nil) + +(autoload 'helm-lisp-completion-or-file-name-at-point "helm-elisp" "\ +Preconfigured helm to complete lisp symbol or filename at point. +Filename completion happen if string start after or between a double quote. + +\(fn)" t nil) + +(autoload 'helm-apropos "helm-elisp" "\ +Preconfigured helm to describe commands, functions, variables and faces. +In non interactives calls DEFAULT argument should be provided as a string, +i.e the `symbol-name' of any existing symbol. + +\(fn DEFAULT)" t nil) + +(autoload 'helm-manage-advice "helm-elisp" "\ +Preconfigured `helm' to disable/enable function advices. + +\(fn)" t nil) + +(autoload 'helm-locate-library "helm-elisp" "\ +Preconfigured helm to locate elisp libraries. + +\(fn)" t nil) + +(autoload 'helm-timers "helm-elisp" "\ +Preconfigured `helm' for timers. + +\(fn)" t nil) + +(autoload 'helm-complex-command-history "helm-elisp" "\ +Preconfigured helm for complex command history. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-elisp" '("helm-" "with-helm-show-completion"))) + +;;;*** + +;;;### (autoloads nil "helm-elisp-package" "helm-elisp-package.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from helm-elisp-package.el + +(autoload 'helm-list-elisp-packages "helm-elisp-package" "\ +Preconfigured helm for listing and handling emacs packages. + +\(fn ARG)" t nil) + +(autoload 'helm-list-elisp-packages-no-fetch "helm-elisp-package" "\ +Preconfigured helm for emacs packages. + +Same as `helm-list-elisp-packages' but don't fetch packages on remote. +Called with a prefix ARG always fetch packages on remote. + +\(fn ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-elisp-package" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-eshell" "helm-eshell.el" (0 0 0 0)) +;;; Generated autoloads from helm-eshell.el + +(autoload 'helm-esh-pcomplete "helm-eshell" "\ +Preconfigured helm to provide helm completion in eshell. + +\(fn)" t nil) + +(autoload 'helm-eshell-history "helm-eshell" "\ +Preconfigured helm for eshell history. + +\(fn)" t nil) + +(autoload 'helm-eshell-prompts "helm-eshell" "\ +Pre-configured `helm' to browse the prompts of the current Eshell. + +\(fn)" t nil) + +(autoload 'helm-eshell-prompts-all "helm-eshell" "\ +Pre-configured `helm' to browse the prompts of all Eshell sessions. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-eshell" '("helm-e"))) + +;;;*** + +;;;### (autoloads nil "helm-eval" "helm-eval.el" (0 0 0 0)) +;;; Generated autoloads from helm-eval.el + +(autoload 'helm-eval-expression "helm-eval" "\ +Preconfigured helm for `helm-source-evaluation-result'. + +\(fn ARG)" t nil) + +(autoload 'helm-eval-expression-with-eldoc "helm-eval" "\ +Preconfigured helm for `helm-source-evaluation-result' with `eldoc' support. + +\(fn)" t nil) + +(autoload 'helm-calcul-expression "helm-eval" "\ +Preconfigured helm for `helm-source-calculation-result'. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-eval" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-external" "helm-external.el" (0 0 0 0)) +;;; Generated autoloads from helm-external.el + +(autoload 'helm-run-external-command "helm-external" "\ +Preconfigured `helm' to run External PROGRAM asyncronously from Emacs. +If program is already running exit with error. +You can set your own list of commands with +`helm-external-commands-list'. + +\(fn PROGRAM)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-external" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-files" "helm-files.el" (0 0 0 0)) +;;; Generated autoloads from helm-files.el + +(autoload 'helm-projects-history "helm-files" "\ + + +\(fn)" t nil) + +(autoload 'helm-browse-project "helm-files" "\ +Preconfigured helm to browse projects. +Browse files and see status of project with its vcs. +Only HG and GIT are supported for now. +Fall back to `helm-browse-project-find-files' +if current directory is not under control of one of those vcs. +With a prefix ARG browse files recursively, with two prefix ARG +rebuild the cache. +If the current directory is found in the cache, start +`helm-browse-project-find-files' even with no prefix ARG. +NOTE: The prefix ARG have no effect on the VCS controlled directories. + +Needed dependencies for VCS: + +and +. + +\(fn ARG)" t nil) + +(autoload 'helm-find-files "helm-files" "\ +Preconfigured `helm' for helm implementation of `find-file'. +Called with a prefix arg show history if some. +Don't call it from programs, use `helm-find-files-1' instead. +This is the starting point for nearly all actions you can do on files. + +\(fn ARG)" t nil) + +(autoload 'helm-delete-tramp-connection "helm-files" "\ +Allow deleting tramp connection or marked tramp connections at once. + +This replace `tramp-cleanup-connection' which is partially broken in +emacs < to 25.1.50.1 (See Emacs Bug#24432). + +It allows additionally to delete more than one connection at once. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-files" '("helm-" "eshell-command-aliases-list"))) + +;;;*** + +;;;### (autoloads nil "helm-find" "helm-find.el" (0 0 0 0)) +;;; Generated autoloads from helm-find.el + +(autoload 'helm-find "helm-find" "\ +Preconfigured `helm' for the find shell command. + +Recursively find files whose names are matched by all specified +globbing PATTERNs under the current directory using the external +program specified in `find-program' (usually \"find\"). Every +input PATTERN is silently wrapped into two stars: *PATTERN*. + +With prefix argument, prompt for a directory to search. + +When user option `helm-findutils-search-full-path' is non-nil, +match against complete paths, otherwise, against file names +without directory part. + +The (possibly empty) list of globbing PATTERNs can be followed by +the separator \"*\" plus any number of additional arguments that +are passed to \"find\" literally. + +\(fn ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-find" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-font" "helm-font.el" (0 0 0 0)) +;;; Generated autoloads from helm-font.el + +(autoload 'helm-select-xfont "helm-font" "\ +Preconfigured `helm' to select Xfont. + +\(fn)" t nil) + +(autoload 'helm-ucs "helm-font" "\ +Preconfigured helm for `ucs-names'. + +Called with a prefix arg force reloading cache. + +\(fn ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-font" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-for-files" "helm-for-files.el" (0 0 0 +;;;;;; 0)) +;;; Generated autoloads from helm-for-files.el + +(autoload 'helm-for-files "helm-for-files" "\ +Preconfigured `helm' for opening files. +Run all sources defined in `helm-for-files-preferred-list'. + +\(fn)" t nil) + +(autoload 'helm-multi-files "helm-for-files" "\ +Preconfigured helm like `helm-for-files' but running locate only on demand. + +Allow toggling back and forth from locate to others sources with +`helm-multi-files-toggle-locate-binding' key. +This avoid launching needlessly locate when what you search is already +found. + +\(fn)" t nil) + +(autoload 'helm-recentf "helm-for-files" "\ +Preconfigured `helm' for `recentf'. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-for-files" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-grep" "helm-grep.el" (0 0 0 0)) +;;; Generated autoloads from helm-grep.el + +(autoload 'helm-goto-precedent-file "helm-grep" "\ +Go to precedent file in helm grep/etags buffers. + +\(fn)" t nil) + +(autoload 'helm-goto-next-file "helm-grep" "\ +Go to precedent file in helm grep/etags buffers. + +\(fn)" t nil) + +(autoload 'helm-do-grep-ag "helm-grep" "\ +Preconfigured helm for grepping with AG in `default-directory'. +With prefix-arg prompt for type if available with your AG version. + +\(fn ARG)" t nil) + +(autoload 'helm-grep-do-git-grep "helm-grep" "\ +Preconfigured helm for git-grepping `default-directory'. +With a prefix arg ARG git-grep the whole repository. + +\(fn ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-grep" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-help" "helm-help.el" (0 0 0 0)) +;;; Generated autoloads from helm-help.el + +(autoload 'helm-documentation "helm-help" "\ +Preconfigured Helm for Helm documentation. +With a prefix arg refresh the documentation. + +Find here the documentation of all documented sources. + +\(fn)" t nil) + +(defvar helm-comp-read-mode-line "\\C/\\[helm-cr-empty-string]:Empty \\\\[helm-help]:Help \\[helm-select-action]:Act \\[helm-maybe-exit-minibuffer]/f1/f2/f-n:NthAct \\[helm-toggle-suspend-update]:Tog.suspend") + +(defvar helm-read-file-name-mode-line-string "\\\\[helm-help]:Help C/\\[helm-cr-empty-string]:Empty \\\\[helm-select-action]:Act \\[helm-maybe-exit-minibuffer]/f1/f2/f-n:NthAct \\[helm-toggle-suspend-update]:Tog.suspend" "\ +String displayed in mode-line in `helm-source-find-files'.") + +(defvar helm-top-mode-line "\\\\[helm-help]:Help \\\\[helm-select-action]:Act \\[helm-maybe-exit-minibuffer]/f1/f2/f-n:NthAct \\[helm-toggle-suspend-update]:Tog.suspend") + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-help" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-id-utils" "helm-id-utils.el" (0 0 0 0)) +;;; Generated autoloads from helm-id-utils.el + +(autoload 'helm-gid "helm-id-utils" "\ +Preconfigured helm for `gid' command line of `ID-Utils'. +Need A database created with the command `mkid' +above `default-directory'. +Need id-utils as dependency which provide `mkid', `gid' etc... +See . + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-id-utils" '("helm-gid-"))) + +;;;*** + +;;;### (autoloads nil "helm-imenu" "helm-imenu.el" (0 0 0 0)) +;;; Generated autoloads from helm-imenu.el + +(autoload 'helm-imenu "helm-imenu" "\ +Preconfigured `helm' for `imenu'. + +\(fn)" t nil) + +(autoload 'helm-imenu-in-all-buffers "helm-imenu" "\ +Preconfigured helm for fetching imenu entries in all buffers with similar mode as current. +A mode is similar as current if it is the same, it is derived i.e `derived-mode-p' +or it have an association in `helm-imenu-all-buffer-assoc'. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-imenu" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-info" "helm-info.el" (0 0 0 0)) +;;; Generated autoloads from helm-info.el + +(autoload 'helm-info "helm-info" "\ +Preconfigured `helm' for searching Info files' indices. + +With a prefix argument \\[universal-argument], set REFRESH to non-nil. + +Optional parameter REFRESH, when non-nil, reevaluates +`helm-default-info-index-list'. If the variable has been +customized, set it to its saved value. If not, set it to its +standard value. See `custom-reevaluate-setting' for more. + +REFRESH is useful when new Info files are installed. If +`helm-default-info-index-list' has not been customized, the new +Info files are made available. + +\(fn &optional REFRESH)" t nil) + +(autoload 'helm-info-at-point "helm-info" "\ +Preconfigured `helm' for searching info at point. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-info" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-locate" "helm-locate.el" (0 0 0 0)) +;;; Generated autoloads from helm-locate.el + +(autoload 'helm-projects-find-files "helm-locate" "\ +Find files with locate in `helm-locate-project-list'. +With a prefix arg refresh the database in each project. + +\(fn UPDATE)" t nil) + +(autoload 'helm-locate "helm-locate" "\ +Preconfigured `helm' for Locate. +Note: you can add locate options after entering pattern. +See 'man locate' for valid options and also `helm-locate-command'. + +You can specify a local database with prefix argument ARG. +With two prefix arg, refresh the current local db or create it +if it doesn't exists. + +To create a user specific db, use +\"updatedb -l 0 -o db_path -U directory\". +Where db_path is a filename matched by +`helm-locate-db-file-regexp'. + +\(fn ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-locate" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-man" "helm-man.el" (0 0 0 0)) +;;; Generated autoloads from helm-man.el + +(autoload 'helm-man-woman "helm-man" "\ +Preconfigured `helm' for Man and Woman pages. +With a prefix arg reinitialize the cache. + +\(fn ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-man" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-misc" "helm-misc.el" (0 0 0 0)) +;;; Generated autoloads from helm-misc.el + +(autoload 'helm-world-time "helm-misc" "\ +Preconfigured `helm' to show world time. +Default action change TZ environment variable locally to emacs. + +\(fn)" t nil) + +(autoload 'helm-insert-latex-math "helm-misc" "\ +Preconfigured helm for latex math symbols completion. + +\(fn)" t nil) + +(autoload 'helm-ratpoison-commands "helm-misc" "\ +Preconfigured `helm' to execute ratpoison commands. + +\(fn)" t nil) + +(autoload 'helm-stumpwm-commands "helm-misc" "\ +Preconfigured helm for stumpwm commands. + +\(fn)" t nil) + +(autoload 'helm-minibuffer-history "helm-misc" "\ +Preconfigured `helm' for `minibuffer-history'. + +\(fn)" t nil) + +(autoload 'helm-comint-input-ring "helm-misc" "\ +Preconfigured `helm' that provide completion of `comint' history. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-misc" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-mode" "helm-mode.el" (0 0 0 0)) +;;; Generated autoloads from helm-mode.el + +(autoload 'helm-comp-read "helm-mode" "\ +Read a string in the minibuffer, with helm completion. + +It is helm `completing-read' equivalent. + +- PROMPT is the prompt name to use. + +- COLLECTION can be a list, vector, obarray or hash-table. + It can be also a function that receives three arguments: + the values string, predicate and t. See `all-completions' for more details. + +Keys description: + +- TEST: A predicate called with one arg i.e candidate. + +- INITIAL-INPUT: Same as input arg in `helm'. + +- PRESELECT: See preselect arg of `helm'. + +- DEFAULT: This option is used only for compatibility with regular + Emacs `completing-read' (Same as DEFAULT arg of `completing-read'). + +- BUFFER: Name of helm-buffer. + +- MUST-MATCH: Candidate selected must be one of COLLECTION. + +- FUZZY: Enable fuzzy matching. + +- REVERSE-HISTORY: When non--nil display history source after current + source completion. + +- REQUIRES-PATTERN: Same as helm attribute, default is 0. + +- HISTORY: A list containing specific history, default is nil. + When it is non--nil, all elements of HISTORY are displayed in + a special source before COLLECTION. + +- INPUT-HISTORY: A symbol. the minibuffer input history will be + stored there, if nil or not provided, `minibuffer-history' + will be used instead. + +- CASE-FOLD: Same as `helm-case-fold-search'. + +- DEL-INPUT: Boolean, when non--nil (default) remove the partial + minibuffer input from HISTORY is present. + +- PERSISTENT-ACTION: A function called with one arg i.e candidate. + +- PERSISTENT-HELP: A string to document PERSISTENT-ACTION. + +- MODE-LINE: A string or list to display in mode line. + Default is `helm-comp-read-mode-line'. + +- KEYMAP: A keymap to use in this `helm-comp-read'. + (the keymap will be shared with history source) + +- NAME: The name related to this local source. + +- HEADER-NAME: A function to alter NAME, see `helm'. + +- EXEC-WHEN-ONLY-ONE: Bound `helm-execute-action-at-once-if-one' + to non--nil. (possibles values are t or nil). + +- VOLATILE: Use volatile attribute. + +- SORT: A predicate to give to `sort' e.g `string-lessp' + Use this only on small data as it is ineficient. + If you want to sort faster add a sort function to + FC-TRANSFORMER. + Note that FUZZY when enabled is already providing a sort function. + +- FC-TRANSFORMER: A `filtered-candidate-transformer' function + or a list of functions. + +- HIST-FC-TRANSFORMER: A `filtered-candidate-transformer' + function for the history source. + +- MARKED-CANDIDATES: If non--nil return candidate or marked candidates as a list. + +- NOMARK: When non--nil don't allow marking candidates. + +- ALISTP: (default is non--nil) See `helm-comp-read-get-candidates'. + +- CANDIDATES-IN-BUFFER: when non--nil use a source build with + `helm-source-in-buffer' which is much faster. + Argument VOLATILE have no effect when CANDIDATES-IN-BUFFER is non--nil. + +- MATCH-PART: Allow matching only one part of candidate. + See match-part documentation in `helm-source'. + +- ALLOW-NEST: Allow nesting this `helm-comp-read' in a helm session. + See `helm'. + +- MULTILINE: See multiline in `helm-source'. + +Any prefix args passed during `helm-comp-read' invocation will be recorded +in `helm-current-prefix-arg', otherwise if prefix args were given before +`helm-comp-read' invocation, the value of `current-prefix-arg' will be used. +That's mean you can pass prefix args before or after calling a command +that use `helm-comp-read' See `helm-M-x' for example. + +\(fn PROMPT COLLECTION &key TEST INITIAL-INPUT DEFAULT PRESELECT (BUFFER \"*Helm Completions*\") MUST-MATCH FUZZY REVERSE-HISTORY (REQUIRES-PATTERN 0) HISTORY INPUT-HISTORY (CASE-FOLD helm-comp-read-case-fold-search) (DEL-INPUT t) (PERSISTENT-ACTION nil) (PERSISTENT-HELP \"DoNothing\") (MODE-LINE helm-comp-read-mode-line) HELP-MESSAGE (KEYMAP helm-comp-read-map) (NAME \"Helm Completions\") HEADER-NAME CANDIDATES-IN-BUFFER MATCH-PART EXEC-WHEN-ONLY-ONE QUIT-WHEN-NO-CAND (VOLATILE t) SORT FC-TRANSFORMER HIST-FC-TRANSFORMER MARKED-CANDIDATES NOMARK (ALISTP t) (CANDIDATE-NUMBER-LIMIT helm-candidate-number-limit) MULTILINE ALLOW-NEST)" nil nil) + +(autoload 'helm-read-file-name "helm-mode" "\ +Read a file name with helm completion. +It is helm `read-file-name' emulation. + +Argument PROMPT is the default prompt to use. + +Keys description: + +- NAME: Source name, default to \"Read File Name\". + +- INITIAL-INPUT: Where to start read file name, default to `default-directory'. + +- BUFFER: `helm-buffer' name default to \"*Helm Completions*\". + +- TEST: A predicate called with one arg 'candidate'. + +- CASE-FOLD: Same as `helm-case-fold-search'. + +- PRESELECT: helm preselection. + +- HISTORY: Display HISTORY in a special source. + +- MUST-MATCH: Can be 'confirm, nil, or t. + +- FUZZY: Enable fuzzy matching when non-nil (Enabled by default). + +- MARKED-CANDIDATES: When non--nil return a list of marked candidates. + +- NOMARK: When non--nil don't allow marking candidates. + +- ALISTP: Don't use `all-completions' in history (take effect only on history). + +- PERSISTENT-ACTION-IF: a persistent if action function. + +- PERSISTENT-HELP: persistent help message. + +- MODE-LINE: A mode line message, default is `helm-read-file-name-mode-line-string'. + +\(fn PROMPT &key (NAME \"Read File Name\") (INITIAL-INPUT default-directory) (BUFFER \"*Helm file completions*\") TEST (CASE-FOLD helm-file-name-case-fold-search) PRESELECT HISTORY MUST-MATCH (FUZZY t) DEFAULT MARKED-CANDIDATES (CANDIDATE-NUMBER-LIMIT helm-ff-candidate-number-limit) NOMARK (ALISTP t) (PERSISTENT-ACTION-IF \\='helm-find-files-persistent-action-if) (PERSISTENT-HELP \"Hit1 Expand Candidate, Hit2 or (C-u) Find file\") (MODE-LINE helm-read-file-name-mode-line-string))" nil nil) + +(defvar helm-mode nil "\ +Non-nil if Helm mode is enabled. +See the `helm-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `helm-mode'.") + +(custom-autoload 'helm-mode "helm-mode" nil) + +(autoload 'helm-mode "helm-mode" "\ +Toggle generic helm completion. + +All functions in Emacs that use `completing-read' +or `read-file-name' and friends will use helm interface +when this mode is turned on. + +However you can modify this behavior for functions of your choice +with `helm-completing-read-handlers-alist'. + +Also commands using `completion-in-region' will be helmized when +`helm-mode-handle-completion-in-region' is non nil, you can modify +this behavior with `helm-mode-no-completion-in-region-in-modes'. + +Called with a positive arg, turn on unconditionally, with a +negative arg turn off. +You can turn it on with `helm-mode'. + +Some crap emacs functions may not be supported, +e.g `ffap-alternate-file' and maybe others +You can add such functions to `helm-completing-read-handlers-alist' +with a nil value. + +About `ido-mode': +When you are using `helm-mode', DO NOT use `ido-mode', instead if you +want some commands use `ido', add these commands to +`helm-completing-read-handlers-alist' with `ido' as value. + +Note: This mode is incompatible with Emacs23. + +\(fn &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-mode" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-net" "helm-net.el" (0 0 0 0)) +;;; Generated autoloads from helm-net.el + +(autoload 'helm-browse-url-firefox "helm-net" "\ +Same as `browse-url-firefox' but detach from emacs. + +So when you quit emacs you can keep your firefox session open +and not be prompted to kill firefox process. + +NOTE: Probably not supported on some systems (e.g Windows). + +\(fn URL &optional IGNORE)" t nil) + +(autoload 'helm-browse-url-opera "helm-net" "\ +Browse URL with opera browser and detach from emacs. + +So when you quit emacs you can keep your opera session open +and not be prompted to kill opera process. + +NOTE: Probably not supported on some systems (e.g Windows). + +\(fn URL &optional IGNORE)" t nil) + +(autoload 'helm-browse-url-chromium "helm-net" "\ +Browse URL with google chrome browser. + +\(fn URL &optional IGNORE)" t nil) + +(autoload 'helm-browse-url-uzbl "helm-net" "\ +Browse URL with uzbl browser. + +\(fn URL &optional IGNORE)" t nil) + +(autoload 'helm-browse-url-conkeror "helm-net" "\ +Browse URL with conkeror browser. + +\(fn URL &optional IGNORE)" t nil) + +(autoload 'helm-surfraw "helm-net" "\ +Preconfigured `helm' to search PATTERN with search ENGINE. + +\(fn PATTERN ENGINE)" t nil) + +(autoload 'helm-google-suggest "helm-net" "\ +Preconfigured `helm' for google search with google suggest. + +\(fn)" t nil) + +(autoload 'helm-wikipedia-suggest "helm-net" "\ +Preconfigured `helm' for Wikipedia lookup with Wikipedia suggest. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-net" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-org" "helm-org.el" (0 0 0 0)) +;;; Generated autoloads from helm-org.el + +(autoload 'helm-org-agenda-files-headings "helm-org" "\ +Preconfigured helm for org files headings. + +\(fn)" t nil) + +(autoload 'helm-org-in-buffer-headings "helm-org" "\ +Preconfigured helm for org buffer headings. + +\(fn)" t nil) + +(autoload 'helm-org-parent-headings "helm-org" "\ +Preconfigured helm for org headings that are parents of the +current heading. + +\(fn)" t nil) + +(autoload 'helm-org-capture-templates "helm-org" "\ +Preconfigured helm for org templates. + +\(fn)" t nil) + +(autoload 'helm-org-completing-read-tags "helm-org" "\ +Completing read function for Org tags. + +This function is used as a `completing-read' function in +`helm-completing-read-handlers-alist' by `org-set-tags' and +`org-capture'. + +NOTE: Org tag completion will work only if you disable org fast tag +selection, see (info \"(org) setting tags\"). + +\(fn PROMPT COLLECTION PRED REQ INITIAL HIST DEF INHERIT-INPUT-METHOD NAME BUFFER)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-org" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-regexp" "helm-regexp.el" (0 0 0 0)) +;;; Generated autoloads from helm-regexp.el + +(autoload 'helm-moccur-mode "helm-regexp" "\ +Major mode to provide actions in helm moccur saved buffer. + +Special commands: +\\{helm-moccur-mode-map} + +\(fn)" t nil) + +(autoload 'helm-regexp "helm-regexp" "\ +Preconfigured helm to build regexps. +`query-replace-regexp' can be run from there against found regexp. + +\(fn)" t nil) + +(autoload 'helm-occur "helm-regexp" "\ +Preconfigured helm for searching lines matching pattern in `current-buffer'. + +When `helm-source-occur' is member of +`helm-sources-using-default-as-input' which is the default, +symbol at point is searched at startup. + +When a region is marked search only in this region by narrowing. + +To search in multiples buffers start from one of the commands listing +buffers (i.e. a helm command using `helm-source-buffers-list' like +`helm-mini') and use the multi occur buffers action. + +This is the helm implementation that collect lines matching pattern +like vanilla emacs `occur' but have nothing to do with it, the search +engine beeing completely different. + +\(fn)" t nil) + +(autoload 'helm-occur-from-isearch "helm-regexp" "\ +Invoke `helm-occur' from isearch. + +\(fn)" t nil) + +(autoload 'helm-multi-occur-from-isearch "helm-regexp" "\ +Invoke `helm-multi-occur' from isearch. + +With a prefix arg, reverse the behavior of +`helm-moccur-always-search-in-current'. +The prefix arg can be set before calling +`helm-multi-occur-from-isearch' or during the buffer selection. + +\(fn &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-regexp" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-ring" "helm-ring.el" (0 0 0 0)) +;;; Generated autoloads from helm-ring.el + +(autoload 'helm-mark-ring "helm-ring" "\ +Preconfigured `helm' for `helm-source-mark-ring'. + +\(fn)" t nil) + +(autoload 'helm-global-mark-ring "helm-ring" "\ +Preconfigured `helm' for `helm-source-global-mark-ring'. + +\(fn)" t nil) + +(autoload 'helm-all-mark-rings "helm-ring" "\ +Preconfigured `helm' for `helm-source-global-mark-ring' and `helm-source-mark-ring'. + +\(fn)" t nil) + +(autoload 'helm-register "helm-ring" "\ +Preconfigured `helm' for Emacs registers. + +\(fn)" t nil) + +(autoload 'helm-show-kill-ring "helm-ring" "\ +Preconfigured `helm' for `kill-ring'. +It is drop-in replacement of `yank-pop'. + +First call open the kill-ring browser, next calls move to next line. + +\(fn)" t nil) + +(autoload 'helm-execute-kmacro "helm-ring" "\ +Preconfigured helm for keyboard macros. +Define your macros with `f3' and `f4'. +See (info \"(emacs) Keyboard Macros\") for detailed infos. +This command is useful when used with persistent action. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-ring" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-semantic" "helm-semantic.el" (0 0 0 0)) +;;; Generated autoloads from helm-semantic.el + +(autoload 'helm-semantic "helm-semantic" "\ +Preconfigured `helm' for `semantic'. +If ARG is supplied, pre-select symbol at point instead of current + +\(fn ARG)" t nil) + +(autoload 'helm-semantic-or-imenu "helm-semantic" "\ +Preconfigured helm for `semantic' or `imenu'. +If ARG is supplied, pre-select symbol at point instead of current +semantic tag in scope. + +If `semantic-mode' is active in the current buffer, then use +semantic for generating tags, otherwise fall back to `imenu'. +Fill in the symbol at point by default. + +\(fn ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-semantic" '("helm-s"))) + +;;;*** + +;;;### (autoloads nil "helm-sys" "helm-sys.el" (0 0 0 0)) +;;; Generated autoloads from helm-sys.el + +(defvar helm-top-poll-mode nil "\ +Non-nil if Helm-Top-Poll mode is enabled. +See the `helm-top-poll-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `helm-top-poll-mode'.") + +(custom-autoload 'helm-top-poll-mode "helm-sys" nil) + +(autoload 'helm-top-poll-mode "helm-sys" "\ +Refresh automatically helm top buffer once enabled. + +\(fn &optional ARG)" t nil) + +(autoload 'helm-top "helm-sys" "\ +Preconfigured `helm' for top command. + +\(fn)" t nil) + +(autoload 'helm-list-emacs-process "helm-sys" "\ +Preconfigured `helm' for emacs process. + +\(fn)" t nil) + +(autoload 'helm-xrandr-set "helm-sys" "\ +Preconfigured helm for xrandr. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-sys" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-tags" "helm-tags.el" (0 0 0 0)) +;;; Generated autoloads from helm-tags.el + +(autoload 'helm-etags-select "helm-tags" "\ +Preconfigured helm for etags. +If called with a prefix argument REINIT +or if any of the tag files have been modified, reinitialize cache. + +This function aggregates three sources of tag files: + + 1) An automatically located file in the parent directories, + by `helm-etags-get-tag-file'. + 2) `tags-file-name', which is commonly set by `find-tag' command. + 3) `tags-table-list' which is commonly set by `visit-tags-table' command. + +\(fn REINIT)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-tags" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-types" "helm-types.el" (0 0 0 0)) +;;; Generated autoloads from helm-types.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-types" '("helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-utils" "helm-utils.el" (0 0 0 0)) +;;; Generated autoloads from helm-utils.el + +(defvar helm-popup-tip-mode nil "\ +Non-nil if Helm-Popup-Tip mode is enabled. +See the `helm-popup-tip-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `helm-popup-tip-mode'.") + +(custom-autoload 'helm-popup-tip-mode "helm-utils" nil) + +(autoload 'helm-popup-tip-mode "helm-utils" "\ +Show help-echo informations in a popup tip at end of line. + +\(fn &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-utils" '("helm-" "with-helm-display-marked-candidates"))) + +;;;*** + +;;;### (autoloads nil "helm-x-files" "helm-x-files.el" (0 0 0 0)) +;;; Generated autoloads from helm-x-files.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-x-files" '("helm-"))) + +;;;*** + +;;;### (autoloads nil nil ("helm-easymenu.el" "helm-pkg.el") (0 0 +;;;;;; 0 0)) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; helm-autoloads.el ends here diff --git a/elpa/helm-20181113.923/helm-bookmark.el b/elpa/helm-20181113.923/helm-bookmark.el new file mode 100644 index 00000000..0c7af085 --- /dev/null +++ b/elpa/helm-20181113.923/helm-bookmark.el @@ -0,0 +1,737 @@ +;;; helm-bookmark.el --- Helm for Emacs regular Bookmarks. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: +(require 'cl-lib) +(require 'bookmark) +(require 'helm) +(require 'helm-lib) +(require 'helm-help) +(require 'helm-types) +(require 'helm-utils) +(require 'helm-info) +(require 'helm-adaptive) +(require 'helm-net) + +(declare-function helm-browse-project "helm-files" (arg)) +(declare-function addressbook-bookmark-edit "ext:addressbook-bookmark.el" (bookmark)) + +(defgroup helm-bookmark nil + "Predefined configurations for `helm.el'." + :group 'helm) + +(defcustom helm-bookmark-show-location nil + "Show location of bookmark on display." + :group 'helm-bookmark + :type 'boolean) + +(defcustom helm-bookmark-default-filtered-sources + (append '(helm-source-bookmark-org + helm-source-bookmark-files&dirs + helm-source-bookmark-helm-find-files + helm-source-bookmark-info + helm-source-bookmark-gnus + helm-source-bookmark-man + helm-source-bookmark-images + helm-source-bookmark-w3m) + (list 'helm-source-bookmark-uncategorized + 'helm-source-bookmark-set)) + "List of sources to use in `helm-filtered-bookmarks'." + :group 'helm-bookmark + :type '(repeat (choice symbol))) + + +(defface helm-bookmark-info + '((t (:foreground "green"))) + "Face used for W3m Emacs bookmarks (not w3m bookmarks)." + :group 'helm-bookmark) + +(defface helm-bookmark-w3m + '((t (:foreground "yellow"))) + "Face used for W3m Emacs bookmarks (not w3m bookmarks)." + :group 'helm-bookmark) + +(defface helm-bookmark-gnus + '((t (:foreground "magenta"))) + "Face used for Gnus bookmarks." + :group 'helm-bookmark) + +(defface helm-bookmark-man + '((t (:foreground "Orange4"))) + "Face used for Woman/man bookmarks." + :group 'helm-bookmark) + +(defface helm-bookmark-file + '((t (:foreground "Deepskyblue2"))) + "Face used for file bookmarks." + :group 'helm-bookmark) + +(defface helm-bookmark-file-not-found + '((t (:foreground "Slategray4"))) + "Face used for file bookmarks." + :group 'helm-bookmark) + +(defface helm-bookmark-directory + '((t (:inherit helm-ff-directory))) + "Face used for file bookmarks." + :group 'helm-bookmark) + +(defface helm-bookmark-addressbook + '((t (:foreground "tomato"))) + "Face used for addressbook bookmarks." + :group 'helm-bookmark) + + +(defvar helm-bookmark-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "C-c o") 'helm-bookmark-run-jump-other-window) + (define-key map (kbd "C-c C-o") 'helm-bookmark-run-jump-other-frame) + (define-key map (kbd "C-d") 'helm-bookmark-run-delete) + (define-key map (kbd "C-]") 'helm-bookmark-toggle-filename) + (define-key map (kbd "M-e") 'helm-bookmark-run-edit) + map) + "Generic Keymap for emacs bookmark sources.") + +(defclass helm-source-basic-bookmarks (helm-source-in-buffer helm-type-bookmark) + ((init :initform (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global + (bookmark-all-names)))) + (filtered-candidate-transformer :initform 'helm-bookmark-transformer))) + +(defvar helm-source-bookmarks + (helm-make-source "Bookmarks" 'helm-source-basic-bookmarks) + "See (info \"(emacs)Bookmarks\").") + +(defun helm-bookmark-transformer (candidates _source) + (cl-loop for i in candidates + for loc = (bookmark-location i) + for len = (string-width i) + for trunc = (if (> len bookmark-bmenu-file-column) + (helm-substring i bookmark-bmenu-file-column) + i) + for sep = (make-string (- (+ bookmark-bmenu-file-column 2) + (length trunc)) + ? ) + if helm-bookmark-show-location + collect (cons (concat trunc sep (if (listp loc) (car loc) loc)) i) + else collect i)) + +(defun helm-bookmark-toggle-filename-1 (_candidate) + (let* ((real (helm-get-selection helm-buffer)) + (trunc (if (> (string-width real) bookmark-bmenu-file-column) + (helm-substring real bookmark-bmenu-file-column) + real)) + (loc (bookmark-location real))) + (setq helm-bookmark-show-location (not helm-bookmark-show-location)) + (helm-update (if helm-bookmark-show-location + (concat (regexp-quote trunc) + " +" + (regexp-quote + (if (listp loc) (car loc) loc))) + (regexp-quote real))))) + +(defun helm-bookmark-toggle-filename () + "Toggle bookmark location visibility." + (interactive) + (with-helm-alive-p + (helm-attrset 'toggle-filename + '(helm-bookmark-toggle-filename-1 . never-split)) + (helm-execute-persistent-action 'toggle-filename))) +(put 'helm-bookmark-toggle-filename 'helm-only t) + +(defun helm-bookmark-jump (candidate) + "Jump to bookmark action." + (let ((current-prefix-arg helm-current-prefix-arg) + non-essential) + (bookmark-jump candidate))) + +(defun helm-bookmark-jump-other-frame (candidate) + "Jump to bookmark in other frame action." + (let ((current-prefix-arg helm-current-prefix-arg) + non-essential) + (bookmark-jump candidate 'switch-to-buffer-other-frame))) + +(defun helm-bookmark-jump-other-window (candidate) + "Jump to bookmark in other window action." + (let (non-essential) + (bookmark-jump-other-window candidate))) + + +;;; bookmark-set +;; +(defvar helm-source-bookmark-set + (helm-build-dummy-source "Set Bookmark" + :filtered-candidate-transformer + (lambda (_candidates _source) + (list (or (and (not (string= helm-pattern "")) + helm-pattern) + "Enter a bookmark name to record"))) + :action '(("Set bookmark" . (lambda (candidate) + (if (string= helm-pattern "") + (message "No bookmark name given for record") + (bookmark-set candidate)))))) + "See (info \"(emacs)Bookmarks\").") + + +;;; Predicates +;; +(defconst helm-bookmark--non-file-filename " - no file -" + "Name to use for `filename' entry, for non-file bookmarks.") + +(defun helm-bookmark-gnus-bookmark-p (bookmark) + "Return non-nil if BOOKMARK is a Gnus bookmark. +BOOKMARK is a bookmark name or a bookmark record." + (or (eq (bookmark-get-handler bookmark) 'bmkext-jump-gnus) + (eq (bookmark-get-handler bookmark) 'gnus-summary-bookmark-jump) + (eq (bookmark-get-handler bookmark) 'bookmarkp-jump-gnus))) + +(defun helm-bookmark-w3m-bookmark-p (bookmark) + "Return non-nil if BOOKMARK is a W3m bookmark. +BOOKMARK is a bookmark name or a bookmark record." + (or (eq (bookmark-get-handler bookmark) 'bmkext-jump-w3m) + (eq (bookmark-get-handler bookmark) 'bookmark-w3m-bookmark-jump) + (eq (bookmark-get-handler bookmark) 'bookmarkp-jump-w3m))) + +(defun helm-bookmark-woman-bookmark-p (bookmark) + "Return non-nil if BOOKMARK is a Woman bookmark. +BOOKMARK is a bookmark name or a bookmark record." + (or (eq (bookmark-get-handler bookmark) 'bmkext-jump-woman) + (eq (bookmark-get-handler bookmark) 'woman-bookmark-jump) + (eq (bookmark-get-handler bookmark) 'bookmarkp-jump-woman))) + +(defun helm-bookmark-man-bookmark-p (bookmark) + "Return non-nil if BOOKMARK is a Man bookmark. +BOOKMARK is a bookmark name or a bookmark record." + (or (eq (bookmark-get-handler bookmark) 'bmkext-jump-man) + (eq (bookmark-get-handler bookmark) 'Man-bookmark-jump) + (eq (bookmark-get-handler bookmark) 'bookmarkp-jump-man))) + +(defun helm-bookmark-woman-man-bookmark-p (bookmark) + "Return non-nil if BOOKMARK is a Man or Woman bookmark. +BOOKMARK is a bookmark name or a bookmark record." + (or (helm-bookmark-man-bookmark-p bookmark) + (helm-bookmark-woman-bookmark-p bookmark))) + +(defun helm-bookmark-info-bookmark-p (bookmark) + "Return non-nil if BOOKMARK is an Info bookmark. +BOOKMARK is a bookmark name or a bookmark record." + (eq (bookmark-get-handler bookmark) 'Info-bookmark-jump)) + +(defun helm-bookmark-image-bookmark-p (bookmark) + "Return non-nil if BOOKMARK bookmarks an image file." + (if (stringp bookmark) + (assq 'image-type (assq bookmark bookmark-alist)) + (assq 'image-type bookmark))) + +(defun helm-bookmark-file-p (bookmark) + "Return non-nil if BOOKMARK bookmarks a file or directory. +BOOKMARK is a bookmark name or a bookmark record. +This excludes bookmarks of a more specific kind (Info, Gnus, and W3m)." + (let* ((filename (bookmark-get-filename bookmark)) + (isnonfile (equal filename helm-bookmark--non-file-filename))) + (and filename (not isnonfile) (not (bookmark-get-handler bookmark))))) + +(defun helm-bookmark-org-file-p (bookmark) + (let* ((filename (bookmark-get-filename bookmark))) + (or (string-suffix-p ".org" filename t) + (string-suffix-p ".org_archive" filename t)))) + +(defun helm-bookmark-helm-find-files-p (bookmark) + "Return non-nil if BOOKMARK bookmarks a `helm-find-files' session. +BOOKMARK is a bookmark name or a bookmark record." + (eq (bookmark-get-handler bookmark) 'helm-ff-bookmark-jump)) + +(defun helm-bookmark-addressbook-p (bookmark) + "Return non--nil if BOOKMARK is a contact recorded with addressbook-bookmark. +BOOKMARK is a bookmark name or a bookmark record." + (if (listp bookmark) + (string= (assoc-default 'type bookmark) "addressbook") + (string= (assoc-default + 'type (assoc bookmark bookmark-alist)) "addressbook"))) + +(defun helm-bookmark-uncategorized-bookmark-p (bookmark) + "Return non--nil if BOOKMARK match no known category." + (cl-loop for pred in '(helm-bookmark-org-file-p + helm-bookmark-addressbook-p + helm-bookmark-gnus-bookmark-p + helm-bookmark-w3m-bookmark-p + helm-bookmark-woman-man-bookmark-p + helm-bookmark-info-bookmark-p + helm-bookmark-image-bookmark-p + helm-bookmark-file-p + helm-bookmark-helm-find-files-p + helm-bookmark-addressbook-p) + never (funcall pred bookmark))) + +(defun helm-bookmark-filter-setup-alist (fn) + "Return a filtered `bookmark-alist' sorted alphabetically." + (cl-loop for b in bookmark-alist + for name = (car b) + when (funcall fn b) collect + (propertize name 'location (bookmark-location name)))) + +;;; Bookmark handlers +;; +(defvar w3m-async-exec) +(defun helm-bookmark-jump-w3m (bookmark) + "Jump to W3m bookmark BOOKMARK, setting a new tab. +If `browse-url-browser-function' is set to something else +than `w3m-browse-url' use it." + (require 'helm-net) + (let* ((file (or (bookmark-prop-get bookmark 'filename) + (bookmark-prop-get bookmark 'url))) + (buf (generate-new-buffer-name "*w3m*")) + (w3m-async-exec nil) + ;; If user don't have anymore w3m installed let it browse its + ;; bookmarks with default browser otherwise assume bookmark + ;; have been bookmarked from w3m and use w3m. + (browse-url-browser-function (or (and (fboundp 'w3m-browse-url) + (executable-find "w3m") + 'w3m-browse-url) + browse-url-browser-function)) + (really-use-w3m (equal browse-url-browser-function 'w3m-browse-url))) + (helm-browse-url file really-use-w3m) + (when really-use-w3m + (bookmark-default-handler + `("" (buffer . ,buf) . ,(bookmark-get-bookmark-record bookmark)))))) + +;; All bookmarks recorded with the handler provided with w3m +;; (`bookmark-w3m-bookmark-jump') will use our handler which open +;; the bookmark in a new tab or in an external browser depending +;; on `browse-url-browser-function'. +(defalias 'bookmark-w3m-bookmark-jump 'helm-bookmark-jump-w3m) + +;; Provide compatibility with old handlers provided in external +;; packages bookmark-extensions.el and bookmark+. +(defalias 'bmkext-jump-woman 'woman-bookmark-jump) +(defalias 'bmkext-jump-man 'Man-bookmark-jump) +(defalias 'bmkext-jump-w3m 'helm-bookmark-jump-w3m) +(defalias 'bmkext-jump-gnus 'gnus-summary-bookmark-jump) +(defalias 'bookmarkp-jump-gnus 'gnus-summary-bookmark-jump) +(defalias 'bookmarkp-jump-w3m 'helm-bookmark-jump-w3m) +(defalias 'bookmarkp-jump-woman 'woman-bookmark-jump) +(defalias 'bookmarkp-jump-man 'Man-bookmark-jump) + + +;;;; Filtered bookmark sources +;; +;; +(defclass helm-source-filtered-bookmarks (helm-source-in-buffer helm-type-bookmark) + ((filtered-candidate-transformer + :initform '(helm-adaptive-sort + helm-highlight-bookmark)))) + +;;; W3m bookmarks. +;; +(defun helm-bookmark-w3m-setup-alist () + "Specialized filter function for bookmarks w3m." + (helm-bookmark-filter-setup-alist 'helm-bookmark-w3m-bookmark-p)) + +(defvar helm-source-bookmark-w3m + (helm-make-source "Bookmark W3m" 'helm-source-filtered-bookmarks + :init (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global (helm-bookmark-w3m-setup-alist))))) + +;;; Images +;; +(defun helm-bookmark-images-setup-alist () + "Specialized filter function for images bookmarks." + (helm-bookmark-filter-setup-alist 'helm-bookmark-image-bookmark-p)) + +(defvar helm-source-bookmark-images + (helm-make-source "Bookmark Images" 'helm-source-filtered-bookmarks + :init (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global (helm-bookmark-images-setup-alist))))) + +;;; Woman Man +;; +(defun helm-bookmark-man-setup-alist () + "Specialized filter function for bookmarks w3m." + (helm-bookmark-filter-setup-alist 'helm-bookmark-woman-man-bookmark-p)) + +(defvar helm-source-bookmark-man + (helm-make-source "Bookmark Woman&Man" 'helm-source-filtered-bookmarks + :init (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global (helm-bookmark-man-setup-alist))))) + +;;; Org files +;; +(defun helm-bookmark-org-setup-alist () + "Specialized filter function for Org file bookmarks." + (helm-bookmark-filter-setup-alist 'helm-bookmark-org-file-p)) + +(defvar helm-source-bookmark-org + (helm-make-source " Bookmarked Org files" 'helm-source-filtered-bookmarks + :init (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global (helm-bookmark-org-setup-alist))))) + +;;; Gnus +;; +(defun helm-bookmark-gnus-setup-alist () + "Specialized filter function for bookmarks gnus." + (helm-bookmark-filter-setup-alist 'helm-bookmark-gnus-bookmark-p)) + +(defvar helm-source-bookmark-gnus + (helm-make-source "Bookmark Gnus" 'helm-source-filtered-bookmarks + :init (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global (helm-bookmark-gnus-setup-alist))))) + +;;; Info +;; +(defun helm-bookmark-info-setup-alist () + "Specialized filter function for bookmarks info." + (helm-bookmark-filter-setup-alist 'helm-bookmark-info-bookmark-p)) + +(defvar helm-source-bookmark-info + (helm-make-source "Bookmark Info" 'helm-source-filtered-bookmarks + :init (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global (helm-bookmark-info-setup-alist))))) + +;;; Files and directories +;; +(defun helm-bookmark-local-files-setup-alist () + "Specialized filter function for bookmarks locals files." + (helm-bookmark-filter-setup-alist 'helm-bookmark-file-p)) + +(defvar helm-source-bookmark-files&dirs + (helm-make-source "Bookmark Files&Directories" 'helm-source-filtered-bookmarks + :init (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global (helm-bookmark-local-files-setup-alist))))) + +;;; Helm find files sessions. +;; +(defun helm-bookmark-helm-find-files-setup-alist () + "Specialized filter function for `helm-find-files' bookmarks." + (helm-bookmark-filter-setup-alist 'helm-bookmark-helm-find-files-p)) + +(defun helm-bookmark-browse-project (candidate) + "Run `helm-browse-project' from action." + (with-helm-default-directory + (bookmark-get-filename candidate) + (helm-browse-project nil))) + +(defun helm-bookmark-run-browse-project () + "Run `helm-bookmark-browse-project' from keyboard." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-bookmark-browse-project))) +(put 'helm-bookmark-run-browse-project 'helm-only t) + +(defvar helm-bookmark-find-files-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-bookmark-map) + (define-key map (kbd "C-x C-d") 'helm-bookmark-run-browse-project) + map)) + +(defclass helm-bookmark-override-inheritor (helm-source) ()) + +(defmethod helm--setup-source ((source helm-bookmark-override-inheritor)) + ;; Ensure `helm-source-in-buffer' method is called. + (call-next-method) + (setf (slot-value source 'action) + (helm-append-at-nth + (cl-loop for (name . action) in helm-type-bookmark-actions + unless (memq action '(helm-bookmark-jump-other-frame + helm-bookmark-jump-other-window)) + collect (cons name action)) + '(("Browse project" . helm-bookmark-browse-project)) 1)) + (setf (slot-value source 'keymap) helm-bookmark-find-files-map)) + +(defclass helm-bookmark-find-files-class (helm-source-filtered-bookmarks + helm-bookmark-override-inheritor) + ()) + +(defvar helm-source-bookmark-helm-find-files + (helm-make-source "Bookmark helm-find-files sessions" 'helm-bookmark-find-files-class + :init (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global (helm-bookmark-helm-find-files-setup-alist))) + :persistent-action (lambda (_candidate) (ignore)) + :persistent-help "Do nothing")) + +;;; Uncategorized bookmarks +;; +(defun helm-bookmark-uncategorized-setup-alist () + "Specialized filter function for uncategorized bookmarks." + (helm-bookmark-filter-setup-alist 'helm-bookmark-uncategorized-bookmark-p)) + +(defvar helm-source-bookmark-uncategorized + (helm-make-source "Bookmark uncategorized" 'helm-source-filtered-bookmarks + :init (lambda () + (bookmark-maybe-load-default-file) + (helm-init-candidates-in-buffer + 'global (helm-bookmark-uncategorized-setup-alist))))) + +;;; Transformer +;; + +(defun helm-highlight-bookmark (bookmarks _source) + "Used as `filtered-candidate-transformer' to colorize bookmarks." + (let ((non-essential t)) + (cl-loop for i in bookmarks + for isfile = (bookmark-get-filename i) + for hff = (helm-bookmark-helm-find-files-p i) + for handlerp = (and (fboundp 'bookmark-get-handler) + (bookmark-get-handler i)) + for isw3m = (and (fboundp 'helm-bookmark-w3m-bookmark-p) + (helm-bookmark-w3m-bookmark-p i)) + for isgnus = (and (fboundp 'helm-bookmark-gnus-bookmark-p) + (helm-bookmark-gnus-bookmark-p i)) + for isman = (and (fboundp 'helm-bookmark-man-bookmark-p) ; Man + (helm-bookmark-man-bookmark-p i)) + for iswoman = (and (fboundp 'helm-bookmark-woman-bookmark-p) ; Woman + (helm-bookmark-woman-bookmark-p i)) + for isannotation = (bookmark-get-annotation i) + for isabook = (string= (bookmark-prop-get i 'type) + "addressbook") + for isinfo = (eq handlerp 'Info-bookmark-jump) + for loc = (bookmark-location i) + for len = (string-width i) + for trunc = (if (and helm-bookmark-show-location + (> len bookmark-bmenu-file-column)) + (helm-substring + i bookmark-bmenu-file-column) + i) + ;; Add a * if bookmark have annotation + if (and isannotation (not (string-equal isannotation ""))) + do (setq trunc (concat "*" (if helm-bookmark-show-location trunc i))) + for sep = (and helm-bookmark-show-location + (make-string (- (+ bookmark-bmenu-file-column 2) + (string-width trunc)) + ? )) + for bmk = (cond ( ;; info buffers + isinfo + (propertize trunc 'face 'helm-bookmark-info + 'help-echo isfile)) + ( ;; w3m buffers + isw3m + (propertize trunc 'face 'helm-bookmark-w3m + 'help-echo isfile)) + ( ;; gnus buffers + isgnus + (propertize trunc 'face 'helm-bookmark-gnus + 'help-echo isfile)) + ( ;; Man Woman + (or iswoman isman) + (propertize trunc 'face 'helm-bookmark-man + 'help-echo isfile)) + ( ;; Addressbook + isabook + (propertize trunc 'face 'helm-bookmark-addressbook)) + (;; Directories (helm-find-files) + hff + (if (and (file-remote-p isfile) + (not (file-remote-p isfile nil t))) + (propertize trunc 'face 'helm-bookmark-file-not-found + 'help-echo isfile) + (propertize trunc 'face 'helm-bookmark-directory + 'help-echo isfile))) + ( ;; Directories (dired) + (and isfile + ;; This is needed because `non-essential' + ;; is not working on Emacs-24.2 and the behavior + ;; of tramp seems to have changed since previous + ;; versions (Need to reenter password even if a + ;; first connection have been established, + ;; probably when host is named differently + ;; i.e machine/localhost) + (and (not (file-remote-p isfile)) + (file-directory-p isfile))) + (propertize trunc 'face 'helm-bookmark-directory + 'help-echo isfile)) + ( ;; Non existing files. + (and isfile + ;; Be safe and call `file-exists-p' + ;; only if file is not remote or + ;; remote but connected. + (or (and (file-remote-p isfile) + (not (file-remote-p isfile nil t))) + (not (file-exists-p isfile)))) + (propertize trunc 'face 'helm-bookmark-file-not-found + 'help-echo isfile)) + ( ;; regular files + t + (propertize trunc 'face 'helm-bookmark-file + 'help-echo isfile))) + collect (if helm-bookmark-show-location + (cons (concat bmk sep (if (listp loc) (car loc) loc)) + i) + (cons bmk i))))) + + +;;; Edit/rename/save bookmarks. +;; +;; +(defun helm-bookmark-edit-bookmark (bookmark-name) + "Edit bookmark's name and file name, and maybe save them. +BOOKMARK-NAME is the current (old) name of the bookmark to be renamed." + (let ((bmk (helm-bookmark-get-bookmark-from-name bookmark-name)) + (handler (bookmark-prop-get bookmark-name 'handler))) + (if (eq handler 'addressbook-bookmark-jump) + (addressbook-bookmark-edit + (assoc bmk bookmark-alist)) + (helm-bookmark-edit-bookmark-1 bookmark-name handler)))) + +(defun helm-bookmark-edit-bookmark-1 (bookmark-name handler) + (let* ((helm--reading-passwd-or-string t) + (bookmark-fname (bookmark-get-filename bookmark-name)) + (bookmark-loc (bookmark-prop-get bookmark-name 'location)) + (new-name (read-from-minibuffer "Name: " bookmark-name)) + (new-loc (read-from-minibuffer "FileName or Location: " + (or bookmark-fname + (if (consp bookmark-loc) + (car bookmark-loc) + bookmark-loc)))) + (docid (and (eq handler 'mu4e-bookmark-jump) + (read-number "Docid: " (cdr bookmark-loc))))) + (when docid + (setq new-loc (cons new-loc docid))) + (when (and (not (equal new-name "")) (not (equal new-loc "")) + (y-or-n-p "Save changes? ")) + (if bookmark-fname + (progn + (helm-bookmark-rename bookmark-name new-name 'batch) + (bookmark-set-filename new-name new-loc)) + (bookmark-prop-set + (bookmark-get-bookmark bookmark-name) 'location new-loc) + (helm-bookmark-rename bookmark-name new-name 'batch)) + (helm-bookmark-maybe-save-bookmark) + (list new-name new-loc)))) + +(defun helm-bookmark-maybe-save-bookmark () + "Increment save counter and maybe save `bookmark-alist'." + (setq bookmark-alist-modification-count (1+ bookmark-alist-modification-count)) + (when (bookmark-time-to-save-p) (bookmark-save))) + +(defun helm-bookmark-rename (old &optional new batch) + "Change bookmark's name from OLD to NEW. +Interactively: + If called from the keyboard, then prompt for OLD. + If called from the menubar, select OLD from a menu. +If NEW is nil, then prompt for its string value. + +If BATCH is non-nil, then do not rebuild the menu list. + +While the user enters the new name, repeated `C-w' inserts consecutive +words from the buffer into the new bookmark name." + (interactive (list (bookmark-completing-read "Old bookmark name"))) + (bookmark-maybe-historicize-string old) + (bookmark-maybe-load-default-file) + (save-excursion (skip-chars-forward " ") (setq bookmark-yank-point (point))) + (setq bookmark-current-buffer (current-buffer)) + (let ((newname (or new (read-from-minibuffer + "New name: " nil + (let ((now-map (copy-keymap minibuffer-local-map))) + (define-key now-map "\C-w" 'bookmark-yank-word) + now-map) + nil 'bookmark-history)))) + (bookmark-set-name old newname) + (setq bookmark-current-bookmark newname) + (unless batch (bookmark-bmenu-surreptitiously-rebuild-list)) + (helm-bookmark-maybe-save-bookmark) newname)) + +(defun helm-bookmark-run-edit () + "Run `helm-bookmark-edit-bookmark' from keyboard." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-bookmark-edit-bookmark))) +(put 'helm-bookmark-run-edit 'helm-only t) + + +(defun helm-bookmark-run-jump-other-frame () + "Jump to bookmark other frame from keyboard." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-bookmark-jump-other-frame))) +(put 'helm-bookmark-run-jump-other-frame 'helm-only t) + +(defun helm-bookmark-run-jump-other-window () + "Jump to bookmark from keyboard." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-bookmark-jump-other-window))) +(put 'helm-bookmark-run-jump-other-window 'helm-only t) + +(defun helm-bookmark-run-delete () + "Delete bookmark from keyboard." + (interactive) + (with-helm-alive-p + (when (y-or-n-p "Delete bookmark(s)?") + (helm-exit-and-execute-action 'helm-delete-marked-bookmarks)))) +(put 'helm-bookmark-run-delete 'helm-only t) + +(defun helm-bookmark-get-bookmark-from-name (bmk) + "Return bookmark name even if it is a bookmark with annotation. +e.g prepended with *." + (let ((bookmark (replace-regexp-in-string "\\`\\*" "" bmk))) + (if (assoc bookmark bookmark-alist) bookmark bmk))) + +(defun helm-delete-marked-bookmarks (_ignore) + "Delete this bookmark or all marked bookmarks." + (cl-dolist (i (helm-marked-candidates)) + (bookmark-delete (helm-bookmark-get-bookmark-from-name i) + 'batch))) + + +;;;###autoload +(defun helm-bookmarks () + "Preconfigured `helm' for bookmarks." + (interactive) + (helm :sources '(helm-source-bookmarks + helm-source-bookmark-set) + :buffer "*helm bookmarks*" + :default (buffer-name helm-current-buffer))) + +;;;###autoload +(defun helm-filtered-bookmarks () + "Preconfigured helm for bookmarks (filtered by category). +Optional source `helm-source-bookmark-addressbook' is loaded +only if external addressbook-bookmark package is installed." + (interactive) + (helm :sources helm-bookmark-default-filtered-sources + :prompt "Search Bookmark: " + :buffer "*helm filtered bookmarks*" + :default (list (thing-at-point 'symbol) + (buffer-name helm-current-buffer)))) + +(provide 'helm-bookmark) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-bookmark.el ends here diff --git a/elpa/helm-20181113.923/helm-buffers.el b/elpa/helm-20181113.923/helm-buffers.el new file mode 100644 index 00000000..65f37359 --- /dev/null +++ b/elpa/helm-20181113.923/helm-buffers.el @@ -0,0 +1,1065 @@ +;;; helm-buffers.el --- helm support for buffers. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-types) +(require 'helm-utils) +(require 'helm-grep) +(require 'helm-regexp) +(require 'helm-help) + +(declare-function ido-make-buffer-list "ido" (default)) +(declare-function ido-add-virtual-buffers-to-list "ido") +(declare-function helm-comp-read "helm-mode") +(declare-function helm-browse-project "helm-files") + + +(defgroup helm-buffers nil + "Buffers related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-boring-buffer-regexp-list + '("\\` " "\\`\\*helm" "\\`\\*Echo Area" "\\`\\*Minibuf") + "The regexp list that match boring buffers. +Buffer candidates matching these regular expression will be +filtered from the list of candidates if the +`helm-skip-boring-buffers' candidate transformer is used." + :type '(repeat (choice regexp)) + :group 'helm-buffers) + +(defcustom helm-white-buffer-regexp-list nil + "The regexp list of not boring buffers. +These buffers will be displayed even if they match one of +`helm-boring-buffer-regexp-list'." + :type '(repeat (choice regexp)) + :group 'helm-buffers) + +(defcustom helm-buffers-favorite-modes '(lisp-interaction-mode + emacs-lisp-mode + text-mode + org-mode) + "List of preferred mode to open new buffers with." + :type '(repeat (choice function)) + :group 'helm-buffers) + +(defcustom helm-buffer-max-length 20 + "Max length of buffer names before truncate. +When disabled (nil) use the longest buffer-name length found." + :group 'helm-buffers + :type '(choice (const :tag "Disabled" nil) + (integer :tag "Length before truncate"))) + +(defcustom helm-buffer-details-flag t + "Always show details in buffer list when non--nil." + :group 'helm-buffers + :type 'boolean) + +(defcustom helm-buffers-fuzzy-matching nil + "Fuzzy matching buffer names when non--nil. +Only buffer names are fuzzy matched when this is enabled, +`major-mode' matching is not affected by this." + :group 'helm-buffers + :type 'boolean) + +(defcustom helm-buffer-skip-remote-checking nil + "Ignore checking for `file-exists-p' on remote files." + :group 'helm-buffers + :type 'boolean) + +(defcustom helm-buffers-truncate-lines t + "Truncate lines in `helm-buffers-list' when non--nil." + :group 'helm-buffers + :type 'boolean) + +(defcustom helm-mini-default-sources '(helm-source-buffers-list + helm-source-recentf + helm-source-buffer-not-found) + "Default sources list used in `helm-mini'. + +When adding a source here it is up to you to ensure the library of +this source is accessible and properly loaded." + :group 'helm-buffers + :type '(repeat (choice symbol))) + +(defcustom helm-buffers-end-truncated-string "..." + "The string to display at end of truncated buffer names." + :type 'string + :group 'helm-buffers) + +(defcustom helm-buffers-column-separator " " + "Separator for columns in buffer listing." + :type 'string + :group 'helm-buffers) + +(defcustom helm-buffer--pretty-names '((dired-mode . "Dired") + (lisp-interaction-mode . "Lisp Inter")) + "An alist specifying pretty names for modes. +Most of the time buffer's `mode-name' is a string so no need to add it +here as there is no need to compute it, but sometimes it may be a +mode-line specification which may be costly to compute, in this case +add here the pretty name as a string to avoid this costly computation. +Also if some pretty names are too long you can add your own +abbreviation here." + :type '(alist :key-type symbol :value-type string) + :group 'helm-buffers) + +;;; Faces +;; +;; +(defgroup helm-buffers-faces nil + "Customize the appearance of helm-buffers." + :prefix "helm-" + :group 'helm-buffers + :group 'helm-faces) + +(defface helm-buffer-saved-out + '((t (:foreground "red" :background "black"))) + "Face used for buffer files modified outside of emacs." + :group 'helm-buffers-faces) + +(defface helm-buffer-not-saved + '((t (:foreground "Indianred2"))) + "Face used for buffer files not already saved on disk." + :group 'helm-buffers-faces) + +(defface helm-buffer-modified + '((t :inherit font-lock-comment-face)) + "Face used for modified buffers." + :group 'helm-buffers-faces) + +(defface helm-buffer-size + '((((background dark)) :foreground "RosyBrown") + (((background light)) :foreground "SlateGray")) + "Face used for buffer size." + :group 'helm-buffers-faces) + +(defface helm-buffer-process + '((t (:foreground "Sienna3"))) + "Face used for process status in buffer." + :group 'helm-buffers-faces) + +(defface helm-buffer-directory + '((t (:foreground "DarkRed" :background "LightGray"))) + "Face used for directories in `helm-buffers-list'." + :group 'helm-buffers-faces) + +(defface helm-buffer-file + '((t :inherit font-lock-builtin-face)) + "Face for buffer file names in `helm-buffers-list'." + :group 'helm-buffers-faces) + +(defface helm-buffer-archive + '((t (:foreground "Gold"))) + "Face for archive file names in `helm-buffers-list'." + :group 'helm-buffers-faces) + +(defface helm-non-file-buffer + '((t (:inherit italic))) + "Face used for non-file buffers in `helm-buffers-list'." + :group 'helm-buffers-faces) + +(defvar helm-buffers-tick-counter nil + "Allows recording local changes to a non-file buffer. +Typical usage of this var is for modes that want to see if +their buffers have changed since last visit. +Such programs may want to record tick counter after visiting their +buffers like this: + + (setq helm-buffers-tick-counter (buffer-modified-tick)) + +Note that this variable is buffer-local.") +(make-variable-buffer-local 'helm-buffers-tick-counter) + + +;;; Buffers keymap +;; +(defvar helm-buffer-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + ;; No need to have separate command for grep and zgrep + ;; as we don't use recursivity for buffers. + ;; So use zgrep for both as it is capable to handle non--compressed files. + (define-key map (kbd "M-g s") 'helm-buffer-run-zgrep) + (define-key map (kbd "C-s") 'helm-buffers-run-multi-occur) + (define-key map (kbd "C-x C-d") 'helm-buffers-run-browse-project) + (define-key map (kbd "C-c o") 'helm-buffer-switch-other-window) + (define-key map (kbd "C-c C-o") 'helm-buffer-switch-other-frame) + (define-key map (kbd "C-c =") 'helm-buffer-run-ediff) + (define-key map (kbd "M-=") 'helm-buffer-run-ediff-merge) + (define-key map (kbd "C-=") 'helm-buffer-diff-persistent) + (define-key map (kbd "M-G") 'helm-buffer-revert-persistent) + (define-key map (kbd "C-c d") 'helm-buffer-run-kill-persistent) + (define-key map (kbd "M-D") 'helm-buffer-run-kill-buffers) + (define-key map (kbd "C-x C-s") 'helm-buffer-save-persistent) + (define-key map (kbd "C-M-%") 'helm-buffer-run-query-replace-regexp) + (define-key map (kbd "M-%") 'helm-buffer-run-query-replace) + (define-key map (kbd "M-R") 'helm-buffer-run-rename-buffer) + (define-key map (kbd "M-m") 'helm-toggle-all-marks) + (define-key map (kbd "M-a") 'helm-mark-all) + (define-key map (kbd "C-]") 'helm-toggle-buffers-details) + (define-key map (kbd "C-c a") 'helm-buffers-toggle-show-hidden-buffers) + (define-key map (kbd "C-M-SPC") 'helm-buffers-mark-similar-buffers) + map) + "Keymap for buffer sources in helm.") + +(defvar helm-buffers-ido-virtual-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "C-c o") 'helm-ff-run-switch-other-window) + (define-key map (kbd "C-c C-o") 'helm-ff-run-switch-other-frame) + (define-key map (kbd "M-g s") 'helm-ff-run-grep) + (define-key map (kbd "M-g z") 'helm-ff-run-zgrep) + (define-key map (kbd "M-D") 'helm-ff-run-delete-file) + (define-key map (kbd "C-c C-x") 'helm-ff-run-open-file-externally) + map)) + + +(defvar helm-buffer-max-len-mode nil) +(defvar helm-buffers-in-project-p nil) +(defvar helm-source-buffers-list nil) + +(defun helm-buffers-list--init () + (require 'dired) + ;; Issue #51 Create the list before `helm-buffer' creation. + ;; We were using a global cache in the past and 'candidates was + ;; bound to this cache, this was a problem when using more than one + ;; source with a different 'buffer-list fn as the same cache was + ;; reused in each source (issue #1907), now 'candidates attr is set + ;; directly so that each list of candidates is local to source. + (helm-attrset 'candidates (funcall (helm-attr 'buffer-list))) + (let ((result (cl-loop with allbufs = (memq 'helm-shadow-boring-buffers + (helm-attr + 'filtered-candidate-transformer + helm-source-buffers-list)) + for b in (if allbufs + (helm-attr 'candidates) + (helm-skip-boring-buffers + (helm-attr 'candidates) + helm-source-buffers-list)) + maximize (length b) into len-buf + maximize (length (helm-buffer--format-mode-name b)) + into len-mode + finally return (cons len-buf len-mode)))) + (unless (default-value 'helm-buffer-max-length) + (helm-set-local-variable 'helm-buffer-max-length (car result))) + (unless (default-value 'helm-buffer-max-len-mode) + (helm-set-local-variable 'helm-buffer-max-len-mode (cdr result))))) + +(defclass helm-source-buffers (helm-source-sync helm-type-buffer) + ((buffer-list + :initarg :buffer-list + :initform #'helm-buffer-list + :custom function + :documentation + " A function with no arguments to create buffer list.") + (init :initform 'helm-buffers-list--init) + (multimatch :initform nil) + (match :initform 'helm-buffers-match-function) + (persistent-action :initform 'helm-buffers-list-persistent-action) + (keymap :initform helm-buffer-map) + (migemo :initform 'nomultimatch) + (volatile :initform t) + (nohighlight :initform t) + (resume :initform (lambda () (setq helm-buffers-in-project-p nil))) + (help-message :initform 'helm-buffer-help-message))) + +(defvar helm-source-buffer-not-found + (helm-build-dummy-source + "Create buffer" + :action (helm-make-actions + "Create buffer (C-u choose mode)" + (lambda (candidate) + (let ((mjm (or (and helm-current-prefix-arg + (intern-soft (helm-comp-read + "Major-mode: " + helm-buffers-favorite-modes))) + (cl-loop for (r . m) in auto-mode-alist + when (string-match r candidate) + return m))) + (buffer (get-buffer-create candidate))) + (if mjm + (with-current-buffer buffer (funcall mjm)) + (set-buffer-major-mode buffer)) + (switch-to-buffer buffer)))))) + +(defvar ido-temp-list) +(defvar ido-ignored-list) +(defvar ido-process-ignore-lists) +(defvar ido-use-virtual-buffers) +(defvar ido-virtual-buffers) + +(defvar helm-source-ido-virtual-buffers + (helm-build-sync-source "Ido virtual buffers" + :candidates (lambda () + (let (ido-temp-list + ido-ignored-list + (ido-process-ignore-lists t)) + (when ido-use-virtual-buffers + (ido-add-virtual-buffers-to-list) + ido-virtual-buffers))) + :fuzzy-match helm-buffers-fuzzy-matching + :keymap helm-buffers-ido-virtual-map + :help-message 'helm-buffers-ido-virtual-help-message + :action '(("Find file" . helm-find-many-files) + ("Find file other window" . find-file-other-window) + ("Find file other frame" . find-file-other-frame) + ("Find file as root" . helm-find-file-as-root) + ("Grep File(s) `C-u recurse'" . helm-find-files-grep) + ("Zgrep File(s) `C-u Recurse'" . helm-ff-zgrep) + ("View file" . view-file) + ("Delete file(s)" . helm-delete-marked-files) + ("Open file externally (C-u to choose)" + . helm-open-file-externally)))) + + +(defvar ido-use-virtual-buffers) +(defvar ido-ignore-buffers) +(defun helm-buffer-list () + "Return the current list of buffers. +Currently visible buffers are put at the end of the list. +See `ido-make-buffer-list' for more infos." + (require 'ido) + (let ((ido-process-ignore-lists t) + ido-ignored-list + ido-ignore-buffers + ido-use-virtual-buffers) + (ido-make-buffer-list nil))) + +(defun helm-buffer-size (buffer) + "Return size of BUFFER." + (with-current-buffer buffer + (save-restriction + (widen) + (helm-file-human-size + (- (position-bytes (point-max)) + (position-bytes (point-min))))))) + +(defun helm-buffer--show-details (buf-name prefix help-echo + size mode dir face1 face2 + proc details type) + (append + (list + (concat prefix + (propertize buf-name 'face face1 + 'help-echo help-echo + 'type type))) + (and details + (list size mode + (propertize + (if proc + (format "(%s %s in `%s')" + (process-name proc) + (process-status proc) dir) + (format "(in `%s')" dir)) + 'face face2))))) + +(defun helm-buffer--format-mode-name (buf) + "Prevent using `format-mode-line' as much as possible." + (with-current-buffer buf + (helm-acond ((assq major-mode helm-buffer--pretty-names) + (cdr it)) + ((stringp mode-name) mode-name) + (t (format-mode-line mode-name))))) + +(defun helm-buffer--details (buffer &optional details) + (require 'dired) + (let* ((mode (helm-buffer--format-mode-name buffer)) + (buf (get-buffer buffer)) + (size (propertize (helm-buffer-size buf) + 'face 'helm-buffer-size)) + (proc (get-buffer-process buf)) + (dir (with-current-buffer buffer + (helm-aif default-directory (abbreviate-file-name it)))) + (file-name (helm-aif (buffer-file-name buf) (abbreviate-file-name it))) + (name (buffer-name buf)) + (name-prefix (when (and dir (file-remote-p dir)) + (propertize "@ " 'face 'helm-ff-prefix))) + (archive-p (and (fboundp 'tramp-archive-file-name-p) + (tramp-archive-file-name-p dir)))) + (when name-prefix + ;; Remote tramp buffer names may be hexified, make them more readable. + (setq dir (helm-url-unhex-string dir) + name (helm-url-unhex-string name))) + ;; Handle tramp archive buffers specially. + (if archive-p + (helm-buffer--show-details + name name-prefix file-name size mode dir + 'helm-buffer-archive 'helm-buffer-process nil details 'filebuf) + ;; No fancy things on remote buffers. + (if (and name-prefix helm-buffer-skip-remote-checking) + (helm-buffer--show-details + name name-prefix file-name size mode dir + 'helm-buffer-file 'helm-buffer-process nil details 'filebuf) + (cond + (;; A dired buffer. + (rassoc buf dired-buffers) + (helm-buffer--show-details + name name-prefix dir size mode dir + 'helm-buffer-directory 'helm-buffer-process nil details 'dired)) + ;; A buffer file modified somewhere outside of emacs.=>red + ((and file-name + (file-exists-p file-name) + (not (verify-visited-file-modtime buf))) + (helm-buffer--show-details + name name-prefix file-name size mode dir + 'helm-buffer-saved-out 'helm-buffer-process nil details 'modout)) + ;; A new buffer file not already saved on disk (or a deleted file) .=>indianred2 + ((and file-name (not (file-exists-p file-name))) + (helm-buffer--show-details + name name-prefix file-name size mode dir + 'helm-buffer-not-saved 'helm-buffer-process nil details 'notsaved)) + ;; A buffer file modified and not saved on disk.=>orange + ((and file-name (buffer-modified-p buf)) + (helm-buffer--show-details + name name-prefix file-name size mode dir + 'helm-buffer-modified 'helm-buffer-process nil details 'mod)) + ;; A buffer file not modified and saved on disk.=>green + (file-name + (helm-buffer--show-details + name name-prefix file-name size mode dir + 'helm-buffer-file 'helm-buffer-process nil details 'filebuf)) + ;; A non-file, modified buffer + ((with-current-buffer name + (and helm-buffers-tick-counter + (/= helm-buffers-tick-counter (buffer-modified-tick)))) + (helm-buffer--show-details + name (and proc name-prefix) dir size mode dir + 'helm-buffer-modified 'helm-buffer-process proc details 'nofile-mod)) + ;; Any non--file buffer.=>italic + (t + (helm-buffer--show-details + name (and proc name-prefix) dir size mode dir + 'helm-non-file-buffer 'helm-buffer-process proc details 'nofile))))))) + +(defun helm-highlight-buffers (buffers _source) + "Transformer function to highlight BUFFERS list. +Should be called after others transformers i.e (boring buffers)." + (cl-loop for i in buffers + for (name size mode meta) = (if helm-buffer-details-flag + (helm-buffer--details i 'details) + (helm-buffer--details i)) + for truncbuf = (if (> (string-width name) helm-buffer-max-length) + (helm-substring-by-width + name helm-buffer-max-length + helm-buffers-end-truncated-string) + (concat name + (make-string + (- (+ helm-buffer-max-length + (length + helm-buffers-end-truncated-string)) + (string-width name)) + ? ))) + for len = (length mode) + when (> len helm-buffer-max-len-mode) + do (setq helm-buffer-max-len-mode len) + for fmode = (concat (make-string + (- (max helm-buffer-max-len-mode len) len) ? ) + mode) + ;; The max length of a number should be 1023.9X where X is the + ;; units, this is 7 characters. + for formatted-size = (and size (format "%7s" size)) + collect (let ((helm-pattern (helm-buffers--pattern-sans-filters + (and helm-buffers-fuzzy-matching "")))) + (cons (if helm-buffer-details-flag + (concat + (funcall helm-fuzzy-matching-highlight-fn + truncbuf) + helm-buffers-column-separator + formatted-size + helm-buffers-column-separator + fmode + helm-buffers-column-separator + meta) + (funcall helm-fuzzy-matching-highlight-fn name)) + (get-buffer i))))) + +(defun helm-buffer--get-preselection (buffer) + (let ((bufname (buffer-name buffer))) + (when (and bufname + (file-remote-p (with-current-buffer bufname + default-directory))) + (setq bufname (concat "@ " (helm-url-unhex-string bufname)))) + (concat "^" + (if (and (null helm-buffer-details-flag) + (numberp helm-buffer-max-length) + (> (string-width bufname) + helm-buffer-max-length)) + (regexp-quote + (helm-substring-by-width + bufname helm-buffer-max-length + helm-buffers-end-truncated-string)) + (concat (regexp-quote bufname) + (if helm-buffer-details-flag + "$" "[[:blank:]]+")))))) + +(defun helm-toggle-buffers-details () + (interactive) + (with-helm-alive-p + (let* ((buf (helm-get-selection)) + (preselect (helm-buffer--get-preselection buf))) + (setq helm-buffer-details-flag (not helm-buffer-details-flag)) + (helm-update (lambda () + (helm-awhile (re-search-forward preselect nil t) + (helm-mark-current-line) + (when (equal buf (helm-get-selection)) + (cl-return t)))))))) +(put 'helm-toggle-buffers-details 'helm-only t) + +(defun helm-buffers--pattern-sans-filters (&optional separator) + (cl-loop for p in (helm-mm-split-pattern helm-pattern) + unless (member (substring p 0 1) '("*" "/" "@" "!")) + collect p into lst + finally return (mapconcat 'identity lst (or separator " ")))) + +(defun helm-buffers-sort-transformer (candidates source) + (if (string= helm-pattern "") + candidates + (if helm-buffers-fuzzy-matching + (let ((helm-pattern (helm-buffers--pattern-sans-filters))) + (funcall helm-fuzzy-sort-fn candidates source)) + (sort candidates + (lambda (s1 s2) + (< (string-width s1) (string-width s2))))))) + +(defun helm-buffers-mark-similar-buffers-1 () + (with-helm-window + (let* ((src (helm-get-current-source)) + (type (get-text-property + 0 'type (helm-get-selection nil 'withprop src)))) + (save-excursion + (goto-char (helm-get-previous-header-pos)) + (helm-next-line) + (let* ((next-head (helm-get-next-header-pos)) + (end (and next-head + (save-excursion + (goto-char next-head) + (forward-line -1) + (point)))) + (maxpoint (or end (point-max)))) + (while (< (point) maxpoint) + (helm-mark-current-line) + (let ((cand (helm-get-selection nil 'withprop src))) + (when (and (not (helm-this-visible-mark)) + (eq (get-text-property 0 'type cand) type)) + (helm-make-visible-mark))) + (forward-line 1) (end-of-line)))) + (helm-mark-current-line) + (helm-display-mode-line src t) + (message "%s candidates marked" (length helm-marked-candidates))))) + +(defun helm-buffers-mark-similar-buffers () + "Mark All buffers that have same property `type' than current. +i.e same color." + (interactive) + (with-helm-alive-p + (let ((marked (helm-marked-candidates))) + (if (and (>= (length marked) 1) + (with-helm-window helm-visible-mark-overlays)) + (helm-unmark-all) + (helm-buffers-mark-similar-buffers-1))))) +(put 'helm-buffers-mark-similar-buffers 'helm-only t) + + +;;; match functions +;; +(defun helm-buffer--match-mjm (pattern mjm) + (when (string-match "\\`\\*" pattern) + (cl-loop with patterns = (split-string (substring pattern 1) ",") + for pat in patterns + if (string-match "\\`!" pat) + collect (string-match (substring pat 1) mjm) into neg + else collect (string-match pat mjm) into pos + finally return + (let ((neg-test (cl-loop for i in neg thereis (numberp i))) + (pos-test (cl-loop for i in pos thereis (numberp i)))) + (or + (and neg (not pos) (not neg-test)) + (and pos pos-test) + (and neg neg-test (not neg-test))))))) + +(defvar helm-buffer--memo-hash (make-hash-table :test 'equal)) +(defun helm-buffer--memo-pattern (pattern) + (or (gethash pattern helm-buffer--memo-hash) + (puthash pattern (helm--mapconcat-pattern pattern) + helm-buffer--memo-hash))) + +(defun helm-buffer--match-pattern (pattern candidate &optional nofuzzy) + (let ((bfn (if (and helm-buffers-fuzzy-matching + (not nofuzzy) + (not helm-migemo-mode) + (not (string-match "\\`\\^" pattern))) + #'helm-buffer--memo-pattern + #'identity)) + (mfn (if helm-migemo-mode + #'helm-mm-migemo-string-match #'string-match))) + (if (string-match "\\`!" pattern) + (not (funcall mfn (funcall bfn (substring pattern 1)) + candidate)) + (funcall mfn (funcall bfn pattern) candidate)))) + +(defun helm-buffers--match-from-mjm (candidate) + (let* ((cand (replace-regexp-in-string "^\\s-\\{1\\}" "" candidate)) + (buf (get-buffer cand)) + (regexp (cl-loop with pattern = helm-pattern + for p in (helm-mm-split-pattern pattern) + when (string-match "\\`\\*" p) + return p))) + (if regexp + (when buf + (with-current-buffer buf + (let ((mjm (symbol-name major-mode))) + (helm-buffer--match-mjm regexp mjm)))) + t))) + +(defun helm-buffers--match-from-pat (candidate) + (let* ((regexp-list (cl-loop with pattern = helm-pattern + for p in (helm-mm-split-pattern pattern) + unless (string-match + "\\`\\(\\*\\|/\\|@\\)" p) + collect p)) + (nofuzzy (cdr regexp-list))) + (if regexp-list + (cl-loop for re in regexp-list + always (helm-buffer--match-pattern re candidate nofuzzy)) + t))) + +(defun helm-buffers--match-from-inside (candidate) + (let* ((cand (replace-regexp-in-string "^\\s-\\{1\\}" "" candidate)) + (buf (get-buffer cand)) + (regexp (cl-loop with pattern = helm-pattern + for p in (helm-mm-split-pattern pattern) + when (string-match "\\`@\\(.*\\)" p) + return (match-string 1 p)))) + (if (and buf regexp) + (with-current-buffer buf + (save-excursion + (goto-char (point-min)) + (if helm-migemo-mode + (helm-mm-migemo-forward regexp nil t) + (re-search-forward regexp nil t)))) + t))) + +(defun helm-buffers--match-from-directory (candidate) + (let* ((cand (replace-regexp-in-string "^\\s-\\{1\\}" "" candidate)) + (buf (get-buffer cand)) + (buf-fname (or (buffer-file-name buf) + (car-safe (rassoc buf dired-buffers)))) + (regexps (cl-loop with pattern = helm-pattern + for p in (helm-mm-split-pattern pattern) + when (string-match "\\`/" p) + collect p))) + (if regexps + (cl-loop for re in regexps + thereis + (and buf-fname + (string-match + (substring re 1) (helm-basedir buf-fname)))) + t))) + +(defun helm-buffers-match-function (candidate) + "Default function to match buffers." + (and (helm-buffers--match-from-pat candidate) + (helm-buffers--match-from-mjm candidate) + (helm-buffers--match-from-inside candidate) + (helm-buffers--match-from-directory candidate))) + + +(defun helm-buffer-query-replace-1 (&optional regexp-flag buffers) + "Query replace in marked buffers. +If REGEXP-FLAG is given use `query-replace-regexp'." + (let ((prompt (if regexp-flag "Query replace regexp" "Query replace")) + (bufs (or buffers (helm-marked-candidates))) + (helm--reading-passwd-or-string t)) + (cl-loop with args = (query-replace-read-args prompt regexp-flag t) + for buf in bufs + do + (save-window-excursion + (switch-to-buffer buf) + (save-excursion + (let ((case-fold-search t)) + (goto-char (point-min)) + (apply #'perform-replace + (list (nth 0 args) (nth 1 args) + t regexp-flag (nth 2 args) nil + multi-query-replace-map)))))))) + +(defun helm-buffer-query-replace-regexp (_candidate) + (helm-buffer-query-replace-1 'regexp)) + +(defun helm-buffer-query-replace (_candidate) + (helm-buffer-query-replace-1)) + +(defun helm-buffer-toggle-diff (candidate) + "Toggle diff buffer CANDIDATE with it's file." + (helm-aif (get-buffer-window "*Diff*" 'visible) + (progn (kill-buffer "*Diff*") + (set-window-buffer it helm-current-buffer)) + (diff-buffer-with-file (get-buffer candidate)))) + +(defun helm-buffer-diff-persistent () + "Toggle diff buffer without quitting helm." + (interactive) + (with-helm-alive-p + (helm-attrset 'diff-action 'helm-buffer-toggle-diff) + (helm-execute-persistent-action 'diff-action))) +(put 'helm-buffer-diff-persistent 'helm-only t) + +(defun helm-revert-buffer (candidate) + (with-current-buffer candidate + (helm-aif (buffer-file-name) + (and (file-exists-p it) (revert-buffer t t))))) + +(defun helm-revert-marked-buffers (_ignore) + (mapc 'helm-revert-buffer (helm-marked-candidates))) + +(defun helm-buffer-revert-and-update (_candidate) + (with-helm-buffer + (let ((marked (helm-marked-candidates)) + (preselect (helm-buffers--quote-truncated-buffer + (helm-get-selection)))) + (cl-loop for buf in marked do (helm-revert-buffer buf)) + (when helm-marked-candidates (helm-unmark-all)) + (helm-update preselect)))) + +(defun helm-buffer-revert-persistent () + "Revert buffer without quitting helm." + (interactive) + (with-helm-alive-p + (helm-attrset 'revert-action '(helm-buffer-revert-and-update . never-split)) + (helm-execute-persistent-action 'revert-action))) +(put 'helm-buffer-revert-persistent 'helm-only t) + +(defun helm-buffer-save-and-update (_candidate) + (with-helm-buffer + (let ((marked (helm-marked-candidates)) + (preselect (helm-get-selection nil t)) + (enable-recursive-minibuffers t)) + (cl-loop for buf in marked do + (with-current-buffer (get-buffer buf) + (when (buffer-file-name) (save-buffer)))) + (when helm-marked-candidates (helm-unmark-all)) + (helm-update (regexp-quote preselect))))) + +(defun helm-buffer-save-persistent () + "Save buffer without quitting helm." + (interactive) + (with-helm-alive-p + (helm-attrset 'save-action '(helm-buffer-save-and-update . never-split)) + (helm-execute-persistent-action 'save-action))) +(put 'helm-buffer-save-persistent 'helm-only t) + +(defun helm-buffers-rename-buffer (candidate) + (with-current-buffer candidate + (rename-buffer (helm-read-string "New name: " (buffer-name)) t))) + +(defun helm-buffer-run-rename-buffer () + "Run rename buffer action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-buffers-rename-buffer))) +(put 'helm-buffer-run-rename-buffer 'helm-only t) + +(defun helm-buffer-run-kill-persistent () + "Kill buffer without quitting helm." + (interactive) + (with-helm-alive-p + (helm-attrset 'kill-action '(helm-buffers-persistent-kill . never-split)) + (helm-execute-persistent-action 'kill-action))) +(put 'helm-buffer-run-kill-persistent 'helm-only t) + +(defun helm-kill-marked-buffers (_ignore) + (let* ((bufs (helm-marked-candidates)) + (killed-bufs (cl-count-if 'kill-buffer bufs))) + (when (buffer-live-p helm-buffer) + (with-helm-buffer + (setq helm-marked-candidates nil + helm-visible-mark-overlays nil))) + (message "Killed %s buffer(s)" killed-bufs))) + +(defun helm-buffer-run-kill-buffers () + "Run kill buffer action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-kill-marked-buffers))) +(put 'helm-buffer-run-kill-buffers 'helm-only t) + +(defun helm-buffer-run-grep () + "Run Grep action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-grep-buffers))) +(put 'helm-buffer-run-grep 'helm-only t) + +(defun helm-buffer-run-zgrep () + "Run Grep action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-zgrep-buffers))) +(put 'helm-buffer-run-zgrep 'helm-only t) + +(defun helm-buffer-run-query-replace-regexp () + "Run Query replace regexp action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-buffer-query-replace-regexp))) +(put 'helm-buffer-run-query-replace-regexp 'helm-only t) + +(defun helm-buffer-run-query-replace () + "Run Query replace action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-buffer-query-replace))) +(put 'helm-buffer-run-query-replace 'helm-only t) + +(defun helm-buffer-switch-other-window () + "Run switch to other window action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-buffer-switch-buffers-other-window))) +(put 'helm-buffer-switch-other-window 'helm-only t) + +(defun helm-buffer-switch-other-frame () + "Run switch to other frame action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'switch-to-buffer-other-frame))) +(put 'helm-buffer-switch-other-frame 'helm-only t) + +(defun helm-buffer-switch-buffers (_candidate) + "Switch to buffer candidates and replace current buffer. + +If more than one buffer marked switch to these buffers in separate windows. +If a prefix arg is given split windows vertically." + (let ((buffers (helm-marked-candidates))) + (helm-window-show-buffers buffers))) + +(defun helm-buffer-switch-buffers-other-window (_candidate) + "Switch to marked buffers in other windows." + (let ((buffers (helm-marked-candidates))) + (helm-window-show-buffers buffers t))) + +(defun helm-buffer-run-ediff () + "Run ediff action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ediff-marked-buffers))) +(put 'helm-buffer-run-ediff 'helm-only t) + +(defun helm-buffer-run-ediff-merge () + "Run ediff action from `helm-source-buffers-list'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ediff-marked-buffers-merge))) +(put 'helm-buffer-run-ediff-merge 'helm-only t) + +(defun helm-buffers-persistent-kill-1 (buffer-or-name) + "Persistent action to kill buffer." + (let ((buf (get-buffer buffer-or-name)) helm-buf-or-cur) + (if (or (and (eql buf (get-buffer helm-current-buffer)) + (setq helm-buf-or-cur "helm-current-buffer")) + (and (eql buf (get-buffer helm-buffer)) + (setq helm-buf-or-cur "helm-buffer"))) + (progn + (message "Can't kill `%s' without quitting session" helm-buf-or-cur) + (sit-for 1)) + (kill-buffer buf) + (helm-delete-current-selection)))) + +(defun helm-buffers--quote-truncated-buffer (buffer) + (let ((bufname (and (bufferp buffer) + (buffer-name buffer)))) + (when (and bufname + (file-remote-p (with-current-buffer bufname + default-directory))) + (setq bufname (concat "@ " (helm-url-unhex-string bufname)))) + (when bufname + (regexp-quote + (if (and helm-buffer-max-length + helm-buffer-details-flag) + (helm-substring-by-width + bufname helm-buffer-max-length + "") + bufname))))) + +(defun helm-buffers-persistent-kill (_buffer) + (let ((marked (helm-marked-candidates)) + (sel (helm-get-selection))) + (unwind-protect + (cl-loop for b in marked + do (progn + ;; We need to preselect each marked because + ;; helm-buffers-persistent-kill is deleting + ;; current selection. + (helm-preselect + (format "^%s" + (helm-buffers--quote-truncated-buffer b))) + (helm-buffers-persistent-kill-1 b) + (message nil) + (helm--remove-marked-and-update-mode-line b))) + (with-helm-buffer + (setq helm-marked-candidates nil + helm-visible-mark-overlays nil)) + (helm-force-update (helm-buffers--quote-truncated-buffer sel))))) + +(defun helm-buffers-list-persistent-action (candidate) + (let ((current (window-buffer helm-persistent-action-display-window))) + (if (or (helm-follow-mode-p) + (eql current (get-buffer helm-current-buffer)) + (not (eql current (get-buffer candidate)))) + (switch-to-buffer candidate) + (if (and helm-persistent-action-display-window + (window-dedicated-p + (next-window helm-persistent-action-display-window 1))) + (delete-window helm-persistent-action-display-window) + (switch-to-buffer helm-current-buffer))))) + +(defun helm-ediff-marked-buffers (_candidate &optional merge) + "Ediff 2 marked buffers or CANDIDATE and `helm-current-buffer'. +With optional arg MERGE call `ediff-merge-buffers'." + (let ((lg-lst (length (helm-marked-candidates))) + buf1 buf2) + (cl-case lg-lst + (0 + (error "Error:You have to mark at least 1 buffer")) + (1 + (setq buf1 helm-current-buffer + buf2 (cl-first (helm-marked-candidates)))) + (2 + (setq buf1 (cl-first (helm-marked-candidates)) + buf2 (cl-second (helm-marked-candidates)))) + (t + (error "Error:Too many buffers marked!"))) + (if merge + (ediff-merge-buffers buf1 buf2) + (ediff-buffers buf1 buf2)))) + +(defun helm-ediff-marked-buffers-merge (candidate) + "Ediff merge `helm-current-buffer' with CANDIDATE. +See `helm-ediff-marked-buffers'." + (helm-ediff-marked-buffers candidate t)) + +(defun helm-multi-occur-as-action (_candidate) + "Multi occur action for `helm-source-buffers-list'. +Can be used by any source that list buffers." + (let ((helm-moccur-always-search-in-current + (if helm-current-prefix-arg + (not helm-moccur-always-search-in-current) + helm-moccur-always-search-in-current)) + (buffers (helm-marked-candidates)) + (input (cl-loop for i in (split-string helm-pattern " " t) + thereis (and (string-match "\\`@\\(.*\\)" i) + (match-string 1 i))))) + (helm-multi-occur-1 buffers input))) + +(defun helm-buffers-run-multi-occur () + "Run `helm-multi-occur-as-action' by key." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-multi-occur-as-action))) +(put 'helm-buffers-run-multi-occur 'helm-only t) + +(defun helm-buffers-toggle-show-hidden-buffers () + (interactive) + (with-helm-alive-p + (let ((filter-attrs (helm-attr 'filtered-candidate-transformer + helm-source-buffers-list))) + (if (memq 'helm-shadow-boring-buffers filter-attrs) + (helm-attrset 'filtered-candidate-transformer + (cons 'helm-skip-boring-buffers + (remove 'helm-shadow-boring-buffers + filter-attrs)) + helm-source-buffers-list) + (helm-attrset 'filtered-candidate-transformer + (cons 'helm-shadow-boring-buffers + (remove 'helm-skip-boring-buffers + filter-attrs)) + helm-source-buffers-list)) + (helm-force-update)))) +(put 'helm-buffers-toggle-show-hidden-buffers 'helm-only t) + +(defun helm-buffers-browse-project (buf) + "Browse project from buffer." + (with-current-buffer buf + (helm-browse-project helm-current-prefix-arg))) + +(defun helm-buffers-run-browse-project () + "Run `helm-buffers-browse-project' from key." + (interactive) + (with-helm-alive-p + (if helm-buffers-in-project-p + (user-error "You are already browsing this project") + (helm-exit-and-execute-action 'helm-buffers-browse-project)))) + +;;; Candidate Transformers +;; +;; +(defun helm-skip-boring-buffers (buffers _source) + (helm-skip-entries buffers + helm-boring-buffer-regexp-list + helm-white-buffer-regexp-list)) + +(defun helm-shadow-boring-buffers (buffers _source) + "Buffers matching `helm-boring-buffer-regexp' will be +displayed with the `file-name-shadow' face if available." + (helm-shadow-entries buffers helm-boring-buffer-regexp-list)) + + +;;;###autoload +(defun helm-buffers-list () + "Preconfigured `helm' to list buffers." + (interactive) + (unless helm-source-buffers-list + (setq helm-source-buffers-list + (helm-make-source "Buffers" 'helm-source-buffers))) + (helm :sources '(helm-source-buffers-list + helm-source-ido-virtual-buffers + helm-source-buffer-not-found) + :buffer "*helm buffers*" + :keymap helm-buffer-map + :truncate-lines helm-buffers-truncate-lines)) + +;;;###autoload +(defun helm-mini () + "Preconfigured `helm' lightweight version \(buffer -> recentf\)." + (interactive) + (require 'helm-x-files) + (unless helm-source-buffers-list + (setq helm-source-buffers-list + (helm-make-source "Buffers" 'helm-source-buffers))) + (helm :sources helm-mini-default-sources + :buffer "*helm mini*" + :ff-transformer-show-only-basename nil + :truncate-lines helm-buffers-truncate-lines)) + +(defun helm-quit-and-helm-mini () + "Drop into `helm-mini' from `helm'." + (interactive) + (with-helm-alive-p + (helm-run-after-exit 'helm-mini))) + +(provide 'helm-buffers) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-buffers.el ends here diff --git a/elpa/helm-20181113.923/helm-color.el b/elpa/helm-20181113.923/helm-color.el new file mode 100644 index 00000000..106e9bec --- /dev/null +++ b/elpa/helm-20181113.923/helm-color.el @@ -0,0 +1,170 @@ +;;; helm-color.el --- colors and faces -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'helm-elisp) + +;;; Customize Face +;; +;; +(defun helm-custom-faces-init () + "Initialize buffer for `helm-source-customize-face'." + (unless (helm-candidate-buffer) + (save-selected-window + (list-faces-display) + (message nil)) + (helm-init-candidates-in-buffer + 'global + (with-current-buffer (get-buffer "*Faces*") + (buffer-substring + (next-single-char-property-change (point-min) 'face) + (point-max)))) + (kill-buffer "*Faces*"))) + +(defvar helm-source-customize-face + (helm-build-in-buffer-source "Customize Face" + :init 'helm-custom-faces-init + :get-line 'buffer-substring + :persistent-action (lambda (candidate) + (helm-elisp--persistent-help + (intern (car (split-string candidate))) + 'helm-describe-face)) + :persistent-help "Describe face" + :action '(("Customize" + . (lambda (line) + (customize-face (intern (car (split-string line)))))) + ("Copy name" + . (lambda (line) + (kill-new (car (split-string line " " t))))))) + "See (info \"(emacs)Faces\")") + +;;; Colors browser +;; +;; +(defun helm-colors-init () + (unless (helm-candidate-buffer) + (save-selected-window + (list-colors-display) + (message nil)) + (helm-init-candidates-in-buffer + 'global + (with-current-buffer (get-buffer "*Colors*") + (buffer-string))) + (kill-buffer "*Colors*"))) + +(defun helm-color-insert-name (candidate) + (with-helm-current-buffer + (insert (helm-colors-get-name candidate)))) + +(defun helm-color-kill-name (candidate) + (kill-new (helm-colors-get-name candidate))) + +(defun helm-color-insert-rgb (candidate) + (with-helm-current-buffer + (insert (helm-colors-get-rgb candidate)))) + +(defun helm-color-kill-rgb (candidate) + (kill-new (helm-colors-get-rgb candidate))) + +(defun helm-color-run-insert-name () + "Insert name of color from `helm-source-colors'" + (interactive) + (with-helm-alive-p (helm-exit-and-execute-action 'helm-color-insert-name))) +(put 'helm-color-run-insert-name 'helm-only t) + +(defun helm-color-run-kill-name () + "Kill name of color from `helm-source-colors'" + (interactive) + (with-helm-alive-p (helm-exit-and-execute-action 'helm-color-kill-name))) +(put 'helm-color-run-kill-name 'helm-only t) + +(defun helm-color-run-insert-rgb () + "Insert RGB of color from `helm-source-colors'" + (interactive) + (with-helm-alive-p (helm-exit-and-execute-action 'helm-color-insert-rgb))) +(put 'helm-color-run-insert-rgb 'helm-only t) + +(defun helm-color-run-kill-rgb () + "Kill RGB of color from `helm-source-colors'" + (interactive) + (with-helm-alive-p (helm-exit-and-execute-action 'helm-color-kill-rgb))) +(put 'helm-color-run-kill-rgb 'helm-only t) + +(defvar helm-color-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "C-c n") 'helm-color-run-insert-name) + (define-key map (kbd "C-c N") 'helm-color-run-kill-name) + (define-key map (kbd "C-c r") 'helm-color-run-insert-rgb) + (define-key map (kbd "C-c R") 'helm-color-run-kill-rgb) + map)) + +(defvar helm-source-colors + (helm-build-in-buffer-source "Colors" + :init 'helm-colors-init + :get-line 'buffer-substring + :keymap helm-color-map + :persistent-help "Kill entry in RGB format." + :persistent-action 'helm-color-kill-rgb + :help-message 'helm-colors-help-message + :action + '(("Copy Name (C-c N)" . helm-color-kill-name) + ("Copy RGB (C-c R)" . helm-color-kill-rgb) + ("Insert Name (C-c n)" . helm-color-insert-name) + ("Insert RGB (C-c r)" . helm-color-insert-rgb)))) + +(defun helm-colors-get-name (candidate) + "Get color name." + (replace-regexp-in-string + " " "" + (with-temp-buffer + (insert (capitalize candidate)) + (goto-char (point-min)) + (search-forward-regexp "\\s-\\{2,\\}") + (delete-region (point) (point-max)) + (buffer-string)))) + +(defun helm-colors-get-rgb (candidate) + "Get color RGB." + (replace-regexp-in-string + " " "" + (with-temp-buffer + (insert (capitalize candidate)) + (goto-char (point-max)) + (search-backward-regexp "\\s-\\{2,\\}") + (delete-region (point) (point-min)) + (buffer-string)))) + +;;;###autoload +(defun helm-colors () + "Preconfigured `helm' for color." + (interactive) + (helm :sources '(helm-source-colors helm-source-customize-face) + :buffer "*helm colors*")) + +(provide 'helm-color) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-color.el ends here diff --git a/elpa/helm-20181113.923/helm-command.el b/elpa/helm-20181113.923/helm-command.el new file mode 100644 index 00000000..7639a781 --- /dev/null +++ b/elpa/helm-20181113.923/helm-command.el @@ -0,0 +1,306 @@ +;;; helm-command.el --- Helm execute-exended-command. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'helm-mode) +(require 'helm-elisp) + + +(defgroup helm-command nil + "Emacs command related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-M-x-requires-pattern 0 + "Value of requires-pattern for `helm-M-x'. +Show all candidates on startup when 0 (default)." + :group 'helm-command + :type 'boolean) + +(defcustom helm-M-x-always-save-history nil + "`helm-M-x' Save command in `extended-command-history' even when it fail." + :group 'helm-command + :type 'boolean) + +(defcustom helm-M-x-reverse-history nil + "The history source of `helm-M-x' appear in second position when non--nil." + :group 'helm-command + :type 'boolean) + +(defcustom helm-M-x-fuzzy-match nil + "Enable fuzzy matching in `helm-M-x' when non--nil." + :group 'helm-command + :type 'boolean) + +(defcustom helm-M-x-default-sort-fn #'helm-M-x-fuzzy-sort-candidates + "Default sort function for `helm-M-x'. + +It should sort against REAL value of candidates. + +It is used only when `helm-M-x-fuzzy-match' is enabled." + :group 'helm-command + :type 'function) + +;;; Faces +;; +;; +(defgroup helm-command-faces nil + "Customize the appearance of helm-command." + :prefix "helm-" + :group 'helm-command + :group 'helm-faces) + +(defface helm-M-x-key '((t (:foreground "orange" :underline t))) + "Face used in helm-M-x to show keybinding." + :group 'helm-command-faces) + + +(defvar helm-M-x-input-history nil) +(defvar helm-M-x-prefix-argument nil + "Prefix argument before calling `helm-M-x'.") + + +(defun helm-M-x-get-major-mode-command-alist (mode-map) + "Return alist of MODE-MAP." + (when mode-map + (cl-loop for key being the key-seqs of mode-map using (key-bindings com) + for str-key = (key-description key) + for ismenu = (string-match "" str-key) + unless ismenu collect (cons str-key com)))) + +(defun helm-get-mode-map-from-mode (mode) + "Guess the mode-map name according to MODE. +Some modes don't use conventional mode-map name +so we need to guess mode-map name. e.g python-mode ==> py-mode-map. +Return nil if no mode-map found." + (cl-loop ;; Start with a conventional mode-map name. + with mode-map = (intern-soft (format "%s-map" mode)) + with mode-string = (symbol-name mode) + with mode-name = (replace-regexp-in-string "-mode" "" mode-string) + while (not mode-map) + for count downfrom (length mode-name) + ;; Return when no result after parsing entire string. + when (eq count 0) return nil + for sub-name = (substring mode-name 0 count) + do (setq mode-map (intern-soft (format "%s-map" (concat sub-name "-mode")))) + finally return mode-map)) + +(defun helm-M-x-current-mode-map-alist () + "Return mode-map alist of current `major-mode'." + (let ((map-sym (helm-get-mode-map-from-mode major-mode))) + (when (and map-sym (boundp map-sym)) + (helm-M-x-get-major-mode-command-alist (symbol-value map-sym))))) + + +(defun helm-M-x-transformer-1 (candidates &optional sort) + "Transformer function to show bindings in emacs commands. +Show global bindings and local bindings according to current `major-mode'. +If SORT is non nil sort list with `helm-generic-sort-fn'. +Note that SORT should not be used when fuzzy matching because +fuzzy matching is running its own sort function with a different algorithm." + (with-helm-current-buffer + (cl-loop with local-map = (helm-M-x-current-mode-map-alist) + for cand in candidates + for local-key = (car (rassq cand local-map)) + for key = (substitute-command-keys (format "\\[%s]" cand)) + unless (get (intern (if (consp cand) (car cand) cand)) 'helm-only) + collect + (cons (cond ((and (string-match "^M-x" key) local-key) + (format "%s (%s)" + cand (propertize + local-key + 'face 'helm-M-x-key))) + ((string-match "^M-x" key) cand) + (t (format "%s (%s)" + cand (propertize + key + 'face 'helm-M-x-key)))) + cand) + into ls + finally return + (if sort (sort ls #'helm-generic-sort-fn) ls)))) + +(defun helm-M-x-transformer (candidates _source) + "Transformer function for `helm-M-x' candidates." + (helm-M-x-transformer-1 candidates (null helm--in-fuzzy))) + +(defun helm-M-x-transformer-hist (candidates _source) + "Transformer function for `helm-M-x' candidates." + (helm-M-x-transformer-1 candidates)) + +(defun helm-M-x--notify-prefix-arg () + ;; Notify a prefix-arg set AFTER calling M-x. + (when prefix-arg + (with-helm-window + (helm-display-mode-line (helm-get-current-source) 'force)))) + +(defun helm-cmd--get-current-function-name () + (save-excursion + (beginning-of-defun) + (cadr (split-string (buffer-substring-no-properties + (point-at-bol) (point-at-eol)))))) + +(defun helm-cmd--get-preconfigured-commands (&optional dir) + (let* ((helm-dir (or dir (helm-basedir (locate-library "helm")))) + (helm-autoload-file (expand-file-name "helm-autoloads.el" helm-dir)) + results) + (when (file-exists-p helm-autoload-file) + (with-temp-buffer + (insert-file-contents helm-autoload-file) + (while (re-search-forward "Preconfigured" nil t) + (push (substring (helm-cmd--get-current-function-name) 1) results)))) + results)) + +(defvar helm-M-x-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-comp-read-map) + (define-key map (kbd "C-u") nil) + (define-key map (kbd "C-u") 'helm-M-x-universal-argument) + map)) + +(defun helm-M-x-universal-argument () + "Same as `universal-argument' but for `helm-M-x'." + (interactive) + (if helm-M-x-prefix-argument + (progn (setq helm-M-x-prefix-argument nil) + (let ((inhibit-read-only t)) + (with-selected-window (minibuffer-window) + (save-excursion + (goto-char (point-min)) + (delete-char (- (minibuffer-prompt-width) (length "M-x ")))))) + (message "Initial prefix arg disabled")) + (setq prefix-arg (list 4)) + (universal-argument--mode))) +(put 'helm-M-x-universal-argument 'helm-only t) + +(defun helm-M-x-fuzzy-sort-candidates (candidates _source) + (helm-fuzzy-matching-default-sort-fn-1 candidates t)) + +(defun helm-M-x-read-extended-command (&optional collection history) + "Read command name to invoke in `helm-M-x'. +Helm completion is not provided when executing or defining +kbd macros. +Optional arg COLLECTION is to allow using another COLLECTION +than the default which is OBARRAY." + (if (or defining-kbd-macro executing-kbd-macro) + (if helm-mode + (unwind-protect + (progn + (helm-mode -1) + (read-extended-command)) + (helm-mode 1)) + (read-extended-command)) + (let* ((helm-fuzzy-sort-fn helm-M-x-default-sort-fn) + (helm--mode-line-display-prefarg t) + (tm (run-at-time 1 0.1 'helm-M-x--notify-prefix-arg)) + (helm-move-selection-after-hook + (cons (lambda () (setq current-prefix-arg nil)) + helm-move-selection-after-hook))) + (setq extended-command-history + (cl-loop for c in extended-command-history + when (and c (commandp (intern c))) + do (set-text-properties 0 (length c) nil c) + and collect c)) + (unwind-protect + (progn + (setq current-prefix-arg nil) + (helm-comp-read + (concat (cond + ((eq helm-M-x-prefix-argument '-) "- ") + ((and (consp helm-M-x-prefix-argument) + (eq (car helm-M-x-prefix-argument) 4)) "C-u ") + ((and (consp helm-M-x-prefix-argument) + (integerp (car helm-M-x-prefix-argument))) + (format "%d " (car helm-M-x-prefix-argument))) + ((integerp helm-M-x-prefix-argument) + (format "%d " helm-M-x-prefix-argument))) + "M-x ") + (or collection obarray) + :test 'commandp + :requires-pattern helm-M-x-requires-pattern + :name "Emacs Commands" + :buffer "*helm M-x*" + :persistent-action (lambda (candidate) + (helm-elisp--persistent-help + candidate 'helm-describe-function)) + :persistent-help "Describe this command" + :history (or history extended-command-history) + :reverse-history helm-M-x-reverse-history + :input-history 'helm-M-x-input-history + :del-input nil + :help-message 'helm-M-x-help-message + :keymap helm-M-x-map + :must-match t + :match-part (lambda (c) (car (split-string c))) + :fuzzy helm-M-x-fuzzy-match + :nomark t + :candidates-in-buffer t + :fc-transformer 'helm-M-x-transformer + :hist-fc-transformer 'helm-M-x-transformer-hist)) + (cancel-timer tm) + (setq helm--mode-line-display-prefarg nil))))) + +;;;###autoload +(defun helm-M-x (_arg &optional command-name) + "Preconfigured `helm' for Emacs commands. +It is `helm' replacement of regular `M-x' `execute-extended-command'. + +Unlike regular `M-x' emacs vanilla `execute-extended-command' command, +the prefix args if needed, can be passed AFTER starting `helm-M-x'. +When a prefix arg is passed BEFORE starting `helm-M-x', the first `C-u' +while in `helm-M-x' session will disable it. + +You can get help on each command by persistent action." + (interactive + (progn + (setq helm-M-x-prefix-argument current-prefix-arg) + (list current-prefix-arg (helm-M-x-read-extended-command)))) + (unless (string= command-name "") + (let ((sym-com (and (stringp command-name) (intern-soft command-name)))) + (when sym-com + ;; Avoid having `this-command' set to *exit-minibuffer. + (setq this-command sym-com + ;; Handle C-x z (repeat) Issue #322 + real-this-command sym-com) + ;; If helm-M-x is called with regular emacs completion (kmacro) + ;; use the value of arg otherwise use helm-current-prefix-arg. + (let ((prefix-arg (or helm-current-prefix-arg helm-M-x-prefix-argument))) + (cl-flet ((save-hist (command) + (setq extended-command-history + (cons command (delete command extended-command-history))))) + (condition-case-unless-debug err + (progn + (command-execute sym-com 'record) + (save-hist command-name)) + (error + (when helm-M-x-always-save-history + (save-hist command-name)) + (signal (car err) (cdr err)))))))))) +(put 'helm-M-x 'interactive-only 'command-execute) + +(provide 'helm-command) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-command.el ends here diff --git a/elpa/helm-20181113.923/helm-config.el b/elpa/helm-20181113.923/helm-config.el new file mode 100644 index 00000000..b99ab639 --- /dev/null +++ b/elpa/helm-20181113.923/helm-config.el @@ -0,0 +1,172 @@ +;;; helm-config.el --- Applications library for `helm.el' -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + + +;;; Require +;; +;; +(declare-function async-bytecomp-package-mode "ext:async-bytecomp.el") +(when (require 'async-bytecomp nil t) + (and (fboundp 'async-bytecomp-package-mode) + (async-bytecomp-package-mode 1))) + + +(defgroup helm-config nil + "Various configurations for Helm." + :group 'helm) + +(defcustom helm-command-prefix-key "C-x c" + "The key `helm-command-prefix' is bound to in the global map." + :type '(choice (string :tag "Key") (const :tag "no binding")) + :group 'helm-config + :set + (lambda (var key) + (when (and (boundp var) (symbol-value var)) + (define-key (current-global-map) + (read-kbd-macro (symbol-value var)) nil)) + (when key + (define-key (current-global-map) + (read-kbd-macro key) 'helm-command-prefix)) + (set var key))) + +(defcustom helm-minibuffer-history-key "C-r" + "The key `helm-minibuffer-history' is bound to in minibuffer local maps." + :type '(choice (string :tag "Key") (const :tag "no binding")) + :group 'helm-config + :set + (lambda (var key) + (cl-dolist (map '(minibuffer-local-completion-map + minibuffer-local-filename-completion-map + minibuffer-local-filename-must-match-map ; Emacs 23.1.+ + minibuffer-local-isearch-map + minibuffer-local-map + minibuffer-local-must-match-filename-map ; Older Emacsen + minibuffer-local-must-match-map + minibuffer-local-ns-map)) + (when (and (boundp map) (keymapp (symbol-value map))) + (when (and (boundp var) (symbol-value var)) + (define-key (symbol-value map) + (read-kbd-macro (symbol-value var)) nil)) + (when key + (define-key (symbol-value map) + (read-kbd-macro key) 'helm-minibuffer-history)))) + (set var key))) + +;;; Command Keymap +;; +;; +(defvar helm-command-map + (let ((map (make-sparse-keymap))) + (define-key map (kbd "a") 'helm-apropos) + (define-key map (kbd "e") 'helm-etags-select) + (define-key map (kbd "l") 'helm-locate) + (define-key map (kbd "s") 'helm-surfraw) + (define-key map (kbd "r") 'helm-regexp) + (define-key map (kbd "m") 'helm-man-woman) + (define-key map (kbd "t") 'helm-top) + (define-key map (kbd "/") 'helm-find) + (define-key map (kbd "i") 'helm-semantic-or-imenu) + (define-key map (kbd "I") 'helm-imenu-in-all-buffers) + (define-key map (kbd "") 'helm-lisp-completion-at-point) + (define-key map (kbd "p") 'helm-list-emacs-process) + (define-key map (kbd "C-x r b") 'helm-filtered-bookmarks) + (define-key map (kbd "M-y") 'helm-show-kill-ring) + (define-key map (kbd "C-c ") 'helm-all-mark-rings) + (define-key map (kbd "C-x C-f") 'helm-find-files) + (define-key map (kbd "f") 'helm-multi-files) + (define-key map (kbd "C-:") 'helm-eval-expression-with-eldoc) + (define-key map (kbd "C-,") 'helm-calcul-expression) + (define-key map (kbd "M-x") 'helm-M-x) + (define-key map (kbd "M-s o") 'helm-occur) + (define-key map (kbd "M-g a") 'helm-do-grep-ag) + (define-key map (kbd "c") 'helm-colors) + (define-key map (kbd "F") 'helm-select-xfont) + (define-key map (kbd "8") 'helm-ucs) + (define-key map (kbd "C-c f") 'helm-recentf) + (define-key map (kbd "C-c g") 'helm-google-suggest) + (define-key map (kbd "h i") 'helm-info-at-point) + (define-key map (kbd "h r") 'helm-info-emacs) + (define-key map (kbd "h g") 'helm-info-gnus) + (define-key map (kbd "h h") 'helm-documentation) + (define-key map (kbd "C-x C-b") 'helm-buffers-list) + (define-key map (kbd "C-x r i") 'helm-register) + (define-key map (kbd "C-c C-x") 'helm-run-external-command) + (define-key map (kbd "b") 'helm-resume) + (define-key map (kbd "M-g i") 'helm-gid) + (define-key map (kbd "@") 'helm-list-elisp-packages) + map)) + +;; Don't override the keymap we just defined with an empty +;; keymap. This also protect bindings changed by the user. +(defvar helm-command-prefix) +(define-prefix-command 'helm-command-prefix) +(fset 'helm-command-prefix helm-command-map) +(setq helm-command-prefix helm-command-map) + + +;;; Menu + +(require 'helm-easymenu) + + +;;;###autoload +(defun helm-configuration () + "Customize `helm'." + (interactive) + (customize-group "helm")) + + +;;; Fontlock +(cl-dolist (mode '(emacs-lisp-mode lisp-interaction-mode)) + (font-lock-add-keywords + mode + '(("(\\<\\(with-helm-after-update-hook\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(with-helm-temp-hook\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(with-helm-window\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(with-helm-quittable\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(with-helm-current-buffer\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(with-helm-buffer\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(with-helm-show-completion\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(with-helm-default-directory\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(with-helm-restore-variables\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(helm-multi-key-defun\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(helm-while-no-input\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(helm-aif\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(helm-awhile\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(helm-acond\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(helm-aand\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(helm-with-gensyms\\)\\>" 1 font-lock-keyword-face) + ("(\\<\\(helm-read-answer\\)\\>" 1 font-lock-keyword-face)))) + + +;;; Load the autoload file +;; It should have been generated either by +;; package.el or the make file. + +(load "helm-autoloads" nil t) + +(provide 'helm-config) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-config.el ends here diff --git a/elpa/helm-20181113.923/helm-dabbrev.el b/elpa/helm-20181113.923/helm-dabbrev.el new file mode 100644 index 00000000..33617a36 --- /dev/null +++ b/elpa/helm-20181113.923/helm-dabbrev.el @@ -0,0 +1,388 @@ +;;; helm-dabbrev.el --- Helm implementation of dabbrev. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'helm) +(require 'helm-lib) +(require 'helm-help) +(require 'helm-elisp) ; For show-completion. + +(defgroup helm-dabbrev nil + "Dabbrev related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-dabbrev-always-search-all t + "Always search in all buffers when non--nil. +Note that even if nil, a search in all buffers +will occur if the length of candidates is <= than +`helm-dabbrev-max-length-result'." + :group 'helm-dabbrev + :type 'boolean) + +(defcustom helm-dabbrev-candidates-number-limit 1000 + "Maximum number of candidates to collect. + +Higher this number is, slower the computation of candidates will be. +You can use safely a higher value with emacs-26+. +Note that this have nothing to do with `helm-candidate-number-limit'." + :group 'helm-dabbrev + :type 'integer) + +(defcustom helm-dabbrev-ignored-buffers-regexps + '("\\*helm" "\\*Messages" "\\*Echo Area" "\\*Buffer List") + "List of regexps matching names of buffers that helm-dabbrev should not check." + :group 'helm-dabbrev + :type '(repeat regexp)) + +(defcustom helm-dabbrev-related-buffer-fn #'helm-dabbrev--same-major-mode-p + "A function that decide if a buffer to search in is related to `current-buffer'. +This is actually determined by comparing `major-mode' of the buffer to search +and the `current-buffer'. +The function take one arg, the buffer which is current, look at +`helm-dabbrev--same-major-mode-p' for example. + +When nil all buffers are considered related to `current-buffer'." + :group 'helm-dabbrev + :type 'function) + +(defcustom helm-dabbrev-major-mode-assoc nil + "Major mode association alist. +This allow helm-dabbrev searching in buffers with the associated `major-mode'. +e.g \(emacs-lisp-mode . lisp-interaction-mode\) +will allow searching in the lisp-interaction-mode buffer when `current-buffer' +is an `emacs-lisp-mode' buffer and vice versa i.e +no need to provide \(lisp-interaction-mode . emacs-lisp-mode\) association. + +When nil check is the searched buffer have same `major-mode' +than the `current-buffer'. +This have no effect when `helm-dabbrev-related-buffer-fn' is nil or of course +bound to a function that doesn't handle this var." + :type '(alist :key-type symbol :value-type symbol) + :group 'helm-dabbrev) + +(defcustom helm-dabbrev-lineno-around 30 + "Search first in this number of lines before an after point." + :group 'helm-dabbrev + :type 'integer) + +(defcustom helm-dabbrev-cycle-threshold 5 + "Number of time helm-dabbrev cycle before displaying helm completion. +When nil or 0 disable cycling." + :group 'helm-dabbrev + :type '(choice (const :tag "Cycling disabled" nil) integer)) + +(defcustom helm-dabbrev-case-fold-search 'smart + "Set `case-fold-search' in `helm-dabbrev'. +Same as `helm-case-fold-search' but for `helm-dabbrev'. +Note that this is not affecting searching in helm buffer, +but the initial search for all candidates in buffer(s)." + :group 'helm-dabbrev + :type '(choice (const :tag "Ignore case" t) + (const :tag "Respect case" nil) + (other :tag "Smart" 'smart))) + +(defcustom helm-dabbrev-use-thread nil + "[EXPERIMENTAL] Compute candidates asynchronously (partially) when non nil. + +The idea is to compute candidates while cycling the first ones, so +this is available only if `helm-dabbrev-cycle-threshold' is not 0 or +nil, also it is available only on emacs-26+ (needs threads). + +This is reasonably working when you don't have to complete a huge list +of candidates, otherwise you will have a small delay after the first cycle +because thread is released unexpectedly when helm-dabbrev exit after +first insertion. + +IOW keep `helm-dabbrev-candidates-number-limit' to a reasonable +value (I don't!) and give enough prefix before completing e.g. for +completing \"helm-dabbrev\" use \"helm-d\" and not \"he\" if you want +to use this." + :group 'helm-dabbrev + :type 'boolean) + +(defvaralias 'helm-dabbrev--regexp 'helm-dabbrev-separator-regexp) +(make-obsolete-variable 'helm-dabbrev--regexp + 'helm-dabbrev-separator-regexp "2.8.3") +;; Check for beginning of line should happen last (^\n\\|^). +(defvar helm-dabbrev-separator-regexp + "\\s-\\|\t\\|[(\\[\\{\"'`=<$;,@.#+]\\|\\s\\\\|^\n\\|^" + "Regexp matching the start of a dabbrev candidate.") + + +(defvar helm-dabbrev-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-/") 'helm-next-line) + (define-key map (kbd "M-:") 'helm-previous-line) + map)) + +;; Internal +(defvar helm-dabbrev--cache nil) +(defvar helm-dabbrev--data nil) +(cl-defstruct helm-dabbrev-info dabbrev limits iterator) +(defvar helm-dabbrev--already-tried nil) +(defvar helm-dabbrev--current-thread nil) + + +(defun helm-dabbrev--buffer-list () + (cl-loop for buf in (buffer-list) + unless (cl-loop for r in helm-dabbrev-ignored-buffers-regexps + thereis (string-match r (buffer-name buf))) + collect buf)) + +(defun helm-dabbrev--same-major-mode-p (start-buffer) + "Decide if current-buffer is related to START-BUFFER." + (helm-same-major-mode-p start-buffer helm-dabbrev-major-mode-assoc)) + +(defun helm-dabbrev--collect (str limit ignore-case all) + (let* ((case-fold-search ignore-case) + (buffer1 (current-buffer)) ; start buffer. + (minibuf (minibufferp buffer1)) + result pos-before pos-after + (search-and-store + (lambda (pattern direction) + (while (and (<= (length result) limit) + (cl-case direction + (1 (search-forward pattern nil t)) + (-1 (search-backward pattern nil t)) + (2 (let ((pos + (save-excursion + (forward-line + helm-dabbrev-lineno-around) + (point)))) + (setq pos-after pos) + (search-forward pattern pos t))) + (-2 (let ((pos + (save-excursion + (forward-line + (- helm-dabbrev-lineno-around)) + (point)))) + (setq pos-before pos) + (search-backward pattern pos t))))) + (let* ((pbeg (match-beginning 0)) + (replace-regexp (concat "\\(" helm-dabbrev-separator-regexp + "\\)\\'")) + (match-word (helm-dabbrev--search + pattern pbeg replace-regexp))) + (when (and match-word (not (member match-word result))) + (push match-word result))))))) + (catch 'break + (dolist (buf (if all (helm-dabbrev--buffer-list) + (list (current-buffer)))) + (with-current-buffer buf + (when (or minibuf ; check against all buffers when in minibuffer. + (if helm-dabbrev-related-buffer-fn + (funcall helm-dabbrev-related-buffer-fn buffer1) + t)) + (save-excursion + ;; Start searching before thing before point. + (goto-char (- (point) (length str))) + ;; Search the last 30 lines before point. + (funcall search-and-store str -2)) ; store pos [1] + (save-excursion + ;; Search the next 30 lines after point. + (funcall search-and-store str 2)) ; store pos [2] + (save-excursion + ;; Search all before point. + ;; If limit is reached in previous call of + ;; search-and-store pos-before is never set and + ;; goto-char will fail, so check it. + (when pos-before + (goto-char pos-before) ; start from [1] + (funcall search-and-store str -1))) + (save-excursion + ;; Search all after point. + ;; Same comment as above for pos-after. + (when pos-after + (goto-char pos-after) ; start from [2] + (funcall search-and-store str 1))))) + (when (>= (length result) limit) (throw 'break nil)))) + (nreverse result))) + +(defun helm-dabbrev--search (pattern beg sep-regexp) + "Search word or symbol at point matching PATTERN. +Argument BEG is corresponding to the previous match-beginning search. +The search starts at (1- BEG) with a regexp starting with +`helm-dabbrev-separator-regexp' followed by PATTERN followed by a +regexp matching syntactically any word or symbol. +The possible false positives matching SEP-REGEXP at end are finally +removed." + (let ((eol (point-at-eol))) + (save-excursion + (goto-char (1- beg)) + (when (re-search-forward + (concat "\\(" + helm-dabbrev-separator-regexp + "\\)" + "\\(?99:\\(" + (regexp-quote pattern) + "\\(\\sw\\|\\s_\\)+\\)\\)") + eol t) + (replace-regexp-in-string + sep-regexp "" + (match-string-no-properties 99)))))) + +(defun helm-dabbrev--get-candidates (dabbrev &optional limit) + (cl-assert dabbrev nil "[No Match]") + (helm-dabbrev--collect + dabbrev (or limit helm-dabbrev-candidates-number-limit) + (cl-case helm-dabbrev-case-fold-search + (smart (helm-set-case-fold-search-1 dabbrev)) + (t helm-dabbrev-case-fold-search)) + helm-dabbrev-always-search-all)) + +(defun helm-dabbrev-default-action (candidate) + (with-helm-current-buffer + (let* ((limits (helm-bounds-of-thing-before-point + helm-dabbrev-separator-regexp)) + (beg (car limits)) + (end (point))) + (run-with-timer + 0.01 nil + 'helm-insert-completion-at-point + beg end candidate)))) + +;;;###autoload +(cl-defun helm-dabbrev () + "Preconfigured helm for dynamic abbreviations." + (interactive) + (let ((dabbrev (helm-thing-before-point + nil helm-dabbrev-separator-regexp)) + (limits (helm-bounds-of-thing-before-point + helm-dabbrev-separator-regexp)) + (enable-recursive-minibuffers t) + (cycling-disabled-p (or (null helm-dabbrev-cycle-threshold) + (zerop helm-dabbrev-cycle-threshold))) + (helm-execute-action-at-once-if-one t) + (helm-quit-if-no-candidate + (lambda () + (message "[Helm-dabbrev: No expansion found]")))) + (cl-assert (and (stringp dabbrev) (not (string= dabbrev ""))) + nil "[Helm-dabbrev: Nothing found before point]") + (when (and + ;; have been called at least once. + (helm-dabbrev-info-p helm-dabbrev--data) + ;; But user have moved with some other command + ;; in the meaning time. + (not (eq last-command 'helm-dabbrev))) + (setq helm-dabbrev--data nil)) + ;; When candidates are requested in helm directly without cycling, + ;; we need them right now before running helm, so no need to use a + ;; thread here. + (when cycling-disabled-p + (setq helm-dabbrev--cache (helm-dabbrev--get-candidates dabbrev))) + (unless (or cycling-disabled-p + (helm-dabbrev-info-p helm-dabbrev--data)) + (setq helm-dabbrev--data + (make-helm-dabbrev-info + :dabbrev dabbrev + :limits limits + :iterator + (helm-iter-list + (cl-loop for i in (helm-dabbrev--get-candidates + dabbrev helm-dabbrev-cycle-threshold) + when (string-match-p + (concat "^" (regexp-quote dabbrev)) i) + collect i)))) + ;; Thread is released as soon as helm-dabbrev exits after first + ;; insertion so this is unusable for now, keep it like this for + ;; now hooping the situation with threads will be improved in + ;; emacs. The idea is to compute whole list of candidates in + ;; background while cycling with the first + ;; helm-dabbrev-cycle-threshold ones. + (when (and (fboundp 'make-thread) helm-dabbrev-use-thread) + (setq helm-dabbrev--current-thread + (make-thread + (lambda () + (setq helm-dabbrev--cache + (helm-dabbrev--get-candidates dabbrev))))))) + (let ((iter (and (helm-dabbrev-info-p helm-dabbrev--data) + (helm-dabbrev-info-iterator helm-dabbrev--data))) + deactivate-mark) + ;; Cycle until iterator is consumed. + (helm-aif (and iter (helm-iter-next iter)) + (progn + (helm-insert-completion-at-point + (car (helm-dabbrev-info-limits helm-dabbrev--data)) + ;; END is the end of the previous inserted string, not + ;; the end (apart for first insertion) of the initial string. + (cdr limits) it) + ;; Move already tried candidates to end of list. + (push it helm-dabbrev--already-tried)) + ;; Iterator is now empty, reset dabbrev to initial value + ;; and start helm completion. + (let* ((old-dabbrev (if (helm-dabbrev-info-p helm-dabbrev--data) + (helm-dabbrev-info-dabbrev helm-dabbrev--data) + dabbrev)) + (only-one (null (cdr (all-completions + old-dabbrev + helm-dabbrev--already-tried))))) + (unless helm-dabbrev-use-thread + (message "Waiting for helm-dabbrev candidates...") + (setq helm-dabbrev--cache + (helm-dabbrev--get-candidates old-dabbrev))) + ;; If the length of candidates is only one when computed + ;; that's mean the unique matched item have already been + ;; inserted by the iterator, so no need to reinsert the old dabbrev, + ;; just let helm exiting with "No expansion found". + (unless (or only-one cycling-disabled-p) + (setq dabbrev old-dabbrev + limits (helm-dabbrev-info-limits helm-dabbrev--data)) + (setq helm-dabbrev--data nil) + (delete-region (car limits) (point)) + (insert dabbrev)) + ;; Cycling is finished, block until helm-dabbrev--cache have + ;; finished to complete. + (when (and (fboundp 'thread-join) + helm-dabbrev-use-thread + (thread-alive-p helm-dabbrev--current-thread)) + (thread-join helm-dabbrev--current-thread)) + (when (and (null cycling-disabled-p) only-one) + (cl-return-from helm-dabbrev + (message "[Helm-dabbrev: No expansion found]"))) + (with-helm-show-completion (car limits) (cdr limits) + (unwind-protect + (helm :sources + (helm-build-in-buffer-source "Dabbrev Expand" + :data + (cl-loop for cand in helm-dabbrev--cache + unless + (member cand helm-dabbrev--already-tried) + collect cand into lst + finally return + (append lst helm-dabbrev--already-tried)) + :persistent-action 'ignore + :persistent-help "DoNothing" + :keymap helm-dabbrev-map + :action 'helm-dabbrev-default-action + :group 'helm-dabbrev) + :buffer "*helm dabbrev*" + :input (concat "^" dabbrev " ") + :resume 'noresume + :allow-nest t) + (setq helm-dabbrev--already-tried nil)))))))) + +(provide 'helm-dabbrev) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-dabbrev.el ends here diff --git a/elpa/helm-20181113.923/helm-easymenu.el b/elpa/helm-20181113.923/helm-easymenu.el new file mode 100644 index 00000000..5619aacb --- /dev/null +++ b/elpa/helm-20181113.923/helm-easymenu.el @@ -0,0 +1,90 @@ +;;; helm-easymenu.el --- Helm easymenu definitions. -*- lexical-binding: t -*- + +;; Copyright (C) 2015 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'easymenu) + +(easy-menu-add-item + nil '("Tools") + '("Helm" + ["Find any Files/Buffers" helm-multi-files t] + ["Helm Everywhere (Toggle)" helm-mode t] + ["Helm resume" helm-resume t] + "----" + ("Files" + ["Find files" helm-find-files t] + ["Recent Files" helm-recentf t] + ["Locate" helm-locate t] + ["Search Files with find" helm-find t] + ["Bookmarks" helm-filtered-bookmarks t]) + ("Buffers" + ["Find buffers" helm-buffers-list t]) + ("Commands" + ["Emacs Commands" helm-M-x t] + ["Externals Commands" helm-run-external-command t]) + ("Help" + ["Helm Apropos" helm-apropos t]) + ("Info" + ["Info at point" helm-info-at-point t] + ["Emacs Manual index" helm-info-emacs t] + ["Gnus Manual index" helm-info-gnus t] + ["Helm documentation" helm-documentation t]) + ("Org" + ["Org headlines in org agenda files" helm-org-agenda-files-headings t] + ["Org headlines in buffer" helm-org-in-buffer-headings t]) + ("Elpa" + ["Elisp packages" helm-list-elisp-packages t] + ["Elisp packages no fetch" helm-list-elisp-packages-no-fetch t]) + ("Tools" + ["Occur" helm-occur t] + ["Grep current directory with AG" helm-do-grep-ag t] + ["Gid" helm-gid t] + ["Etags" helm-etags-select t] + ["Lisp complete at point" helm-lisp-completion-at-point t] + ["Browse Kill ring" helm-show-kill-ring t] + ["Browse register" helm-register t] + ["Mark Ring" helm-all-mark-rings t] + ["Regexp handler" helm-regexp t] + ["Colors & Faces" helm-colors t] + ["Show xfonts" helm-select-xfont t] + ["Ucs Symbols" helm-ucs t] + ["Imenu" helm-imenu t] + ["Imenu all" helm-imenu-in-all-buffers t] + ["Semantic or Imenu" helm-semantic-or-imenu t] + ["Google Suggest" helm-google-suggest t] + ["Eval expression" helm-eval-expression-with-eldoc t] + ["Calcul expression" helm-calcul-expression t] + ["Man pages" helm-man-woman t] + ["Top externals process" helm-top t] + ["Emacs internals process" helm-list-emacs-process t]) + "----" + ["Preferred Options" helm-configuration t]) + "Spell Checking") + +(easy-menu-add-item nil '("Tools") '("----") "Spell Checking") + + +(provide 'helm-easymenu) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-easymenu.el ends here diff --git a/elpa/helm-20181113.923/helm-elisp-package.el b/elpa/helm-20181113.923/helm-elisp-package.el new file mode 100644 index 00000000..be0de6b4 --- /dev/null +++ b/elpa/helm-20181113.923/helm-elisp-package.el @@ -0,0 +1,466 @@ +;;; helm-elisp-package.el --- helm interface for package.el -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'package) + +(defgroup helm-el-package nil + "helm elisp packages." + :group 'helm) + +(defcustom helm-el-package-initial-filter 'all + "Show only installed, upgraded or all packages at startup." + :group 'helm-el-package + :type '(radio :tag "Initial filter for elisp packages" + (const :tag "Show all packages" all) + (const :tag "Show installed packages" installed) + (const :tag "Show not installed packages" uninstalled) + (const :tag "Show upgradable packages" upgrade))) + +(defcustom helm-el-truncate-lines t + "Truncate lines in helm-buffer when non--nil." + :group 'helm-el-package + :type 'boolean) + +;; internals vars +(defvar helm-el-package--show-only 'all) +(defvar helm-el-package--initialized-p nil) +(defvar helm-el-package--tabulated-list nil) +(defvar helm-el-package--upgrades nil) +(defvar helm-el-package--removable-packages nil) + +;; Shutup bytecompiler for emacs-24* +(defvar package-menu-async) ; Only available on emacs-25. +(declare-function async-byte-recompile-directory "ext:async-bytecomp.el") + +(defun helm-el-package--init () + (let (package-menu-async + (inhibit-read-only t)) + (when (null package-alist) + (setq helm-el-package--show-only 'all)) + (when (and (fboundp 'package--removable-packages) + (setq helm-el-package--removable-packages + (package--removable-packages)) + (fboundp 'package-autoremove)) + (package-autoremove)) + (unwind-protect + (progn + (save-selected-window + (if (and helm-el-package--initialized-p + (fboundp 'package-show-package-list)) + ;; Use this as `list-packages' doesn't work + ;; properly (empty buffer) when called from lisp + ;; with 'no-fetch (emacs-25 WA). + (package-show-package-list) + (when helm--force-updating-p (message "Refreshing packages list...")) + (list-packages helm-el-package--initialized-p)) + (setq helm-el-package--initialized-p t) + (message nil)) + (helm-init-candidates-in-buffer + 'global + (with-current-buffer (get-buffer "*Packages*") + (setq helm-el-package--tabulated-list tabulated-list-entries) + (remove-text-properties (point-min) (point-max) + '(read-only button follow-link category)) + (buffer-string))) + (setq helm-el-package--upgrades (helm-el-package-menu--find-upgrades)) + (if helm--force-updating-p + (if helm-el-package--upgrades + (message "Refreshing packages list done, [%d] package(s) to upgrade" + (length helm-el-package--upgrades)) + (message "Refreshing packages list done, no upgrades available")) + (setq helm-el-package--show-only (if helm-el-package--upgrades + 'upgrade + helm-el-package-initial-filter)))) + (kill-buffer "*Packages*")))) + +(defun helm-el-package-describe (candidate) + (let ((id (get-text-property 0 'tabulated-list-id candidate))) + (describe-package (if (fboundp 'package-desc-name) + (package-desc-name id) + (car id))))) + +(defun helm-el-package-visit-homepage (candidate) + (let* ((id (get-text-property 0 'tabulated-list-id candidate)) + (pkg (if (fboundp 'package-desc-name) (package-desc-name id) + (car id))) + (desc (cadr (assoc pkg package-archive-contents))) + (extras (package-desc-extras desc)) + (url (and (listp extras) (cdr-safe (assoc :url extras))))) + (if (stringp url) + (browse-url url) + (message "Package %s has no homepage" + (propertize (symbol-name pkg) + 'face 'font-lock-keyword-face))))) + +(defun helm-el-run-visit-homepage () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-el-package-visit-homepage))) +(put 'helm-el-run-visit-homepage 'helm-only t) + +(defun helm-el-package-install-1 (pkg-list) + (cl-loop with mkd = pkg-list + for p in mkd + for id = (get-text-property 0 'tabulated-list-id p) + for pkg = (if (fboundp 'package-desc-name) id (car id)) + do (package-install pkg) + collect pkg into installed-list + finally do (if (fboundp 'package-desc-full-name) + (message (format "%d packages installed:\n(%s)" + (length installed-list) + (mapconcat #'package-desc-full-name + installed-list ", "))) + (message (format "%d packages installed:\n(%s)" + (length installed-list) + (mapconcat 'symbol-name installed-list ", ")))))) + +(defun helm-el-package-install (_candidate) + (helm-el-package-install-1 (helm-marked-candidates))) + +(defun helm-el-run-package-install () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-el-package-install))) +(put 'helm-el-run-package-install 'helm-only t) + +(defun helm-el-package-uninstall-1 (pkg-list &optional force) + (cl-loop with mkd = pkg-list + for p in mkd + for id = (get-text-property 0 'tabulated-list-id p) + do + (condition-case-unless-debug err + (with-no-warnings + (if (fboundp 'package-desc-full-name) + ;; emacs 24.4 + (condition-case nil + (package-delete id force) + (wrong-number-of-arguments + (package-delete id))) + ;; emacs 24.3 + (package-delete (symbol-name (car id)) + (package-version-join (cdr id))))) + (error (message (cadr err)))) + ;; Seems like package-descs are symbols with props instead of + ;; vectors in emacs-27, use package-desc-name to ensure + ;; compatibility in all emacs versions. + unless (assoc (package-desc-name id) package-alist) + collect (if (fboundp 'package-desc-full-name) + id + (cons (symbol-name (car id)) + (package-version-join (cdr id)))) + into delete-list + finally do (if delete-list + (if (fboundp 'package-desc-full-name) + ;; emacs 24.4 + (message (format "%d packages deleted:\n(%s)" + (length delete-list) + (mapconcat #'package-desc-full-name + delete-list ", "))) + ;; emacs 24.3 + (message (format "%d packages deleted:\n(%s)" + (length delete-list) + (mapconcat (lambda (x) + (concat (car x) "-" (cdr x))) + delete-list ", "))) + ;; emacs 24.3 doesn't update + ;; its `package-alist' after deleting. + (cl-loop for p in package-alist + when (assq (symbol-name (car p)) delete-list) + do (setq package-alist (delete p package-alist)))) + "No package deleted"))) + +(defun helm-el-package-uninstall (_candidate) + (helm-el-package-uninstall-1 (helm-marked-candidates) helm-current-prefix-arg)) + +(defun helm-el-run-package-uninstall () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-el-package-uninstall))) +(put 'helm-el-run-package-uninstall 'helm-only t) + +(defun helm-el-package-menu--find-upgrades () + (cl-loop for entry in helm-el-package--tabulated-list + for pkg-desc = (car entry) + for status = (package-desc-status pkg-desc) + when (member status '("installed" "unsigned" "dependency")) + collect pkg-desc + into installed + when (member status '("available" "new")) + collect (cons (package-desc-name pkg-desc) pkg-desc) + into available + finally return + (cl-loop for pkg in installed + for avail-pkg = (assq (package-desc-name pkg) available) + when (and avail-pkg + (version-list-< (package-desc-version pkg) + (package-desc-version + (cdr avail-pkg)))) + collect avail-pkg))) + +(defun helm-el-package-upgrade-1 (pkg-list) + (cl-loop for p in pkg-list + for pkg-desc = (car p) + for upgrade = (cdr (assq (package-desc-name pkg-desc) + helm-el-package--upgrades)) + do + (cond ((null upgrade) + (ignore)) + ((equal pkg-desc upgrade) + ;;Install. + (with-no-warnings + (if (boundp 'package-selected-packages) + (package-install pkg-desc t) + (package-install pkg-desc)))) + (t + ;; Delete. + (if (boundp 'package-selected-packages) + (with-no-warnings + (package-delete pkg-desc t t)) + (package-delete pkg-desc)))))) + +(defun helm-el-package-upgrade (_candidate) + (helm-el-package-upgrade-1 + (cl-loop with pkgs = (helm-marked-candidates) + for p in helm-el-package--tabulated-list + for pkg = (car p) + if (member (symbol-name (package-desc-name pkg)) pkgs) + collect p))) + +(defun helm-el-run-package-upgrade () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-el-package-upgrade))) +(put 'helm-el-run-package-upgrade 'helm-only t) + +(defun helm-el-package-upgrade-all () + (if helm-el-package--upgrades + (with-helm-display-marked-candidates + helm-marked-buffer-name (mapcar (lambda (x) (symbol-name (car x))) + helm-el-package--upgrades) + (when (y-or-n-p "Upgrade all packages? ") + (helm-el-package-upgrade-1 helm-el-package--tabulated-list))) + (message "No packages to upgrade actually!"))) + +(defun helm-el-package-upgrade-all-action (_candidate) + (helm-el-package-upgrade-all)) + +(defun helm-el-run-package-upgrade-all () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-el-package-upgrade-all-action))) +(put 'helm-el-run-package-upgrade-all 'helm-only t) + +(defun helm-el-package--transformer (candidates _source) + (cl-loop for c in candidates + for id = (get-text-property 0 'tabulated-list-id c) + for name = (if (fboundp 'package-desc-name) + (and id (package-desc-name id)) + (car id)) + for desc = (package-desc-status id) + for built-in-p = (and (package-built-in-p name) + (not (member desc '("available" "new" + "installed" "dependency")))) + for installed-p = (member desc '("installed" "dependency")) + for upgrade-p = (assq name helm-el-package--upgrades) + for user-installed-p = (and (boundp 'package-selected-packages) + (memq name package-selected-packages)) + do (when user-installed-p (put-text-property 0 2 'display "S " c)) + do (when (memq name helm-el-package--removable-packages) + (put-text-property 0 2 'display "U " c) + (put-text-property + 2 (+ (length (symbol-name name)) 2) + 'face 'font-lock-variable-name-face c)) + for cand = (cons c (car (split-string c))) + when (or (and built-in-p + (eq helm-el-package--show-only 'built-in)) + (and upgrade-p + (eq helm-el-package--show-only 'upgrade)) + (and installed-p + (eq helm-el-package--show-only 'installed)) + (and (not installed-p) + (not built-in-p) + (eq helm-el-package--show-only 'uninstalled)) + (eq helm-el-package--show-only 'all)) + collect cand)) + +(defun helm-el-package-show-built-in () + (interactive) + (with-helm-alive-p + (setq helm-el-package--show-only 'built-in) + (helm-update))) +(put 'helm-el-package-show-built-in 'helm-only t) + +(defun helm-el-package-show-upgrade () + (interactive) + (with-helm-alive-p + (setq helm-el-package--show-only 'upgrade) + (helm-update))) +(put 'helm-el-package-show-upgrade 'helm-only t) + +(defun helm-el-package-show-installed () + (interactive) + (with-helm-alive-p + (setq helm-el-package--show-only 'installed) + (helm-update))) +(put 'helm-el-package-show-installed 'helm-only t) + +(defun helm-el-package-show-all () + (interactive) + (with-helm-alive-p + (setq helm-el-package--show-only 'all) + (helm-update))) +(put 'helm-el-package-show-all 'helm-only t) + +(defun helm-el-package-show-uninstalled () + (interactive) + (with-helm-alive-p + (setq helm-el-package--show-only 'uninstalled) + (helm-update))) +(put 'helm-el-package-show-uninstalled 'helm-only t) + +(defvar helm-el-package-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-I") 'helm-el-package-show-installed) + (define-key map (kbd "M-O") 'helm-el-package-show-uninstalled) + (define-key map (kbd "M-U") 'helm-el-package-show-upgrade) + (define-key map (kbd "M-B") 'helm-el-package-show-built-in) + (define-key map (kbd "M-A") 'helm-el-package-show-all) + (define-key map (kbd "C-c i") 'helm-el-run-package-install) + (define-key map (kbd "C-c r") 'helm-el-run-package-reinstall) + (define-key map (kbd "C-c d") 'helm-el-run-package-uninstall) + (define-key map (kbd "C-c u") 'helm-el-run-package-upgrade) + (define-key map (kbd "C-c U") 'helm-el-run-package-upgrade-all) + (define-key map (kbd "C-c @") 'helm-el-run-visit-homepage) + map)) + +(defvar helm-source-list-el-package nil) +(defclass helm-list-el-package-source (helm-source-in-buffer) + ((init :initform 'helm-el-package--init) + (get-line :initform 'buffer-substring) + (filtered-candidate-transformer :initform 'helm-el-package--transformer) + (action-transformer :initform 'helm-el-package--action-transformer) + (help-message :initform 'helm-el-package-help-message) + (keymap :initform helm-el-package-map) + (update :initform 'helm-el-package--update) + (candidate-number-limit :initform 9999) + (action :initform '(("Describe package" . helm-el-package-describe) + ("Visit homepage" . helm-el-package-visit-homepage))) + (group :initform 'helm-el-package))) + +(defun helm-el-package--action-transformer (actions candidate) + (let* ((pkg-desc (get-text-property 0 'tabulated-list-id candidate)) + (status (package-desc-status pkg-desc)) + (pkg-name (package-desc-name pkg-desc)) + (built-in (and (package-built-in-p pkg-name) + (not (member status '("available" "new" + "installed" "dependency"))))) + (acts (if helm-el-package--upgrades + (append actions '(("Upgrade all packages" + . helm-el-package-upgrade-all-action))) + actions))) + (cond (built-in '(("Describe package" . helm-el-package-describe))) + ((and (package-installed-p pkg-name) + (cdr (assq pkg-name helm-el-package--upgrades)) + (member status '("installed" "dependency"))) + (append '(("Upgrade package(s)" . helm-el-package-upgrade) + ("Uninstall package(s)" . helm-el-package-uninstall)) + acts)) + ((and (package-installed-p pkg-name) + (cdr (assq pkg-name helm-el-package--upgrades)) + (string= status "available")) + (append '(("Upgrade package(s)" . helm-el-package-upgrade)) + acts)) + ((and (package-installed-p pkg-name) + (or (null (package-built-in-p pkg-name)) + (and (package-built-in-p pkg-name) + (assq pkg-name package-alist)))) + (append acts '(("Reinstall package(s)" . helm-el-package-reinstall) + ("Recompile package(s)" . helm-el-package-recompile) + ("Uninstall package(s)" . helm-el-package-uninstall)))) + (t (append acts '(("Install packages(s)" . helm-el-package-install))))))) + +(defun helm-el-package--update () + (setq helm-el-package--initialized-p nil)) + +(defun helm-el-package-recompile (_pkg) + (cl-loop for p in (helm-marked-candidates) + for pkg-desc = (get-text-property 0 'tabulated-list-id p) + for name = (package-desc-name pkg-desc) + for dir = (package-desc-dir pkg-desc) + do (if (fboundp 'async-byte-recompile-directory) + (async-byte-recompile-directory dir) + (when (y-or-n-p (format "Really recompile `%s' while already loaded ?" name)) + (byte-recompile-directory dir 0 t))))) + +(defun helm-el-package-reinstall (_pkg) + (cl-loop for p in (helm-marked-candidates) + for pkg-desc = (get-text-property 0 'tabulated-list-id p) + for name = (package-desc-name pkg-desc) + do (if (boundp 'package-selected-packages) + (with-no-warnings + (package-delete pkg-desc 'force 'nosave) + ;; pkg-desc contain the description + ;; of the installed package just removed + ;; and is BTW no more valid. + ;; Use the entry in package-archive-content + ;; which is the non--installed package entry. + ;; For some reason `package-install' + ;; need a pkg-desc (package-desc-p) for the build-in + ;; packages already installed, the name (as symbol) + ;; fails with such packages. + (package-install + (cadr (assq name package-archive-contents)) t)) + (package-delete pkg-desc) + (package-install name)))) + +(defun helm-el-run-package-reinstall () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-el-package-reinstall))) +(put 'helm-el-run-package-reinstall 'helm-only t) + +;;;###autoload +(defun helm-list-elisp-packages (arg) + "Preconfigured helm for listing and handling emacs packages." + (interactive "P") + (when arg (setq helm-el-package--initialized-p nil)) + (unless helm-source-list-el-package + (setq helm-source-list-el-package + (helm-make-source "list packages" 'helm-list-el-package-source))) + (helm :sources 'helm-source-list-el-package + :truncate-lines helm-el-truncate-lines + :full-frame t + :buffer "*helm list packages*")) + +;;;###autoload +(defun helm-list-elisp-packages-no-fetch (arg) + "Preconfigured helm for emacs packages. + +Same as `helm-list-elisp-packages' but don't fetch packages on remote. +Called with a prefix ARG always fetch packages on remote." + (interactive "P") + (let ((helm-el-package--initialized-p (null arg))) + (helm-list-elisp-packages nil))) + +(provide 'helm-elisp-package) + +;;; helm-elisp-package.el ends here diff --git a/elpa/helm-20181113.923/helm-elisp.el b/elpa/helm-20181113.923/helm-elisp.el new file mode 100644 index 00000000..40b5d549 --- /dev/null +++ b/elpa/helm-20181113.923/helm-elisp.el @@ -0,0 +1,979 @@ +;;; helm-elisp.el --- Elisp symbols completion for helm. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: +(require 'cl-lib) +(require 'helm) +(require 'helm-lib) +(require 'helm-help) +(require 'helm-types) +(require 'helm-utils) +(require 'helm-info) +(require 'helm-eval) +(require 'helm-files) + +(declare-function 'helm-describe-function "helm-lib") +(declare-function 'helm-describe-variable "helm-lib") +(declare-function 'helm-describe-face "helm-lib") + + +;;; Customizable values + +(defgroup helm-elisp nil + "Elisp related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-turn-on-show-completion t + "Display candidate in `current-buffer' while moving selection when non--nil." + :group 'helm-elisp + :type 'boolean) + +(defcustom helm-show-completion-min-window-height 7 + "Minimum completion window height used in show completion. +This is used in macro `with-helm-show-completion'." + :group 'helm-elisp + :type 'integer) + +(defcustom helm-lisp-quoted-function-list + '(funcall apply mapc cl-mapc mapcar cl-mapcar + callf callf2 cl-callf cl-callf2 fset + fboundp fmakunbound symbol-function) + "List of function where quoted function completion happen. +e.g give only function names after \(funcall '." + :group 'helm-elisp + :type '(repeat (choice symbol))) + +(defcustom helm-lisp-unquoted-function-list + '(function defadvice) + "List of function where unquoted function completion happen. +e.g give only function names after \(function ." + :group 'helm-elisp + :type '(repeat (choice symbol))) + +(defcustom helm-apropos-fuzzy-match nil + "Enable fuzzy matching for `helm-apropos' when non-nil." + :group 'helm-elisp + :type 'boolean) + +(defcustom helm-lisp-fuzzy-completion nil + "Enable fuzzy matching in emacs-lisp completion when non-nil. +NOTE: This enable fuzzy matching in helm native implementation of +elisp completion, but not on helmized elisp completion, i.e +fuzzy completion is not available in `completion-at-point'." + :group 'helm-elisp + :type 'boolean) + +(defcustom helm-apropos-function-list '(helm-def-source--emacs-commands + helm-def-source--emacs-functions + helm-def-source--eieio-classes + helm-def-source--eieio-generic + helm-def-source--emacs-variables + helm-def-source--emacs-faces) + "A list of functions that build helm sources to use in `helm-apropos'." + :group 'helm-elisp + :type '(repeat (choice symbol))) + +(defcustom helm-apropos-defaut-info-lookup-sources '(helm-source-info-elisp + helm-source-info-cl + helm-source-info-eieio) + "A list of sources to look into when searching info page of a symbol." + :group 'helm-elisp + :type '(repeat (choice symbol))) + +(defcustom helm-show-completion-display-function + (if (display-graphic-p) + #'helm-display-buffer-in-own-frame + #'helm-show-completion-default-display-function) + "The function used to display helm completion buffer. + +This function is used by `with-helm-show-completion', when nil +fallback to `helm-default-display-buffer'. + +Default is to use a separate frame on graphic display and +`helm-show-completion-default-display-function' on non graphic +display." + :group 'helm-elisp + :type 'function) + +;;; Faces +;; +;; +(defgroup helm-elisp-faces nil + "Customize the appearance of helm-elisp." + :prefix "helm-" + :group 'helm-elisp + :group 'helm-faces) + +(defface helm-lisp-show-completion + '((t (:background "DarkSlateGray"))) + "Face used for showing candidates in `helm-lisp-completion'." + :group 'helm-elisp-faces) + +(defface helm-lisp-completion-info + '((t (:foreground "red"))) + "Face used for showing info in `helm-lisp-completion'." + :group 'helm-elisp-faces) + +(defcustom helm-elisp-help-function + 'helm-elisp-show-help + "Function for displaying help for Lisp symbols." + :group 'helm-elisp + :type '(choice (function :tag "Open help for the symbol." + helm-elisp-show-help) + (function :tag "Show one liner in modeline." + helm-elisp-show-doc-modeline))) + +(defcustom helm-locate-library-fuzzy-match t + "Enable fuzzy-matching in `helm-locate-library' when non--nil." + :type 'boolean + :group 'helm-elisp) + + +;;; Show completion. +;; +;; Provide show completion with macro `with-helm-show-completion'. + +(defvar helm-show-completion-overlay nil) + +;; Called each time cursor move in helm-buffer. +(defun helm-show-completion () + (with-helm-current-buffer + (overlay-put helm-show-completion-overlay + 'display (substring-no-properties + (helm-get-selection))))) + +(defun helm-show-completion-init-overlay (beg end) + (setq helm-show-completion-overlay (make-overlay beg end)) + (overlay-put helm-show-completion-overlay + 'face 'helm-lisp-show-completion)) + +(defun helm-show-completion-default-display-function (buffer &rest _args) + "A special resized helm window is used depending on position in BUFFER." + (with-selected-window (selected-window) + (if (window-dedicated-p) + (helm-default-display-buffer buffer) + (let* ((screen-size (+ (count-screen-lines (window-start) (point) t) + 1 ; mode-line + (if header-line-format 1 0))) ; header-line + (def-size (- (window-height) + helm-show-completion-min-window-height)) + (upper-height (max window-min-height (min screen-size def-size))) + split-window-keep-point) + (recenter -1) + (set-window-buffer (if (active-minibuffer-window) + (minibuffer-selected-window) + (split-window nil upper-height + helm-split-window-default-side)) + buffer))))) + +(defmacro with-helm-show-completion (beg end &rest body) + "Show helm candidate in an overlay at point. +BEG and END are the beginning and end position of the current completion +in `helm-current-buffer'. +BODY is an helm call where we want to enable show completion. +If `helm-turn-on-show-completion' is nil do nothing." + (declare (indent 2) (debug t)) + `(unwind-protect + (if helm-turn-on-show-completion + (let ((helm-move-selection-after-hook + (append (list 'helm-show-completion) + helm-move-selection-after-hook)) + (helm-split-window-default-side + (if (eq helm-split-window-default-side 'same) + 'below helm-split-window-default-side)) + helm-split-window-inside-p + helm-reuse-last-window-split-state) + (helm-set-local-variable + 'helm-display-function + (or helm-show-completion-display-function + 'helm-default-display-buffer)) + (helm-show-completion-init-overlay ,beg ,end) + ,@body) + ,@body) + (when (and helm-show-completion-overlay + (overlayp helm-show-completion-overlay)) + (delete-overlay helm-show-completion-overlay)))) + + +;;; Lisp symbol completion. +;; +;; +(defun helm-lisp-completion--predicate-at-point (beg) + ;; Return a predicate for `all-completions'. + (let ((fn-sym-p (lambda () + (or + (and (eq (char-before) ?\ ) + (save-excursion + (skip-syntax-backward " " (point-at-bol)) + (memq (symbol-at-point) + helm-lisp-unquoted-function-list))) + (and (eq (char-before) ?\') + (save-excursion + (forward-char -1) + (eq (char-before) ?\#))))))) + (save-excursion + (goto-char beg) + (if (or + ;; Complete on all symbols in non--lisp modes (logs mail etc..) + (not (memq major-mode '(emacs-lisp-mode + lisp-interaction-mode + inferior-emacs-lisp-mode))) + (not (or (funcall fn-sym-p) + (and (eq (char-before) ?\') + (save-excursion + (forward-char (if (funcall fn-sym-p) -2 -1)) + (skip-syntax-backward " " (point-at-bol)) + (memq (symbol-at-point) + helm-lisp-quoted-function-list))) + (eq (char-before) ?\())) ; no paren before str. + ;; Looks like we are in a let statement. + (condition-case nil + (progn (up-list -2) (forward-char 1) + (eq (char-after) ?\()) + (error nil))) + (lambda (sym) + (or (boundp sym) (fboundp sym) (symbol-plist sym))) + #'fboundp)))) + +(defun helm-thing-before-point (&optional limits regexp) + "Return symbol name before point. +If REGEXP is specified return what REGEXP find before point. +By default match the beginning of symbol before point. +With LIMITS arg specified return the beginning and end position +of symbol before point." + (save-excursion + (let (beg + (end (point)) + (boundary (field-beginning nil nil (point-at-bol)))) + (if (re-search-backward (or regexp "\\_<") boundary t) + (setq beg (match-end 0)) + (setq beg boundary)) + (unless (= beg end) + (if limits + (cons beg end) + (buffer-substring-no-properties beg end)))))) + +(defun helm-bounds-of-thing-before-point (&optional regexp) + "Get the beginning and end position of `helm-thing-before-point'. +Return a cons \(beg . end\)." + (helm-thing-before-point 'limits regexp)) + +(defun helm-insert-completion-at-point (beg end str) + ;; When there is no space after point + ;; we are completing inside a symbol or + ;; after a partial symbol with the next arg aside + ;; without space, in this case mark the region. + ;; deleting it would remove the + ;; next arg which is unwanted. + (delete-region beg end) + (insert str) + (let ((pos (cdr (or (bounds-of-thing-at-point 'symbol) + ;; needed for helm-dabbrev. + (bounds-of-thing-at-point 'filename))))) + (when (and pos (< (point) pos)) + (push-mark pos t t)))) + +(defvar helm-lisp-completion--cache nil) +(defvar helm-lgst-len nil) +;;;###autoload +(defun helm-lisp-completion-at-point () + "Preconfigured helm for lisp symbol completion at point." + (interactive) + (setq helm-lgst-len 0) + (let* ((target (helm-thing-before-point)) + (beg (car (helm-bounds-of-thing-before-point))) + (end (point)) + (pred (and beg (helm-lisp-completion--predicate-at-point beg))) + (loc-vars (and (fboundp 'elisp--local-variables) + (ignore-errors + (mapcar #'symbol-name (elisp--local-variables))))) + (glob-syms (and target pred (all-completions target obarray pred))) + (candidates (append loc-vars glob-syms)) + (helm-quit-if-no-candidate t) + (helm-execute-action-at-once-if-one t) + (enable-recursive-minibuffers t)) + (setq helm-lisp-completion--cache (cl-loop for sym in candidates + for len = (length sym) + when (> len helm-lgst-len) + do (setq helm-lgst-len len) + collect sym)) + (if candidates + (with-helm-show-completion beg end + ;; Overlay is initialized now in helm-current-buffer. + (helm + :sources (helm-build-in-buffer-source "Lisp completion" + :data helm-lisp-completion--cache + :persistent-action `(helm-lisp-completion-persistent-action . + ,(and (eq helm-elisp-help-function + 'helm-elisp-show-doc-modeline) + 'never-split)) + :nomark t + :match-part (lambda (c) (car (split-string c))) + :fuzzy-match helm-lisp-fuzzy-completion + :persistent-help (helm-lisp-completion-persistent-help) + :filtered-candidate-transformer + 'helm-lisp-completion-transformer + :action (lambda (candidate) + (with-helm-current-buffer + (run-with-timer + 0.01 nil + 'helm-insert-completion-at-point + beg end candidate)))) + :input (if helm-lisp-fuzzy-completion + target (concat target " ")) + :resume 'noresume + :truncate-lines t + :buffer "*helm lisp completion*" + :allow-nest t)) + (message "[No Match]")))) + +(defun helm-lisp-completion-persistent-action (candidate &optional name) + "Show documentation for the function. +Documentation is shown briefly in mode-line or completely +in other window according to the value of `helm-elisp-help-function'." + (funcall helm-elisp-help-function candidate name)) + +(defun helm-lisp-completion-persistent-help () + "Return persistent-help according to the value of `helm-elisp-help-function'" + (cl-ecase helm-elisp-help-function + (helm-elisp-show-doc-modeline "Show brief doc in mode-line") + (helm-elisp-show-help "Toggle show help for the symbol"))) + +(defun helm-elisp--show-help-1 (candidate &optional name) + (let ((sym (intern-soft candidate))) + (cl-typecase sym + ((and fboundp boundp) + (if (member name '("describe-function" "describe-variable")) + (funcall (intern (format "helm-%s" name)) sym) + ;; When there is no way to know what to describe + ;; prefer describe-function. + (helm-describe-function sym))) + (fbound (helm-describe-function sym)) + (bound (helm-describe-variable sym)) + (face (helm-describe-face sym))))) + +(defun helm-elisp-show-help (candidate &optional name) + "Show full help for the function CANDIDATE. +Arg NAME specify the name of the top level function +calling helm generic completion (e.g \"describe-function\") +which allow calling the right function when CANDIDATE symbol +refers at the same time to variable and a function." + (helm-elisp--persistent-help + candidate 'helm-elisp--show-help-1 name)) + +(defun helm-elisp-show-doc-modeline (candidate &optional name) + "Show brief documentation for the function in modeline." + (let ((cursor-in-echo-area t) + mode-line-in-non-selected-windows) + (helm-show-info-in-mode-line + (propertize + (helm-get-first-line-documentation + (intern candidate) name) + 'face 'helm-lisp-completion-info)))) + +(defun helm-lisp-completion-transformer (candidates _source) + "Helm candidates transformer for lisp completion." + (cl-loop for c in candidates + for sym = (intern c) + for annot = (cl-typecase sym + (command " (Com)") + (class " (Class)") + (generic " (Gen)") + (fbound " (Fun)") + (bound " (Var)") + (face " (Face)")) + for spaces = (make-string (- helm-lgst-len (length c)) ? ) + collect (cons (concat c spaces annot) c) into lst + finally return (sort lst #'helm-generic-sort-fn))) + +(defun helm-get-first-line-documentation (sym &optional name) + "Return first line documentation of symbol SYM. +If SYM is not documented, return \"Not documented\"." + (let ((doc (cl-typecase sym + ((and fboundp boundp) + (cond ((string= name "describe-function") + (documentation sym t)) + ((string= name "describe-variable") + (documentation-property sym 'variable-documentation t)) + (t (documentation sym t)))) + (fbound (documentation sym t)) + (bound (documentation-property sym 'variable-documentation t)) + (face (face-documentation sym))))) + (if (and doc (not (string= doc "")) + ;; `documentation' return "\n\n(args...)" + ;; for CL-style functions. + (not (string-match-p "^\n\n" doc))) + (car (split-string doc "\n")) + "Not documented"))) + +;;; File completion. +;; +;; Complete file name at point. + +;;;###autoload +(defun helm-complete-file-name-at-point (&optional force) + "Preconfigured helm to complete file name at point." + (interactive) + (require 'helm-mode) + (let* ((tap (thing-at-point 'filename)) + beg + (init (and tap + (or force + (save-excursion + (end-of-line) + (search-backward tap (point-at-bol) t) + (setq beg (point)) + (looking-back "[^'`( ]" (1- (point))))) + (expand-file-name + (substring-no-properties tap)))) + (end (point)) + (helm-quit-if-no-candidate t) + (helm-execute-action-at-once-if-one t) + completion) + (with-helm-show-completion beg end + (setq completion (helm-read-file-name "FileName: " + :initial-input init))) + (when (and completion (not (string= completion ""))) + (delete-region beg end) (insert (if (string-match "^~" tap) + (abbreviate-file-name completion) + completion))))) + +;;;###autoload +(defun helm-lisp-indent () + ;; It is meant to use with `helm-define-multi-key' which + ;; does not support args for functions yet, so use `current-prefix-arg' + ;; for now instead of (interactive "P"). + (interactive) + (let ((tab-always-indent (or (eq tab-always-indent 'complete) + tab-always-indent))) + (indent-for-tab-command current-prefix-arg))) + +;;;###autoload +(defun helm-lisp-completion-or-file-name-at-point () + "Preconfigured helm to complete lisp symbol or filename at point. +Filename completion happen if string start after or between a double quote." + (interactive) + (let* ((tap (thing-at-point 'filename))) + (if (and tap (save-excursion + (end-of-line) + (search-backward tap (point-at-bol) t) + (looking-back "[^'`( ]" (1- (point))))) + (helm-complete-file-name-at-point) + (helm-lisp-completion-at-point)))) + + +;;; Apropos +;; +;; +(defvar helm-apropos-history nil) + +(defun helm-apropos-init (test default) + "Init candidates buffer for `helm-apropos' sources." + (require 'helm-help) + (helm-init-candidates-in-buffer 'global + (let ((default-symbol (and (stringp default) + (intern-soft default))) + (symbols (all-completions "" obarray test))) + (if (and default-symbol (funcall test default-symbol)) + (cons default-symbol symbols) + symbols)))) + +(defun helm-apropos-init-faces (default) + "Init candidates buffer for faces for `helm-apropos'." + (require 'helm-help) + (with-current-buffer (helm-candidate-buffer 'global) + (goto-char (point-min)) + (let ((default-symbol (and (stringp default) + (intern-soft default))) + (faces (face-list))) + (when (and default-symbol (facep default-symbol)) + (insert (concat default "\n"))) + (insert + (mapconcat #'prin1-to-string + (if default + (cl-remove-if (lambda (sym) (string= sym default)) faces) + faces) + "\n"))))) + +(defun helm-apropos-default-sort-fn (candidates _source) + (if (string= helm-pattern "") + candidates + (sort candidates #'helm-generic-sort-fn))) + +(defun helm-apropos-clean-history-variable (candidate) + (with-helm-current-buffer ; var is maybe local + (let* ((sym (intern-soft candidate)) + (cands (symbol-value sym)) + (mkds (and (listp cands) + (helm-comp-read "Delete entry: " + cands :marked-candidates t)))) + (cl-assert (listp mkds) nil "Variable value is not a list") + (cl-loop for elm in mkds do + (if (local-variable-p sym) + (set (make-local-variable sym) + (setq cands (delete elm cands))) + (set sym (setq cands (delete elm cands)))))))) + +(defun helm-apropos-clean-ring (candidate) + (with-helm-current-buffer ; var is maybe local + (let* ((sym (intern-soft candidate)) + (val (symbol-value sym)) + (cands (and (ring-p val) (ring-elements val))) + (mkds (and cands (helm-comp-read + "Delete entry: " + cands :marked-candidates t)))) + (when mkds + (cl-loop for elm in mkds do + (ring-remove + val (helm-position + elm + (ring-elements val) + :test 'equal)) + and do (if (local-variable-p sym) + (set (make-local-variable sym) val) + (set sym val))))))) + +(defun helm-apropos-action-transformer (actions candidate) + (let* ((sym (helm-symbolify candidate)) + (val (with-helm-current-buffer (symbol-value sym)))) + (cond ((custom-variable-p sym) + (append + actions + (let ((standard-value (eval (car (get sym 'standard-value))))) + (unless (equal standard-value (symbol-value sym)) + `(("Reset Variable to default value" + . ,(lambda (candidate) + (let ((sym (helm-symbolify candidate))) + (set sym standard-value))))))) + '(("Customize variable" . + (lambda (candidate) + (customize-option (helm-symbolify candidate))))))) + ((and val (with-helm-current-buffer (ring-p (symbol-value sym)))) + (append actions + '(("Clean ring" . helm-apropos-clean-ring)))) + ((and (string-match-p "history" candidate) (listp val)) + (append actions + '(("Clean variable" . + helm-apropos-clean-history-variable)))) + (t actions)))) + +(defun helm-def-source--emacs-variables (&optional default) + (helm-build-in-buffer-source "Variables" + :init (lambda () + (helm-apropos-init + (lambda (x) (and (boundp x) (not (keywordp x)))) default)) + :fuzzy-match helm-apropos-fuzzy-match + :filtered-candidate-transformer (and (null helm-apropos-fuzzy-match) + 'helm-apropos-default-sort-fn) + :nomark t + :persistent-action (lambda (candidate) + (helm-elisp--persistent-help + candidate 'helm-describe-variable)) + :persistent-help "Toggle describe variable" + :action '(("Describe variable" . helm-describe-variable) + ("Find variable" . helm-find-variable) + ("Info lookup" . helm-info-lookup-symbol) + ("Set variable" . helm-set-variable)) + :action-transformer 'helm-apropos-action-transformer)) + +(defun helm-def-source--emacs-faces (&optional default) + "Create `helm' source for faces to be displayed with +`helm-apropos'." + (helm-build-in-buffer-source "Faces" + :init (lambda () (helm-apropos-init-faces default)) + :fuzzy-match helm-apropos-fuzzy-match + :filtered-candidate-transformer + (append (and (null helm-apropos-fuzzy-match) + '(helm-apropos-default-sort-fn)) + (list + (lambda (candidates _source) + (cl-loop for c in candidates + collect (propertize c 'face (intern c)))))) + :persistent-action (lambda (candidate) + (helm-elisp--persistent-help + candidate 'helm-describe-face)) + :persistent-help "Toggle describe face" + :action '(("Describe face" . helm-describe-face) + ("Find face" . helm-find-face-definition) + ("Customize face" . (lambda (candidate) + (customize-face (helm-symbolify candidate))))))) + +(defun helm-def-source--emacs-commands (&optional default) + (helm-build-in-buffer-source "Commands" + :init (lambda () + (helm-apropos-init 'commandp default)) + :fuzzy-match helm-apropos-fuzzy-match + :filtered-candidate-transformer (and (null helm-apropos-fuzzy-match) + 'helm-apropos-default-sort-fn) + :nomark t + :persistent-action (lambda (candidate) + (helm-elisp--persistent-help + candidate 'helm-describe-function)) + :persistent-help "Toggle describe command" + :action '(("Describe function" . helm-describe-function) + ("Find function" . helm-find-function) + ("Info lookup" . helm-info-lookup-symbol)))) + +(defun helm-def-source--emacs-functions (&optional default) + (helm-build-in-buffer-source "Functions" + :init (lambda () + (helm-apropos-init (lambda (x) + (and (fboundp x) + (not (commandp x)) + (not (generic-p x)) + (not (class-p x)))) + default)) + :fuzzy-match helm-apropos-fuzzy-match + :filtered-candidate-transformer (and (null helm-apropos-fuzzy-match) + 'helm-apropos-default-sort-fn) + :persistent-action (lambda (candidate) + (helm-elisp--persistent-help + candidate 'helm-describe-function)) + :persistent-help "Toggle describe function" + :nomark t + :action '(("Describe function" . helm-describe-function) + ("Find function" . helm-find-function) + ("Info lookup" . helm-info-lookup-symbol)))) + +(defun helm-def-source--eieio-classes (&optional default) + (helm-build-in-buffer-source "Classes" + :init (lambda () + (helm-apropos-init (lambda (x) + (class-p x)) + default)) + :fuzzy-match helm-apropos-fuzzy-match + :filtered-candidate-transformer (and (null helm-apropos-fuzzy-match) + 'helm-apropos-default-sort-fn) + :nomark t + :persistent-action (lambda (candidate) + (helm-elisp--persistent-help + candidate 'helm-describe-function)) + :persistent-help "Toggle describe class" + :action '(("Describe function" . helm-describe-function) + ("Find function" . helm-find-function) + ("Info lookup" . helm-info-lookup-symbol)))) + +(defun helm-def-source--eieio-generic (&optional default) + (helm-build-in-buffer-source "Generic functions" + :init (lambda () + (helm-apropos-init (lambda (x) + (generic-p x)) + default)) + :fuzzy-match helm-apropos-fuzzy-match + :filtered-candidate-transformer (and (null helm-apropos-fuzzy-match) + 'helm-apropos-default-sort-fn) + :nomark t + :persistent-action (lambda (candidate) + (helm-elisp--persistent-help + candidate 'helm-describe-function)) + :persistent-help "Toggle describe generic function" + :action '(("Describe function" . helm-describe-function) + ("Find function" . helm-find-function) + ("Info lookup" . helm-info-lookup-symbol)))) + +(defun helm-info-lookup-fallback-source (candidate) + (let ((sym (helm-symbolify candidate)) + src-name fn) + (cond ((class-p sym) + (setq fn #'helm-describe-function + src-name "Describe class")) + ((generic-p sym) + (setq fn #'helm-describe-function + src-name "Describe generic function")) + ((fboundp sym) + (setq fn #'helm-describe-function + src-name "Describe function")) + ((facep sym) + (setq fn #'helm-describe-face + src-name "Describe face")) + (t + (setq fn #'helm-describe-variable + src-name "Describe variable"))) + (helm-build-sync-source src-name + :candidates (list candidate) + :persistent-action (lambda (candidate) + (helm-elisp--persistent-help + candidate fn)) + :persistent-help src-name + :nomark t + :action fn))) + +(defun helm-info-lookup-symbol-1 (c) + (let ((helm-execute-action-at-once-if-one 'current-source)) + (helm :sources (append helm-apropos-defaut-info-lookup-sources + (list (helm-info-lookup-fallback-source c))) + :resume 'noresume + :buffer "*helm lookup*" + :input c))) + +(defun helm-info-lookup-symbol (candidate) + ;; ???:Running an idle-timer allows not catching RET when exiting + ;; with the fallback source. + ;; (run-with-idle-timer 0.01 nil #'helm-info-lookup-symbol-1 candidate) + (helm-info-lookup-symbol-1 candidate)) + +;;;###autoload +(defun helm-apropos (default) + "Preconfigured helm to describe commands, functions, variables and faces. +In non interactives calls DEFAULT argument should be provided as a string, +i.e the `symbol-name' of any existing symbol." + (interactive (list (thing-at-point 'symbol))) + (helm :sources + (mapcar (lambda (func) + (funcall func default)) + helm-apropos-function-list) + :history 'helm-apropos-history + :buffer "*helm apropos*" + :preselect (and default (concat "\\_<" (regexp-quote default) "\\_>")))) + + +;;; Advices +;; +;; +(defvar helm-source-advice + (helm-build-sync-source "Function Advice" + :init (lambda () (require 'advice)) + :candidates 'helm-advice-candidates + :action (helm-make-actions "Toggle Enable/Disable" 'helm-advice-toggle) + :persistent-action 'helm-advice-persistent-action + :nomark t + :multiline t + :persistent-help "Toggle describe function / C-u C-j: Toggle advice")) + +(defun helm-advice-candidates () + (cl-loop for (fname) in ad-advised-functions + for function = (intern fname) + append + (cl-loop for class in ad-advice-classes append + (cl-loop for advice in (ad-get-advice-info-field function class) + for enabled = (ad-advice-enabled advice) + collect + (cons (format + "%s %s %s" + (if enabled "Enabled " "Disabled") + (propertize fname 'face 'font-lock-function-name-face) + (ad-make-single-advice-docstring advice class nil)) + (list function class advice)))))) + +(defun helm-advice-persistent-action (func-class-advice) + (if current-prefix-arg + (helm-advice-toggle func-class-advice) + (describe-function (car func-class-advice)))) + +(defun helm-advice-toggle (func-class-advice) + (cl-destructuring-bind (function _class advice) func-class-advice + (cond ((ad-advice-enabled advice) + (ad-advice-set-enabled advice nil) + (message "Disabled")) + (t + (ad-advice-set-enabled advice t) + (message "Enabled"))) + (ad-activate function) + (and helm-in-persistent-action + (helm-advice-update-current-display-string)))) + +(defun helm-advice-update-current-display-string () + (helm-edit-current-selection + (let ((newword (cond ((looking-at "Disabled") "Enabled") + ((looking-at "Enabled") "Disabled")))) + (when newword + (delete-region (point) (progn (forward-word 1) (point))) + (insert newword))))) + +;;;###autoload +(defun helm-manage-advice () + "Preconfigured `helm' to disable/enable function advices." + (interactive) + (helm-other-buffer 'helm-source-advice "*helm advice*")) + + +;;; Locate elisp library +;; +;; +(defun helm-locate-library-scan-list () + (cl-loop for dir in load-path + with load-suffixes = '(".el") + when (file-directory-p dir) + append (directory-files + dir t (concat (regexp-opt (get-load-suffixes)) + "\\'")))) + +;;;###autoload +(defun helm-locate-library () + "Preconfigured helm to locate elisp libraries." + (interactive) + (helm :sources (helm-build-in-buffer-source "Elisp libraries (Scan)" + :data #'helm-locate-library-scan-list + :fuzzy-match helm-locate-library-fuzzy-match + :keymap helm-generic-files-map + :search (unless helm-locate-library-fuzzy-match + (lambda (regexp) + (re-search-forward + (if helm-ff-transformer-show-only-basename + (replace-regexp-in-string + "\\`\\^" "" regexp) + regexp) + nil t))) + :match-part (lambda (candidate) + (if helm-ff-transformer-show-only-basename + (helm-basename candidate) candidate)) + :filter-one-by-one (lambda (c) + (if helm-ff-transformer-show-only-basename + (cons (helm-basename c) c) c)) + :action (helm-actions-from-type-file)) + :ff-transformer-show-only-basename nil + :buffer "*helm locate library*")) + +(defun helm-set-variable (var) + "Set value to VAR interactively." + (let* ((sym (helm-symbolify var)) + (val (default-value sym))) + (set-default sym (eval-minibuffer (format "Set `%s': " var) + (if (or (stringp val) (memq val '(nil t))) + (prin1-to-string val) + (format "'%s" (prin1-to-string val))))))) + + +;;; Elisp Timers. +;; +;; +(defclass helm-absolute-time-timers-class (helm-source-sync helm-type-timers) + ((candidates :initform timer-list) + (allow-dups :initform t) + (candidate-transformer + :initform + (lambda (candidates) + (cl-loop for timer in candidates + collect (cons (helm-elisp--format-timer timer) timer)))))) + +(defvar helm-source-absolute-time-timers + (helm-make-source "Absolute Time Timers" 'helm-absolute-time-timers-class)) + +(defclass helm-idle-time-timers-class (helm-source-sync helm-type-timers) + ((candidates :initform timer-idle-list) + (allow-dups :initform t) + (candidate-transformer + :initform + (lambda (candidates) + (cl-loop for timer in candidates + collect (cons (helm-elisp--format-timer timer) timer)))))) + +(defvar helm-source-idle-time-timers + (helm-make-source "Idle Time Timers" 'helm-idle-time-timers-class)) + +(defun helm-elisp--format-timer (timer) + (format "%s repeat=%s %s(%s)" + (let ((time (timer--time timer))) + (if (timer--idle-delay timer) + (format-time-string "idle-for=%5s" time) + (format-time-string "%m/%d %T" time))) + (or (timer--repeat-delay timer) "nil") + (mapconcat 'identity (split-string + (prin1-to-string (timer--function timer)) + "\n") " ") + (mapconcat 'prin1-to-string (timer--args timer) " "))) + +;;;###autoload +(defun helm-timers () + "Preconfigured `helm' for timers." + (interactive) + (helm :sources '(helm-source-absolute-time-timers + helm-source-idle-time-timers) + :buffer "*helm timers*")) + + +;;; Complex command history +;; +;; +(defun helm-btf--usable-p () + "Return t if current version of `backtrace-frame' accept 2 arguments." + (condition-case nil + (progn (backtrace-frame 1 'condition-case) t) + (wrong-number-of-arguments nil))) + +(if (helm-btf--usable-p) ; Check if BTF accept more than one arg. + ;; Emacs 24.4. + (dont-compile + (defvar helm-sexp--last-sexp nil) + ;; This wont work compiled. + (defun helm-sexp-eval-1 () + (interactive) + (unwind-protect + (progn + ;; Trick called-interactively-p into thinking that `cand' is + ;; an interactive call, See `repeat-complex-command'. + (add-hook 'called-interactively-p-functions + #'helm-complex-command-history--called-interactively-skip) + (eval (read helm-sexp--last-sexp))) + (remove-hook 'called-interactively-p-functions + #'helm-complex-command-history--called-interactively-skip))) + + (defun helm-complex-command-history--called-interactively-skip (i _frame1 frame2) + (and (eq 'eval (cadr frame2)) + (eq 'helm-sexp-eval-1 + (cadr (backtrace-frame (+ i 2) #'called-interactively-p))) + 1)) + + (defun helm-sexp-eval (_candidate) + (call-interactively #'helm-sexp-eval-1))) + ;; Emacs 24.3 + (defun helm-sexp-eval (cand) + (let ((sexp (read cand))) + (condition-case err + (if (> (length (remove nil sexp)) 1) + (eval sexp) + (apply 'call-interactively sexp)) + (error (message "Evaluating gave an error: %S" err) + nil))))) + +(defvar helm-source-complex-command-history + (helm-build-sync-source "Complex Command History" + :candidates (lambda () + ;; Use cdr to avoid adding + ;; `helm-complex-command-history' here. + (cl-loop for i in command-history + unless (equal i '(helm-complex-command-history)) + collect (prin1-to-string i))) + :action (helm-make-actions + "Eval" (lambda (candidate) + (and (boundp 'helm-sexp--last-sexp) + (setq helm-sexp--last-sexp candidate)) + (let ((command (read candidate))) + (unless (equal command (car command-history)) + (setq command-history (cons command command-history)))) + (run-with-timer 0.1 nil #'helm-sexp-eval candidate)) + "Edit and eval" (lambda (candidate) + (edit-and-eval-command "Eval: " (read candidate)))) + :persistent-action #'helm-sexp-eval + :multiline t)) + +;;;###autoload +(defun helm-complex-command-history () + "Preconfigured helm for complex command history." + (interactive) + (helm :sources 'helm-source-complex-command-history + :buffer "*helm complex commands*")) + +(provide 'helm-elisp) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-elisp.el ends here diff --git a/elpa/helm-20181113.923/helm-eshell.el b/elpa/helm-20181113.923/helm-eshell.el new file mode 100644 index 00000000..66e81d75 --- /dev/null +++ b/elpa/helm-20181113.923/helm-eshell.el @@ -0,0 +1,487 @@ +;;; helm-eshell.el --- pcomplete and eshell completion for helm. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Commentary: +;; +;; Enable like this in .emacs: +;; (add-hook 'eshell-mode-hook +;; (lambda () +;; (eshell-cmpl-initialize) +;; (define-key eshell-mode-map [remap eshell-pcomplete] 'helm-esh-pcomplete) +;; (define-key eshell-mode-map (kbd "M-s f") 'helm-eshell-prompts-all))) +;; (define-key eshell-mode-map (kbd "M-r") 'helm-eshell-history))) + + +;;; Code: +(require 'cl-lib) +(require 'helm) +(require 'helm-lib) +(require 'helm-help) +(require 'helm-elisp) + +(declare-function eshell-read-aliases-list "em-alias") +(declare-function eshell-send-input "esh-mode" (&optional use-region queue-p no-newline)) +(declare-function eshell-bol "esh-mode") +(declare-function eshell-parse-arguments "esh-arg" (beg end)) +(declare-function eshell-backward-argument "esh-mode" (&optional arg)) +(declare-function helm-quote-whitespace "helm-lib") +(declare-function eshell-skip-prompt "em-prompt") +(defvar eshell-special-chars-outside-quoting) + + +(defgroup helm-eshell nil + "Helm eshell completion and history." + :group 'helm) + + +(defcustom helm-eshell-fuzzy-match nil + "Enable fuzzy matching in `helm-esh-pcomplete' when non--nil." + :group 'helm-eshell + :type 'boolean) + + +(defvar helm-eshell-history-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-p") 'helm-next-line) + map) + "Keymap for `helm-eshell-history'.") + +(defvar helm-esh-completion-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "TAB") 'helm-next-line) + map) + "Keymap for `helm-esh-pcomplete'.") + +(defvar helm-eshell--quit-flag nil) + + +(defclass helm-esh-source (helm-source-sync) + ((init :initform (lambda () + (setq pcomplete-current-completions nil + pcomplete-last-completion-raw nil) + ;; Eshell-command add this hook in all minibuffers + ;; Remove it for the helm one. (Fixed in Emacs24) + (remove-hook 'minibuffer-setup-hook 'eshell-mode))) + (candidates :initform 'helm-esh-get-candidates) + ;(nomark :initform t) + (persistent-action :initform 'ignore) + (nohighlight :initform t) + (filtered-candidate-transformer + :initform + (lambda (candidates _sources) + (cl-loop + for i in candidates + collect + (cond ((string-match "\\`~/?" helm-ec-target) + (abbreviate-file-name i)) + ((string-match "\\`/" helm-ec-target) i) + (t + (file-relative-name i))) + into lst + finally return (sort lst 'helm-generic-sort-fn)))) + (action :initform 'helm-ec-insert)) + "Helm class to define source for Eshell completion.") + +;; Internal. +(defvar helm-ec-target "") +(defun helm-ec-insert (_candidate) + "Replace text at point with CANDIDATE. +The function that call this should set `helm-ec-target' to thing at point." + (set (make-local-variable 'comint-file-name-quote-list) + eshell-special-chars-outside-quoting) + (let ((pt (point))) + (when (and helm-ec-target + (search-backward helm-ec-target nil t) + (string= (buffer-substring (point) pt) helm-ec-target)) + (delete-region (point) pt))) + (when (string-match "\\`\\*" helm-ec-target) (insert "*")) + (let ((marked (helm-marked-candidates))) + (prog1 t ;; Makes helm returns t on action. + (insert + (mapconcat + (lambda (x) + (cond ((string-match "\\`~/" helm-ec-target) + ;; Strip out the first escape char added by + ;; `comint-quote-filename' before "~" (Issue #1803). + (substring (comint-quote-filename (abbreviate-file-name x)) 1)) + ((string-match "\\`/" helm-ec-target) + (comint-quote-filename x)) + (t + (concat (and (string-match "\\`[.]/" helm-ec-target) "./") + (comint-quote-filename + (file-relative-name x)))))) + marked " ") + (or (helm-aand (car (last marked)) + (string-match-p "/\\'" it) + "") + " "))))) + +(defun helm-esh-get-candidates () + "Get candidates for eshell completion using `pcomplete'." + (catch 'pcompleted + (with-helm-current-buffer + (let* ((pcomplete-stub) + pcomplete-seen pcomplete-norm-func + pcomplete-args pcomplete-last pcomplete-index + (pcomplete-autolist pcomplete-autolist) + (pcomplete-suffix-list pcomplete-suffix-list) + (table (pcomplete-completions)) + (entry (or (try-completion helm-pattern + (pcomplete-entries)) + helm-pattern))) + (cl-loop ;; expand entry too to be able to compare it with file-cand. + with exp-entry = (and (stringp entry) + (not (string= entry "")) + (file-name-as-directory + (expand-file-name entry default-directory))) + with comps = (all-completions pcomplete-stub table) + unless comps return (prog1 nil + ;; Don't add final space when + ;; there is no completion (issue #1990). + (setq helm-eshell--quit-flag t) + (message "No completions of %s" pcomplete-stub)) + for i in comps + ;; Transform the related names to abs names. + for file-cand = (and exp-entry + (if (file-remote-p i) i + (expand-file-name + i (file-name-directory entry)))) + ;; Compare them to avoid dups. + for file-entry-p = (and (stringp exp-entry) + (stringp file-cand) + ;; Fix :/tmp/foo/ $ cd foo + (not (file-directory-p file-cand)) + (file-equal-p exp-entry file-cand)) + if (and file-cand (or (file-remote-p file-cand) + (file-exists-p file-cand)) + (not file-entry-p)) + collect file-cand into ls + else + ;; Avoid adding entry here. + unless file-entry-p collect i into ls + finally return + (if (and exp-entry + (file-directory-p exp-entry) + ;; If the car of completion list is + ;; an executable, probably we are in + ;; command completion, so don't add a + ;; possible file related entry here. + (and ls (not (executable-find (car ls)))) + ;; Don't add entry if already in prompt. + (not (file-equal-p exp-entry pcomplete-stub))) + (append (list exp-entry) + ;; Entry should not be here now but double check. + (remove entry ls)) + ls)))))) + +;;; Eshell history. +;; +;; +(defclass helm-eshell-history-source (helm-source-sync) + ((init :initform + (lambda () + ;; Same comment as in `helm-source-esh'. + (remove-hook 'minibuffer-setup-hook 'eshell-mode))) + (candidates + :initform + (lambda () + (with-helm-current-buffer + (cl-loop for c from 0 to (ring-length eshell-history-ring) + collect (eshell-get-history c))))) + (nomark :initform t) + (multiline :initform t) + (keymap :initform helm-eshell-history-map) + (candidate-number-limit :initform 9999) + (action :initform (lambda (candidate) + (eshell-kill-input) + (insert candidate)))) + "Helm class to define source for Eshell history.") + + +;;;###autoload +(defun helm-esh-pcomplete () + "Preconfigured helm to provide helm completion in eshell." + (interactive) + (let* ((helm-quit-if-no-candidate t) + (helm-execute-action-at-once-if-one t) + (end (point-marker)) + (beg (save-excursion (eshell-bol) (point))) + (args (catch 'eshell-incomplete + (eshell-parse-arguments beg end))) + (target + (or (and (looking-back " " (1- (point))) " ") + (buffer-substring-no-properties + (save-excursion + (eshell-backward-argument 1) (point)) + end))) + (users-comp (string= target "~")) + (first (car args)) ; Maybe lisp delimiter "(". + last ; Will be the last but parsed by pcomplete. + del-space + del-dot) + (setq helm-ec-target (or target " ") + end (point) + ;; Reset beg for `with-helm-show-completion'. + beg (or (and target (not (string= target " ")) + (- end (length target))) + ;; Nothing at point. + (progn (insert " ") (setq del-space t) (point)))) + (when (string-match "\\`[~.]*.*/[.]\\'" target) + ;; Fix completion on + ;; "~/.", "~/[...]/.", and "../." + (delete-char -1) (setq del-dot t) + (setq helm-ec-target (substring helm-ec-target 0 (1- (length helm-ec-target))))) + (cond ((eq first ?\() + (helm-lisp-completion-or-file-name-at-point)) + ;; In eshell `pcomplete-parse-arguments' is called + ;; with `pcomplete-parse-arguments-function' + ;; locally bound to `eshell-complete-parse-arguments' + ;; which is calling `lisp-complete-symbol', + ;; calling it before would popup the + ;; *completions* buffer. + (t (setq last (replace-regexp-in-string + "\\`\\*" "" + (car (last (ignore-errors + (pcomplete-parse-arguments)))))) + ;; Set helm-eshell--quit-flag to non-nil only on + ;; quit, this tells to not add final suffix when quitting + ;; helm. + (add-hook 'helm-quit-hook 'helm-eshell--quit-hook-fn) + (with-helm-show-completion beg end + (unwind-protect + (or (helm :sources (helm-make-source "Eshell completions" 'helm-esh-source + :fuzzy-match helm-eshell-fuzzy-match) + :buffer "*helm pcomplete*" + :keymap helm-esh-completion-map + :resume 'noresume + :input (if (and (stringp last) + (not (string= last "")) + (not users-comp) + ;; Fix completion on + ;; "../" see #1832. + (or (file-exists-p last) + (helm-aand + (file-name-directory last) + (file-directory-p it)))) + (if (and (file-directory-p last) + (string-match "\\`[~.]*.*/[.]\\'" target)) + ;; Fix completion on + ;; "~/.", "~/[...]/.", and "../." + (expand-file-name + (concat (helm-basedir (file-name-as-directory last)) + (regexp-quote (helm-basename target)))) + (expand-file-name last)) + ;; Don't add "~" to input to + ;; provide completion on all + ;; users instead of only on + ;; current $HOME (#1832). + (unless users-comp last))) + ;; Delete removed dot on quit + (and del-dot (prog1 t (insert "."))) + ;; A space is needed to have completion, remove + ;; it when nothing found. + (and del-space (looking-back "\\s-" (1- (point))) + (delete-char -1)) + (if (and (null helm-eshell--quit-flag) + (and (stringp last) (file-directory-p last)) + (looking-back "\\([.]\\{1,2\\}\\|[^/]\\)\\'" + (1- (point)))) + (prog1 t (insert "/")) + ;; We need another flag for space here, but + ;; global to pass it to `helm-quit-hook', this + ;; space is added when point is just after + ;; previous completion and there is no + ;; more completion, see issue #1832. + (unless (or helm-eshell--quit-flag + (looking-back "/\\'" (1- (point)))) + (prog1 t (insert " "))) + (when (and helm-eshell--quit-flag + (string-match-p "[.]\\{2\\}\\'" last)) + (insert "/")))) + (remove-hook 'helm-quit-hook 'helm-eshell--quit-hook-fn) + (setq helm-eshell--quit-flag nil))))))) + +(defun helm-eshell--quit-hook-fn () + (setq helm-eshell--quit-flag t)) + +;;;###autoload +(defun helm-eshell-history () + "Preconfigured helm for eshell history." + (interactive) + (let* ((end (point)) + (beg (save-excursion (eshell-bol) (point))) + (input (buffer-substring beg end)) + flag-empty) + (when (eq beg end) + (insert " ") + (setq flag-empty t) + (setq end (point))) + (unwind-protect + (with-helm-show-completion beg end + (helm :sources (helm-make-source "Eshell history" + 'helm-eshell-history-source) + :buffer "*helm eshell history*" + :resume 'noresume + :input input)) + (when (and flag-empty + (looking-back " " (1- (point)))) + (delete-char -1))))) + + +;;; Eshell prompts +;; +(defface helm-eshell-prompts-promptidx + '((t (:foreground "cyan"))) + "Face used to highlight Eshell prompt index." + :group 'helm-eshell-faces) + +(defface helm-eshell-prompts-buffer-name + '((t (:foreground "green"))) + "Face used to highlight Eshell buffer name." + :group 'helm-eshell-faces) + +(defcustom helm-eshell-prompts-promptidx-p t + "Show prompt number." + :group 'helm-eshell + :type 'boolean) + +(defvar helm-eshell-prompts-keymap + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "C-c o") 'helm-eshell-prompts-other-window) + (define-key map (kbd "C-c C-o") 'helm-eshell-prompts-other-frame) + map) + "Keymap for `helm-eshell-prompt-all'.") + +(defvar eshell-prompt-regexp) +(defvar eshell-highlight-prompt) + +(defun helm-eshell-prompts-list (&optional buffer) + "List the prompts in Eshell BUFFER. + +Return a list of (\"prompt\" (point) (buffer-name) prompt-index)) +e.g. (\"ls\" 162 \"*eshell*\" 3). +If BUFFER is nil, use current buffer." + (with-current-buffer (or buffer (current-buffer)) + (when (eq major-mode 'eshell-mode) + (save-excursion + (goto-char (point-min)) + (let (result (count 1)) + (helm-awhile (re-search-forward eshell-prompt-regexp nil t) + (when (or (and eshell-highlight-prompt + (get-text-property (match-beginning 0) 'read-only)) + (null eshell-highlight-prompt)) + (push (list (buffer-substring-no-properties + it (point-at-eol)) + it (buffer-name) count) + result) + (setq count (1+ count)))) + (nreverse result)))))) + +(defun helm-eshell-prompts-list-all () + "List the prompts of all Eshell buffers. +See `helm-eshell-prompts-list'." + (cl-loop for b in (buffer-list) + append (helm-eshell-prompts-list b))) + +(defun helm-eshell-prompts-transformer (candidates &optional all) + ;; ("ls" 162 "*eshell*" 3) => ("*eshell*:3:ls" . ("ls" 162 "*eshell*" 3)) + (cl-loop for (prt pos buf id) in candidates + collect `(,(concat + (when all + (concat (propertize + buf + 'face 'helm-eshell-prompts-buffer-name) + ":")) + (when helm-eshell-prompts-promptidx-p + (concat (propertize + (number-to-string id) + 'face 'helm-eshell-prompts-promptidx) + ":")) + prt) + . ,(list prt pos buf id)))) + +(defun helm-eshell-prompts-all-transformer (candidates) + (helm-eshell-prompts-transformer candidates t)) + +(cl-defun helm-eshell-prompts-goto (candidate &optional (action 'switch-to-buffer)) + ;; Candidate format: ("ls" 162 "*eshell*" 3) + (let ((buf (nth 2 candidate))) + (unless (and (string= (buffer-name) buf) + (eq action 'switch-to-buffer)) + (funcall action buf)) + (goto-char (nth 1 candidate)) + (recenter))) + +(defun helm-eshell-prompts-goto-other-window (candidate) + (helm-eshell-prompts-goto candidate 'switch-to-buffer-other-window)) + +(defun helm-eshell-prompts-goto-other-frame (candidate) + (helm-eshell-prompts-goto candidate 'switch-to-buffer-other-frame)) + +(defun helm-eshell-prompts-other-window () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-eshell-prompts-goto-other-window))) +(put 'helm-eshell-prompts-other-window 'helm-only t) + +(defun helm-eshell-prompts-other-frame () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-eshell-prompts-goto-other-frame))) +(put 'helm-eshell-prompts-other-frame 'helm-only t) + +;;;###autoload +(defun helm-eshell-prompts () + "Pre-configured `helm' to browse the prompts of the current Eshell." + (interactive) + (if (eq major-mode 'eshell-mode) + (helm :sources + (helm-build-sync-source "Eshell prompts" + :candidates (helm-eshell-prompts-list) + :candidate-transformer 'helm-eshell-prompts-transformer + :action '(("Go to prompt" . helm-eshell-prompts-goto))) + :buffer "*helm Eshell prompts*") + (message "Current buffer is not an Eshell buffer"))) + +;;;###autoload +(defun helm-eshell-prompts-all () + "Pre-configured `helm' to browse the prompts of all Eshell sessions." + (interactive) + (helm :sources + (helm-build-sync-source "All Eshell prompts" + :candidates (helm-eshell-prompts-list-all) + :candidate-transformer 'helm-eshell-prompts-all-transformer + :action '(("Go to prompt" . helm-eshell-prompts-goto) + ("Go to prompt in other window `C-c o`" . + helm-eshell-prompts-goto-other-window) + ("Go to prompt in other frame `C-c C-o`" . + helm-eshell-prompts-goto-other-frame)) + :keymap helm-eshell-prompts-keymap) + :buffer "*helm Eshell all prompts*")) + +(provide 'helm-eshell) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-eshell ends here diff --git a/elpa/helm-20181113.923/helm-eval.el b/elpa/helm-20181113.923/helm-eval.el new file mode 100644 index 00000000..06ffd081 --- /dev/null +++ b/elpa/helm-20181113.923/helm-eval.el @@ -0,0 +1,204 @@ +;;; helm-eval.el --- eval expressions from helm. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'eldoc) +(require 'edebug) + + +(defgroup helm-eval nil + "Eval related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-eldoc-in-minibuffer-show-fn + 'helm-show-info-in-mode-line + "A function to display eldoc info. +Should take one arg: the string to display." + :group 'helm-eval + :type 'symbol) + +(defcustom helm-show-info-in-mode-line-delay 12 + "Eldoc will show info in mode-line during this delay if user is idle." + :type 'integer + :group 'helm-eval) + + +;;; Eldoc compatibility between emacs-24 and emacs-25 +;; +(if (require 'elisp-mode nil t) ; emacs-25 + ;; Maybe the eldoc functions have been + ;; already aliased by eldoc-eval. + (cl-loop for (f . a) in '((eldoc-current-symbol . + elisp--current-symbol) + (eldoc-fnsym-in-current-sexp . + elisp--fnsym-in-current-sexp) + (eldoc-get-fnsym-args-string . + elisp-get-fnsym-args-string) + (eldoc-get-var-docstring . + elisp-get-var-docstring)) + unless (fboundp f) + do (defalias f a)) + ;; Emacs-24. + (declare-function eldoc-current-symbol "eldoc") + (declare-function eldoc-get-fnsym-args-string "eldoc" (sym &optional index)) + (declare-function eldoc-get-var-docstring "eldoc" (sym)) + (declare-function eldoc-fnsym-in-current-sexp "eldoc")) + +;;; Evaluation Result +;; +;; +;; Internal +(defvar helm-eldoc-active-minibuffers-list nil) + +(defvar helm-eval-expression-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "") 'helm-eval-new-line-and-indent) + (define-key map (kbd "") 'lisp-indent-line) + (define-key map (kbd "") 'helm-lisp-completion-at-point) + (define-key map (kbd "C-p") 'previous-line) + (define-key map (kbd "C-n") 'next-line) + (define-key map (kbd "") 'previous-line) + (define-key map (kbd "") 'next-line) + (define-key map (kbd "") 'forward-char) + (define-key map (kbd "") 'backward-char) + map)) + +(defun helm-build-evaluation-result-source () + (helm-build-dummy-source "Evaluation Result" + :multiline t + :mode-line "C-RET: nl-and-indent, M-tab: reindent, C-tab:complete, C-p/n: next/prec-line." + :filtered-candidate-transformer (lambda (_candidates _source) + (list + (condition-case nil + (with-helm-current-buffer + (pp-to-string + (if edebug-active + (edebug-eval-expression + (read helm-pattern)) + (eval (read helm-pattern))))) + (error "Error")))) + :nohighlight t + :keymap helm-eval-expression-map + :action '(("Copy result to kill-ring" . (lambda (candidate) + (kill-new + (replace-regexp-in-string + "\n" "" candidate)) + (message "Result copied to kill-ring"))) + ("copy sexp to kill-ring" . (lambda (_candidate) + (kill-new helm-input) + (message "Sexp copied to kill-ring")))))) + +(defun helm-eval-new-line-and-indent () + (interactive) + (newline) (lisp-indent-line)) + +(defun helm-eldoc-store-minibuffer () + "Store minibuffer buffer name in `helm-eldoc-active-minibuffers-list'." + (with-selected-window (minibuffer-window) + (push (current-buffer) helm-eldoc-active-minibuffers-list))) + +(defun helm-eldoc-show-in-eval () + "Return eldoc in mode-line for current minibuffer input." + (let ((buf (window-buffer (active-minibuffer-window)))) + (condition-case err + (when (member buf helm-eldoc-active-minibuffers-list) + (with-current-buffer buf + (let* ((sym (save-excursion + (unless (looking-back ")\\|\"" (1- (point))) + (forward-char -1)) + (eldoc-current-symbol))) + (info-fn (eldoc-fnsym-in-current-sexp)) + (doc (or (eldoc-get-var-docstring sym) + (eldoc-get-fnsym-args-string + (car info-fn) (cadr info-fn))))) + (when doc (funcall helm-eldoc-in-minibuffer-show-fn doc))))) + (error (message "Eldoc in minibuffer error: %S" err) nil)))) + +(defun helm-show-info-in-mode-line (str) + "Display string STR in mode-line." + (save-selected-window + (with-current-buffer helm-buffer + (let ((mode-line-format (concat " " str))) + (force-mode-line-update) + (sit-for helm-show-info-in-mode-line-delay)) + (force-mode-line-update)))) + +;;; Calculation Result +;; +;; +(defvar helm-source-calculation-result + (helm-build-dummy-source "Calculation Result" + :filtered-candidate-transformer (lambda (_candidates _source) + (list + (condition-case nil + (calc-eval helm-pattern) + (error "error")))) + :nohighlight t + :action '(("Copy result to kill-ring" . (lambda (candidate) + (kill-new candidate) + (message "Result \"%s\" copied to kill-ring" + candidate))) + ("Copy operation to kill-ring" . (lambda (_candidate) + (kill-new helm-input) + (message "Calculation copied to kill-ring")))))) + +;;;###autoload +(defun helm-eval-expression (arg) + "Preconfigured helm for `helm-source-evaluation-result'." + (interactive "P") + (helm :sources (helm-build-evaluation-result-source) + :input (when arg (thing-at-point 'sexp)) + :buffer "*helm eval*" + :echo-input-in-header-line nil + :history 'read-expression-history)) + +(defvar eldoc-idle-delay) +;;;###autoload +(defun helm-eval-expression-with-eldoc () + "Preconfigured helm for `helm-source-evaluation-result' with `eldoc' support. " + (interactive) + (let ((timer (run-with-idle-timer + eldoc-idle-delay 'repeat + 'helm-eldoc-show-in-eval))) + (unwind-protect + (minibuffer-with-setup-hook + 'helm-eldoc-store-minibuffer + (call-interactively 'helm-eval-expression)) + (and timer (cancel-timer timer)) + (setq helm-eldoc-active-minibuffers-list + (cdr helm-eldoc-active-minibuffers-list))))) + +;;;###autoload +(defun helm-calcul-expression () + "Preconfigured helm for `helm-source-calculation-result'." + (interactive) + (helm :sources 'helm-source-calculation-result + :buffer "*helm calcul*")) + +(provide 'helm-eval) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-eval.el ends here diff --git a/elpa/helm-20181113.923/helm-external.el b/elpa/helm-20181113.923/helm-external.el new file mode 100644 index 00000000..5c9015ca --- /dev/null +++ b/elpa/helm-20181113.923/helm-external.el @@ -0,0 +1,213 @@ +;;; helm-external.el --- Run Externals commands within Emacs with helm completion. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'helm-net) + + +(defgroup helm-external nil + "External related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-raise-command nil + "A shell command to jump to a window running specific program. +Need external program wmctrl. +This will be use with `format', so use something like \"wmctrl -xa %s\"." + :type 'string + :group 'helm-external) + +(defcustom helm-external-programs-associations nil + "Alist to store externals programs associated with file extension. +This variable overhide setting in .mailcap file. +e.g : '\(\(\"jpg\" . \"gqview\"\) (\"pdf\" . \"xpdf\"\)\) " + :type '(alist :key-type string :value-type string) + :group 'helm-external) + +(defcustom helm-default-external-file-browser "nautilus" + "Default external file browser for your system. +Directories will be opened externally with it when +opening file externally in `helm-find-files'. +Set to nil if you do not have external file browser +or do not want to use it. +Windows users should set that to \"explorer.exe\"." + :group 'helm-external + :type 'string) + + +;;; Internals +(defvar helm-external-command-history nil) +(defvar helm-external-commands-list nil + "A list of all external commands the user can execute. +If this variable is not set by the user, it will be calculated +automatically.") + +(defun helm-external-commands-list-1 (&optional sort) + "Returns a list of all external commands the user can execute. +If `helm-external-commands-list' is non-nil it will +return its contents. Else it calculates all external commands +and sets `helm-external-commands-list'." + (helm-aif helm-external-commands-list + it + (setq helm-external-commands-list + (cl-loop + for dir in (split-string (getenv "PATH") path-separator) + when (and (file-exists-p dir) (file-accessible-directory-p dir)) + for lsdir = (cl-loop for i in (directory-files dir t) + for bn = (file-name-nondirectory i) + when (and (not (member bn completions)) + (not (file-directory-p i)) + (file-executable-p i)) + collect bn) + append lsdir into completions + finally return + (if sort (sort completions 'string-lessp) completions))))) + +(defun helm-run-or-raise (exe &optional file) + "Run asynchronously EXE or jump to the application window. +If EXE is already running just jump to his window if `helm-raise-command' +is non--nil. +When FILE argument is provided run EXE with FILE." + (let* ((real-com (car (split-string exe))) + (proc (if file (concat real-com " " file) real-com)) + process-connection-type) + (if (get-process proc) + (if helm-raise-command + (shell-command (format helm-raise-command real-com)) + (error "Error: %s is already running" real-com)) + (when (member real-com helm-external-commands-list) + (message "Starting %s..." real-com) + (if file + (start-process-shell-command + proc nil (format "%s %s" + real-com + (shell-quote-argument + (if (eq system-type 'windows-nt) + (helm-w32-prepare-filename file) + (expand-file-name file))))) + (start-process-shell-command proc nil real-com)) + (set-process-sentinel + (get-process proc) + (lambda (process event) + (when (and (string= event "finished\n") + helm-raise-command + (not (helm-get-pid-from-process-name real-com))) + (shell-command (format helm-raise-command "emacs"))) + (message "%s process...Finished." process)))) + (setq helm-external-commands-list + (cons real-com + (delete real-com helm-external-commands-list)))))) + +(defun helm-get-mailcap-for-file (filename) + "Get the command to use for FILENAME from mailcap files." + (mailcap-parse-mailcaps) + (let* ((ext (file-name-extension filename)) + (mime (when ext (mailcap-extension-to-mime ext))) + (result (when mime (mailcap-mime-info mime)))) + ;; If elisp file have no associations in .mailcap + ;; `mailcap-maybe-eval' is returned, in this case just return nil. + (when (stringp result) (helm-basename result)))) + +(defun helm-get-default-program-for-file (filename) + "Try to find a default program to open FILENAME. +Try first in `helm-external-programs-associations' and then in mailcap file +if nothing found return nil." + (let* ((ext (file-name-extension filename)) + (def-prog (assoc-default ext helm-external-programs-associations))) + (cond ((and def-prog (not (string= def-prog ""))) def-prog) + ((and helm-default-external-file-browser (file-directory-p filename)) + helm-default-external-file-browser) + (t (helm-get-mailcap-for-file filename))))) + +(defun helm-open-file-externally (file) + "Open FILE with an external program. +Try to guess which program to use with `helm-get-default-program-for-file'. +If not found or a prefix arg is given query the user which tool to use." + (let* ((fname (expand-file-name file)) + (collection (helm-external-commands-list-1 'sort)) + (def-prog (helm-get-default-program-for-file fname)) + (program (if (or helm-current-prefix-arg (not def-prog)) + ;; Prefix arg or no default program. + (prog1 + (helm-comp-read + "Program: " collection + :must-match t + :name "Open file Externally" + :del-input nil + :history helm-external-command-history) + ;; Always prompt to set this program as default. + (setq def-prog nil)) + ;; No prefix arg or default program exists. + def-prog))) + (unless (or def-prog ; Association exists, no need to record it. + ;; Don't try to record non--filenames associations (e.g urls). + (not (file-exists-p fname))) + (when + (y-or-n-p + (format + "Do you want to make `%s' the default program for this kind of files? " + program)) + (helm-aif (assoc (file-name-extension fname) + helm-external-programs-associations) + (setq helm-external-programs-associations + (delete it helm-external-programs-associations))) + (push (cons (file-name-extension fname) + (helm-read-string + "Program (Add args maybe and confirm): " program)) + helm-external-programs-associations) + (customize-save-variable 'helm-external-programs-associations + helm-external-programs-associations))) + (helm-run-or-raise program file) + (setq helm-external-command-history + (cons program + (delete program + (cl-loop for i in helm-external-command-history + when (executable-find i) collect i)))))) + +;;;###autoload +(defun helm-run-external-command (program) + "Preconfigured `helm' to run External PROGRAM asyncronously from Emacs. +If program is already running exit with error. +You can set your own list of commands with +`helm-external-commands-list'." + (interactive (list + (helm-comp-read + "RunProgram: " + (helm-external-commands-list-1 'sort) + :must-match t + :del-input nil + :name "External Commands" + :history helm-external-command-history))) + (helm-run-or-raise program) + (setq helm-external-command-history + (cons program (delete program + (cl-loop for i in helm-external-command-history + when (executable-find i) collect i))))) + + +(provide 'helm-external) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-external ends here diff --git a/elpa/helm-20181113.923/helm-files.el b/elpa/helm-20181113.923/helm-files.el new file mode 100644 index 00000000..93101abd --- /dev/null +++ b/elpa/helm-20181113.923/helm-files.el @@ -0,0 +1,4476 @@ +;;; helm-files.el --- helm file browser and related. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-types) +(require 'helm-utils) +(require 'helm-grep) +(require 'helm-help) +(require 'helm-locate) +(require 'helm-tags) +(require 'helm-buffers) +(eval-when-compile + (require 'thingatpt) + (require 'ffap) + (require 'dired-aux) + (require 'dired-x) + (require 'tramp) + (require 'image-dired)) + +(declare-function find-library-name "find-func.el" (library)) +(declare-function w32-shell-execute "ext:w32fns.c" (operation document &optional parameters show-flag)) +(declare-function gnus-dired-attach "ext:gnus-dired.el" (files-to-attach)) +(declare-function image-dired-display-image "image-dired.el" (file &optional original-size)) +(declare-function image-dired-update-property "image-dired.el" (prop value)) +(declare-function eshell-read-aliases-list "em-alias") +(declare-function eshell-send-input "esh-mode" (&optional use-region queue-p no-newline)) +(declare-function eshell-kill-input "esh-mode") +(declare-function eshell-bol "esh-mode") +(declare-function eshell-reset "esh-mode.el") +(declare-function eshell/cd "em-dirs.el") +(declare-function eshell-next-prompt "em-prompt.el") +(declare-function eshell-quote-argument "esh-arg.el") +(declare-function helm-ls-git-ls "ext:helm-ls-git") +(declare-function helm-hg-find-files-in-project "ext:helm-ls-hg") +(declare-function helm-gid "helm-id-utils.el") +(declare-function helm-find-1 "helm-find") +(declare-function helm-get-default-program-for-file "helm-external") +(declare-function helm-open-file-externally "helm-external") + +(defvar recentf-list) +(defvar helm-mm-matching-method) +(defvar dired-async-mode) +(defvar org-directory) + +(defgroup helm-files nil + "Files applications and libraries for Helm." + :group 'helm) + +(defcustom helm-tramp-verbose 0 + "Just like `tramp-verbose' but specific to helm. +When set to 0 don't show tramp messages in helm. +If you want to have the default tramp messages set it to 3." + :type 'integer + :group 'helm-files) + +(defcustom helm-ff-auto-update-initial-value nil + "Auto update when only one candidate directory is matched. +Default value when starting `helm-find-files' is nil because +it prevent using to delete char backward and by the way +confuse beginners. +For a better experience with `helm-find-files' set this to non--nil +and use C- to toggle it." + :group 'helm-files + :type 'boolean) + +(defcustom helm-ff-lynx-style-map t + "Use arrow keys to navigate with `helm-find-files'. +You will have to restart Emacs or reeval `helm-find-files-map' +and `helm-read-file-map' for this take effect." + :group 'helm-files + :type 'boolean) + +(defcustom helm-ff-history-max-length 100 + "Number of elements shown in `helm-find-files' history." + :group 'helm-files + :type 'integer) + +(defcustom helm-ff-fuzzy-matching t + "Enable fuzzy matching for `helm-find-files' when non--nil. +See `helm-ff--transform-pattern-for-completion' for more info." + :group 'helm-files + :type 'boolean) + +(defcustom helm-ff-exif-data-program "exiftran" + "Program used to extract exif data of an image file." + :group 'helm-files + :type 'string) + +(defcustom helm-ff-exif-data-program-args "-d" + "Arguments used for `helm-ff-exif-data-program'." + :group 'helm-files + :type 'string) + +(defcustom helm-ff-newfile-prompt-p t + "Whether Prompt or not when creating new file. +This set `ffap-newfile-prompt'." + :type 'boolean + :group 'helm-files) + +(defcustom helm-ff-avfs-directory "~/.avfs" + "The default avfs directory, usually '~/.avfs'. +When this is set you will be able to expand archive filenames with `C-j' +inside an avfs directory mounted with mountavfs. +See ." + :type 'string + :group 'helm-files) + +(defcustom helm-ff-file-compressed-list '("gz" "bz2" "zip" "7z") + "Minimal list of compressed files extension." + :type '(repeat (choice string)) + :group 'helm-files) + +(defcustom helm-ff-printer-list nil + "A list of available printers on your system. +When non--nil let you choose a printer to print file. +Otherwise when nil the variable `printer-name' will be used. +On Unix based systems (lpstat command needed) you don't need to set this, +`helm-ff-find-printers' will find a list of available printers for you." + :type '(repeat (choice string)) + :group 'helm-files) + +(defcustom helm-ff-transformer-show-only-basename t + "Show only basename of candidates in `helm-find-files'. +This can be toggled at anytime from `helm-find-files' with \ +\\\\[helm-ff-run-toggle-basename]." + :type 'boolean + :group 'helm-files) + +(defcustom helm-ff-signal-error-on-dot-files t + "Signal error when file is `.' or `..' on file deletion when non--nil. +Default is non--nil. +WARNING: Setting this to nil is unsafe and can cause deletion of a whole tree." + :group 'helm-files + :type 'boolean) + +(defcustom helm-ff-search-library-in-sexp nil + "Search for library in `require' and `declare-function' sexp." + :group 'helm-files + :type 'boolean) + +(defcustom helm-tooltip-hide-delay 25 + "Hide tooltips automatically after this many seconds." + :group 'helm-files + :type 'integer) + +(defcustom helm-ff-file-name-history-use-recentf nil + "Use `recentf-list' instead of `file-name-history' in `helm-find-files'." + :group 'helm-files + :type 'boolean) + +(defcustom helm-ff-skip-boring-files nil + "Non--nil to skip files matching regexps in +`helm-boring-file-regexp-list'. + +This take effect in `helm-find-files' and file completion used by `helm-mode' +i.e `helm-read-file-name'. +Note that when non-nil this will slow down slightly `helm-find-files'." + :group 'helm-files + :type 'boolean) + +(defcustom helm-ff-candidate-number-limit 5000 + "The `helm-candidate-number-limit' for `helm-find-files' and friends. +Note that when going one level up with `\\\\[helm-find-files-up-one-level]' +The length of directory will be used instead if it is higher than this +value, this to avoid failing to preselect the previous directory/file if +this one is situated lower than `helm-ff-candidate-number-limit' num +candidate." + :group 'helm-files + :type 'integer) + +(defcustom helm-ff-up-one-level-preselect t + "Always preselect previous directory when going one level up. + +When non nil `candidate-number-limit' source value is modified +dynamically when going one level up if the position of previous +candidate in its directory is > to `helm-ff-candidate-number-limit'. + +This can be helpful to disable this and reduce +`helm-ff-candidate-number-limit' if you often navigate across very +large directories." + :group 'helm-files + :type 'boolean) + +(defcustom helm-files-save-history-extra-sources + '("Find" "Locate" "Recentf" + "Files from Current Directory" "File Cache") + "Extras source that save candidate to `file-name-history'." + :group 'helm-files + :type '(repeat (choice string))) + +(defcustom helm-find-files-before-init-hook nil + "Hook that run before initialization of `helm-find-files'." + :group 'helm-files + :type 'hook) + +(defcustom helm-find-files-after-init-hook nil + "Hook that run after initialization of `helm-find-files'." + :group 'helm-files + :type 'hook) + +(defcustom helm-find-files-bookmark-prefix "Helm-find-files: " + "bookmark name prefix of `helm-find-files' sessions." + :group 'helm-files + :type 'string) + +(defcustom helm-ff-guess-ffap-filenames nil + "Use ffap to guess local filenames at point in `helm-find-files'. +This doesn't disable url or mail at point, see +`helm-ff-guess-ffap-urls' for this." + :group 'helm-files + :type 'boolean) + +(defcustom helm-ff-guess-ffap-urls t + "Use ffap to guess local urls at point in `helm-find-files'. +This doesn't disable guessing filenames at point, +see `helm-ff-guess-ffap-filenames' for this. +See also `ffap-url-unwrap-remote' that may override this variable." + :group 'helm-files + :type 'boolean) + +(defcustom helm-ff-no-preselect nil + "When non--nil `helm-find-files' starts at root of current directory." + :group 'helm-files + :type 'boolean) + +(defcustom helm-find-files-ignore-thing-at-point nil + "Use only `default-directory' as default input in `helm-find-files'. +I.e text under cursor in `current-buffer' is ignored. +Note that when non-nil you will be unable to complete filename at point +in `current-buffer'." + :group 'helm-files + :type 'boolean) + +(defcustom helm-substitute-in-filename-stay-on-remote nil + "Don't switch back to local filesystem when expanding pattern with / or ~/." + :group 'helm-files + :type 'boolean) + +(defcustom helm-ff-goto-first-real-dired-exceptions '(dired-goto-file) + "Dired commands that are allowed moving to first real candidate." + :group 'helm-files + :type '(repeat (choice symbol))) + +(defcustom helm-mounted-network-directories nil + "A list of directories used for mounting remotes filesystem. + +When nil `helm-file-on-mounted-network-p' always return nil otherwise +it checks if a file is in one of these directories. + +Remote filesystem are generally mounted with sshfs." + :group 'helm-files + :type '(repeat string)) + +(defcustom helm-browse-project-default-find-files-fn + #'helm-browse-project-walk-directory + "The default function to retrieve files in a non-vc directory. + +A function that takes a directory name as only arg." + :group 'helm-files + :type 'function) + +(defcustom helm-ff-kill-or-find-buffer-fname-fn + #'helm-ff-kill-or-find-buffer-fname + "Default function used to expand non-directory filenames in `helm-find-files'. + +This variable will take effect only in `helm-find-files', it affects +the behavior of persistent-action on filenames and non-existing +filenames. + +The default is to expand filename on first hit on +\\\\[helm-execute-persistent-action], pop buffer in other +window on second hit and finally kill this buffer on third hit, this +is very handy to create several new buffers, or when navigating, show +quickly the buffer of file to see its contents briefly before killing +it and continue navigating. + +However some users may not want this, so to disable this behavior just +set this to `ignore' function. + +Of course you can also write your own function to do something else." + :group 'helm-files + :type 'function) + +(defcustom helm-modes-using-escaped-strings + '(eshell-mode shell-mode term-mode) + "Modes that requires string's insertion to be escaped." + :group 'helm-files + :type '(repeat symbol)) + +(defcustom helm-ff-allow-recursive-deletes nil + "when 'always don't prompt for recursive deletion of directories. +When nil, will ask for recursive deletion. +Note that when deleting multiple directories you can answer ! when +prompted to avoid beeing asked for next directories, so it is probably +better to not modify this variable." + :group 'helm-files + :type '(choice + (const :tag "Delete non-empty directories" t) + (const :tag "Confirm for each directory" nil))) + +(defcustom helm-ff-delete-files-function #'helm-delete-marked-files + "The function to use by default to delete files. + +Default is to delete files synchronously, other choice is to delete +files asynchronously. + +BE AWARE that when deleting async you will not be warned about +recursive deletion of directories, IOW non empty directories will be +deleted with no warnings in background!!! + +It is the function that will be used when using `\\\\[helm-ff-run-delete-file]' +from `helm-find-files'." + :group 'helm-files + :type '(choice (function :tag "Delete files synchronously." + helm-delete-marked-files) + (function :tag "Delete files asynchronously." + helm-delete-marked-files-async))) + +(defcustom helm-trash-remote-files nil + "Allow trashing remote files when non-nil. + +Deleting remote files with tramp doesn't work out of the box, it is +why it is disabled by default. + +Following is NOT documented in tramp AFAIK but tramp is using +external trash command in its `delete-file' and `delete-directory' +handlers. + +If you want to enable this you will have to install the 'trash' command +on remote (or locally if you want to trash as root), the package on +Ubuntu based distribution is 'trash-cli'." + :group 'helm-files + :type 'boolean) + +(defcustom helm-list-directory-function + (cl-case system-type + (gnu/linux #'helm-list-dir-external) + (berkeley-unix #'helm-list-dir-external) + (windows-nt #'helm-list-dir-lisp) + (t #'helm-list-dir-lisp)) + "The function used in `helm-find-files' to list remote directories. + +Actually helm provides two functions to do this: `helm-list-dir-lisp' +and `helm-list-dir-external'. + +Using `helm-list-dir-external' will provides a similar display to what +provided with local files i.e. colorized symlinks, executables files +etc... whereas using `helm-list-dir-lisp' will allow colorizing only +directories but is more portable. + +NOTE that `helm-list-dir-external' needs ls and awk as dependencies." + :type 'function + :group 'helm-files) + +;;; Faces +;; +;; +(defgroup helm-files-faces nil + "Customize the appearance of helm-files." + :prefix "helm-" + :group 'helm-files + :group 'helm-faces) + +(defface helm-ff-prefix + '((t (:background "yellow" :foreground "black"))) + "Face used to prefix new file or url paths in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-executable + '((t (:foreground "green"))) + "Face used for executable files in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-suid + '((t (:background "red" :foreground "white"))) + "Face used for suid files in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-directory + '((t (:foreground "DarkRed" :background "LightGray"))) + "Face used for directories in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-dotted-directory + '((t (:foreground "black" :background "DimGray"))) + "Face used for dotted directories in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-dotted-symlink-directory + '((t (:foreground "DarkOrange" :background "DimGray"))) + "Face used for dotted symlinked directories in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-symlink + '((t :inherit font-lock-comment-face)) + "Face used for symlinks in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-invalid-symlink + '((t (:foreground "black" :background "red"))) + "Face used for invalid symlinks in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-denied + '((t (:foreground "red" :background "black"))) + "Face used for non accessible files in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-file + '((t (:inherit font-lock-builtin-face))) + "Face used for file names in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-truename + '((t (:inherit font-lock-string-face))) + "Face used for symlink truenames in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-dirs + '((t (:inherit font-lock-function-name-face))) + "Face used for file names in recursive dirs completion in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-socket + '((t (:foreground "DeepPink"))) + "Face used for socket files in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-ff-pipe + '((t (:foreground "yellow" :background "black"))) + "Face used for named pipes and character device files in `helm-find-files'." + :group 'helm-files-faces) + +(defface helm-history-deleted + '((t (:inherit helm-ff-invalid-symlink))) + "Face used for deleted files in `file-name-history'." + :group 'helm-files-faces) + +(defface helm-history-remote + '((t (:foreground "Indianred1"))) + "Face used for remote files in `file-name-history'." + :group 'helm-files-faces) + +(defface helm-delete-async-message + '((t (:foreground "yellow"))) + "Face used for mode-line message." + :group 'helm-files-faces) + +;;; Helm-find-files - The helm file browser. +;; +;; Keymaps +(defvar helm-find-files-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "RET") 'helm-ff-RET) + (define-key map (kbd "C-]") 'helm-ff-run-toggle-basename) + (define-key map (kbd "C-x C-f") 'helm-ff-run-locate) + (define-key map (kbd "C-x C-d") 'helm-ff-run-browse-project) + (define-key map (kbd "C-x r m") 'helm-ff-bookmark-set) + (define-key map (kbd "C-x r b") 'helm-find-files-toggle-to-bookmark) + (define-key map (kbd "C-x C-q") 'helm-ff-run-marked-files-in-dired) + (define-key map (kbd "C-s") 'helm-ff-run-grep) + (define-key map (kbd "M-g s") 'helm-ff-run-grep) + (define-key map (kbd "M-g p") 'helm-ff-run-pdfgrep) + (define-key map (kbd "M-g z") 'helm-ff-run-zgrep) + (define-key map (kbd "M-g a") 'helm-ff-run-grep-ag) + (define-key map (kbd "M-g g") 'helm-ff-run-git-grep) + (define-key map (kbd "M-g i") 'helm-ff-run-gid) + (define-key map (kbd "M-.") 'helm-ff-run-etags) + (define-key map (kbd "M-R") 'helm-ff-run-rename-file) + (define-key map (kbd "M-C") 'helm-ff-run-copy-file) + (define-key map (kbd "M-B") 'helm-ff-run-byte-compile-file) + (define-key map (kbd "M-L") 'helm-ff-run-load-file) + (define-key map (kbd "M-S") 'helm-ff-run-symlink-file) + (define-key map (kbd "M-Y") 'helm-ff-run-relsymlink-file) + (define-key map (kbd "M-H") 'helm-ff-run-hardlink-file) + (define-key map (kbd "M-D") 'helm-ff-run-delete-file) + (define-key map (kbd "M-K") 'helm-ff-run-kill-buffer-persistent) + (define-key map (kbd "M-T") 'helm-ff-run-touch-files) + (define-key map (kbd "C-c d") 'helm-ff-persistent-delete) + (define-key map (kbd "M-e") 'helm-ff-run-switch-to-eshell) + (define-key map (kbd "C-c i") 'helm-ff-run-complete-fn-at-point) + (define-key map (kbd "C-c o") 'helm-ff-run-switch-other-window) + (define-key map (kbd "C-c C-o") 'helm-ff-run-switch-other-frame) + (define-key map (kbd "C-c C-x") 'helm-ff-run-open-file-externally) + (define-key map (kbd "C-c C-v") 'helm-ff-run-preview-file-externally) + (define-key map (kbd "C-c X") 'helm-ff-run-open-file-with-default-tool) + (define-key map (kbd "M-!") 'helm-ff-run-eshell-command-on-file) + (define-key map (kbd "M-@") 'helm-ff-run-query-replace-fnames-on-marked) + (define-key map (kbd "M-%") 'helm-ff-run-query-replace) + (define-key map (kbd "C-M-%") 'helm-ff-run-query-replace-regexp) + (define-key map (kbd "C-c =") 'helm-ff-run-ediff-file) + (define-key map (kbd "M-=") 'helm-ff-run-ediff-merge-file) + (define-key map (kbd "M-p") 'helm-find-files-history) + (define-key map (kbd "C-c h") 'helm-ff-file-name-history) + (define-key map (kbd "M-i") 'helm-ff-properties-persistent) + (define-key map (kbd "C-}") 'helm-narrow-window) + (define-key map (kbd "C-{") 'helm-enlarge-window) + (define-key map (kbd "C-") 'helm-ff-run-toggle-auto-update) + (define-key map (kbd "C-c ") 'helm-ff-run-toggle-auto-update) + (define-key map (kbd "C-c C-a") 'helm-ff-run-mail-attach-files) + (define-key map (kbd "C-c p") 'helm-ff-run-print-file) + (define-key map (kbd "C-c /") 'helm-ff-run-find-sh-command) + ;; Next 2 have no effect if candidate is not an image file. + (define-key map (kbd "M-l") 'helm-ff-rotate-left-persistent) + (define-key map (kbd "M-r") 'helm-ff-rotate-right-persistent) + (define-key map (kbd "C-l") 'helm-find-files-up-one-level) + (define-key map (kbd "C-r") 'helm-find-files-down-last-level) + (define-key map (kbd "C-c r") 'helm-ff-run-find-file-as-root) + (define-key map (kbd "C-x C-v") 'helm-ff-run-find-alternate-file) + (define-key map (kbd "C-c @") 'helm-ff-run-insert-org-link) + (helm-define-key-with-subkeys map (kbd "DEL") ?\d 'helm-ff-delete-char-backward + '((C-backspace . helm-ff-run-toggle-auto-update) + ([C-c DEL] . helm-ff-run-toggle-auto-update)) + nil 'helm-ff-delete-char-backward--exit-fn) + (when helm-ff-lynx-style-map + (define-key map (kbd "") 'helm-find-files-up-one-level) + (define-key map (kbd "") 'helm-execute-persistent-action)) + (delq nil map)) + "Keymap for `helm-find-files'.") + +(defvar helm-read-file-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "") 'helm-cr-empty-string) + (define-key map (kbd "M-RET") 'helm-cr-empty-string) + (define-key map (kbd "C-]") 'helm-ff-run-toggle-basename) + (define-key map (kbd "C-.") 'helm-find-files-up-one-level) + (define-key map (kbd "C-l") 'helm-find-files-up-one-level) + (define-key map (kbd "C-r") 'helm-find-files-down-last-level) + (define-key map (kbd "C-c h") 'helm-ff-file-name-history) + (define-key map (kbd "C-") 'helm-ff-run-toggle-auto-update) + (define-key map (kbd "C-c ") 'helm-ff-run-toggle-auto-update) + (helm-define-key-with-subkeys map (kbd "DEL") ?\d 'helm-ff-delete-char-backward + '((C-backspace . helm-ff-run-toggle-auto-update) + ([C-c DEL] . helm-ff-run-toggle-auto-update)) + nil 'helm-ff-delete-char-backward--exit-fn) + (when helm-ff-lynx-style-map + (define-key map (kbd "") 'helm-find-files-up-one-level) + (define-key map (kbd "") 'helm-execute-persistent-action) + (define-key map (kbd "") 'helm-previous-source) + (define-key map (kbd "") 'helm-next-source)) + (delq nil map)) + "Keymap for `helm-read-file-name'.") + + +;; Internal. +(defvar helm-find-files-doc-header " (\\\\[helm-find-files-up-one-level]: Go up one level)" + "*The doc that is inserted in the Name header of a find-files or dired source.") +(defvar helm-ff-auto-update-flag nil + "Internal, flag to turn on/off auto-update in `helm-find-files'. +Don't set it directly, use instead `helm-ff-auto-update-initial-value'.") +(defvar helm-ff-last-expanded nil + "Store last expanded directory or file.") +(defvar helm-ff-default-directory nil) +(defvar helm-ff-history nil) +(defvar helm-ff-cand-to-mark nil) +(defvar helm-ff-url-regexp + "\\`\\(news\\(post\\)?:\\|nntp:\\|mailto:\\|file:\\|\\(ftp\\|https?\\|telnet\\|gopher\\|www\\|wais\\):/?/?\\).*" + "Same as `ffap-url-regexp' but match earlier possible url.") +;; helm-tramp-file-name-regexp is based on old version of +;; tramp-file-name-regexp i.e. "\\`/\\([^[/:]+\\|[^/]+]\\):" but it +;; seems it is wrong and a simpler regexp is enough, let's try it and +;; watch out! +(defvar helm-tramp-file-name-regexp "\\`/\\([^/:|]+\\):") +(defvar helm-marked-buffer-name "*helm marked*") +(defvar helm-ff--auto-update-state nil) +(defvar helm-ff--deleting-char-backward nil) +(defvar helm-multi-files--toggle-locate nil) +(defvar helm-ff--move-to-first-real-candidate t) +(defvar helm-find-files--toggle-bookmark nil) +(defvar helm-ff--tramp-methods nil) +(defvar helm-ff--directory-files-hash (make-hash-table :test 'equal)) +(defvar helm-ff-history-buffer-name "*helm-find-files history*") + +;;; Helm-find-files +;; +;; +(defcustom helm-find-files-actions + (helm-make-actions + "Find File" 'helm-find-file-or-marked + "Find file in Dired" 'helm-point-file-in-dired + "View file" 'view-file + "Query replace fnames on marked `M-@'" 'helm-ff-query-replace-fnames-on-marked + "Marked files in dired `C-x C-q, C-u wdired'" 'helm-marked-files-in-dired + "Query replace contents on marked `M-%'" 'helm-ff-query-replace + "Query replace regexp contents on marked `C-M-%'" 'helm-ff-query-replace-regexp + "Attach file(s) to mail buffer `C-c C-a'" 'helm-ff-mail-attach-files + "Serial rename files" 'helm-ff-serial-rename + "Serial rename by symlinking files" 'helm-ff-serial-rename-by-symlink + "Serial rename by copying files" 'helm-ff-serial-rename-by-copying + "Open file with default tool" 'helm-open-file-with-default-tool + "Find file in hex dump" 'hexl-find-file + "Browse project `C-x C-d'" 'helm-ff-browse-project + "Complete at point `C-c i'" 'helm-insert-file-name-completion-at-point + "Insert as org link `C-c @'" 'helm-files-insert-as-org-link + "Find shell command `C-c /'" 'helm-ff-find-sh-command + "Add marked files to file-cache" 'helm-ff-cache-add-file + "Open file externally `C-c C-x, C-u to choose'" 'helm-open-file-externally + "Grep File(s) `C-s, C-u Recurse'" 'helm-find-files-grep + "Grep current directory with AG `M-g a, C-u select type'" 'helm-find-files-ag + "Git grep `M-g g, C-u from root'" 'helm-ff-git-grep + "Zgrep File(s) `M-g z, C-u Recurse'" 'helm-ff-zgrep + "Gid `M-g i'" 'helm-ff-gid + "Switch to Eshell `M-e'" 'helm-ff-switch-to-eshell + "Etags `M-., C-u reload tag file'" 'helm-ff-etags-select + "Eshell command on file(s) `M-!, C-u take all marked as arguments.'" + 'helm-find-files-eshell-command-on-file + "Find file as root `C-c r'" 'helm-find-file-as-root + "Find alternate file `C-x C-v'" 'find-alternate-file + "Ediff File `C-c ='" 'helm-find-files-ediff-files + "Ediff Merge File `M-='" 'helm-find-files-ediff-merge-files + (lambda () (format "Delete File(s)%s `M-D' (C-u reverse trash)" + (if (eq helm-ff-delete-files-function + 'helm-delete-marked-files-async) + " async" ""))) + 'helm-ff-delete-files + "Touch File(s) `M-T'" 'helm-ff-touch-files + "Copy file(s) `M-C, C-u to follow'" 'helm-find-files-copy + "Rename file(s) `M-R, C-u to follow'" 'helm-find-files-rename + "Backup files" 'helm-find-files-backup + "Symlink files(s) `M-S, C-u to follow'" 'helm-find-files-symlink + "Relsymlink file(s) `M-Y, C-u to follow'" 'helm-find-files-relsymlink + "Hardlink file(s) `M-H, C-u to follow'" 'helm-find-files-hardlink + "Find file other window `C-c o'" 'helm-find-files-other-window + "Find file other frame `C-c C-o'" 'find-file-other-frame + "Print File `C-c p, C-u to refresh'" 'helm-ff-print + "Locate `C-x C-f, C-u to specify locate db'" 'helm-ff-locate) + "Actions for `helm-find-files'." + :group 'helm-files + :type '(alist :key-type string :value-type function)) + +(defvar helm-source-find-files nil + "The main source to browse files. +Should not be used among other sources.") + +(defclass helm-source-ffiles (helm-source-sync) + ((header-name + :initform (lambda (name) + (concat name (substitute-command-keys + helm-find-files-doc-header)))) + (init + :initform (lambda () + (setq helm-ff-auto-update-flag + helm-ff-auto-update-initial-value) + (setq helm-ff--auto-update-state + helm-ff-auto-update-flag) + (helm-set-local-variable 'bookmark-make-record-function + #'helm-ff-make-bookmark-record) + (require 'helm-external))) + (candidates :initform 'helm-find-files-get-candidates) + (filtered-candidate-transformer + :initform '(helm-ff-sort-candidates + (lambda (candidates _source) + (cl-loop for f in candidates + for ff = (helm-ff-filter-candidate-one-by-one f) + when ff collect ff)))) + (persistent-action-if :initform 'helm-find-files-persistent-action-if) + (persistent-help :initform "Hit1 Expand Candidate, Hit2 or (C-u) Find file") + (help-message :initform 'helm-ff-help-message) + (mode-line :initform (list "File(s)" helm-mode-line-string)) + (volatile :initform t) + (cleanup :initform 'helm-find-files-cleanup) + (migemo :initform t) + (nohighlight :initform t) + (keymap :initform helm-find-files-map) + (candidate-number-limit :initform 'helm-ff-candidate-number-limit) + (action-transformer + :initform 'helm-find-files-action-transformer) + (action :initform 'helm-find-files-actions) + (before-init-hook :initform 'helm-find-files-before-init-hook) + (after-init-hook :initform 'helm-find-files-after-init-hook) + (group :initform 'helm-files))) + +;; Bookmark handlers. +;; +(defun helm-ff-make-bookmark-record () + "The `bookmark-make-record-function' for `helm-find-files'." + (with-helm-buffer + `((filename . ,helm-ff-default-directory) + (presel . ,(helm-get-selection)) + (handler . helm-ff-bookmark-jump)))) + +(defun helm-ff-bookmark-jump (bookmark) + "bookmark handler for `helm-find-files'." + (let ((fname (bookmark-prop-get bookmark 'filename)) + (presel (bookmark-prop-get bookmark 'presel))) + ;; Force tramp connection with `file-directory-p' before lauching + ;; hff otherwise the directory name is inserted on top before + ;; tramp starts and display candidates. FNAME is here always a + ;; directory. + (when (file-directory-p fname) + (helm-find-files-1 fname (if helm-ff-transformer-show-only-basename + (helm-basename presel) + presel))))) + +(defun helm-ff-bookmark-set () + "Record `helm-find-files' session in bookmarks." + (interactive) + (with-helm-alive-p + (with-helm-buffer + (bookmark-set + (concat helm-find-files-bookmark-prefix + (abbreviate-file-name helm-ff-default-directory)))) + (message "Helm find files session bookmarked! "))) +(put 'helm-ff-bookmark-set 'helm-only t) + +(defcustom helm-dwim-target nil + "Default target directory for file actions. + +Define the directory where you want to start navigating for the target +directory when copying, renaming etc... You can use the +`default-directory' of `next-window', the current +`default-directory' or have completion on all the directories +belonging to each window." + :group 'helm-files + :type '(radio :tag "Define default target directory for file actions." + (const :tag "Directory belonging to next window" next-window) + (const :tag "Completion on directories belonging to each window" completion) + (const :tag "Use initial directory or `default-directory'" nil))) + +(defun helm-dwim-target-directory () + "Try to return a suitable directory according to `helm-dwim-target'." + (with-helm-current-buffer + (let* ((wins (remove (get-buffer-window helm-marked-buffer-name) + (window-list))) + (num-windows (length wins))) + (expand-file-name + (cond ((and (> num-windows 1) + (eq helm-dwim-target 'completion)) + (helm-comp-read "Browse target starting from: " + (append (list (or (car-safe helm-ff-history) + default-directory) + default-directory) + (cl-loop for w in wins collect + (with-selected-window w + default-directory))))) + ((and (> num-windows 1) + (eq helm-dwim-target 'next-window)) + (with-selected-window (next-window) + default-directory)) + ((or (= num-windows 1) + (null helm-dwim-target)) + ;; Using the car of *ff-history allow + ;; staying in the directory visited instead of + ;; current. + (or (car-safe helm-ff-history) default-directory))))))) + +(defun helm-ff--count-and-collect-dups (files) + (cl-loop with dups = (make-hash-table :test 'equal) + for f in files + for file = (if (file-directory-p f) + (concat (helm-basename f) "/") + (helm-basename f)) + for count = (gethash file dups) + if count do (puthash file (1+ count) dups) + else do (puthash file 1 dups) + finally return (cl-loop for k being the hash-keys in dups + using (hash-value v) + if (> v 1) + collect (format "%s(%s)" k v) + else + collect k))) + +(defun helm-find-files-do-action (action) + "Generic function for creating actions from `helm-source-find-files'. +ACTION must be an action supported by `helm-dired-action'." + (require 'dired-async) + (let* ((ifiles (mapcar 'expand-file-name ; Allow modify '/foo/.' -> '/foo' + (helm-marked-candidates :with-wildcard t))) + (cand (helm-get-selection)) ; Target + (prefarg helm-current-prefix-arg) + (prompt (format "%s %s file(s) to: " + (if (and (and (fboundp 'dired-async-mode) + dired-async-mode) + (null prefarg)) + (concat "Async " (symbol-name action)) + (capitalize (symbol-name action))) + (length ifiles))) + helm-ff--move-to-first-real-candidate + helm-display-source-at-screen-top ; prevent setting window-start. + helm-ff-auto-update-initial-value + ;; It is not possible to rename a file to a boring name when + ;; helm-ff-skip-boring-files is enabled + helm-ff-skip-boring-files + ;; If HFF is using a frame use a frame as well. + (helm-actions-inherit-frame-settings t) + helm-use-frame-when-more-than-two-windows + (dest (with-helm-display-marked-candidates + helm-marked-buffer-name + (helm-ff--count-and-collect-dups ifiles) + (with-helm-current-buffer + (helm-read-file-name + prompt + :preselect (unless (cdr ifiles) + (concat + "^" + (regexp-quote + (if helm-ff-transformer-show-only-basename + (helm-basename cand) cand)))) + :initial-input (helm-dwim-target-directory) + :history (helm-find-files-history nil :comp-read nil))))) + (dest-dir-p (file-directory-p dest)) + (dest-dir (helm-basedir dest))) + (unless (or dest-dir-p (file-directory-p dest-dir)) + (when (y-or-n-p (format "Create directory `%s'? " dest-dir)) + (make-directory dest-dir t))) + (helm-dired-action + dest :files ifiles :action action :follow prefarg))) + +(defun helm-find-files-copy (_candidate) + "Copy files from `helm-find-files'." + (helm-find-files-do-action 'copy)) + +(defun helm-find-files-backup (_candidate) + "Backup files from `helm-find-files'. +This reproduce the behavior of \"cp --backup=numbered from to\"." + (cl-assert (and (fboundp 'dired-async-mode) dired-async-mode) nil + "Backup only available when `dired-async-mode' is enabled") + (helm-find-files-do-action 'backup)) + +(defun helm-find-files-rename (_candidate) + "Rename files from `helm-find-files'." + (helm-find-files-do-action 'rename)) + +(defun helm-find-files-symlink (_candidate) + "Symlink files from `helm-find-files'." + (helm-find-files-do-action 'symlink)) + +(defun helm-find-files-relsymlink (_candidate) + "Relsymlink files from `helm-find-files'." + (helm-find-files-do-action 'relsymlink)) + +(defun helm-find-files-hardlink (_candidate) + "Hardlink files from `helm-find-files'." + (helm-find-files-do-action 'hardlink)) + +(defun helm-find-files-other-window (_candidate) + "Keep current-buffer and open files in separate windows. +When a prefix arg is detected files are opened in a vertical windows +layout." + (let* ((files (helm-marked-candidates)) + (buffers (mapcar 'find-file-noselect files))) + (helm-window-show-buffers buffers t))) + +(defun helm-find-files-byte-compile (_candidate) + "Byte compile elisp files from `helm-find-files'." + (let ((files (helm-marked-candidates :with-wildcard t)) + (parg helm-current-prefix-arg)) + (cl-loop for fname in files + do (byte-compile-file fname parg)))) + +(defun helm-find-files-load-files (_candidate) + "Load elisp files from `helm-find-files'." + (let ((files (helm-marked-candidates :with-wildcard t))) + (cl-loop for fname in files + do (load fname)))) + +(defun helm-find-files-ediff-files-1 (candidate &optional merge) + "Generic function to ediff/merge files in `helm-find-files'." + (let* ((helm-dwim-target 'next-window) + (bname (helm-basename candidate)) + (marked (helm-marked-candidates :with-wildcard t)) + (prompt (if merge "Ediff Merge `%s' With File: " + "Ediff `%s' With File: ")) + (fun (if merge 'ediff-merge-files 'ediff-files)) + (input (helm-dwim-target-directory)) + (presel (if helm-ff-transformer-show-only-basename + (helm-basename candidate) + (expand-file-name + (helm-basename candidate) + input)))) + (if (= (length marked) 2) + (funcall fun (car marked) (cadr marked)) + (funcall fun candidate (helm-read-file-name + (format prompt bname) + :initial-input input + :preselect presel))))) + +(defun helm-find-files-ediff-files (candidate) + (helm-find-files-ediff-files-1 candidate)) + +(defun helm-find-files-ediff-merge-files (candidate) + (helm-find-files-ediff-files-1 candidate 'merge)) + +(defun helm-find-files-grep (_candidate) + "Default action to grep files from `helm-find-files'." + (helm-do-grep-1 (helm-marked-candidates :with-wildcard t) + helm-current-prefix-arg)) + +(defun helm-ff-git-grep (_candidate) + "Default action to git-grep `helm-ff-default-directory'." + (helm-grep-git-1 helm-ff-default-directory helm-current-prefix-arg)) + +(defun helm-find-files-ag (_candidate) + (helm-grep-ag helm-ff-default-directory + helm-current-prefix-arg)) + +(defun helm-ff-zgrep (_candidate) + "Default action to zgrep files from `helm-find-files'." + (helm-ff-zgrep-1 (helm-marked-candidates :with-wildcard t) helm-current-prefix-arg)) + +(defun helm-ff-pdfgrep (_candidate) + "Default action to pdfgrep files from `helm-find-files'." + (let* ((recurse nil) + (cands (cl-loop for file in (helm-marked-candidates :with-wildcard t) + for dir = (file-directory-p file) + when dir do (setq recurse t) + when (or dir + (string= (file-name-extension file) "pdf") + (string= (file-name-extension file) "PDF")) + collect file))) + (when cands + (helm-do-pdfgrep-1 cands recurse)))) + +(defun helm-ff-etags-select (candidate) + "Default action to jump to etags from `helm-find-files'." + (when (get-buffer helm-action-buffer) + (kill-buffer helm-action-buffer)) + (let* ((source-name (assoc-default 'name (helm-get-current-source))) + (default-directory (if (string= source-name "Find Files") + helm-ff-default-directory + (file-name-directory candidate)))) + (helm-etags-select helm-current-prefix-arg))) + +(defvar eshell-command-aliases-list nil) +(defvar helm-eshell-command-on-file-input-history nil) +(defun helm-find-files-eshell-command-on-file-1 (&optional map) + "Run `eshell-command' on CANDIDATE or marked candidates. +This is done possibly with an eshell alias, if no alias found, you can type in +an eshell command. + +Only aliases accepting a file as argument at the end of command line +are collected, i.e aliases ending with \"$1\" or \"$*\". + +Basename of CANDIDATE can be a wild-card. +e.g you can do \"eshell-command command *.el\" +Where \"*.el\" is the CANDIDATE. + +It is possible to do eshell-command command +like this: \"command %s some more args\". + +If MAP is given run `eshell-command' on all marked files at once, +Otherwise, run `eshell-command' on each marked files. +In other terms, with a prefix arg do on the three marked files +\"foo\" \"bar\" \"baz\": + +\"eshell-command command foo bar baz\" + +otherwise do + +\"eshell-command command foo\" +\"eshell-command command bar\" +\"eshell-command command baz\" + +Note: +You have to setup some aliases in eshell with the `alias' command or +by editing yourself the file `eshell-aliases-file' to make this +working." + (require 'em-alias) (eshell-read-aliases-list) + (when (or eshell-command-aliases-list + (y-or-n-p "No eshell aliases found, run eshell-command without alias anyway? ")) + (let* ((cand-list (helm-marked-candidates)) + (default-directory (or helm-ff-default-directory + ;; If candidate is an url *-ff-default-directory is nil + ;; so keep value of default-directory. + default-directory)) + (command (helm-comp-read + "Command: " + (cl-loop for (a c) in (eshell-read-aliases-list) + ;; Positional arguments may be double + ;; quoted (Issue #1881). + when (string-match "[\"]?.*\\(\\$1\\|\\$\\*\\)[\"]?\\'" c) + collect (propertize a 'help-echo c) into ls + finally return (sort ls 'string<)) + :buffer "*helm eshell on file*" + :name "Eshell command" + :mode-line + '("Eshell alias" + "C-h m: Help, \\[universal-argument]: Insert output at point") + :help-message 'helm-esh-help-message + :input-history + 'helm-eshell-command-on-file-input-history)) + (alias-value (car (assoc-default command eshell-command-aliases-list))) + cmd-line) + (if (or (equal helm-current-prefix-arg '(16)) + (equal map '(16))) + ;; Two time C-u from `helm-comp-read' mean print to current-buffer. + ;; i.e `eshell-command' will use this value. + (setq current-prefix-arg '(16)) + ;; Else reset the value of `current-prefix-arg' + ;; to avoid printing in current-buffer. + (setq current-prefix-arg nil)) + (if (and (or + ;; One prefix-arg have been passed before `helm-comp-read'. + ;; If map have been set with C-u C-u (value == '(16)) + ;; ignore it. + (and map (equal map '(4))) + ;; One C-u from `helm-comp-read'. + (equal helm-current-prefix-arg '(4)) + ;; An alias that finish with $* + (and alias-value + ;; If command is an alias be sure it accept + ;; more than one arg i.e $*. + (string-match "\\$\\*$" alias-value))) + (cdr cand-list)) + + ;; Run eshell-command with ALL marked files as arguments. + ;; This wont work on remote files, because tramp handlers depends + ;; on `default-directory' (limitation). + (let ((mapfiles (mapconcat 'eshell-quote-argument cand-list " "))) + (if (string-match "'%s'\\|\"%s\"\\|%s" command) + (setq cmd-line (format command mapfiles)) ; See [1] + (setq cmd-line (format "%s %s" command mapfiles))) + (helm-log "%S" cmd-line) + (eshell-command cmd-line)) + + ;; Run eshell-command on EACH marked files. + ;; To work with tramp handler we have to call + ;; COMMAND on basename of each file, using + ;; its basedir as `default-directory'. + (cl-loop for f in cand-list + for dir = (and (not (string-match helm--url-regexp f)) + (helm-basedir f)) + for file = (eshell-quote-argument + (format "%s" (if (and dir (file-remote-p dir)) + (helm-basename f) f))) + for com = (if (string-match "'%s'\\|\"%s\"\\|%s" command) + ;; [1] This allow to enter other args AFTER filename + ;; i.e + (format command file) + (format "%s %s" command file)) + do (let ((default-directory (or dir default-directory))) + (eshell-command com))))))) + +(defun helm-find-files-eshell-command-on-file (_candidate) + "Run `eshell-command' on CANDIDATE or marked candidates. +See `helm-find-files-eshell-command-on-file-1' for more info." + (helm-find-files-eshell-command-on-file-1 helm-current-prefix-arg)) + +(defun helm-ff-switch-to-eshell (_candidate) + "Switch to eshell and cd to `helm-ff-default-directory'. + +With a numeric prefix arg switch to numbered eshell buffer, if no +prefix arg provided and more than one eshell buffer exists, provide +completions on those buffers. If only one eshell buffer exists, +switch to this one, if no eshell buffer exists or if the numeric +prefix arg eshell buffer doesn't exists, create it and switch to it." + (let ((cd-eshell (lambda () + (eshell/cd helm-ff-default-directory) + (eshell-reset))) + (bufs (cl-loop for b in (mapcar 'buffer-name (buffer-list)) + when (helm-ff--eshell-interactive-buffer-p b) + collect b))) + (helm-aif (and (null helm-current-prefix-arg) + (if (cdr bufs) + (helm-comp-read "Switch to eshell buffer: " bufs + :must-match t) + (car bufs))) + (switch-to-buffer it) + (eshell helm-current-prefix-arg)) + (unless (get-buffer-process (current-buffer)) + (funcall cd-eshell)))) + +(defun helm-ff--eshell-interactive-buffer-p (buffer) + (with-current-buffer buffer + (and (eq major-mode 'eshell-mode) + (save-excursion + (goto-char (point-min)) + (eshell-next-prompt 1) + (null (eql (point) (point-min))))))) + +(defun helm-ff-touch-files (_candidate) + "The touch files action for helm-find-files." + (let* ((files (helm-marked-candidates)) + (split (cl-loop for f in files + for spt = (unless helm-current-prefix-arg + (cons (helm-basedir f) + (split-string f ", ?"))) + if spt + append (cl-loop with dir = (car spt) + for ff in (cdr spt) + collect (expand-file-name ff dir)) + else collect f)) + (timestamp (helm-comp-read + "Timestamp (default Now): " + (cl-loop for f in split + for time = (file-attributes f) + for date = (and time + (format-time-string + "%Y-%m-%d %H:%M:%S" + (nth 5 time))) + when date + collect (cons (format "%s: %s" + (helm-basename f) date) + date)) + :default + (format-time-string "%Y-%m-%d %H:%M:%S" + (current-time)))) + (failures + (cl-loop with default-directory = helm-ff-default-directory + for f in split + for file = (or (file-remote-p f 'localname) f) + when (> (process-file + "touch" nil nil nil "-d" timestamp file) + 0) + collect f))) + (when failures + (message "Failed to touch *%s files:\n%s" + (length failures) + (mapconcat (lambda (f) (format "- %s\n" f)) failures ""))))) + +(defun helm-ff-run-touch-files () + "Used to interactively run touch file action from keyboard." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-touch-files))) +(put 'helm-ff-run-touch-files 'helm-only t) + +(defun helm-ff-serial-rename-action (method) + "Rename all marked files in `helm-ff-default-directory' with METHOD. +See `helm-ff-serial-rename-1'." + (let* ((helm--reading-passwd-or-string t) + (cands (helm-marked-candidates :with-wildcard t)) + (def-name (car cands)) + (name (helm-read-string "NewName: " + (replace-regexp-in-string + "[0-9]+$" "" + (helm-basename + def-name + (file-name-extension def-name))))) + (start (read-number "StartAtNumber: ")) + (extension (helm-read-string "Extension: " + (file-name-extension (car cands)))) + (dir (expand-file-name + (helm-read-file-name + "Serial Rename to directory: " + :initial-input + (expand-file-name helm-ff-default-directory) + :test 'file-directory-p + :must-match t))) + done) + (with-helm-display-marked-candidates + helm-marked-buffer-name (helm-ff--count-and-collect-dups cands) + (if (y-or-n-p + (format "Rename %s file(s) to <%s> like this ?\n%s " + (length cands) dir (format "%s <-> %s%s.%s" + (helm-basename (car cands)) + name start extension))) + (progn + (helm-ff-serial-rename-1 + dir cands name start extension :method method) + (setq done t) + (message nil)))) + (if done + (with-helm-current-buffer (helm-find-files-1 dir)) + (message "Operation aborted")))) + +(defun helm-ff-member-directory-p (file directory) + (let ((dir-file (expand-file-name + (file-name-as-directory (file-name-directory file)))) + (cur-dir (expand-file-name (file-name-as-directory directory)))) + (string= dir-file cur-dir))) + +(cl-defun helm-ff-serial-rename-1 + (directory collection new-name start-at-num extension &key (method 'rename)) + "rename files in COLLECTION to DIRECTORY with the prefix name NEW-NAME. +Rename start at number START-AT-NUM - ex: prefixname-01.jpg. +EXTENSION is the file extension to use, in empty prompt, +reuse the original extension of file. +METHOD can be one of rename, copy or symlink. +Files will be renamed if they are files of current directory, otherwise they +will be treated with METHOD. +Default METHOD is rename." + ;; Maybe remove directories selected by error in collection. + (setq collection (cl-remove-if 'file-directory-p collection)) + (let* ((tmp-dir (file-name-as-directory + (concat (file-name-as-directory directory) + (symbol-name (cl-gensym "tmp"))))) + (fn (cl-case method + (copy 'copy-file) + (symlink 'make-symbolic-link) + (rename 'rename-file) + (t (error "Error: Unknown method %s" method))))) + (make-directory tmp-dir) + (unwind-protect + (progn + ;; Rename all files to tmp-dir with new-name. + ;; If files are not from start directory, use method + ;; to move files to tmp-dir. + (cl-loop for i in collection + for count from start-at-num + for fnum = (if (< count 10) "0%s" "%s") + for nname = (concat tmp-dir new-name (format fnum count) + (if (not (string= extension "")) + (format ".%s" (replace-regexp-in-string + "[.]" "" extension)) + (file-name-extension i 'dot))) + do (if (helm-ff-member-directory-p i directory) + (rename-file i nname) + (funcall fn i nname))) + ;; Now move all from tmp-dir to destination. + (cl-loop with dirlist = (directory-files + tmp-dir t directory-files-no-dot-files-regexp) + for f in dirlist do + (if (file-symlink-p f) + (make-symbolic-link (file-truename f) + (concat (file-name-as-directory directory) + (helm-basename f))) + (rename-file f directory)))) + (delete-directory tmp-dir t)))) + +(defun helm-ff-serial-rename (_candidate) + "Serial rename all marked files to `helm-ff-default-directory'. +Rename only file of current directory, and symlink files coming from +other directories. +See `helm-ff-serial-rename-1'." + (helm-ff-serial-rename-action 'rename)) + +(defun helm-ff-serial-rename-by-symlink (_candidate) + "Serial rename all marked files to `helm-ff-default-directory'. +Rename only file of current directory, and symlink files coming from +other directories. +See `helm-ff-serial-rename-1'." + (helm-ff-serial-rename-action 'symlink)) + +(defun helm-ff-serial-rename-by-copying (_candidate) + "Serial rename all marked files to `helm-ff-default-directory'. +Rename only file of current directory, and copy files coming from +other directories. +See `helm-ff-serial-rename-1'." + (helm-ff-serial-rename-action 'copy)) + +(defvar helm-ff-query-replace-fnames-history-from nil) +(defvar helm-ff-query-replace-fnames-history-to nil) +(defun helm-ff-query-replace-on-filenames (candidates) + "Query replace on filenames of CANDIDATES. +This doesn't replace inside the files, only modify filenames." + (with-helm-display-marked-candidates + helm-marked-buffer-name + (mapcar 'helm-basename candidates) + (let* ((regexp (read-string "Replace regexp on filename(s): " + nil 'helm-ff-query-replace-history-from + (helm-basename (car candidates)))) + (rep (read-string (format "Replace regexp `%s' with: " regexp) + nil 'helm-ff-query-replace-history-to)) + subexp) + (cl-loop with query = "y" + with count = 0 + with target = nil + for old in candidates + for new = (concat (helm-basedir old) + (helm--replace-regexp-in-buffer-string + (save-match-data + (cond ((string= regexp "%.") + (setq subexp 1) + (helm-ff--prepare-str-with-regexp + (setq target (helm-basename old t)))) + ((string= regexp ".%") + (setq subexp 1) + (helm-ff--prepare-str-with-regexp + (setq target (file-name-extension old)))) + ((string= regexp "%") + (regexp-quote + (setq target (helm-basename old)))) + ((string-match "%:\\([0-9]+\\):\\([0-9]+\\)" regexp) + (setq subexp 1) + (let ((beg (match-string 1 regexp)) + (end (match-string 2 regexp)) + (str (helm-basename old))) + (setq target (substring str + (string-to-number beg) + (string-to-number end))) + (helm-ff--prepare-str-with-regexp str beg end))) + (t regexp))) + (save-match-data + (cond (;; Handle incremental + ;; replacement with \# in + ;; search and replace + ;; feature in placeholder \@. + (string-match + "\\\\@/\\(.*\\)/\\(\\(?99:.*\\)\\\\#\\)/" + rep) + (replace-regexp-in-string + (match-string 1 rep) + (concat (match-string 99 rep) + (format "%03d" (1+ count))) + target)) + ;; Incremental replacement + ;; before or after \@. + ((and (string-match-p "\\\\#" rep) + (string-match "\\\\@" rep)) + (replace-regexp-in-string + "\\\\#" (format "%03d" (1+ count)) + (replace-match target t t rep))) + ;; Simple incremental replacement. + ((string-match "\\\\#" rep) + (replace-match + (format "%03d" (1+ count)) t t rep)) + ;; Substring replacement in placeholder. + ((string-match + "\\\\@:\\([0-9]*\\):\\([0-9]*\\)" rep) + (replace-match (substring + target + (string-to-number + (match-string 1 rep)) + (pcase (match-string 2 rep) + ((pred (string= "")) + (length target)) + (res (string-to-number res)))) + t t rep)) + ;; Search and replace in + ;; placeholder. Doesn't + ;; handle incremental here. + ((string-match "\\\\@/\\(.*\\)/\\(.*\\)/" rep) + (replace-match (replace-regexp-in-string + (match-string 1 rep) + (match-string 2 rep) + target t) + t t rep)) + ;; Simple replacement by placeholder. + ((string-match "\\\\@" rep) + (replace-match target t t rep)) + ;; Replacement with + ;; upcase, downcase or + ;; capitalized text. + ((string= rep "%u") #'upcase) + ((string= rep "%d") #'downcase) + ((string= rep "%c") #'capitalize) + ;; Simple replacement with + ;; whole replacement regexp. + (t rep))) + (helm-basename old) t nil subexp)) + ;; If `regexp' is not matched in `old' + ;; `replace-regexp-in-string' will + ;; return `old' unmodified. + unless (string= old new) + do (progn + (when (file-exists-p new) + (setq new (concat (file-name-sans-extension new) + (format "(%s)" count) + (file-name-extension new t)))) + (unless (string= query "!") + (setq query (helm-read-answer (format + "Replace `%s' by `%s' [!,y,n,q]" + old new) + '("y" "n" "!" "q")))) + (when (string= query "q") + (cl-return (message "Operation aborted"))) + (unless (string= query "n") + (rename-file old new) + (cl-incf count))) + finally (message "%d Files renamed" count)))) + ;; This fix the emacs bug where "Emacs-Lisp:" is sent + ;; in minibuffer (not the echo area). + (sit-for 0.1) + (with-current-buffer (window-buffer (minibuffer-window)) + (delete-minibuffer-contents))) + +(defun helm-ff--prepare-str-with-regexp (str &optional rep1 rep2) + ;; This is used in `helm-ff-query-replace-on-filenames' to prepare + ;; STR when REGEXP is specified as substring e.g %:1:3 in this case + ;; substring from 1 to 3 in STR will be enclosed with parenthesis to + ;; match this substring as a subexp e.g %:1:3 on string "emacs" will + ;; be replaced by "e\\(ma\\)cs" using subexp 1 like this: + ;; (helm--replace-regexp-in-buffer-string "e\\(ma\\)cs" "fo" "emacs" nil t 1) + ;; => "efocs" + ;; ^^ + ;; Where "1" and "3" will be strings extracted with match-string + ;; from regexp and refered respectively in this function as REP1 and + ;; REP2. + (let* ((from (or (and rep1 (string-to-number rep1)) 0)) + (to (or (and rep2 (string-to-number rep2)) (length str))) + (subexp (concat "\\(" (regexp-quote (substring str from to)) "\\)")) + (before-str (unless (zerop from) + (regexp-quote (substring str 0 from)))) + (after-str (unless (= to (length str)) + (regexp-quote (substring str to (length str)))))) + (concat before-str subexp after-str))) + +;; The action. +(defun helm-ff-query-replace-fnames-on-marked (_candidate) + (let ((marked (helm-marked-candidates :with-wildcard t))) + (helm-ff-query-replace-on-filenames marked))) + +;; The command for `helm-find-files-map'. +(defun helm-ff-run-query-replace-fnames-on-marked () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-query-replace-fnames-on-marked))) +(put 'helm-ff-run-query-replace-fnames-on-marked 'helm-only t) + +(defun helm-ff-query-replace (_candidate) + (let ((bufs (cl-loop for f in (helm-marked-candidates :with-wildcard t) + collect (buffer-name (find-file-noselect f))))) + (helm-buffer-query-replace-1 nil bufs))) + +(defun helm-ff-query-replace-regexp (_candidate) + (let ((bufs (cl-loop for f in (helm-marked-candidates :with-wildcard t) + collect (buffer-name (find-file-noselect f))))) + (helm-buffer-query-replace-1 'regexp bufs))) + +(defun helm-ff-run-query-replace () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-query-replace))) +(put 'helm-ff-run-query-replace 'helm-only t) + +(defun helm-ff-run-query-replace-regexp () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-query-replace-regexp))) +(put 'helm-ff-run-query-replace-regexp 'helm-only t) + +(defun helm-ff-toggle-auto-update (_candidate) + (if helm-ff--deleting-char-backward + (progn + (message "[Auto expansion disabled]") + (sit-for 1) (message nil) + (setq helm-ff--auto-update-state nil)) + (setq helm-ff-auto-update-flag (not helm-ff-auto-update-flag)) + (setq helm-ff--auto-update-state helm-ff-auto-update-flag) + (message "[Auto expansion %s]" + (if helm-ff-auto-update-flag "enabled" "disabled")))) + +(defun helm-ff-run-toggle-auto-update () + (interactive) + (with-helm-alive-p + (helm-attrset 'toggle-auto-update '(helm-ff-toggle-auto-update . never-split)) + (helm-execute-persistent-action 'toggle-auto-update))) +(put 'helm-ff-run-toggle-auto-update 'helm-only t) + +(defun helm-ff-delete-char-backward () + "Disable helm find files auto update and delete char backward." + (interactive) + (with-helm-alive-p + (setq helm-ff-auto-update-flag nil) + (setq helm-ff--deleting-char-backward t) + (call-interactively + (lookup-key (current-global-map) + (read-kbd-macro "DEL"))) + (helm--update-header-line))) +(put 'helm-ff-delete-char-backward 'helm-only t) + +(defun helm-ff-delete-char-backward--exit-fn () + (setq helm-ff-auto-update-flag helm-ff--auto-update-state) + (setq helm-ff--deleting-char-backward nil)) + +(defun helm-ff-RET-1 (&optional must-match) + "Used for RET action in `helm-find-files'. +See `helm-ff-RET' for details. +If MUST-MATCH is specified exit with +`helm-confirm-and-exit-minibuffer' which handle must-match mechanism." + (let* ((cands (helm-marked-candidates)) + (sel (car cands))) + (cl-assert sel nil "Trying to exit with no candidates") + (if (and (not (cdr cands)) + (file-directory-p sel) + (not (string= "." (helm-basename sel)))) + (helm-execute-persistent-action) + (if must-match + (helm-confirm-and-exit-minibuffer) + (helm-maybe-exit-minibuffer))))) + +(defun helm-ff-RET () + "Default action for RET in `helm-find-files'. + +Behave differently depending of `helm-selection': + +- candidate basename is \".\" => open it in dired. +- candidate is a directory => expand it. +- candidate is a file => open it. +- marked candidates (1+) => open them with default action." + (interactive) + (helm-ff-RET-1)) + +(defun helm-ff-RET-must-match () + "Same as `helm-ff-RET' but used in must-match map." + (interactive) + (helm-ff-RET-1 t)) + +(defun helm-ff-run-grep () + "Run Grep action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-grep))) +(put 'helm-ff-run-grep 'helm-only t) + +(defun helm-ff-run-git-grep () + "Run git-grep action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-git-grep))) +(put 'helm-ff-run-git-grep 'helm-only t) + +(defun helm-ff-run-grep-ag () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-ag))) +(put 'helm-ff-run-grep-ag 'helm-only t) + +(defun helm-ff-run-pdfgrep () + "Run Pdfgrep action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-pdfgrep))) +(put 'helm-ff-run-pdfgrep 'helm-only t) + +(defun helm-ff-run-zgrep () + "Run Grep action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-zgrep))) +(put 'helm-ff-run-zgrep 'helm-only t) + +(defun helm-ff-run-copy-file () + "Run Copy file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-copy))) +(put 'helm-ff-run-copy-file 'helm-only t) + +(defun helm-ff-run-rename-file () + "Run Rename file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-rename))) +(put 'helm-ff-run-rename-file 'helm-only t) + +(defun helm-ff-run-byte-compile-file () + "Run Byte compile file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-byte-compile))) +(put 'helm-ff-run-byte-compile-file 'helm-only t) + +(defun helm-ff-run-load-file () + "Run Load file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-load-files))) +(put 'helm-ff-run-load-file 'helm-only t) + +(defun helm-ff-run-eshell-command-on-file () + "Run eshell command on file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action + 'helm-find-files-eshell-command-on-file))) +(put 'helm-ff-run-eshell-command-on-file 'helm-only t) + +(defun helm-ff-run-ediff-file () + "Run Ediff file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-ediff-files))) +(put 'helm-ff-run-ediff-file 'helm-only t) + +(defun helm-ff-run-ediff-merge-file () + "Run Ediff merge file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action + 'helm-find-files-ediff-merge-files))) +(put 'helm-ff-run-ediff-merge-file 'helm-only t) + +(defun helm-ff-run-symlink-file () + "Run Symlink file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-symlink))) +(put 'helm-ff-run-symlink-file 'helm-only t) + +(defun helm-ff-run-relsymlink-file () + "Run Symlink file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-relsymlink))) +(put 'helm-ff-run-relsymlink-file 'helm-only t) + +(defun helm-ff-run-hardlink-file () + "Run Hardlink file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-hardlink))) +(put 'helm-ff-run-hardlink-file 'helm-only t) + +(defun helm-ff-delete-files (candidate) + "Delete files default action." + (funcall helm-ff-delete-files-function candidate)) + +(defun helm-ff-run-delete-file () + "Run Delete file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action #'helm-ff-delete-files))) +(put 'helm-ff-run-delete-file 'helm-only t) + +(defun helm-ff-run-complete-fn-at-point () + "Run complete file name action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action + 'helm-insert-file-name-completion-at-point))) +(put 'helm-ff-run-complete-fn-at-point 'helm-only t) + +(defun helm-ff-run-switch-to-eshell () + "Run switch to eshell action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-switch-to-eshell))) +(put 'helm-ff-run-switch-to-eshell 'helm-only t) + +(defun helm-ff-run-switch-other-window () + "Run switch to other window action from `helm-source-find-files'. +When a prefix arg is provided, split is done vertically." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-files-other-window))) +(put 'helm-ff-run-switch-other-window 'helm-only t) + +(defun helm-ff-run-switch-other-frame () + "Run switch to other frame action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'find-file-other-frame))) +(put 'helm-ff-run-switch-other-frame 'helm-only t) + +(defun helm-ff-run-open-file-externally () + "Run open file externally command action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-open-file-externally))) +(put 'helm-ff-run-open-file-externally 'helm-only t) + +(defun helm-ff-run-open-file-with-default-tool () + "Run open file externally command action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-open-file-with-default-tool))) +(put 'helm-ff-run-open-file-with-default-tool 'helm-only t) + +(defun helm-ff-locate (candidate) + "Locate action function for `helm-find-files'." + (helm-locate-set-command) + (let ((default (concat (helm-basename + (expand-file-name + candidate + helm-ff-default-directory)) + (unless (or + ;; "-b" is already added when fuzzy matching. + helm-locate-fuzzy-match + ;; The locate '-b' option doesn't exists + ;; in everything (es). + (and (eq system-type 'windows-nt) + (string-match "^es" helm-locate-command))) + " -b")))) + (helm-locate-1 helm-current-prefix-arg nil 'from-ff default))) + +(defun helm-ff-run-locate () + "Run locate action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-locate))) +(put 'helm-ff-run-locate 'helm-only t) + +(defun helm-files-insert-as-org-link (candidate) + (insert (format "[[%s][]]" candidate)) + (goto-char (- (point) 2))) + +(defun helm-ff-run-insert-org-link () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-files-insert-as-org-link))) +(put 'helm-ff-run-insert-org-link 'helm-only t) + +(defun helm-ff-run-find-file-as-root () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-find-file-as-root))) +(put 'helm-ff-run-find-file-as-root 'helm-only t) + +(defun helm-ff-run-find-alternate-file () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'find-alternate-file))) +(put 'helm-ff-run-find-alternate-file 'helm-only t) + +(defun helm-ff-run-mail-attach-files () + "Run mail attach files command action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-mail-attach-files))) +(put 'helm-ff-run-mail-attach-files 'helm-only t) + +(defun helm-ff-run-etags () + "Run Etags command action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-etags-select))) +(put 'helm-ff-run-etags 'helm-only t) + +(defvar lpr-printer-switch) +(defun helm-ff-print (_candidate) + "Print marked files. + +You may to set in order +variables `lpr-command',`lpr-switches' and/or `printer-name', +but with no settings helm should detect your printer(s) and +print with the default `lpr' settings. + +NOTE: DO NOT set the \"-P\" flag in `lpr-switches', if you really +have to modify this, do it in `lpr-printer-switch'. + +Same as `dired-do-print' but for helm." + (require 'lpr) + (when (or helm-current-prefix-arg + (not helm-ff-printer-list)) + (setq helm-ff-printer-list + (helm-ff-find-printers))) + (let* ((file-list (helm-marked-candidates :with-wildcard t)) + (len (length file-list)) + (printer-name (if helm-ff-printer-list + (helm-comp-read + "Printer: " helm-ff-printer-list) + printer-name)) + (lpr-switches + (if (and (stringp printer-name) + (string< "" printer-name)) + (cons (concat lpr-printer-switch printer-name) + lpr-switches) + lpr-switches)) + (command (helm-read-string + (format "Print *%s File(s):\n%s with: " + len + (mapconcat + (lambda (f) (format "- %s\n" f)) + file-list "")) + (when (and lpr-command lpr-switches) + (mapconcat 'identity + (cons lpr-command + (if (stringp lpr-switches) + (list lpr-switches) + lpr-switches)) + " ")))) + (file-args (mapconcat (lambda (x) + (format "'%s'" x)) + file-list " ")) + (cmd-line (concat command " " file-args))) + (if command + (start-process-shell-command "helm-print" nil cmd-line) + (error "Error: Please verify your printer settings in Emacs.")))) + +(defun helm-ff-run-print-file () + "Run Print file action from `helm-source-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-print))) +(put 'helm-ff-run-print-file 'helm-only t) + +(defun helm-ff-checksum (file) + "Calculate the checksum of FILE. +The checksum is copied to kill-ring." + (cl-assert (file-regular-p file) + nil "`%s' is not a regular file" file) + (let ((algo (intern (helm-comp-read + "Algorithm: " + '(md5 sha1 sha224 sha256 sha384 sha512)))) + (bn (helm-basename file))) + (message "Calculating %s checksum for %s..." algo bn) + (async-let ((sum (with-temp-buffer + (insert-file-contents-literally file) + (secure-hash algo (current-buffer))))) + (kill-new sum) + (message "Calculating %s checksum for `%s' done and copied to kill-ring" algo bn)))) + +(defun helm-ff-toggle-basename (_candidate) + (with-helm-buffer + (setq helm-ff-transformer-show-only-basename + (not helm-ff-transformer-show-only-basename)) + (let* ((cand (helm-get-selection nil t)) + (target (if helm-ff-transformer-show-only-basename + (helm-basename cand) cand))) + (helm-force-update (concat (regexp-quote target) "$"))))) + +(defun helm-ff-run-toggle-basename () + (interactive) + (with-helm-alive-p + (unless (helm-empty-source-p) + (helm-ff-toggle-basename nil)))) +(put 'helm-ff-run-toggle-basename 'helm-only t) + +(defun helm-reduce-file-name (fname level) + "Reduce FNAME by number LEVEL from end." + ;; This version comes from issue #2004 (UNC paths) and should fix it. + (while (> level 0) + (unless (or (string= fname "/") + (string= (file-remote-p fname 'localname) "/")) + (setq fname (expand-file-name + (concat (expand-file-name fname) "/../")))) + (setq level (1- level))) + fname) + +(defvar helm-find-files--level-tree nil) +(defvar helm-find-files--level-tree-iterator nil) +(defun helm-find-files-up-one-level (arg) + "Go up one level like unix command `cd ..'. +If prefix numeric arg is given go ARG level up." + (interactive "p") + (with-helm-alive-p + (let ((src (helm-get-current-source))) + (when (and (helm-file-completion-source-p src) + (not (helm-ff--invalid-tramp-name-p))) + (with-helm-window + (when (helm-follow-mode-p) + (helm-follow-mode -1) (message nil))) + ;; When going up one level we want to be at the line + ;; corresponding to actual directory, so store this info + ;; in `helm-ff-last-expanded'. + (let ((cur-cand (helm-get-selection nil nil src)) + (new-pattern (helm-reduce-file-name helm-pattern arg))) + ;; Ensure visibility on all candidates for preselection. + (helm-attrset 'candidate-number-limit + (if helm-ff-up-one-level-preselect + (max (gethash new-pattern + helm-ff--directory-files-hash + helm-ff-candidate-number-limit) + helm-ff-candidate-number-limit) + helm-ff-candidate-number-limit)) + (cond ((file-directory-p helm-pattern) + (setq helm-ff-last-expanded helm-ff-default-directory)) + ((file-exists-p helm-pattern) + (setq helm-ff-last-expanded helm-pattern)) + ((and cur-cand (file-exists-p cur-cand)) + (setq helm-ff-last-expanded cur-cand))) + (unless helm-find-files--level-tree + (setq helm-find-files--level-tree + (cons helm-ff-default-directory + helm-find-files--level-tree))) + (setq helm-find-files--level-tree-iterator nil) + (push new-pattern helm-find-files--level-tree) + (helm-set-pattern new-pattern helm-suspend-update-flag) + (with-helm-after-update-hook (helm-ff-retrieve-last-expanded))))))) +(put 'helm-find-files-up-one-level 'helm-only t) + +(defun helm-find-files-down-last-level () + "Retrieve previous paths reached by `C-l' in helm-find-files." + (interactive) + (with-helm-alive-p + (when (and (helm-file-completion-source-p) + (not (helm-ff--invalid-tramp-name-p))) + (unless helm-find-files--level-tree-iterator + (setq helm-find-files--level-tree-iterator + (helm-iter-list (cdr helm-find-files--level-tree)))) + (setq helm-find-files--level-tree nil) + (helm-aif (helm-iter-next helm-find-files--level-tree-iterator) + (helm-set-pattern it) + (setq helm-find-files--level-tree-iterator nil))))) +(put 'helm-find-files-down-last-level 'helm-only t) + +(defun helm-find-files--reset-level-tree () + (setq helm-find-files--level-tree-iterator nil + helm-find-files--level-tree nil)) + +(add-hook 'helm-cleanup-hook 'helm-find-files--reset-level-tree) +(add-hook 'post-self-insert-hook 'helm-find-files--reset-level-tree) +(add-hook 'helm-after-persistent-action-hook 'helm-find-files--reset-level-tree) + +(defun helm-ff-retrieve-last-expanded () + "Move overlay to last visited directory `helm-ff-last-expanded'. +This happen after using `helm-find-files-up-one-level', +or hitting C-j on \"..\"." + (when helm-ff-last-expanded + (let ((presel (if helm-ff-transformer-show-only-basename + (helm-basename + (directory-file-name helm-ff-last-expanded)) + (directory-file-name helm-ff-last-expanded)))) + (with-helm-window + (when (re-search-forward (concat "^" (regexp-quote presel) "$") nil t) + (forward-line 0) + (helm-mark-current-line))) + (setq helm-ff-last-expanded nil)))) + +(defun helm-ff-move-to-first-real-candidate () + "When candidate is an incomplete file name move to first real candidate." + (let* ((src (helm-get-current-source)) + (name (assoc-default 'name src)) + ;; Ensure `helm-file-completion-source-p' returns nil on + ;; `helm-read-file-name' history. + minibuffer-completing-file-name) + (helm-aif (and (helm-file-completion-source-p src) + (not (helm-empty-source-p)) + ;; Prevent dired commands moving to first real + ;; (Issue #910). + (or (memq (intern-soft name) + helm-ff-goto-first-real-dired-exceptions) + (not (string-match "\\`[Dd]ired-" name))) + helm-ff--move-to-first-real-candidate + (helm-get-selection nil nil src)) + (unless (or (not (stringp it)) + (and (string-match helm-tramp-file-name-regexp it) + (not (file-remote-p it nil t))) + (file-exists-p it)) + (helm-next-line))))) + +;;; Auto-update - helm-find-files auto expansion of directories. +;; +;; +(defun helm-ff-update-when-only-one-matched () + "Expand to directory when sole completion. +When only one candidate is remaining and it is a directory, +expand to this directory. +This happen only when `helm-ff-auto-update-flag' is non--nil +or when `helm-pattern' is equal to \"~/\"." + (let ((src (helm-get-current-source))) + (when (and (helm-file-completion-source-p src) + (not (get-buffer-window helm-action-buffer 'visible)) + (not (helm-ff--invalid-tramp-name-p)) + (not (string-match-p "\\`[.]\\{2\\}[^/]+" + (helm-basename helm-pattern)))) + (with-helm-buffer + (let* ((history-p (string= (assoc-default 'name src) + "Read File Name History")) + (pat (if (string-match helm-tramp-file-name-regexp + helm-pattern) + (helm-ff--create-tramp-name helm-pattern) + helm-pattern)) + (completed-p (string= (file-name-as-directory + (expand-file-name + (substitute-in-file-name pat))) + helm-ff-default-directory)) + (candnum (helm-get-candidate-number)) + (lt2-p (and (<= candnum 2) + (>= (string-width (helm-basename helm-pattern)) 2))) + (cur-cand (prog2 + (unless (or completed-p + (file-exists-p pat) + history-p (null lt2-p)) + ;; Only one non--existing candidate + ;; and one directory candidate, move to it, + ;; but not when renaming, copying etc..., + ;; so for this use + ;; `helm-ff-move-to-first-real-candidate' + ;; instead of `helm-next-line' (Issue #910). + (helm-ff-move-to-first-real-candidate)) + (helm-get-selection nil nil src)))) + (when (and (or (and helm-ff-auto-update-flag + (null helm-ff--deleting-char-backward) + ;; Issue #295 + ;; File predicates are returning t + ;; with paths like //home/foo. + ;; So check it is not the case by regexp + ;; to allow user to do C-a / to start e.g + ;; entering a tramp method e.g /sudo::. + (not (string-match "\\`//" helm-pattern)) + (not (eq last-command 'helm-yank-text-at-point))) + ;; Fix issue #542. + (string= helm-pattern "~/") + ;; Only one remaining directory, expand it. + (and (= candnum 1) + helm-ff--auto-update-state + (file-accessible-directory-p pat) + (null helm-ff--deleting-char-backward))) + (or + ;; Only one candidate remaining + ;; and at least 2 char in basename. + lt2-p + ;; Already completed. + completed-p) + (not history-p) ; Don't try to auto complete in history. + (stringp cur-cand) + (file-accessible-directory-p cur-cand)) + (if (and (not (helm-dir-is-dot cur-cand)) ; [1] + ;; Maybe we are here because completed-p is true + ;; but check this again to be sure. (Windows fix) + (<= candnum 2)) ; [2] + ;; If after going to next line the candidate + ;; is not one of "." or ".." [1] + ;; and only one candidate is remaining [2], + ;; assume candidate is a new directory to expand, and do it. + (helm-set-pattern (file-name-as-directory cur-cand)) + ;; The candidate is one of "." or ".." + ;; that mean we have entered the last letter of the directory name + ;; in prompt, so expansion is already done, just add the "/" at end + ;; of name unless helm-pattern ends with "." + ;; (i.e we are writing something starting with ".") + (unless (string-match "\\`.*[.]\\{1\\}\\'" helm-pattern) + (helm-set-pattern + ;; Need to expand-file-name to avoid e.g /ssh:host:./ in prompt. + (expand-file-name (file-name-as-directory helm-pattern))))) + (helm-check-minibuffer-input))))))) + +(defun helm-ff-auto-expand-to-home-or-root () + "Allow expanding to home/user directory or root or text yanked after pattern." + (when (and (helm-file-completion-source-p) + (with-current-buffer (window-buffer (minibuffer-window)) (eolp)) + (not (string-match helm-ff-url-regexp helm-pattern))) + (cond ((and (not (file-remote-p helm-pattern)) + (null (file-exists-p helm-pattern)) + (string-match-p + "\\`\\([.]\\|\\s-\\)\\{2\\}[^/]+" + (helm-basename helm-pattern)) + (string-match-p "/\\'" helm-pattern)) + (helm-ff-recursive-dirs helm-pattern) + (with-helm-window (helm-check-minibuffer-input))) + ((string-match + "\\(?:\\`~/\\)\\|/?\\$.*/\\|/\\./\\|/\\.\\./\\|/~.*/\\|//\\|\\(/[[:alpha:]]:/\\|\\s\\+\\)" + helm-pattern) + (let* ((match (match-string 0 helm-pattern)) + (input (cond ((string= match "/./") + (expand-file-name default-directory)) + ((string= helm-pattern "/../") "/") + ((string-match-p "\\`/\\$" match) + (let ((sub (substitute-in-file-name match))) + (if (file-directory-p sub) + sub (replace-regexp-in-string "/\\'" "" sub)))) + (t (helm-ff--expand-substitued-pattern helm-pattern))))) + ;; `file-directory-p' returns t on "/home/me/." (issue #1844). + (if (and (file-directory-p input) + (not (string-match-p "[^.]\\.\\'" input))) + (setq helm-ff-default-directory + (setq input (file-name-as-directory input))) + (setq helm-ff-default-directory (file-name-as-directory + (file-name-directory input)))) + (with-helm-window + (helm-set-pattern input) + (helm-check-minibuffer-input))))))) + +(defun helm-ff--expand-file-name-no-dot (name &optional directory) + "Prevent expanding \"/home/user/.\" to \"/home/user\"." + ;; Issue #1844 - If user enter "~/." to type an hidden filename + ;; don't expand to /home/him e.g. + ;; (expand-file-name "~/.") =>"/home/thierry" + ;; (helm-ff--expand-substitued-pattern "~/.") =>"/home/thierry/." + (concat (expand-file-name name directory) + (and (string-match "[^.]\\.\\'" name) "/."))) + +(defun helm-ff--expand-substitued-pattern (pattern) + ;; [Windows] On UNC paths "/" expand to current machine, + ;; so use the root of current Drive. (i.e "C:/") + (let* ((directory (and (memq system-type '(windows-nt ms-dos)) + (getenv "SystemDrive"))) + ;; On Windows use a simple call to `expand-file-name' to + ;; avoid Issue #2004. + (expand-fn (if directory + #'expand-file-name + #'helm-ff--expand-file-name-no-dot))) + (funcall expand-fn (helm-substitute-in-filename pattern) + ;; directory is nil on Nix. + directory))) + +(defun helm-substitute-in-filename (fname) + "Substitute all parts of FNAME from start up to \"~/\" or \"/\". +On windows system substitute from start up to \"/[[:lower:]]:/\". +This function is needed for `helm-ff-auto-expand-to-home-or-root' +and should be used carefully elsewhere, or not at all, using +`substitute-in-file-name' instead." + (cond ((and helm--url-regexp + (string-match-p helm--url-regexp fname)) + fname) + ((and (file-remote-p fname) + helm-substitute-in-filename-stay-on-remote) + (let ((sub (substitute-in-file-name fname))) + (if (file-directory-p sub) + sub (replace-regexp-in-string "/\\'" "" sub)))) + (t + (with-temp-buffer + (insert fname) + (goto-char (point-min)) + (when (memq system-type '(windows-nt ms-dos)) + (skip-chars-forward "/")) ;; Avoid infloop in UNC paths Issue #424 + (if (re-search-forward "~.*/?\\|//\\|/[[:alpha:]]:/" nil t) + (let ((match (match-string 0))) + (goto-char (if (or (string= match "//") + (string-match-p "/[[:alpha:]]:/" match)) + (1+ (match-beginning 0)) + (match-beginning 0))) + (buffer-substring-no-properties (point) (point-at-eol))) + fname))))) + +(defun helm-point-file-in-dired (file) + "Put point on filename FILE in dired buffer." + (unless (and helm--url-regexp + (string-match-p helm--url-regexp file)) + (let ((target (expand-file-name (helm-substitute-in-filename file)))) + (dired (file-name-directory target)) + (dired-goto-file target)))) + +(defun helm-marked-files-in-dired (_candidate) + "Open a dired buffer with only marked files. + +With a prefix arg toggle dired buffer to wdired mode." + (advice-add 'wdired-finish-edit :override #'helm--advice-wdired-finish-edit) + (advice-add 'wdired-get-filename :override #'helm--advice-wdired-get-filename) + (let* ((marked (helm-marked-candidates :with-wildcard t)) + (current (car marked))) + (unless (and helm--url-regexp + (string-match-p helm--url-regexp current)) + (let ((target (expand-file-name (helm-substitute-in-filename current)))) + (dired (cons helm-ff-default-directory marked)) + (dired-goto-file target) + (when (or helm-current-prefix-arg current-prefix-arg) + (call-interactively 'wdired-change-to-wdired-mode)))))) + +(defun helm-ff-run-marked-files-in-dired () + "Execute `helm-marked-files-in-dired' interactively." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-marked-files-in-dired))) +(put 'helm-ff-run-marked-files-in-dired 'helm-only t) + +(defun helm-ff--create-tramp-name (fname) + "Build filename from `helm-pattern' like /su:: or /sudo::." + ;; `tramp-make-tramp-file-name' takes 7 args on emacs-26 whereas it + ;; takes only 5 args in emacs-24/25. + (apply #'tramp-make-tramp-file-name + ;; `tramp-dissect-file-name' returns a list in emacs-26 + ;; whereas in 24.5 it returns a vector, thus the car is a + ;; symbol (`tramp-file-name') which is not needed as argument + ;; for `tramp-make-tramp-file-name' so transform the cdr in + ;; vector, and for 24.5 use directly the returned value. + (cl-loop with v = (helm-ff--tramp-cons-or-vector + (tramp-dissect-file-name fname)) + for i across v collect i))) + +(defun helm-ff--tramp-cons-or-vector (vector-or-cons) + "Return VECTOR-OR-CONS as a vector." + (pcase vector-or-cons + (`(,_l . ,ll) (vconcat ll)) + ((and vec (pred vectorp)) vec))) + +(defun helm-ff--get-tramp-methods () + "Returns a list of the car of `tramp-methods'." + (or helm-ff--tramp-methods + (setq helm-ff--tramp-methods (mapcar 'car tramp-methods)))) + +(defun helm-ff--previous-mh-tramp-method (str) + (save-match-data + (with-temp-buffer + (insert str) + (when (re-search-backward + (concat "\\([|]\\)\\(" + (mapconcat 'identity (helm-ff--get-tramp-methods) "\\|") + "\\):") + nil t) + (list + (buffer-substring-no-properties (point-at-bol) (match-beginning 2)) + (buffer-substring-no-properties (match-beginning 2) (match-end 2))))))) + +(defun helm-ff--get-host-from-tramp-invalid-fname (fname) + "Extract hostname from an incomplete tramp file name. +Return nil on valid file name remote or not." + ;; Check first if whole file is remote (file-remote-p is inefficient + ;; in this case) otherwise we are matching e.g. /home/you/ssh:foo/ + ;; which is not a remote name. + ;; FIXME this will not work with a directory or a file named like + ;; "ssh:foo" and located at root (/) but it seems there is no real + ;; solution apart disabling tramp-mode when a file/dir located at / + ;; is matching helm-tramp-file-name-regexp; This would prevent usage + ;; of tramp if one have such a directory at / (who would want to + ;; have such a dir at / ???) See emacs-bug#31489. + (when (string-match-p helm-tramp-file-name-regexp fname) + (let* ((bn (helm-basename fname)) + (bd (replace-regexp-in-string (regexp-quote bn) "" fname)) + (split (split-string bn ":" t)) + (meth (car (member (car split) + (helm-ff--get-tramp-methods))))) + (and meth (string= bd "/") (car (last split)))))) + +(cl-defun helm-ff--tramp-hostnames (&optional (pattern helm-pattern)) + "Get a list of hosts for tramp method found in `helm-pattern'. +Argument PATTERN default to `helm-pattern', it is here only for debugging +purpose." + (when (string-match helm-tramp-file-name-regexp pattern) + (let* ((mh-method (helm-ff--previous-mh-tramp-method pattern)) + (method (or (cadr mh-method) (match-string 1 pattern))) + (current-mh-host (helm-aif (and mh-method + (helm-ff--get-host-from-tramp-invalid-fname pattern)) + (concat (car mh-method) method ":" + (car (split-string it "|" t))))) + (all-methods (helm-ff--get-tramp-methods)) + (comps (cl-loop for (f . h) in (tramp-get-completion-function method) + append (cl-loop for e in (funcall f (car h)) + for host = (and (consp e) (cadr e)) + when (and host (not (member host all-methods))) + collect (concat (or (car mh-method) "/") + method ":" host))))) + (helm-fast-remove-dups + (delq nil (cons current-mh-host comps)) + :test 'equal)))) + +(defun helm-ff-before-action-hook-fn () + "Exit helm when user try to execute action on an invalid tramp fname." + (let* ((src (helm-get-current-source)) + (cand (helm-get-selection nil nil src))) + (when (and (helm-file-completion-source-p src) + (stringp cand) + (helm-ff--invalid-tramp-name-p cand) ; Check candidate. + (helm-ff--invalid-tramp-name-p)) ; check helm-pattern. + (error "Error: Unknown file or directory `%s'" cand)))) +(add-hook 'helm-before-action-hook 'helm-ff-before-action-hook-fn) + +(cl-defun helm-ff--invalid-tramp-name-p (&optional (pattern helm-pattern)) + "Return non--nil when PATTERN is an invalid tramp filename." + (string= (helm-ff-set-pattern pattern) + "Invalid tramp file name")) + +(defun helm-ff--tramp-postfixed-p (str) + (let (result) + (save-match-data + (with-temp-buffer + (save-excursion (insert str)) + (helm-awhile (search-forward ":" nil t) + (if (save-excursion + (forward-char -1) + (looking-back + (mapconcat 'identity (helm-ff--get-tramp-methods) "\\|") + (point-at-bol))) + (setq result nil) + (setq result it))))) + result)) + +(defun helm-ff-set-pattern (pattern) + "Handle tramp filenames in `helm-pattern'." + (let* ((methods (helm-ff--get-tramp-methods)) + ;; Returns the position of last ":" entered. + (postfixed (helm-ff--tramp-postfixed-p pattern)) + (reg "\\`/\\([^[/:]+\\|[^/]+]\\):.*:") + cur-method tramp-name) + ;; In some rare cases tramp can return a nil input, + ;; so be sure pattern is a string for safety (Issue #476). + (unless pattern (setq pattern "")) + (cond ((string-match helm-ff-url-regexp pattern) pattern) + ((string-match "\\`\\$" pattern) + (substitute-in-file-name pattern)) + ((string= pattern "") "") + ((string-match "\\`[.]\\{1,2\\}/\\'" pattern) + (expand-file-name pattern)) + ;; Directories ending by a dot (issue #1940) + ((string-match "[^/][.]/\\'" pattern) + (expand-file-name pattern)) + ((string-match ".*\\(~?/?[.]\\{1\\}/\\)\\'" pattern) + (expand-file-name default-directory)) + ((string-match ".*\\(~//\\|//\\)\\'" pattern) + (expand-file-name "/")) ; Expand to "/" or "c:/" + ((string-match "\\`\\(~/\\|.*/~/\\)\\'" pattern) + (expand-file-name "~/")) + ((string-match "\\`~/" pattern) + (expand-file-name pattern)) + ;; Match "/method:maybe_hostname:~" + ((and (string-match (concat reg "~") pattern) + postfixed + (setq cur-method (match-string 1 pattern)) + (member cur-method methods)) + (setq tramp-name (expand-file-name + (helm-ff--create-tramp-name + (match-string 0 pattern)))) + (replace-match tramp-name nil t pattern)) + ;; Match "/method:maybe_hostname:" + ((and (string-match reg pattern) + postfixed + (setq cur-method (match-string 1 pattern)) + (member cur-method methods)) + (setq tramp-name (helm-ff--create-tramp-name + (match-string 0 pattern))) + (replace-match tramp-name nil t pattern)) + ;; Match "/hostname:" + ((and (string-match helm-tramp-file-name-regexp pattern) + postfixed + (setq cur-method (match-string 1 pattern)) + (and cur-method (not (member cur-method methods)))) + (setq tramp-name (helm-ff--create-tramp-name + (match-string 0 pattern))) + (replace-match tramp-name nil t pattern)) + ;; Match "/method:" in this case don't try to connect. + ((and (null postfixed) + (string-match helm-tramp-file-name-regexp pattern) + (member (match-string 1 pattern) methods)) + "Invalid tramp file name") ; Write in helm-buffer. + ;; Return PATTERN unchanged. + (t pattern)))) + +(defun helm-find-files-get-candidates (&optional require-match) + "Create candidate list for `helm-source-find-files'." + (let* ((path (helm-ff-set-pattern helm-pattern)) + (dir-p (file-accessible-directory-p path)) + basedir + invalid-basedir + non-essential + (tramp-verbose helm-tramp-verbose)) ; No tramp message when 0. + ;; Tramp check if path is valid without waiting a valid + ;; connection and may send a file-error. + (setq helm--ignore-errors (file-remote-p path)) + (set-text-properties 0 (length path) nil path) + ;; Issue #118 allow creation of newdir+newfile. + (unless (or + ;; A tramp file name not completed. + (string= path "Invalid tramp file name") + ;; An empty pattern + (string= path "") + (and (string-match-p ":\\'" path) + (helm-ff--tramp-postfixed-p path)) + ;; Check if base directory of PATH is valid. + (helm-aif (file-name-directory path) + ;; If PATH is a valid directory IT=PATH, + ;; else IT=basedir of PATH. + (file-directory-p it))) + ;; BASEDIR is invalid, that's mean user is starting + ;; to write a non--existing path in minibuffer + ;; probably to create a 'new_dir' or a 'new_dir+new_file'. + (setq invalid-basedir t)) + ;; Don't set now `helm-pattern' if `path' == "Invalid tramp file name" + ;; like that the actual value (e.g /ssh:) is passed to + ;; `helm-ff--tramp-hostnames'. + (unless (or (string= path "Invalid tramp file name") + invalid-basedir) ; Leave helm-pattern unchanged. + (setq helm-ff-auto-update-flag ; [1] + ;; Unless auto update is disabled start auto updating only + ;; at third char. + (unless (or (null helm-ff--auto-update-state) + ;; But don't enable auto update when + ;; deleting backward. + helm-ff--deleting-char-backward + (and dir-p (not (string-match-p "/\\'" path)))) + (or (>= (length (helm-basename path)) 3) dir-p))) + ;; At this point the tramp connection is triggered. + (helm-log + "Pattern=%S" + (setq helm-pattern (helm-ff--transform-pattern-for-completion path))) + ;; This have to be set after [1] to allow deleting char backward. + (setq basedir (or (helm-aand + (if (and dir-p helm-ff-auto-update-flag) + ;; Add the final "/" to path + ;; when `helm-ff-auto-update-flag' is enabled. + (file-name-as-directory path) + (if (string= path "") + "/" (file-name-directory path))) + (expand-file-name it)) + default-directory)) + (setq helm-ff-default-directory + (if (string= helm-pattern "") + (expand-file-name "/") ; Expand to "/" or "c:/" + ;; If path is an url *default-directory have to be nil. + (unless (or (string-match helm-ff-url-regexp path) + (and helm--url-regexp + (string-match helm--url-regexp path))) + basedir)))) + (when (and (string-match ":\\'" path) + (file-remote-p basedir nil t)) + (setq helm-pattern basedir)) + (cond ((string= path "Invalid tramp file name") + (or (helm-ff--tramp-hostnames) ; Hostnames completion. + (prog2 + ;; `helm-pattern' have not been modified yet. + ;; Set it here to the value of `path' that should be now + ;; "Invalid tramp file name" and set the candidates list + ;; to ("Invalid tramp file name") to make `helm-pattern' + ;; match single candidate "Invalid tramp file name". + (setq helm-pattern path) + ;; "Invalid tramp file name" is now printed + ;; in `helm-buffer'. + (list path)))) + ((or (and (file-regular-p path) + (eq last-repeatable-command 'helm-execute-persistent-action)) + ;; `ffap-url-regexp' don't match until url is complete. + (string-match helm-ff-url-regexp path) + invalid-basedir + (and (not (file-exists-p path)) (string-match "/$" path)) + (and helm--url-regexp (string-match helm--url-regexp path))) + (list path)) + ((string= path "") (helm-ff-directory-files "/")) + ;; Check here if directory is accessible (not working on Windows). + ((and (file-directory-p path) (not (file-readable-p path))) + (list (format "file-error: Opening directory permission denied `%s'" path))) + ;; A fast expansion of PATH is made only if `helm-ff-auto-update-flag' + ;; is enabled. + ((and dir-p helm-ff-auto-update-flag) + (helm-ff-directory-files path)) + (t (append (unless (or require-match + ;; When `helm-ff-auto-update-flag' has been + ;; disabled, whe don't want PATH to be added on top + ;; if it is a directory. + dir-p) + (list path)) + (helm-ff-directory-files basedir)))))) + +(defun helm-list-directory (directory) + "List directory DIRECTORY. + +If DIRECTORY is remote use `helm-list-directory-function' otherwise use +`directory-files'." + (if (file-remote-p directory) + (funcall helm-list-directory-function directory) + (directory-files directory t directory-files-no-dot-files-regexp))) + +(defun helm-list-dir-lisp (directory) + "List DIRECTORY with `file-name-all-completions' as backend. + +Add a `helm-ff-dir' property on each fname ending with \"/\"." + ;; NOTE: `file-name-all-completions' and `directory-files' and most + ;; tramp file handlers don't handle cntrl characters in fnames, so + ;; the displayed files will be plain wrong in this case, even worst + ;; the filenames will be splitted in two or more filenames. + (cl-loop for f in (sort (file-name-all-completions "" directory) + 'string-lessp) + unless (or (string= f "") + (member f '("./" "../")) + ;; Ignore the tramp names from / + ;; completion, e.g. ssh: scp: etc... + (char-equal (aref f (1- (length f))) ?:)) + if (and (helm--dir-name-p f) + (helm--dir-file-name f directory)) + collect (propertize it 'helm-ff-dir t) + else collect (propertize (expand-file-name f directory) + 'helm-ff-file t))) + +(defun helm-list-dir-external (dir) + "List directory DIR with external shell command as backend. + +This function is fast enough to be used for remote files and save the +type of files at the same time in a property for using it later in the +transformer." + (let ((default-directory (file-name-as-directory + (expand-file-name dir)))) + (with-temp-buffer + (when (eq (process-file-shell-command + (format + ;; -A remove dot files, -F append [*=@|/>] at eof + ;; and -Q quote the real filename. If not using -Q, + ;; there is no way to distinguish if foo* is a real + ;; file or if it is foo the executable file so with + ;; -Q we have "foo"* for the executable file foo and + ;; "foo*" for the real file foo. The downside is + ;; that we need an extra step to remove the quotes + ;; at the end which impact performances. + "ls -A -1 -F -b -Q | awk -v dir=%s '{print dir $1}'" + (shell-quote-argument default-directory)) + nil t nil) + 0) + (goto-char (point-min)) + (save-excursion + (while (re-search-forward "[*=@|/>]$" nil t) + ;; A line looks like /home/you/"foo"@ + (helm-acase (match-string 0) + ("*" (replace-match "") + (put-text-property + (point-at-bol) (point-at-eol) 'helm-ff-exe t)) + ("@" (replace-match "") + (put-text-property + (point-at-bol) (point-at-eol) 'helm-ff-sym t)) + ("/" (replace-match "") + (put-text-property + (point-at-bol) (point-at-eol) 'helm-ff-dir t)) + (("=" "|" ">") (replace-match ""))))) + (while (re-search-forward "[\"]" nil t) + (replace-match "")) + (add-text-properties (point-min) (point-max) '(helm-ff-file t)) + (split-string (buffer-string) "\n" t))))) + +(defun helm-ff-directory-files (directory) + "List contents of DIRECTORY. +Argument FULL mean absolute path. +It is same as `directory-files' but always returns the +dotted filename '.' and '..' even on root directories in Windows +systems." + (setq directory (file-name-as-directory + (expand-file-name directory))) + (let* (file-error + (ls (condition-case err + (helm-list-directory directory) + ;; Handle file-error from here for Windows + ;; because predicates like `file-readable-p' and friends + ;; seem broken on emacs for Windows systems (always returns t). + ;; This should never be called on GNU/Linux/Unix + ;; as the error is properly intercepted in + ;; `helm-find-files-get-candidates' by `file-readable-p'. + (file-error + (prog1 + (list (format "%s:%s" + (car err) + (mapconcat 'identity (cdr err) " "))) + (setq file-error t))))) + (dot (concat directory ".")) + (dot2 (concat directory ".."))) + (puthash directory (+ (length ls) 2) helm-ff--directory-files-hash) + (append (and (not file-error) (list dot dot2)) ls))) + +(defun helm-ff-handle-backslash (fname) + ;; Allow creation of filenames containing a backslash. + (cl-loop with bad = '((92 . "")) + for i across fname + if (assq i bad) concat (cdr it) + else concat (string i))) + +(defun helm-ff-fuzzy-matching-p () + (and helm-ff-fuzzy-matching + (not (memq helm-mm-matching-method '(multi1 multi3p))))) + +(defun helm-ff--transform-pattern-for-completion (pattern) + "Maybe return PATTERN with it's basename modified as a regexp. +This happen only when `helm-ff-fuzzy-matching' is enabled. +This provide a similar behavior as `ido-enable-flex-matching'. +See also `helm--mapconcat-pattern'. +If PATTERN is an url returns it unmodified. +When PATTERN contain a space fallback to multi-match. +If basename contain one or more space fallback to multi-match. +If PATTERN is a valid directory name,return PATTERN unchanged." + ;; handle bad filenames containing a backslash (no more needed in + ;; emacs-26, also prevent regexp matching with e.g. "\|"). + ;; (setq pattern (helm-ff-handle-backslash pattern)) + (let ((bn (helm-basename pattern)) + (bd (or (helm-basedir pattern) "")) + ;; Trigger tramp connection with file-directory-p. + (dir-p (file-directory-p pattern)) + (tramp-p (cl-loop for (m . f) in tramp-methods + thereis (string-match m pattern)))) + ;; Always regexp-quote base directory name to handle + ;; crap dirnames such e.g bookmark+ + (cond + ((or (and dir-p tramp-p (string-match ":\\'" pattern)) + (string= pattern "") + (and dir-p (<= (length bn) 2)) + ;; Fix Issue #541 when BD have a subdir similar + ;; to BN, don't switch to match plugin + ;; which will match both. + (and dir-p (string-match (regexp-quote bn) bd))) + ;; Use full PATTERN on e.g "/ssh:host:". + (regexp-quote pattern)) + ;; Prefixing BN with a space call multi-match completion. + ;; This allow showing all files/dirs matching BN (Issue #518). + ;; FIXME: some multi-match methods may not work here. + (dir-p (concat (regexp-quote bd) " " (regexp-quote bn))) + ((or (not (helm-ff-fuzzy-matching-p)) + (string-match "\\s-" bn)) ; Fall back to multi-match. + (concat (regexp-quote bd) bn)) + ((or (string-match "[*][.]?.*" bn) ; Allow entering wilcard. + (string-match "/$" pattern) ; Allow mkdir. + (string-match helm-ff-url-regexp pattern) + (and (string= helm-ff-default-directory "/") tramp-p)) + ;; Don't treat wildcards ("*") as regexp char. + ;; (e.g ./foo/*.el => ./foo/[*].el) + (concat (regexp-quote bd) + (replace-regexp-in-string "[*]" "[*]" bn))) + (t (concat (regexp-quote bd) + (if (>= (length bn) 2) ; wait 2nd char before concating. + (helm--mapconcat-pattern bn) + (concat ".*" (regexp-quote bn)))))))) + +(defun helm-dir-is-dot (dir) + (string-match "\\(?:/\\|\\`\\)\\.\\{1,2\\}\\'" dir)) + +(defun helm-ff-save-history () + "Store the last value of `helm-ff-default-directory' in `helm-ff-history'. +Note that only existing directories are saved here." + (when (and helm-ff-default-directory + (helm-file-completion-source-p) + (file-directory-p helm-ff-default-directory)) + (set-text-properties 0 (length helm-ff-default-directory) + nil helm-ff-default-directory) + (push helm-ff-default-directory helm-ff-history))) +(add-hook 'helm-cleanup-hook 'helm-ff-save-history) + +(defun helm-files-save-file-name-history (&optional force) + "Save marked files to `file-name-history'." + (let* ((src (helm-get-current-source)) + (src-name (assoc-default 'name src))) + (when (or force (helm-file-completion-source-p src) + (member src-name helm-files-save-history-extra-sources)) + (let ((mkd (helm-marked-candidates :with-wildcard t)) + (history-delete-duplicates t)) + (cl-loop for sel in mkd + when (and sel + (stringp sel) + (file-exists-p sel) + (not (file-directory-p sel))) + do + ;; we use `abbreviate-file-name' here because + ;; other parts of Emacs seems to, + ;; and we don't want to introduce duplicates. + (add-to-history 'file-name-history + (abbreviate-file-name sel))))))) +(add-hook 'helm-exit-minibuffer-hook 'helm-files-save-file-name-history) + +(defun helm-ff-valid-symlink-p (file) + (helm-aif (condition-case-unless-debug nil + ;; `file-truename' send error + ;; on cyclic symlinks (Issue #692). + (file-truename file) + (error nil)) + (file-exists-p it))) + +(defun helm-get-default-mode-for-file (filename) + "Return the default mode to open FILENAME." + (let ((mode (cl-loop for (r . m) in auto-mode-alist + thereis (and (string-match r filename) m)))) + (or (and (symbolp mode) mode) "Fundamental"))) + +(defun helm-ff-properties (candidate) + "Show file properties of CANDIDATE in a tooltip or message." + (require 'helm-external) ; For `helm-get-default-program-for-file'. + (helm-aif (helm-file-attributes candidate) + (let* ((all it) + (dired-line (helm-file-attributes + candidate :dired t :human-size t)) + (type (cl-getf all :type)) + (mode-type (cl-getf all :mode-type)) + (owner (cl-getf all :uid)) + (owner-right (cl-getf all :user t)) + (group (cl-getf all :gid)) + (group-right (cl-getf all :group)) + (other-right (cl-getf all :other)) + (size (helm-file-human-size (cl-getf all :size))) + (modif (cl-getf all :modif-time)) + (access (cl-getf all :access-time)) + (ext (helm-get-default-program-for-file candidate)) + (tooltip-hide-delay (or helm-tooltip-hide-delay tooltip-hide-delay))) + (if (and (display-graphic-p) tooltip-mode) + (tooltip-show + (concat + (helm-basename candidate) "\n" + dired-line "\n" + (format "Mode: %s\n" (helm-get-default-mode-for-file candidate)) + (format "Ext prog: %s\n" (or (and ext (replace-regexp-in-string + " %s" "" ext)) + "Not defined")) + (format "Type: %s: %s\n" type mode-type) + (when (string= type "symlink") + (format "True name: '%s'\n" + (cond ((string-match "^\.#" (helm-basename candidate)) + "Autosave symlink") + ((helm-ff-valid-symlink-p candidate) + (file-truename candidate)) + (t "Invalid Symlink")))) + (format "Owner: %s: %s\n" owner owner-right) + (format "Group: %s: %s\n" group group-right) + (format "Others: %s\n" other-right) + (format "Size: %s\n" size) + (format "Modified: %s\n" modif) + (format "Accessed: %s\n" access))) + (message dired-line) (sit-for 5))) + (message "Permission denied, file not readable"))) + +(defun helm-ff-properties-persistent () + "Show properties without quitting helm." + (interactive) + (with-helm-alive-p + (helm-attrset 'properties-action '(helm-ff-properties . never-split)) + (helm-execute-persistent-action 'properties-action))) +(put 'helm-ff-properties-persistent 'helm-only t) + +(defun helm-ff-persistent-delete () + "Delete current candidate without quitting." + (interactive) + (with-helm-alive-p + (helm-attrset 'quick-delete '(helm-ff-quick-delete . never-split)) + (helm-execute-persistent-action 'quick-delete))) +(put 'helm-ff-persistent-delete 'helm-only t) + +(defun helm-ff-dot-file-p (file) + "Check if FILE is `.' or `..'." + (member (helm-basename file) '("." ".."))) + +(defun helm-ff-kill-buffer-fname (candidate) + (let* ((buf (get-file-buffer candidate)) + (buf-name (buffer-name buf))) + (cond ((and buf (eq buf (get-buffer helm-current-buffer))) + (user-error + "Can't kill `helm-current-buffer' without quitting session")) + (buf (kill-buffer buf) (message "Buffer `%s' killed" buf-name)) + (t (message "No buffer to kill"))))) + +(defun helm-ff-kill-or-find-buffer-fname (candidate) + "Find file CANDIDATE or kill it's buffer if it is visible. +Never kill `helm-current-buffer'. +Never kill buffer modified. +This is called normally on third hit of \ +\\\\[helm-execute-persistent-action] +in `helm-find-files-persistent-action-if'." + (let* ((buf (get-file-buffer candidate)) + (buf-name (buffer-name buf)) + (win (get-buffer-window buf)) + (helm--reading-passwd-or-string t)) + (cond ((and buf win (eq buf (get-buffer helm-current-buffer))) + (user-error + "Can't kill `helm-current-buffer' without quitting session")) + ((and buf win (buffer-modified-p buf)) + (message "Can't kill modified buffer, please save it before")) + ((and buf win) + (kill-buffer buf) + (if (and helm-persistent-action-display-window + (window-dedicated-p (next-window win 1))) + (delete-window helm-persistent-action-display-window) + (set-window-buffer win helm-current-buffer)) + (message "Buffer `%s' killed" buf-name)) + (t (find-file candidate))))) + +(defun helm-ff-run-kill-buffer-persistent () + "Execute `helm-ff-kill-buffer-fname' without quitting." + (interactive) + (with-helm-alive-p + (helm-attrset 'kill-buffer-fname 'helm-ff-kill-buffer-fname) + (helm-execute-persistent-action 'kill-buffer-fname))) +(put 'helm-ff-run-kill-buffer-persistent 'helm-only t) + +;; Preview with external tool +(defun helm-ff-persistent-open-file-externally (file) + (require 'helm-external) + (if (helm-get-default-program-for-file file) + (helm-open-file-externally file) + (message "Please configure an external program for `*%s' file in `helm-external-programs-associations'" + (file-name-extension file t)))) + +(defun helm-ff-run-preview-file-externally () + (interactive) + (with-helm-alive-p + (helm-attrset 'open-file-externally '(helm-ff-persistent-open-file-externally . never-split)) + (helm-execute-persistent-action 'open-file-externally))) +(put 'helm-ff-run-preview-file-externally 'helm-only t) + +(defun helm-ff-prefix-filename (fname &optional file-or-symlinkp new-file) + "Return filename FNAME maybe prefixed with [?] or [@]. +If FILE-OR-SYMLINKP is non--nil this mean we assume FNAME is an +existing filename or valid symlink and there is no need to test it. +NEW-FILE when non--nil mean FNAME is a non existing file and +return FNAME prefixed with [?]." + (let* ((prefix-new (propertize + " " 'display + (propertize "[?]" 'face 'helm-ff-prefix))) + (prefix-url (propertize + " " 'display + (propertize "[@]" 'face 'helm-ff-prefix)))) + (cond (file-or-symlinkp fname) + ((or (string-match helm-ff-url-regexp fname) + (and helm--url-regexp (string-match helm--url-regexp fname))) + (concat prefix-url " " fname)) + (new-file (concat prefix-new " " fname))))) + +(defun helm-ff-score-candidate-for-pattern (str pattern) + (if (member str '("." "..")) + 200 + (helm-score-candidate-for-pattern str pattern))) + +(defun helm-ff-sort-candidates-1 (candidates input) + "Sort function for `helm-source-find-files'. +Return candidates prefixed with basename of INPUT first." + (if (or (and (file-directory-p input) + (string-match "/\\'" input)) + (string-match "\\`\\$" input) + (null candidates)) + candidates + (let* ((c1 (car candidates)) + (cand1real (if (consp c1) (cdr c1) c1)) + (cand1 (unless (file-exists-p cand1real) c1)) + (rest-cand (if cand1 (cdr candidates) candidates)) + (memo-src (make-hash-table :test 'equal)) + (all (sort rest-cand + (lambda (s1 s2) + (let* ((score (lambda (str) + (helm-ff-score-candidate-for-pattern + str (helm-basename input)))) + (bn1 (helm-basename (if (consp s1) (cdr s1) s1))) + (bn2 (helm-basename (if (consp s2) (cdr s2) s2))) + (sc1 (or (gethash bn1 memo-src) + (puthash bn1 (funcall score bn1) memo-src))) + (sc2 (or (gethash bn2 memo-src) + (puthash bn2 (funcall score bn2) memo-src)))) + (cond ((= sc1 sc2) + (< (string-width bn1) + (string-width bn2))) + ((> sc1 sc2)))))))) + (if cand1 (cons cand1 all) all)))) + +(defun helm-ff-sort-candidates (candidates _source) + "Sort function for `helm-source-find-files'. +Return candidates prefixed with basename of `helm-input' first." + (helm-ff-sort-candidates-1 candidates helm-input)) + +(defun helm-ff-boring-file-p (file) + ;; Prevent user doing silly thing like + ;; adding the dotted files to boring regexps (#924). + (and (not (string-match "\\.$" file)) + (string-match helm-ff--boring-regexp file))) + +(defun helm-ff-filter-candidate-one-by-one (file) + "`filter-one-by-one' Transformer function for `helm-source-find-files'." + ;; Handle boring files + (let ((basename (helm-basename file)) + dot) + (unless (and helm-ff-skip-boring-files + (helm-ff-boring-file-p basename)) + + ;; Handle tramp files with minimal highlighting. + (if (and (or (string-match-p helm-tramp-file-name-regexp helm-pattern) + (helm-file-on-mounted-network-p helm-pattern))) + (let* (hostp + (disp (if (and helm-ff-transformer-show-only-basename + (not (setq dot (helm-dir-is-dot file)))) + (or (setq hostp + (helm-ff--get-host-from-tramp-invalid-fname + file)) + basename) + file))) + ;; Filename with cntrl chars e.g. foo^J + ;; This will not work as long as most tramp file handlers doesn't + ;; handle such case, e.g. file-name-all-completions, + ;; directory-files, file-name-nondirectory etc... + ;; Keep it though in case they fix this upstream... + (setq disp (replace-regexp-in-string "[[:cntrl:]]" "?" disp)) + (cond (;; Dot directories . and .. + dot (propertize file 'face 'helm-ff-dotted-directory)) + ;; Directories. + ((get-text-property 1 'helm-ff-dir file) + (cons (propertize disp 'face 'helm-ff-directory) file)) + ;; Executable files. + ((get-text-property 1 'helm-ff-exe file) + (cons (propertize disp 'face 'helm-ff-executable) file)) + ;; Symlinks. + ((get-text-property 1 'helm-ff-sym file) + (cons (propertize disp 'face 'helm-ff-symlink) file)) + ;; Regular files. + ((get-text-property 1 'helm-ff-file file) + (cons (propertize disp 'face 'helm-ff-file) file)) + ;; non existing files. + (t (cons (helm-ff-prefix-filename + (propertize disp 'face 'helm-ff-file) + hostp (unless hostp 'new-file)) + file)))) + + ;; Highlight local files showing everything, symlinks, exe, + ;; dirs etc... + (let* ((disp (if (and helm-ff-transformer-show-only-basename + (not (setq dot (helm-dir-is-dot file))) + (not (and helm--url-regexp + (string-match helm--url-regexp file))) + (not (string-match helm-ff-url-regexp file))) + (or (helm-ff--get-host-from-tramp-invalid-fname file) + basename) + file)) + (attr (file-attributes file)) + (type (car attr)) + x-bit) + ;; Filename cntrl chars e.g. foo^J + (setq disp (replace-regexp-in-string "[[:cntrl:]]" "?" disp)) + (cond ((string-match "file-error" file) file) + (;; A dead symlink. + (and (stringp type) + (not (helm-ff-valid-symlink-p file)) + (not (string-match "^\\.#" basename))) + (cons (propertize disp 'face 'helm-ff-invalid-symlink) + file)) + ;; A dotted directory symlinked. + ((and dot (stringp type)) + (cons (propertize disp 'face 'helm-ff-dotted-symlink-directory) + file)) + ;; A dotted directory. + ((helm-ff-dot-file-p file) + (cons (propertize disp 'face 'helm-ff-dotted-directory) + file)) + ;; A symlink. + ((stringp type) + (cons (propertize disp 'display + (concat (propertize disp 'face 'helm-ff-symlink) + " -> " + (propertize (abbreviate-file-name type) + 'face 'helm-ff-truename))) + file)) + ;; A directory. + ((eq t type) + (cons (propertize disp 'face 'helm-ff-directory) + file)) + ;; A character device file. + ((and attr (string-match + "\\`[cp]" (setq x-bit (substring (nth 8 attr) 0 4)))) + (cons (propertize disp 'face 'helm-ff-pipe) + file)) + ;; A socket file. + ((and attr (string-match "\\`[s]" x-bit)) + (cons (propertize disp 'face 'helm-ff-socket) + file)) + ;; An executable file. + ((and attr + (string-match + "x\\'" x-bit)) + (cons (propertize disp 'face 'helm-ff-executable) + file)) + ;; An executable file with suid + ((and attr (string-match "s\\'" x-bit)) + (cons (propertize disp 'face 'helm-ff-suid) + file)) + ;; A file. + ((and attr (null type)) + (cons (propertize disp 'face 'helm-ff-file) + file)) + ;; A non--existing file. + (t (cons (helm-ff-prefix-filename + (propertize disp 'face 'helm-ff-file) nil 'new-file) + file)))))))) + +(defun helm-find-files-action-transformer (actions candidate) + "Action transformer for `helm-source-find-files'." + (let ((str-at-point (with-helm-current-buffer + (buffer-substring-no-properties + (point-at-bol) (point-at-eol))))) + (when (file-regular-p candidate) + (setq actions (helm-append-at-nth + actions '(("Checksum File" . helm-ff-checksum)) 4))) + (cond ((and (string-match "Trash/files/?\\'" (helm-basedir candidate)) + (not (member (helm-basename candidate) '("." ".."))) + (file-exists-p candidate) + (executable-find "trash")) + (helm-append-at-nth + actions + '(("Restore file(s) from trash" . helm-restore-file-from-trash) + ("Delete file(s) from trash" . helm-ff-trash-rm)) + 1)) + ((and helm--url-regexp + (not (string-match-p helm--url-regexp str-at-point)) + (not (with-helm-current-buffer (eq major-mode 'dired-mode))) + (string-match-p ":\\([0-9]+:?\\)" str-at-point)) + (append '(("Find file to line number" . helm-ff-goto-linum)) + actions)) + ((string-match (image-file-name-regexp) candidate) + (helm-append-at-nth + actions + '(("Rotate image right `M-r'" . helm-ff-rotate-image-right) + ("Rotate image left `M-l'" . helm-ff-rotate-image-left)) + 3)) + ((string-match "\\.el$" (helm-aif (helm-marked-candidates) + (car it) candidate)) + (helm-append-at-nth + actions + '(("Byte compile lisp file(s) `M-B, C-u to load'" + . helm-find-files-byte-compile) + ("Load File(s) `M-L'" . helm-find-files-load-files)) + 2)) + ((and (string-match "\\.html?$" candidate) + (file-exists-p candidate)) + (helm-append-at-nth + actions '(("Browse url file" . browse-url-of-file)) 2)) + ((or (string= (file-name-extension candidate) "pdf") + (string= (file-name-extension candidate) "PDF")) + (helm-append-at-nth + actions '(("Pdfgrep File(s)" . helm-ff-pdfgrep)) 4)) + (t actions)))) + +(defun helm-ff-trash-action (fn names &rest args) + "Execute a trash action FN on marked files. + +Arg NAMES is a list of strings to pass to messages +e.g. '(\"delete\" \"deleting\"), ARGS are other args to be passed to FN." + (let ((mkd (helm-marked-candidates)) + errors) + (with-helm-display-marked-candidates + helm-marked-buffer-name + (helm-ff--count-and-collect-dups (mapcar 'helm-basename mkd)) + (when (y-or-n-p (format "%s %s files from trash? " + (capitalize (car names)) + (length mkd))) + (message "%s files from trash..." (capitalize (cadr names))) + (cl-loop for f in mkd do + (condition-case err + (apply fn f args) + (error (push (format "%s" (cadr err)) errors) + nil))))) + (if errors + (display-warning 'helm + (with-temp-buffer + (insert (format-time-string "%Y-%m-%d %H:%M:%S\n" + (current-time))) + (insert (format + "Failed to %s %s/%s files from trash\n" + (car names) (length errors) (length mkd))) + (insert (mapconcat 'identity errors "\n") "\n ") + (buffer-string)) + :error + "*helm restore warnings*") + (message "%s %s files from trash done" + (capitalize (cadr names)) (length mkd))))) + +(defun helm-ff-trash-rm (_candidate) + "Delete marked-files from a Trash directory. + +The Trash directory should be a directory compliant with + and each file +should have its '*.trashinfo' correspondent file in Trash/info +directory." + (helm-ff-trash-action 'helm-ff-trash-rm-1 '("delete" "deleting"))) + +(defun helm-restore-file-from-trash (_candidate) + "Restore marked-files from a Trash directory. + +The Trash directory should be a directory compliant with + and each file +should have its '*.trashinfo' correspondent file in Trash/info +directory." + (let* ((default-directory (file-name-as-directory + helm-ff-default-directory)) + (trashed-files (with-temp-buffer + (process-file "trash-list" nil t nil) + (split-string (buffer-string) "\n")))) + (helm-ff-trash-action 'helm-restore-file-from-trash-1 + '("restore" "restoring") + trashed-files))) + +(defun helm-ff-trash-rm-1 (file) + (let ((info-file (concat (helm-reduce-file-name file 2) + "info/" (helm-basename file) + ".trashinfo"))) + (cl-assert (file-exists-p file) + nil (format "No such file or directory `%s'" + file)) + (cl-assert (file-exists-p info-file) + nil (format "No such file or directory `%s'" + info-file)) + (delete-file file) + (delete-file info-file))) + +(defun helm-restore-file-from-trash-1 (file trashed-files) + "Restore FILE from a trash directory. +Arg TRASHED-FILES is the list of files in the trash directory obtained +with 'trash-list' command." + (let ((info-file (concat (helm-reduce-file-name file 2) + "info/" + (helm-basename file) + ".trashinfo")) + (dest-file (helm-ff--get-dest-file-from-trash + trashed-files file))) + (cl-assert (not (file-exists-p dest-file)) nil + (format "File `%s' already exists" dest-file)) + (cl-assert dest-file nil "No such file in trash") + (rename-file file dest-file) + (delete-file info-file))) + +(defun helm-ff--get-dest-file-from-trash (trashed-files file) + (cl-loop for f in trashed-files + when (string-match + (concat (regexp-quote (helm-basename file)) + "\\'") + f) + return + (replace-regexp-in-string + "\\`\\([0-9]\\{2,4\\}[-:][0-9]\\{2\\}[:-][0-9]\\{2\\} \\)\\{2\\}" + "" f))) + +(defun helm-ff-goto-linum (candidate) + "Find file CANDIDATE and maybe jump to line number found in fname at point. +line number should be added at end of fname preceded with \":\". +e.g \"foo:12\"." + (let ((linum (with-helm-current-buffer + (let ((str (buffer-substring-no-properties + (point-at-bol) (point-at-eol)))) + (when (string-match ":\\([0-9]+:?\\)" str) + (match-string 1 str)))))) + (find-file candidate) + (and linum (not (string= linum "")) + (helm-goto-line (string-to-number linum) t)))) + +(defun helm-ff-mail-attach-files (_candidate) + "Run `mml-attach-file' on `helm-marked-candidates'." + (require 'mml) + (let ((flist (helm-marked-candidates :with-wildcard t)) + (dest-buf (and (derived-mode-p 'message-mode 'mail-mode) + (current-buffer))) + bufs) + (unless dest-buf + (setq bufs (cl-loop for b in (buffer-list) + when (with-current-buffer b + (derived-mode-p 'message-mode 'mail-mode)) + collect (buffer-name b))) + (if (and bufs (y-or-n-p "Attach files to existing mail composition buffer? ")) + (setq dest-buf + (if (cdr bufs) + (helm-comp-read "Attach to buffer: " bufs :nomark t) + (car bufs))) + (compose-mail) + (setq dest-buf (current-buffer)))) + (switch-to-buffer dest-buf) + (save-restriction + (widen) + (save-excursion + (goto-char (point-max)) + (cl-loop for f in flist + do (mml-attach-file f (or (mm-default-file-encoding f) + "application/octet-stream"))))))) + +(defvar image-dired-display-image-buffer) +(defun helm-ff-rotate-current-image-1 (file &optional num-arg) + "Rotate current image at NUM-ARG degrees. +This is a destructive operation on FILE made by external tool mogrify." + (setq file (file-truename file)) ; For symlinked images. + ;; When FILE is not an image-file, do nothing. + (when (string-match (image-file-name-regexp) file) + (if (executable-find "mogrify") + (progn + (shell-command (format "mogrify -rotate %s %s" + (or num-arg 90) + (shell-quote-argument file))) + (when (buffer-live-p image-dired-display-image-buffer) + (kill-buffer image-dired-display-image-buffer)) + (image-dired-display-image file) + (message nil) + (display-buffer (get-buffer image-dired-display-image-buffer))) + (error "mogrify not found")))) + +(defun helm-ff-rotate-image-left (candidate) + "Rotate image file CANDIDATE left. +This affect directly file CANDIDATE." + (helm-ff-rotate-current-image-1 candidate -90)) + +(defun helm-ff-rotate-image-right (candidate) + "Rotate image file CANDIDATE right. +This affect directly file CANDIDATE." + (helm-ff-rotate-current-image-1 candidate)) + +(defun helm-ff-rotate-left-persistent () + "Rotate image left without quitting helm." + (interactive) + (with-helm-alive-p + (helm-attrset 'image-action1 'helm-ff-rotate-image-left) + (helm-execute-persistent-action 'image-action1))) +(put 'helm-ff-rotate-left-persistent 'helm-only t) + +(defun helm-ff-rotate-right-persistent () + "Rotate image right without quitting helm." + (interactive) + (with-helm-alive-p + (helm-attrset 'image-action2 'helm-ff-rotate-image-right) + (helm-execute-persistent-action 'image-action2))) +(put 'helm-ff-rotate-right-persistent 'helm-only t) + +(defun helm-ff-exif-data (candidate) + "Extract exif data from file CANDIDATE using `helm-ff-exif-data-program'." + (if (and helm-ff-exif-data-program + (executable-find helm-ff-exif-data-program)) + (shell-command-to-string (format "%s %s %s" + helm-ff-exif-data-program + helm-ff-exif-data-program-args + candidate)) + (format "No program %s found to extract exif" + helm-ff-exif-data-program))) + +(cl-defun helm-find-files-persistent-action-if (candidate) + "Open subtree CANDIDATE without quitting helm. +If CANDIDATE is not a directory expand CANDIDATE filename. +If CANDIDATE is alone, open file CANDIDATE filename. +That's mean: +First hit on C-j expand CANDIDATE second hit open file. +If a prefix arg is given or `helm-follow-mode' is on open file." + (let* ((follow (or (helm-follow-mode-p) + helm--temp-follow-flag)) + (image-cand (string-match-p (image-file-name-regexp) candidate)) + (new-pattern (helm-get-selection)) + (num-lines-buf (with-current-buffer helm-buffer + (count-lines (point-min) (point-max)))) + (insert-in-minibuffer (lambda (fname) + (with-selected-window (or (active-minibuffer-window) + (minibuffer-window)) + (unless follow + (delete-minibuffer-contents) + (set-text-properties 0 (length fname) + nil fname) + (insert fname)))))) + (helm-attrset 'candidate-number-limit helm-ff-candidate-number-limit) + (unless image-cand + (when follow + (helm-follow-mode -1) + (cl-return-from helm-find-files-persistent-action-if + (message "Helm-follow-mode allowed only on images, disabling")))) + (cond ((and (helm-ff--invalid-tramp-name-p) + (string-match helm-tramp-file-name-regexp candidate)) + (cons (lambda (_candidate) + ;; First hit insert hostname and + ;; second hit insert ":" and expand. + (if (string= candidate helm-pattern) + (funcall insert-in-minibuffer (concat candidate ":")) + (funcall insert-in-minibuffer candidate))) + 'never-split)) + (;; A symlink directory, expand it but not to its truename + ;; unless a prefix arg is given. + (and (file-directory-p candidate) (file-symlink-p candidate)) + (cons (lambda (_candidate) + (funcall insert-in-minibuffer + (file-name-as-directory + (if current-prefix-arg + (file-truename (expand-file-name candidate)) + (expand-file-name candidate))))) + 'never-split)) + ;; A directory, open it. + ((file-directory-p candidate) + (cons (lambda (_candidate) + (when (string= (helm-basename candidate) "..") + (setq helm-ff-last-expanded helm-ff-default-directory)) + (funcall insert-in-minibuffer (file-name-as-directory + (expand-file-name candidate)))) + 'never-split)) + ;; A symlink file, expand to it's true name. (first hit) + ((and (file-symlink-p candidate) (not current-prefix-arg) (not follow)) + (cons (lambda (_candidate) + (funcall insert-in-minibuffer (file-truename candidate))) + 'never-split)) + ;; A regular file, expand it, (first hit) + ((and (>= num-lines-buf 3) (not current-prefix-arg) (not follow)) + (cons (lambda (_candidate) + (setq helm-pattern "") ; Force update. + (funcall insert-in-minibuffer new-pattern)) + 'never-split)) + ;; An image file and it is the second hit on C-j, + ;; show the file in `image-dired'. + (image-cand + (lambda (_candidate) + (require 'image-dired) + (let* ((win (get-buffer-window + image-dired-display-image-buffer 'visible)) + (fname (and win + (with-selected-window win + (get-text-property (point-min) + 'original-file-name)))) + (remove-buf-only (and win + fname + (with-helm-buffer + (file-equal-p candidate fname))))) + (when remove-buf-only + (with-helm-window + (if (and helm-persistent-action-display-window + (window-dedicated-p (next-window win 1))) + (delete-window helm-persistent-action-display-window) + (set-window-buffer win helm-current-buffer)))) + (when (buffer-live-p (get-buffer image-dired-display-image-buffer)) + (kill-buffer image-dired-display-image-buffer)) + (unless remove-buf-only + ;; Fix emacs bug never fixed upstream. + (unless (file-directory-p image-dired-dir) + (make-directory image-dired-dir)) + (switch-to-buffer image-dired-display-image-buffer) + (message "Resizing image...") + (cl-letf (((symbol-function 'message) #'ignore)) + (image-dired-display-image candidate)) + (message "Resizing image done") + (with-current-buffer image-dired-display-image-buffer + (let ((exif-data (helm-ff-exif-data candidate))) + (setq default-directory helm-ff-default-directory) + (image-dired-update-property 'help-echo exif-data))))))) + ;; Allow browsing archive on avfs fs. + ;; Assume volume is already mounted with mountavfs. + ((helm-aand helm-ff-avfs-directory + (file-name-directory candidate) + (string-match + (regexp-quote (expand-file-name helm-ff-avfs-directory)) + it) + (helm-ff-file-compressed-p candidate)) + (cons (lambda (_candidate) + (funcall insert-in-minibuffer (concat candidate "#/"))) + 'never-split)) + ;; File doesn't exists and basename starts with ".." or " ", + ;; Start a recursive search for directories. + ((and (not (file-exists-p candidate)) + (not (file-remote-p candidate)) + (string-match-p "\\`\\([.]\\|\\s-\\)\\{2\\}[^/]+" + (helm-basename candidate))) + ;; As soon as the final "/" is added the job is passed + ;; to `helm-ff-auto-expand-to-home-or-root'. + (cons (lambda (_candidate) + (funcall insert-in-minibuffer (concat candidate "/"))) + 'never-split)) + ;; File is not existing and have no basedir, typically when + ;; user hit C-k (minibuffer is empty) and then write foo and + ;; hit C-j. This make clear that when no basedir, helm will + ;; create the file in default-directory. + ((and (not (file-exists-p candidate)) + (not (helm-basedir candidate))) + (cons (lambda (_candidate) + (funcall insert-in-minibuffer + (expand-file-name candidate default-directory))) + 'never-split)) + ;; On second hit we open file. + ;; On Third hit we kill it's buffer maybe. + (t + (lambda (_candidate) + (funcall helm-ff-kill-or-find-buffer-fname-fn candidate)))))) + + +;;; Recursive dirs completion +;; +(defun helm-find-files-recursive-dirs (directory &optional input) + (when (string-match "\\(\\s-+\\|[.]\\)\\{2\\}" input) + (setq input (replace-match "" nil t input))) + (message "Recursively searching %s from %s ..." + input (abbreviate-file-name directory)) + ;; Ensure to not create a new frame + (let (helm-actions-inherit-frame-settings) + (helm :sources + (helm-make-source + "Recursive directories" 'helm-locate-subdirs-source + :basedir (if (string-match-p + "\\`es" helm-locate-recursive-dirs-command) + directory + (shell-quote-argument directory)) + :subdir (shell-quote-argument input) + :candidate-transformer + `((lambda (candidates) + (cl-loop for c in candidates + when (and (file-directory-p c) + (null (helm-boring-directory-p + c helm-boring-file-regexp-list)) + (string-match-p ,(regexp-quote input) + (helm-basename c))) + collect (propertize c 'face 'helm-ff-dirs))) + helm-w32-pathname-transformer + (lambda (candidates) + (helm-ff-sort-candidates-1 candidates ,input))) + :persistent-action 'ignore + :action (lambda (c) + (helm-set-pattern + (file-name-as-directory (expand-file-name c))))) + :candidate-number-limit 999999 + :allow-nest t + :resume 'noresume + :ff-transformer-show-only-basename nil + :buffer "*helm recursive dirs*"))) + +(defun helm-ff-recursive-dirs (_candidate) + "Launch a recursive search in `helm-ff-default-directory'." + (with-helm-default-directory helm-ff-default-directory + (helm-find-files-recursive-dirs + (helm-current-directory) + (helm-basename (helm-get-selection))))) + +(defun helm-ff-file-compressed-p (candidate) + "Whether CANDIDATE is a compressed file or not." + (member (file-name-extension candidate) + helm-ff-file-compressed-list)) + +(defun helm-ff--fname-at-point () + "Try to guess fname at point." + (let ((end (point)) + (limit (helm-aif (bounds-of-thing-at-point 'filename) + (car it) + (point)))) + (save-excursion + (while (re-search-backward "\\(~\\|/\\|[[:lower:][:upper:]]:/\\)" + limit t)) + (buffer-substring-no-properties (point) end)))) + +(defun helm-insert-file-name-completion-at-point (_candidate) + "Insert file name completion at point. + +When completing i.e. there is already something at point, insert +filename abbreviated, relative or full according to initial input, +whereas when inserting i.e. there is nothing at point, insert filename +full, abbreviated or relative according to prefix arg, respectively no +prefix arg, one prefix arg or two prefix arg." + (with-helm-current-buffer + (if buffer-read-only + (error "Error: Buffer `%s' is read-only" (buffer-name)) + (let* ((mkds (helm-marked-candidates :with-wildcard t)) + (candidate (car mkds)) + (end (point)) + (tap (helm-ff--fname-at-point)) + (guess (and (stringp tap) + (substring-no-properties tap))) + (beg (if guess (- (point) (length guess)) (point))) + (full-path-p (and (stringp guess) + (or (string-match-p + (concat "^" (getenv "HOME")) + guess) + (string-match-p + "\\`\\(/\\|[[:lower:][:upper:]]:/\\)" + guess)))) + (escape-fn (with-helm-current-buffer + (if (memq major-mode + helm-modes-using-escaped-strings) + #'shell-quote-argument #'identity)))) + (insert + (funcall escape-fn (helm-ff--insert-fname + candidate beg end full-path-p guess)) + (if (cdr mkds) " " "") + (mapconcat escape-fn + (cl-loop for f in (cdr mkds) + collect (helm-ff--insert-fname f)) + " ")))))) + +(defun helm-ff--insert-fname (candidate &optional beg end full-path guess) + (set-text-properties 0 (length candidate) nil candidate) + (if (and beg end guess (not (string= guess "")) + (or (string-match + "^\\(~/\\|/\\|[[:lower:][:upper:]]:/\\)" + guess) + (file-exists-p candidate))) + (prog1 + (cond (full-path + (expand-file-name candidate)) + ((string= (match-string 1 guess) "~/") + (abbreviate-file-name candidate)) + (t (file-relative-name candidate))) + (delete-region beg end)) + (cond ((equal helm-current-prefix-arg '(4)) + (abbreviate-file-name candidate)) + ((equal helm-current-prefix-arg '(16)) + (file-relative-name candidate)) + (t candidate)))) + +(cl-defun helm-find-files-history (arg &key (comp-read t)) + "The `helm-find-files' history. +Show the first `helm-ff-history-max-length' elements of +`helm-ff-history' in an `helm-comp-read'." + (interactive "p") + (let ((history (when helm-ff-history + (helm-fast-remove-dups helm-ff-history + :test 'equal)))) + (when history + (setq helm-ff-history + (if (>= (length history) helm-ff-history-max-length) + (cl-subseq history 0 helm-ff-history-max-length) + history)) + (if comp-read + (let ((src (helm-build-sync-source "Helm Find Files History" + :candidates helm-ff-history + :fuzzy-match (helm-ff-fuzzy-matching-p) + :persistent-action 'ignore + :migemo t + :action (lambda (candidate) + (if arg + (helm-set-pattern + (expand-file-name candidate)) + (identity candidate)))))) + (helm :sources src + :resume 'noresume + :buffer helm-ff-history-buffer-name + :allow-nest t)) + helm-ff-history)))) +(put 'helm-find-files-history 'helm-only t) + +(defun helm-find-files-1 (fname &optional preselect) + "Find FNAME filename with PRESELECT filename preselected. + +Use it for non--interactive calls of `helm-find-files'." + (require 'tramp) + ;; Resolve FNAME now outside of helm. + ;; [FIXME] When `helm-find-files-1' is used directly from lisp + ;; and FNAME is an abbreviated path, for some reasons + ;; `helm-update' is called many times before resolving + ;; the abbreviated path (Issue #1939) so be sure to pass a + ;; full path to helm-find-files-1. + (unless (string-match-p helm-ff-url-regexp fname) + (setq fname (expand-file-name (substitute-in-file-name fname)))) + (when (get-buffer helm-action-buffer) + (kill-buffer helm-action-buffer)) + (setq helm-find-files--toggle-bookmark nil) + (let* ( ;; Be sure we don't erase the precedent minibuffer if some. + (helm-ff-auto-update-initial-value + (and helm-ff-auto-update-initial-value + (not (minibuffer-window-active-p (minibuffer-window))))) + (tap (thing-at-point 'filename)) + (def (and tap (or (file-remote-p tap) + (expand-file-name tap))))) + (helm-set-local-variable 'helm-follow-mode-persistent nil) + (unless helm-source-find-files + (setq helm-source-find-files (helm-make-source + "Find Files" 'helm-source-ffiles))) + (when (helm-attr 'follow helm-source-find-files) + (helm-attrset 'follow -1 helm-source-find-files)) + (helm-ff-setup-update-hook) + (add-hook 'helm-resume-after-hook 'helm-ff--update-resume-after-hook) + (unwind-protect + (helm :sources 'helm-source-find-files + :input fname + :case-fold-search helm-file-name-case-fold-search + :preselect preselect + :ff-transformer-show-only-basename + helm-ff-transformer-show-only-basename + :default def + :prompt "Find files or url: " + :buffer "*helm find files*") + (helm-ff--update-resume-after-hook nil t) + (setq helm-ff-default-directory nil)))) + +(defun helm-ff--update-resume-after-hook (sources &optional nohook) + "Meant to be used in `helm-resume-after-hook'. +When NOHOOK is non nil run inconditionally, otherwise only when source +is helm-source-find-files." + (when (or nohook (string= "Find Files" + (assoc-default 'name (car sources)))) + (helm-attrset 'resume `(lambda () + (helm-ff-setup-update-hook) + (setq helm-ff-default-directory + ,helm-ff-default-directory + helm-ff-last-expanded + ,helm-ff-last-expanded)) + helm-source-find-files))) + +(defun helm-ff-clean-initial-input () + ;; When using hff in an external frame initial input is printed in + ;; the minibuffer of initial-frame, delete it. + (with-selected-frame helm-initial-frame + (helm-clean-up-minibuffer))) + +(defun helm-ff-setup-update-hook () + (dolist (hook '(helm-ff-clean-initial-input ; Add to be called first. + helm-ff-move-to-first-real-candidate + helm-ff-update-when-only-one-matched + helm-ff-auto-expand-to-home-or-root)) + (add-hook 'helm-after-update-hook hook))) + +(defun helm-find-files-cleanup () + (mapc (lambda (hook) + (remove-hook 'helm-after-update-hook hook)) + '(helm-ff-auto-expand-to-home-or-root + helm-ff-update-when-only-one-matched + helm-ff-move-to-first-real-candidate + helm-ff-clean-initial-input))) + +(defun helm-find-files-toggle-to-bookmark () + "Toggle helm-bookmark for `helm-find-files' and `helm-find-files.'" + (interactive) + (require 'helm-bookmark) + (with-helm-alive-p + (with-helm-buffer + (if (setq helm-find-files--toggle-bookmark + (not helm-find-files--toggle-bookmark)) + (progn + (helm-set-pattern "" t) + (helm-set-sources '(helm-source-bookmark-helm-find-files))) + ;; Switch back to helm-find-files. + (helm-set-pattern "./" t) ; Back to initial directory of hff session. + (helm-set-sources '(helm-source-find-files)) + (helm--maybe-update-keymap))))) +(put 'helm-find-files-toggle-to-bookmark 'helm-only t) + +(defun helm-find-files-initial-input (&optional input) + "Return INPUT if present, otherwise try to guess it." + (unless (eq major-mode 'image-mode) + (or (and input (or (and (file-remote-p input) input) + (expand-file-name input))) + (helm-find-files-input + (helm-ffap-guesser) + (thing-at-point 'filename))))) + +(defun helm-ffap-guesser () + "Same as `ffap-guesser' but without gopher and machine support." + (require 'ffap) + ;; Avoid "Stack overflow in regexp matcher" error + ;; in evil `ffap-guesser' by removing crap `ffap-gopher-at-point' + ;; (bug fixed in emacs-26 #25391) . + ;; `ffap-machine-at-point' have been removed too as it was anyway + ;; disabled with `ffap-machine-p-known' bound to 'reject. + ;; `ffap-file-at-point' can be neutralized with + ;; `helm-ff-guess-ffap-filenames' and `ffap-url-at-point' with + ;; `helm-ff-guess-ffap-urls' + ;; Note also that `ffap-url-unwrap-remote' can override these + ;; variables. + (let ((ffap-alist (and helm-ff-guess-ffap-filenames ffap-alist)) + (ffap-url-regexp helm--url-regexp)) + (if (eq major-mode 'dired-mode) + (let ((beg (save-excursion (dired-move-to-filename))) + (end (save-excursion (dired-move-to-end-of-filename t)))) + (helm-aif (and beg end (member (buffer-substring beg end) + '("." ".."))) + (concat (file-name-as-directory + (expand-file-name dired-directory)) + (car it)) + (dired-get-filename 'no-dir t))) + (let* ((beg (and (use-region-p) (region-beginning))) + (end (and (use-region-p) (region-end))) + (str (and beg end (buffer-substring-no-properties beg end))) + (ffap (or (and helm-ff-guess-ffap-urls ffap-url-regexp + (ffap-fixup-url (ffap-url-at-point))) + (ffap-file-at-point)))) + ;; Workaround emacs bugs: + ;; When the region is active and a file is detected + ;; `ffap-string-at-point' returns the region prefixed with + ;; "/", e.g. at a beginning of a patch (first bug) and make + ;; `file-remote-p' returning an error (second bug), so in such + ;; case returns the region itself instead of the region + ;; corrupted by ffap. + (if (and str ffap) str ffap))))) + +(defun helm-find-files-input (file-at-pt thing-at-pt) + "Try to guess a default input for `helm-find-files'." + (let* ((non-essential t) + (remp (or (and file-at-pt (file-remote-p file-at-pt)) + (and thing-at-pt (file-remote-p thing-at-pt)))) + (def-dir (helm-current-directory)) + (urlp (and file-at-pt helm--url-regexp + (string-match helm--url-regexp file-at-pt))) + (lib (when helm-ff-search-library-in-sexp + (helm-find-library-at-point))) + (hlink (helm-ff-find-url-at-point)) + (file-p (and file-at-pt + (not (string= file-at-pt "")) + (not remp) + (file-exists-p file-at-pt) + thing-at-pt + (not (string= thing-at-pt "")) + (file-exists-p + (file-name-directory + (expand-file-name thing-at-pt def-dir)))))) + (cond (lib) ; e.g we are inside a require sexp. + (hlink) ; String at point is an hyperlink. + (file-p ; a regular file + (and file-at-pt (if (not (member (helm-basename file-at-pt) + '("." ".."))) + (expand-file-name file-at-pt) + file-at-pt))) + (urlp (helm-html-decode-entities-string file-at-pt)) ; possibly an url or email. + ((and file-at-pt + (not remp) + (file-exists-p file-at-pt)) + (expand-file-name file-at-pt))))) + +(defun helm-ff-find-url-at-point () + "Try to find link to an url in text-property at point." + (let* ((he (get-text-property (point) 'help-echo)) + (ov (overlays-at (point))) + (ov-he (and ov (overlay-get + (car (overlays-at (point))) 'help-echo))) + (w3m-l (get-text-property (point) 'w3m-href-anchor)) + (nt-prop (get-text-property (point) 'nt-link))) + ;; Org link. + (when (and (stringp he) (string-match "^LINK: " he)) + (setq he (replace-match "" t t he))) + (cl-loop for i in (list he ov-he w3m-l nt-prop) + thereis (and (stringp i) helm--url-regexp (string-match helm--url-regexp i) i)))) + +(defun helm-find-library-at-point () + "Try to find library path at point. +Find inside `require' and `declare-function' sexp." + (require 'find-func) + (let* ((beg-sexp (save-excursion (search-backward "(" (point-at-bol) t))) + (end-sexp (save-excursion (search-forward ")" (point-at-eol) t))) + (sexp (and beg-sexp end-sexp + (buffer-substring-no-properties + (1+ beg-sexp) (1- end-sexp))))) + (ignore-errors + (cond ((and sexp (string-match "require \'.+[^)]" sexp)) + (find-library-name + (replace-regexp-in-string + "'\\|\)\\|\(" "" + ;; If require use third arg, ignore it, + ;; always use library path found in `load-path'. + (cl-second (split-string (match-string 0 sexp)))))) + ((and sexp (string-match-p "^declare-function" sexp)) + (find-library-name + (replace-regexp-in-string + "\"\\|ext:" "" + (cl-third (split-string sexp))))) + (t nil))))) + + +;;; Handle copy, rename, symlink, relsymlink and hardlink from helm. +;; +;; +(defun helm-ff--valid-default-directory () + (with-helm-current-buffer + (cl-loop for b in (buffer-list) + for cd = (with-current-buffer b default-directory) + when (eq (car (file-attributes cd)) t) + return cd))) + +(cl-defun helm-dired-action (candidate + &key action follow (files (dired-get-marked-files))) + "Execute ACTION on FILES to CANDIDATE. +Where ACTION is a symbol that can be one of: +'copy, 'rename, 'symlink,'relsymlink, 'hardlink or 'backup. +Argument FOLLOW when non--nil specify to follow FILES to destination for the actions +copy and rename." + (require 'dired-async) + (require 'dired-x) ; For dired-keep-marker-relsymlink + (when (get-buffer dired-log-buffer) (kill-buffer dired-log-buffer)) + ;; When default-directory in current-buffer is an invalid directory, + ;; (e.g buffer-file directory have been renamed somewhere else) + ;; be sure to use a valid value to give to dired-create-file. + ;; i.e start-process is creating a process buffer based on default-directory. + (let ((default-directory (helm-ff--valid-default-directory)) + (fn (cl-case action + (copy 'dired-copy-file) + (rename 'dired-rename-file) + (symlink 'make-symbolic-link) + (relsymlink 'dired-make-relative-symlink) + (hardlink 'dired-hardlink) + (backup 'backup-file))) + (marker (cl-case action + ((copy rename backup) dired-keep-marker-copy) + (symlink dired-keep-marker-symlink) + (relsymlink dired-keep-marker-relsymlink) + (hardlink dired-keep-marker-hardlink))) + (dirflag (and (= (length files) 1) + (file-directory-p (car files)) + (not (file-directory-p candidate)))) + (dired-async-state (if (and (boundp 'dired-async-mode) + dired-async-mode) + 1 -1))) + (and follow (fboundp 'dired-async-mode) (dired-async-mode -1)) + (when (and (cdr files) (not (file-directory-p candidate))) + (error "%s: target `%s' is not a directory" action candidate)) + (unwind-protect + (dired-create-files + fn (symbol-name action) files + ;; CANDIDATE is the destination. + (if (file-directory-p candidate) + ;; When CANDIDATE is a directory, build file-name in this directory. + ;; Else we use CANDIDATE. + (lambda (from) + (expand-file-name (file-name-nondirectory from) candidate)) + (lambda (_from) candidate)) + marker) + (and (fboundp 'dired-async-mode) + (dired-async-mode dired-async-state))) + (push (file-name-as-directory + (if (file-directory-p candidate) + (expand-file-name candidate) + (file-name-directory candidate))) + helm-ff-history) + ;; If follow is non--nil we should not be in async mode. + (when (and follow + (not (memq action '(symlink relsymlink hardlink))) + (not (get-buffer dired-log-buffer))) + (let ((target (directory-file-name candidate))) + (unwind-protect + (progn + (setq helm-ff-cand-to-mark + (helm-get-dest-fnames-from-list files candidate dirflag)) + (with-helm-after-update-hook (helm-ff-maybe-mark-candidates)) + (if (and dirflag (eq action 'rename)) + (helm-find-files-1 (file-name-directory target) + (if helm-ff-transformer-show-only-basename + (helm-basename target) target)) + (helm-find-files-1 (file-name-as-directory + (expand-file-name candidate))))) + (setq helm-ff-cand-to-mark nil)))))) + +(defun helm-get-dest-fnames-from-list (flist dest-cand rename-dir-flag) + "Transform filenames of FLIST to abs of DEST-CAND. +If RENAME-DIR-FLAG is non--nil collect the `directory-file-name' of transformed +members of FLIST." + ;; At this point files have been renamed/copied at destination. + ;; That's mean DEST-CAND exists. + (cl-loop + with dest = (expand-file-name dest-cand) + for src in flist + for basename-src = (helm-basename src) + for fname = (cond (rename-dir-flag (directory-file-name dest)) + ((file-directory-p dest) + (concat (file-name-as-directory dest) basename-src)) + (t dest)) + when (file-exists-p fname) + collect fname into tmp-list + finally return (sort tmp-list 'string<))) + +(defun helm-ff-maybe-mark-candidates () + "Mark all candidates of list `helm-ff-cand-to-mark'. +This is used when copying/renaming/symlinking etc... and +following files to destination." + (when (and (string= (assoc-default 'name (helm-get-current-source)) + (assoc-default 'name helm-source-find-files)) + helm-ff-cand-to-mark) + (with-helm-window + (while helm-ff-cand-to-mark + (if (string= (car helm-ff-cand-to-mark) (helm-get-selection)) + (progn + (helm-make-visible-mark) + (helm-next-line) + (setq helm-ff-cand-to-mark (cdr helm-ff-cand-to-mark))) + (helm-next-line))) + (unless (helm-this-visible-mark) + (helm-prev-visible-mark))))) + + +;;; Routines for files +;; +;; +(defun helm-file-buffers (filename) + "Returns a list of buffer names corresponding to FILENAME." + (cl-loop with name = (expand-file-name filename) + for buf in (buffer-list) + for bfn = (buffer-file-name buf) + when (and bfn (string= name bfn)) + collect (buffer-name buf))) + +(defun helm-ff--delete-by-moving-to-trash (file) + "Decide to trash or delete FILE. +Returns non-nil when FILE needs to be trashed." + (let ((remote (file-remote-p file))) + (or + (and delete-by-moving-to-trash + (null helm-current-prefix-arg) + (null current-prefix-arg) + (or (and remote helm-trash-remote-files) + (null remote))) + (and (null delete-by-moving-to-trash) + (or helm-current-prefix-arg + current-prefix-arg) + (or (and remote helm-trash-remote-files) + (null remote)))))) + +(defun helm-ff-quick-delete (_candidate) + "Delete file CANDIDATE without quitting. + +When a prefix arg is given, meaning of `delete-by-moving-to-trash' is +inversed." + (with-helm-window + (let ((marked (helm-marked-candidates))) + (unwind-protect + (cl-loop with trash = (helm-ff--delete-by-moving-to-trash (car marked)) + for c in marked do + (progn (helm-preselect + (concat "^" (regexp-quote + (if (and helm-ff-transformer-show-only-basename + (not (helm-ff-dot-file-p c))) + (helm-basename c) c)))) + (when (y-or-n-p + (format "Really %s file `%s'? " + (if trash "Trash" "Delete") + (abbreviate-file-name c))) + (helm-delete-file + c helm-ff-signal-error-on-dot-files 'synchro trash) + (helm-delete-current-selection) + (message nil) + (helm--remove-marked-and-update-mode-line c)))) + (setq helm-marked-candidates nil + helm-visible-mark-overlays nil) + (helm-force-update + (let ((presel (helm-get-selection))) + (concat "^" (regexp-quote (if (and helm-ff-transformer-show-only-basename + (not (helm-ff-dot-file-p presel))) + (helm-basename presel) presel))))))))) + +(defun helm-delete-file (file &optional error-if-dot-file-p synchro trash) + "Delete FILE after querying the user. + +When a prefix arg is given, meaning of `delete-by-moving-to-trash' is +inversed. + +Return error when ERROR-IF-DOT-FILE-P is non nil and user tries to +delete a dotted file i.e. \".\" or \"..\". + +Ask user when directory are not empty to allow recursive deletion +unless `helm-ff-allow-recursive-deletes' is non nil. +When user is asked and reply with \"!\" don't ask for remaining +directories. + +Ask to kill buffers associated with that file, too. + +When TRASH is non nil, trash FILE even if `delete-by-moving-to-trash' +is nil." + (require 'dired) + (cl-block nil + (when (and error-if-dot-file-p + (helm-ff-dot-file-p file)) + (error "Error: Cannot operate on `.' or `..'")) + (let ((buffers (helm-file-buffers file)) + (helm--reading-passwd-or-string t) + (file-attrs (file-attributes file)) + (trash (or trash (helm-ff--delete-by-moving-to-trash file))) + (delete-by-moving-to-trash trash)) + (cond ((and (eq (nth 0 file-attrs) t) + (directory-files file t dired-re-no-dot)) + ;; Synchro means persistent deletion from HFF. + (if synchro + (when (or helm-ff-allow-recursive-deletes + trash + (y-or-n-p (format "Recursive delete of `%s'? " + (abbreviate-file-name file)))) + (delete-directory file 'recursive trash)) + ;; Avoid using dired-delete-file really annoying in + ;; emacs-26 but allows using ! (instead of all) to not + ;; confirm anymore for recursive deletion of + ;; directory. This is not persistent for all session + ;; like emacs-26 does with dired-delete-file (think it + ;; is a bug). + (if (or helm-ff-allow-recursive-deletes trash) + (delete-directory file 'recursive trash) + (helm-acase (helm-read-answer (format "Recursive delete of `%s'? [y,n,!,q]" + (abbreviate-file-name file)) + '("y" "n" "!" "q")) + ("y" (delete-directory file 'recursive trash)) + ("!" (setq helm-ff-allow-recursive-deletes t) + (delete-directory file 'recursive trash)) + ("n" (cl-return 'skip)) + ("q" (throw 'helm-abort-delete-file + (progn + (message "Abort file deletion") (sleep-for 1)))))))) + ((eq (nth 0 file-attrs) t) + (delete-directory file nil trash)) + (t (delete-file file trash))) + (when buffers + (cl-dolist (buf buffers) + (when (y-or-n-p (format "Kill buffer %s, too? " buf)) + (kill-buffer buf))))))) + +(defun helm-delete-marked-files (_ignore) + "Delete marked files with `helm-delete-file'. + +When a prefix arg is given, meaning of `delete-by-moving-to-trash' is +inversed." + (let* ((files (helm-marked-candidates :with-wildcard t)) + (len 0) + (trash (helm-ff--delete-by-moving-to-trash (car files))) + (prmt (if trash "Trash" "Delete")) + (old--allow-recursive-deletes helm-ff-allow-recursive-deletes)) + (with-helm-display-marked-candidates + helm-marked-buffer-name + (helm-ff--count-and-collect-dups files) + (if (not (y-or-n-p (format "%s *%s File(s)" prmt (length files)))) + (message "(No deletions performed)") + (catch 'helm-abort-delete-file + (unwind-protect + (cl-dolist (i files) + (set-text-properties 0 (length i) nil i) + (let ((res (helm-delete-file + i helm-ff-signal-error-on-dot-files nil trash))) + (if (eq res 'skip) + (progn (message "Directory is not empty, skipping") + (sleep-for 1)) + (cl-incf len)))) + (setq helm-ff-allow-recursive-deletes old--allow-recursive-deletes))) + (message "%s File(s) %s" len (if trash "trashed" "deleted")))))) + +;;; Delete files async +;; +;; +(defvar helm-ff-delete-log-file + (expand-file-name "helm-delete-file.log" user-emacs-directory) + "The file use to communicate with emacs child when deleting files async.") + +(defvar helm-ff--trash-flag nil) + +(define-minor-mode helm-ff--delete-async-modeline-mode + "Notify mode-line that an async process run." + :group 'dired-async + :global t + ;; FIXME: Handle jobs like in dired-async, needs first to allow + ;; naming properly processes in async, they are actually all named + ;; emacs and running `async-batch-invoke', so if one copy a file and + ;; delete another file at the same time it may clash. + :lighter (:eval (propertize (format " %s file(s) async ..." + (if helm-ff--trash-flag + "Trashing" "Deleting")) + 'face 'helm-delete-async-message)) + (unless helm-ff--delete-async-modeline-mode + (let ((visible-bell t)) (ding)) + (setq helm-ff--trash-flag nil))) + +(defun helm-delete-async-mode-line-message (text face &rest args) + "Notify end of async operation in `mode-line'." + (message nil) + (let ((mode-line-format (concat + " " (propertize + (if args + (apply #'format text args) + text) + 'face face)))) + (force-mode-line-update) + (sit-for 3) + (force-mode-line-update))) + +(defun helm-delete-marked-files-async (_ignore) + "Same as `helm-delete-marked-files' but async. + +When a prefix arg is given, meaning of `delete-by-moving-to-trash' is +inversed. + +This function is not using `helm-delete-file' and BTW not asking user +for recursive deletion of directory, be warned that directories are +always deleted with no warnings." + (let* ((files (helm-marked-candidates :with-wildcard t)) + (trash (helm-ff--delete-by-moving-to-trash (car files))) + (prmt (if trash "Trash" "Delete")) + (buffers (cl-loop for file in files + for buf = (helm-file-buffers file) + when buf append buf)) + (callback (lambda (result) + (helm-ff--delete-async-modeline-mode -1) + (when (file-exists-p helm-ff-delete-log-file) + (display-warning 'helm + (with-temp-buffer + (insert-file-contents + helm-ff-delete-log-file) + (buffer-string)) + :error + "*helm delete files*") + (fit-window-to-buffer (get-buffer-window + "*helm delete files*")) + (delete-file helm-ff-delete-log-file)) + (when buffers + (dolist (buf buffers) + (let ((last-nonmenu-event t)) + (when (y-or-n-p (format "Kill buffer %s, too? " buf)) + (kill-buffer buf))))) + (run-with-timer + 0.1 nil + (lambda () + (helm-delete-async-mode-line-message + "%s (%s/%s) file(s) async done" + 'helm-delete-async-message + (if trash "Trashing" "Deleting") + result (length files)))))) + ;; Workaround emacs-26 bug with tramp see + ;; https://github.com/jwiegley/emacs-async/issues/80. + (async-quiet-switch "-q")) + (setq helm-ff--trash-flag trash) + (with-helm-display-marked-candidates + helm-marked-buffer-name + (helm-ff--count-and-collect-dups files) + (if (not (y-or-n-p (format "%s *%s File(s)" prmt (length files)))) + (message "(No deletions performed)") + (async-start + `(lambda () + ;; `delete-by-moving-to-trash' have to be set globally, + ;; using the TRASH argument of delete-file or + ;; delete-directory is not enough. + (setq delete-by-moving-to-trash ,trash) + (let ((result 0)) + (dolist (file ',files result) + (condition-case err + (cond ((eq (nth 0 (file-attributes file)) t) + (delete-directory file 'recursive ,trash) + (setq result (1+ result))) + (t (delete-file file ,trash) + (setq result (1+ result)))) + (error (with-temp-file ,helm-ff-delete-log-file + (insert (format-time-string "%x:%H:%M:%S\n")) + (insert (format "%s:%s\n " + (car err) + (mapconcat 'identity (cdr err) " "))))))))) + callback) + (helm-ff--delete-async-modeline-mode 1))))) + +(defun helm-find-file-or-marked (candidate) + "Open file CANDIDATE or open helm marked files in separate windows. +Called with one prefix arg open files in separate windows in a +vertical split. +Called with two prefix arg open files in background without selecting them." + (let ((marked (helm-marked-candidates :with-wildcard t)) + (url-p (and helm--url-regexp ; we should have only one candidate. + (string-match helm--url-regexp candidate))) + (ffap-newfile-prompt helm-ff-newfile-prompt-p) + (find-file-wildcards nil) + (helm--reading-passwd-or-string t)) + (if (cdr marked) + (if (equal helm-current-prefix-arg '(16)) + (mapcar 'find-file-noselect marked) + ;; If helm-current-prefix-arg is detected split is done + ;; vertically. + (helm-window-show-buffers (mapcar 'find-file-noselect marked))) + (let ((dir (and (not url-p) (helm-basedir candidate)))) + (cond ((and dir (file-directory-p dir)) + (find-file (substitute-in-file-name candidate))) + (url-p (find-file-at-point candidate)) + ;; A a non--existing filename ending with / + ;; Create a directory and jump to it. + ((and (not (file-exists-p candidate)) + (string-match "/$" candidate)) + (helm-ff--mkdir candidate 'helm-ff)) + ;; A non--existing filename NOT ending with / or + ;; an existing filename, create or jump to it. + ;; If the basedir of candidate doesn't exists, + ;; ask for creating it. + (dir + (helm-ff--mkdir dir) + (find-file candidate)) + ;; Find file at `default-directory' when basedir is + ;; unspecified e.g user hit C-k foo RET. + (t (find-file candidate))))))) + +(defun helm-ff--mkdir (dir &optional helm-ff) + (when (or (not confirm-nonexistent-file-or-buffer) + (y-or-n-p (format "Create directory `%s'? " + (abbreviate-file-name + (expand-file-name dir))))) + (let ((dirfname (directory-file-name dir))) + (if (file-exists-p dirfname) + (error + "Mkdir: Unable to create directory `%s': file exists." + (helm-basename dirfname)) + (make-directory dir 'parent))) + (when helm-ff + ;; Allow having this new dir in history + ;; to be able to retrieve it immediately + ;; if we want to e.g copy a file from somewhere in it. + (setq helm-ff-default-directory + (file-name-as-directory (expand-file-name dir))) + (push helm-ff-default-directory helm-ff-history)) + (or (and helm-ff (helm-find-files-1 dir)) t))) + +(defun helm-transform-file-load-el (actions candidate) + "Add action to load the file CANDIDATE if it is an emacs lisp +file. Else return ACTIONS unmodified." + (if (member (file-name-extension candidate) '("el" "elc")) + (append actions '(("Load Emacs Lisp File" . load-file))) + actions)) + +(defun helm-transform-file-browse-url (actions candidate) + "Add an action to browse the file CANDIDATE if it is a html file or URL. +Else return ACTIONS unmodified." + (let ((browse-action '("Browse with Browser" . browse-url))) + (cond ((string-match "^http\\|^ftp" candidate) + (cons browse-action actions)) + ((string-match "\\.html?$" candidate) + (append actions (list browse-action))) + (t actions)))) + +(defun helm-file-on-mounted-network-p (file) + "Returns non-nil when FILE is part of a mounted remote directory. + +This function is checking `helm-mounted-network-directories' list." + (when helm-mounted-network-directories + (cl-loop for dir in helm-mounted-network-directories + thereis (file-in-directory-p file dir)))) + +;; helm-find-files bindings for filecache +(defvar file-cache-alist) + +(defun helm-ff-cache-add-file (_candidate) + (require 'filecache) + (let ((mkd (helm-marked-candidates :with-wildcard t))) + (mapc 'file-cache-add-file mkd))) + +(defun helm-ff-file-cache-remove-file-1 (file) + "Remove FILE from `file-cache-alist'." + (let ((entry (assoc (helm-basename file) file-cache-alist)) + (dir (helm-basedir file)) + new-entry) + (setq new-entry (remove dir entry)) + (when (= (length entry) 1) + (setq new-entry nil)) + (setq file-cache-alist + (cons new-entry (remove entry file-cache-alist))))) + +(defun helm-ff-file-cache-remove-file (_file) + "Remove marked files from `file-cache-alist.'" + (let ((mkd (helm-marked-candidates))) + (mapc 'helm-ff-file-cache-remove-file-1 mkd))) + + +;;; File name history +;; +;; +(defvar helm-source-file-name-history + (helm-build-sync-source "File Name History" + :candidates 'file-name-history + :persistent-action #'ignore + :filtered-candidate-transformer #'helm-file-name-history-transformer + :action 'helm-type-file-actions)) + +(defvar helm-source--ff-file-name-history nil + "[Internal] This source is build to be used with `helm-find-files'. +Don't use it in your own code unless you know what you are doing.") + +(defun helm-file-name-history-transformer (candidates _source) + (cl-loop for c in candidates collect + (cond ((or (file-remote-p c) + (and (fboundp 'tramp-archive-file-name-p) + (tramp-archive-file-name-p c))) + (cons (propertize c 'face 'helm-history-remote) c)) + ((file-exists-p c) + (cons (propertize c 'face 'helm-ff-file) c)) + (t (cons (propertize c 'face 'helm-history-deleted) c))))) + +(defun helm-ff-file-name-history () + "Switch to `file-name-history' without quitting `helm-find-files'." + (interactive) + (unless helm-source--ff-file-name-history + (setq helm-source--ff-file-name-history + (helm-build-sync-source "File name history" + :init (lambda () + (with-helm-alive-p + (require 'tramp-archive nil t) + (when helm-ff-file-name-history-use-recentf + (require 'recentf) + (or recentf-mode (recentf-mode 1))))) + :candidates (lambda () + (if helm-ff-file-name-history-use-recentf + recentf-list + file-name-history)) + :fuzzy-match t + :persistent-action 'ignore + :migemo t + :filtered-candidate-transformer 'helm-file-name-history-transformer + :action (helm-make-actions + "Find file" (lambda (candidate) + (helm-set-pattern + (expand-file-name candidate)) + (with-helm-after-update-hook (helm-exit-minibuffer))) + "Find file in helm" (lambda (candidate) + (helm-set-pattern + (expand-file-name candidate))))))) + (with-helm-alive-p + (helm :sources 'helm-source--ff-file-name-history + :buffer "*helm-file-name-history*" + :allow-nest t + :resume 'noresume))) +(put 'helm-ff-file-name-history 'helm-only t) + +;;; Browse project +;; Need dependencies: +;; +;; +;; Only hg and git are supported for now. +(defvar helm--browse-project-cache (make-hash-table :test 'equal)) +(defvar helm-buffers-in-project-p) + +(defun helm-browse-project-get-buffers (root-directory) + (cl-loop for b in (helm-buffer-list) + ;; FIXME: Why default-directory is root-directory + ;; for current-buffer when coming from helm-quit-and-find-file. + for cd = (with-current-buffer b default-directory) + for bn = (buffer-file-name (get-buffer b)) + if (or (and bn (file-in-directory-p bn root-directory)) + (and (null bn) + (not (file-remote-p cd)) + (file-in-directory-p cd root-directory))) + collect b)) + +(defun helm-browse-project-build-buffers-source (directory) + (helm-make-source "Buffers in project" 'helm-source-buffers + :header-name (lambda (name) + (format + "%s (%s)" + name (abbreviate-file-name directory))) + :buffer-list (lambda () (helm-browse-project-get-buffers directory)))) + +(defun helm-browse-project-walk-directory (directory) + "Default function for `helm-browse-project-default-find-files-fn'." + (helm-walk-directory + directory + :directories nil :path 'full :skip-subdirs t)) + +(defun helm-browse-project-ag-find-files (directory) + "A suitable function for `helm-browse-project-default-find-files-fn'. + +Needs AG as backend." + (with-temp-buffer + (call-process-shell-command + (format "ag --hidden -g '.*' %s" directory) + nil t nil) + (mapcar (lambda (f) (expand-file-name f directory)) + (split-string (buffer-string) "\n")))) + +(defun helm-browse-project-find-files (directory &optional refresh) + (when refresh (remhash directory helm--browse-project-cache)) + (unless (gethash directory helm--browse-project-cache) + (puthash directory (funcall helm-browse-project-default-find-files-fn + directory) + helm--browse-project-cache)) + (helm :sources `(,(helm-browse-project-build-buffers-source directory) + ,(helm-build-in-buffer-source "Browse project" + :data (gethash directory helm--browse-project-cache) + :header-name (lambda (name) + (format + "%s (%s)" + name (abbreviate-file-name directory))) + :match-part (lambda (c) + (if (with-helm-buffer + helm-ff-transformer-show-only-basename) + (helm-basename c) c)) + :filter-one-by-one + (lambda (c) + (if (with-helm-buffer + helm-ff-transformer-show-only-basename) + (cons (propertize (helm-basename c) + 'face 'helm-ff-file) + c) + (propertize c 'face 'helm-ff-file))) + :keymap helm-generic-files-map + :action 'helm-type-file-actions)) + :ff-transformer-show-only-basename nil + :buffer "*helm browse project*")) + +(defvar helm-browse-project-history nil) + +;;;###autoload +(defun helm-projects-history () + (interactive) + (helm :sources + (helm-build-sync-source "Project history" + :candidates helm-browse-project-history + :action (lambda (candidate) + (with-helm-default-directory candidate + (helm-browse-project nil)))) + :buffer "*helm browse project history*")) + +;;;###autoload +(defun helm-browse-project (arg) + "Preconfigured helm to browse projects. +Browse files and see status of project with its vcs. +Only HG and GIT are supported for now. +Fall back to `helm-browse-project-find-files' +if current directory is not under control of one of those vcs. +With a prefix ARG browse files recursively, with two prefix ARG +rebuild the cache. +If the current directory is found in the cache, start +`helm-browse-project-find-files' even with no prefix ARG. +NOTE: The prefix ARG have no effect on the VCS controlled directories. + +Needed dependencies for VCS: + +and +." + (interactive "P") + (let ((helm-type-buffer-actions + (remove (assoc "Browse project from buffer" + helm-type-buffer-actions) + helm-type-buffer-actions)) + (helm-buffers-in-project-p t)) + (cl-flet ((push-to-hist (root) + (setq helm-browse-project-history + (cons root (delete root helm-browse-project-history))))) + (helm-acond ((and (require 'helm-ls-git nil t) + (fboundp 'helm-ls-git-root-dir) + (helm-ls-git-root-dir)) + (push-to-hist it) + (helm-ls-git-ls)) + ((and (require 'helm-ls-hg nil t) + (fboundp 'helm-hg-root) + (helm-hg-root)) + (push-to-hist it) + (helm-hg-find-files-in-project)) + ((helm-browse-project-get--root-dir (helm-current-directory)) + (if (or arg (gethash it helm--browse-project-cache)) + (progn + (push-to-hist it) + (helm-browse-project-find-files it (equal arg '(16)))) + (helm :sources (helm-browse-project-build-buffers-source it) + :buffer "*helm browse project*"))))))) + +(defun helm-browse-project-get--root-dir (directory) + (cl-loop with dname = (file-name-as-directory directory) + while (and dname (not (gethash dname helm--browse-project-cache))) + if (file-remote-p dname) + do (setq dname nil) else + do (setq dname (helm-basedir (substring dname 0 (1- (length dname))))) + finally return (or dname (file-name-as-directory directory)))) + +(defun helm-ff-browse-project (_candidate) + "Browse project in current directory. +See `helm-browse-project'." + (with-helm-default-directory helm-ff-default-directory + (helm-browse-project helm-current-prefix-arg))) + +(defun helm-ff-run-browse-project () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-browse-project))) +(put 'helm-ff-run-browse-project 'helm-only t) + +(defun helm-ff-gid (_candidate) + (with-helm-default-directory helm-ff-default-directory + (helm-gid))) + +(defun helm-ff-run-gid () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-gid))) +(put 'helm-ff-run-gid 'helm-only t) + +;; helm-find bindings for helm-find-files. +(defun helm-ff-find-sh-command (_candidate) + "Run `helm-find' from `helm-find-files'." + (require 'helm-find) + (helm-find-1 helm-ff-default-directory)) + +(defun helm-ff-run-find-sh-command () + "Run find shell command action with key from `helm-find-files'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-ff-find-sh-command))) +(put 'helm-ff-run-find-sh-command 'helm-only t) + + +;;;###autoload +(defun helm-find-files (arg) + "Preconfigured `helm' for helm implementation of `find-file'. +Called with a prefix arg show history if some. +Don't call it from programs, use `helm-find-files-1' instead. +This is the starting point for nearly all actions you can do on files." + (interactive "P") + (let* ((hist (and arg helm-ff-history (helm-find-files-history nil))) + (smart-input (or hist (helm-find-files-initial-input))) + (default-input (expand-file-name (helm-current-directory))) + (input (cond ((and (null hist) + helm-find-files-ignore-thing-at-point) + default-input) + ((and (eq major-mode 'org-agenda-mode) + org-directory + (not smart-input)) + (expand-file-name org-directory)) + ((and (eq major-mode 'dired-mode) smart-input) + (file-name-directory smart-input)) + ((and (not (string= smart-input "")) + smart-input)) + (t default-input))) + (input-as-presel (null (nth 0 (file-attributes input)))) + (presel (helm-aif (or hist + (and input-as-presel input) + (buffer-file-name (current-buffer)) + (and (eq major-mode 'dired-mode) + smart-input)) + (if (and helm-ff-transformer-show-only-basename + (null hist) + (not (string-match-p "[.]\\{1,2\\}\\'" it))) + (helm-basename it) it)))) + ;; Continue using the same display function as history which used + ;; probably itself the same display function as inner HFF call, + ;; i.e. if history was using frame use a frame otherwise use a window. + (when (and hist (buffer-live-p (get-buffer helm-ff-history-buffer-name))) + (helm-set-local-variable 'helm-display-function + (with-current-buffer helm-ff-history-buffer-name + helm-display-function) + 'helm--last-frame-parameters + (with-current-buffer helm-ff-history-buffer-name + helm--last-frame-parameters))) + (set-text-properties 0 (length input) nil input) + (setq current-prefix-arg nil) + ;; Allow next helm session to reuse helm--last-frame-parameters as + ;; resume would do. + (let ((helm--executing-helm-action (not (null hist)))) + (helm-find-files-1 input (and presel (null helm-ff-no-preselect) + (concat "^" (regexp-quote presel))))))) + +;;;###autoload +(defun helm-delete-tramp-connection () + "Allow deleting tramp connection or marked tramp connections at once. + +This replace `tramp-cleanup-connection' which is partially broken in +emacs < to 25.1.50.1 (See Emacs Bug#24432). + +It allows additionally to delete more than one connection at once." + (interactive) + (let ((helm-quit-if-no-candidate + (lambda () + (message "No Tramp connection found")))) + (helm :sources (helm-build-sync-source "Tramp connections" + :candidates (tramp-list-connections) + :candidate-transformer (lambda (candidates) + (cl-loop for v in candidates + for name = (apply #'tramp-make-tramp-file-name + (cl-loop with v = (helm-ff--tramp-cons-or-vector v) + for i across v collect i)) + when (or (processp (tramp-get-connection-process v)) + (buffer-live-p (get-buffer (tramp-buffer-name v)))) + collect (cons name v))) + :action (lambda (_vec) + (let ((vecs (helm-marked-candidates))) + (cl-loop for v in vecs + do (progn + (tramp-cleanup-connection v) + (remhash v tramp-cache-data)))))) + :buffer "*helm tramp connections*"))) + + +(provide 'helm-files) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-files.el ends here diff --git a/elpa/helm-20181113.923/helm-find.el b/elpa/helm-20181113.923/helm-find.el new file mode 100644 index 00000000..80b3ecc6 --- /dev/null +++ b/elpa/helm-20181113.923/helm-find.el @@ -0,0 +1,179 @@ +;;; helm-find.el --- helm interface for find command. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'helm-files) +(require 'helm-external) + +(defcustom helm-findutils-skip-boring-files t + "Ignore boring files in find command results." + :group 'helm-files + :type 'boolean) + +(defcustom helm-findutils-search-full-path nil + "Search in full path with shell command find when non--nil. +I.e use the -path/ipath arguments of find instead of -name/iname." + :group 'helm-files + :type 'boolean) + +(defvar helm-find-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-generic-files-map) + (define-key map (kbd "DEL") 'helm-delete-backward-no-update) + map)) + +(defvar helm-source-findutils + (helm-build-async-source "Find" + :header-name (lambda (name) + (concat name " in [" (helm-default-directory) "]")) + :candidates-process 'helm-find-shell-command-fn + :filtered-candidate-transformer 'helm-findutils-transformer + :action-transformer 'helm-transform-file-load-el + :persistent-action 'helm-ff-kill-or-find-buffer-fname + :action 'helm-type-file-actions + :help-message 'helm-generic-file-help-message + :keymap helm-find-map + :candidate-number-limit 9999 + :requires-pattern 3)) + +(defun helm-findutils-transformer (candidates _source) + (let (non-essential + (default-directory (helm-default-directory))) + (cl-loop for i in candidates + for abs = (expand-file-name + (helm-aif (file-remote-p default-directory) + (concat it i) i)) + for type = (car (file-attributes abs)) + for disp = (if (and helm-ff-transformer-show-only-basename + (not (string-match "[.]\\{1,2\\}$" i))) + (helm-basename abs) abs) + collect (cond ((eq t type) + (cons (propertize disp 'face 'helm-ff-directory) + abs)) + ((stringp type) + (cons (propertize disp 'face 'helm-ff-symlink) + abs)) + (t (cons (propertize disp 'face 'helm-ff-file) + abs)))))) + +(defun helm-find--build-cmd-line () + (require 'find-cmd) + (let* ((default-directory (or (file-remote-p default-directory 'localname) + default-directory)) + (patterns+options (split-string helm-pattern "\\(\\`\\| +\\)\\* +")) + (fold-case (helm-set-case-fold-search (car patterns+options))) + (patterns (split-string (car patterns+options))) + (additional-options (and (cdr patterns+options) + (list (concat (cadr patterns+options) " ")))) + (ignored-dirs ()) + (ignored-files (when helm-findutils-skip-boring-files + (cl-loop for f in completion-ignored-extensions + if (string-match "/$" f) + do (push (replace-match "" nil t f) + ignored-dirs) + else collect (concat "*" f)))) + (path-or-name (if helm-findutils-search-full-path + '(ipath path) '(iname name))) + (name-or-iname (if fold-case + (car path-or-name) (cadr path-or-name)))) + (find-cmd (and ignored-dirs + `(prune (name ,@ignored-dirs))) + (and ignored-files + `(not (name ,@ignored-files))) + `(and ,@(mapcar + (lambda (pattern) + `(,name-or-iname ,(concat "*" pattern "*"))) + patterns) + ,@additional-options)))) + +(defun helm-find-shell-command-fn () + "Asynchronously fetch candidates for `helm-find'. +Additional find options can be specified after a \"*\" +separator." + (let* (process-connection-type + non-essential + (cmd (helm-find--build-cmd-line)) + (proc (start-file-process-shell-command "hfind" helm-buffer cmd))) + (helm-log "Find command:\n%s" cmd) + (prog1 proc + (set-process-sentinel + proc + (lambda (process event) + (helm-process-deferred-sentinel-hook + process event (helm-default-directory)) + (if (string= event "finished\n") + (with-helm-window + (setq mode-line-format + '(" " mode-line-buffer-identification " " + (:eval (format "L%s" (helm-candidate-number-at-point))) " " + (:eval (propertize + (format "[Find process finished - (%s results)]" + (max (1- (count-lines + (point-min) (point-max))) + 0)) + 'face 'helm-locate-finish)))) + (force-mode-line-update)) + (helm-log "Error: Find %s" + (replace-regexp-in-string "\n" "" event)))))))) + +(defun helm-find-1 (dir) + (let ((default-directory (file-name-as-directory dir))) + (helm :sources 'helm-source-findutils + :buffer "*helm find*" + :ff-transformer-show-only-basename nil + :case-fold-search helm-file-name-case-fold-search))) + + +;;; Preconfigured commands +;; +;; +;;;###autoload +(defun helm-find (arg) + "Preconfigured `helm' for the find shell command. + +Recursively find files whose names are matched by all specified +globbing PATTERNs under the current directory using the external +program specified in `find-program' (usually \"find\"). Every +input PATTERN is silently wrapped into two stars: *PATTERN*. + +With prefix argument, prompt for a directory to search. + +When user option `helm-findutils-search-full-path' is non-nil, +match against complete paths, otherwise, against file names +without directory part. + +The (possibly empty) list of globbing PATTERNs can be followed by +the separator \"*\" plus any number of additional arguments that +are passed to \"find\" literally." + (interactive "P") + (let ((directory + (if arg + (file-name-as-directory + (read-directory-name "DefaultDirectory: ")) + default-directory))) + (helm-find-1 directory))) + +(provide 'helm-find) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-find.el ends here diff --git a/elpa/helm-20181113.923/helm-font.el b/elpa/helm-20181113.923/helm-font.el new file mode 100644 index 00000000..c4e25d9d --- /dev/null +++ b/elpa/helm-20181113.923/helm-font.el @@ -0,0 +1,335 @@ +;;; helm-font --- Font and ucs selection for Helm -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-help) + + +(defgroup helm-font nil + "Related applications to display fonts in helm." + :group 'helm) + +(defcustom helm-ucs-recent-size 10 + "Number of recent chars to keep." + :type 'integer + :group 'helm-font) + +(defcustom helm-ucs-actions + '(("Insert character" . helm-ucs-insert-char) + ("Insert character name" . helm-ucs-insert-name) + ("Insert character code in hex" . helm-ucs-insert-code) + ("Kill marked characters" . helm-ucs-kill-char) + ("Kill name" . helm-ucs-kill-name) + ("Kill code" . helm-ucs-kill-code)) + "Actions for `helm-source-ucs'." + :group 'helm-font + :type '(alist :key-type string :value-type function)) + +(defvar helm-ucs-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "") 'helm-ucs-persistent-delete) + (define-key map (kbd "") 'helm-ucs-persistent-backward) + (define-key map (kbd "") 'helm-ucs-persistent-forward) + (define-key map (kbd "C-c SPC") 'helm-ucs-persistent-insert-space) + map) + "Keymap for `helm-ucs'.") + +(defface helm-ucs-char + '((((class color) (background dark)) (:foreground "Gold"))) + "Face used to display ucs characters." + :group 'helm-font) + +;;; Xfont selection +;; +;; +(defvar helm-xfonts-cache nil) +(defvar helm-previous-font nil) +(defvar helm-source-xfonts + (helm-build-sync-source "X Fonts" + :init (lambda () + (unless helm-xfonts-cache + (setq helm-xfonts-cache + (x-list-fonts "*"))) + ;; Save current font so it can be restored in cleanup + (setq helm-previous-font (cdr (assq 'font (frame-parameters))))) + :candidates 'helm-xfonts-cache + :action '(("Copy font to kill ring" . (lambda (elm) + (kill-new elm))) + ("Set font" . (lambda (elm) + (kill-new elm) + (set-frame-font elm 'keep-size) + (message "Font copied to kill ring")))) + :cleanup (lambda () + ;; Restore previous font + (set-frame-font helm-previous-font 'keep-size)) + :persistent-action (lambda (new-font) + (set-frame-font new-font 'keep-size) + (kill-new new-font)) + :persistent-help "Preview font and copy to kill-ring")) + + +;;; 𝕌𝕔𝕤 𝕊𝕪𝕞𝕓𝕠𝕝 𝕔𝕠𝕞𝕡𝕝𝕖𝕥𝕚𝕠𝕟 +;; +;; +(defvar helm-ucs--max-len nil) +(defvar helm-ucs--names nil) +(defvar helm-ucs-history nil) +(defvar helm-ucs-recent nil + "Ring of recent `helm-ucs' selections.") + +(defun helm-calculate-ucs-alist-max-len (names) + "Calculate the length of the longest NAMES list candidate." + (cl-loop for (_n . v) in names + maximize (length (format "#x%x:" v)) into code + maximize (max 1 (string-width (format "%c" v))) into char + finally return (cons code char))) + +(defun helm-calculate-ucs-hash-table-max-len (names) + "Calculate the length of the longest NAMES hash table candidate." + (cl-loop for _n being the hash-keys of names + using (hash-values v) + maximize (length (format "#x%x:" v)) into code + maximize (max 1 (string-width (format "%c" v))) into char + finally return (cons code char))) + +(defun helm-calculate-ucs-max-len () + "Calculate the length of longest `ucs-names' candidate." + (let ((ucs-struct (ucs-names))) + (if (hash-table-p ucs-struct) + (helm-calculate-ucs-hash-table-max-len ucs-struct) + (helm-calculate-ucs-alist-max-len ucs-struct)))) + +(defun helm-ucs-collect-symbols-alist (names) + "Collect ucs symbols from the NAMES list." + (cl-loop with pr = (make-progress-reporter + "collecting ucs names" + 0 (length names)) + for (n . v) in names + for count from 1 + for xcode = (format "#x%x:" v) + for len = (length xcode) + for diff = (- (car helm-ucs--max-len) len) + for code = (format "(#x%x): " v) + for char = (propertize (format "%c" v) + 'face 'helm-ucs-char) + unless (or (string= "" n) + ;; `char-displayable-p' return a font object or + ;; t for some char that are displayable but have + ;; no special font (e.g 10) so filter out char + ;; with no font. + (not (fontp (char-displayable-p (read xcode))))) + collect + (concat code (make-string diff ? ) + char " " n) + and do (progress-reporter-update pr count))) + +(defun helm-ucs-collect-symbols-hash-table (names) + "Collect ucs symbols from the NAMES hash-table." + (cl-loop with pr = (make-progress-reporter + "collecting ucs names" + 0 (hash-table-count names)) + for n being the hash-keys of names + using (hash-values v) + for count from 1 + for xcode = (format "#x%x:" v) + for len = (length xcode) + for diff = (- (car helm-ucs--max-len) len) + for code = (format "(#x%x): " v) + for char = (propertize (format "%c" v) + 'face 'helm-ucs-char) + unless (or (string= "" n) + (not (fontp (char-displayable-p (read xcode))))) + collect + (concat code (make-string diff ? ) + char " " n) + and do (progress-reporter-update pr count))) + +(defun helm-ucs-collect-symbols (ucs-struct) + "Collect ucs symbols from UCS-STRUCT. + +Depending on the Emacs version, the variable `ucs-names' can +either be an alist or a hash-table." + (if (hash-table-p ucs-struct) + (helm-ucs-collect-symbols-hash-table ucs-struct) + (helm-ucs-collect-symbols-alist ucs-struct))) + +(defun helm-ucs-init () + "Initialize an helm buffer with ucs symbols. +Only math* symbols are collected." + (unless helm-ucs--max-len + (setq helm-ucs--max-len + (helm-calculate-ucs-max-len))) + (or helm-ucs--names + (setq helm-ucs--names + (helm-ucs-collect-symbols (ucs-names))))) + +;; Actions (insertion) + +(defun helm-ucs-match (candidate n) + "Return the N part of an ucs CANDIDATE. +Where N=1 is the ucs code, N=2 the ucs char and N=3 the ucs name." + (when (string-match + "^(\\(#x[a-f0-9]+\\)): *\\(.\\) *\\([^:]+\\)+" + candidate) + (match-string n candidate))) + +(defun helm-ucs-save-recentest (candidate) + (let ((lst (cons candidate (delete candidate helm-ucs-recent)))) + (setq helm-ucs-recent + (if (> (length lst) helm-ucs-recent-size) + (nbutlast lst 1) + lst)))) + +(defun helm-ucs-insert (candidate n) + "Insert the N part of CANDIDATE." + (with-helm-current-buffer + (helm-ucs-save-recentest candidate) + (insert (helm-ucs-match candidate n)))) + +(defun helm-ucs-insert-char (candidate) + "Insert ucs char part of CANDIDATE at point." + (helm-ucs-insert candidate 2)) + +(defun helm-ucs-insert-code (candidate) + "Insert ucs code part of CANDIDATE at point." + (helm-ucs-insert candidate 1)) + +(defun helm-ucs-insert-name (candidate) + "Insert ucs name part of CANDIDATE at point." + (helm-ucs-insert candidate 3)) + +;; Kill actions +(defun helm-ucs-kill-char (_candidate) + "Action that concatenate ucs marked chars." + (let ((marked (helm-marked-candidates))) + (cl-loop for candidate in marked + do (helm-ucs-save-recentest candidate)) + (kill-new (mapconcat (lambda (x) + (helm-ucs-match x 2)) + marked "")))) + +(defun helm-ucs-kill-code (candidate) + (helm-ucs-save-recentest candidate) + (kill-new (helm-ucs-match candidate 1))) + +(defun helm-ucs-kill-name (candidate) + (helm-ucs-save-recentest candidate) + (kill-new (helm-ucs-match candidate 3))) + +;; Navigation in current-buffer (persistent) + +(defun helm-ucs-forward-char (_candidate) + (with-helm-current-buffer + (forward-char 1))) + +(defun helm-ucs-backward-char (_candidate) + (with-helm-current-buffer + (forward-char -1))) + +(defun helm-ucs-delete-backward (_candidate) + (with-helm-current-buffer + (delete-char -1))) + +(defun helm-ucs-insert-space (_candidate) + (with-helm-current-buffer + (insert " "))) + +(defun helm-ucs-persistent-forward () + (interactive) + (with-helm-alive-p + (helm-attrset 'action-forward 'helm-ucs-forward-char) + (helm-execute-persistent-action 'action-forward))) +(put 'helm-ucs-persistent-forward 'helm-only t) + +(defun helm-ucs-persistent-backward () + (interactive) + (with-helm-alive-p + (helm-attrset 'action-back 'helm-ucs-backward-char) + (helm-execute-persistent-action 'action-back))) +(put 'helm-ucs-persistent-backward 'helm-only t) + +(defun helm-ucs-persistent-delete () + (interactive) + (with-helm-alive-p + (helm-attrset 'action-delete 'helm-ucs-delete-backward) + (helm-execute-persistent-action 'action-delete))) +(put 'helm-ucs-persistent-delete 'helm-only t) + +(defun helm-ucs-persistent-insert-space () + (interactive) + (with-helm-alive-p + (helm-attrset 'action-insert-space 'helm-ucs-insert-space) + (helm-execute-persistent-action 'action-insert-space))) + +(defvar helm-source-ucs-recent + (helm-build-sync-source "Recent UCS" + :action helm-ucs-actions + :candidates (lambda () helm-ucs-recent) + :help-message helm-ucs-help-message + :keymap helm-ucs-map + :volatile t)) + +(defvar helm-source-ucs + (helm-build-in-buffer-source "UCS names" + :data #'helm-ucs-init + :get-line #'buffer-substring + :help-message 'helm-ucs-help-message + :filtered-candidate-transformer + (lambda (candidates _source) (sort candidates #'helm-generic-sort-fn)) + :action helm-ucs-actions + :persistent-action (lambda (candidate) + (helm-ucs-insert-char candidate) + (helm-force-update)) + :keymap helm-ucs-map) + "Source for collecting `ucs-names' math symbols.") + +;;;###autoload +(defun helm-select-xfont () + "Preconfigured `helm' to select Xfont." + (interactive) + (helm :sources 'helm-source-xfonts + :buffer "*helm select xfont*")) + +;;;###autoload +(defun helm-ucs (arg) + "Preconfigured helm for `ucs-names'. + +Called with a prefix arg force reloading cache." + (interactive "P") + (when arg + (setq helm-ucs--names nil + helm-ucs--max-len nil + ucs-names nil)) + (let ((char (helm-aif (char-after) (string it)))) + (helm :sources (list helm-source-ucs-recent helm-source-ucs) + :history 'helm-ucs-history + :input (and char (multibyte-string-p char) char) + :buffer "*helm ucs*"))) + +(provide 'helm-font) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-font.el ends here diff --git a/elpa/helm-20181113.923/helm-for-files.el b/elpa/helm-20181113.923/helm-for-files.el new file mode 100644 index 00000000..c259704d --- /dev/null +++ b/elpa/helm-20181113.923/helm-for-files.el @@ -0,0 +1,308 @@ +;;; helm-for-files.el --- helm-for-files and related. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'helm-files) +(require 'helm-external) +(require 'helm-bookmark) + +(defcustom helm-multi-files-toggle-locate-binding "C-c p" + "Default binding to switch back and forth locate in `helm-multi-files'." + :group 'helm-files + :type 'string) + +(defcustom helm-for-files-preferred-list + '(helm-source-buffers-list + helm-source-recentf + helm-source-bookmarks + helm-source-file-cache + helm-source-files-in-current-dir + helm-source-locate) + "Your preferred sources for `helm-for-files' and `helm-multi-files'. + +When adding a source here it is up to you to ensure the library of +this source is accessible and properly loaded." + :type '(repeat (choice symbol)) + :group 'helm-files) + +(defcustom helm-for-files-tramp-not-fancy t + "Colorize remote files when non nil. + +Be aware that a nil value will make tramp display very slow." + :group 'helm-files + :type 'boolean) + +;;; File Cache +;; +;; +(defvar file-cache-alist) + +(defclass helm-file-cache (helm-source-in-buffer helm-type-file) + ((init :initform (lambda () (require 'filecache))))) + +(defun helm-file-cache-get-candidates () + (cl-loop for item in file-cache-alist append + (cl-destructuring-bind (base &rest dirs) item + (cl-loop for dir in dirs collect + (concat dir base))))) + +(defvar helm-source-file-cache nil) + +(defcustom helm-file-cache-fuzzy-match nil + "Enable fuzzy matching in `helm-source-file-cache' when non--nil." + :group 'helm-files + :type 'boolean + :set (lambda (var val) + (set var val) + (setq helm-source-file-cache + (helm-make-source "File Cache" 'helm-file-cache + :fuzzy-match helm-file-cache-fuzzy-match + :data 'helm-file-cache-get-candidates)))) + +(cl-defun helm-file-cache-add-directory-recursively + (dir &optional match (ignore-dirs t)) + (require 'filecache) + (cl-loop for f in (helm-walk-directory + dir + :path 'full + :directories nil + :match match + :skip-subdirs ignore-dirs) + do (file-cache-add-file f))) + +(defun helm-transform-file-cache (actions _candidate) + (let ((source (helm-get-current-source))) + (if (string= (assoc-default 'name source) "File Cache") + (append actions + '(("Remove marked files from file-cache" + . helm-ff-file-cache-remove-file))) + actions))) + +;;; Recentf files +;; +;; +(defvar helm-recentf--basename-flag nil) + +(defun helm-recentf-pattern-transformer (pattern) + (let ((pattern-no-flag (replace-regexp-in-string " -b" "" pattern))) + (cond ((and (string-match " " pattern-no-flag) + (string-match " -b\\'" pattern)) + (setq helm-recentf--basename-flag t) + pattern-no-flag) + ((string-match "\\([^ ]*\\) -b\\'" pattern) + (prog1 (match-string 1 pattern) + (setq helm-recentf--basename-flag t))) + (t (setq helm-recentf--basename-flag nil) + pattern)))) + +(defcustom helm-turn-on-recentf t + "Automatically turn on `recentf-mode' when non-nil." + :group 'helm-files + :type 'boolean) + +(defclass helm-recentf-source (helm-source-sync helm-type-file) + ((init :initform (lambda () + (require 'recentf) + (when helm-turn-on-recentf (recentf-mode 1)))) + (candidates :initform (lambda () recentf-list)) + (pattern-transformer :initform 'helm-recentf-pattern-transformer) + (match-part :initform (lambda (candidate) + (if (or helm-ff-transformer-show-only-basename + helm-recentf--basename-flag) + (helm-basename candidate) candidate))) + (migemo :initform t) + (persistent-action :initform 'helm-ff-kill-or-find-buffer-fname))) + +(defmethod helm--setup-source :after ((source helm-recentf-source)) + (setf (slot-value source 'action) + (append (symbol-value (helm-actions-from-type-file)) + '(("Delete file(s) from recentf" . + (lambda (_candidate) + (cl-loop for file in (helm-marked-candidates) + do (setq recentf-list (delete file recentf-list))))))))) + +(defvar helm-source-recentf nil + "See (info \"(emacs)File Conveniences\"). +Set `recentf-max-saved-items' to a bigger value if default is too small.") + +(defcustom helm-recentf-fuzzy-match nil + "Enable fuzzy matching in `helm-source-recentf' when non--nil." + :group 'helm-files + :type 'boolean + :set (lambda (var val) + (set var val) + (let ((helm-fuzzy-sort-fn 'helm-fuzzy-matching-sort-fn-preserve-ties-order)) + (setq helm-source-recentf + (helm-make-source "Recentf" 'helm-recentf-source + :fuzzy-match helm-recentf-fuzzy-match))))) + + +;;; Files in current dir +;; +;; +(defun helm-highlight-files (files _source) + "A basic transformer for helm files sources. +Colorize only symlinks, directories and files." + (cl-loop with mp-fn = (or (assoc-default + 'match-part (helm-get-current-source)) + 'identity) + for i in files + for disp = (if (and helm-ff-transformer-show-only-basename + (not (helm-dir-is-dot i)) + (not (and helm--url-regexp + (string-match helm--url-regexp i))) + (not (string-match helm-ff-url-regexp i))) + (helm-basename i) (abbreviate-file-name i)) + for isremote = (or (file-remote-p i) + (helm-file-on-mounted-network-p i)) + ;; Call file-attributes only if: + ;; - file is not remote + ;; - helm-for-files--tramp-not-fancy is nil and file is remote AND + ;; connected. (Issue #1679) + for type = (and (or (null isremote) + (and (null helm-for-files-tramp-not-fancy) + (file-remote-p i nil t))) + (car (file-attributes i))) + collect + (cond ((and (null type) isremote) (cons disp i)) + ((stringp type) + (cons (propertize disp + 'face 'helm-ff-symlink + 'match-part (funcall mp-fn disp) + 'help-echo (expand-file-name i)) + i)) + ((eq type t) + (cons (propertize disp + 'face 'helm-ff-directory + 'match-part (funcall mp-fn disp) + 'help-echo (expand-file-name i)) + i)) + (t (cons (propertize disp + 'face 'helm-ff-file + 'match-part (funcall mp-fn disp) + 'help-echo (expand-file-name i)) + i))))) + +(defclass helm-files-in-current-dir-source (helm-source-sync helm-type-file) + ((candidates :initform (lambda () + (with-helm-current-buffer + (let ((dir (helm-current-directory))) + (when (file-accessible-directory-p dir) + (directory-files dir t)))))) + (pattern-transformer :initform 'helm-recentf-pattern-transformer) + (match-part :initform (lambda (candidate) + (if (or helm-ff-transformer-show-only-basename + helm-recentf--basename-flag) + (helm-basename candidate) candidate))) + (fuzzy-match :initform t) + (migemo :initform t))) + +(defvar helm-source-files-in-current-dir + (helm-make-source "Files from Current Directory" + 'helm-files-in-current-dir-source)) + +;;;###autoload +(defun helm-for-files () + "Preconfigured `helm' for opening files. +Run all sources defined in `helm-for-files-preferred-list'." + (interactive) + (require 'helm-x-files) + (unless helm-source-buffers-list + (setq helm-source-buffers-list + (helm-make-source "Buffers" 'helm-source-buffers))) + (helm :sources helm-for-files-preferred-list + :ff-transformer-show-only-basename nil + :buffer "*helm for files*" + :truncate-lines helm-buffers-truncate-lines)) + +(defun helm-multi-files-toggle-to-locate () + (interactive) + (with-helm-alive-p + (with-helm-buffer + (if (setq helm-multi-files--toggle-locate + (not helm-multi-files--toggle-locate)) + (progn + (helm-set-sources (unless (memq 'helm-source-locate + helm-sources) + (cons 'helm-source-locate helm-sources))) + (helm-set-source-filter '(helm-source-locate))) + (helm-kill-async-processes) + (helm-set-sources (remove 'helm-source-locate + helm-for-files-preferred-list)) + (helm-set-source-filter nil))))) +(put 'helm-multi-files-toggle-to-locate 'helm-only t) + +;;;###autoload +(defun helm-multi-files () + "Preconfigured helm like `helm-for-files' but running locate only on demand. + +Allow toggling back and forth from locate to others sources with +`helm-multi-files-toggle-locate-binding' key. +This avoid launching needlessly locate when what you search is already +found." + (interactive) + (require 'helm-x-files) + (unless helm-source-buffers-list + (setq helm-source-buffers-list + (helm-make-source "Buffers" 'helm-source-buffers))) + (setq helm-multi-files--toggle-locate nil) + (helm-locate-set-command) + (helm-set-local-variable 'helm-async-outer-limit-hook + (list (lambda () + (when (and helm-locate-fuzzy-match + (not (string-match-p + "\\s-" helm-pattern))) + (helm-redisplay-buffer))))) + (let ((sources (remove 'helm-source-locate helm-for-files-preferred-list)) + (helm-locate-command + (if helm-locate-fuzzy-match + (unless (string-match-p "\\`locate -b" helm-locate-command) + (replace-regexp-in-string + "\\`locate" "locate -b" helm-locate-command)) + helm-locate-command)) + (old-key (lookup-key + helm-map + (read-kbd-macro helm-multi-files-toggle-locate-binding)))) + (with-helm-temp-hook 'helm-after-initialize-hook + (define-key helm-map (kbd helm-multi-files-toggle-locate-binding) + 'helm-multi-files-toggle-to-locate)) + (unwind-protect + (helm :sources sources + :ff-transformer-show-only-basename nil + :buffer "*helm multi files*" + :truncate-lines helm-buffers-truncate-lines) + (define-key helm-map (kbd helm-multi-files-toggle-locate-binding) + old-key)))) + +;;;###autoload +(defun helm-recentf () + "Preconfigured `helm' for `recentf'." + (interactive) + (helm :sources 'helm-source-recentf + :ff-transformer-show-only-basename nil + :buffer "*helm recentf*")) + +(provide 'helm-for-files) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-for-files.el ends here diff --git a/elpa/helm-20181113.923/helm-grep.el b/elpa/helm-20181113.923/helm-grep.el new file mode 100644 index 00000000..a4add2c1 --- /dev/null +++ b/elpa/helm-20181113.923/helm-grep.el @@ -0,0 +1,1641 @@ +;;; helm-grep.el --- Helm Incremental Grep. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: +(require 'cl-lib) +(require 'format-spec) +(require 'helm) +(require 'helm-help) +(require 'helm-regexp) + +;;; load wgrep proxy if it's available +(require 'wgrep-helm nil t) + +(declare-function helm-buffer-list "helm-buffers") +(declare-function View-quit "view") +(declare-function doc-view-goto-page "doc-view" (page)) +(declare-function pdf-view-goto-page "pdf-view" (page &optional window)) +(declare-function helm-mm-split-pattern "helm-multi-match") +(declare-function helm--ansi-color-apply "helm-lib") +(defvar helm--ansi-color-regexp) + + +(defgroup helm-grep nil + "Grep related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-grep-default-command + "grep --color=always -a -d skip %e -n%cH -e %p %f" + "Default grep format command for `helm-do-grep-1'. +Where: +'%e' format spec is for --exclude or --include grep options or + ack-grep --type option. (Not mandatory) + +'%c' format spec is for case-fold-search, + whether to use the -i option of grep. (Not mandatory) + When you specify this spec, helm grep will use smartcase + that is when a upcase character is found in pattern case will + be respected and no '-i' option will be used, otherwise, when + no upcase character is found in pattern always use '-i'. + If you don't want this behavior, don't use this spec and + specify or not the '-i' option. + Note that with ack-grep this is not needed, just specify + the '--smart-case' option. + +'%p' format spec is for pattern. (Mandatory) + +'%f' format spec is for filenames. (Mandatory) + +If your grep version doesn't support the --exclude/include args +don't specify the '%e' format spec. + +Helm also support ack-grep and git-grep , +here a default command example for ack-grep: + +\(setq helm-grep-default-command \"ack-grep -Hn --color --smart-case --no-group %e %p %f\" + helm-grep-default-recurse-command \"ack-grep -H --color --smart-case --no-group %e %p %f\") + +You can ommit the %e spec if you don't want to be prompted for types. + +NOTE: Helm for ack-grep support ANSI sequences, so you can remove +the \"--no-color\" option safely (recommended) +However you should specify --color to enable multi matches highlighting +because ack disable it when output is piped. + +Same for grep you can use safely the option \"--color=always\" (default). +You can customize the color of matches using GREP_COLORS env var. +e.g: \(setenv \"GREP_COLORS\" \"ms=30;43:mc=30;43:sl=01;37:cx=:fn=35:ln=32:bn=32:se=36\") + +To enable ANSI color in git-grep just add \"--color=always\". +To customize the ANSI color in git-grep, GREP_COLORS have no effect, +you will have to setup this in your .gitconfig: + + [color \"grep\"] + match = black yellow + +where \"black\" is the foreground and \"yellow\" the background. +See the git documentation for more infos. + +`helm-grep-default-command' and `helm-grep-default-recurse-command'are +independents, so you can enable `helm-grep-default-command' with ack-grep +and `helm-grep-default-recurse-command' with grep if you want to be faster +on recursive grep. + +NOTE: Remote grepping is not available with ack-grep, + and badly supported with grep because tramp handle badly + repeated remote processes in a short delay (< to 5s)." + :group 'helm-grep + :type 'string) + +(defcustom helm-grep-default-recurse-command + "grep --color=always -a -d recurse %e -n%cH -e %p %f" + "Default recursive grep format command for `helm-do-grep-1'. +See `helm-grep-default-command' for format specs and infos about ack-grep." + :group 'helm-grep + :type 'string) + +(defcustom helm-default-zgrep-command + "zgrep --color=always -a -n%cH -e %p %f" + "Default command for Zgrep. +See `helm-grep-default-command' for infos on format specs. +Option --color=always is supported and can be used safely +to replace the helm internal match highlighting, +see `helm-grep-default-command' for more infos." + :group 'helm-grep + :type 'string) + +(defcustom helm-pdfgrep-default-command + "pdfgrep --color always -niH %s %s" + "Default command for pdfgrep. +Option \"--color always\" is supported starting helm version 1.7.8, +when used matchs will be highlighted according to GREP_COLORS env var." + :group 'helm-grep + :type 'string) + +(defcustom helm-pdfgrep-default-recurse-command + "pdfgrep --color always -rniH %s %s" + "Default recurse command for pdfgrep. +Option \"--color always\" is supported starting helm version 1.7.8, +when used matchs will be highlighted according to GREP_COLORS env var." + :group 'helm-grep + :type 'string) + +(defcustom helm-grep-use-ioccur-style-keys t + "Use Arrow keys to jump to occurences." + :group 'helm-grep + :type 'boolean) + +(defcustom helm-pdfgrep-default-read-command nil + "Default command to read pdf files from pdfgrep. +Where '%f' format spec is filename and '%p' is page number. +e.g In Ubuntu you can set it to: + + \"evince --page-label=%p '%f'\" + +If set to nil either `doc-view-mode' or `pdf-view-mode' will be used +instead of an external command." + :group 'helm-grep + :type 'string) + +(defcustom helm-grep-max-length-history 100 + "Max number of elements to save in `helm-grep-history'." + :group 'helm-grep + :type 'integer) + +(defcustom helm-zgrep-file-extension-regexp + ".*\\(\\.gz\\|\\.bz\\|\\.xz\\|\\.lzma\\)$" + "Default file extensions zgrep will search in." + :group 'helm-grep + :type 'string) + +(defcustom helm-grep-preferred-ext nil + "This file extension will be preselected for grep." + :group 'helm-grep + :type 'string) + +(defcustom helm-grep-save-buffer-name-no-confirm nil + "when *hgrep* already exists,auto append suffix." + :group 'helm-grep + :type 'boolean) + +(defcustom helm-grep-ignored-files + (cons ".#*" (delq nil (mapcar (lambda (s) + (unless (string-match-p "/\\'" s) + (concat "*" s))) + completion-ignored-extensions))) + "List of file names which `helm-grep' shall exclude." + :group 'helm-grep + :type '(repeat string)) + +(defcustom helm-grep-ignored-directories + helm-walk-ignore-directories + "List of names of sub-directories which `helm-grep' shall not recurse into." + :group 'helm-grep + :type '(repeat string)) + +(defcustom helm-grep-truncate-lines t + "When nil the grep line that appears will not be truncated." + :group 'helm-grep + :type 'boolean) + +(defcustom helm-grep-file-path-style 'basename + "File path display style when grep results are displayed. +Possible value are: + basename: displays only the filename, none of the directory path + absolute: displays absolute path + relative: displays relative path from root grep directory." + :group 'helm-grep + :type '(choice (const :tag "Basename" basename) + (const :tag "Absolute" absolute) + (const :tag "Relative" relative))) + +(defcustom helm-grep-actions + (helm-make-actions + "Find File" 'helm-grep-action + "Find file other frame" 'helm-grep-other-frame + "Save results in grep buffer" 'helm-grep-save-results + "Find file other window (C-u vertically)" 'helm-grep-other-window) + "Actions for helm grep." + :group 'helm-grep + :type '(alist :key-type string :value-type function)) + +(defcustom helm-grep-pipe-cmd-switches nil + "A list of additional parameters to pass to grep pipe command. +This will be used for pipe command for multiple pattern matching +for grep, zgrep ack-grep and git-grep backends. +If you add extra args for ack-grep, use ack-grep options, +for others (grep, zgrep and git-grep) use grep options. +Here are the commands where you may want to add switches: + + grep --color=always + ack-grep --smart-case --color + +You probably don't need to use this unless you know what you are doing." + :group 'helm-grep + :type 'string) + +(defcustom helm-grep-ag-pipe-cmd-switches nil + "A list of additional parameters to pass to grep-ag pipe command. +Use parameters compatibles with the backend you are using +\(i.e AG for AG, PT for PT or RG for RG) + +You probably don't need to use this unless you know what you are doing." + :group 'helm-grep + :type 'string) + + +;;; Faces +;; +;; +(defgroup helm-grep-faces nil + "Customize the appearance of helm-grep." + :prefix "helm-" + :group 'helm-grep + :group 'helm-faces) + +(defface helm-grep-match + '((((background light)) :foreground "#b00000") + (((background dark)) :foreground "gold1")) + "Face used to highlight grep matches. +Have no effect when grep backend use \"--color=\"." + :group 'helm-grep-faces) + +(defface helm-grep-file + '((t (:foreground "BlueViolet" + :underline t))) + "Face used to highlight grep results filenames." + :group 'helm-grep-faces) + +(defface helm-grep-lineno + '((t (:foreground "Darkorange1"))) + "Face used to highlight grep number lines." + :group 'helm-grep-faces) + +(defface helm-grep-finish + '((t (:foreground "Green"))) + "Face used in mode line when grep is finish." + :group 'helm-grep-faces) + +(defface helm-grep-cmd-line + '((t (:inherit font-lock-type-face))) + "Face used to highlight grep command line when no results." + :group 'helm-grep-faces) + + +;;; Keymaps +;; +;; +(defvar helm-grep-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-") 'helm-goto-next-file) + (define-key map (kbd "M-") 'helm-goto-precedent-file) + (define-key map (kbd "C-c o") 'helm-grep-run-other-window-action) + (define-key map (kbd "C-c C-o") 'helm-grep-run-other-frame-action) + (define-key map (kbd "C-x C-s") 'helm-grep-run-save-buffer) + (define-key map (kbd "DEL") 'helm-delete-backward-no-update) + (when helm-grep-use-ioccur-style-keys + (define-key map (kbd "") 'helm-execute-persistent-action) + (define-key map (kbd "") 'helm-grep-run-default-action)) + (delq nil map)) + "Keymap used in Grep sources.") + +(defvar helm-pdfgrep-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-") 'helm-goto-next-file) + (define-key map (kbd "M-") 'helm-goto-precedent-file) + (define-key map (kbd "DEL") 'helm-delete-backward-no-update) + map) + "Keymap used in pdfgrep.") + +(defvar helm-grep-mode-map + (let ((map (make-sparse-keymap))) + (define-key map (kbd "RET") 'helm-grep-mode-jump) + (define-key map (kbd "C-o") 'helm-grep-mode-jump-other-window) + (define-key map (kbd "") 'helm-grep-mode-jump-other-window-forward) + (define-key map (kbd "") 'helm-grep-mode-jump-other-window-backward) + (define-key map (kbd "") 'helm-gm-next-file) + (define-key map (kbd "") 'helm-gm-precedent-file) + (define-key map (kbd "M-n") 'helm-grep-mode-jump-other-window-forward) + (define-key map (kbd "M-p") 'helm-grep-mode-jump-other-window-backward) + (define-key map (kbd "M-N") 'helm-gm-next-file) + (define-key map (kbd "M-P") 'helm-gm-precedent-file) + map)) + + +;;; Internals vars +;; +;; +(defvar helm-rzgrep-cache (make-hash-table :test 'equal)) +(defvar helm-grep-default-function 'helm-grep-init) +(defvar helm-zgrep-recurse-flag nil) +(defvar helm-grep-history nil) +(defvar helm-grep-ag-history nil) +(defvar helm-grep-last-targets nil) +(defvar helm-grep-include-files nil) +(defvar helm-grep-in-recurse nil) +(defvar helm-grep-use-zgrep nil) +(defvar helm-grep-default-directory-fn nil + "A function that should return a directory to expand candidate to. +It is intended to use as a let-bound variable, DON'T set this globaly.") +(defvar helm-pdfgrep-targets nil) +(defvar helm-grep-last-cmd-line nil) +(defvar helm-grep-split-line-regexp "^\\([[:lower:][:upper:]]?:?.*?\\):\\([0-9]+\\):\\(.*\\)") + + +;;; Init +;; +;; +(defun helm-grep-prepare-candidates (candidates in-directory) + "Prepare filenames and directories CANDIDATES for grep command line." + ;; If one or more candidate is a directory, search in all files + ;; of this candidate (e.g /home/user/directory/*). + ;; If r option is enabled search also in subdidrectories. + ;; We need here to expand wildcards to support crap windows filenames + ;; as grep doesn't accept quoted wildcards (e.g "dir/*.el"). + (if helm-zgrep-recurse-flag + (mapconcat 'shell-quote-argument candidates " ") + ;; When candidate is a directory, search in all its files. + ;; NOTE that `file-expand-wildcards' will return also + ;; directories, they will be ignored by grep but not + ;; by ack-grep that will grep all files of this directory + ;; without recursing in their subdirs though, see that as a one + ;; level recursion with ack-grep. + ;; So I leave it as it is, considering it is a feature. [1] + (cl-loop for i in candidates append + (cond ((string-match "^git" helm-grep-default-command) + (list i)) + ;; Candidate is a directory and we use recursion or ack. + ((and (file-directory-p i) + (or helm-grep-in-recurse + ;; ack-grep accept directory [1]. + (helm-grep-use-ack-p))) + (list (expand-file-name i))) + ;; Grep doesn't support directory only when not in recurse. + ((file-directory-p i) + (file-expand-wildcards + (concat (file-name-as-directory (expand-file-name i)) "*") t)) + ;; Candidate is a file or wildcard and we use recursion, use the + ;; current directory instead of candidate. + ((and (or (file-exists-p i) (string-match "[*]" i)) + helm-grep-in-recurse) + (list (expand-file-name + (directory-file-name ; Needed for windoze. + (file-name-directory (directory-file-name i)))))) + ;; Else should be one or more file/directory + ;; possibly marked. + ;; When real is a normal filename without wildcard + ;; file-expand-wildcards returns a list of one file. + ;; wildcards should have been already handled by + ;; helm-read-file-name or helm-find-files but do it from + ;; here too in case we are called from elsewhere. + (t (file-expand-wildcards i t))) into all-files ; [1] + finally return + (let ((files (if (file-remote-p in-directory) + ;; Grep don't understand tramp filenames + ;; use the local name. + (mapcar (lambda (x) + (file-remote-p x 'localname)) + all-files) + all-files))) + ;; When user mark files and use recursion with grep + ;; backend enabled, the loop collect on each marked + ;; candidate its `file-name-directory' and we endup with + ;; duplicates (Issue #1714). FIXME: For now as a quick fix + ;; I just remove dups here but I should handle this inside + ;; the cond above. + (setq files (helm-fast-remove-dups files :test 'equal)) + (if (string-match "^git" helm-grep-default-command) + (mapconcat 'identity files " ") + (mapconcat 'shell-quote-argument files " ")))))) + +(defun helm-grep-command (&optional recursive grep) + (let* ((com (if recursive + helm-grep-default-recurse-command + helm-grep-default-command)) + (exe (if grep + (symbol-name grep) + (and com (car (split-string com " ")))))) + (if (and exe (string= exe "git")) "git-grep" exe))) + +(cl-defun helm-grep-use-ack-p (&key where) + (let* ((rec-com (helm-grep-command t)) + (norm-com (helm-grep-command)) + (norm-com-ack-p (string-match "\\`ack" norm-com)) + (rec-com-ack-p (and rec-com (string-match "\\`ack" rec-com)))) + (cl-case where + (default (and norm-com norm-com-ack-p)) + (recursive (and rec-com rec-com-ack-p)) + (strict (and norm-com rec-com rec-com-ack-p norm-com-ack-p)) + (t (and (not (and norm-com (string= norm-com "git-grep"))) + (or (and norm-com norm-com-ack-p) + (and rec-com rec-com-ack-p))))))) + +(defun helm-grep--pipe-command-for-grep-command (smartcase pipe-switches &optional grep-cmd) + (pcase (or grep-cmd (helm-grep-command)) + ;; Use grep for GNU regexp based tools. + ((or "grep" "zgrep" "git-grep") + (format "grep --color=always%s %s" + (if smartcase " -i" "") + pipe-switches)) + ;; Use ack-grep for PCRE based tools. + ;; Sometimes ack-grep cmd is ack only. + ((and (pred (string-match-p "ack")) ack) + (format "%s --smart-case --color %s" ack pipe-switches)))) + +(defun helm-grep--prepare-cmd-line (only-files &optional include zgrep) + (let* ((default-directory (or helm-ff-default-directory + (helm-default-directory) + default-directory)) + (fnargs (helm-grep-prepare-candidates + only-files default-directory)) + (ignored-files (unless (helm-grep-use-ack-p) + (mapconcat + (lambda (x) + (concat "--exclude=" + (shell-quote-argument x))) + helm-grep-ignored-files " "))) + (ignored-dirs (unless (helm-grep-use-ack-p) + (mapconcat + ;; Need grep version >=2.5.4 + ;; of Gnuwin32 on windoze. + (lambda (x) + (concat "--exclude-dir=" + (shell-quote-argument x))) + helm-grep-ignored-directories " "))) + (exclude (unless (helm-grep-use-ack-p) + (if helm-grep-in-recurse + (concat (or include ignored-files) + " " ignored-dirs) + ignored-files))) + (types (and (helm-grep-use-ack-p) + ;; When %e format spec is not specified + ;; in `helm-grep-default-command' + ;; we need to pass an empty string + ;; to types to avoid error. + (or include ""))) + (smartcase (if (helm-grep-use-ack-p) + "" + (unless (let ((case-fold-search nil)) + (string-match-p + "[[:upper:]]" helm-pattern)) + "i"))) + (helm-grep-default-command + (concat helm-grep-default-command " %m")) ; `%m' like multi. + (patterns (helm-mm-split-pattern helm-pattern t)) + (pipe-switches (mapconcat 'identity helm-grep-pipe-cmd-switches " ")) + (pipes + (helm-aif (cdr patterns) + (cl-loop with pipcom = (helm-grep--pipe-command-for-grep-command + smartcase pipe-switches) + for p in it concat + (format " | %s %s" pipcom (shell-quote-argument p))) + ""))) + (format-spec + helm-grep-default-command + (delq nil + (list (unless zgrep + (if types + (cons ?e types) + (cons ?e exclude))) + (cons ?c (or smartcase "")) + (cons ?p (shell-quote-argument (car patterns))) + (cons ?f fnargs) + (cons ?m pipes)))))) + +(defun helm-grep-init (cmd-line) + "Start an asynchronous grep process with CMD-LINE using ZGREP if non--nil." + (let* ((default-directory (or helm-ff-default-directory + (helm-default-directory) + default-directory)) + (zgrep (string-match "\\`zgrep" cmd-line)) + ;; Use pipe only with grep, zgrep or git-grep. + (process-connection-type (and (not zgrep) (helm-grep-use-ack-p))) + (tramp-verbose helm-tramp-verbose) + (start-time (float-time)) + (proc-name (if helm-grep-use-zgrep + "Zgrep" + (capitalize + (if helm-grep-in-recurse + (helm-grep-command t) + (helm-grep-command))))) + non-essential) + ;; Start grep process. + (helm-log "Starting Grep process in directory `%s'" default-directory) + (helm-log "Command line used was:\n\n%s" + (concat ">>> " (propertize cmd-line 'face 'helm-grep-cmd-line) "\n\n")) + (prog1 ; This function should return the process first. + (start-file-process-shell-command + proc-name helm-buffer cmd-line) + ;; Init sentinel. + (set-process-sentinel + (get-buffer-process helm-buffer) + (lambda (process event) + (let* ((err (process-exit-status process)) + (noresult (= err 1))) + (unless (and err (> err 0)) + (helm-process-deferred-sentinel-hook + process event (helm-default-directory))) + (cond ((and noresult + ;; This is a workaround for zgrep + ;; that exit with code 1 + ;; after a certain amount of results. + (with-helm-buffer (helm-empty-buffer-p))) + (with-helm-buffer + (insert (concat "* Exit with code 1, no result found," + " command line was:\n\n " + (propertize helm-grep-last-cmd-line + 'face 'helm-grep-cmd-line))) + (setq mode-line-format + `(" " mode-line-buffer-identification " " + (:eval (format "L%s" (helm-candidate-number-at-point))) " " + (:eval (propertize + (format + "[%s process finished - (no results)] " + ,proc-name) + 'face 'helm-grep-finish)))))) + ((or (string= event "finished\n") + (and noresult + ;; This is a workaround for zgrep + ;; that exit with code 1 + ;; after a certain amount of results. + (with-helm-buffer (not (helm-empty-buffer-p))))) + (helm-log "%s process finished with %s results in %fs" + proc-name + (helm-get-candidate-number) + (- (float-time) start-time)) + (helm-maybe-show-help-echo) + (with-helm-window + (setq mode-line-format + `(" " mode-line-buffer-identification " " + (:eval (format "L%s" (helm-candidate-number-at-point))) " " + (:eval (propertize + (format + "[%s process finished in %.2fs - (%s results)] " + ,proc-name + ,(- (float-time) start-time) + (helm-get-candidate-number)) + 'face 'helm-grep-finish)))) + (force-mode-line-update) + (when helm-allow-mouse + (helm--bind-mouse-for-selection helm-selection-point)))) + ;; Catch error output in log. + (t (helm-log + "Error: %s %s" + proc-name + (replace-regexp-in-string "\n" "" event)))))))))) + +(defun helm-grep-collect-candidates () + (let ((cmd-line (helm-grep--prepare-cmd-line + helm-grep-last-targets + helm-grep-include-files + helm-grep-use-zgrep))) + (set (make-local-variable 'helm-grep-last-cmd-line) cmd-line) + (funcall helm-grep-default-function cmd-line))) + + +;;; Actions +;; +;; +(defun helm-grep-action (candidate &optional where) + "Define a default action for `helm-do-grep-1' on CANDIDATE. +WHERE can be one of other-window, other-frame." + (let* ((split (helm-grep-split-line candidate)) + (split-pat (helm-mm-split-pattern helm-input)) + (lineno (string-to-number (nth 1 split))) + (loc-fname (or (with-current-buffer + (if (eq major-mode 'helm-grep-mode) + (current-buffer) + helm-buffer) + (get-text-property (point-at-bol) 'helm-grep-fname)) + (car split))) + (tramp-method (file-remote-p (or helm-ff-default-directory + default-directory) 'method)) + (tramp-host (file-remote-p (or helm-ff-default-directory + default-directory) 'host)) + (tramp-prefix (concat "/" tramp-method ":" tramp-host ":")) + (fname (if tramp-host + (concat tramp-prefix loc-fname) loc-fname))) + (cl-case where + (other-window (helm-window-show-buffers + (list (find-file-noselect fname)) t)) + (other-frame (find-file-other-frame fname)) + (grep (helm-grep-save-results-1)) + (pdf (if helm-pdfgrep-default-read-command + (helm-pdfgrep-action-1 split lineno (car split)) + (find-file (car split)) (if (derived-mode-p 'pdf-view-mode) + (pdf-view-goto-page lineno) + (doc-view-goto-page lineno)))) + (t (find-file fname))) + (unless (or (eq where 'grep) (eq where 'pdf)) + (helm-goto-line lineno)) + ;; Move point to the nearest matching regexp from bol. + (cl-loop for reg in split-pat + when (save-excursion + (condition-case _err + (if helm-migemo-mode + (helm-mm-migemo-forward reg (point-at-eol) t) + (re-search-forward reg (point-at-eol) t)) + (invalid-regexp nil))) + collect (match-beginning 0) into pos-ls + finally (when pos-ls (goto-char (apply #'min pos-ls)))) + ;; Save history + (unless (or helm-in-persistent-action + (eq major-mode 'helm-grep-mode) + (string= helm-pattern "")) + (setq helm-grep-history + (cons helm-pattern + (delete helm-pattern helm-grep-history))) + (when (> (length helm-grep-history) + helm-grep-max-length-history) + (setq helm-grep-history + (delete (car (last helm-grep-history)) + helm-grep-history)))))) + +(defun helm-grep-persistent-action (candidate) + "Persistent action for `helm-do-grep-1'. +With a prefix arg record CANDIDATE in `mark-ring'." + (helm-grep-action candidate) + (helm-highlight-current-line)) + +(defun helm-grep-other-window (candidate) + "Jump to result in other window from helm grep." + (helm-grep-action candidate 'other-window)) + +(defun helm-grep-other-frame (candidate) + "Jump to result in other frame from helm grep." + (helm-grep-action candidate 'other-frame)) + +(defun helm-goto-next-or-prec-file (n) + "Go to next or precedent candidate file in helm grep/etags buffers. +If N is positive go forward otherwise go backward." + (let* ((allow-mode (or (eq major-mode 'helm-grep-mode) + (eq major-mode 'helm-moccur-mode))) + (sel (if allow-mode + (buffer-substring (point-at-bol) (point-at-eol)) + (helm-get-selection nil t))) + (current-line-list (helm-grep-split-line sel)) + (current-fname (nth 0 current-line-list)) + (bob-or-eof (if (eq n 1) 'eobp 'bobp)) + (mark-maybe (lambda () + (if allow-mode + (ignore) + (helm-mark-current-line))))) + (catch 'break + (while (not (funcall bob-or-eof)) + (forward-line n) ; Go forward or backward depending of n value. + ;; Exit when current-fname is not matched or in `helm-grep-mode' + ;; the line is not a grep line i.e 'fname:num:tag'. + (setq sel (buffer-substring (point-at-bol) (point-at-eol))) + (when helm-allow-mouse + (helm--mouse-reset-selection-help-echo)) + (unless (or (string= current-fname + (car (helm-grep-split-line sel))) + (and (eq major-mode 'helm-grep-mode) + (not (get-text-property (point-at-bol) 'helm-grep-fname)))) + (funcall mark-maybe) + (throw 'break nil)))) + (cond ((and (> n 0) (eobp)) + (re-search-backward ".") + (forward-line 0) + (funcall mark-maybe)) + ((and (< n 0) (bobp)) + (helm-aif (next-single-property-change (point-at-bol) 'helm-grep-fname) + (goto-char it) + (forward-line 1)) + (funcall mark-maybe))) + (unless allow-mode + (helm-follow-execute-persistent-action-maybe) + (helm-log-run-hook 'helm-move-selection-after-hook)))) + +;;;###autoload +(defun helm-goto-precedent-file () + "Go to precedent file in helm grep/etags buffers." + (interactive) + (with-helm-alive-p + (with-helm-window + (helm-goto-next-or-prec-file -1)))) +(put 'helm-goto-precedent-file 'helm-only t) + +;;;###autoload +(defun helm-goto-next-file () + "Go to precedent file in helm grep/etags buffers." + (interactive) + (with-helm-window + (helm-goto-next-or-prec-file 1))) + +(defun helm-grep-run-default-action () + "Run grep default action from `helm-do-grep-1'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-grep-action))) +(put 'helm-grep-run-default-action 'helm-only t) + +(defun helm-grep-run-other-window-action () + "Run grep goto other window action from `helm-do-grep-1'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-grep-other-window))) +(put 'helm-grep-run-other-window-action 'helm-only t) + +(defun helm-grep-run-other-frame-action () + "Run grep goto other frame action from `helm-do-grep-1'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-grep-other-frame))) +(put 'helm-grep-run-other-frame-action 'helm-only t) + +(defun helm-grep-run-save-buffer () + "Run grep save results action from `helm-do-grep-1'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-grep-save-results))) +(put 'helm-grep-run-save-buffer 'helm-only t) + + +;;; helm-grep-mode +;; +;; +(defun helm-grep-save-results (candidate) + (helm-grep-action candidate 'grep)) + +(defun helm-grep-save-results-1 () + "Save helm grep result in a `helm-grep-mode' buffer." + (let ((buf "*hgrep*") + new-buf + (pattern (with-helm-buffer helm-input-local)) + (src-name (assoc-default 'name (helm-get-current-source)))) + (when (get-buffer buf) + (if helm-grep-save-buffer-name-no-confirm + (setq new-buf (format "*hgrep|%s|-%s" pattern + (format-time-string "%H-%M-%S*"))) + (setq new-buf (helm-read-string "GrepBufferName: " buf)) + (cl-loop for b in (helm-buffer-list) + when (and (string= new-buf b) + (not (y-or-n-p + (format "Buffer `%s' already exists overwrite? " + new-buf)))) + do (setq new-buf (helm-read-string "GrepBufferName: " "*hgrep ")))) + (setq buf new-buf)) + (with-current-buffer (get-buffer-create buf) + (setq default-directory (or helm-ff-default-directory + (helm-default-directory) + default-directory)) + (setq buffer-read-only t) + (let ((inhibit-read-only t) + (map (make-sparse-keymap))) + (erase-buffer) + (insert "-*- mode: helm-grep -*-\n\n" + (format "%s Results for `%s':\n\n" src-name pattern)) + (save-excursion + (insert (with-current-buffer helm-buffer + (goto-char (point-min)) (forward-line 1) + (buffer-substring (point) (point-max))))) + (save-excursion + (while (not (eobp)) + (add-text-properties (point-at-bol) (point-at-eol) + `(keymap ,map + help-echo ,(concat + (get-text-property + (point) 'helm-grep-fname) + "\nmouse-1: set point\nmouse-2: jump to selection") + mouse-face highlight)) + (define-key map [mouse-1] 'mouse-set-point) + (define-key map [mouse-2] 'helm-grep-mode-mouse-jump) + (define-key map [mouse-3] 'ignore) + (forward-line 1)))) + (helm-grep-mode)) + (pop-to-buffer buf) + (message "Helm %s Results saved in `%s' buffer" src-name buf))) + +(defun helm-grep-mode-mouse-jump (event) + (interactive "e") + (let* ((window (posn-window (event-end event))) + (pos (posn-point (event-end event)))) + (with-selected-window window + (when (eq major-mode 'helm-grep-mode) + (goto-char pos) + (helm-grep-mode-jump))))) +(put 'helm-grep-mode-mouse-jump 'helm-only t) + +(define-derived-mode helm-grep-mode + special-mode "helm-grep" + "Major mode to provide actions in helm grep saved buffer. + +Special commands: +\\{helm-grep-mode-map}" + (set (make-local-variable 'helm-grep-last-cmd-line) + (with-helm-buffer helm-grep-last-cmd-line)) + (set (make-local-variable 'revert-buffer-function) + #'helm-grep-mode--revert-buffer-function)) +(put 'helm-grep-mode 'helm-only t) + +(defun helm-grep-mode--revert-buffer-function (&optional _ignore-auto _noconfirm) + (goto-char (point-min)) + (when (re-search-forward helm-grep-split-line-regexp nil t) (forward-line 0)) + (let ((inhibit-read-only t)) + (delete-region (point) (point-max))) + (message "Reverting buffer...") + (let ((process-connection-type + ;; Git needs a nil value otherwise it tries to use a pager. + (null (string-match-p "\\`git" helm-grep-last-cmd-line)))) + (set-process-sentinel + (start-file-process-shell-command + "hgrep" (generate-new-buffer "*hgrep revert*") helm-grep-last-cmd-line) + 'helm-grep-mode--sentinel))) + +(defun helm-grep-mode--sentinel (process event) + (when (string= event "finished\n") + (with-current-buffer (current-buffer) + (let ((inhibit-read-only t)) + (save-excursion + (cl-loop for l in (with-current-buffer (process-buffer process) + (prog1 (split-string (buffer-string) "\n") + (kill-buffer))) + for line = (if (string-match-p helm--ansi-color-regexp l) + (helm--ansi-color-apply l) l) + when (string-match helm-grep-split-line-regexp line) + do (insert (propertize + (car (helm-grep-filter-one-by-one line)) + ;; needed for wgrep. + 'helm-realvalue line) + "\n")))) + (message "Reverting buffer done")))) + +(defun helm-gm-next-file () + (interactive) + (helm-goto-next-or-prec-file 1)) + +(defun helm-gm-precedent-file () + (interactive) + (helm-goto-next-or-prec-file -1)) + +(defun helm-grep-mode-jump () + (interactive) + (helm-grep-action + (buffer-substring (point-at-bol) (point-at-eol))) + (helm-match-line-cleanup-pulse)) + +(defun helm-grep-mode-jump-other-window-1 (arg) + (let ((candidate (buffer-substring (point-at-bol) (point-at-eol)))) + (condition-case nil + (progn + (save-selected-window + (helm-grep-action candidate 'other-window) + (helm-match-line-cleanup-pulse) + (recenter)) + (forward-line arg)) + (error nil)))) + +(defun helm-grep-mode-jump-other-window-forward () + (interactive) + (helm-grep-mode-jump-other-window-1 1)) + +(defun helm-grep-mode-jump-other-window-backward () + (interactive) + (helm-grep-mode-jump-other-window-1 -1)) + +(defun helm-grep-mode-jump-other-window () + (interactive) + (let ((candidate (buffer-substring (point-at-bol) (point-at-eol)))) + (condition-case nil + (progn (helm-grep-action candidate 'other-window) + (helm-match-line-cleanup-pulse)) + (error nil)))) + + +;;; ack-grep types +;; +;; +(defun helm-grep-hack-types () + "Return a list of known ack-grep types." + (with-temp-buffer + ;; "--help-types" works with both 1.96 and 2.1+, while + ;; "--help types" works only with 1.96 Issue #422. + ;; `helm-grep-command' should return the ack executable + ;; when this function is used in the right context + ;; i.e After checking is we are using ack-grep with + ;; `helm-grep-use-ack-p'. + (call-process (helm-grep-command t) nil t nil "--help-types") + (goto-char (point-min)) + (cl-loop while (re-search-forward + "^ *--\\(\\[no\\]\\)\\([^. ]+\\) *\\(.*\\)" nil t) + collect (cons (concat (match-string 2) + " [" (match-string 3) "]") + (match-string 2)) + collect (cons (concat "no" (match-string 2) + " [" (match-string 3) "]") + (concat "no" (match-string 2)))))) + +(defun helm-grep-ack-types-transformer (candidates _source) + (cl-loop for i in candidates + if (stringp i) + collect (rassoc i helm-grep-ack-types-cache) + else + collect i)) + +(defvar helm-grep-ack-types-cache nil) +(defun helm-grep-read-ack-type () + "Select types for the '--type' argument of ack-grep." + (require 'helm-mode) + (require 'helm-adaptive) + (setq helm-grep-ack-types-cache (helm-grep-hack-types)) + (let ((types (helm-comp-read + "Types: " helm-grep-ack-types-cache + :name "*Ack-grep types*" + :marked-candidates t + :must-match t + :fc-transformer '(helm-adaptive-sort + helm-grep-ack-types-transformer) + :buffer "*helm ack-types*"))) + (mapconcat (lambda (type) (concat "--type=" type)) types " "))) + + +;;; grep extensions +;; +;; +(defun helm-grep-guess-extensions (files) + "Try to guess file extensions in FILES list when using grep recurse. +These extensions will be added to command line with --include arg of grep." + (cl-loop with ext-list = (list helm-grep-preferred-ext "*") + with lst = (if (file-directory-p (car files)) + (directory-files + (car files) nil + directory-files-no-dot-files-regexp) + files) + for i in lst + for ext = (file-name-extension i 'dot) + for glob = (and ext (not (string= ext "")) + (concat "*" ext)) + unless (or (not glob) + (and glob-list (member glob glob-list)) + (and glob-list (member glob ext-list)) + (and glob-list (member glob helm-grep-ignored-files))) + collect glob into glob-list + finally return (delq nil (append ext-list glob-list)))) + +(defun helm-grep-get-file-extensions (files) + "Try to return a list of file extensions to pass to '--include' arg of grep." + (require 'helm-adaptive) + (let* ((all-exts (helm-grep-guess-extensions + (mapcar 'expand-file-name files))) + (extensions (helm-comp-read "Search Only in: " all-exts + :marked-candidates t + :fc-transformer 'helm-adaptive-sort + :buffer "*helm grep exts*" + :name "*helm grep extensions*"))) + (when (listp extensions) ; Otherwise it is empty string returned by C-RET. + ;; If extensions is a list of one string containing spaces, + ;; assume user entered more than one glob separated by space(s) and + ;; split this string to pass it later to mapconcat. + ;; e.g '("*.el *.py") + (cl-loop for i in extensions + append (split-string-and-unquote i " "))))) + + +;;; Set up source +;; +;; +(defvar helm-grep-before-init-hook nil + "Hook that runs before initialization of the helm buffer.") + +(defvar helm-grep-after-init-hook nil + "Hook that runs after initialization of the helm buffer.") + +(defclass helm-grep-class (helm-source-async) + ((candidates-process :initform 'helm-grep-collect-candidates) + (filter-one-by-one :initform 'helm-grep-filter-one-by-one) + (keymap :initform helm-grep-map) + (pcre :initarg :pcre :initform nil + :documentation + " Backend is using pcre regexp engine when non--nil.") + (nohighlight :initform t) + (nomark :initform t) + (backend :initarg :backend + :initform nil + :documentation + " The grep backend that will be used. + It is actually used only as an internal flag + and don't set the backend by itself. + You probably don't want to modify this.") + (candidate-number-limit :initform 9999) + (help-message :initform 'helm-grep-help-message) + (history :initform 'helm-grep-history) + (action :initform 'helm-grep-actions) + (persistent-action :initform 'helm-grep-persistent-action) + (persistent-help :initform "Jump to line (`C-u' Record in mark ring)") + (requires-pattern :initform 2) + (before-init-hook :initform 'helm-grep-before-init-hook) + (after-init-hook :initform 'helm-grep-after-init-hook) + (group :initform 'helm-grep))) + +(defvar helm-source-grep nil) + +(defmethod helm--setup-source ((source helm-grep-class)) + (call-next-method) + (helm-aif (and helm-follow-mode-persistent + (if (eq (slot-value source 'backend) 'git) + helm-source-grep-git + helm-source-grep)) + (setf (slot-value source 'follow) + (assoc-default 'follow it)))) + +(cl-defun helm-do-grep-1 (targets &optional recurse backend exts + default-input input (source 'helm-source-grep)) + "Launch helm using backend BACKEND on a list of TARGETS files. + +When RECURSE is given and BACKEND is 'grep' use -r option of +BACKEND and prompt user for EXTS to set the --include args of BACKEND. +Interactively you can give more than one arg separated by space at prompt. +e.g + $Pattern: *.el *.py *.tex + +From lisp use the EXTS argument as a list of extensions as above. +If you are using ack-grep, you will be prompted for --type +instead and EXTS will be ignored. +If prompt is empty `helm-grep-ignored-files' are added to --exclude. + +Argument DEFAULT-INPUT is use as `default' arg of `helm' and INPUT +is used as `input' arg of `helm', See `helm' docstring. + +Arg BACKEND when non--nil specify which backend to use +It is used actually to specify 'zgrep' or 'git'. +When BACKEND 'zgrep' is used don't prompt for a choice +in recurse, and ignore EXTS, search being made recursively on files matching +`helm-zgrep-file-extension-regexp' only." + (let* (non-essential + (ack-rec-p (helm-grep-use-ack-p :where 'recursive)) + (exts (and recurse + ;; [FIXME] I could handle this from helm-walk-directory. + (not (eq backend 'zgrep)) ; zgrep doesn't handle -r opt. + (not ack-rec-p) + (or exts (helm-grep-get-file-extensions targets)))) + (include-files + (and exts + (mapconcat (lambda (x) + (concat "--include=" + (shell-quote-argument x))) + (if (> (length exts) 1) + (remove "*" exts) + exts) " "))) + (types (and (not include-files) + (not (eq backend 'zgrep)) + recurse + ack-rec-p + ;; When %e format spec is not specified + ;; ignore types and do not prompt for choice. + (string-match "%e" helm-grep-default-command) + (helm-grep-read-ack-type))) + (src-name (capitalize (helm-grep-command recurse backend))) + (com (cond ((eq backend 'zgrep) helm-default-zgrep-command) + ((eq backend 'git) helm-grep-git-grep-command) + (recurse helm-grep-default-recurse-command) + ;; When resuming, the local value of + ;; `helm-grep-default-command' is used, only git-grep + ;; should need this. + (t helm-grep-default-command)))) + ;; When called as action from an other source e.g *-find-files + ;; we have to kill action buffer. + (when (get-buffer helm-action-buffer) + (kill-buffer helm-action-buffer)) + ;; If `helm-find-files' haven't already started, + ;; give a default value to `helm-ff-default-directory' + ;; and set locally `default-directory' to this value . See below [1]. + (unless helm-ff-default-directory + (setq helm-ff-default-directory default-directory)) + ;; We need to store these vars locally + ;; to pass infos later to `helm-resume'. + (helm-set-local-variable + 'helm-zgrep-recurse-flag (and recurse (eq backend 'zgrep)) + 'helm-grep-last-targets targets + 'helm-grep-include-files (or include-files types) + 'helm-grep-in-recurse recurse + 'helm-grep-use-zgrep (eq backend 'zgrep) + 'helm-grep-default-command com + 'default-directory helm-ff-default-directory) ;; [1] + ;; Setup the source. + (set source (helm-make-source src-name 'helm-grep-class + :backend backend + :pcre (string-match-p "\\`ack" com))) + (helm + :sources source + :buffer (format "*helm %s*" (helm-grep-command recurse backend)) + :default default-input + :input input + :keymap helm-grep-map + :history 'helm-grep-history + :truncate-lines helm-grep-truncate-lines))) + + +;;; zgrep +;; +;; +(defun helm-ff-zgrep-1 (flist recursive) + (unwind-protect + (let* ((def-dir (or helm-ff-default-directory + default-directory)) + (only (if recursive + (or (gethash def-dir helm-rzgrep-cache) + (puthash + def-dir + (helm-walk-directory + def-dir + :directories nil + :path 'full + :match helm-zgrep-file-extension-regexp) + helm-rzgrep-cache)) + flist))) + (helm-do-grep-1 only recursive 'zgrep)) + (setq helm-zgrep-recurse-flag nil))) + + +;;; transformers +;; +;; +(defun helm-grep-split-line (line) + "Split a grep output line." + ;; The output of grep may send a truncated line in this chunk, + ;; so don't split until grep line is valid, that is + ;; once the second part of the line comes with next chunk + ;; send by process. + (when (string-match helm-grep-split-line-regexp line) + ;; Don't use split-string because buffer/file name or string + ;; may contain a ":". + (cl-loop for n from 1 to 3 collect (match-string n line)))) + +(defun helm-grep--filter-candidate-1 (candidate &optional dir) + (let* ((root (or dir (and helm-grep-default-directory-fn + (funcall helm-grep-default-directory-fn)))) + (ansi-p (string-match-p helm--ansi-color-regexp candidate)) + (line (if ansi-p (helm--ansi-color-apply candidate) candidate)) + (split (helm-grep-split-line line)) + (fname (if (and root split) + ;; Filename should always be provided as a local + ;; path, if the root directory is remote, the + ;; tramp prefix will be added before executing + ;; action, see `helm-grep-action' and issue #2032. + (expand-file-name (car split) + (or (file-remote-p root 'localname) + root)) + (car-safe split))) + (lineno (nth 1 split)) + (str (nth 2 split)) + (display-fname (cl-ecase helm-grep-file-path-style + (basename (and fname (file-name-nondirectory fname))) + (absolute fname) + (relative (and fname root + (file-relative-name fname root)))))) + (if (and display-fname lineno str) + (cons (concat (propertize display-fname + 'face 'helm-grep-file + 'help-echo (abbreviate-file-name fname) + 'helm-grep-fname fname) + ":" + (propertize lineno 'face 'helm-grep-lineno) + ":" + (if ansi-p str (helm-grep-highlight-match str t))) + line) + ""))) + +(defun helm-grep-filter-one-by-one (candidate) + "`filter-one-by-one' transformer function for `helm-do-grep-1'." + (let ((helm-grep-default-directory-fn + (or helm-grep-default-directory-fn + (lambda () (or helm-ff-default-directory + (and (null (eq major-mode 'helm-grep-mode)) + (helm-default-directory)) + default-directory))))) + (if (consp candidate) + ;; Already computed do nothing (default as input). + candidate + (and (stringp candidate) + (helm-grep--filter-candidate-1 candidate))))) + +(defun helm-grep-highlight-match (str &optional multi-match) + "Highlight in string STR all occurences matching `helm-pattern'." + (let (beg end) + (condition-case-unless-debug nil + (with-temp-buffer + (insert (propertize str 'read-only nil)) ; Fix (#1176) + (goto-char (point-min)) + (cl-loop for reg in + (if multi-match + ;; (m)occur. + (cl-loop for r in (helm-mm-split-pattern + helm-pattern) + unless (string-match "\\`!" r) + collect + (helm-aif (and helm-migemo-mode + (assoc r helm-mm--previous-migemo-info)) + (cdr it) r)) + ;; async sources (grep, gid etc...) + (list helm-input)) + do + (while (and (re-search-forward reg nil t) + (> (- (setq end (match-end 0)) + (setq beg (match-beginning 0))) 0)) + (helm-add-face-text-properties beg end 'helm-grep-match)) + do (goto-char (point-min))) + (buffer-string)) + (error nil)))) + + +;;; Grep from buffer list +;; +;; +(defun helm-grep-buffers-1 (candidate &optional zgrep) + "Run grep on all file--buffers or CANDIDATE if it is a file--buffer. +If one of selected buffers is not a file--buffer, +it is ignored and grep will run on all others file--buffers. +If only one candidate is selected and it is not a file--buffer, +switch to this buffer and run `helm-occur'. +If a prefix arg is given run grep on all buffers ignoring non--file-buffers." + (let* ((prefarg (or current-prefix-arg helm-current-prefix-arg)) + (helm-ff-default-directory + (if (and helm-ff-default-directory + (file-remote-p helm-ff-default-directory)) + default-directory + helm-ff-default-directory)) + (cands (if prefarg + (buffer-list) + (helm-marked-candidates))) + (win-conf (current-window-configuration)) + ;; Non--fname and remote buffers are ignored. + (bufs (cl-loop for buf in cands + for fname = (buffer-file-name (get-buffer buf)) + when (and fname (not (file-remote-p fname))) + collect (expand-file-name fname)))) + (if bufs + (if zgrep + (helm-do-grep-1 bufs nil 'zgrep) + (helm-do-grep-1 bufs)) + ;; bufs is empty, thats mean we have only CANDIDATE + ;; and it is not a buffer-filename, fallback to occur. + (switch-to-buffer candidate) + (when (get-buffer helm-action-buffer) + (kill-buffer helm-action-buffer)) + (helm-occur) + (when (eq helm-exit-status 1) + (set-window-configuration win-conf))))) + +(defun helm-grep-buffers (candidate) + "Action to grep buffers." + (helm-grep-buffers-1 candidate)) + +(defun helm-zgrep-buffers (candidate) + "Action to zgrep buffers." + (helm-grep-buffers-1 candidate 'zgrep)) + + +;;; Helm interface for pdfgrep +;; pdfgrep program +;; and a pdf-reader (e.g xpdf) are needed. +;; +(defvar helm-pdfgrep-default-function 'helm-pdfgrep-init) +(defun helm-pdfgrep-init (only-files &optional recurse) + "Start an asynchronous pdfgrep process in ONLY-FILES list." + (let* ((default-directory (or helm-ff-default-directory + default-directory)) + (fnargs (helm-grep-prepare-candidates + (if (file-remote-p default-directory) + (mapcar (lambda (x) + (file-remote-p x 'localname)) + only-files) + only-files) + default-directory)) + (cmd-line (format (if recurse + helm-pdfgrep-default-recurse-command + helm-pdfgrep-default-command) + helm-pattern + fnargs)) + process-connection-type) + ;; Start pdf grep process. + (helm-log "Starting Pdf Grep process in directory `%s'" default-directory) + (helm-log "Command line used was:\n\n%s" + (concat ">>> " (propertize cmd-line 'face 'helm-grep-cmd-line) "\n\n")) + (prog1 + (start-file-process-shell-command + "pdfgrep" helm-buffer cmd-line) + (message nil) + (set-process-sentinel + (get-buffer-process helm-buffer) + (lambda (_process event) + (if (string= event "finished\n") + (with-helm-window + (setq mode-line-format + '(" " mode-line-buffer-identification " " + (:eval (format "L%s" (helm-candidate-number-at-point))) " " + (:eval (propertize + (format "[Pdfgrep Process Finish - %s result(s)] " + (max (1- (count-lines + (point-min) (point-max))) 0)) + 'face 'helm-grep-finish)))) + (force-mode-line-update) + (when helm-allow-mouse + (helm--bind-mouse-for-selection helm-selection-point))) + (helm-log "Error: Pdf grep %s" + (replace-regexp-in-string "\n" "" event)))))))) + +(defun helm-do-pdfgrep-1 (only &optional recurse) + "Launch pdfgrep with a list of ONLY files." + (unless (executable-find "pdfgrep") + (error "Error: No such program `pdfgrep'.")) + (let (helm-grep-in-recurse) ; recursion is implemented differently in *pdfgrep. + ;; When called as action from an other source e.g *-find-files + ;; we have to kill action buffer. + (when (get-buffer helm-action-buffer) + (kill-buffer helm-action-buffer)) + (setq helm-pdfgrep-targets only) + (helm + :sources (helm-build-async-source "PdfGrep" + :init (lambda () + ;; If `helm-find-files' haven't already started, + ;; give a default value to `helm-ff-default-directory'. + (setq helm-ff-default-directory (or helm-ff-default-directory + default-directory))) + :candidates-process (lambda () + (funcall helm-pdfgrep-default-function + helm-pdfgrep-targets recurse)) + :nohighlight t + :nomark t + :filter-one-by-one #'helm-grep-filter-one-by-one + :candidate-number-limit 9999 + :history 'helm-grep-history + :keymap helm-pdfgrep-map + :help-message 'helm-pdfgrep-help-message + :action #'helm-pdfgrep-action + :persistent-help "Jump to PDF Page" + :requires-pattern 2) + :buffer "*helm pdfgrep*" + :history 'helm-grep-history))) + +(defun helm-pdfgrep-action (candidate) + (helm-grep-action candidate 'pdf)) + +(defun helm-pdfgrep-action-1 (_split pageno fname) + (save-selected-window + (start-file-process-shell-command + "pdf-reader" nil + (format-spec helm-pdfgrep-default-read-command + (list (cons ?f fname) (cons ?p pageno)))))) + +;;; AG - PT - RG +;; +;; https://github.com/ggreer/the_silver_searcher +;; https://github.com/monochromegane/the_platinum_searcher +;; https://github.com/BurntSushi/ripgrep + +(defcustom helm-grep-ag-command + "ag --line-numbers -S --hidden --color --nogroup %s %s %s" + "The default command for AG, PT or RG. + +Takes three format specs, the first for type(s), the second for pattern +and the third for directory. + +You can use safely \"--color\" (used by default) with AG RG and PT. + +For ripgrep here is the command line to use: + + rg --color=always --smart-case --no-heading --line-number %s %s %s + +NOTE: Old versions of ripgrep was not supporting colors in emacs and a +workaround had to be used (i.e prefixing command line with +\"TERM=eterm-color\"), this is no more needed. +See issue for more infos. + +You must use an output format that fit with helm grep, that is: + + \"filename:line-number:string\" + +The option \"--nogroup\" allow this. +The option \"--line-numbers\" is also mandatory except with PT (not supported). +For RG the options \"--no-heading\" and \"--line-number\" are the ones to use. + +When modifying the default colors of matches with e.g \"--color-match\" option of AG +you may want to modify as well `helm-grep-ag-pipe-cmd-switches' to have all matches +colorized with same color in multi match." + :group 'helm-grep + :type 'string) + +(defun helm-grep--ag-command () + (car (helm-remove-if-match + "\\`[A-Z]*=" (split-string helm-grep-ag-command)))) + +(defun helm-grep-ag-get-types () + "Returns a list of AG types if available with AG version. +See AG option \"--list-file-types\" +Ripgrep (rg) types are also supported if this backend is used." + (with-temp-buffer + (let* ((com (helm-grep--ag-command)) + (ripgrep (string= com "rg")) + (regex (if ripgrep "^\\(.*\\):" "^ *\\(--[a-z]*\\)")) + (prefix (if ripgrep "-t" ""))) + (when (equal (call-process com + nil t nil + (if ripgrep + "--type-list" "--list-file-types")) 0) + (goto-char (point-min)) + (cl-loop while (re-search-forward regex nil t) + for type = (match-string 1) + collect (cons type (concat prefix type))))))) + +(defun helm-grep-ag-prepare-cmd-line (pattern directory &optional type) + "Prepare AG command line to search PATTERN in DIRECTORY. +When TYPE is specified it is one of what returns `helm-grep-ag-get-types' +if available with current AG version." + (let* ((patterns (helm-mm-split-pattern pattern t)) + (pipe-switches (mapconcat 'identity helm-grep-ag-pipe-cmd-switches " ")) + (pipe-cmd (helm-acase (helm-grep--ag-command) + (("ag" "pt") + (format "%s -S --color%s" it (concat " " pipe-switches))) + ("rg" (format "rg -N -S --color=always%s" + (concat " " pipe-switches))))) + (cmd (format helm-grep-ag-command + (mapconcat 'identity type " ") + (shell-quote-argument (car patterns)) + (shell-quote-argument directory)))) + (helm-aif (cdr patterns) + (concat cmd (cl-loop for p in it concat + (format " | %s %s" + pipe-cmd (shell-quote-argument p)))) + cmd))) + +(defun helm-grep-ag-init (directory &optional type) + "Start AG process in DIRECTORY maybe searching only files of type TYPE." + (let ((default-directory (or helm-ff-default-directory + (helm-default-directory) + default-directory)) + (cmd-line (helm-grep-ag-prepare-cmd-line + helm-pattern (or (file-remote-p directory 'localname) + directory) + type)) + (start-time (float-time)) + (proc-name (helm-grep--ag-command))) + (set (make-local-variable 'helm-grep-last-cmd-line) cmd-line) + (helm-log "Starting %s process in directory `%s'" + proc-name directory) + (helm-log "Command line used was:\n\n%s" + (concat ">>> " cmd-line "\n\n")) + (prog1 + (start-file-process-shell-command + proc-name helm-buffer cmd-line) + (set-process-sentinel + (get-buffer-process helm-buffer) + (lambda (process event) + (let* ((err (process-exit-status process)) + (noresult (= err 1))) + (cond (noresult + (with-helm-buffer + (insert (concat "* Exit with code 1, no result found," + " command line was:\n\n " + (propertize helm-grep-last-cmd-line + 'face 'helm-grep-cmd-line))) + (setq mode-line-format + `(" " mode-line-buffer-identification " " + (:eval (format "L%s" (helm-candidate-number-at-point))) " " + (:eval (propertize + (format + "[%s process finished - (no results)] " + ,(upcase proc-name)) + 'face 'helm-grep-finish)))))) + ((string= event "finished\n") + (helm-log "%s process finished with %s results in %fs" + proc-name + (helm-get-candidate-number) + (- (float-time) start-time)) + (helm-maybe-show-help-echo) + (with-helm-window + (setq mode-line-format + `(" " mode-line-buffer-identification " " + (:eval (format "L%s" (helm-candidate-number-at-point))) " " + (:eval (propertize + (format + "[%s process finished in %.2fs - (%s results)] " + ,(upcase proc-name) + ,(- (float-time) start-time) + (helm-get-candidate-number)) + 'face 'helm-grep-finish)))) + (force-mode-line-update) + (when helm-allow-mouse + (helm--bind-mouse-for-selection helm-selection-point)))) + (t (helm-log + "Error: %s %s" + proc-name + (replace-regexp-in-string "\n" "" event)))))))))) + +(defclass helm-grep-ag-class (helm-source-async) + ((nohighlight :initform t) + (pcre :initarg :pcre :initform t + :documentation + " Backend is using pcre regexp engine when non--nil.") + (keymap :initform helm-grep-map) + (history :initform 'helm-grep-ag-history) + (help-message :initform 'helm-grep-help-message) + (filter-one-by-one :initform 'helm-grep-filter-one-by-one) + (persistent-action :initform 'helm-grep-persistent-action) + (persistent-help :initform "Jump to line (`C-u' Record in mark ring)") + (candidate-number-limit :initform 99999) + (requires-pattern :initform 2) + (nomark :initform t) + (action :initform 'helm-grep-actions) + (group :initform 'helm-grep))) + +(defvar helm-source-grep-ag nil) + +(defmethod helm--setup-source ((source helm-grep-ag-class)) + (call-next-method) + (helm-aif (and helm-follow-mode-persistent + helm-source-grep-ag + (assoc-default 'follow helm-source-grep-ag)) + (setf (slot-value source 'follow) it))) + +(defun helm-grep-ag-1 (directory &optional type) + "Start helm ag in DIRECTORY maybe searching in files of type TYPE." + (setq helm-source-grep-ag + (helm-make-source (upcase (helm-grep--ag-command)) 'helm-grep-ag-class + :header-name (lambda (name) + (format "%s [%s]" + name (abbreviate-file-name directory))) + :candidates-process + (lambda () (helm-grep-ag-init directory type)))) + (helm :sources 'helm-source-grep-ag + :keymap helm-grep-map + :history 'helm-grep-ag-history + :truncate-lines helm-grep-truncate-lines + :buffer (format "*helm %s*" (helm-grep--ag-command)))) + +(defun helm-grep-ag (directory with-types) + "Start grep AG in DIRECTORY. +When WITH-TYPES is non-nil provide completion on AG types." + (require 'helm-adaptive) + (helm-grep-ag-1 directory + (helm-aif (and with-types + (helm-grep-ag-get-types)) + (helm-comp-read + "Ag type: " it + :must-match t + :marked-candidates t + :fc-transformer 'helm-adaptive-sort + :buffer "*helm ag types*")))) + +;;; Git grep +;; +;; +(defvar helm-source-grep-git nil) + +(defcustom helm-grep-git-grep-command + "git --no-pager grep -n%cH --color=always --full-name -e %p -- %f" + "The git grep default command line. +The option \"--color=always\" can be used safely. +The color of matched items can be customized in your .gitconfig +See `helm-grep-default-command' for more infos. + +The \"--exclude-standard\" and \"--no-index\" switches allow +skipping unwanted files specified in ~/.gitignore_global +and searching files not already staged (not enabled by default). + +You have also to enable this in global \".gitconfig\" with + \"git config --global core.excludesfile ~/.gitignore_global\"." + :group 'helm-grep + :type 'string) + +(defun helm-grep-git-1 (directory &optional all default input) + "Run git-grep on DIRECTORY. +If DIRECTORY is not inside or part of a git repo exit with error. +If optional arg ALL is non-nil grep the whole repo otherwise start +at DIRECTORY. +Arg DEFAULT is what you will have with `next-history-element', +arg INPUT is what you will have by default at prompt on startup." + (require 'vc) + (let* (helm-grep-default-recurse-command + ;; Expand filename of each candidate with the git root dir. + ;; The filename will be in the helm-grep-fname prop. + (helm-grep-default-directory-fn (lambda () + (vc-find-root directory ".git"))) + (helm-ff-default-directory (funcall helm-grep-default-directory-fn))) + (cl-assert helm-ff-default-directory nil "Not inside a Git repository") + (helm-do-grep-1 (if all '("") `(,(expand-file-name directory))) + nil 'git nil default input 'helm-source-grep-git))) + + +;;;###autoload +(defun helm-do-grep-ag (arg) + "Preconfigured helm for grepping with AG in `default-directory'. +With prefix-arg prompt for type if available with your AG version." + (interactive "P") + (require 'helm-files) + (helm-grep-ag (expand-file-name default-directory) arg)) + +;;;###autoload +(defun helm-grep-do-git-grep (arg) + "Preconfigured helm for git-grepping `default-directory'. +With a prefix arg ARG git-grep the whole repository." + (interactive "P") + (require 'helm-files) + (helm-grep-git-1 default-directory arg)) + + +(provide 'helm-grep) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-grep.el ends here diff --git a/elpa/helm-20181113.923/helm-help.el b/elpa/helm-20181113.923/helm-help.el new file mode 100644 index 00000000..935ddba8 --- /dev/null +++ b/elpa/helm-20181113.923/helm-help.el @@ -0,0 +1,1728 @@ +;;; helm-help.el --- Help messages for Helm. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: +(require 'helm) + +(defvar helm-org-headings--nofilename) +(declare-function helm-source-org-headings-for-files "helm-org.el") + + +(defgroup helm-help nil + "Embedded help for `helm'." + :group 'helm) + +(defface helm-helper + '((t :inherit helm-header)) + "Face for Helm help string in minibuffer." + :group 'helm-help) + +(defvar helm-help--string-list '(helm-help-message + helm-buffer-help-message + helm-ff-help-message + helm-read-file-name-help-message + helm-generic-file-help-message + helm-grep-help-message + helm-pdfgrep-help-message + helm-etags-help-message + helm-ucs-help-message + helm-bookmark-help-message + helm-esh-help-message + helm-buffers-ido-virtual-help-message + helm-moccur-help-message + helm-top-help-message + helm-el-package-help-message + helm-M-x-help-message + helm-imenu-help-message + helm-colors-help-message + helm-semantic-help-message + helm-kmacro-help-message)) + +(defvar helm-documentation-buffer-name "*helm documentation*") + +;;;###autoload +(defun helm-documentation () + "Preconfigured Helm for Helm documentation. +With a prefix arg refresh the documentation. + +Find here the documentation of all documented sources." + (interactive) + (require 'helm-org) + (with-current-buffer (get-buffer-create helm-documentation-buffer-name) + (let ((inhibit-read-only t)) + (erase-buffer) + (cl-loop for elm in helm-help--string-list + for str = (helm-interpret-value elm) + do (insert (substitute-command-keys str) "\n\n")) + (org-mode)) + (setq buffer-read-only t) + (view-mode)) + (let ((helm-org-headings--nofilename t)) + (helm :sources (helm-source-org-headings-for-files + (list (get-buffer helm-documentation-buffer-name))) + :candidate-number-limit 99999 + :buffer "*helm doc*"))) + +;;; Local help messages. + +;;; `helm-buffer-list' help +;; +;; +(defvar helm-buffer-help-message + "* Helm Buffer + +** Tips + +*** Completion + +**** Major-mode + +You can enter a partial major-mode name (e.g. lisp, sh) to narrow down buffers. +To specify the major-mode, prefix it with \"*\" e.g. \"*lisp\". + +If you want to match all buffers but the ones with a specific major-mode +\(negation), prefix the major-mode with \"!\" e.g. \"*!lisp\". + +If you want to specify more than one major-mode, separate them with \",\", +e.g. \"*!lisp,!sh,!fun\" lists all buffers but the ones in lisp-mode, sh-mode +and fundamental-mode. + +Then enter a space followed by a pattern to narrow down to buffers matching this +pattern. + +**** Search inside buffers + +If you enter a space and a pattern prefixed by \"@\", Helm searches for text +matching this pattern \*inside* the buffer (i.e. not in the name of the buffer). + +If you enter a pattern prefixed with an escaped \"@\", Helm searches for a +buffer matching \"@pattern\" but does not search inside. + +**** Search by directory name + +If you prefix the pattern with \"/\", Helm matches over the directory names +of the buffers. + +This feature can be used to narrow down the search to one directory while +subsequent strings entered after a space match over the buffer name only. + +Note that negation is not supported for matching on buffer filename. + +Starting from Helm v1.6.8, you can specify more than one directory. + +**** Fuzzy matching + +`helm-buffers-fuzzy-matching' turns on fuzzy matching on buffer names, but not +on directory names or major modes. A pattern starting with \"^\" disables fuzzy +matching and matches by exact regexp. + +**** Examples + +With the following pattern + + \"*lisp ^helm @moc\" + +Helm narrows down the list by selecting only the buffers that are in lisp mode, +start with \"helm\" and which content matches \"moc\". + +Without the \"@\" + + \"*lisp ^helm moc\" + +Helm looks for lisp mode buffers starting with \"helm\" and containing \"moc\" +in their name. + +With this other pattern + + \"*!lisp !helm\" + +Helm narrows down to buffers that are not in \"lisp\" mode and that do not match +\"helm\". + +With this last pattern + + /helm/ w3 + +Helm narrows down to buffers that are in any \"helm\" subdirectory and +matching \"w3\". + +*** Creating buffers + +When creating a new buffer, use `\\[universal-argument]' to choose a mode from a +list. This list is customizable, see `helm-buffers-favorite-modes'. + +*** Killing buffers + +You can kill buffers either one by one or all the marked buffers at once. + +One kill-buffer command leaves Helm while the other is persistent. Run the +persistent kill-buffer command either with the regular +`helm-execute-persistent-action' called with a prefix argument (`\\[universal-argument] \\\\[helm-execute-persistent-action]') +or with its specific command `helm-buffer-run-kill-persistent'. See the +bindings below. + +*** Switching to buffers + +To switch to a buffer, press RET, to switch to a buffer in another window, select this buffer +and press \\\\[helm-buffer-switch-other-window], when called with a prefix arg +the buffer will be displayed vertically in other window. +If you mark more than one buffer, the marked buffers will be displayed in different windows. + +*** Meaning of colors and prefixes for buffers + +Remote buffers are prefixed with '@'. +Red => Buffer's file was modified on disk by an external process. +Indianred2 => Buffer exists but its file has been deleted. +Orange => Buffer is modified and not saved to disk. +Italic => A non-file buffer. +Yellow => Tramp archive buffer. + +** Commands +\\ +\\[helm-buffer-run-zgrep]\t\tGrep Buffer(s) works as zgrep too (`\\[universal-argument]' to grep all buffers but non-file buffers). +\\[helm-buffers-run-multi-occur]\t\tMulti-Occur buffer or marked buffers (`\\[universal-argument]' to toggle force-searching current-buffer). +\\[helm-buffer-switch-other-window]\t\tSwitch to other window. +\\[helm-buffer-switch-other-frame]\t\tSwitch to other frame. +\\[helm-buffers-run-browse-project]\t\tBrowse project from buffer. +\\[helm-buffer-run-query-replace-regexp]\t\tQuery-replace-regexp in marked buffers. +\\[helm-buffer-run-query-replace]\t\tQuery-replace in marked buffers. +\\[helm-buffer-run-ediff]\t\tEdiff current buffer with candidate. With two marked buffers, ediff those buffers. +\\[helm-buffer-run-ediff-merge]\t\tEdiff-merge current buffer with candidate. With two marked buffers, ediff-merge those buffers. +\\[helm-buffer-diff-persistent]\t\tToggle Diff-buffer with saved file without leaving Helm. +\\[helm-buffer-revert-persistent]\t\tRevert buffer without leaving Helm. +\\[helm-buffer-save-persistent]\t\tSave buffer without leaving Helm. +\\[helm-buffer-run-kill-buffers]\t\tDelete marked buffers and leave Helm. +\\[helm-buffer-run-kill-persistent]\t\tDelete buffer without leaving Helm. +\\[helm-buffer-run-rename-buffer]\t\tRename buffer. +\\[helm-toggle-all-marks]\t\tToggle all marks. +\\[helm-mark-all]\t\tMark all. +\\[helm-toggle-buffers-details]\t\tToggle details. +\\[helm-buffers-toggle-show-hidden-buffers]\t\tShow hidden buffers. +\\[helm-buffers-mark-similar-buffers]\t\tMark all buffers of the same type (color) as current buffer.") + +;;; Find files help (`helm-find-files') +;; +;; +(defvar helm-ff-help-message + "* Helm Find Files + +** Tips + +*** Navigation summary + +For a better experience you can enable auto completion by setting +`helm-ff-auto-update-initial-value' to non-nil in your init file. It is not +enabled by default to not confuse new users. + +**** Use `\\\\[helm-execute-persistent-action]' (persistent action) on a directory to go down one level + +On a symlinked directory a prefix argument expands to its true name. + +**** Use `\\\\[helm-find-files-up-one-level]' on a directory to go up one level + +**** Use `\\\\[helm-find-files-down-last-level]' to walk back the resulting tree of all the `\\\\[helm-execute-persistent-action]' you did + +The tree is reinitialized each time you browse a new tree with +`\\\\[helm-execute-persistent-action]' or by entering some pattern in the prompt. + +**** `RET' behavior + +It behaves differently depending on `helm-selection' (current candidate in helm-buffer): + +- candidate basename is \".\" => Open it in dired. +- candidate is a directory => Expand it. +- candidate is a file => Open it. +- marked candidates (1+) => Open them with default action. + +Note that when copying, renaming, etc. from `helm-find-files' the +destination file is selected with `helm-read-file-name'. + +To avoid confusion when using `read-file-name' or `read-directory-name', `RET' +follows its standard Emacs behaviour, i.e. it exits the minibuffer as soon as +you press `RET'. If you want the same behavior as in `helm-find-files', bind +`helm-ff-RET' to the `helm-read-file-map': + + (define-key helm-read-file-map (kbd \"RET\") 'helm-ff-RET) + +*** Find file at point + +Helm uses `ffap' partially or completely to find file at point depending on the +value of `helm-ff-guess-ffap-filenames': if non-nil, support is complete +\(annoying), if nil, support is partial. + +**** Find file at line number + +When text at point is in the form of + + ~/elisp/helm/helm.el:1234 + +Helm finds this file at the indicated line number, here 1234. + +**** Find URL at point + +When a URL is found at point, Helm expands to that URL only. +Pressing `RET' opens that URL using `browse-url-browser-function'. + +**** Find e-mail address at point + +When an e-mail address is found at point, Helm expands to this e-mail address +prefixed with \"mailto:\". Pressing `RET' opens a message buffer with that +e-mail address. + +*** Quick pattern expansion + +**** Enter `~/' at end of pattern to quickly reach home directory + +**** Enter `/' at end of pattern to quickly reach the file system root + +**** Enter `./' at end of pattern to quickly reach `default-directory' + +\(As per its value at the beginning of the session.) + +If you already are in the `default-directory' this will move the cursor to the top. + +**** Enter `../' at end of pattern will reach upper directory, moving cursor to the top + +This is different from using `\\\\[helm-find-files-up-one-level]' in that it moves +the cursor to the top instead of remaining on the previous subdir name. + +**** Enter `..name/' at end of pattern to start a recursive search + +It searches directories matching \"name\" under the current directory, see the +\"Recursive completion on subdirectories\" section below for more details. + +**** Any environment variable (e.g. `$HOME') at end of pattern gets expanded + +**** Any valid filename yanked after pattern gets expanded + +**** Special case: URL at point + +The quick expansions do not take effect after end a URL, you must kill the +pattern first (`\\[helm-delete-minibuffer-contents]'). + +*** Helm-find-files supports fuzzy matching + +It starts from the third character of the pattern. + +For instance \"fob\" or \"fbr\" will complete \"foobar\" but \"fb\" needs a +third character in order to complete it. + +*** Use `\\[universal-argument] \\[helm-execute-persistent-action]' or `\\[helm-follow-action-forward]' to display an image + +*** `\\[helm-execute-persistent-action]' on a filename expands to that filename in the Helm buffer + +Second hit displays the buffer filename. +Third hit kills the buffer filename. +Note: `\\[universal-argument] \\[helm-execute-persistent-action]' displays the buffer directly. + +*** Browse images directories with `helm-follow-mode' and navigate up/down + +You can also use `helm-follow-action-forward' and `helm-follow-action-backward' with +`\\[helm-follow-action-forward]' and `\\[helm-follow-action-backward]' respectively. + +*** Toggle auto-completion with `\\[helm-ff-run-toggle-auto-update]' + +It is useful when trying to create a new file or directory and you don't want +Helm to complete what you are writing. + +Note: On a terminal, the default binding `C-' may not work. +In this case use `C-c '. + +*** You can create a new directory and a new file at the same time + +Simply write the path in the prompt and press `RET', e.g. +\"~/new/newnew/newnewnew/my_newfile.txt\". + +*** To create a new directory, append a \"/\" to the new name and press `RET' + +*** To create a new file, enter a filename not ending with \"/\" + +Note that when you enter a new name, this one is prefixed with +\[?] if you are in a writable directory. If you are in a directory +where you have no write permission the new file name is not +prefixed and is colored in red. There is not such distinction +when using tramp, new filename just appear on top of buffer. + +*** Recursive search from Helm-find-files + +**** You can use Helm-browse-project (see binding below) + +- With no prefix argument: +If the current directory is under version control with either git or hg and +helm-ls-git and/or helm-ls-hg are installed, it lists all the files under +version control. Otherwise it falls back to Helm-find-files. See +https://github.com/emacs-helm/helm-ls-git and +https://github.com/emacs-helm/helm-ls-hg. + +- With one prefix argument: +List all the files under this directory and other subdirectories +\(recursion) and this list of files will be cached. + +- With two prefix arguments: +Same but the cache is refreshed. + +**** You can start a recursive search with \"locate\" or \"find\" + +See \"Note\" in the [[Recusive completion on subdirectories][section on subdirectories]]. + +Using \"locate\", you can enable the local database with a prefix argument. If the +local database doesn't already exists, you will be prompted for its creation. +If it exists and you want to refresh it, give it two prefix args. + +When using locate the helm-buffer remains empty until you type something. +Regardless Helm uses the basename of the pattern entered in the helm-find-files +session by default. Hitting `\\[next-history-element]' should just kick in the +locate search with this pattern. If you want Helm to automatically do this, add +`helm-source-locate' to `helm-sources-using-default-as-input'. + +**** Recursive completion on subdirectories + +Starting from the directory you are currently browsing, it is possible to have +completion of all directories underneath. Say you are at \"/home/you/foo/\" and +you want to go to \"/home/you/foo/bar/baz/somewhere/else\", simply type +\"/home/you/foo/..else\" and hit `\\[helm-execute-persistent-action]' or enter +the final \"/\". Helm will then list all possible directories under \"foo\" +matching \"else\". + +Entering two spaces before \"else\" instead of two dots also works. + +Note: Completion on subdirectories uses \"locate\" as backend, you can configure +the command with `helm-locate-recursive-dirs-command'. Because this completion +uses an index, the directory tree displayed may be out-of-date and not reflect +the latest change until you update the index (using \"updatedb\" for \"locate\"). + +If for some reason you cannot use an index, the \"find\" command from +\"findutils\" can be used instead. It will be slower though. You need to pass +the basedir as first argument of \"find\" and the subdir as the value for +'-(i)regex' or '-(i)name' with the two format specs that are mandatory in +`helm-locate-recursive-dirs-command'. + +Examples: +- \"find %s -type d -name '*%s*'\" +- \"find %s -type d -regex .*%s.*$\" + +*** Insert filename at point or complete filename at point + +On insertion (not on completion, i.e. there is nothing at point): + +- `\\[helm-ff-run-complete-fn-at-point]': insert absolute file name. +- `\\[universal-argument] \\[helm-ff-run-complete-fn-at-point]': insert abbreviated file name. +- `\\[universal-argument] \\[universal-argument] \\[helm-ff-run-complete-fn-at-point]': insert relative file name. + +On completion: + +- Target starts with \"~/\": insert abbreviate file name. +- target starts with \"/\" or \"[a-z]:/\": insert full path. +- Otherwise: insert relative file name. + +*** Use the wildcard to select multiple files + +Use of wilcard is supported to run an action over a set of files. + +Example: You can copy all the files with \".el\" extension by using \"*.el\" and +then run copy action. + +Similarly, \"**.el\" (note the two stars) will recursively select all \".el\" +files under the current directory. + +Note that when recursively copying files, you may have files with same name +dispatched across different subdirectories, so when copying them in the same +directory they will get overwritten. To avoid this Helm has a special action +called \"backup files\" that has the same behavior as the command line \"cp -f +--backup=numbered\": it allows you to copy many files with the same name from +different subdirectories into one directory. Files with same name are renamed +as follows: \"foo.txt.~1~\". Like with the --force option of cp, it is possible +to backup files in current directory. + +This command is available only when `dired-async-mode' is active. + +When using an action that involves an external backend (e.g. grep), using \"**\" +is not recommended (even thought it works fine) because it will be slower to +select all the files. You are better off leaving the backend to do it, it will +be faster. However, if you know you have not many files it is reasonable to use +this, also using not recursive wilcard (e.g. \"*.el\") is perfectly fine for +this. + +The \"**\" feature is active by default in the option `helm-file-globstar'. It +is different from the Bash \"shopt globstar\" feature in that to list files with +a named extension recursively you would write \"**.el\" whereas in Bash it would +be \"**/*.el\". Directory selection with \"**/\" like Bash \"shopt globstar\" +option is not supported yet. + +*** Query replace regexp on filenames + +Replace different parts of a file basename with something else. + +When calling this action you will be prompted twice as with +`query-replace', first for the matching expression of the text to +replace and second for the replacement text. Several facilities, +however, are provided to make the two prompts more powerfull. + +**** Syntax of the first prompt + +In addition to simple regexps, these shortcuts are available: + +- Basename without extension => \"%.\" +- Only extension => \".%\" +- Substring => \"%::\" +- Whole basename => \"%\" + +**** Syntax of the second prompt + +In addition to a simple string to use as replacement, here is what you can use: + +- A placeholder refering to what you have selected in the first prompt: \"\\@\". + +After this placeholder you can use a search-and-replace syntax à-la sed: + + \"\\@/// + +You can select a substring from the string represented by the placeholder: + + \"\\@::\" + +- A special character representing a number which is incremented: \"\\#\". + +- Shortcuts for `upcase', `downcase' and `capitalize' +are available as`%u', `%d' and `%c' respectively. + +**** Examples + +***** Recursively rename all files with \".JPG\" extension to \".jpg\" + +Use the `helm-file-globstar' feature described in [[Using wildcard to select multiple files][recursive globbing]] +by entering \"**.JPG\" at the end of the Helm-find-files pattern, then hit +\\\\[helm-ff-query-replace-on-filenames]: First \"JPG\", then \"jpg\" +and hit `RET'. + +Alternatively you can enter \".%\" at the first prompt, then \"jpg\" and hit +`RET'. Note that when using this instead of using \"JPG\" at the first prompt, +all extensions will be renamed to \"jpg\" even if the extension of one of the +files is, say, \"png\". If you want to keep the original extension you can use +\"%d\" at the second prompt (downcase). + +***** Batch-rename files from number 001 to 00x + +Use \"\\#\" inside the second prompt. + +Example 1: To rename the files + + foo.jpg + bar.jpg + baz.jpg + +to + + foo-001.jpg + foo-002.jpg + foo-003.jpg + +use \"%.\" as matching regexp and \"foo-\\#\" as replacement string. + +Example 2: To rename the files + + foo.jpg + bar.jpg + baz.jpg + +to + + foo-001.jpg + bar-002.jpg + baz-003.jpg + +use as matching regexp \"%.\" and as replacement string \"\\@-\\#\". + +***** Replace a substring + +Use \"%::\". + +Example: To rename files + + foo.jpg + bar.jpg + baz.jpg + +to + + fOo.jpg + bAr.jpg + bAz.jpg + +use as matching regexp \"%:1:2\" and as replacement string \"%u\" (upcase). + +Note that you \*cannot* use \"%.\" and \".%\" along with substring replacement. + +***** Modify the string from the placeholder (\\@) + +- By substring, i.e. only using the substring of the placeholder: \"\\@::\". +The length of placeholder is used for when unspecified. + +Example 1: \"\\@:0:2\" replaces from the beginning to the second char of the placeholder. + +Example 2: \\@:2: replaces from the second char of the placeholder to the end. + +- By search-and-replace: \"\\@///\". + +Incremental replacement is also handled in . + +Example 3: \"\\@/foo/bar/\" replaces \"foo\" by \"bar\" in the placeholder. + +Example 4: \"\\@/foo/-\\#/\" replaces \"foo\" in the placeholder by 001, 002, etc. + +***** Clash in replacements (avoid overwriting files) + +When performing any of these replacement operations you may end up with same +names as replacement. In such cases Helm numbers the file that would otherwise +overwritten. For instance, should you remove the \"-m\" part from the files +\"emacs-m1.txt\", \"emacs-m2.txt\" and \"emacs-m3.txt\" you would end up with +three files named \"emacs.txt\", the second renaming overwriting first file, and +the third renaming overwriting second file and so on. Instead Helm will +automatically rename the second and third files as \"emacs(1).txt\" and +\"emacs(2).txt\" respectively. + +***** Query-replace on filenames vs. serial-rename action + +Unlike the [[Serial renaming][serial rename]] actions, the files renamed with +the query-replace action stay in their initial directory and are not moved to +the current directory. As such, using \"\\#\" to serial-rename files only makes +sense for files inside the same directory. It even keeps renaming files +with an incremental number in the next directories. + +*** Serial-rename + +You can use the serial-rename actions to rename, copy or symlink marked files to +a specific directory or in the current directory with all the files numbered +incrementally. + +- Serial-rename by renaming: +Rename all marked files with incremental numbering to a specific directory. + +- Serial-rename by copying: +Copy all marked files with incremental numbering to a specific directory. + +- Serial-rename by symlinking: +Symlink all marked files with incremental numbering to a specific directory. + +*** Edit marked files in a dired buffer + +You can open a dired buffer containing only marked files with `\\\\[helm-ff-run-marked-files-in-dired]'. +With a prefix argument you can open this same dired buffer in wdired mode for +editing. Note that wildcards are supported as well, so you can use e.g. +\"*.txt\" to select all \".txt\" files in the current directory or \"**.txt\" to +select all files recursively from the current directory. +See [[Use the wildcard to select multiple files]] section above. + +*** Defining default target directory for copying, renaming, etc + +You can customize `helm-dwim-target' to behave differently depending on the +windows open in the current frame. Default is to provide completion on all +directories associated to each window. + +*** Copying and renaming asynchronously + +If you have the async library installed (if you got Helm from MELPA you do), you +can use it for copying/renaming files by enabling `dired-async-mode'. + +Note that even when async is enabled, running a copy/rename action with a prefix +argument will execute action synchronously. Moreover it will follow the first +file of the marked files in its destination directory. + +When `dired-async-mode' is enabled, an additional action named \"Backup files\" +will be available. (Such command is not natively available in Emacs). +See [[Use the wildcard to select multiple files]] for details. + +*** Bookmark the `helm-find-files' session + +You can bookmark the `helm-find-files' session with `\\[helm-ff-bookmark-set]'. +You can later retrieve these bookmarks by calling `helm-filtered-bookmarks' +or, from the current `helm-find-files' session, by hitting `\\[helm-find-files-toggle-to-bookmark]'. + +*** Grep files from `helm-find-files' + +You can grep individual files from `helm-find-files' by using +\`\\\\[helm-ff-run-grep]'. This same command can also +recursively grep files from the current directory when called with a prefix +argument. In this case you will be prompted for the file extensions to use +\(grep backend) or the types of files to use (ack-grep backend). See the +`helm-grep-default-command' documentation to set this up. For compressed files +or archives, use zgrep with \`\\\\[helm-ff-run-zgrep]'. + +Otherwise you can use recursive commands like \`\\\\[helm-ff-run-grep-ag]' or `\\\\[helm-ff-run-git-grep]' +that are much faster than using `\\\\[helm-ff-run-grep]' with a prefix argument. +See `helm-grep-ag-command' and `helm-grep-git-grep-command' to set this up. + +You can also use \"id-utils\"' GID with \`\\\\[helm-ff-run-gid]' +by creating an ID index file with the \"mkid\" shell command. + +All those grep commands use the symbol at point as the default pattern. +Note that default is different from input (nothing is added to the prompt until +you hit `\\[next-history-element]'). + +**** Grepping on remote files + +On remote files grep is not well supported by TRAMP unless you suspend updates before +entering the pattern and re-enable it once your pattern is ready. +To toggle suspend-update, use `\\\\[helm-toggle-suspend-update]'. + +*** Setting up aliases in Eshell allows you to set up powerful customized commands + +Adding Eshell aliases to your `eshell-aliases-file' or using the +`alias' command from Eshell allows you to create personalized +commands not available in `helm-find-files' actions and use them +from `\\\\[helm-ff-run-eshell-command-on-file]'. + +Example: You want a command to uncompress some \"*.tar.gz\" files from `helm-find-files': + +1) Create an Eshell alias named, say, \"untargz\" with the command +\"alias untargz tar zxvf $*\". + +2) Now from `helm-find-files' select the \"*.tar.gz\" file (you can also +mark files if needed) and hit `\\\\[helm-ff-run-eshell-command-on-file]'. + +Note: When using marked files with this, the meaning of the prefix argument is +quite subtle. Say you have \"foo\", \"bar\" and \"baz\" marked; when you run +the alias command `example' on these files with no prefix argument it will run +`example' sequentially on each file: + +$ example foo +$ example bar +$ example baz + +With a prefix argument however it will apply `example' on all files at once: + +$ example foo bar baz + +Of course the alias command should support this. + +*** Using TRAMP with `helm-find-files' to read remote directories + +`helm-find-files' works fine with TRAMP despite some limitations. + +- Grepping files is not very well supported when used incrementally. +See [[Grepping on remote files]]. + +- Locate does not work on remote directories. + +**** A TRAMP syntax crash course + +Please refer to TRAMP's documentation for more details. + +- Connect to host 192.168.0.4 as user \"foo\": + +/scp:192.168.0.4@foo: + +- Connect to host 192.168.0.4 as user \"foo\" on port 2222: + +/scp:192.168.0.4@foo#2222: + +- Connect to host 192.168.0.4 as root using multihops syntax: + +/ssh:192.168.0.4@foo|sudo:192.168.0.4: + +Note: You can also use `tramp-default-proxies-alist' when connecting often to +the same hosts. + +As a rule of thumb, prefer the scp method unless using multihops (which only +works with the ssh method), especially when copying large files. + +You need to hit `C-j' once on top of a directory on the first connection +to complete the pattern in the minibuffer. + +**** Display color for directories, symlinks etc... with tramp + +Starting at helm version 2.9.7 it is somewhat possible to +colorize fnames by listing files without loosing performances with +external commands (ls and awk) if your system is compatible. +For this you can use `helm-list-dir-external' as value +for `helm-list-directory-function'. + +See `helm-list-directory-function' documentation for more infos. + +**** Completing host + +As soon as you enter the first \":\" after method e.g =/scp:= you will +have some completion about previously used hosts or from your =~/.ssh/config= +file, hitting `\\[helm-execute-persistent-action]' or `right' on a candidate will insert this host in minibuffer +without addind the ending \":\", second hit insert the last \":\". +As soon the last \":\" is entered TRAMP will kick in and you should see the list +of candidates soon after. + +When connection fails, be sure to delete your TRAMP connection with M-x +`helm-delete-tramp-connection' before retrying. + +**** Editing local files as root + +Use the sudo method: + +\"/sudo:host:\" or simply \"/sudo::\". + +*** Attach files to a mail buffer (message-mode) + +If you are in a `message-mode' or `mail-mode' buffer, that action will appear +in action menu, otherwise it is available at any time with \\\\[helm-ff-run-mail-attach-files]. +It behaves as follows: + +- If you are in a (mail or message) buffer, files are attached there. + +- If you are not in a mail buffer but one or more mail buffers exist, you are +prompted to attach files to one of these mail buffers. + +- If you are not in a mail buffer and no mail buffer exists, +a new mail buffer is created with the attached files in it. + +*** Open files in separate windows + +When [[Marked candidates][marking]] multiple files or using [[Use the wildcard to select multiple files][wildcard]], helm allow opening all +this files in separate windows using an horizontal layout or a +vertical layout if you used a prefix arg, when no more windows can be +displayed in frame, next files are opened in background without being +displayed. When using \\\\[helm-ff-run-switch-other-window] the current +buffer is kept and files are displayed next to it with same behavior as above. +When using two prefix args, files are opened in background without beeing displayed. + +*** Expand archives as directories in a avfs directory + +If you have mounted your filesystem with mountavfs, +you can expand archives in the \"~/.avfs\" directory with \\\\[helm-execute-persistent-action]. + +*** Tramp archive support (emacs-27+ only) + +If your emacs have library tramp-archive.el, you can browse the +content of archives with emacs and BTW helm-find-files. However this beeing +experimental and not very fast, helm doesn't provide an automatic +expansion and detection of archives, you will have to add the final / +manually and may have to force update (\\\\[helm-refresh]) +or remove and add again the final / until tramp finish decompressing archive. + +*** Touch files + +In the completion buffer, you can choose the default which is the current-time, it is +the first candidate or the timestamp of one of the selected files. +If you need to use something else, use \\\\[next-history-element] and edit +the date in minibuffer. +It is also a way to quickly create a new file without opening a buffer, saving it +and killing it. +To touch more than one new file, separate you filenames with a comma (\",\"). +If one wants to create (touch) a new file with comma inside the name use a prefix arg, +this will prevent splitting the name and create multiple files. + +*** Delete files + +You can delete files without quitting helm with +`\\\\[helm-ff-persistent-delete]' or delete files and quit helm with `\\[helm-ff-run-delete-file]'. + +In the second method you can choose to +make this command asynchronous by customizing +\`helm-ff-delete-files-function'. + +_WARNING_: When deleting files asynchronously you will NOT be +WARNED if directories are not empty, that's mean non empty directories will +be deleted in background without asking. + +A good compromise is to trash your files +when using asynchronous method (see [[Trashing files][Trashing files]]). + +When choosing synchronous delete, you can allow recursive +deletion of directories with `helm-ff-allow-recursive-deletes'. +Note that when trashing (synchronous) you are not asked for recursive deletion. + +Note that `helm-ff-allow-recursive-deletes' have no effect when +deleting asynchronously. + +First method (persistent delete) is always synchronous. + +Note that when a prefix arg is given, trashing behavior is inversed. +See [[Trashing files][Trashing files]]. + +**** Trashing files + +If you want to trash your files instead of deleting them you can +set `delete-by-moving-to-trash' to non nil, like this your files +will be moved to trash instead of beeing deleted. + +You can reverse at any time the behavior of `delete-by-moving-to-trash' by using +a prefix arg with any of the delete files command. + +On GNULinux distribution, when navigating to a Trash directory you +can restore any file in ..Trash/files directory with the 'Restore +from trash' action you will find in action menu (needs the +trash-cli package installed). +You can as well delete files from Trash directories with the 'delete files from trash' +action. + +Tip: Navigate to your Trash/files directories with `helm-find-files' and set a bookmark +there with \\\\[helm-ff-bookmark-set] for fast access to Trash. + +_WARNING:_ + +If you have an ENV var XDG_DATA_HOME in your .profile or .bash_profile +and this var is set to something like $HOME/.local/share (like preconized) +`move-file-to-trash' may try to create $HOME/.local/share/Trash (literally) +and its subdirs in the directory where you are actually trying to trash files. +because `move-file-to-trash' is interpreting XDG_DATA_HOME literally instead +of evaling its value (with `substitute-in-file-name'). + +***** Trashing remote files with tramp + +Trashing remote files (or local files with sudo method) is disabled by default +because tramp is requiring the 'trash' command to be installed, if you want to +trash your remote files, customize `helm-trash-remote-files'. +The package on most GNU/Linux based distributions is trash-cli, it is available [[https://github.com/andreafrancia/trash-cli][here]]. + +NOTE: +When deleting your files with sudo method, your trashed files will not be listed +with trash-list until you log in as root. + +** Commands +\\ +\\[helm-ff-run-locate]\t\tRun `locate' (`\\[universal-argument]' to specify locate database, `M-n' to insert basename of candidate). +\\[helm-ff-run-browse-project]\t\tBrowse project (`\\[universal-argument]' to recurse, `\\[universal-argument] \\[universal-argument]' to recurse and refresh database). +\\[helm-ff-run-find-sh-command]\t\tRun `find' shell command from this directory. +\\[helm-ff-run-grep]\t\tRun Grep (`\\[universal-argument]' to recurse). +\\[helm-ff-run-pdfgrep]\t\tRun Pdfgrep on marked files. +\\[helm-ff-run-zgrep]\t\tRun zgrep (`\\[universal-argument]' to recurse). +\\[helm-ff-run-grep-ag]\t\tRun AG grep on current directory. +\\[helm-ff-run-git-grep]\t\tRun git-grep on current directory. +\\[helm-ff-run-gid]\t\tRun gid (id-utils). +\\[helm-ff-run-etags]\t\tRun Etags (`\\[universal-argument]' to use thing-at-point, `\\[universal-argument] \\[universal-argument]' to reload cache). +\\[helm-ff-run-rename-file]\t\tRename Files (`\\[universal-argument]' to follow). +\\[helm-ff-run-query-replace-fnames-on-marked]\t\tQuery replace on marked files. +\\[helm-ff-run-copy-file]\t\tCopy Files (`\\[universal-argument]' to follow). +\\[helm-ff-run-byte-compile-file]\t\tByte Compile Files (`\\[universal-argument]' to load). +\\[helm-ff-run-load-file]\t\tLoad Files. +\\[helm-ff-run-symlink-file]\t\tSymlink Files. +\\[helm-ff-run-hardlink-file]\t\tHardlink files. +\\[helm-ff-run-relsymlink-file]\t\tRelative symlink Files. +\\[helm-ff-run-delete-file]\t\tDelete Files. +\\[helm-ff-run-touch-files]\t\tTouch files. +\\[helm-ff-run-kill-buffer-persistent]\t\tKill buffer candidate without leaving Helm. +\\[helm-ff-persistent-delete]\t\tDelete file without leaving Helm. +\\[helm-ff-run-switch-to-eshell]\t\tSwitch to Eshell. +\\[helm-ff-run-eshell-command-on-file]\t\tEshell command on file (`\\[universal-argument]' to apply on marked files, otherwise treat them sequentially). +\\[helm-ff-run-ediff-file]\t\tEdiff file. +\\[helm-ff-run-ediff-merge-file]\t\tEdiff merge file. +\\[helm-ff-run-complete-fn-at-point]\t\tComplete file name at point. +\\[helm-ff-run-switch-other-window]\t\tSwitch to other window. +\\[helm-ff-run-switch-other-frame]\t\tSwitch to other frame. +\\[helm-ff-run-open-file-externally]\t\tOpen file with external program (`\\[universal-argument]' to choose). +\\[helm-ff-run-preview-file-externally]\t\tPreview file with external program. +\\[helm-ff-run-open-file-with-default-tool]\t\tOpen file externally with default tool. +\\[helm-ff-rotate-left-persistent]\t\tRotate image left. +\\[helm-ff-rotate-right-persistent]\t\tRotate image right. +\\[helm-find-files-up-one-level]\t\tGo to parent directory. +\\[helm-find-files-history]\t\tSwitch to the visited-directory history. +\\[helm-ff-file-name-history]\t\tSwitch to file name history. +\\[helm-ff-properties-persistent]\t\tShow file properties in a tooltip. +\\[helm-mark-all]\t\tMark all visible candidates. +\\[helm-ff-run-toggle-auto-update]\t\tToggle auto-expansion of directories. +\\[helm-unmark-all]\t\tUnmark all candidates, visible and invisible ones. +\\[helm-ff-run-gnus-attach-files]\t\tGnus' attach files to message buffer. +\\[helm-ff-run-print-file]\t\tPrint file, (`\\[universal-argument]' to refresh printer list). +\\[helm-enlarge-window]\t\tEnlarge Helm window. +\\[helm-narrow-window]\t\tNarrow Helm window. +\\[helm-ff-run-toggle-basename]\t\tToggle basename/fullpath. +\\[helm-ff-run-find-file-as-root]\t\tFind file as root. +\\[helm-ff-run-find-alternate-file]\t\tFind alternate file. +\\[helm-ff-run-insert-org-link]\t\tInsert org link. +\\[helm-ff-bookmark-set]\t\tSet bookmark to current directory. +\\[helm-find-files-toggle-to-bookmark]\t\tJump to bookmark list.") + +;;; Help for `helm-read-file-name' +;; +;; +(defun helm-read-file-name-help-message () + (let ((name (if helm-alive-p + (assoc-default 'name (helm-get-current-source)) + "generic"))) + (format + "* Helm `%s' read file name completion + +This is `%s' read file name completion that have been \"helmized\" +because you have enabled [[Helm mode][helm-mode]]'. +Don't confuse this with `helm-find-files' which is a native helm command, +see [[Helm functions vs helmized emacs functions]]. + +** Tips + +*** Navigation + +**** Enter `~/' at end of pattern to quickly reach home directory + +**** Enter `/' at end of pattern to quickly reach the file system root + +**** Enter `./' at end of pattern to quickly reach `default-directory' + +\(As per its value at the beginning of the session.) + +If you already are in the `default-directory' this will move the cursor to the top. + +**** Enter `../' at end of pattern will reach upper directory, moving cursor on top + +This is different from using `\\[helm-find-files-up-one-level]' in that it moves +the cursor to the top instead of remaining on the previous subdir name. + +**** You can complete with partial basename + +It starts from the third character of the pattern. + +For instance \"fob\" or \"fbr\" will complete \"foobar\" but \"fb\" needs a +third character in order to complete it. + +*** Persistent actions + +By default `helm-read-file-name' uses the persistent actions of `helm-find-files'. + +**** Use `\\[universal-argument] \\\\[helm-execute-persistent-action]' to display an image + +**** `\\\\[helm-execute-persistent-action]' on a filename will expand to this filename in Helm-buffer + +Second hit displays the buffer filename. +Third hit kills the buffer filename. +Note: `\\[universal-argument] \\\\[helm-execute-persistent-action]' displays the buffer directly. + +**** Browse images directories with `helm-follow-mode' and navigate up/down + +*** Delete characters backward + +When you want to delete characters backward, e.g. to create a new file or directory, +auto-update may come in the way when it keeps updating to an existent directory. +In that case, type `C-' and then `'. +This should not be needed when copying/renaming files because autoupdate is disabled +by default in that case. + +Note: On a terminal, the default binding `C-' may not work. +In this case use `C-c '. + +*** Create new directories and files + +**** You can create a new directory and a new file at the same time + +Simply write the path in prompt and press `RET', e.g. +\"~/new/newnew/newnewnew/my_newfile.txt\". + +**** To create a new directory, append a \"/\" at to the new name and press `RET' + +**** To create a new file, enter a filename not ending with \"/\" + +File and directory creation works only with some commands (e.g. `find-file') +and it will not work with others where it is not intended to return a file or +a directory \(e.g `list-directory'). + +*** Exiting minibuffer with empty string + +You can exit minibuffer with empty string with \\\\[helm-cr-empty-string]. +It is useful when some commands are prompting continuously until you enter an empty prompt. + +** Commands +\\ +\\[helm-find-files-up-one-level]\t\tGo to parent directory. +\\[helm-ff-run-toggle-auto-update]\t\tToggle auto-expansion of directories. +\\[helm-ff-run-toggle-basename]\t\tToggle basename. +\\[helm-ff-file-name-history]\t\tFile name history. +C/\\[helm-cr-empty-string]\t\tReturn empty string unless `must-match' is non-nil. +\\[helm-next-source]\t\tGo to next source. +\\[helm-previous-source]\t\tGo to previous source." + name name))) + +;;; Generic file help - Used by locate. +;; +;; +(defvar helm-generic-file-help-message + "* Helm Generic files + +** Tips + +*** Locate + +You can append to the search pattern any of the locate command line options, +e.g. -b, -e, -n , etc. See the locate(1) man page for more details. + +Some other sources (at the moment \"recentf\" and \"file in current directory\") +support the -b flag for compatibility with locate when they are used with it. + +When you enable fuzzy matching on locate with `helm-locate-fuzzy-match', the +search will be performed on basename only for efficiency (so don't add \"-b\" at +prompt). As soon as you separate the patterns with spaces, fuzzy matching will +be disabled and search will be done on the full filename. Note that in +multi-match, fuzzy is completely disabled, which means that each pattern is a +match regexp (i.e. \"helm\" will match \"helm\" but \"hlm\" will \*not* match +\"helm\"). + +*** Browse project + +When the current directory is not under version control, don't forget to refresh +the cache when files have been added/removed in the directory. + +*** Find command + +Recursively search files using the \"find\" shell command. + +Candidates are all filenames that match all given globbing patterns. This +respects the options `helm-case-fold-search' and +`helm-findutils-search-full-path'. + +You can pass arbitrary \"find\" options directly after a \"*\" separator. +For example, this would find all files matching \"book\" that are larger +than 1 megabyte: + + book * -size +1M + +** Commands +\\ +\\[helm-ff-run-toggle-basename]\t\tToggle basename. +\\[helm-ff-run-grep]\t\tRun grep (`\\[universal-argument]' to recurse). +\\[helm-ff-run-zgrep]\t\tRun zgrep. +\\[helm-ff-run-gid]\t\tRun GID (id-utils). +\\[helm-ff-run-pdfgrep]\t\tRun PDFgrep on marked files. +\\[helm-ff-run-copy-file]\t\tCopy file(s) +\\[helm-ff-run-rename-file]\t\tRename file(s). +\\[helm-ff-run-symlink-file]\t\tSymlink file(s). +\\[helm-ff-run-hardlink-file]\t\tHardlink file(s). +\\[helm-ff-run-delete-file]\t\tDelete file(s). +\\[helm-ff-run-byte-compile-file]\t\tByte compile Elisp file(s) (`\\[universal-argument]' to load). +\\[helm-ff-run-load-file]\t\tLoad Elisp file(s). +\\[helm-ff-run-ediff-file]\t\tEdiff file. +\\[helm-ff-run-ediff-merge-file]\t\tEdiff-merge file. +\\[helm-ff-run-switch-other-window]\t\tSwitch to other window. +\\[helm-ff-properties-persistent]\t\tShow file properties. +\\[helm-ff-run-etags]\t\tRun etags (`\\[universal-argument]' to use tap, `\\[universal-argument] \\[universal-argument]' to reload the database). +\\[helm-yank-text-at-point]\t\tYank text at point. +\\[helm-ff-run-open-file-externally]\t\tOpen file with external program (`\\[universal-argument]' to choose). +\\[helm-ff-run-open-file-with-default-tool]\t\tOpen file externally with default tool. +\\[helm-ff-run-insert-org-link]\t\tInsert org link.") + +;;; Grep help +;; +;; +(defvar helm-grep-help-message + "* Helm Grep + +** Tips + +*** Use a prefix argument to grep recursively + +With Helm supporting git-grep and AG however, you are better off using one of +them for recursive searches. + +*** You can use wild cards when selecting files (e.g. \"*.el\") + +*** You can grep in many different directories by marking files or using wild cards + +*** You can save the result in a `helm-grep-mode' buffer + +See [[Commands][commands]] below. + +Once in that buffer you can use \"emacs-wgrep\" (external package not bundled with Helm) +to edit your changes. + +*** Helm-grep supports multi-matching + +\(Starting from version 1.9.4.) + +Simply add a space between each pattern as for most Helm commands. + +*** See full path of selected candidate + +Add (helm-popup-tip-mode 1) in your init file or enable it interactively with +M-x helm-popup-tip-mode. + +*** Open file in other window + +The command \\\\[helm-grep-run-other-window-action] allow you to open file +in other window horizontally or vertically if a prefix arg is supplied. + +*** Performance over TRAMP + +Grepping works but it is badly supported as TRAMP doesn't support multiple +processes running in a short delay (less than 5s) among other things. + +Helm uses a special hook to suspend the process automatically while you are +typing. Even if Helm handles this automatically by delaying each process by 5s, +you are adviced to this manually by hitting `\\\\[helm-toggle-suspend-update]' (suspend process) before +typing, and hit again `\\\\[helm-toggle-suspend-update]' when the regexp is ready to send to the remote +process. For simple regexps, there should be no need for this. + +Another solution is to not use TRAMP at all and mount your remote file system via +SSHFS. + +* Helm GID + +** Tips + +Helm-GID reads the database created with the `mkid' command from id-utils. +The name of the database file can be customized with `helm-gid-db-file-name', it +is usually \"ID\". + +Helm-GID use the symbol at point as default-input. This command is also +accessible from `helm-find-files' which allow you to navigate to another +directory to consult its database. + +Note: Helm-GID supports multi-matches but only the last pattern entered will be +highlighted since there is no ~--color~-like option in GID itself. + +* Helm AG + +** Tips + +Helm-AG is different from grep or ack-grep in that it works on a directory and +not on a list of files. + +You can ignore files and directories with a \".agignore\" file, local to a +directory or global when placed in the home directory. \(See the AG man page for +more details.) That file follows the same syntax as `helm-grep-ignored-files' +and `helm-grep-ignored-directories'. + +As always you can access Helm AG from `helm-find-files'. + +Starting with version 0.30, AG accepts one or more TYPE arguments on its command +line. Helm provides completion on these TYPE arguments when available with your +AG version. Use a prefix argument when starting a Helm-AG session to enable this +completion. + +Note: You can mark several types to match in the AG query. The first AG +versions providing this feature allowed only one type, so in this case only the +last mark will be used. + +* Helm git-grep + +Helm-git-grep searches the current directory, i.e the default directory or the +directory in Helm-find-files. If this current directory is a subdirectory of a +project and you want to also match parent directories (i.e the whole project), +use a prefix argument. + +** Commands +\\ +\\[helm-goto-next-file]\t\tNext File. +\\[helm-goto-precedent-file]\t\tPrevious File. +\\[helm-yank-text-at-point]\t\tYank text at point in minibuffer. +\\[helm-grep-run-other-window-action]\t\tJump to other window. +\\[helm-grep-run-other-frame-action]\t\tJump to other frame. +\\[helm-grep-run-default-action]\t\tRun default action (same as `RET'). +\\[helm-grep-run-save-buffer]\t\tSave to a `helm-grep-mode' enabled buffer.") + +;;; PDF grep help +;; +;; +(defvar helm-pdfgrep-help-message + "* Helm PDFgrep Map + +** Commands +\\ +\\[helm-goto-next-file]\t\tNext file. +\\[helm-goto-precedent-file]\t\tPrevious file. +\\[helm-yank-text-at-point]\t\tYank text at point in minibuffer.") + +;;; Etags help +;; +;; +(defvar helm-etags-help-message + "* Helm Etags Map + +** Commands +\\ +\\[helm-goto-next-file]\t\tNext file. +\\[helm-goto-precedent-file]\t\tPrevious file. +\\[helm-yank-text-at-point]\t\tYank text at point in minibuffer.") + +;;; UCS help +;; +;; +(defvar helm-ucs-help-message + "* Helm UCS + +** Tips + +Use commands below to insert unicode characters in current buffer without +leaving Helm. + +** Commands +\\ +\\[helm-ucs-persistent-insert]\t\tInsert character. +\\[helm-ucs-persistent-forward]\t\tForward character. +\\[helm-ucs-persistent-backward]\t\tBackward character. +\\[helm-ucs-persistent-delete]\t\tDelete character backward. +\\[helm-ucs-persistent-insert-space]\t\tInsert space.") + +;;; Bookmark help +;; +;; +(defvar helm-bookmark-help-message + "* Helm bookmark name + +** Commands +\\ +\\[helm-bookmark-run-jump-other-window]\t\tJump other window. +\\[helm-bookmark-run-delete]\t\tDelete bookmark. +\\[helm-bookmark-run-edit]\t\tEdit bookmark. +\\[helm-bookmark-toggle-filename]\t\tToggle bookmark location visibility.") + +;;; Eshell command on file help +;; +;; +(defvar helm-esh-help-message + "* Helm Eshell on file + +** Tips + +*** Pass extra arguments after filename + +Normally the command or alias will be called with file as argument. For instance + + candidate_file + +But you can also pass an argument or more after \"candidate_file\" like this: + + %s [extra_args] + +\"candidate_file\" will be added at \"%s\" and the command will look at this: + + candidate_file [extra_args] + +*** Specify marked files as arguments + +Example: + + file1 file2... + +Call `helm-find-files-eshell-command-on-file' with one prefix argument. Otherwise +you can pass one prefix argument from the command selection buffer. + +Note: This does not work on remote files. + +With two prefix-args the output is printed to the `current-buffer'. + +With no prefix argument or a prefix argument value of '(16) (`\\[universal-argument] \\[universal-argument]') +the command is called once for each file like this: + + file1 + file2 + ... + +** Commands +\\") + +;;; Ido virtual buffer help +;; +;; +(defvar helm-buffers-ido-virtual-help-message + "* Helm Ido virtual buffers + +** Commands +\\ +\\[helm-ff-run-switch-other-window]\t\tSwitch to other window. +\\[helm-ff-run-switch-other-frame]\t\tSwitch to other frame. +\\[helm-ff-run-grep]\t\tGrep file. +\\[helm-ff-run-zgrep]\t\tZgrep file. +\\[helm-ff-run-delete-file]\t\tDelete file. +\\[helm-ff-run-open-file-externally]\t\tOpen file externally.") + +;;; Moccur help +;; +;; +(defvar helm-moccur-help-message + "* Helm Moccur + +** Tips + +*** Matching + +Multiple regexp matching is allowed, simply enter a space to separate the regexps. + +Matching empty lines is supported with the regexp \"^$\", you then get the +results displayed as the buffer-name and the line number only. You can +save and edit these results, i.e. add text to the empty line. + +*** Automatically match symbol at point + +Helm can automatically match the symbol at point while keeping the minibuffer +empty, ready to be written to. This behaviour is disabled by default. To +enable this you need to add `helm-source-occur' and `helm-source-moccur' to +`helm-sources-using-default-as-input'. + +*** Jump to the corresponding line in the searched buffer + +You can do this with `\\\\[helm-execute-persistent-action]' (persistent-action), to do it repeatedly +you can use `\\\\[helm-follow-action-forward]' and `\\\\[helm-follow-action-backward]' or enable `helm-follow-mode' with `\\\\[helm-follow-mode]'. + +*** Switch to buffer in other window + +The command \\\\[helm-moccur-run-goto-line-ow] allow you to switch to buffer +in other window horizontally or vertically if a prefix arg is supplied. + +*** Save the results + +Similarly to Helm-grep, you can save the results with `\\\\[helm-moccur-run-save-buffer]'. +Once in the saved buffer, you can edit it, see [[Edit a saved buffer][below]]. + +Of course if you don't save the results, you can resume the Helm session with +`helm-resume'. + +*** Refresh the resumed session + +When the buffer(s) where you ran helm-(m)occur get(s) modified, the Helm buffer +will flash red as a warning. You can refresh the buffer by running `\\\\[helm-refresh]'. +This can be done automatically by customizing `helm-moccur-auto-update-on-resume'. + +*** Refresh a saved buffer + +Type `g' to update the buffer. + +*** Edit a saved buffer + +First, install wgrep (https://github.com/mhayashi1120/Emacs-wgrep) and then: + +1) `C-c C-p' (`wgrep-change-to-wgrep-mode') to edit the buffer(s). +2) `C-x C-s' to save your changes. + +Tip: Use the excellent iedit (https://github.com/victorhge/iedit) to modify all +occurences at once in the buffer. + +*** Search in region + +When searching in current-buffer with `helm-occur', if a region +is found helm will search in this region only. If you marked +this region with `mark-defun' the symbol that was at point before +marking defun will be used when `helm-source-occur' is member of +`helm-sources-using-default-as-input'. + +** Commands +\\ +\\[helm-goto-next-file]\t\tNext buffer. +\\[helm-goto-precedent-file]\t\tPrevious buffer. +\\[helm-yank-text-at-point]\t\tYank text at point in minibuffer. +\\[helm-moccur-run-goto-line-ow]\t\tGo to line in other window. +\\[helm-moccur-run-goto-line-of]\t\tGo to line in new frame.") + +;;; Helm Top +;; +;; +(defvar helm-top-help-message + "* Helm Top + +** Commands +\\ +\\[helm-top-run-sort-by-com]\t\tSort by commands. +\\[helm-top-run-sort-by-cpu]\t\tSort by CPU usage. +\\[helm-top-run-sort-by-user]\t\tSort alphabetically by user. +\\[helm-top-run-sort-by-mem]\t\tSort by memory.") + +;;; Helm Elisp package +;; +;; +(defvar helm-el-package-help-message + "* Helm Elisp package + +** Tips + +*** Compile all your packages asynchronously + +If you use async (if you have installed Helm from MELPA you do), only \"helm\", +\"helm-core\", and \"magit\" are compiled asynchronously. If you want all your +packages compiled asynchronously, add this to your init file: + + (setq async-bytecomp-allowed-packages '(all)) + +*** Upgrade Elisp packages + +On initialization (when Emacs is fetching packages on remote), if Helm finds +packages to upgrade, it will start in the upgradable packages view showing the packages +available for upgrade. + +On subsequent runs, you will have to refresh the list with `C-c \\[universal-argument]'. If Helm +finds upgrades you can switch to upgrade view (see below) to see what packages +are available for upgrade or simply hit `C-c U' to upgrade them all. + +To see upgradable packages hit `M-U'. + +Then you can install all upgradable packages with the \"upgrade all\" action +\(`C-c \\[universal-argument]'), or upgrade only specific packages by marking them and running the +\"upgrade\" action (visible only when there are upgradable packages). Of course +you can upgrade a single package by just running the \"upgrade\" action without +marking it (`C-c u' or `RET') . + +\*Warning:* You are strongly advised to \*restart* Emacs after \*upgrading* packages. + +*** Meaning of flags prefixing packages + +\(Emacs ≥25) + +- The flag \"S\" that prefixes package names means that the packages belong to `package-selected-packages'. + +- The flag \"U\" that prefix package names mean that this package is no more needed. + +** Commands +\\ +\\[helm-el-package-show-all]\t\tShow all packages. +\\[helm-el-package-show-installed]\t\tShow installed packages only. +\\[helm-el-package-show-uninstalled]\t\tShow non-installed packages only. +\\[helm-el-package-show-upgrade]\t\tShow upgradable packages only. +\\[helm-el-package-show-built-in]\t\tShow built-in packages only. +\\[helm-el-run-package-install]\t\tInstall package(s). +\\[helm-el-run-package-reinstall]\t\tReinstall package(s). +\\[helm-el-run-package-uninstall]\t\tUninstall package(s). +\\[helm-el-run-package-upgrade]\t\tUpgrade package(s). +\\[helm-el-run-package-upgrade-all]\t\tUpgrade all packages. +\\[helm-el-run-visit-homepage]\t\tVisit package homepage.") + +;;; Helm M-x +;; +;; +(defvar helm-M-x-help-message + "* Helm M-x + +** Tips + +*** You can get help on any command with persistent action (\\[helm-execute-persistent-action]) + +*** Prefix arguments + +You must pass prefix arguments \*after* starting `helm-M-x'. A mode-line +counter will display the number of given prefix arguments. + +If you pass prefix arguments before running `helm-M-x', it will be displayed in the prompt. +The first `\\[universal-argument]' after `helm-M-x' clears those prefix arguments.") + +;;; Helm imenu +;; +;; +(defvar helm-imenu-help-message + "* Helm Imenu + +** Commands +\\ +\\[helm-imenu-next-section]\t\tGo to next section. +\\[helm-imenu-previous-section]\t\tGo to previous section.") + +;;; Helm colors +;; +;; +(defvar helm-colors-help-message + "* Helm colors + +** Commands +\\ +\\[helm-color-run-insert-name]\t\tInsert the entry name. +\\[helm-color-run-kill-name]\t\tKill the entry name. +\\[helm-color-run-insert-rgb]\t\tInsert entry in RGB format. +\\[helm-color-run-kill-rgb]\t\tKill entry in RGB format.") + +;;; Helm Semantic +;; +;; +(defvar helm-semantic-help-message + "* Helm Semantic + +** Commands +\\") + +;;; Helm kmacro +;; +;; +(defvar helm-kmacro-help-message + "* Helm kmacro + +** Tips + +- Start recording a kmacro with `f3'. +- End the kmacro recording with `f4'. +- Run `helm-execute-kmacro' to list all your kmacros. + +Use persistent action to run your kmacro as many time as needed. +You can browse the kmacros with `helm-next-line' and `helm-previous-line'. + +Note: You can't record keys running Helm commands except `helm-M-x', under the +condition that you don't choose a command using Helm completion. + +** Commands +\\") + +;;; Kill ring +;; +;; +(defvar helm-kill-ring-help-message + "* Helm kill ring + +** Tips + +Every Helm session lets you save a candidate to the kill-ring / clipboard / +primary-selection with `\\\\[helm-kill-selection-and-quit]'. + +To save space, Helm-kill-ring truncates the candidates longer than +`helm-kill-ring-max-offset'. +`\\\\[helm-kill-ring-kill-selection]' then saves the whole +text and not the truncated value. The view of truncated candidates can be +toggled; see the command list below. + +As opposed to `yank', numeric prefix arguments are ignored with +`helm-show-kill-ring': there is no need for them since selection happens within +Helm. Moreover Helm has [[Shortcuts for executing Default Action on the nth +candidate][Shortcuts for executing Default Action on the nth candidate]]. + +It is recommended to globally bind `M-y' to `helm-show-kill-ring'. Once in the +Helm-kill-ring session you can navigate to next/previous line with `M-y' and +`M-u' for convenience. Of course `\\[helm-next-line]' and `\\[helm-previous-line]' are still available. + +It is possible to delete candidates from the kill ring. + +You can concatenate marked candidates and yank them in the current +buffer, thus creating a new entry in the kill ring. Candidates are +concatenated with `helm-kill-ring-separator' as default but you can +change interactively the separator while yanking by using two prefix +args. When you have something else than \"\\n\" as default value for +`helm-kill-ring-separator' and you want to use \"\\n\" from prompt, use +`C-q C-j' to enter a newline in prompt. + +To not push a new entry in the kill ring, use `\\\\[helm-copy-to-buffer]' instead of RET +\(note that you can't change separator with this). + +When inserting candidates with the default action (`RET'), `point' is placed at +the end of the candidate and `mark' at the beginning. You can revert this behavior +by using a prefix argument, i.e. `C-u RET', like the regular `yank' command does. + +** Commands +\\ +\\[helm-next-line]\t\tNext line. +\\[helm-previous-line]\t\tPrevious line. +\\[helm-kill-ring-delete]\t\tDelete entry. +\\[helm-kill-ring-toggle-truncated]\t\tToggle truncated view of candidate. +\\[helm-kill-ring-kill-selection]\t\tKill non-truncated of selection.") + +;;; Org headings +;; +;; +(defvar helm-org-headings-help-message + "* Helm Org headings + +** Tips + +*** Refiling + +You can refile one or more headings at a time. + +To refile one heading, move the point to the entry you want to refile and run +\\[helm-org-in-buffer-headings]. Then select the heading you want to refile to +and press \\\\[helm-org-run-refile-heading-to] or select the refile action from the actions menu. + +To refile multiple headings, run \\[helm-org-in-buffer-headings] and mark the +headings you want to refile. Then select the heading you want to refile to +\(without marking it) and press \\\\[helm-org-run-refile-heading-to] or select the refile action from the +actions menu. + +*** Tags completion + +Tags completion use `completing-read-multiple', perhaps have a +look at its docstring. + +**** Single tag + +From an org heading hit C-c C-c which provide a +\"Tags\" prompt, then hit TAB and RET if you want to enter an +existing tag or write a new tag in prompt. At this point you end +up with an entry in your prompt, if you enter RET, the entry is +added as tag in your org header. + +**** Multiple tags + +If you want to add more tag to your org header, add a separator[1] after +your tag and write a new tag or hit TAB to find another existing +tag, and so on until you have all the tags you want +e.g \"foo,bar,baz\" then press RET to finally add the tags to your +org header. +Note: [1] A separator can be a comma, a colon i.e. [,:] or a space. + +** Commands +\\ +\\[helm-org-run-open-heading-in-indirect-buffer]\t\tOpen heading in indirect buffer. +\\[helm-org-run-refile-heading-to]\t\tRefile current or marked headings to selection. +\\[helm-org-run-insert-link-to-heading-at-marker]\t\tInsert link at point to selection." + ) + +;;; Completing-read +;; +(defun helm-comp-read-help-message () + (let ((com (assoc-default 'name (helm-get-current-source)))) + (format + "* Helm completing-read completion for `%s' + +Command `%s' is using a `completing-read' for completion on your input, +this completion have been \"helmized\" because you have enabled [[Helm mode][helm-mode]]'. + +** Tips + +*** Disabling or use something else than helm for completion of some commands + +You can disable helm completion or use something else for specific commands of your choice, +for this customize variable `helm-completing-read-handlers-alist'. + +*** Exiting minibuffer with empty string + +You can exit minibuffer with empty string with \\\\[helm-cr-empty-string]. +It is useful when some commands are prompting continuously until you enter an empty prompt. + +** Commands +\\ +\\[helm-cr-empty-string]\t\tExit minibuffer with empty string." + com com))) + + +;;; Mode line strings +;; +;; +;;;###autoload +(defvar helm-comp-read-mode-line "\ +\\\ +C/\\[helm-cr-empty-string]:Empty \ +\\\ +\\[helm-help]:Help \ +\\[helm-select-action]:Act \ +\\[helm-maybe-exit-minibuffer]/\ +f1/f2/f-n:NthAct \ +\\[helm-toggle-suspend-update]:Tog.suspend") + +;;;###autoload +(defvar helm-read-file-name-mode-line-string "\ +\\\ +\\[helm-help]:Help \ +C/\\[helm-cr-empty-string]:Empty \ +\\\ +\\[helm-select-action]:Act \ +\\[helm-maybe-exit-minibuffer]/\ +f1/f2/f-n:NthAct \ +\\[helm-toggle-suspend-update]:Tog.suspend" + "String displayed in mode-line in `helm-source-find-files'.") + +;;;###autoload +(defvar helm-top-mode-line "\ +\\\ +\\[helm-help]:Help \ +\\\ +\\[helm-select-action]:Act \ +\\[helm-maybe-exit-minibuffer]/\ +f1/f2/f-n:NthAct \ +\\[helm-toggle-suspend-update]:Tog.suspend") + + +(provide 'helm-help) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-help.el ends here diff --git a/elpa/helm-20181113.923/helm-id-utils.el b/elpa/helm-20181113.923/helm-id-utils.el new file mode 100644 index 00000000..b01aea54 --- /dev/null +++ b/elpa/helm-20181113.923/helm-id-utils.el @@ -0,0 +1,131 @@ +;;; helm-id-utils.el --- Helm interface for id-utils. -*- lexical-binding: t -*- + +;; Copyright (C) 2015 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'helm-grep) +(require 'helm-help) + +(defgroup helm-id-utils nil + "ID-Utils related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-gid-program "gid" + "Name of gid command (usually `gid'). +For Mac OS X users, if you install GNU coreutils, the name `gid' +might be occupied by `id' from GNU coreutils, and you should set +it to correct name (or absolute path), for example, if using +MacPorts to install id-utils, it should be `gid32'." + :group 'helm-id-utils + :type 'file) + +(defcustom helm-gid-db-file-name "ID" + "Name of a database file created by `mkid' command from `ID-utils'." + :group 'helm-id-utils + :type 'string) + +(defun helm-gid-candidates-process () + (let* ((patterns (helm-mm-split-pattern helm-pattern)) + (default-com (format "%s -r %s" helm-gid-program + (shell-quote-argument (car patterns)))) + (cmd (helm-aif (cdr patterns) + (concat default-com + (cl-loop for p in it + concat (format " | grep --color=always %s" + (shell-quote-argument p)))) + default-com)) + (proc (start-process-shell-command + "gid" helm-buffer cmd))) + (set (make-local-variable 'helm-grep-last-cmd-line) cmd) + (prog1 proc + (set-process-sentinel + proc (lambda (_process event) + (when (string= event "finished\n") + (helm-maybe-show-help-echo) + (with-helm-window + (setq mode-line-format + '(" " mode-line-buffer-identification " " + (:eval (format "L%s" (helm-candidate-number-at-point))) " " + (:eval (propertize + (format "[Helm Gid process finished - (%s results)]" + (max (1- (count-lines + (point-min) (point-max))) + 0)) + 'face 'helm-locate-finish)))) + (force-mode-line-update)) + (helm-log "Error: Gid %s" + (replace-regexp-in-string "\n" "" event)))))))) + +(defun helm-gid-filtered-candidate-transformer (candidates _source) + ;; "gid -r" may add dups in some rare cases. + (cl-loop for c in (helm-fast-remove-dups candidates :test 'equal) + collect (helm-grep--filter-candidate-1 c))) + +(defclass helm-gid-source (helm-source-async) + ((header-name + :initform + (lambda (name) + (concat name " [" (helm-attr 'db-dir) "]"))) + (db-dir :initarg :db-dir + :initform nil + :custom string + :documentation " Location of ID file.") + (candidates-process :initform #'helm-gid-candidates-process) + (filtered-candidate-transformer + :initform #'helm-gid-filtered-candidate-transformer) + (candidate-number-limit :initform 99999) + (action :initform (helm-make-actions + "Find File" 'helm-grep-action + "Find file other frame" 'helm-grep-other-frame + "Save results in grep buffer" 'helm-grep-save-results + "Find file other window" 'helm-grep-other-window)) + (persistent-action :initform 'helm-grep-persistent-action) + (history :initform 'helm-grep-history) + (nohighlight :initform t) + (help-message :initform 'helm-grep-help-message) + (requires-pattern :initform 2))) + +;;;###autoload +(defun helm-gid () + "Preconfigured helm for `gid' command line of `ID-Utils'. +Need A database created with the command `mkid' +above `default-directory'. +Need id-utils as dependency which provide `mkid', `gid' etc... +See ." + (interactive) + (let* ((db (locate-dominating-file + default-directory + helm-gid-db-file-name)) + (helm-grep-default-directory-fn + (lambda () default-directory)) + (helm--maybe-use-default-as-input t)) + (cl-assert db nil "No DataBase found, create one with `mkid'") + (helm :sources (helm-make-source "Gid" 'helm-gid-source + :db-dir db) + :buffer "*helm gid*" + :keymap helm-grep-map + :truncate-lines helm-grep-truncate-lines))) + +(provide 'helm-id-utils) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-id-utils ends here diff --git a/elpa/helm-20181113.923/helm-imenu.el b/elpa/helm-20181113.923/helm-imenu.el new file mode 100644 index 00000000..6ebac9e3 --- /dev/null +++ b/elpa/helm-20181113.923/helm-imenu.el @@ -0,0 +1,363 @@ +;;; helm-imenu.el --- Helm interface for Imenu -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-lib) +(require 'imenu) +(require 'helm-utils) +(require 'helm-help) + + +(defgroup helm-imenu nil + "Imenu related libraries and applications for helm." + :group 'helm) + +(defcustom helm-imenu-delimiter " / " + "Delimit types of candidates and his value in `helm-buffer'." + :group 'helm-imenu + :type 'string) + +(defcustom helm-imenu-execute-action-at-once-if-one + #'helm-imenu--execute-action-at-once-p + "Goto the candidate when only one is remaining." + :group 'helm-imenu + :type 'function) + +(defcustom helm-imenu-lynx-style-map t + "Use Arrow keys to jump to occurences." + :group 'helm-imenu + :type 'boolean) + +(defcustom helm-imenu-all-buffer-assoc nil + "Major mode association alist for `helm-imenu-in-all-buffers'. +Allow `helm-imenu-in-all-buffers' searching in these associated buffers +even if they are not derived from each other. +The alist is bidirectional, i.e no need to add '((foo . bar) (bar . foo)) +only '((foo . bar)) is needed." + :type '(alist :key-type symbol :value-type symbol) + :group 'helm-imenu) + +(defcustom helm-imenu-in-all-buffers-separate-sources t + "Display imenu index of each buffer in its own source when non-nil. + +When nil all candidates are displayed in a single source. + +NOTE: Each source will have as name \"Imenu \". +`helm-source-imenu-all' will not be set, however it will continue +to be used as a flag for using default as input, if you do not want +this behavior, remove it from `helm-sources-using-default-as-input' +even if not using a single source to display imenu in all buffers." + :type 'boolean + :group 'helm-imenu) + +(defcustom helm-imenu-type-faces + '(("^Variables$" . font-lock-variable-name-face) + ("^\\(Function\\|Functions\\|Defuns\\)$" . font-lock-function-name-face) + ("^\\(Types\\|Provides\\|Requires\\|Classes\\|Class\\|Includes\\|Imports\\|Misc\\|Code\\)$" . font-lock-type-face)) + "Faces for showing type in helm-imenu. +This is a list of cons cells. The cdr of each cell is a face to be used, +and it can also just be like \\='(:foreground \"yellow\"). +Each car is a regexp match pattern of the imenu type string." + :group 'helm-faces + :type '(repeat + (cons + (regexp :tag "Imenu type regexp pattern") + (sexp :tag "Face")))) + +(defcustom helm-imenu-extra-modes nil + "Extra modes where helm-imenu-in-all-buffers should look into." + :group 'helm-imenu + :type '(repeat symbol)) + +;;; keymap +(defvar helm-imenu-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-") 'helm-imenu-next-section) + (define-key map (kbd "M-") 'helm-imenu-previous-section) + (when helm-imenu-lynx-style-map + (define-key map (kbd "") 'helm-maybe-exit-minibuffer) + (define-key map (kbd "") 'helm-execute-persistent-action) + (define-key map (kbd "M-") 'helm-previous-source) + (define-key map (kbd "M-") 'helm-next-source)) + (delq nil map))) + +(defun helm-imenu-next-or-previous-section (n) + (with-helm-buffer + (let* ((fn (lambda () + (car (split-string (helm-get-selection nil t) + helm-imenu-delimiter)))) + (curtype (funcall fn)) + (move-fn (if (> n 0) #'helm-next-line #'helm-previous-line)) + (stop-fn (if (> n 0) + #'helm-end-of-source-p + #'helm-beginning-of-source-p))) + (catch 'break + (while (not (funcall stop-fn)) + (funcall move-fn) + (unless (string= curtype (funcall fn)) + (throw 'break nil))))))) + +(defun helm-imenu-next-section () + (interactive) + (helm-imenu-next-or-previous-section 1)) + +(defun helm-imenu-previous-section () + (interactive) + (helm-imenu-next-or-previous-section -1)) + + +;;; Internals +(defvar helm-cached-imenu-alist nil) +(make-variable-buffer-local 'helm-cached-imenu-alist) + +(defvar helm-cached-imenu-candidates nil) +(make-variable-buffer-local 'helm-cached-imenu-candidates) + +(defvar helm-cached-imenu-tick nil) +(make-variable-buffer-local 'helm-cached-imenu-tick) + +(defvar helm-imenu--in-all-buffers-cache nil) + +(defvar helm-source-imenu nil "See (info \"(emacs)Imenu\")") +(defvar helm-source-imenu-all nil) + +(defclass helm-imenu-source (helm-source-sync) + ((candidates :initform 'helm-imenu-candidates) + (candidate-transformer :initform 'helm-imenu-transformer) + (persistent-action :initform 'helm-imenu-persistent-action) + (persistent-help :initform "Show this entry") + (nomark :initform t) + (keymap :initform helm-imenu-map) + (help-message :initform 'helm-imenu-help-message) + (action :initform 'helm-imenu-action) + (group :initform 'helm-imenu))) + +(defcustom helm-imenu-fuzzy-match nil + "Enable fuzzy matching in `helm-source-imenu'." + :group 'helm-imenu + :type 'boolean + :set (lambda (var val) + (set var val) + (setq helm-source-imenu + (helm-make-source "Imenu" 'helm-imenu-source + :fuzzy-match helm-imenu-fuzzy-match)))) + +(defun helm-imenu--maybe-switch-to-buffer (candidate) + (let ((cand (cdr candidate))) + (helm-aif (and (markerp cand) (marker-buffer cand)) + (switch-to-buffer it)))) + +(defun helm-imenu--execute-action-at-once-p () + (let ((cur (helm-get-selection)) + (mb (with-helm-current-buffer + (save-excursion + (goto-char (point-at-bol)) + (point-marker))))) + (if (equal (cdr cur) mb) + (prog1 nil + (helm-set-pattern "") + (helm-force-update)) + t))) + +(defun helm-imenu-action (candidate) + "Default action for `helm-source-imenu'." + (helm-log-run-hook 'helm-goto-line-before-hook) + (helm-imenu--maybe-switch-to-buffer candidate) + (imenu candidate) + ;; If semantic is supported in this buffer + ;; imenu used `semantic-imenu-goto-function' + ;; and position have been highlighted, + ;; no need to highlight again. + (unless (eq imenu-default-goto-function + 'semantic-imenu-goto-function) + (helm-highlight-current-line))) + +(defun helm-imenu-persistent-action (candidate) + "Default persistent action for `helm-source-imenu'." + (helm-imenu--maybe-switch-to-buffer candidate) + (imenu candidate) + (helm-highlight-current-line)) + +(defun helm-imenu-candidates (&optional buffer) + (with-current-buffer (or buffer helm-current-buffer) + (let ((tick (buffer-modified-tick))) + (if (eq helm-cached-imenu-tick tick) + helm-cached-imenu-candidates + (setq imenu--index-alist nil) + (prog1 (setq helm-cached-imenu-candidates + (let ((index (imenu--make-index-alist t))) + (helm-imenu--candidates-1 + (delete (assoc "*Rescan*" index) index)))) + (setq helm-cached-imenu-tick tick)))))) + +(defun helm-imenu-candidates-in-all-buffers (&optional build-sources) + (let* ((lst (buffer-list)) + (progress-reporter (make-progress-reporter + "Imenu indexing buffers..." 1 (length lst)))) + (prog1 + (cl-loop with cur-buf = (if build-sources + (current-buffer) helm-current-buffer) + for b in lst + for count from 1 + when (with-current-buffer b + (and (or (member major-mode helm-imenu-extra-modes) + (derived-mode-p 'prog-mode)) + (helm-same-major-mode-p + cur-buf helm-imenu-all-buffer-assoc))) + if build-sources + collect (helm-make-source + (format "Imenu in %s" (buffer-name b)) + 'helm-imenu-source + :candidates (with-current-buffer b + (helm-imenu-candidates b)) + :fuzzy-match helm-imenu-fuzzy-match) + else + append (with-current-buffer b + (helm-imenu-candidates b)) + do (progress-reporter-update progress-reporter count)) + (progress-reporter-done progress-reporter)))) + +(defun helm-imenu--candidates-1 (alist) + (cl-loop for elm in alist + nconc (cond + ((imenu--subalist-p elm) + (helm-imenu--candidates-1 + (cl-loop for (e . v) in (cdr elm) collect + (cons (propertize + e 'helm-imenu-type (car elm)) + ;; If value is an integer, convert it + ;; to a marker, otherwise it is a cons cell + ;; and it will be converted on next recursions. + ;; (Issue #1060) [1]. + (if (integerp v) (copy-marker v) v))))) + ((listp (cdr elm)) + (and elm (list elm))) + (t + ;; bug in imenu, should not be needed. + (and (cdr elm) + ;; Semantic uses overlays whereas imenu uses + ;; markers (issue #1706). + (setcdr elm (pcase (cdr elm) ; Same as [1]. + ((and ov (pred overlayp)) + (copy-overlay ov)) + ((and mk (or (pred markerp) + (pred integerp))) + (copy-marker mk)))) + (list elm)))))) + +(defun helm-imenu--get-prop (item) + ;; property value of ITEM can have itself + ;; a property value which have itself a property value + ;; ...and so on; Return a list of all these + ;; properties values starting at ITEM. + (let* ((prop (get-text-property 0 'helm-imenu-type item)) + (lst (list prop item))) + (when prop + (while prop + (setq prop (get-text-property 0 'helm-imenu-type prop)) + (and prop (push prop lst))) + lst))) + +(defun helm-imenu-transformer (candidates) + (cl-loop for (k . v) in candidates + ;; (k . v) == (symbol-name . marker) + for bufname = (buffer-name + (pcase v + ((pred overlayp) (overlay-buffer v)) + ((or (pred markerp) (pred integerp)) + (marker-buffer v)))) + for types = (or (helm-imenu--get-prop k) + (list (if (with-current-buffer bufname + (derived-mode-p 'prog-mode)) + "Function" + "Top level") + k)) + for disp1 = (mapconcat + (lambda (x) + (propertize + x 'face + (cl-loop for (p . f) in helm-imenu-type-faces + when (string-match p x) return f + finally return 'default))) + types helm-imenu-delimiter) + for disp = (propertize disp1 'help-echo bufname) + collect + (cons disp (cons k v)))) + +;;;###autoload +(defun helm-imenu () + "Preconfigured `helm' for `imenu'." + (interactive) + (unless helm-source-imenu + (setq helm-source-imenu + (helm-make-source "Imenu" 'helm-imenu-source + :fuzzy-match helm-imenu-fuzzy-match))) + (let ((imenu-auto-rescan t) + (str (thing-at-point 'symbol)) + (helm-execute-action-at-once-if-one + helm-imenu-execute-action-at-once-if-one)) + (helm :sources 'helm-source-imenu + :default (list (concat "\\_<" (and str (regexp-quote str)) "\\_>") str) + :preselect str + :buffer "*helm imenu*"))) + +;;;###autoload +(defun helm-imenu-in-all-buffers () + "Preconfigured helm for fetching imenu entries in all buffers with similar mode as current. +A mode is similar as current if it is the same, it is derived i.e `derived-mode-p' +or it have an association in `helm-imenu-all-buffer-assoc'." + (interactive) + (unless helm-imenu-in-all-buffers-separate-sources + (unless helm-source-imenu-all + (setq helm-source-imenu-all + (helm-make-source "Imenu in all buffers" 'helm-imenu-source + :init (lambda () + ;; Use a cache to avoid repeatedly sending + ;; progress-reporter message when updating + ;; (Issue #1704). + (setq helm-imenu--in-all-buffers-cache + (helm-imenu-candidates-in-all-buffers))) + :candidates 'helm-imenu--in-all-buffers-cache + :fuzzy-match helm-imenu-fuzzy-match)))) + (let ((imenu-auto-rescan t) + (str (thing-at-point 'symbol)) + (helm-execute-action-at-once-if-one + helm-imenu-execute-action-at-once-if-one) + (helm--maybe-use-default-as-input + (not (null (memq 'helm-source-imenu-all + helm-sources-using-default-as-input)))) + (sources (if helm-imenu-in-all-buffers-separate-sources + (helm-imenu-candidates-in-all-buffers 'build-sources) + '(helm-source-imenu-all)))) + (helm :sources sources + :default (list (concat "\\_<" (and str (regexp-quote str)) "\\_>") str) + :preselect (unless helm--maybe-use-default-as-input str) + :buffer "*helm imenu all*"))) + +(provide 'helm-imenu) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-imenu.el ends here diff --git a/elpa/helm-20181113.923/helm-info.el b/elpa/helm-20181113.923/helm-info.el new file mode 100644 index 00000000..b5216c41 --- /dev/null +++ b/elpa/helm-20181113.923/helm-info.el @@ -0,0 +1,267 @@ +;;; helm-info.el --- Browse info index with helm -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-lib) +(require 'helm-utils) +(require 'info) + +(declare-function Info-index-nodes "info" (&optional file)) +(declare-function Info-goto-node "info" (&optional fork)) +(declare-function Info-find-node "info.el" (filename nodename &optional no-going-back)) +(defvar Info-history) +(defvar Info-directory-list) + +;;; Customize + +(defgroup helm-info nil + "Info-related applications and libraries for Helm." + :group 'helm) + +(defcustom helm-info-default-sources + '(helm-source-info-elisp + helm-source-info-cl + helm-source-info-eieio + helm-source-info-pages) + "Default sources to use for looking up symbols at point in Info +files with `helm-info-at-point'." + :group 'helm-info + :type '(repeat (choice symbol))) + +;;; Build info-index sources with `helm-info-source' class. + +(cl-defun helm-info-init (&optional (file (helm-attr 'info-file))) + ;; Allow reinit candidate buffer when using edebug. + (helm-aif (and debug-on-error + (helm-candidate-buffer)) + (kill-buffer it)) + (unless (helm-candidate-buffer) + (save-selected-window + (info file " *helm info temp buffer*") + (let ((tobuf (helm-candidate-buffer 'global)) + Info-history + start end line) + (cl-dolist (node (Info-index-nodes)) + (Info-goto-node node) + (goto-char (point-min)) + (while (search-forward "\n* " nil t) + (unless (search-forward "Menu:\n" (1+ (point-at-eol)) t) + (setq start (point-at-bol) + ;; Fix issue #1503 by getting the invisible + ;; info displayed on next line in long strings. + ;; e.g "* Foo.\n (line 12)" instead of + ;; "* Foo.(line 12)" + end (or (save-excursion + (goto-char (point-at-bol)) + (re-search-forward "(line +[0-9]+)" nil t)) + (point-at-eol)) + ;; Long string have a new line inserted before the + ;; invisible spec, remove it. + line (replace-regexp-in-string + "\n" "" (buffer-substring start end))) + (with-current-buffer tobuf + (insert line) + (insert "\n"))))) + (bury-buffer))))) + +(defun helm-info-goto (node-line) + (Info-goto-node (car node-line)) + (helm-goto-line (cdr node-line))) + +(defun helm-info-display-to-real (line) + (and (string-match + ;; This regexp is stolen from Info-apropos-matches + "\\* +\\([^\n]*.+[^\n]*\\):[ \t]+\\([^\n]*\\)\\.\\(?:[ \t\n]*(line +\\([0-9]+\\))\\)?" line) + (cons (format "(%s)%s" (helm-attr 'info-file) (match-string 2 line)) + (string-to-number (or (match-string 3 line) "1"))))) + +(defclass helm-info-source (helm-source-in-buffer) + ((info-file :initarg :info-file + :initform nil + :custom 'string) + (init :initform #'helm-info-init) + (display-to-real :initform #'helm-info-display-to-real) + (get-line :initform #'buffer-substring) + (action :initform '(("Goto node" . helm-info-goto))))) + +(defmacro helm-build-info-source (fname &rest args) + `(helm-make-source (concat "Info Index: " ,fname) 'helm-info-source + :info-file ,fname ,@args)) + +(defun helm-build-info-index-command (name doc source buffer) + "Define a helm command NAME with documentation DOC. +Arg SOURCE will be an existing helm source named +`helm-source-info-' and BUFFER a string buffer name." + (defalias (intern (concat "helm-info-" name)) + (lambda () + (interactive) + (helm :sources source + :buffer buffer + :candidate-number-limit 1000)) + doc)) + +(defun helm-define-info-index-sources (var-value &optional commands) + "Define helm sources named helm-source-info-. +Sources are generated for all entries of `helm-default-info-index-list'. +If COMMANDS arg is non-nil, also build commands named `helm-info-'. +Where NAME is an element of `helm-default-info-index-list'." + (cl-loop for str in var-value + for sym = (intern (concat "helm-source-info-" str)) + do (set sym (helm-build-info-source str)) + when commands + do (helm-build-info-index-command + str (format "Predefined helm for %s info." str) + sym (format "*helm info %s*" str)))) + +(defun helm-info-index-set (var value) + (set var value) + (helm-define-info-index-sources value t)) + +;;; Search Info files + +;; `helm-info' is the main entry point here. It prompts the user for an Info +;; file, then a term in the file's index to jump to. + +(defvar helm-info-searched (make-ring 32) + "Ring of previously searched Info files.") + +(defun helm-get-info-files () + "Return list of Info files to use for `helm-info'. + +Elements of the list are strings of Info file names without +extensions (e.g. \"emacs\" for file \"emacs.info.gz\"). Info +files are found by searching directories in +`Info-directory-list'." + (let ((files (cl-loop for d in (or Info-directory-list + Info-default-directory-list) + when (file-directory-p d) + append (directory-files d nil "\\.info")))) + (helm-fast-remove-dups + (cl-loop for f in files collect + (helm-file-name-sans-extension f)) + :test 'equal))) + +(defcustom helm-default-info-index-list + (helm-get-info-files) + "Info files to search in with `helm-info'." + :group 'helm-info + :type '(repeat (choice string)) + :set 'helm-info-index-set) + +(defun helm-info-search-index (candidate) + "Search the index of CANDIDATE's Info file using the function +helm-info-." + (let ((helm-info-function + (intern-soft (concat "helm-info-" candidate)))) + (when (fboundp helm-info-function) + (funcall helm-info-function) + (ring-insert helm-info-searched candidate)))) + +(defun helm-def-source--info-files () + "Return a `helm' source for Info files." + (helm-build-sync-source "Helm Info" + :candidates + (lambda () (copy-sequence helm-default-info-index-list)) + :candidate-number-limit 999 + :candidate-transformer + (lambda (candidates) + (sort candidates #'string-lessp)) + :nomark t + :action '(("Search index" . helm-info-search-index)))) + +;;;###autoload +(defun helm-info (&optional refresh) + "Preconfigured `helm' for searching Info files' indices. + +With a prefix argument \\[universal-argument], set REFRESH to non-nil. + +Optional parameter REFRESH, when non-nil, reevaluates +`helm-default-info-index-list'. If the variable has been +customized, set it to its saved value. If not, set it to its +standard value. See `custom-reevaluate-setting' for more. + +REFRESH is useful when new Info files are installed. If +`helm-default-info-index-list' has not been customized, the new +Info files are made available." + (interactive "P") + (let ((default (unless (ring-empty-p helm-info-searched) + (ring-ref helm-info-searched 0)))) + (when refresh + (custom-reevaluate-setting 'helm-default-info-index-list)) + (helm :sources (helm-def-source--info-files) + :buffer "*helm Info*" + :preselect (and default + (concat "\\_<" (regexp-quote default) "\\_>"))))) + +;;;; Info at point + +;; `helm-info-at-point' is the main entry point here. It searches for the +;; symbol at point through the Info sources defined in +;; `helm-info-default-sources' and jumps to it. + +(defvar helm-info--pages-cache nil + "Cache for all Info pages on the system.") + +(defvar helm-source-info-pages + (helm-build-sync-source "Info Pages" + :init #'helm-info-pages-init + :candidates (lambda () helm-info--pages-cache) + :action '(("Show with Info" . + (lambda (node-str) + (info (replace-regexp-in-string + "^[^:]+: " "" node-str))))) + :requires-pattern 2) + "Helm source for Info pages.") + +(defun helm-info-pages-init () + "Collect candidates for initial Info node Top." + (or helm-info--pages-cache + (let ((info-topic-regexp "\\* +\\([^:]+: ([^)]+)[^.]*\\)\\.")) + (save-selected-window + (info "dir" " *helm info temp buffer*") + (Info-find-node "dir" "top") + (goto-char (point-min)) + (while (re-search-forward info-topic-regexp nil t) + (push (match-string-no-properties 1) + helm-info--pages-cache)) + (kill-buffer))))) + +;;;###autoload +(defun helm-info-at-point () + "Preconfigured `helm' for searching info at point." + (interactive) + (cl-loop for src in helm-info-default-sources + for name = (if (symbolp src) + (assoc 'name (symbol-value src)) + (assoc 'name src)) + unless name + do (warn "Couldn't build source `%S' without its info file" src)) + (helm :sources helm-info-default-sources + :buffer "*helm info*")) + +(provide 'helm-info) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-info.el ends here diff --git a/elpa/helm-20181113.923/helm-locate.el b/elpa/helm-20181113.923/helm-locate.el new file mode 100644 index 00000000..a7ce7417 --- /dev/null +++ b/elpa/helm-20181113.923/helm-locate.el @@ -0,0 +1,464 @@ +;;; helm-locate.el --- helm interface for locate. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;; NOTE for WINDOZE users: +;; You have to install Everything with his command line interface here: +;; http://www.voidtools.com/download.php + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-types) +(require 'helm-help) + + +(defgroup helm-locate nil + "Locate related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-locate-db-file-regexp "m?locate\.db$" + "Default regexp to match locate database. +If nil Search in all files." + :type 'string + :group 'helm-locate) + +(defcustom helm-ff-locate-db-filename "locate.db" + "The basename of the locatedb file you use locally in your directories. +When this is set and `helm' find such a file in the directory from +where you launch locate, it will use this file and will not prompt you +for a db file. +Note that this happen only when locate is launched with a prefix arg." + :group 'helm-locate + :type 'string) + +(defcustom helm-locate-command nil + "A list of arguments for locate program. + +Helm will calculate a default value for your system on startup unless +`helm-locate-command' is non-nil, here the default values it will use +according to your system: + +Gnu/linux: \"locate %s -e -A --regex %s\" +berkeley-unix: \"locate %s %s\" +windows-nt: \"es %s %s\" +Others: \"locate %s %s\" + +This string will be passed to format so it should end with `%s'. +The first format spec is used for the \"-i\" value of locate/es, +So don't set it directly but use `helm-locate-case-fold-search' +for this. + +The last option must be the one preceding pattern i.e \"-r\" or \"--regex\". + +You will be able to pass other options such as \"-b\" or \"l\" +during helm invocation after entering pattern only when multi matching, +not when fuzzy matching. + +Note that the \"-b\" option is added automatically by helm when +var `helm-locate-fuzzy-match' is non-nil and switching back from +multimatch to fuzzy matching (this is done automatically when a space +is detected in pattern)." + :type 'string + :group 'helm-locate) + +(defcustom helm-locate-create-db-command + "updatedb -l 0 -o '%s' -U '%s'" + "Command used to create a locale locate db file." + :type 'string + :group 'helm-locate) + +(defcustom helm-locate-case-fold-search helm-case-fold-search + "It have the same meaning as `helm-case-fold-search'. +The -i option of locate will be used depending of value of +`helm-pattern' when this is set to 'smart. +When nil \"-i\" will not be used at all. +and when non--nil it will always be used. +NOTE: the -i option of the \"es\" command used on windows does +the opposite of \"locate\" command." + :group 'helm-locate + :type 'symbol) + +(defcustom helm-locate-fuzzy-match nil + "Enable fuzzy matching in `helm-locate'. +Note that when this is enabled searching is done on basename." + :group 'helm-locate + :type 'boolean) + +(defcustom helm-locate-fuzzy-sort-fn + #'helm-locate-default-fuzzy-sort-fn + "Default fuzzy matching sort function for locate." + :group 'helm-locate + :type 'boolean) + +(defcustom helm-locate-project-list nil + "A list of directories, your projects. +When set, allow browsing recursively files in all +directories of this list with `helm-projects-find-files'." + :group 'helm-locate + :type '(repeat string)) + +(defcustom helm-locate-recursive-dirs-command "locate -i -e -A --regex '^%s' '%s.*$'" + "Command used for recursive directories completion in `helm-find-files'. + +For Windows and `es' use something like \"es -r ^%s.*%s.*$\" + +The two format specs are mandatory. + +If for some reasons you can't use locate because your filesystem +doesn't have a data base, you can use find command from findutils but +be aware that it will be much slower, see `helm-find-files' embebded +help for more infos." + :type 'string + :group 'helm-files) + + +(defvar helm-locate-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-generic-files-map) + (define-key map (kbd "DEL") 'helm-delete-backward-no-update) + map)) + +(defface helm-locate-finish + '((t (:foreground "Green"))) + "Face used in mode line when locate process is finish." + :group 'helm-locate) + + +(defun helm-ff-find-locatedb (&optional from-ff) + "Try to find if a local locatedb file is available. +The search is done in `helm-ff-default-directory' or +fall back to `default-directory' if FROM-FF is nil." + (helm-aif (and helm-ff-locate-db-filename + (locate-dominating-file + (or (and from-ff + helm-ff-default-directory) + default-directory) + helm-ff-locate-db-filename)) + (expand-file-name helm-ff-locate-db-filename it))) + +(defun helm-locate-create-db-default-function (db-name directory) + "Default function used to create a locale locate db file. +Argument DB-NAME name of the db file. +Argument DIRECTORY root of file system subtree to scan." + (format helm-locate-create-db-command + db-name (expand-file-name directory))) + +(defvar helm-locate-create-db-function + #'helm-locate-create-db-default-function + "Function used to create a locale locate db file. +It should receive the same arguments as +`helm-locate-create-db-default-function'.") + +(defun helm-locate-1 (&optional localdb init from-ff default) + "Generic function to run Locate. +Prefix arg LOCALDB when (4) search and use a local locate db file when it +exists or create it, when (16) force update of existing db file +even if exists. +It have no effect when locate command is 'es'. +INIT is a string to use as initial input in prompt. +See `helm-locate-with-db' and `helm-locate'." + (require 'helm-mode) + (helm-locate-set-command) + (let ((pfn (lambda (candidate) + (if (file-directory-p candidate) + (message "Error: The locate Db should be a file") + (if (= (shell-command + (funcall helm-locate-create-db-function + candidate + helm-ff-default-directory)) + 0) + (message "New locatedb file `%s' created" candidate) + (error "Failed to create locatedb file `%s'" candidate))))) + (locdb (and localdb + (not (string-match "^es" helm-locate-command)) + (or (and (equal '(4) localdb) + (helm-ff-find-locatedb from-ff)) + (helm-read-file-name + "Create Locate Db file: " + :initial-input (expand-file-name "locate.db" + (or helm-ff-default-directory + default-directory)) + :preselect helm-locate-db-file-regexp + :test (lambda (x) + (if helm-locate-db-file-regexp + ;; Select only locate db files and directories + ;; to allow navigation. + (or (string-match + helm-locate-db-file-regexp x) + (file-directory-p x)) + x))))))) + (when (and locdb (or (equal localdb '(16)) + (not (file-exists-p locdb)))) + (funcall pfn locdb)) + (helm-locate-with-db (and localdb locdb) init default))) + +(defun helm-locate-set-command () + "Setup `helm-locate-command' if not already defined." + (unless helm-locate-command + (setq helm-locate-command + (cl-case system-type + (gnu/linux "locate %s -e -A --regex %s") + (berkeley-unix "locate %s %s") + (windows-nt "es %s %s") + (t "locate %s %s"))))) + +(defun helm-locate-initial-setup () + (require 'helm-for-files) + (helm-locate-set-command)) + +(defvar helm-file-name-history nil) +(defun helm-locate-with-db (&optional db initial-input default) + "Run locate -d DB. +If DB is not given or nil use locate without -d option. +Argument DB can be given as a string or list of db files. +Argument INITIAL-INPUT is a string to use as initial-input. +See also `helm-locate'." + (require 'helm-files) + (when (and db (stringp db)) (setq db (list db))) + (helm-locate-set-command) + (let ((helm-locate-command + (if db + (replace-regexp-in-string + "locate" + (format (if helm-locate-fuzzy-match + "locate -b -d '%s'" "locate -d '%s'") + (mapconcat 'identity + ;; Remove eventually + ;; marked directories by error. + (cl-loop for i in db + unless (file-directory-p i) + ;; expand-file-name to resolve + ;; abbreviated fnames not + ;; expanding inside single + ;; quotes i.e. '%s'. + collect (expand-file-name i)) + ":")) + helm-locate-command) + (if (and helm-locate-fuzzy-match + (not (string-match-p "\\`locate -b" helm-locate-command))) + (replace-regexp-in-string + "\\`locate" "locate -b" helm-locate-command) + helm-locate-command)))) + (setq helm-file-name-history (mapcar 'helm-basename file-name-history)) + (helm :sources 'helm-source-locate + :buffer "*helm locate*" + :ff-transformer-show-only-basename nil + :input initial-input + :default default + :history 'helm-file-name-history))) + +(defun helm-locate-init () + "Initialize async locate process for `helm-source-locate'." + (let* ((locate-is-es (string-match "\\`es" helm-locate-command)) + (real-locate (string-match "\\`locate" helm-locate-command)) + (case-sensitive-flag (if locate-is-es "-i" "")) + (ignore-case-flag (if (or locate-is-es + (not real-locate)) "" "-i")) + (args (helm-mm-split-pattern helm-pattern)) + (cmd (format helm-locate-command + (cl-case helm-locate-case-fold-search + (smart (let ((case-fold-search nil)) + (if (string-match "[[:upper:]]" helm-pattern) + case-sensitive-flag + ignore-case-flag))) + (t (if helm-locate-case-fold-search + ignore-case-flag + case-sensitive-flag))) + (concat + ;; The pattern itself. + (shell-quote-argument (car args)) " " + ;; Possible locate args added + ;; after pattern, don't quote them. + (mapconcat 'identity (cdr args) " ")))) + (default-directory (if (file-directory-p default-directory) + default-directory "/"))) + (helm-log "Starting helm-locate process") + (helm-log "Command line used was:\n\n%s" + (concat ">>> " (propertize cmd 'face 'font-lock-comment-face) "\n\n")) + (prog1 + (start-process-shell-command + "locate-process" helm-buffer + cmd) + (set-process-sentinel + (get-buffer-process helm-buffer) + (lambda (process event) + (let* ((err (process-exit-status process)) + (noresult (= err 1))) + (cond (noresult + (with-helm-buffer + (unless (cdr helm-sources) + (insert (concat "* Exit with code 1, no result found," + " command line was:\n\n " + cmd))))) + ((string= event "finished\n") + (when (and helm-locate-fuzzy-match + (not (string-match-p "\\s-" helm-pattern))) + (helm-redisplay-buffer)) + (with-helm-window + (setq mode-line-format + '(" " mode-line-buffer-identification " " + (:eval (format "L%s" (helm-candidate-number-at-point))) " " + (:eval (propertize + (format "[Locate process finished - (%s results)]" + (max (1- (count-lines + (point-min) (point-max))) + 0)) + 'face 'helm-locate-finish)))) + (force-mode-line-update))) + (t + (helm-log "Error: Locate %s" + (replace-regexp-in-string "\n" "" event)))))))))) + +(defun helm-locate-default-fuzzy-sort-fn (candidates) + "Default sort function for files in fuzzy matching. +Sort is done on basename of CANDIDATES." + (helm-fuzzy-matching-default-sort-fn-1 candidates nil t)) + +(defclass helm-locate-override-inheritor (helm-type-file) ()) + +(defclass helm-locate-source (helm-source-async helm-locate-override-inheritor) + ((init :initform 'helm-locate-initial-setup) + (candidates-process :initform 'helm-locate-init) + (requires-pattern :initform 3) + (history :initform 'helm-file-name-history) + (persistent-action :initform 'helm-ff-kill-or-find-buffer-fname) + (candidate-number-limit :initform 9999) + (redisplay :initform (progn helm-locate-fuzzy-sort-fn)) + (group :initform 'helm-locate))) + +;; Override helm-type-file class keymap. +(defmethod helm--setup-source :after ((source helm-locate-override-inheritor)) + (setf (slot-value source 'keymap) helm-locate-map)) + +(defvar helm-source-locate + (helm-make-source "Locate" 'helm-locate-source + :pattern-transformer 'helm-locate-pattern-transformer + ;; :match-part is only used here to tell helm which part + ;; of candidate to highlight. + :match-part (lambda (candidate) + (if (or (string-match-p " -b\\'" helm-pattern) + (and helm-locate-fuzzy-match + (not (string-match "\\s-" helm-pattern)))) + (helm-basename candidate) + candidate)))) + +(defun helm-locate-pattern-transformer (pattern) + (if helm-locate-fuzzy-match + ;; When fuzzy is enabled helm add "-b" option on startup. + (cond ((string-match-p " " pattern) + (when (string-match "\\`locate -b" helm-locate-command) + (setq helm-locate-command + (replace-match "locate" t t helm-locate-command))) + pattern) + (t + (unless (string-match-p "\\`locate -b" helm-locate-command) + (setq helm-locate-command + (replace-regexp-in-string + "\\`locate" "locate -b" helm-locate-command))) + (helm--mapconcat-pattern pattern))) + pattern)) + +(defun helm-locate-find-dbs-in-projects (&optional update) + (let* ((pfn (lambda (candidate directory) + (unless (= (shell-command + (funcall helm-locate-create-db-function + candidate + directory)) + 0) + (error "Failed to create locatedb file `%s'" candidate))))) + (cl-loop for p in helm-locate-project-list + for db = (expand-file-name + helm-ff-locate-db-filename + (file-name-as-directory p)) + if (and (null update) (file-exists-p db)) + collect db + else do (funcall pfn db p) + and collect db))) + +;;; Directory completion for hff. +;; +(defclass helm-locate-subdirs-source (helm-source-in-buffer) + ((basedir :initarg :basedir + :initform nil + :custom string) + (subdir :initarg :subdir + :initform nil + :custom 'string) + (data :initform #'helm-locate-init-subdirs) + (group :initform 'helm-locate))) + +(defun helm-locate-init-subdirs () + (with-temp-buffer + (call-process-shell-command + (format helm-locate-recursive-dirs-command + (if (string-match-p "\\`es" helm-locate-recursive-dirs-command) + ;; Fix W32 paths. + (replace-regexp-in-string + "/" "\\\\\\\\" (helm-attr 'basedir)) + (helm-attr 'basedir)) + (helm-attr 'subdir)) + nil t nil) + (buffer-string))) + +;;;###autoload +(defun helm-projects-find-files (update) + "Find files with locate in `helm-locate-project-list'. +With a prefix arg refresh the database in each project." + (interactive "P") + (helm-locate-set-command) + (cl-assert (and (string-match-p "\\`locate" helm-locate-command) + (executable-find "updatedb")) + nil "Unsupported locate version") + (let ((dbs (helm-locate-find-dbs-in-projects update))) + (if dbs + (helm-locate-with-db dbs) + (user-error "No projects found, please setup `helm-locate-project-list'")))) + +;;;###autoload +(defun helm-locate (arg) + "Preconfigured `helm' for Locate. +Note: you can add locate options after entering pattern. +See 'man locate' for valid options and also `helm-locate-command'. + +You can specify a local database with prefix argument ARG. +With two prefix arg, refresh the current local db or create it +if it doesn't exists. + +To create a user specific db, use +\"updatedb -l 0 -o db_path -U directory\". +Where db_path is a filename matched by +`helm-locate-db-file-regexp'." + (interactive "P") + (helm-set-local-variable 'helm-async-outer-limit-hook + (list (lambda () + (when (and helm-locate-fuzzy-match + (not (string-match-p + "\\s-" helm-pattern))) + (helm-redisplay-buffer))))) + (setq helm-ff-default-directory default-directory) + (helm-locate-1 arg nil nil (thing-at-point 'filename))) + +(provide 'helm-locate) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-locate.el ends here diff --git a/elpa/helm-20181113.923/helm-man.el b/elpa/helm-20181113.923/helm-man.el new file mode 100644 index 00000000..ab2d3002 --- /dev/null +++ b/elpa/helm-20181113.923/helm-man.el @@ -0,0 +1,119 @@ +;;; helm-man.el --- Man and woman UI -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-help) + +(defvar woman-topic-all-completions) +(defvar woman-manpath) +(defvar woman-path) +(defvar woman-expanded-directory-path) +(declare-function woman-file-name "woman.el" (topic &optional re-cache)) +(declare-function woman-file-name-all-completions "woman.el" (topic)) +(declare-function Man-getpage-in-background "man.el" (topic)) +(declare-function woman-expand-directory-path "woman.el" (path-dirs path-regexps)) +(declare-function woman-topic-all-completions "woman.el" (path)) +(declare-function helm-generic-sort-fn "helm-utils.el" (S1 S2)) + +(defgroup helm-man nil + "Man and Woman applications for helm." + :group 'helm) + +(defcustom helm-man-or-woman-function 'Man-getpage-in-background + "Default command to display a man page." + :group 'helm-man + :type '(radio :tag "Preferred command to display a man page" + (const :tag "Man" Man-getpage-in-background) + (const :tag "Woman" woman))) + +(defcustom helm-man-format-switches (cl-case system-type + ((darwin macos) "%s") + (t "-l %s")) + "Arguments to pass to the `manual-entry' function. +Arguments are passed to `manual-entry' with `format.'" + :group 'helm-man + :type 'string) + +;; Internal +(defvar helm-man--pages nil + "All man pages on system. +Will be calculated the first time you invoke helm with this +source.") + +(defun helm-man-default-action (candidate) + "Default action for jumping to a woman or man page from helm." + (let ((wfiles (mapcar #'car (woman-file-name-all-completions candidate)))) + (condition-case nil + (let ((file (if (cdr wfiles) + (helm-comp-read "ManFile: " wfiles :must-match t) + (car wfiles)))) + (if (eq helm-man-or-woman-function 'Man-getpage-in-background) + (manual-entry (format helm-man-format-switches file)) + (condition-case nil + (woman-find-file file) + ;; If woman is unable to format correctly + ;; try Man instead. + (error (kill-buffer) + (manual-entry (format helm-man-format-switches file)))))) + ;; If even Man failed with file as argument, try again with Man + ;; but using Topic candidate instead of the file calculated by + ;; woman. + (error (kill-buffer) + (Man-getpage-in-background candidate))))) + +(defun helm-man--init () + (require 'woman) + (require 'helm-utils) + (unless helm-man--pages + (setq woman-expanded-directory-path + (woman-expand-directory-path woman-manpath woman-path)) + (setq woman-topic-all-completions + (woman-topic-all-completions woman-expanded-directory-path)) + (setq helm-man--pages (mapcar 'car woman-topic-all-completions))) + (helm-init-candidates-in-buffer 'global helm-man--pages)) + +(defvar helm-source-man-pages + (helm-build-in-buffer-source "Manual Pages" + :init #'helm-man--init + :persistent-action #'ignore + :filtered-candidate-transformer + (lambda (candidates _source) + (sort candidates #'helm-generic-sort-fn)) + :action '(("Display Man page" . helm-man-default-action)) + :group 'helm-man)) + +;;;###autoload +(defun helm-man-woman (arg) + "Preconfigured `helm' for Man and Woman pages. +With a prefix arg reinitialize the cache." + (interactive "P") + (when arg (setq helm-man--pages nil)) + (helm :sources 'helm-source-man-pages + :buffer "*helm man woman*")) + +(provide 'helm-man) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-man.el ends here diff --git a/elpa/helm-20181113.923/helm-misc.el b/elpa/helm-20181113.923/helm-misc.el new file mode 100644 index 00000000..971650bf --- /dev/null +++ b/elpa/helm-20181113.923/helm-misc.el @@ -0,0 +1,361 @@ +;;; helm-misc.el --- Various functions for helm -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'helm-types) + +(declare-function display-time-world-display "time.el") +(defvar display-time-world-list) +(declare-function LaTeX-math-mode "ext:latex.el") +(declare-function jabber-chat-with "ext:jabber.el") +(declare-function jabber-read-account "ext:jabber.el") + + +(defgroup helm-misc nil + "Various Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-time-zone-home-location "Paris" + "The time zone of your home" + :group 'helm-misc + :type 'string) + +(defcustom helm-timezone-actions + '(("Set timezone env (TZ)" . (lambda (candidate) + (setenv "TZ" candidate)))) + "Actions for helm-timezone." + :group 'helm-misc + :type '(alist :key-type string :value-type function)) + +(defface helm-time-zone-current + '((t (:foreground "green"))) + "Face used to colorize current time in `helm-world-time'." + :group 'helm-misc) + +(defface helm-time-zone-home + '((t (:foreground "red"))) + "Face used to colorize home time in `helm-world-time'." + :group 'helm-misc) + + + +;;; Latex completion +;; +;; Test +;; (setq LaTeX-math-menu '("Math" +;; ["foo" val0 t] +;; ("bar" +;; ["baz" val1 t]) +;; ("aze" +;; ["zer" val2 t]) +;; ("AMS" +;; ("rec" +;; ["fer" val3 t]) +;; ("rty" +;; ["der" val4 t])) +;; ("ABC" +;; ("xcv" +;; ["sdf" val5 t]) +;; ("dfg" +;; ["fgh" val6 t])))) +;; (helm-latex-math-candidates) +;; => +;; (("foo" . val0) +;; ("baz" . val1) +;; ("zer" . val2) +;; ("fer" . val3) +;; ("der" . val4) +;; ("sdf" . val5) +;; ("fgh" . val6)) + +(defvar LaTeX-math-menu) +(defun helm-latex-math-candidates () + (cl-labels ((helm-latex--math-collect (L) + (cond ((vectorp L) + (list (cons (aref L 0) (aref L 1)))) + ((listp L) + (cl-loop for a in L nconc + (helm-latex--math-collect a)))))) + (helm-latex--math-collect LaTeX-math-menu))) + +(defvar helm-source-latex-math + (helm-build-sync-source "Latex Math Menu" + :init (lambda () + (with-helm-current-buffer + (LaTeX-math-mode 1))) + :candidate-number-limit 9999 + :candidates 'helm-latex-math-candidates + :action (lambda (candidate) + (call-interactively candidate)))) + + +;;; Jabber Contacts (jabber.el) +(defun helm-jabber-online-contacts () + "List online Jabber contacts." + (with-no-warnings + (cl-loop for item in (jabber-concat-rosters) + when (get item 'connected) + collect + (if (get item 'name) + (cons (get item 'name) item) + (cons (symbol-name item) item))))) + +(defvar helm-source-jabber-contacts + (helm-build-sync-source "Jabber Contacts" + :init (lambda () (require 'jabber)) + :candidates (lambda () (mapcar 'car (helm-jabber-online-contacts))) + :action (lambda (x) + (jabber-chat-with + (jabber-read-account) + (symbol-name + (cdr (assoc x (helm-jabber-online-contacts)))))))) + +;;; World time +;; +(defvar zoneinfo-style-world-list) +(defvar legacy-style-world-list) + +(defun helm-time-zone-transformer (candidates _source) + (cl-loop for i in candidates + for (z . p) in display-time-world-list + collect + (cons + (cond ((string-match (format-time-string "%H:%M" (current-time)) i) + (propertize i 'face 'helm-time-zone-current)) + ((string-match helm-time-zone-home-location i) + (propertize i 'face 'helm-time-zone-home)) + (t i)) + z))) + +(defvar helm-source-time-world + (helm-build-in-buffer-source "Time World List" + :init (lambda () + (require 'time) + (unless (and display-time-world-list + (listp display-time-world-list)) + ;; adapted from `time--display-world-list' from + ;; emacs-27 for compatibility as + ;; `display-time-world-list' is set by default to t. + (setq display-time-world-list + ;; Determine if zoneinfo style timezones are + ;; supported by testing that America/New York and + ;; Europe/London return different timezones. + (let ((nyt (format-time-string "%z" nil "America/New_York")) + (gmt (format-time-string "%z" nil "Europe/London"))) + (if (string-equal nyt gmt) + legacy-style-world-list + zoneinfo-style-world-list))))) + :data (lambda () + (with-temp-buffer + (display-time-world-display display-time-world-list) + (buffer-string))) + :action 'helm-timezone-actions + :filtered-candidate-transformer 'helm-time-zone-transformer)) + +;;; Commands +;; +(defun helm-call-interactively (cmd-or-name) + "Execute CMD-OR-NAME as Emacs command. +It is added to `extended-command-history'. +`helm-current-prefix-arg' is used as the command's prefix argument." + (setq extended-command-history + (cons (helm-stringify cmd-or-name) + (delete (helm-stringify cmd-or-name) extended-command-history))) + (let ((current-prefix-arg helm-current-prefix-arg) + (cmd (helm-symbolify cmd-or-name))) + (if (stringp (symbol-function cmd)) + (execute-kbd-macro (symbol-function cmd)) + (setq this-command cmd) + (call-interactively cmd)))) + +;;; Minibuffer History +;; +;; +(defvar helm-minibuffer-history-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map [remap helm-minibuffer-history] 'undefined) + map)) + +(defcustom helm-minibuffer-history-must-match t + "Allow inserting non matching elements when nil or 'confirm." + :group 'helm-misc + :type '(choice + (const :tag "Must match" t) + (const :tag "Confirm" 'confirm) + (const :tag "Always allow" nil))) + +;;; Shell history +;; +;; +(defun helm-comint-input-ring-action (candidate) + "Default action for comint history." + (with-helm-current-buffer + (delete-region (comint-line-beginning-position) (point-max)) + (insert candidate))) + +(defvar helm-source-comint-input-ring + (helm-build-sync-source "Comint history" + :candidates (lambda () + (with-helm-current-buffer + (ring-elements comint-input-ring))) + :action 'helm-comint-input-ring-action) + "Source that provide helm completion against `comint-input-ring'.") + + +;;; Helm ratpoison UI +;; +;; +(defvar helm-source-ratpoison-commands + (helm-build-in-buffer-source "Ratpoison Commands" + :init 'helm-ratpoison-commands-init + :action (helm-make-actions + "Execute the command" 'helm-ratpoison-commands-execute) + :display-to-real 'helm-ratpoison-commands-display-to-real + :candidate-number-limit 999999)) + +(defun helm-ratpoison-commands-init () + (unless (helm-candidate-buffer) + (with-current-buffer (helm-candidate-buffer 'global) + ;; with ratpoison prefix key + (save-excursion + (call-process "ratpoison" nil (current-buffer) nil "-c" "help")) + (while (re-search-forward "^\\([^ ]+\\) \\(.+\\)$" nil t) + (replace-match " \\1: \\2")) + (goto-char (point-max)) + ;; direct binding + (save-excursion + (call-process "ratpoison" nil (current-buffer) nil "-c" "help top")) + (while (re-search-forward "^\\([^ ]+\\) \\(.+\\)$" nil t) + (replace-match "\\1: \\2"))))) + +(defun helm-ratpoison-commands-display-to-real (display) + (and (string-match ": " display) + (substring display (match-end 0)))) + +(defun helm-ratpoison-commands-execute (candidate) + (call-process "ratpoison" nil nil nil "-ic" candidate)) + +;;; Helm stumpwm UI +;; +;; +(defvar helm-source-stumpwm-commands + (helm-build-in-buffer-source "Stumpwm Commands" + :init 'helm-stumpwm-commands-init + :action (helm-make-actions + "Execute the command" 'helm-stumpwm-commands-execute) + :candidate-number-limit 999999)) + +(defun helm-stumpwm-commands-init () + (with-current-buffer (helm-candidate-buffer 'global) + (save-excursion + (call-process "stumpish" nil (current-buffer) nil "commands")) + (while (re-search-forward "[ ]*\\([^ ]+\\)[ ]*\n?" nil t) + (replace-match "\n\\1\n")) + (delete-blank-lines) + (sort-lines nil (point-min) (point-max)) + (goto-char (point-max)))) + +(defun helm-stumpwm-commands-execute (candidate) + (call-process "stumpish" nil nil nil candidate)) + +;;;###autoload +(defun helm-world-time () + "Preconfigured `helm' to show world time. +Default action change TZ environment variable locally to emacs." + (interactive) + (helm-other-buffer 'helm-source-time-world "*helm world time*")) + +;;;###autoload +(defun helm-insert-latex-math () + "Preconfigured helm for latex math symbols completion." + (interactive) + (helm-other-buffer 'helm-source-latex-math "*helm latex*")) + +;;;###autoload +(defun helm-ratpoison-commands () + "Preconfigured `helm' to execute ratpoison commands." + (interactive) + (helm-other-buffer 'helm-source-ratpoison-commands + "*helm ratpoison commands*")) + +;;;###autoload +(defun helm-stumpwm-commands() + "Preconfigured helm for stumpwm commands." + (interactive) + (helm-other-buffer 'helm-source-stumpwm-commands + "*helm stumpwm commands*")) + +;;;###autoload +(defun helm-minibuffer-history () + "Preconfigured `helm' for `minibuffer-history'." + (interactive) + (cl-assert (minibuffer-window-active-p (selected-window)) nil + "Error: Attempt to use minibuffer history outside a minibuffer") + (let* ((enable-recursive-minibuffers t) + (query-replace-p (or (eq last-command 'query-replace) + (eq last-command 'query-replace-regexp))) + (elm (helm-comp-read "pattern: " + (cl-loop for i in + (symbol-value minibuffer-history-variable) + unless (string= "" i) collect i into history + finally return + (if (consp (car history)) + (mapcar 'prin1-to-string history) + history)) + :header-name + (lambda (name) + (format "%s (%s)" name minibuffer-history-variable)) + :buffer "*helm minibuffer-history*" + :must-match helm-minibuffer-history-must-match + :multiline t + :keymap helm-minibuffer-history-map + :allow-nest t))) + ;; Fix issue #1667 with emacs-25+ `query-replace-from-to-separator'. + (when (and (boundp 'query-replace-from-to-separator) query-replace-p) + (let ((pos (string-match "\0" elm))) + (and pos + (add-text-properties + pos (1+ pos) + `(display ,query-replace-from-to-separator separator t) + elm)))) + (delete-minibuffer-contents) + (insert elm))) + +;;;###autoload +(defun helm-comint-input-ring () + "Preconfigured `helm' that provide completion of `comint' history." + (interactive) + (when (derived-mode-p 'comint-mode) + (helm :sources 'helm-source-comint-input-ring + :input (buffer-substring-no-properties (comint-line-beginning-position) + (point-at-eol)) + :buffer "*helm comint history*"))) + + +(provide 'helm-misc) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-misc.el ends here diff --git a/elpa/helm-20181113.923/helm-mode.el b/elpa/helm-20181113.923/helm-mode.el new file mode 100644 index 00000000..15ee93c0 --- /dev/null +++ b/elpa/helm-20181113.923/helm-mode.el @@ -0,0 +1,1466 @@ +;;; helm-mode.el --- Enable helm completion everywhere. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-lib) +(require 'helm-files) + +(defvar crm-separator) + + +(defgroup helm-mode nil + "Enable helm completion." + :group 'helm) + +(defcustom helm-completing-read-handlers-alist + '((describe-function . helm-completing-read-symbols) + (describe-variable . helm-completing-read-symbols) + (describe-symbol . helm-completing-read-symbols) + (debug-on-entry . helm-completing-read-symbols) + (find-function . helm-completing-read-symbols) + (disassemble . helm-completing-read-symbols) + (trace-function . helm-completing-read-symbols) + (trace-function-foreground . helm-completing-read-symbols) + (trace-function-background . helm-completing-read-symbols) + (find-tag . helm-completing-read-default-find-tag) + (org-capture . helm-org-completing-read-tags) + (org-set-tags . helm-org-completing-read-tags) + (ffap-alternate-file . nil) + (tmm-menubar . nil) + (find-file . nil) + (find-file-at-point . helm-completing-read-sync-default-handler) + (ffap . helm-completing-read-sync-default-handler) + (execute-extended-command . nil) + (dired-do-rename . helm-read-file-name-handler-1) + (dired-do-copy . helm-read-file-name-handler-1) + (dired-do-symlink . helm-read-file-name-handler-1) + (dired-do-relsymlink . helm-read-file-name-handler-1) + (dired-do-hardlink . helm-read-file-name-handler-1) + (basic-save-buffer . helm-read-file-name-handler-1) + (write-file . helm-read-file-name-handler-1) + (write-region . helm-read-file-name-handler-1)) + "Completing read functions for specific Emacs commands. + +By default `helm-mode' use `helm-completing-read-default-handler' to +provide helm completion in each `completing-read' or `read-file-name' +found, but other functions can be specified here for specific +commands. This also allow disabling helm completion for some commands +when needed. + +Each entry is a cons cell like (EMACS_COMMAND . COMPLETING-READ_HANDLER) +where key and value are symbols. + +Each key is an Emacs command that use originaly `completing-read'. + +Each value maybe a helm function that takes same arguments as +`completing-read' plus NAME and BUFFER, where NAME is the name of the new +helm source and BUFFER the name of the buffer we will use, but it can +be also a function not using helm, in this case the function should +take same args as `completing-read' and not be prefixed by \"helm-\". + +`helm' will use the name of the command calling `completing-read' as +NAME and BUFFER will be computed as well with NAME but prefixed with +\"*helm-mode-\". + +This function prefix name must start by \"helm-\" when it uses helm, +otherwise `helm' assumes the function is not a helm function and +expects same args as `completing-read', this allow you to define a +handler not using helm completion. + +Example: + + (defun foo/test () + (interactive) + (message \"%S\" (completing-read \"test: \" '(a b c d e)))) + + (defun helm-foo/test-completing-read-handler (prompt collection + predicate require-match + initial-input hist def + inherit-input-method + name buffer) + (helm-comp-read prompt collection :marked-candidates t + :name name + :buffer buffer)) + + (add-to-list 'helm-completing-read-handlers-alist + '(foo/test . helm-foo/test-completing-read-handler)) + + +We want here to make the regular `completing-read' in `foo/test' +returns a list of candidate(s) instead of a single candidate. + +Note that this function will be reused for ALL the `completing-read' +of this command, so it should handle all cases, e.g +If first `completing-read' complete against symbols and +second `completing-read' should handle only buffer, +your specialized function should handle the both. + +If the value of an entry is nil completion will fall back to +emacs vanilla behavior. +Example: + +If you want to disable helm completion for `describe-function', use: + + (describe-function . nil) + +Ido is also supported, you can use `ido-completing-read' and +`ido-read-file-name' as value of an entry or just 'ido. +Example: +Enable ido completion for `find-file': + + (find-file . ido) + +same as + + (find-file . ido-read-file-name) + +Note that you don't need to enable `ido-mode' for this to work, see +`helm-mode' documentation." + :group 'helm-mode + :type '(alist :key-type symbol :value-type symbol)) + +(defcustom helm-comp-read-case-fold-search helm-case-fold-search + "Default Local setting of `helm-case-fold-search' for `helm-comp-read'. +See `helm-case-fold-search' for more info." + :group 'helm-mode + :type 'symbol) + +(defcustom helm-mode-handle-completion-in-region t + "Whether to replace or not `completion-in-region-function'. +This enable support for `completing-read-multiple' and `completion-at-point' +when non--nil." + :group 'helm-mode + :type 'boolean) + +(defcustom helm-mode-reverse-history t + "Display history source after current source in `helm-mode' handled commands." + :group 'helm-mode + :type 'boolean) + +(defcustom helm-mode-no-completion-in-region-in-modes nil + "A list of modes that do not want helm for `completion-in-region'." + :group 'helm-mode + :type 'boolean) + +(defcustom helm-completion-in-region-fuzzy-match nil + "Whether `helm-completion-in-region' use fuzzy matching or not. +Affect among others `completion-at-point', `completing-read-multiple'." + :group 'helm-mode + :type 'boolean) + +(defcustom helm-completion-in-region-default-sort-fn + 'helm-completion-in-region-sort-fn + "The default sort function to sort candidates in completion-in-region. + +When nil no sorting is done. +The function is a `filtered-candidate-transformer' function which takes +two args CANDIDATES and SOURCE. +It will be used only when `helm-completion-in-region-fuzzy-match' is +nil otherwise fuzzy use its own sort function." + :group 'helm-mode + :type 'function) + +(defcustom helm-mode-fuzzy-match nil + "Enable fuzzy matching in `helm-mode' globally. +Note that this will slow down completion and modify sorting +which is unwanted in many places. +This affect only the functions with completing-read helmized by helm-mode. +To fuzzy match `completion-at-point' and friends see +`helm-completion-in-region-fuzzy-match'." + :group 'helm-mode + :type 'boolean) + +(defcustom helm-mode-minibuffer-setup-hook-black-list '(minibuffer-completion-help) + "Incompatible `minibuffer-setup-hook' functions go here. +A list of symbols. +Helm-mode is rejecting all lambda's, byte-code fns +and all functions belonging in this list from `minibuffer-setup-hook'." + :group 'helm-mode + :type '(repeat (choice symbol))) + +(defcustom helm-completing-read-dynamic-complete nil + "Use dynamic completion in `completing-read' when non-nil. + +The default is to not use this because it is most of the time unneeded +in `completing-read' and thus it is much more slower. +If you feel one emacs function need this you have better time to tell +`helm-mode' to use a dynamic completion for this function only by using +`helm-completing-read-handlers-alist' with an entry like this: + + (my-function . helm-completing-read-sync-default-handler) + +So you should not change the default setting of this variable unless you +know what you are doing." + :group 'helm-mode + :type 'boolean) + + +(defvar helm-comp-read-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "") 'helm-cr-empty-string) + (define-key map (kbd "M-RET") 'helm-cr-empty-string) + map) + "Keymap for `helm-comp-read'.") + +;;; helm-comp-read +;; +;; +(defun helm-cr-empty-string () + "Return empty string." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action + (lambda (_candidate) + (identity ""))))) +(put 'helm-cr-empty-string 'helm-only t) + +(defun helm-mode--keyboard-quit () + ;; Use this instead of `keyboard-quit' + ;; to avoid deactivating mark in current-buffer. + (let ((debug-on-quit nil)) + (signal 'quit nil))) + +(cl-defun helm-comp-read-get-candidates (collection &optional + test sort-fn alistp + (input helm-pattern)) + "Convert COLLECTION to list removing elements that don't match TEST. +See `helm-comp-read' about supported COLLECTION arguments. + +SORT-FN is a predicate to sort COLLECTION. + +ALISTP when non--nil will not use `all-completions' to collect +candidates because it doesn't handle alists correctly for helm. +i.e In `all-completions' the car of each pair is used as value. +In helm we want to use the cdr instead like \(display . real\), +so we return the alist as it is with no transformation by +`all-completions'. + +e.g + +\(setq A '((a . 1) (b . 2) (c . 3))) +==>((a . 1) (b . 2) (c . 3)) +\(helm-comp-read \"test: \" A :alistp nil + :exec-when-only-one t + :initial-input \"a\") +==>\"a\" Which is not what we expect. + +\(helm-comp-read \"test: \" A :alistp t + :exec-when-only-one t + :initial-input \"1\") +==>\"1\" + +See docstring of `all-completions' for more info. + +INPUT is the string you want to complete against, defaulting to +`helm-pattern' which is the value of what you enter in minibuffer. +Note that when using a function as COLLECTION this value will be +available with the input argument of the function only when using a +sync source from `helm-comp-read', i.e not using +`:candidates-in-buffer', otherwise the function is called only once +with an empty string as value for `helm-pattern' because +`helm-pattern' is not yet computed, which is what we want otherwise +data would not be fully collected at init time. + +If COLLECTION is an `obarray', a TEST should be needed. See `obarray'." + ;; Ensure COLLECTION is computed from `helm-current-buffer' + ;; because some functions used as COLLECTION work + ;; only in the context of current-buffer (Issue #1030) . + (with-helm-current-buffer + (let ((cands + (cond ((vectorp collection) + (all-completions input collection test)) + ((and (symbolp collection) (boundp collection) + ;; Issue #324 history is let-bounded and given + ;; quoted as hist argument of completing-read. + ;; See example in `rcirc-browse-url'. + (symbolp (symbol-value collection))) + nil) + ;; When collection is a symbol, most of the time + ;; it should be a symbol used as a minibuffer-history. + ;; The value of this symbol in this case return a list + ;; of string which maybe are converted later as symbol + ;; in special cases. + ;; we treat here commandp as a special case as it return t + ;; also with a string unless its last arg is provided. + ;; Also, the history collections generally collect their + ;; elements as string, so intern them to call predicate. + ((and (symbolp collection) (boundp collection) test) + (let ((predicate (lambda (elm) + (condition-case _err + (if (eq test 'commandp) + (funcall test (intern elm)) + (funcall test elm)) + (wrong-type-argument + (funcall test (intern elm))))))) + (all-completions input (symbol-value collection) predicate))) + ((and (symbolp collection) (boundp collection)) + (all-completions input (symbol-value collection))) + ;; Normally file completion should not be handled here, + ;; but special cases like `find-file-at-point' do it. + ;; Handle here specially such cases. + ((and (functionp collection) (not (string= input "")) + minibuffer-completing-file-name) + (cl-loop for f in (funcall collection input test t) + unless (member f '("./" "../")) + if (string-match helm--url-regexp input) + collect f + else + collect (concat (file-name-as-directory + (helm-basedir input)) + f))) + ((functionp collection) + (funcall collection input test t)) + ((and alistp (null test)) collection) + ;; Next test ensure circular objects are removed + ;; with `all-completions' (Issue #1530). + (t (all-completions input collection test))))) + (if sort-fn (sort cands sort-fn) cands)))) + +(defun helm-cr--pattern-in-candidates-p (candidates) + (or (assoc helm-pattern candidates) + (assq (intern helm-pattern) candidates) + (member helm-pattern candidates) + (member (downcase helm-pattern) candidates) + (member (upcase helm-pattern) candidates))) + +(defun helm-cr-default-transformer (candidates source) + "Default filter candidate function for `helm-comp-read'." + (let ((must-match (helm-attr 'must-match source)) + unknown-pattern) + (unless (or (eq must-match t) + (string= helm-pattern "") + (helm-cr--pattern-in-candidates-p candidates)) + (setq candidates (append (list + ;; Unquote helm-pattern + ;; when it is added + ;; as candidate: Why? #2015 + ;; (replace-regexp-in-string + ;; "\\s\\" "" helm-pattern) + helm-pattern) + candidates)) + ;; Notify pattern have been added to candidates. + (setq unknown-pattern t)) + (cl-loop for c in candidates + for cand = (if (stringp c) + (replace-regexp-in-string "\\s\\" "" c) + c) + for pat = (replace-regexp-in-string "\\s\\" "" helm-pattern) + if (and (or (equal c pat) (equal c helm-pattern)) + unknown-pattern) + collect + (cons (concat (propertize + " " 'display + (propertize "[?]" 'face 'helm-ff-prefix)) + c) + c) + into lst + else collect (if (and (stringp cand) + (string-match "\n" cand)) + (cons (replace-regexp-in-string "\n" "->" c) c) + c) + into lst + finally return (helm-fast-remove-dups lst :test 'equal)))) + +(defun helm-comp-read--move-to-first-real-candidate () + (helm-aif (helm-get-selection nil 'withprop) + (when (string= (get-text-property 0 'display it) "[?]") + (helm-next-line)))) + +(defun helm-cr-default (default cands) + (delq nil + (cond ((and (stringp default) (not (string= default ""))) + (cons default (delete default cands))) + ((consp default) + (append (cl-loop for d in default + ;; Don't convert + ;; nil to "nil" (i.e the string) + ;; it will be delq'ed on top. + collect (if (null d) d (helm-stringify d))) + cands)) + (t cands)))) + +;;;###autoload +(cl-defun helm-comp-read (prompt collection + &key + test + initial-input + default + preselect + (buffer "*Helm Completions*") + must-match + fuzzy + reverse-history + (requires-pattern 0) + history + input-history + (case-fold helm-comp-read-case-fold-search) + (del-input t) + (persistent-action nil) + (persistent-help "DoNothing") + (mode-line helm-comp-read-mode-line) + help-message + (keymap helm-comp-read-map) + (name "Helm Completions") + header-name + candidates-in-buffer + match-part + exec-when-only-one + quit-when-no-cand + (volatile t) + sort + fc-transformer + hist-fc-transformer + marked-candidates + nomark + (alistp t) + (candidate-number-limit helm-candidate-number-limit) + multiline + allow-nest) + "Read a string in the minibuffer, with helm completion. + +It is helm `completing-read' equivalent. + +- PROMPT is the prompt name to use. + +- COLLECTION can be a list, vector, obarray or hash-table. + It can be also a function that receives three arguments: + the values string, predicate and t. See `all-completions' for more details. + +Keys description: + +- TEST: A predicate called with one arg i.e candidate. + +- INITIAL-INPUT: Same as input arg in `helm'. + +- PRESELECT: See preselect arg of `helm'. + +- DEFAULT: This option is used only for compatibility with regular + Emacs `completing-read' (Same as DEFAULT arg of `completing-read'). + +- BUFFER: Name of helm-buffer. + +- MUST-MATCH: Candidate selected must be one of COLLECTION. + +- FUZZY: Enable fuzzy matching. + +- REVERSE-HISTORY: When non--nil display history source after current + source completion. + +- REQUIRES-PATTERN: Same as helm attribute, default is 0. + +- HISTORY: A list containing specific history, default is nil. + When it is non--nil, all elements of HISTORY are displayed in + a special source before COLLECTION. + +- INPUT-HISTORY: A symbol. the minibuffer input history will be + stored there, if nil or not provided, `minibuffer-history' + will be used instead. + +- CASE-FOLD: Same as `helm-case-fold-search'. + +- DEL-INPUT: Boolean, when non--nil (default) remove the partial + minibuffer input from HISTORY is present. + +- PERSISTENT-ACTION: A function called with one arg i.e candidate. + +- PERSISTENT-HELP: A string to document PERSISTENT-ACTION. + +- MODE-LINE: A string or list to display in mode line. + Default is `helm-comp-read-mode-line'. + +- KEYMAP: A keymap to use in this `helm-comp-read'. + (the keymap will be shared with history source) + +- NAME: The name related to this local source. + +- HEADER-NAME: A function to alter NAME, see `helm'. + +- EXEC-WHEN-ONLY-ONE: Bound `helm-execute-action-at-once-if-one' + to non--nil. (possibles values are t or nil). + +- VOLATILE: Use volatile attribute. + +- SORT: A predicate to give to `sort' e.g `string-lessp' + Use this only on small data as it is ineficient. + If you want to sort faster add a sort function to + FC-TRANSFORMER. + Note that FUZZY when enabled is already providing a sort function. + +- FC-TRANSFORMER: A `filtered-candidate-transformer' function + or a list of functions. + +- HIST-FC-TRANSFORMER: A `filtered-candidate-transformer' + function for the history source. + +- MARKED-CANDIDATES: If non--nil return candidate or marked candidates as a list. + +- NOMARK: When non--nil don't allow marking candidates. + +- ALISTP: \(default is non--nil\) See `helm-comp-read-get-candidates'. + +- CANDIDATES-IN-BUFFER: when non--nil use a source build with + `helm-source-in-buffer' which is much faster. + Argument VOLATILE have no effect when CANDIDATES-IN-BUFFER is non--nil. + +- MATCH-PART: Allow matching only one part of candidate. + See match-part documentation in `helm-source'. + +- ALLOW-NEST: Allow nesting this `helm-comp-read' in a helm session. + See `helm'. + +- MULTILINE: See multiline in `helm-source'. + +Any prefix args passed during `helm-comp-read' invocation will be recorded +in `helm-current-prefix-arg', otherwise if prefix args were given before +`helm-comp-read' invocation, the value of `current-prefix-arg' will be used. +That's mean you can pass prefix args before or after calling a command +that use `helm-comp-read' See `helm-M-x' for example." + + (when (get-buffer helm-action-buffer) + (kill-buffer helm-action-buffer)) + (let ((action-fn `(("Sole action (Identity)" + . (lambda (candidate) + (if ,marked-candidates + (helm-marked-candidates) + (identity candidate))))))) + ;; Assume completion have been already required, + ;; so always use 'confirm. + (when (eq must-match 'confirm-after-completion) + (setq must-match 'confirm)) + (let* ((minibuffer-completion-confirm must-match) + (must-match-map (when must-match + (let ((map (make-sparse-keymap))) + (define-key map (kbd "RET") + 'helm-confirm-and-exit-minibuffer) + map))) + (loc-map (if must-match-map + (make-composed-keymap + must-match-map (or keymap helm-map)) + (or keymap helm-map))) + (minibuffer-completion-predicate test) + (minibuffer-completion-table collection) + (helm-read-file-name-mode-line-string + (replace-regexp-in-string "helm-maybe-exit-minibuffer" + "helm-confirm-and-exit-minibuffer" + helm-read-file-name-mode-line-string)) + (get-candidates + (lambda () + (let ((cands (helm-comp-read-get-candidates + collection test sort alistp + ;; This should not be needed as + ;; `helm-pattern' is not yet computed when + ;; calling this from :init when + ;; candidates-in-buffer is in use. + (if candidates-in-buffer "" helm-pattern)))) + (helm-cr-default default cands)))) + (history-get-candidates + (lambda () + (let ((cands (helm-comp-read-get-candidates + history test nil alistp))) + (when cands + (delete "" (helm-cr-default default cands)))))) + (src-hist (helm-build-sync-source (format "%s History" name) + :candidates history-get-candidates + :fuzzy-match fuzzy + :multiline multiline + :match-part match-part + :filtered-candidate-transformer + (append '((lambda (candidates sources) + (cl-loop for i in candidates + ;; Input is added to history in completing-read's + ;; and may be regexp-quoted, so unquote it + ;; but check if cand is a string (it may be at this stage + ;; a symbol or nil) Issue #1553. + when (stringp i) + collect (replace-regexp-in-string "\\s\\" "" i)))) + (and hist-fc-transformer (helm-mklist hist-fc-transformer))) + :persistent-action persistent-action + :persistent-help persistent-help + :keymap loc-map + :mode-line mode-line + :help-message help-message + :action action-fn)) + (src (helm-build-sync-source name + :candidates get-candidates + :match-part match-part + :multiline multiline + :header-name header-name + :filtered-candidate-transformer + (append (helm-mklist fc-transformer) + '(helm-cr-default-transformer)) + :requires-pattern requires-pattern + :persistent-action persistent-action + :persistent-help persistent-help + :fuzzy-match fuzzy + :keymap loc-map + :mode-line mode-line + :help-message help-message + :action action-fn + :volatile volatile)) + (src-1 (helm-build-in-buffer-source name + :data get-candidates + :match-part match-part + :multiline multiline + :header-name header-name + :filtered-candidate-transformer + (append (helm-mklist fc-transformer) + '(helm-cr-default-transformer)) + :requires-pattern requires-pattern + :persistent-action persistent-action + :fuzzy-match fuzzy + :keymap loc-map + :persistent-help persistent-help + :mode-line mode-line + :help-message help-message + :action action-fn)) + (src-list (list src-hist + (cons (cons 'must-match must-match) + (if candidates-in-buffer + src-1 src)))) + (helm-execute-action-at-once-if-one exec-when-only-one) + (helm-quit-if-no-candidate quit-when-no-cand) + result) + (when nomark + (setq src-list (cl-loop for src in src-list + collect (cons '(nomark) src)))) + (when reverse-history (setq src-list (nreverse src-list))) + (add-hook 'helm-after-update-hook 'helm-comp-read--move-to-first-real-candidate) + (unwind-protect + (setq result (helm + :sources src-list + :input initial-input + :default default + :preselect preselect + :prompt prompt + :resume 'noresume + :keymap loc-map ;; Needed with empty collection. + :allow-nest allow-nest + :candidate-number-limit candidate-number-limit + :case-fold-search case-fold + :history (and (symbolp input-history) input-history) + :buffer buffer)) + (remove-hook 'helm-after-update-hook 'helm-comp-read--move-to-first-real-candidate)) + ;; Avoid adding an incomplete input to history. + (when (and result history del-input) + (cond ((and (symbolp history) ; History is a symbol. + (not (symbolp (symbol-value history)))) ; Fix Issue #324. + ;; Be sure history is not a symbol with a nil value. + (helm-aif (symbol-value history) (setcar it result))) + ((consp history) ; A list with a non--nil value. + (setcar history result)) + (t ; Possibly a symbol with a nil value. + (set history (list result))))) + (or result (helm-mode--keyboard-quit))))) + + +;; Generic completing-read +;; +;; Support also function as collection. +;; e.g M-x man is supported. +;; Support hash-table and vectors as collection. +;; NOTE: +;; Some crap emacs functions may not be supported +;; like ffap-alternate-file (bad use of completing-read) +;; and maybe others. +;; Provide a mode `helm-mode' which turn on +;; helm in all `completing-read' and `read-file-name' in Emacs. +;; +(defvar helm-completion-mode-string " Helm") + +(defvar helm-completion-mode-quit-message + "Helm completion disabled") + +(defvar helm-completion-mode-start-message + "Helm completion enabled") + +;;; Specialized handlers +;; +;; +(defun helm-completing-read-symbols + (prompt _collection test _require-match init + hist default _inherit-input-method name buffer) + "Specialized function for fast symbols completion in `helm-mode'." + (require 'helm-elisp) + (or + (helm + :sources (helm-build-in-buffer-source name + :init (lambda () + (helm-apropos-init (lambda (x) + (and (funcall test x) + (not (keywordp x)))) + (or (car-safe default) default))) + :filtered-candidate-transformer 'helm-apropos-default-sort-fn + :help-message #'helm-comp-read-help-message + :fuzzy-match helm-mode-fuzzy-match + :persistent-action + (lambda (candidate) + (helm-lisp-completion-persistent-action + candidate name)) + :persistent-help (helm-lisp-completion-persistent-help)) + :prompt prompt + :buffer buffer + :input init + :history hist + :resume 'noresume + :default (or default "")) + (helm-mode--keyboard-quit))) + + +;;; Generic completing read +;; +;; +(defun helm-completing-read-default-1 + (prompt collection test require-match + init hist default _inherit-input-method + name buffer &optional cands-in-buffer exec-when-only-one) + "Call `helm-comp-read' with same args as `completing-read'. +Extra optional arg CANDS-IN-BUFFER mean use `candidates-in-buffer' +method which is faster. +It should be used when candidate list don't need to rebuild dynamically." + (let ((history (or (car-safe hist) hist)) + (initial-input (helm-aif (pcase init + ((pred (stringp)) init) + ;; INIT is a cons cell. + (`(,l . ,_ll) l)) + (if minibuffer-completing-file-name it + (regexp-quote it))))) + (helm-comp-read + prompt collection + :test test + :history history + :reverse-history helm-mode-reverse-history + :input-history history + :must-match require-match + :alistp nil + :help-message #'helm-comp-read-help-message + :name name + :requires-pattern (if (and (stringp default) + (string= default "") + (or (eq require-match 'confirm) + (eq require-match + 'confirm-after-completion))) + 1 0) + :candidates-in-buffer cands-in-buffer + :exec-when-only-one exec-when-only-one + :fuzzy helm-mode-fuzzy-match + :buffer buffer + ;; If DEF is not provided, fallback to empty string + ;; to avoid `thing-at-point' to be appended on top of list + :default (or default "") + ;; Fail with special characters (e.g in gnus "nnimap+gmail:") + ;; if regexp-quote is not used. + ;; when init is added to history, it will be unquoted by + ;; helm-comp-read. + :initial-input initial-input))) + +(defun helm-completing-read-default-find-tag + (prompt collection test require-match + init hist default inherit-input-method + name buffer) + "Specialized `helm-mode' handler for `find-tag'." + ;; Some commands like find-tag may use `read-file-name' from inside + ;; the calculation of collection. in this case it clash with + ;; candidates-in-buffer that reuse precedent data (files) which is wrong. + ;; So (re)calculate collection outside of main helm-session. + (let* ((cands (helm-comp-read-get-candidates + collection test nil nil))) + (helm-completing-read-default-1 prompt cands test require-match + init hist default inherit-input-method + name buffer t))) + +(defun helm-completing-read-sync-default-handler + (prompt collection test require-match + init hist default inherit-input-method + name buffer) + "`helm-mode' handler using sync source as backend." + (helm-completing-read-default-1 prompt collection test require-match + init hist default inherit-input-method + name buffer)) + +(defun helm-completing-read-default-handler + (prompt collection test require-match + init hist default inherit-input-method + name buffer) + "Default `helm-mode' handler for all `completing-read'." + (helm-completing-read-default-1 prompt collection test require-match + init hist default inherit-input-method + name buffer + (null helm-completing-read-dynamic-complete))) + +(defun helm--generic-read-buffer (prompt &optional default require-match predicate) + "The `read-buffer-function' for `helm-mode'. +Affects `switch-to-buffer' and related." + (let ((collection (helm-buffer-list))) + (helm--completing-read-default + prompt collection predicate require-match nil nil default))) + +(cl-defun helm--completing-read-default + (prompt collection &optional + predicate require-match + initial-input hist def + inherit-input-method) + "An helm replacement of `completing-read'. +This function should be used only as a `completing-read-function'. + +Don't use it directly, use instead `helm-comp-read' in your programs. + +See documentation of `completing-read' and `all-completions' for details." + (let* ((current-command (or (helm-this-command) this-command)) + (str-command (helm-symbol-name current-command)) + (buf-name (format "*helm-mode-%s*" str-command)) + (entry (assq current-command + helm-completing-read-handlers-alist)) + (def-com (cdr-safe entry)) + (str-defcom (and def-com (helm-symbol-name def-com))) + (def-args (list prompt collection predicate require-match + initial-input hist def inherit-input-method)) + ;; Append the two extra args needed to set the buffer and source name + ;; in helm specialized functions. + (any-args (append def-args (list str-command buf-name))) + helm-completion-mode-start-message ; Be quiet + helm-completion-mode-quit-message + ;; Be sure this pesty *completion* buffer doesn't popup. + ;; Note: `minibuffer-with-setup-hook' may setup a lambda + ;; calling `minibuffer-completion-help' or other minibuffer + ;; functions we DONT WANT here, in these cases removing the hook + ;; (a symbol) have no effect. Issue #448. + ;; Because `minibuffer-completion-table' and + ;; `minibuffer-completion-predicate' are not bound + ;; anymore here, these functions should have no effect now, + ;; except in some rare cases like in `woman-file-name', + ;; so remove all incompatible functions + ;; from `minibuffer-setup-hook' (Issue #1205, #1240). + ;; otherwise helm have not the time to close its initial session. + (minibuffer-setup-hook + (cl-loop for h in minibuffer-setup-hook + unless (or (consp h) ; a lambda. + (byte-code-function-p h) + (memq h helm-mode-minibuffer-setup-hook-black-list)) + collect h)) + ;; Disable hack that could be used before `completing-read'. + ;; i.e (push ?\t unread-command-events). + unread-command-events + (default-handler + ;; Typically when COLLECTION is a function, we can assume + ;; the intention is completing dynamically according to + ;; input; If one want to use in-buffer handler for specific + ;; usage with a function as collection he can specify it in + ;; helm-completing-read-handlers-alist. + (if (functionp collection) + #'helm-completing-read-sync-default-handler + #'helm-completing-read-default-handler))) + (when (eq def-com 'ido) (setq def-com 'ido-completing-read)) + (unless (or (not entry) def-com) + ;; An entry in *read-handlers-alist exists but have + ;; a nil value, so we exit from here, disable `helm-mode' + ;; and run the command again with it original behavior. + ;; `helm-mode' will be restored on exit. + (cl-return-from helm--completing-read-default + (unwind-protect + (progn + (helm-mode -1) + (apply completing-read-function def-args)) + (helm-mode 1)))) + ;; If we use now `completing-read' we MUST turn off `helm-mode' + ;; to avoid infinite recursion and CRASH. It will be reenabled on exit. + (when (or (eq def-com 'completing-read) + ;; All specialized functions are prefixed by "helm" + (and (stringp str-defcom) + (not (string-match "^helm" str-defcom)))) + (helm-mode -1)) + (unwind-protect + (cond (;; An helm specialized function exists, run it. + (and def-com helm-mode) + (apply def-com any-args)) + (;; Try to handle `ido-completing-read' everywhere. + (and def-com (eq def-com 'ido-completing-read)) + (setcar (memq collection def-args) + (all-completions "" collection predicate)) + (apply def-com def-args)) + (;; User set explicitely `completing-read' or something similar + ;; in *read-handlers-alist, use this with exactly the same + ;; args as in `completing-read'. + ;; If we are here `helm-mode' is now disabled. + def-com + (apply def-com def-args)) + (;; Use by default a in-buffer handler unless + ;; COLLECTION is a function. + t + (funcall default-handler + prompt collection predicate require-match + initial-input hist def inherit-input-method + str-command buf-name))) + (helm-mode 1) + ;; When exiting minibuffer, `this-command' is set to + ;; `helm-exit-minibuffer', which is unwanted when starting + ;; on another `completing-read', so restore `this-command' to + ;; initial value when exiting. + (setq this-command current-command)))) + +;;; Generic read-file-name +;; +;; +;;;###autoload +(cl-defun helm-read-file-name + (prompt + &key + (name "Read File Name") + (initial-input default-directory) + (buffer "*Helm file completions*") + test + (case-fold helm-file-name-case-fold-search) + preselect + history + must-match + (fuzzy t) + default + marked-candidates + (candidate-number-limit helm-ff-candidate-number-limit) + nomark + (alistp t) + (persistent-action-if 'helm-find-files-persistent-action-if) + (persistent-help "Hit1 Expand Candidate, Hit2 or (C-u) Find file") + (mode-line helm-read-file-name-mode-line-string)) + "Read a file name with helm completion. +It is helm `read-file-name' emulation. + +Argument PROMPT is the default prompt to use. + +Keys description: + +- NAME: Source name, default to \"Read File Name\". + +- INITIAL-INPUT: Where to start read file name, default to `default-directory'. + +- BUFFER: `helm-buffer' name default to \"*Helm Completions*\". + +- TEST: A predicate called with one arg 'candidate'. + +- CASE-FOLD: Same as `helm-case-fold-search'. + +- PRESELECT: helm preselection. + +- HISTORY: Display HISTORY in a special source. + +- MUST-MATCH: Can be 'confirm, nil, or t. + +- FUZZY: Enable fuzzy matching when non-nil (Enabled by default). + +- MARKED-CANDIDATES: When non--nil return a list of marked candidates. + +- NOMARK: When non--nil don't allow marking candidates. + +- ALISTP: Don't use `all-completions' in history (take effect only on history). + +- PERSISTENT-ACTION-IF: a persistent if action function. + +- PERSISTENT-HELP: persistent help message. + +- MODE-LINE: A mode line message, default is `helm-read-file-name-mode-line-string'." + (require 'tramp) + (when (get-buffer helm-action-buffer) + (kill-buffer helm-action-buffer)) + ;; Assume completion have been already required, + ;; so always use 'confirm. + (when (eq must-match 'confirm-after-completion) + (setq must-match 'confirm)) + (mapc (lambda (hook) + (add-hook 'helm-after-update-hook hook)) + '(helm-ff-move-to-first-real-candidate + helm-ff-update-when-only-one-matched + helm-ff-auto-expand-to-home-or-root)) + (let* ((action-fn `(("Sole action (Identity)" + . (lambda (candidate) + (if ,marked-candidates + (helm-marked-candidates :with-wildcard t) + (identity candidate)))))) + ;; Be sure we don't erase the underlying minibuffer if some. + (helm-ff-auto-update-initial-value + (and helm-ff-auto-update-initial-value + (not (minibuffer-window-active-p (minibuffer-window))))) + helm-follow-mode-persistent + (helm-ff-fuzzy-matching + (and fuzzy + (not (memq helm-mm-matching-method '(multi1 multi3p))))) + (hist (and history (helm-comp-read-get-candidates + history nil nil alistp))) + (minibuffer-completion-confirm must-match) + (must-match-map (when must-match + (let ((map (make-sparse-keymap))) + (define-key map (kbd "RET") + (let ((fn (lookup-key helm-read-file-map (kbd "RET")))) + (if (eq fn 'helm-ff-RET) + #'helm-ff-RET-must-match + #'helm-confirm-and-exit-minibuffer))) + map))) + (cmap (if must-match-map + (make-composed-keymap + must-match-map helm-read-file-map) + helm-read-file-map)) + (minibuffer-completion-predicate test) + (minibuffer-completing-file-name t) + (helm--completing-file-name t) + (helm-read-file-name-mode-line-string + (replace-regexp-in-string "helm-maybe-exit-minibuffer" + "helm-confirm-and-exit-minibuffer" + helm-read-file-name-mode-line-string)) + (src-list + (list + ;; History source. + (helm-build-sync-source (format "%s History" name) + :header-name (lambda (name) + (concat name (substitute-command-keys + helm-find-files-doc-header))) + :mode-line mode-line + :candidates hist + :nohighlight t + :fuzzy-match fuzzy + :persistent-action-if persistent-action-if + :persistent-help persistent-help + :keymap cmap + :nomark nomark + :action action-fn) + ;; Other source. + (helm-build-sync-source name + :header-name (lambda (name) + (concat name (substitute-command-keys + helm-find-files-doc-header))) + :init (lambda () + (setq helm-ff-auto-update-flag + helm-ff-auto-update-initial-value) + (setq helm-ff--auto-update-state + helm-ff-auto-update-flag)) + :mode-line mode-line + :help-message 'helm-read-file-name-help-message + :nohighlight t + :candidates + (lambda () + (append (and (not (file-exists-p helm-pattern)) + (not (helm-ff--invalid-tramp-name-p helm-pattern)) + (list helm-pattern)) + (if test + (cl-loop with hn = (helm-ff--tramp-hostnames) + for i in (helm-find-files-get-candidates + must-match) + when (or (member i hn) ; A tramp host + (funcall test i)) ; Test ok + collect i) + (helm-find-files-get-candidates must-match)))) + :filtered-candidate-transformer 'helm-ff-sort-candidates + :filter-one-by-one 'helm-ff-filter-candidate-one-by-one + :persistent-action-if persistent-action-if + :persistent-help persistent-help + :volatile t + :keymap cmap + :cleanup 'helm-find-files-cleanup + :nomark nomark + :action action-fn))) + ;; Helm result. + (result (helm + :sources (if helm-mode-reverse-history + (reverse src-list) src-list) + :input (expand-file-name initial-input) + :prompt prompt + :candidate-number-limit candidate-number-limit + :resume 'noresume + :case-fold-search case-fold + :default default + :buffer buffer + :full-frame nil + :preselect preselect))) + (or + (cond ((and result (stringp result) + (string= result "") "")) + ((and result + (stringp result) + (file-equal-p result initial-input) + default) + (if (listp default) (car default) default)) + ((and result (listp result)) + (mapcar #'expand-file-name result)) + ((and result (file-directory-p result)) + (file-name-as-directory (expand-file-name result))) + (result (expand-file-name result))) + (helm-mode--keyboard-quit)))) + +(defun helm-mode--default-filename (fname dir initial) + (unless dir (setq dir default-directory)) + (unless (file-name-absolute-p dir) + (setq dir (expand-file-name dir))) + (unless (or fname (consp fname)) + (setq fname (expand-file-name + (or initial buffer-file-name dir) + dir))) + (if (and fname (consp fname)) + (setq fname (cl-loop for f in fname + collect (expand-file-name f dir))) + (if (file-name-absolute-p fname) + fname (expand-file-name fname dir)))) + +(cl-defun helm--generic-read-file-name + (prompt &optional dir default-filename mustmatch initial predicate) + "Generic helm replacement of `read-file-name'. +Don't use it directly, use instead `helm-read-file-name' in your programs." + (let* ((init (or initial dir default-directory)) + (current-command (or (helm-this-command) this-command)) + (str-command (helm-symbol-name current-command)) + (helm--file-completion-sources + (cons str-command + (remove str-command helm--file-completion-sources))) + (buf-name (format "*helm-mode-%s*" str-command)) + (entry (assq current-command + helm-completing-read-handlers-alist)) + (def-com (cdr-safe entry)) + (str-defcom (and def-com (helm-symbol-name def-com))) + ;; Don't modify the original args list for emacs generic functions. + (def-args (list prompt dir default-filename mustmatch initial predicate)) + ;; Append the two extra args needed to set the buffer and source name + ;; in helm specialized functions. + (any-args (append def-args (list str-command buf-name))) + (ido-state ido-mode) + helm-completion-mode-start-message ; Be quiet + helm-completion-mode-quit-message ; Same here + fname) + ;; Build `default-filename' with `dir'+`initial' when + ;; `default-filename' is not specified. + ;; See `read-file-name' docstring for more infos. + (setq default-filename (helm-mode--default-filename + default-filename dir initial)) + ;; Some functions that normally call `completing-read' can switch + ;; brutally to `read-file-name' (e.g find-tag), in this case + ;; the helm specialized function will fail because it is build + ;; for `completing-read', so set it to 'incompatible to be sure + ;; we switch to `helm-read-file-name' and don't try to call it + ;; with wrong number of args. + (when (eq def-com 'ido) + (setq def-com 'ido-read-file-name) (ido-mode 1)) + (when (and def-com (> (length (help-function-arglist def-com)) 8)) + (setq def-com 'incompatible)) + (unless (or (not entry) def-com) + (cl-return-from helm--generic-read-file-name + (unwind-protect + (progn + (helm-mode -1) + (apply read-file-name-function def-args)) + (helm-mode 1)))) + ;; If we use now `read-file-name' we MUST turn off `helm-mode' + ;; to avoid infinite recursion and CRASH. It will be reenabled on exit. + (when (or (eq def-com 'read-file-name) + (eq def-com 'ido-read-file-name) + (and (stringp str-defcom) + (not (string-match "^helm" str-defcom)))) + (helm-mode -1)) + (unwind-protect + (setq fname + (cond (;; A specialized function exists, run it + ;; with the two extra args specific to helm. + ;; Note that the helm handler should ensure + ;; :initial-input is not nil i.e. Use init + ;; which fallback to default-directory instead + ;; of INITIAL. + (and def-com helm-mode + (not (eq def-com 'ido-read-file-name)) + (not (eq def-com 'incompatible))) + (apply def-com any-args)) + (;; Def-com value is `ido-read-file-name' + ;; run it with default args. + (and def-com (eq def-com 'ido-read-file-name)) + (ido-mode 1) + (apply def-com def-args)) + (;; Def-com value is `read-file-name' + ;; run it with default args. + (eq def-com 'read-file-name) + (apply def-com def-args)) + (t ; Fall back to classic `helm-read-file-name'. + (helm-read-file-name + prompt + :name str-command + :buffer buf-name + :default default-filename + ;; Helm handlers should always have a non nil INITIAL arg. + :initial-input (expand-file-name init dir) + :alistp nil + :must-match mustmatch + :test predicate)))) + (helm-mode 1) + (ido-mode (if ido-state 1 -1)) + ;; Same comment as in `helm--completing-read-default'. + (setq this-command current-command)) + (if (and + ;; Using `read-directory-name'. + (eq predicate 'file-directory-p) + ;; `file-name-as-directory' return "./" when FNAME is + ;; empty string. + (not (string= fname ""))) + (file-name-as-directory fname) fname))) + +;; Read file name handler with history (issue #1652) +(defun helm-read-file-name-handler-1 (prompt dir default-filename + mustmatch initial predicate + name buffer) + "A `read-file-name' handler with history. +Can be added to `helm-completing-read-handlers-alist' for functions +that need a `read-file-name' function with directory history. +The `helm-find-files' history `helm-ff-history' is used here." + (let ((helm-always-two-windows t) + (helm-split-window-default-side + (if (eq helm-split-window-default-side 'same) + 'below helm-split-window-default-side)) + helm-split-window-inside-p + helm-reuse-last-window-split-state + ;; Helm handlers should always have a non nil INITIAL arg. + (init (or initial dir default-directory))) + (helm-read-file-name + prompt + :name name + :history helm-ff-history + :buffer buffer + :default default-filename + :initial-input (expand-file-name init dir) + :alistp nil + :must-match mustmatch + :test predicate))) + + +;;; Completion in region +;; +(defun helm-mode--advice-lisp--local-variables (old--fn &rest args) + (ignore-errors + (apply old--fn args))) + +(defun helm-completion-in-region-sort-fn (candidates _source) + "Default sort function for completion-in-region." + (sort candidates 'helm-generic-sort-fn)) + +(defun helm--completion-in-region (start end collection &optional predicate) + "Helm replacement of `completion--in-region'. +Can be used as value for `completion-in-region-function'." + (cl-declare (special require-match prompt)) + (if (memq major-mode helm-mode-no-completion-in-region-in-modes) + (funcall helm--old-completion-in-region-function + start end collection predicate) + (advice-add + 'lisp--local-variables + :around #'helm-mode--advice-lisp--local-variables) + (unwind-protect + (let* ((enable-recursive-minibuffers t) + (input (buffer-substring-no-properties start end)) + (current-command (or (helm-this-command) this-command)) + (crm (eq current-command 'crm-complete)) + (str-command (helm-symbol-name current-command)) + (buf-name (format "*helm-mode-%s*" str-command)) + (require-match (or (and (boundp 'require-match) require-match) + minibuffer-completion-confirm + ;; If prompt have not been propagated here, that's + ;; probably mean we have no prompt and we are in + ;; completion-at-point or friend, so use a non--nil + ;; value for require-match. + (not (boundp 'prompt)))) + ;; `completion-extra-properties' is let-bounded in `completion-at-point'. + ;; `afun' is a closure to call against each string in `data'. + ;; it provide the annotation info for each string. + ;; e.g "foo" => "foo " where foo is a function. + ;; See Issue #407. + (afun (plist-get completion-extra-properties :annotation-function)) + (metadata (completion-metadata + (buffer-substring-no-properties start (point)) + collection predicate)) + (data (completion-all-completions + (buffer-substring start end) + collection + predicate + (- (point) start) + metadata)) + ;; `completion-all-completions' store the base-size in the last `cdr', + ;; so data looks like this: '(a b c d . 0) and (last data) == (d . 0). + (last-data (last data)) + (base-size (helm-aif (cdr (last data)) + (prog1 it + (setcdr last-data nil)) + 0)) + (init-space-suffix (unless (or helm-completion-in-region-fuzzy-match + (string-suffix-p " " input) + (string= input "")) + " ")) + (file-comp-p (or (eq (completion-metadata-get metadata 'category) 'file) + (helm-mode--in-file-completion-p) + ;; Assume that when `afun' and `predicate' are null + ;; we are in filename completion. + (and (null afun) (null predicate)))) + ;; Completion-at-point and friends have no prompt. + (result (if (stringp data) + data + (helm-comp-read + (or (and (boundp 'prompt) prompt) "Pattern: ") + (if file-comp-p + (cl-loop for f in data unless + (string-match "\\`\\.\\{1,2\\}/\\'" f) + collect f) + (if afun + (mapcar (lambda (s) + (let ((ann (funcall afun s))) + (if ann + (cons + (concat + s + (propertize + " " 'display + (propertize + ann + 'face 'completions-annotations))) + s) + s))) + data) + data)) + :name str-command + :fuzzy helm-completion-in-region-fuzzy-match + :nomark (null crm) + :marked-candidates crm + :initial-input + (cond ((and file-comp-p + (not (string-match "/\\'" input))) + (concat (helm-basename input) + init-space-suffix)) + ((string-match "/\\'" input) nil) + ((or (null require-match) + (stringp require-match)) + input) + (t (concat input init-space-suffix))) + :buffer buf-name + :fc-transformer (append '(helm-cr-default-transformer) + (unless (or helm-completion-in-region-fuzzy-match + (null helm-completion-in-region-default-sort-fn)) + (list helm-completion-in-region-default-sort-fn))) + :exec-when-only-one t + :quit-when-no-cand + (lambda () + ;; Delay message to overwrite "Quit". + (run-with-timer + 0.01 nil + (lambda () + (message "[No matches]"))) + t) ; exit minibuffer immediately. + :must-match require-match)))) + (cond ((stringp result) + (choose-completion-string + result (current-buffer) + (list (+ start base-size) end) + completion-list-insert-choice-function)) + ((consp result) ; crm. + (let ((beg (+ start base-size)) + (sep ",")) + ;; Try to find a default separator. + (save-excursion + (goto-char beg) + (when (looking-back crm-separator (1- (point))) + (setq sep (match-string 0)))) + (funcall completion-list-insert-choice-function + beg end (mapconcat 'identity result sep)))) + (t nil))) + (advice-remove 'lisp--local-variables + #'helm-mode--advice-lisp--local-variables)))) + +(defun helm-mode--in-file-completion-p () + (with-helm-current-buffer + (run-hook-with-args-until-success 'file-name-at-point-functions))) + +(when (boundp 'completion-in-region-function) + (defconst helm--old-completion-in-region-function completion-in-region-function)) + +;;;###autoload +(define-minor-mode helm-mode + "Toggle generic helm completion. + +All functions in Emacs that use `completing-read' +or `read-file-name' and friends will use helm interface +when this mode is turned on. + +However you can modify this behavior for functions of your choice +with `helm-completing-read-handlers-alist'. + +Also commands using `completion-in-region' will be helmized when +`helm-mode-handle-completion-in-region' is non nil, you can modify +this behavior with `helm-mode-no-completion-in-region-in-modes'. + +Called with a positive arg, turn on unconditionally, with a +negative arg turn off. +You can turn it on with `helm-mode'. + +Some crap emacs functions may not be supported, +e.g `ffap-alternate-file' and maybe others +You can add such functions to `helm-completing-read-handlers-alist' +with a nil value. + +About `ido-mode': +When you are using `helm-mode', DO NOT use `ido-mode', instead if you +want some commands use `ido', add these commands to +`helm-completing-read-handlers-alist' with `ido' as value. + +Note: This mode is incompatible with Emacs23." + :group 'helm-mode + :global t + :lighter helm-completion-mode-string + (cl-assert (boundp 'completing-read-function) nil + "`helm-mode' not available, upgrade to Emacs-24") + (if helm-mode + (if (fboundp 'add-function) + (progn + (add-function :override completing-read-function + #'helm--completing-read-default) + (add-function :override read-file-name-function + #'helm--generic-read-file-name) + (add-function :override read-buffer-function + #'helm--generic-read-buffer) + (when helm-mode-handle-completion-in-region + (add-function :override completion-in-region-function + #'helm--completion-in-region))) + (setq completing-read-function 'helm--completing-read-default + read-file-name-function 'helm--generic-read-file-name + read-buffer-function 'helm--generic-read-buffer) + (when (and (boundp 'completion-in-region-function) + helm-mode-handle-completion-in-region) + (setq completion-in-region-function #'helm--completion-in-region)) + (message helm-completion-mode-start-message)) + (if (fboundp 'remove-function) + (progn + (remove-function completing-read-function #'helm--completing-read-default) + (remove-function read-file-name-function #'helm--generic-read-file-name) + (remove-function read-buffer-function #'helm--generic-read-buffer) + (remove-function completion-in-region-function #'helm--completion-in-region)) + (setq completing-read-function (and (fboundp 'completing-read-default) + 'completing-read-default) + read-file-name-function (and (fboundp 'read-file-name-default) + 'read-file-name-default) + read-buffer-function (and (fboundp 'read-buffer) 'read-buffer)) + (when (and (boundp 'completion-in-region-function) + (boundp 'helm--old-completion-in-region-function)) + (setq completion-in-region-function helm--old-completion-in-region-function)) + (message helm-completion-mode-quit-message)))) + +(provide 'helm-mode) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-mode.el ends here diff --git a/elpa/helm-20181113.923/helm-net.el b/elpa/helm-20181113.923/helm-net.el new file mode 100644 index 00000000..9678f71c --- /dev/null +++ b/elpa/helm-20181113.923/helm-net.el @@ -0,0 +1,584 @@ +;;; helm-net.el --- helm browse url and search web. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'url) +(require 'xml) +(require 'browse-url) + + +(defgroup helm-net nil + "Net related applications and libraries for Helm." + :group 'helm) + +(defcustom helm-google-suggest-default-browser-function nil + "The browse url function you prefer to use with google suggest. +When nil, use the first browser function available +See `helm-browse-url-default-browser-alist'." + :group 'helm-net + :type 'symbol) + +(defcustom helm-home-url "https://www.google.com" + "Default url to use as home url." + :group 'helm-net + :type 'string) + +(defcustom helm-surfraw-default-browser-function nil + "The browse url function you prefer to use with surfraw. +When nil, fallback to `browse-url-browser-function'." + :group 'helm-net + :type 'symbol) + +(defcustom helm-google-suggest-url + "https://encrypted.google.com/complete/search?output=toolbar&q=%s" + "URL used for looking up Google suggestions. +This is a format string, don't forget the `%s'." + :type 'string + :group 'helm-net) + +(defcustom helm-google-suggest-search-url + "https://encrypted.google.com/search?ie=utf-8&oe=utf-8&q=%s" + "URL used for Google searching. +This is a format string, don't forget the `%s'." + :type 'string + :group 'helm-net) + +(defvaralias 'helm-google-suggest-use-curl-p 'helm-net-prefer-curl) +(make-obsolete-variable 'helm-google-suggest-use-curl-p 'helm-net-prefer-curl "1.7.7") + +(defcustom helm-net-prefer-curl nil + "When non--nil use CURL external program to fetch data. +Otherwise `url-retrieve-synchronously' is used." + :type 'boolean + :group 'helm-net) + +(defcustom helm-surfraw-duckduckgo-url + "https://duckduckgo.com/lite/?q=%s&kp=1" + "The duckduckgo url. +This is a format string, don't forget the `%s'. +If you have personal settings saved on duckduckgo you should have +a personal url, see your settings on duckduckgo." + :type 'string + :group 'helm-net) + +(defcustom helm-wikipedia-suggest-url + "https://en.wikipedia.org/w/api.php?action=opensearch&search=%s" + "Url used for looking up Wikipedia suggestions. +This is a format string, don't forget the `%s'." + :type 'string + :group 'helm-net) + +(defcustom helm-search-suggest-action-wikipedia-url + "https://en.wikipedia.org/wiki/Special:Search?search=%s" + "The Wikipedia search url. +This is a format string, don't forget the `%s'." + :type 'string + :group 'helm-net) + +(defcustom helm-wikipedia-summary-url + "https://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=%s" + "URL for getting the summary of a Wikipedia topic. +This is a format string, don't forget the `%s'." + :type 'string + :group 'helm-net) + +(defcustom helm-search-suggest-action-youtube-url + "https://www.youtube.com/results?aq=f&search_query=%s" + "The Youtube search url. +This is a format string, don't forget the `%s'." + :type 'string + :group 'helm-net) + +(defcustom helm-search-suggest-action-imdb-url + "http://www.imdb.com/find?s=all&q=%s" + "The IMDb search url. +This is a format string, don't forget the `%s'." + :type 'string + :group 'helm-net) + +(defcustom helm-search-suggest-action-google-maps-url + "https://maps.google.com/maps?f=q&source=s_q&q=%s" + "The Google Maps search url. +This is a format string, don't forget the `%s'." + :type 'string + :group 'helm-net) + +(defcustom helm-search-suggest-action-google-news-url + "https://www.google.com/search?safe=off&prmd=nvlifd&source=lnms&tbs=nws:1&q=%s" + "The Google News search url. +This is a format string, don't forget the `%s'." + :type 'string + :group 'helm-net) + +(defcustom helm-google-suggest-actions + '(("Google Search" . helm-google-suggest-action) + ("Wikipedia" . (lambda (candidate) + (helm-search-suggest-perform-additional-action + helm-search-suggest-action-wikipedia-url + candidate))) + ("Youtube" . (lambda (candidate) + (helm-search-suggest-perform-additional-action + helm-search-suggest-action-youtube-url + candidate))) + ("IMDb" . (lambda (candidate) + (helm-search-suggest-perform-additional-action + helm-search-suggest-action-imdb-url + candidate))) + ("Google Maps" . (lambda (candidate) + (helm-search-suggest-perform-additional-action + helm-search-suggest-action-google-maps-url + candidate))) + ("Google News" . (lambda (candidate) + (helm-search-suggest-perform-additional-action + helm-search-suggest-action-google-news-url + candidate)))) + "List of actions for google suggest sources." + :group 'helm-net + :type '(alist :key-type string :value-type function)) + +(defcustom helm-browse-url-firefox-new-window "-new-tab" + "Allow choosing to browse url in new window or new tab. +Can be \"-new-tab\" (default) or \"-new-window\"." + :group 'helm-net + :type '(radio + (const :tag "New tab" "-new-tab") + (const :tag "New window" "-new-window"))) + + +;;; Additional actions for search suggestions +;; +;; +;; Internal + +(defun helm-search-suggest-perform-additional-action (url query) + "Perform the search via URL using QUERY as input." + (browse-url (format url (url-hexify-string query)))) + +(defun helm-net--url-retrieve-sync (request parser) + (if helm-net-prefer-curl + (with-temp-buffer + (call-process "curl" nil t nil request) + (funcall parser)) + (with-current-buffer (url-retrieve-synchronously request) + (funcall parser)))) + + +;;; Google Suggestions +;; +;; +(defun helm-google-suggest-parser () + (cl-loop + with result-alist = (xml-get-children + (car (xml-parse-region + (point-min) (point-max))) + 'CompleteSuggestion) + for i in result-alist collect + (cdr (cl-caadr (assq 'suggestion i))))) + +(defun helm-google-suggest-fetch (input) + "Fetch suggestions for INPUT from XML buffer." + (let ((request (format helm-google-suggest-url + (url-hexify-string input)))) + (helm-net--url-retrieve-sync + request #'helm-google-suggest-parser))) + +(defun helm-google-suggest-set-candidates (&optional request-prefix) + "Set candidates with result and number of google results found." + (let ((suggestions (helm-google-suggest-fetch + (or (and request-prefix + (concat request-prefix + " " helm-pattern)) + helm-pattern)))) + (if (member helm-pattern suggestions) + suggestions + ;; if there is no suggestion exactly matching the input then + ;; prepend a Search on Google item to the list + (append + suggestions + (list (cons (format "Search for '%s' on Google" helm-input) + helm-input)))))) + +(defun helm-ggs-set-number-result (num) + (if num + (progn + (and (numberp num) (setq num (number-to-string num))) + (cl-loop for i in (reverse (split-string num "" t)) + for count from 1 + append (list i) into C + when (= count 3) + append (list ",") into C + and do (setq count 0) + finally return + (replace-regexp-in-string + "^," "" (mapconcat 'identity (reverse C) "")))) + "?")) + +(defun helm-google-suggest-action (candidate) + "Default action to jump to a google suggested candidate." + (let ((arg (format helm-google-suggest-search-url + (url-hexify-string candidate)))) + (helm-aif helm-google-suggest-default-browser-function + (funcall it arg) + (helm-browse-url arg)))) + +(defvar helm-google-suggest-default-function + 'helm-google-suggest-set-candidates + "Default function to use in helm google suggest.") + +(defvar helm-source-google-suggest + (helm-build-sync-source "Google Suggest" + :candidates (lambda () + (funcall helm-google-suggest-default-function)) + :action 'helm-google-suggest-actions + :volatile t + :keymap helm-map + :requires-pattern 3)) + +(defun helm-google-suggest-emacs-lisp () + "Try to emacs lisp complete with google suggestions." + (helm-google-suggest-set-candidates "emacs lisp")) + +;;; Wikipedia suggestions +;; +;; +(declare-function json-read-from-string "json" (string)) +(defun helm-wikipedia-suggest-fetch () + "Fetch Wikipedia suggestions and return them as a list." + (require 'json) + (let ((request (format helm-wikipedia-suggest-url + (url-hexify-string helm-pattern)))) + (helm-net--url-retrieve-sync + request #'helm-wikipedia--parse-buffer))) + +(defun helm-wikipedia--parse-buffer () + (goto-char (point-min)) + (when (re-search-forward "^\\[.+\\[\\(.*\\)\\]\\]" nil t) + (cl-loop for i across (aref (json-read-from-string (match-string 0)) 1) + collect i into result + finally return (or result + (append + result + (list (cons (format "Search for '%s' on wikipedia" + helm-pattern) + helm-pattern))))))) + +(defvar helm-wikipedia--summary-cache (make-hash-table :test 'equal)) +(defun helm-wikipedia-show-summary (input) + "Show Wikipedia summary for INPUT in new buffer." + (interactive) + (let ((buffer (get-buffer-create "*helm wikipedia summary*")) + (summary (helm-wikipedia--get-summary input))) + (with-current-buffer buffer + (visual-line-mode) + (erase-buffer) + (insert summary) + (pop-to-buffer (current-buffer)) + (goto-char (point-min))))) + +(defun helm-wikipedia-persistent-action (candidate) + (unless (string= (format "Search for '%s' on wikipedia" + helm-pattern) + (helm-get-selection nil t)) + (message "Fetching summary from Wikipedia...") + (let ((buf (get-buffer-create "*helm wikipedia summary*")) + (result (helm-wikipedia--get-summary candidate))) + (with-current-buffer buf + (erase-buffer) + (setq cursor-type nil) + (insert result) + (fill-region (point-min) (point-max)) + (goto-char (point-min))) + (display-buffer buf)))) + +(defun helm-wikipedia--get-summary (input) + "Return Wikipedia summary for INPUT as string. +Follows any redirections from Wikipedia, and stores results in +`helm-wikipedia--summary-cache'." + (let (result) + (while (progn + (setq result (or (gethash input helm-wikipedia--summary-cache) + (puthash input + (helm-wikipedia--fetch-summary input) + helm-wikipedia--summary-cache))) + (when (and result + (listp result)) + (setq input (cdr result)) + (message "Redirected to %s" input) + t))) + (unless result + (error "Error when getting summary.")) + result)) + +(defun helm-wikipedia--fetch-summary (input) + (let* ((request (format helm-wikipedia-summary-url + (url-hexify-string input)))) + (helm-net--url-retrieve-sync + request #'helm-wikipedia--parse-summary))) + +(defun helm-wikipedia--parse-summary () + (goto-char (point-min)) + (when (search-forward "{" nil t) + (let ((result (cdr (assq '* + (assq 'text + (assq 'parse + (json-read-from-string + (buffer-substring-no-properties + (1- (point)) (point-max))))))))) + (when result + (if (string-match "]+>\\([^<]+\\)" result) + (cons 'redirect (match-string 1 result)) + + ;; find the beginning of the summary text in the result + + ;; check if there is a table before the summary and skip that + (when (or (string-match "\\(\n\\)?\n

" result) + ;; otherwise just find the first paragraph + (string-match "

" result)) + ;; remove cruft and do a simple formatting + (replace-regexp-in-string + "Cite error: .*" "" + (replace-regexp-in-string + " " "" + (replace-regexp-in-string + "\\[[^\]]+\\]" "" + (replace-regexp-in-string + "<[^>]*>" "" + (replace-regexp-in-string + "

\n

" "\n\n" + (substring result (match-end 0))))))))))))) + + +(defvar helm-wikipedia-map + (let ((map (copy-keymap helm-map))) + (define-key map (kbd "") 'helm-wikipedia-show-summary-action) + map) + "Keymap for `helm-wikipedia-suggest'.") + +(defvar helm-source-wikipedia-suggest + (helm-build-sync-source "Wikipedia Suggest" + :candidates #'helm-wikipedia-suggest-fetch + :action '(("Wikipedia" . (lambda (candidate) + (helm-search-suggest-perform-additional-action + helm-search-suggest-action-wikipedia-url + candidate))) + ("Show summary in new buffer (C-RET)" . helm-wikipedia-show-summary)) + :persistent-action #'helm-wikipedia-persistent-action + :persistent-help "show summary" + :volatile t + :keymap helm-wikipedia-map + :requires-pattern 3)) + +(defun helm-wikipedia-show-summary-action () + "Exit Helm buffer and call `helm-wikipedia-show-summary' with selected candidate." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-wikipedia-show-summary))) + + +;;; Web browser functions. +;; +;; +;; If default setting of `w3m-command' is not +;; what you want and you modify it, you will have to reeval +;; also `helm-browse-url-default-browser-alist'. + +(defvar helm-browse-url-chromium-program "chromium-browser") +(defvar helm-browse-url-uzbl-program "uzbl-browser") +(defvar helm-browse-url-conkeror-program "conkeror") +(defvar helm-browse-url-opera-program "opera") +(defvar helm-browse-url-default-browser-alist + `((,(or (and (boundp 'w3m-command) w3m-command) + "/usr/bin/w3m") . w3m-browse-url) + (,browse-url-firefox-program . browse-url-firefox) + (,helm-browse-url-chromium-program . helm-browse-url-chromium) + (,helm-browse-url-conkeror-program . helm-browse-url-conkeror) + (,helm-browse-url-opera-program . helm-browse-url-opera) + (,helm-browse-url-uzbl-program . helm-browse-url-uzbl) + (,browse-url-kde-program . browse-url-kde) + (,browse-url-gnome-moz-program . browse-url-gnome-moz) + (,browse-url-mozilla-program . browse-url-mozilla) + (,browse-url-galeon-program . browse-url-galeon) + (,browse-url-netscape-program . browse-url-netscape) + (,browse-url-mosaic-program . browse-url-mosaic) + (,browse-url-xterm-program . browse-url-text-xterm) + ("emacs" . eww-browse-url)) + "*Alist of \(executable . function\) to try to find a suitable url browser.") + +(cl-defun helm-generic-browser (url cmd-name &rest args) + "Browse URL with NAME browser." + (let ((proc (concat cmd-name " " url))) + (message "Starting %s..." cmd-name) + (apply 'start-process proc nil cmd-name + (append args (list url))) + (set-process-sentinel + (get-process proc) + (lambda (process event) + (when (string= event "finished\n") + (message "%s process %s" process event)))))) + +;;;###autoload +(defun helm-browse-url-firefox (url &optional _ignore) + "Same as `browse-url-firefox' but detach from emacs. + +So when you quit emacs you can keep your firefox session open +and not be prompted to kill firefox process. + +NOTE: Probably not supported on some systems (e.g Windows)." + (interactive (list (read-string "URL: " (browse-url-url-at-point)) + nil)) + (setq url (browse-url-encode-url url)) + (let ((process-environment (browse-url-process-environment))) + (call-process-shell-command + (format "(%s %s %s &)" + browse-url-firefox-program + helm-browse-url-firefox-new-window + (shell-quote-argument url))))) + +;;;###autoload +(defun helm-browse-url-opera (url &optional _ignore) + "Browse URL with opera browser and detach from emacs. + +So when you quit emacs you can keep your opera session open +and not be prompted to kill opera process. + +NOTE: Probably not supported on some systems (e.g Windows)." + (interactive (list (read-string "URL: " (browse-url-url-at-point)) + nil)) + (setq url (browse-url-encode-url url)) + (let ((process-environment (browse-url-process-environment))) + (call-process-shell-command + (format "(%s %s &)" + helm-browse-url-opera-program (shell-quote-argument url))))) + +;;;###autoload +(defun helm-browse-url-chromium (url &optional _ignore) + "Browse URL with google chrome browser." + (interactive "sURL: ") + (helm-generic-browser + url helm-browse-url-chromium-program)) + +;;;###autoload +(defun helm-browse-url-uzbl (url &optional _ignore) + "Browse URL with uzbl browser." + (interactive "sURL: ") + (helm-generic-browser url helm-browse-url-uzbl-program "-u")) + +;;;###autoload +(defun helm-browse-url-conkeror (url &optional _ignore) + "Browse URL with conkeror browser." + (interactive "sURL: ") + (helm-generic-browser url helm-browse-url-conkeror-program)) + +(defun helm-browse-url-default-browser (url &rest args) + "Find the first available browser and ask it to load URL." + (let ((default-browser-fn + (cl-loop for (exe . fn) in helm-browse-url-default-browser-alist + thereis (and exe (executable-find exe) (fboundp fn) fn)))) + (if default-browser-fn + (apply default-browser-fn url args) + (error "No usable browser found")))) + +(defun helm-browse-url (url &rest args) + "Default command to browse URL." + (if browse-url-browser-function + (browse-url url args) + (helm-browse-url-default-browser url args))) + + +;;; Surfraw +;; +;; Need external program surfraw. +;; + +;; Internal +(defvar helm-surfraw-engines-history nil) +(defvar helm-surfraw-input-history nil) +(defvar helm-surfraw--elvi-cache nil) + +(defun helm-build-elvi-list () + "Return list of all engines and descriptions handled by surfraw." + (or helm-surfraw--elvi-cache + (setq helm-surfraw--elvi-cache + (cdr (with-temp-buffer + (call-process "surfraw" nil t nil "-elvi") + (split-string (buffer-string) "\n")))))) + +;;;###autoload +(defun helm-surfraw (pattern engine) + "Preconfigured `helm' to search PATTERN with search ENGINE." + (interactive + (list + (let* ((default (if (use-region-p) + (buffer-substring-no-properties + (region-beginning) (region-end)) + (thing-at-point 'symbol))) + (prompt (if default + (format "SearchFor (default %s): " default) + "SearchFor: "))) + (read-string prompt nil 'helm-surfraw-input-history default)) + (helm-comp-read + "Engine: " + (helm-build-elvi-list) + :must-match t + :name "Surfraw Search Engines" + :del-input nil + :history helm-surfraw-engines-history))) + (let* ((engine-nodesc (car (split-string engine))) + (url (if (string= engine-nodesc "duckduckgo") + ;; "sr duckduckgo -p foo" is broken, workaround. + (format helm-surfraw-duckduckgo-url + (url-hexify-string pattern)) + (with-temp-buffer + (apply 'call-process "surfraw" nil t nil + (append (list engine-nodesc "-p") (split-string pattern))) + (replace-regexp-in-string + "\n" "" (buffer-string))))) + (browse-url-browser-function (or helm-surfraw-default-browser-function + browse-url-browser-function))) + (if (string= engine-nodesc "W") + (helm-browse-url helm-home-url) + (helm-browse-url url) + (setq helm-surfraw-engines-history + (cons engine (delete engine helm-surfraw-engines-history)))))) + +;;;###autoload +(defun helm-google-suggest () + "Preconfigured `helm' for google search with google suggest." + (interactive) + (helm-other-buffer 'helm-source-google-suggest "*helm google*")) + +;;;###autoload +(defun helm-wikipedia-suggest () + "Preconfigured `helm' for Wikipedia lookup with Wikipedia suggest." + (interactive) + (helm :sources 'helm-source-wikipedia-suggest + :buffer "*helm wikipedia*")) + + +(provide 'helm-net) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-net.el ends here diff --git a/elpa/helm-20181113.923/helm-org.el b/elpa/helm-20181113.923/helm-org.el new file mode 100644 index 00000000..b045ddaa --- /dev/null +++ b/elpa/helm-20181113.923/helm-org.el @@ -0,0 +1,426 @@ +;;; helm-org.el --- Helm for org headlines and keywords completion -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: +(require 'cl-lib) +(require 'helm) +(require 'helm-utils) +(require 'org) + +;; Load org-with-point-at macro when compiling +(eval-when-compile + (require 'org-macs)) + +(declare-function org-agenda-switch-to "org-agenda.el") + +(defgroup helm-org nil + "Org related functions for helm." + :group 'helm) + +(defcustom helm-org-headings-fontify nil + "Fontify org buffers before parsing them. +This reflect fontification in helm-buffer when non--nil. +NOTE: This will be slow on large org buffers." + :group 'helm-org + :type 'boolean) + +(defcustom helm-org-format-outline-path nil + "Show all org level as path." + :group 'helm-org + :type 'boolean) + +(defcustom helm-org-show-filename nil + "Show org filenames in `helm-org-agenda-files-headings' when non--nil. +Note this have no effect in `helm-org-in-buffer-headings'." + :group 'helm-org + :type 'boolean) + +(defcustom helm-org-headings-min-depth 1 + "Minimum depth of org headings to start with." + :group 'helm-org + :type 'integer) + +(defcustom helm-org-headings-max-depth 8 + "Go down to this maximum depth of org headings." + :group 'helm-org + :type 'integer) + +(defcustom helm-org-headings-actions + '(("Go to heading" . helm-org-goto-marker) + ("Open in indirect buffer `C-c i'" . helm-org--open-heading-in-indirect-buffer) + ("Refile heading(s) (marked-to-selected|current-to-selected) `C-c w`" . helm-org--refile-heading-to) + ("Insert link to this heading `C-c l`" . helm-org-insert-link-to-heading-at-marker)) + "Default actions alist for + `helm-source-org-headings-for-files'." + :group 'helm-org + :type '(alist :key-type string :value-type function)) + +(defcustom helm-org-truncate-lines t + "Truncate org-header-lines when non-nil" + :type 'boolean + :group 'helm-org) + +(defcustom helm-org-ignore-autosaves nil + "Ignore autosave files when starting `helm-org-agenda-files-headings'." + :type 'boolean + :group 'helm-org) + + +;;; Org capture templates +;; +;; +(defvar org-capture-templates) +(defun helm-source-org-capture-templates () + (helm-build-sync-source "Org Capture Templates:" + :candidates (cl-loop for template in org-capture-templates + collect (cons (nth 1 template) (nth 0 template))) + :action '(("Do capture" . (lambda (template-shortcut) + (org-capture nil template-shortcut)))))) + +;;; Org headings +;; +;; +(defun helm-org-goto-marker (marker) + (switch-to-buffer (marker-buffer marker)) + (goto-char (marker-position marker)) + (org-show-context) + (re-search-backward "^\\*+ " nil t) + (org-show-entry)) + +(defun helm-org--open-heading-in-indirect-buffer (marker) + (helm-org-goto-marker marker) + (org-tree-to-indirect-buffer) + + ;; Put the non-indirect buffer at the bottom of the prev-buffers + ;; list so it won't be selected when the indirect buffer is killed + (set-window-prev-buffers nil (append (cdr (window-prev-buffers)) + (car (window-prev-buffers))))) + +(defun helm-org-run-open-heading-in-indirect-buffer () + "Open selected Org heading in an indirect buffer." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action #'helm-org--open-heading-in-indirect-buffer))) +(put 'helm-org-run-open-heading-in-indirect-buffer 'helm-only t) + +(defvar helm-org-headings-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "C-c i") 'helm-org-run-open-heading-in-indirect-buffer) + (define-key map (kbd "C-c w") 'helm-org-run-refile-heading-to) + (define-key map (kbd "C-c l") 'helm-org-run-insert-link-to-heading-at-marker) + map) + "Keymap for `helm-source-org-headings-for-files'.") + +(defclass helm-org-headings-class (helm-source-sync) + ((parents + :initarg :parents + :initform nil + :custom boolean) + (match :initform + (lambda (candidate) + (string-match + helm-pattern + (helm-aif (get-text-property 0 'helm-real-display candidate) + it + candidate)))) + (help-message :initform 'helm-org-headings-help-message) + (action :initform 'helm-org-headings-actions) + (keymap :initform 'helm-org-headings-map) + (group :initform 'helm-org))) + +(defmethod helm--setup-source :after ((source helm-org-headings-class)) + (let ((parents (slot-value source 'parents))) + (setf (slot-value source 'candidate-transformer) + (lambda (candidates) + (let ((cands (helm-org-get-candidates candidates parents))) + (if parents (nreverse cands) cands)))))) + +(defun helm-source-org-headings-for-files (filenames &optional parents) + (helm-make-source "Org Headings" 'helm-org-headings-class + :filtered-candidate-transformer 'helm-org-startup-visibility + :parents parents + :candidates filenames)) + +(defun helm-org-startup-visibility (candidates _source) + "Indent headings and hide leading stars displayed in the helm buffer. +If `org-startup-indented' and `org-hide-leading-stars' are nil, do +nothing to CANDIDATES." + (cl-loop for i in candidates + collect + ;; Transformation is not needed if these variables are t. + (if (or helm-org-show-filename helm-org-format-outline-path) + (cons + (car i) (cdr i)) + (cons + (if helm-org-headings-fontify + (when (string-match "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)" (car i)) + (replace-match "\\1\\2\\3" t nil (car i))) + (when (string-match "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)" (car i)) + (let ((foreground (org-find-invisible-foreground))) + (with-helm-current-buffer + (cond + ;; org-startup-indented is t, and org-hide-leading-stars is t + ;; Or: #+STARTUP: indent hidestars + ((and org-startup-indented org-hide-leading-stars) + (with-helm-buffer + (require 'org-indent) + (org-indent-mode 1) + (replace-match + (format "%s\\2\\3" + (propertize (replace-match "\\1" t nil (car i)) + 'face `(:foreground ,foreground))) + t nil (car i)))) + ;; org-startup-indented is nil, org-hide-leading-stars is t + ;; Or: #+STARTUP: noindent hidestars + ((and (not org-startup-indented) org-hide-leading-stars) + (with-helm-buffer + (replace-match + (format "%s\\2\\3" + (propertize (replace-match "\\1" t nil (car i)) + 'face `(:foreground ,foreground))) + t nil (car i)))) + ;; org-startup-indented is nil, and org-hide-leading-stars is nil + ;; Or: #+STARTUP: noindent showstars + (t + (with-helm-buffer + (replace-match "\\1\\2\\3" t nil (car i))))))))) + (cdr i))))) + +(defun helm-org-get-candidates (filenames &optional parents) + (apply #'append + (mapcar (lambda (filename) + (helm-org--get-candidates-in-file + filename + helm-org-headings-fontify + (or parents (null helm-org-show-filename)) + parents)) + filenames))) + +(defun helm-org--get-candidates-in-file (filename &optional fontify nofname parents) + (with-current-buffer (pcase filename + ((pred bufferp) filename) + ((pred stringp) (find-file-noselect filename t))) + (let ((match-fn (if fontify + #'match-string + #'match-string-no-properties)) + (search-fn (lambda () + (re-search-forward + org-complex-heading-regexp nil t))) + (file (unless (or (bufferp filename) nofname) + (concat (helm-basename filename) ":")))) + (when parents + (add-function :around (var search-fn) + (lambda (old-fn &rest args) + (when (org-up-heading-safe) + (apply old-fn args))))) + (save-excursion + (save-restriction + (unless (and (bufferp filename) + (buffer-base-buffer filename)) + ;; Only widen direct buffers, not indirect ones. + (widen)) + (unless parents (goto-char (point-min))) + ;; clear cache for new version of org-get-outline-path + (and (boundp 'org-outline-path-cache) + (setq org-outline-path-cache nil)) + (cl-loop with width = (window-width (helm-window)) + while (funcall search-fn) + for beg = (point-at-bol) + for end = (point-at-eol) + when (and fontify + (null (text-property-any + beg end 'fontified t))) + do (jit-lock-fontify-now beg end) + for level = (length (match-string-no-properties 1)) + for heading = (funcall match-fn 4) + if (and (>= level helm-org-headings-min-depth) + (<= level helm-org-headings-max-depth)) + collect `(,(propertize + (if helm-org-format-outline-path + (org-format-outline-path + ;; org-get-outline-path changed in signature and behaviour since org's + ;; commit 105a4466971. Let's fall-back to the new version in case + ;; of wrong-number-of-arguments error. + (condition-case nil + (append (apply #'org-get-outline-path + (unless parents + (list t level heading))) + (list heading)) + (wrong-number-of-arguments + (org-get-outline-path t t))) + width file) + (if file + (concat file (funcall match-fn 0)) + (funcall match-fn 0))) + 'helm-real-display heading) + . ,(point-marker)))))))) + +(defun helm-org-insert-link-to-heading-at-marker (marker) + (with-current-buffer (marker-buffer marker) + (let ((heading-name (save-excursion (goto-char (marker-position marker)) + (nth 4 (org-heading-components)))) + (file-name (buffer-file-name))) + (with-helm-current-buffer + (org-insert-link + file-name (concat "file:" file-name "::*" heading-name)))))) + +(defun helm-org-run-insert-link-to-heading-at-marker () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action + 'helm-org-insert-link-to-heading-at-marker))) + +(defun helm-org--refile-heading-to (marker) + "Refile headings to heading at MARKER. +If multiple candidates are marked in the Helm session, they will +all be refiled. If no headings are marked, the selected heading +will be refiled." + (let* ((victims (with-helm-buffer (helm-marked-candidates))) + (buffer (marker-buffer marker)) + (filename (buffer-file-name buffer)) + (rfloc (list nil filename nil marker))) + (when (and (= 1 (length victims)) + (equal (helm-get-selection) (car victims))) + ;; No candidates are marked; we are refiling the entry at point + ;; to the selected heading + (setq victims (list (point)))) + ;; Probably best to check that everything returned a value + (when (and victims buffer filename rfloc) + (cl-loop for victim in victims + do (org-with-point-at victim + (org-refile nil nil rfloc)))))) + +(defun helm-org-in-buffer-preselect () + (if (org-on-heading-p) + (buffer-substring-no-properties (point-at-bol) (point-at-eol)) + (save-excursion + (outline-previous-visible-heading 1) + (buffer-substring-no-properties (point-at-bol) (point-at-eol))))) + +(defun helm-org-run-refile-heading-to () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-org--refile-heading-to))) +(put 'helm-org-run-refile-heading-to 'helm-only t) + +;;;###autoload +(defun helm-org-agenda-files-headings () + "Preconfigured helm for org files headings." + (interactive) + (let ((autosaves (cl-loop for f in (org-agenda-files) + when (file-exists-p + (expand-file-name + (concat "#" (helm-basename f) "#") + (helm-basedir f))) + collect (helm-basename f)))) + (when (or (null autosaves) + helm-org-ignore-autosaves + (y-or-n-p (format "%s have auto save data, continue?" + (mapconcat 'identity autosaves ", ")))) + (helm :sources (helm-source-org-headings-for-files (org-agenda-files)) + :candidate-number-limit 99999 + :truncate-lines helm-org-truncate-lines + :buffer "*helm org headings*")))) + +;;;###autoload +(defun helm-org-in-buffer-headings () + "Preconfigured helm for org buffer headings." + (interactive) + (let (helm-org-show-filename) + (helm :sources (helm-source-org-headings-for-files + (list (current-buffer))) + :candidate-number-limit 99999 + :preselect (helm-org-in-buffer-preselect) + :truncate-lines helm-org-truncate-lines + :buffer "*helm org inbuffer*"))) + +;;;###autoload +(defun helm-org-parent-headings () + "Preconfigured helm for org headings that are parents of the +current heading." + (interactive) + ;; Use a large max-depth to ensure all parents are displayed. + (let ((helm-org-headings-min-depth 1) + (helm-org-headings-max-depth 50)) + (helm :sources (helm-source-org-headings-for-files + (list (current-buffer)) t) + :candidate-number-limit 99999 + :truncate-lines helm-org-truncate-lines + :buffer "*helm org parent headings*"))) + +;;;###autoload +(defun helm-org-capture-templates () + "Preconfigured helm for org templates." + (interactive) + (helm :sources (helm-source-org-capture-templates) + :candidate-number-limit 99999 + :truncate-lines helm-org-truncate-lines + :buffer "*helm org capture templates*")) + +;;; Org tag completion + +;; Based on code from Anders Johansson posted on 3 Mar 2016 at +;; + +(defvar crm-separator) + +;;;###autoload +(defun helm-org-completing-read-tags (prompt collection pred req initial + hist def inherit-input-method _name _buffer) + "Completing read function for Org tags. + +This function is used as a `completing-read' function in +`helm-completing-read-handlers-alist' by `org-set-tags' and +`org-capture'. + +NOTE: Org tag completion will work only if you disable org fast tag +selection, see (info \"(org) setting tags\")." + (if (not (string= "Tags: " prompt)) + ;; Not a tags prompt. Use normal completion by calling + ;; `org-icompleting-read' again without this function in + ;; `helm-completing-read-handlers-alist' + (let ((helm-completing-read-handlers-alist + (rassq-delete-all + 'helm-org-completing-read-tags + (copy-alist helm-completing-read-handlers-alist)))) + (org-icompleting-read + prompt collection pred req initial hist def inherit-input-method)) + ;; Tags prompt + (let* ((curr (and (stringp initial) + (not (string= initial "")) + (org-split-string initial ":"))) + (table (delete curr + (org-uniquify + (mapcar 'car org-last-tags-completion-table)))) + (crm-separator ":\\|,\\|\\s-")) + (cl-letf (((symbol-function 'crm-complete-word) + 'self-insert-command)) + (mapconcat 'identity + (completing-read-multiple + prompt table pred nil initial hist def) + ":"))))) + +(provide 'helm-org) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-org.el ends here diff --git a/elpa/helm-20181113.923/helm-pkg.el b/elpa/helm-20181113.923/helm-pkg.el new file mode 100644 index 00000000..44fad715 --- /dev/null +++ b/elpa/helm-20181113.923/helm-pkg.el @@ -0,0 +1,9 @@ +(define-package "helm" "20181113.923" "Helm is an Emacs incremental and narrowing framework" + '((emacs "24.4") + (async "1.9.3") + (popup "0.5.3") + (helm-core "3.0")) + :url "https://emacs-helm.github.io/helm/") +;; Local Variables: +;; no-byte-compile: t +;; End: diff --git a/elpa/helm-20181113.923/helm-regexp.el b/elpa/helm-20181113.923/helm-regexp.el new file mode 100644 index 00000000..f0edbbcd --- /dev/null +++ b/elpa/helm-20181113.923/helm-regexp.el @@ -0,0 +1,763 @@ +;;; helm-regexp.el --- In buffer regexp searching and replacement for helm. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'helm-utils) + +(declare-function helm-mm-split-pattern "helm-multi-match") + + +(defgroup helm-regexp nil + "Regexp related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-moccur-always-search-in-current nil + "Helm multi occur always search in current buffer when non--nil." + :group 'helm-regexp + :type 'boolean) + +(defcustom helm-moccur-use-ioccur-style-keys t + "Similar to `helm-grep-use-ioccur-style-keys' but for multi occur." + :group 'helm-regexp + :type 'boolean) + +(defcustom helm-moccur-auto-update-on-resume nil + "Allow auto updating helm-(m)occur buffer when outdated. +noask => Always update without asking +nil => Don't update but signal buffer needs update +never => Never update and do not signal buffer needs update +Any other non--nil value update after confirmation." + :group 'helm-regexp + :type '(radio :tag "Allow auto updating helm-(m)occur buffer when outdated." + (const :tag "Always update without asking" noask) + (const :tag "Never update and do not signal buffer needs update" never) + (const :tag "Don't update but signal buffer needs update" nil) + (const :tag "Update after confirmation" t))) + +(defcustom helm-source-multi-occur-actions + '(("Go to Line" . helm-moccur-goto-line) + ("Goto line other window (C-u vertically)" . helm-moccur-goto-line-ow) + ("Goto line new frame" . helm-moccur-goto-line-of)) + "Actions for helm-occur and helm-moccur." + :group 'helm-regexp + :type '(alist :key-type string :value-type function)) + +(defcustom helm-moccur-truncate-lines t + "When nil the (m)occur line that appears will not be truncated." + :group 'helm-regexp + :type 'boolean) + +(defcustom helm-moccur-show-buffer-fontification nil + "Show fontification of searched buffer in results when non nil. + +This enable or disable fontification globally in results, but you can +override this default setting with `helm-moccur-buffer-substring-fn-for-modes'." + :group 'helm-regexp + :type '(radio :tag "Allow preserving fontification of searched buffer in results" + (const :tag "Don't preserve buffer fontification" nil) + (const :tag "Preserve buffer fontification" t))) + +(defcustom helm-moccur-buffer-substring-fn-for-modes + '((mu4e-headers-mode . buffer-substring) + (package-menu-mode . buffer-substring-no-properties)) + "Alist that allow configuring the function to use for storing a buffer. + +Can be one of `buffer-substring' or `buffer-substring-no-properties'. +Allow overriding the global effect of `helm-moccur-show-buffer-fontification' +for a specific mode." + :group 'helm-regexp + :type '(alist :key-type (symbol :tag "Mode") + :value-type (radio (const :tag "With text properties" buffer-substring) + (const :tag "Without text properties" buffer-substring-no-properties)))) + +(defcustom helm-occur-show-buffer-name nil + "Show buffer name in `helm-occur' results when non-nil. + +Not that this doesn't affect `helm-moccur' results and +`helm-moccur-mode' buffers where buffer names are always shown." + :group 'helm-regexp + :type 'boolean) + +(defface helm-moccur-buffer + '((t (:foreground "DarkTurquoise" :underline t))) + "Face used to highlight moccur buffer names." + :group 'helm-regexp) + +(defface helm-resume-need-update + '((t (:background "red"))) + "Face used to flash moccur buffer when it needs update." + :group 'helm-regexp) + + +(defvar helm-moccur-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-") 'helm-goto-next-file) + (define-key map (kbd "M-") 'helm-goto-precedent-file) + (define-key map (kbd "C-c o") 'helm-moccur-run-goto-line-ow) + (define-key map (kbd "C-c C-o") 'helm-moccur-run-goto-line-of) + (define-key map (kbd "C-x C-s") 'helm-moccur-run-save-buffer) + (when helm-moccur-use-ioccur-style-keys + (define-key map (kbd "") 'helm-execute-persistent-action) + (define-key map (kbd "") 'helm-moccur-run-default-action)) + (delq nil map)) + "Keymap used in Moccur source.") + + +;; History vars +(defvar helm-build-regexp-history nil) +(defvar helm-occur-history nil) + +(defun helm-query-replace-regexp (_candidate) + "Query replace regexp from `helm-regexp'. +With a prefix arg replace only matches surrounded by word boundaries, +i.e Don't replace inside a word, regexp is surrounded with \\bregexp\\b." + (let ((regexp helm-input)) + (apply 'query-replace-regexp + (helm-query-replace-args regexp)))) + +(defun helm-kill-regexp-as-sexp (_candidate) + "Kill regexp in a format usable in lisp code." + (helm-regexp-kill-new + (prin1-to-string helm-input))) + +(defun helm-kill-regexp (_candidate) + "Kill regexp as it is in `helm-pattern'." + (helm-regexp-kill-new helm-input)) + +(defun helm-query-replace-args (regexp) + "create arguments of `query-replace-regexp' action in `helm-regexp'." + (let ((region-only (helm-region-active-p))) + (list + regexp + (query-replace-read-to regexp + (format "Query replace %sregexp %s" + (if helm-current-prefix-arg "word " "") + (if region-only "in region " "")) + t) + helm-current-prefix-arg + (when region-only (region-beginning)) + (when region-only (region-end))))) + +(defvar helm-source-regexp + (helm-build-in-buffer-source "Regexp Builder" + :init (lambda () + (helm-init-candidates-in-buffer + 'global (with-temp-buffer + (insert-buffer-substring helm-current-buffer) + (buffer-string)))) + :get-line #'helm-regexp-get-line + :persistent-action #'helm-regexp-persistent-action + :persistent-help "Show this line" + :multiline t + :multimatch nil + :requires-pattern 2 + :group 'helm-regexp + :mode-line "Press TAB to select action." + :action '(("Kill Regexp as sexp" . helm-kill-regexp-as-sexp) + ("Query Replace Regexp (C-u Not inside word.)" + . helm-query-replace-regexp) + ("Kill Regexp" . helm-kill-regexp)))) + +(defun helm-regexp-get-line (s e) + (let ((matches (match-data)) + (line (buffer-substring s e))) + (propertize + (cl-loop with ln = (format "%5d: %s" (1- (line-number-at-pos s)) line) + for i from 0 to (1- (/ (length matches) 2)) + if (match-string i) + concat (format "\n%s%s'%s'" + (make-string 10 ? ) (format "Group %d: " i) it) + into ln1 + finally return (concat ln ln1)) + 'helm-realvalue s))) + +(defun helm-regexp-persistent-action (pt) + (helm-goto-char pt) + (helm-highlight-current-line)) + +(defun helm-regexp-kill-new (input) + (kill-new (substring-no-properties input)) + (message "Killed: %s" input)) + + +;;; Occur +;; +;; +(defvar helm-source-occur nil) +(defun helm-occur-init-source () + (unless helm-source-occur + (setq helm-source-occur + (helm-make-source "Occur" 'helm-source-multi-occur)))) + + +;;; Multi occur +;; +;; + +;; Internal +(defvar helm-multi-occur-buffer-list nil) +(defvar helm-multi-occur-buffer-tick nil) +(defvar helm-occur--invisible nil + "[INTERNAL] Hide buffer name in results when non-nil. +Should be a local var to helm-buffer to allow resuming.") + +(defun helm-moccur-init () + "Create the initial helm multi occur buffer." + (helm-init-candidates-in-buffer + 'global + (cl-loop with buffers = (helm-attr 'moccur-buffers) + with bsubstring = (if helm-moccur-show-buffer-fontification + #'buffer-substring #'buffer-substring-no-properties) + for buf in buffers + for bufstr = (with-current-buffer buf + (helm-aif (assq major-mode + helm-moccur-buffer-substring-fn-for-modes) + (setq bsubstring (cdr it))) + ;; A leading space is needed to allow helm + ;; searching the first line of buffer + ;; (#1725). + (concat (if (memql (char-after (point-min)) + '(? ?\t ?\n)) + "" " ") + (funcall bsubstring (point-min) (point-max)))) + do (add-text-properties + 0 (length bufstr) + `(buffer-name ,(buffer-name (get-buffer buf))) + bufstr) + concat bufstr))) + +(defun helm-moccur--next-or-previous-char () + (save-excursion + (or (re-search-forward "^." nil t) + (re-search-backward "^." nil t)))) + +(defun helm-moccur-get-line (beg end) + "Format line for `helm-source-moccur'." + (prog1 + (format "%s:%d:%s" + (get-text-property (if (= beg end) + (helm-moccur--next-or-previous-char) + beg) + 'buffer-name) + (save-restriction + (narrow-to-region (or (previous-single-property-change + (point) 'buffer-name) + (point-at-bol 2)) + (or (next-single-property-change + (if (= beg end) + (helm-moccur--next-or-previous-char) + (point)) + 'buffer-name) + (point-max))) + (line-number-at-pos beg)) + ;; When matching empty line, use empty string + ;; to allow saving and modifying with wgrep. + (if (= beg end) "" (buffer-substring beg end))) + ;; When matching empty line, forward char ("\n") + ;; to not be blocked forever here. + (when (= beg end) (forward-char 1)))) + +(cl-defun helm-moccur-action (candidate + &optional (method (quote buffer))) + "Jump to CANDIDATE with METHOD. +arg METHOD can be one of buffer, buffer-other-window, buffer-other-frame." + (require 'helm-grep) + (let* ((split (helm-grep-split-line candidate)) + (buf (car split)) + (lineno (string-to-number (nth 1 split))) + (split-pat (helm-mm-split-pattern helm-input))) + (cl-case method + (buffer (switch-to-buffer buf)) + (buffer-other-window (helm-window-show-buffers (list buf) t)) + (buffer-other-frame (switch-to-buffer-other-frame buf))) + (with-current-buffer buf + (helm-goto-line lineno) + ;; Move point to the nearest matching regexp from bol. + (cl-loop for reg in split-pat + when (save-excursion + (condition-case _err + (if helm-migemo-mode + (helm-mm-migemo-forward reg (point-at-eol) t) + (re-search-forward reg (point-at-eol) t)) + (invalid-regexp nil))) + collect (match-beginning 0) into pos-ls + finally (when pos-ls (goto-char (apply #'min pos-ls))))))) + +(defun helm-moccur-persistent-action (candidate) + (helm-moccur-goto-line candidate) + (helm-highlight-current-line)) + +(defun helm-moccur-goto-line (candidate) + "From multi occur, switch to buffer and go to nth 1 CANDIDATE line." + (helm-moccur-action + candidate 'buffer)) + +(defun helm-moccur-goto-line-ow (candidate) + "Go to CANDIDATE line in other window. +Same as `helm-moccur-goto-line' but go in other window." + (helm-moccur-action + candidate 'buffer-other-window)) + +(defun helm-moccur-goto-line-of (candidate) + "Go to CANDIDATE line in new frame. +Same as `helm-moccur-goto-line' but go in new frame." + (helm-moccur-action + candidate 'buffer-other-frame)) + +(defun helm-moccur-run-goto-line-ow () + "Run goto line other window action from `helm-source-moccur'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-moccur-goto-line-ow))) +(put 'helm-moccur-run-goto-line-ow 'helm-only t) + +(defun helm-moccur-run-goto-line-of () + "Run goto line new frame action from `helm-source-moccur'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-moccur-goto-line-of))) +(put 'helm-moccur-run-goto-line-of 'helm-only t) + +(defun helm-moccur-run-default-action () + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-moccur-goto-line))) +(put 'helm-moccur-run-default-action 'helm-only t) + +(defvar helm-moccur-before-init-hook nil + "Hook that runs before initialization of the helm buffer.") + +(defvar helm-moccur-after-init-hook nil + "Hook that runs after initialization of the helm buffer.") + +(defvar helm-source-moccur nil) +(defclass helm-source-multi-occur (helm-source-in-buffer) + ((init :initform (lambda () + (require 'helm-grep) + (helm-moccur-init))) + (filter-one-by-one :initform 'helm-moccur-filter-one-by-one) + (get-line :initform helm-moccur-get-line) + (nohighlight :initform t) + (nomark :initform t) + (migemo :initform t) + (action :initform 'helm-source-multi-occur-actions) + (persistent-action :initform 'helm-moccur-persistent-action) + (persistent-help :initform "Go to line") + (resume :initform 'helm-moccur-resume-fn) + (candidate-number-limit :initform 9999) + (help-message :initform 'helm-moccur-help-message) + (keymap :initform helm-moccur-map) + (history :initform 'helm-occur-history) + (requires-pattern :initform 2) + (before-init-hook :initform 'helm-moccur-before-init-hook) + (after-init-hook :initform 'helm-moccur-after-init-hook) + (group :initform 'helm-regexp))) + +(defun helm-moccur-resume-fn () + (with-helm-buffer + (let (new-tick-ls buffer-is-modified) + (set (make-local-variable 'helm-multi-occur-buffer-list) + (cl-loop for b in helm-multi-occur-buffer-list + when (buffer-live-p (get-buffer b)) + collect b)) + (setq buffer-is-modified (/= (length helm-multi-occur-buffer-list) + (length (helm-attr 'moccur-buffers)))) + (helm-attrset 'moccur-buffers helm-multi-occur-buffer-list) + (setq new-tick-ls (cl-loop for b in helm-multi-occur-buffer-list + collect (buffer-chars-modified-tick (get-buffer b)))) + (when buffer-is-modified + (setq helm-multi-occur-buffer-tick new-tick-ls)) + (cl-assert (> (length helm-multi-occur-buffer-list) 0) nil + "helm-resume error: helm-(m)occur buffer list is empty") + (unless (eq helm-moccur-auto-update-on-resume 'never) + (when (or buffer-is-modified + (cl-loop for b in helm-multi-occur-buffer-list + for new-tick = (buffer-chars-modified-tick (get-buffer b)) + for tick in helm-multi-occur-buffer-tick + thereis (/= tick new-tick))) + (helm-aif helm-moccur-auto-update-on-resume + (when (or (eq it 'noask) + (y-or-n-p "Helm (m)occur Buffer outdated, update? ")) + (run-with-idle-timer 0.1 nil (lambda () + (with-helm-buffer + (helm-force-update) + (message "Helm (m)occur Buffer have been udated") + (sit-for 1) (message nil)))) + (unless buffer-is-modified (setq helm-multi-occur-buffer-tick new-tick-ls))) + (run-with-idle-timer 0.1 nil (lambda () + (with-helm-buffer + (let ((ov (make-overlay (save-excursion + (goto-char (point-min)) + (forward-line 1) + (point)) + (point-max)))) + (overlay-put ov 'face 'helm-resume-need-update) + (sit-for 0.3) (delete-overlay ov) + (message "[Helm occur Buffer outdated (C-c C-u to update)]"))))) + (unless buffer-is-modified + (with-helm-after-update-hook + (setq helm-multi-occur-buffer-tick new-tick-ls) + (message "Helm (m)occur Buffer have been udated"))))))))) + +(defun helm-moccur-filter-one-by-one (candidate &optional outside-helm) + "`filter-one-by-one' function for `helm-source-moccur'." + (require 'helm-grep) + (let* ((split (helm-grep-split-line candidate)) + (buf (car split)) + (lineno (nth 1 split)) + (str (nth 2 split))) + (cons (concat (propertize + buf + 'invisible (and (null outside-helm) + (with-helm-buffer + helm-occur--invisible)) + 'face 'helm-moccur-buffer + 'help-echo (buffer-file-name + (get-buffer buf)) + 'buffer-name buf) + (propertize ":" 'invisible (and (null outside-helm) + (with-helm-buffer + helm-occur--invisible))) + (propertize lineno 'face 'helm-grep-lineno) + ":" + (helm-grep-highlight-match str t)) + candidate))) + +(defun helm-multi-occur-1 (buffers &optional input) + "Main function to call `helm-source-moccur' with BUFFERS list." + (let ((bufs (if helm-moccur-always-search-in-current + (cons + ;; will become helm-current-buffer later. + (buffer-name (current-buffer)) + (remove helm-current-buffer buffers)) + buffers))) + (unless helm-source-moccur + (setq helm-source-moccur + (helm-make-source "Moccur" 'helm-source-multi-occur))) + (helm-attrset 'moccur-buffers bufs helm-source-moccur) + (helm-set-local-variable 'helm-multi-occur-buffer-list bufs) + (helm-set-local-variable + 'helm-multi-occur-buffer-tick + (cl-loop for b in bufs + collect (buffer-chars-modified-tick (get-buffer b))))) + (helm :sources 'helm-source-moccur + :buffer "*helm multi occur*" + :default (helm-aif (thing-at-point 'symbol) (regexp-quote it)) + :history 'helm-occur-history + :keymap helm-moccur-map + :input input + :truncate-lines helm-moccur-truncate-lines)) + +(defun helm-moccur-run-save-buffer () + "Run moccur save results action from `helm-moccur'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-moccur-save-results))) +(put 'helm-moccur-run-save-buffer 'helm-only t) + + +;;; helm-moccur-mode +;; +;; +(defvar helm-moccur-mode-map + (let ((map (make-sparse-keymap))) + (define-key map (kbd "RET") 'helm-moccur-mode-goto-line) + (define-key map (kbd "C-o") 'helm-moccur-mode-goto-line-ow) + (define-key map (kbd "") 'helm-moccur-mode-goto-line-ow-forward) + (define-key map (kbd "") 'helm-moccur-mode-goto-line-ow-backward) + (define-key map (kbd "") 'helm-gm-next-file) + (define-key map (kbd "") 'helm-gm-precedent-file) + (define-key map (kbd "M-n") 'helm-moccur-mode-goto-line-ow-forward) + (define-key map (kbd "M-p") 'helm-moccur-mode-goto-line-ow-backward) + (define-key map (kbd "M-N") 'helm-gm-next-file) + (define-key map (kbd "M-P") 'helm-gm-precedent-file) + map)) + +(defun helm-moccur-mode-goto-line () + (interactive) + (helm-aif (get-text-property (point) 'helm-realvalue) + (progn (helm-moccur-goto-line it) (helm-match-line-cleanup-pulse)))) + +(defun helm-moccur-mode-goto-line-ow () + (interactive) + (helm-aif (get-text-property (point) 'helm-realvalue) + (progn (helm-moccur-goto-line-ow it) (helm-match-line-cleanup-pulse)))) + +(defun helm-moccur-mode-goto-line-ow-forward-1 (arg) + (condition-case nil + (progn + (save-selected-window + (helm-moccur-mode-goto-line-ow) + (recenter)) + (forward-line arg)) + (error nil))) + +(defun helm-moccur-mode-goto-line-ow-forward () + (interactive) + (helm-moccur-mode-goto-line-ow-forward-1 1)) + +(defun helm-moccur-mode-goto-line-ow-backward () + (interactive) + (helm-moccur-mode-goto-line-ow-forward-1 -1)) + +(defun helm-moccur-save-results (_candidate) + "Save helm moccur results in a `helm-moccur-mode' buffer." + (let ((buf "*hmoccur*") + new-buf) + (when (get-buffer buf) + (setq new-buf (helm-read-string "OccurBufferName: " buf)) + (cl-loop for b in (helm-buffer-list) + when (and (string= new-buf b) + (not (y-or-n-p + (format "Buffer `%s' already exists overwrite? " + new-buf)))) + do (setq new-buf (helm-read-string "OccurBufferName: " "*hmoccur "))) + (setq buf new-buf)) + (with-current-buffer (get-buffer-create buf) + (setq buffer-read-only t) + (let ((inhibit-read-only t) + (map (make-sparse-keymap))) + (erase-buffer) + (insert "-*- mode: helm-moccur -*-\n\n" + (format "Moccur Results for `%s':\n\n" helm-input)) + (save-excursion + (insert (with-current-buffer helm-buffer + (goto-char (point-min)) (forward-line 1) + (buffer-substring (point) (point-max))))) + (save-excursion + (while (not (eobp)) + (add-text-properties + (point-at-bol) (point-at-eol) + `(keymap ,map + help-echo ,(concat + (buffer-file-name + (get-buffer (get-text-property + (point) 'buffer-name))) + "\nmouse-1: set point\nmouse-2: jump to selection") + mouse-face highlight + invisible nil)) + (define-key map [mouse-1] 'mouse-set-point) + (define-key map [mouse-2] 'helm-moccur-mode-mouse-goto-line) + (define-key map [mouse-3] 'ignore) + (forward-line 1)))) + (helm-moccur-mode)) + (pop-to-buffer buf) + (message "Helm Moccur Results saved in `%s' buffer" buf))) + +(defun helm-moccur-mode-mouse-goto-line (event) + (interactive "e") + (let* ((window (posn-window (event-end event))) + (pos (posn-point (event-end event)))) + (with-selected-window window + (when (eq major-mode 'helm-moccur-mode) + (goto-char pos) + (helm-moccur-mode-goto-line))))) +(put 'helm-moccur-mode-mouse-goto-line 'helm-only t) + +;;;###autoload +(define-derived-mode helm-moccur-mode + special-mode "helm-moccur" + "Major mode to provide actions in helm moccur saved buffer. + +Special commands: +\\{helm-moccur-mode-map}" + (set (make-local-variable 'helm-multi-occur-buffer-list) + (with-helm-buffer helm-multi-occur-buffer-list)) + (set (make-local-variable 'revert-buffer-function) + #'helm-moccur-mode--revert-buffer-function)) +(put 'helm-moccur-mode 'helm-only t) + +(defun helm-moccur-mode--revert-buffer-function (&optional _ignore-auto _noconfirm) + (goto-char (point-min)) + (let (pattern) + (when (re-search-forward "^Moccur Results for `\\(.*\\)'" nil t) + (setq pattern (match-string 1)) + (forward-line 0) + (when (re-search-forward "^$" nil t) + (forward-line 1)) + (let ((inhibit-read-only t) + (buffer (current-buffer)) + (buflst helm-multi-occur-buffer-list) + (bsubstring (if helm-moccur-show-buffer-fontification + #'buffer-substring #'buffer-substring-no-properties))) + (delete-region (point) (point-max)) + (message "Reverting buffer...") + (save-excursion + (with-temp-buffer + (insert + "\n" + (cl-loop for buf in buflst + for bufstr = (or (and (buffer-live-p (get-buffer buf)) + (with-current-buffer buf + (funcall bsubstring + (point-min) (point-max)))) + "") + unless (string= bufstr "") + do (add-text-properties + 0 (length bufstr) + `(buffer-name ,(buffer-name (get-buffer buf))) + bufstr) + concat bufstr) + "\n") + (goto-char (point-min)) + (cl-loop with helm-pattern = pattern + while (helm-mm-search pattern) + for line = (helm-moccur-get-line (point-at-bol) (point-at-eol)) + when line + do (with-current-buffer buffer + (insert + (propertize + (car (helm-moccur-filter-one-by-one line t)) + 'helm-realvalue line) + "\n"))))) + (message "Reverting buffer done"))))) + + +;;; Predefined commands +;; +;; + +;;;###autoload +(defun helm-regexp () + "Preconfigured helm to build regexps. +`query-replace-regexp' can be run from there against found regexp." + (interactive) + (save-restriction + (when (and (helm-region-active-p) + ;; Don't narrow to region if buffer is already narrowed. + (not (helm-current-buffer-narrowed-p (current-buffer)))) + (narrow-to-region (region-beginning) (region-end))) + (helm :sources helm-source-regexp + :buffer "*helm regexp*" + :prompt "Regexp: " + :history 'helm-build-regexp-history))) + +;;;###autoload +(defun helm-occur () + "Preconfigured helm for searching lines matching pattern in `current-buffer'. + +When `helm-source-occur' is member of +`helm-sources-using-default-as-input' which is the default, +symbol at point is searched at startup. + +When a region is marked search only in this region by narrowing. + +To search in multiples buffers start from one of the commands listing +buffers (i.e. a helm command using `helm-source-buffers-list' like +`helm-mini') and use the multi occur buffers action. + +This is the helm implementation that collect lines matching pattern +like vanilla emacs `occur' but have nothing to do with it, the search +engine beeing completely different." + (interactive) + (helm-occur-init-source) + (let ((bufs (list (buffer-name (current-buffer))))) + (helm-attrset 'moccur-buffers bufs helm-source-occur) + (helm-set-local-variable 'helm-multi-occur-buffer-list bufs) + (helm-set-local-variable + 'helm-multi-occur-buffer-tick + (cl-loop for b in bufs + collect (buffer-chars-modified-tick (get-buffer b))))) + (helm-set-local-variable 'helm-occur--invisible + (null helm-occur-show-buffer-name)) + (save-restriction + (let (def pos) + (when (use-region-p) + ;; When user mark defun with `mark-defun' with intention of + ;; using helm-occur on this region, it is relevant to use the + ;; thing-at-point located at previous position which have been + ;; pushed to `mark-ring'. + (setq def (save-excursion + (goto-char (setq pos (car mark-ring))) + (helm-aif (thing-at-point 'symbol) (regexp-quote it)))) + (narrow-to-region (region-beginning) (region-end))) + (unwind-protect + (helm :sources 'helm-source-occur + :buffer "*helm occur*" + :default (or def (helm-aif (thing-at-point 'symbol) (regexp-quote it))) + :history 'helm-occur-history + :preselect (and (memq 'helm-source-occur helm-sources-using-default-as-input) + (format "%s:%d:" (regexp-quote (buffer-name)) + (line-number-at-pos (or pos (point))))) + :truncate-lines helm-moccur-truncate-lines) + (deactivate-mark t))))) + +;;;###autoload +(defun helm-occur-from-isearch () + "Invoke `helm-occur' from isearch." + (interactive) + (let ((input (if isearch-regexp + isearch-string + (regexp-quote isearch-string))) + (bufs (list (buffer-name (current-buffer))))) + (isearch-exit) + (helm-occur-init-source) + (helm-attrset 'moccur-buffers bufs helm-source-occur) + (helm-set-local-variable 'helm-multi-occur-buffer-list bufs) + (helm-set-local-variable + 'helm-multi-occur-buffer-tick + (cl-loop for b in bufs + collect (buffer-chars-modified-tick (get-buffer b)))) + (helm-set-local-variable 'helm-occur--invisible + (null helm-occur-show-buffer-name)) + (helm :sources 'helm-source-occur + :buffer "*helm occur*" + :history 'helm-occur-history + :input input + :truncate-lines helm-moccur-truncate-lines))) + +;;;###autoload +(defun helm-multi-occur-from-isearch (&optional _arg) + "Invoke `helm-multi-occur' from isearch. + +With a prefix arg, reverse the behavior of +`helm-moccur-always-search-in-current'. +The prefix arg can be set before calling +`helm-multi-occur-from-isearch' or during the buffer selection." + (interactive "p") + (let (buf-list + helm-moccur-always-search-in-current + (input (if isearch-regexp + isearch-string + (regexp-quote isearch-string)))) + (isearch-exit) + (setq buf-list (helm-comp-read "Buffers: " + (helm-buffer-list) + :name "Occur in buffer(s)" + :marked-candidates t)) + (setq helm-moccur-always-search-in-current + (if (or current-prefix-arg + helm-current-prefix-arg) + (not helm-moccur-always-search-in-current) + helm-moccur-always-search-in-current)) + (helm-multi-occur-1 buf-list input))) + + +(provide 'helm-regexp) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-regexp.el ends here diff --git a/elpa/helm-20181113.923/helm-ring.el b/elpa/helm-20181113.923/helm-ring.el new file mode 100644 index 00000000..f744536b --- /dev/null +++ b/elpa/helm-20181113.923/helm-ring.el @@ -0,0 +1,559 @@ +;;; helm-ring.el --- kill-ring, mark-ring, and register browsers for helm. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-utils) +(require 'helm-help) +(require 'helm-elisp) + +(declare-function undo-tree-restore-state-from-register "ext:undo-tree.el" (register)) + + +(defgroup helm-ring nil + "Ring related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-kill-ring-threshold 3 + "Minimum length of a candidate to be listed by `helm-source-kill-ring'." + :type 'integer + :group 'helm-ring) + +(defcustom helm-kill-ring-max-offset 400 + "Max number of chars displayed per candidate in kill-ring browser. +When `t', don't truncate candidate, show all. +By default it is approximatively the number of bits contained in five lines +of 80 chars each i.e 80*5. +Note that if you set this to nil multiline will be disabled, i.e you +will not have anymore separators between candidates." + :type '(choice (const :tag "Disabled" t) + (integer :tag "Max candidate offset")) + :group 'helm-ring) + +(defcustom helm-kill-ring-actions + '(("Yank marked" . helm-kill-ring-action-yank) + ("Delete marked" . helm-kill-ring-action-delete)) + "List of actions for kill ring source." + :group 'helm-ring + :type '(alist :key-type string :value-type function)) + +(defcustom helm-kill-ring-separator "\n" + "The separator used to separate marked candidates when yanking." + :group 'helm-ring + :type 'string) + +(defcustom helm-register-max-offset 160 + "Max size of string register entries before truncating." + :group 'helm-ring + :type 'integer) + +;;; Kill ring +;; +;; +(defvar helm-kill-ring-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-y") 'helm-next-line) + (define-key map (kbd "M-u") 'helm-previous-line) + (define-key map (kbd "M-D") 'helm-kill-ring-delete) + (define-key map (kbd "C-]") 'helm-kill-ring-toggle-truncated) + (define-key map (kbd "C-c C-k") 'helm-kill-ring-kill-selection) + map) + "Keymap for `helm-show-kill-ring'.") + +(defvar helm-source-kill-ring + (helm-build-sync-source "Kill Ring" + :init (lambda () + (helm-attrset 'last-command last-command) + (helm-attrset 'multiline helm-kill-ring-max-offset)) + :candidates #'helm-kill-ring-candidates + :filtered-candidate-transformer #'helm-kill-ring-transformer + :action 'helm-kill-ring-actions + :persistent-action 'ignore + :help-message 'helm-kill-ring-help-message + :persistent-help "DoNothing" + :keymap helm-kill-ring-map + :migemo t + :multiline 'helm-kill-ring-max-offset + :group 'helm-ring) + "Source for browse and insert contents of kill-ring.") + +(defun helm-kill-ring-candidates () + (cl-loop for kill in (helm-fast-remove-dups kill-ring :test 'equal) + unless (or (< (length kill) helm-kill-ring-threshold) + (string-match "\\`[\n[:blank:]]+\\'" kill)) + collect kill)) + +(defun helm-kill-ring-transformer (candidates _source) + "Ensure CANDIDATES are not read-only." + (cl-loop for i in candidates + when (get-text-property 0 'read-only i) + do (set-text-properties 0 (length i) '(read-only nil) i) + collect i)) + +(defvar helm-kill-ring--truncated-flag nil) +(defun helm-kill-ring-toggle-truncated () + "Toggle truncated view of candidates in helm kill-ring browser." + (interactive) + (with-helm-alive-p + (setq helm-kill-ring--truncated-flag (not helm-kill-ring--truncated-flag)) + (let* ((cur-cand (helm-get-selection)) + (presel-fn (lambda () + (helm-kill-ring--preselect-fn cur-cand)))) + (helm-attrset 'multiline + (if helm-kill-ring--truncated-flag + 15000000 + helm-kill-ring-max-offset)) + (helm-update presel-fn)))) +(put 'helm-kill-ring-toggle-truncated 'helm-only t) + +(defun helm-kill-ring-kill-selection () + "Store the real value of candidate in kill-ring. +Same as `helm-kill-selection-and-quit' called with a prefix arg." + (interactive) + (helm-kill-selection-and-quit t)) +(put 'helm-kill-ring-kill-selection 'helm-only t) + +(defun helm-kill-ring--preselect-fn (candidate) + "Internal, used to preselect CANDIDATE when toggling truncated view." + ;; Preselection by regexp may not work if candidate is huge, so walk + ;; the helm buffer until selection is on CANDIDATE. + (helm-awhile (condition-case-unless-debug nil + (and (not (helm-pos-header-line-p)) + (helm-get-selection)) + (error nil)) + (if (string= it candidate) + (cl-return) + (helm-next-line)))) + +(defun helm-kill-ring-action-yank (_str) + "Insert concatenated marked candidates in current-buffer. + +When two prefix args are given prompt to choose separator, otherwise +use `helm-kill-ring-separator' as default." + (let ((marked (helm-marked-candidates)) + (sep (if (equal helm-current-prefix-arg '(16)) + (read-string "Separator: ") + helm-kill-ring-separator))) + (helm-kill-ring-action-yank-1 + (cl-loop for c in (butlast marked) + concat (concat c sep) into str + finally return (concat str (car (last marked))))))) + +(defun helm-kill-ring-action-yank-1 (str) + "Insert STR in `kill-ring' and set STR to the head. + +When called with a prefix arg, point and mark are exchanged without +activating region. +If this action is executed just after `yank', +replace with STR as yanked string." + (let ((yank-fn (lambda (&optional before yank-pop) + (insert-for-yank str) + ;; Set the window start back where it was in + ;; the yank command, if possible. + (when yank-pop + (set-window-start (selected-window) yank-window-start t)) + (when (or (equal helm-current-prefix-arg '(4)) before) + ;; Same as exchange-point-and-mark but without + ;; activating region. + (goto-char (prog1 (mark t) + (set-marker (mark-marker) + (point) + helm-current-buffer))))))) + ;; Prevent inserting and saving highlighted items. + (set-text-properties 0 (length str) nil str) + (with-helm-current-buffer + (unwind-protect + (progn + (setq kill-ring (delete str kill-ring)) + ;; Adding a `delete-selection' property + ;; to `helm-kill-ring-action' is not working + ;; because `this-command' will be `helm-maybe-exit-minibuffer', + ;; so use this workaround (Issue #1520). + (when (and (region-active-p) delete-selection-mode) + (delete-region (region-beginning) (region-end))) + (if (not (eq (helm-attr 'last-command helm-source-kill-ring) 'yank)) + (progn + ;; Ensure mark is at beginning of inserted text. + (push-mark) + ;; When yanking in a helm minibuffer we need a small + ;; delay to detect the mark in previous minibuffer. [1] + (run-with-timer 0.01 nil yank-fn)) + ;; from `yank-pop' + (let ((inhibit-read-only t) + (before (< (point) (mark t)))) + (if before + (funcall (or yank-undo-function 'delete-region) (point) (mark t)) + (funcall (or yank-undo-function 'delete-region) (mark t) (point))) + (setq yank-undo-function nil) + (set-marker (mark-marker) (point) helm-current-buffer) + ;; Same as [1] but use the same mark and point as in + ;; the initial yank according to BEFORE even if no + ;; prefix arg is given. + (run-with-timer 0.01 nil yank-fn before 'pop)))) + (kill-new str))))) +(define-obsolete-function-alias 'helm-kill-ring-action 'helm-kill-ring-action-yank "2.4.0") + +(defun helm-kill-ring-action-delete (_candidate) + "Delete marked candidates from `kill-ring'." + (cl-loop for c in (helm-marked-candidates) + do (setq kill-ring + (delete c kill-ring)))) + +(defun helm-kill-ring-delete () + "Delete marked candidates from `kill-ring'. + +This is a command for `helm-kill-ring-map'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action 'helm-kill-ring-action-delete))) + + +;;;; +;; DO NOT use these sources with other sources use +;; the commands `helm-mark-ring', `helm-global-mark-ring' or +;; `helm-all-mark-rings' instead. + +(defun helm-mark-ring-line-string-at-pos (pos) + "Return line string at position POS." + (save-excursion + (goto-char pos) + (forward-line 0) + (let ((line (car (split-string (thing-at-point 'line) "[\n\r]")))) + (remove-text-properties 0 (length line) '(read-only) line) + (if (string= "" line) + "" + line)))) + +(defun helm-mark-ring-get-candidates () + (with-helm-current-buffer + (cl-loop with marks = (if (mark t) + (cons (mark-marker) mark-ring) + mark-ring) + for marker in marks + with max-line-number = (line-number-at-pos (point-max)) + with width = (length (number-to-string max-line-number)) + for m = (format (concat "%" (number-to-string width) "d: %s") + (line-number-at-pos marker) + (helm-mark-ring-line-string-at-pos marker)) + unless (and recip (assoc m recip)) + collect (cons m marker) into recip + finally return recip))) + +(defun helm-mark-ring-default-action (candidate) + (let ((target (copy-marker candidate))) + (helm-aif (marker-buffer candidate) + (progn + (switch-to-buffer it) + (helm-log-run-hook 'helm-goto-line-before-hook) + (helm-match-line-cleanup) + (with-helm-current-buffer + (unless helm-yank-point (setq helm-yank-point (point)))) + (helm-goto-char target) + (helm-highlight-current-line)) + ;; marker points to no buffer, no need to dereference it, just + ;; delete it. + (setq mark-ring (delete target mark-ring)) + (error "Marker points to no buffer")))) + +(defvar helm-source-mark-ring + (helm-build-sync-source "mark-ring" + :candidates #'helm-mark-ring-get-candidates + :action '(("Goto line" . helm-mark-ring-default-action)) + :persistent-help "Show this line" + :group 'helm-ring)) + +;;; Global-mark-ring +(defvar helm-source-global-mark-ring + (helm-build-sync-source "global-mark-ring" + :candidates #'helm-global-mark-ring-get-candidates + :action '(("Goto line" . helm-mark-ring-default-action)) + :persistent-help "Show this line" + :group 'helm-ring)) + +(defun helm-global-mark-ring-format-buffer (marker) + (with-current-buffer (marker-buffer marker) + (goto-char marker) + (forward-line 0) + (let ((line (pcase (thing-at-point 'line) + ((and line (pred stringp) + (guard (not (string-match-p "\\`\n?\\'" line)))) + (car (split-string line "[\n\r]"))) + (_ "")))) + (remove-text-properties 0 (length line) '(read-only) line) + (format "%7d:%s: %s" + (line-number-at-pos) (marker-buffer marker) line)))) + +(defun helm-global-mark-ring-get-candidates () + (let ((marks global-mark-ring)) + (when marks + (cl-loop for marker in marks + for mb = (marker-buffer marker) + for gm = (unless (or (string-match "^ " (format "%s" mb)) + (null mb)) + (helm-global-mark-ring-format-buffer marker)) + when (and gm (not (assoc gm recip))) + collect (cons gm marker) into recip + finally return recip)))) + +;;;; +;;; Insert from register +(defvar helm-source-register + (helm-build-sync-source "Registers" + :candidates #'helm-register-candidates + :action-transformer #'helm-register-action-transformer + :persistent-help "" + :multiline t + :action '(("Delete Register(s)" . + (lambda (_candidate) + (cl-loop for candidate in (helm-marked-candidates) + for register = (car candidate) + do (setq register-alist + (delq (assoc register register-alist) + register-alist)))))) + :group 'helm-ring) + "See (info \"(emacs)Registers\")") + +(defun helm-register-candidates () + "Collecting register contents and appropriate commands." + (cl-loop for (char . val) in register-alist + for key = (single-key-description char) + for string-actions = + (cond + ((numberp val) + (list (int-to-string val) + 'insert-register + 'increment-register)) + ((markerp val) + (let ((buf (marker-buffer val))) + (if (null buf) + (list "a marker in no buffer") + (list (concat + "a buffer position:" + (buffer-name buf) + ", position " + (int-to-string (marker-position val))) + 'jump-to-register + 'insert-register)))) + ((and (consp val) (window-configuration-p (car val))) + (list "window configuration." + 'jump-to-register)) + ((and (vectorp val) + (fboundp 'undo-tree-register-data-p) + (undo-tree-register-data-p (elt val 1))) + (list + "Undo-tree entry." + 'undo-tree-restore-state-from-register)) + ((or (and (vectorp val) (eq 'registerv (aref val 0))) + (and (consp val) (frame-configuration-p (car val)))) + (list "frame configuration." + 'jump-to-register)) + ((and (consp val) (eq (car val) 'file)) + (list (concat "file:" + (prin1-to-string (cdr val)) + ".") + 'jump-to-register)) + ((and (consp val) (eq (car val) 'file-query)) + (list (concat "file:a file-query reference: file " + (car (cdr val)) + ", position " + (int-to-string (car (cdr (cdr val)))) + ".") + 'jump-to-register)) + ((consp val) + (let ((lines (format "%4d" (length val)))) + (list (format "%s: %s\n" lines + (truncate-string-to-width + (mapconcat 'identity (list (car val)) + "^J") (- (window-width) 15))) + 'insert-register))) + ((stringp val) + (list + ;; without properties + (concat (substring-no-properties + val 0 (min (length val) helm-register-max-offset)) + (if (> (length val) helm-register-max-offset) + "[...]" "")) + 'insert-register + 'append-to-register + 'prepend-to-register))) + unless (null string-actions) ; Fix Issue #1107. + collect (cons (format "Register %3s:\n %s" key (car string-actions)) + (cons char (cdr string-actions))))) + +(defun helm-register-action-transformer (actions register-and-functions) + "Decide actions by the contents of register." + (cl-loop with func-actions = + '((insert-register + "Insert Register" . + (lambda (c) (insert-register (car c)))) + (jump-to-register + "Jump to Register" . + (lambda (c) (jump-to-register (car c)))) + (append-to-register + "Append Region to Register" . + (lambda (c) (append-to-register + (car c) (region-beginning) (region-end)))) + (prepend-to-register + "Prepend Region to Register" . + (lambda (c) (prepend-to-register + (car c) (region-beginning) (region-end)))) + (increment-register + "Increment Prefix Arg to Register" . + (lambda (c) (increment-register + helm-current-prefix-arg (car c)))) + (undo-tree-restore-state-from-register + "Restore Undo-tree register" . + (lambda (c) (and (fboundp 'undo-tree-restore-state-from-register) + (undo-tree-restore-state-from-register (car c)))))) + for func in (cdr register-and-functions) + when (assq func func-actions) + collect (cdr it) into transformer-actions + finally return (append transformer-actions actions))) + +;;;###autoload +(defun helm-mark-ring () + "Preconfigured `helm' for `helm-source-mark-ring'." + (interactive) + (helm :sources 'helm-source-mark-ring + :resume 'noresume + :buffer "*helm mark*")) + +;;;###autoload +(defun helm-global-mark-ring () + "Preconfigured `helm' for `helm-source-global-mark-ring'." + (interactive) + (helm :sources 'helm-source-global-mark-ring + :resume 'noresume + :buffer "*helm global mark*")) + +;;;###autoload +(defun helm-all-mark-rings () + "Preconfigured `helm' for `helm-source-global-mark-ring' and \ +`helm-source-mark-ring'." + (interactive) + (helm :sources '(helm-source-mark-ring + helm-source-global-mark-ring) + :resume 'noresume + :buffer "*helm mark ring*")) + +;;;###autoload +(defun helm-register () + "Preconfigured `helm' for Emacs registers." + (interactive) + (helm :sources 'helm-source-register + :resume 'noresume + :buffer "*helm register*")) + +;;;###autoload +(defun helm-show-kill-ring () + "Preconfigured `helm' for `kill-ring'. +It is drop-in replacement of `yank-pop'. + +First call open the kill-ring browser, next calls move to next line." + (interactive) + (setq helm-kill-ring--truncated-flag nil) + (let ((enable-recursive-minibuffers t)) + (helm :sources helm-source-kill-ring + :buffer "*helm kill ring*" + :resume 'noresume + :allow-nest t))) + +;;;###autoload +(defun helm-execute-kmacro () + "Preconfigured helm for keyboard macros. +Define your macros with `f3' and `f4'. +See (info \"(emacs) Keyboard Macros\") for detailed infos. +This command is useful when used with persistent action." + (interactive) + (let ((helm-quit-if-no-candidate + (lambda () (message "No kbd macro has been defined")))) + (helm :sources + (helm-build-sync-source "Kmacro" + :candidates (lambda () + (helm-fast-remove-dups + (cons (kmacro-ring-head) + kmacro-ring) + :test 'equal)) + :multiline t + :candidate-transformer + (lambda (candidates) + (cl-loop for c in candidates collect + (propertize (help-key-description (car c) nil) + 'helm-realvalue c))) + :persistent-help "Execute kmacro" + :help-message 'helm-kmacro-help-message + :action + (helm-make-actions + "Execute kmacro (`C-u ' to execute times)" + 'helm-kbd-macro-execute + "Concat marked macros" + 'helm-kbd-macro-concat-macros + "Delete marked macros" + 'helm-kbd-macro-delete-macro + "Edit marked macro" + 'helm-kbd-macro-edit-macro) + :group 'helm-ring) + :buffer "*helm kmacro*"))) + +(defun helm-kbd-macro-execute (candidate) + ;; Move candidate on top of list for next use. + (setq kmacro-ring (delete candidate kmacro-ring)) + (kmacro-push-ring) + (kmacro-split-ring-element candidate) + (kmacro-exec-ring-item + candidate helm-current-prefix-arg)) + +(defun helm-kbd-macro-concat-macros (_candidate) + (let ((mkd (helm-marked-candidates))) + (when (cdr mkd) + (kmacro-push-ring) + (setq last-kbd-macro + (mapconcat 'identity + (cl-loop for km in mkd + if (vectorp km) + append (cl-loop for k across km collect + (key-description (vector k))) + into result + else collect (car km) into result + finally return result) + ""))))) + +(defun helm-kbd-macro-delete-macro (_candidate) + (let ((mkd (helm-marked-candidates))) + (kmacro-push-ring) + (cl-loop for km in mkd + do (setq kmacro-ring (delete km kmacro-ring))) + (kmacro-pop-ring1))) + +(defun helm-kbd-macro-edit-macro (candidate) + (kmacro-push-ring) + (setq kmacro-ring (delete candidate kmacro-ring)) + (kmacro-split-ring-element candidate) + (kmacro-edit-macro)) + +(provide 'helm-ring) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-ring.el ends here diff --git a/elpa/helm-20181113.923/helm-semantic.el b/elpa/helm-20181113.923/helm-semantic.el new file mode 100644 index 00000000..dcb55e09 --- /dev/null +++ b/elpa/helm-20181113.923/helm-semantic.el @@ -0,0 +1,231 @@ +;;; helm-semantic.el --- Helm interface for Semantic -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2017 Daniel Hackney +;; 2012 ~ 2018 Thierry Volpiatto + +;; Author: Daniel Hackney + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Commentary: + +;; Uses `candidates-in-buffer' for speed. + +;;; Code: + +(require 'cl-lib) +(require 'semantic) +(require 'helm-help) +(require 'helm-imenu) + +(declare-function pulse-momentary-highlight-one-line "pulse.el" (point &optional face)) + +(defgroup helm-semantic nil + "Semantic tags related libraries and applications for helm." + :group 'helm) + +(defcustom helm-semantic-lynx-style-map t + "Use Arrow keys to jump to occurences." + :group 'helm-semantic + :type 'boolean) + +(defcustom helm-semantic-display-style + '((python-mode . semantic-format-tag-summarize) + (c-mode . semantic-format-tag-concise-prototype-c-mode) + (emacs-lisp-mode . semantic-format-tag-abbreviate-emacs-lisp-mode)) + "Function to present a semantic tag according to `major-mode'. + +It is an alist where the `car' of each element is a `major-mode' and +the `cdr' a `semantic-format-tag-*' function. + +If no function is found for current `major-mode', fall back to +`semantic-format-tag-summarize' default function. + +You can have more or less informations depending of the `semantic-format-tag-*' +function you choose. + +All the supported functions are prefixed with \"semantic-format-tag-\", +you have completion on these functions with `C-M i' in the customize interface." + :group 'helm-semantic + :type '(alist :key-type symbol :value-type symbol)) + +;;; keymap +(defvar helm-semantic-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (when helm-semantic-lynx-style-map + (define-key map (kbd "") 'helm-maybe-exit-minibuffer) + (define-key map (kbd "") 'helm-execute-persistent-action)) + (delq nil map))) + +;; Internals vars +(defvar helm-semantic--tags-cache nil) + +(defun helm-semantic--fetch-candidates (tags depth &optional class) + "Write the contents of TAGS to the current buffer." + (let ((class class) cur-type + (stylefn (or (with-helm-current-buffer + (assoc-default major-mode helm-semantic-display-style)) + #'semantic-format-tag-summarize))) + (cl-dolist (tag tags) + (when (listp tag) + (cl-case (setq cur-type (semantic-tag-class tag)) + ((function variable type) + (let ((spaces (make-string (* depth 2) ?\s)) + (type-p (eq cur-type 'type))) + (unless (and (> depth 0) (not type-p)) + (setq class nil)) + (insert + (if (and class (not type-p)) + (format "%s%s(%s) " + spaces (if (< depth 2) "" "├►") class) + spaces) + ;; Save the tag for later + (propertize (funcall stylefn tag nil t) + 'semantic-tag tag) + "\n") + (and type-p (setq class (car tag))) + ;; Recurse to children + (unless (eq cur-type 'function) + (helm-semantic--fetch-candidates + (semantic-tag-components tag) (1+ depth) class)))) + + ;; Don't do anything with packages or includes for now + ((package include) + (insert + (propertize (funcall stylefn tag nil t) + 'semantic-tag tag) + "\n") + ) + ;; Catch-all + (t)))))) + +(defun helm-semantic-default-action (_candidate &optional persistent) + ;; By default, helm doesn't pass on the text properties of the selection. + ;; Fix this. + (helm-log-run-hook 'helm-goto-line-before-hook) + (with-current-buffer helm-buffer + (when (looking-at " ") + (goto-char (next-single-property-change + (point-at-bol) 'semantic-tag nil (point-at-eol)))) + (let ((tag (get-text-property (point) 'semantic-tag))) + (semantic-go-to-tag tag) + (unless persistent + (pulse-momentary-highlight-one-line (point)))))) + +(defun helm-semantic--maybe-set-needs-update () + (with-helm-current-buffer + (when (semantic-parse-tree-needs-update-p) + (semantic-parse-tree-set-needs-update)))) + +(defvar helm-source-semantic nil) + +(defclass helm-semantic-source (helm-source-in-buffer) + ((init :initform (lambda () + (helm-semantic--maybe-set-needs-update) + (setq helm-semantic--tags-cache (semantic-fetch-tags)) + (with-current-buffer (helm-candidate-buffer 'global) + (let ((major-mode (with-helm-current-buffer major-mode))) + (helm-semantic--fetch-candidates helm-semantic--tags-cache 0))))) + (get-line :initform 'buffer-substring) + (persistent-help :initform "Show this entry") + (keymap :initform 'helm-semantic-map) + (help-message :initform 'helm-semantic-help-message) + (persistent-action :initform (lambda (elm) + (helm-semantic-default-action elm t) + (helm-highlight-current-line))) + (action :initform 'helm-semantic-default-action))) + +(defcustom helm-semantic-fuzzy-match nil + "Enable fuzzy matching in `helm-source-semantic'." + :group 'helm-semantic + :type 'boolean + :set (lambda (var val) + (set var val) + (setq helm-source-semantic + (helm-make-source "Semantic Tags" 'helm-semantic-source + :fuzzy-match helm-semantic-fuzzy-match)))) + +;;;###autoload +(defun helm-semantic (arg) + "Preconfigured `helm' for `semantic'. +If ARG is supplied, pre-select symbol at point instead of current" + (interactive "P") + (let ((tag (helm-aif (car (semantic-current-tag-parent)) + (let ((curtag (car (semantic-current-tag)))) + (if (string= it curtag) + (format "\\_<%s\\_>" curtag) + (cons (format "\\_<%s\\_>" it) + (format "\\_<%s\\_>" curtag)))) + (format "\\_<%s\\_>" (car (semantic-current-tag)))))) + (unless helm-source-semantic + (setq helm-source-semantic + (helm-make-source "Semantic Tags" 'helm-semantic-source + :fuzzy-match helm-semantic-fuzzy-match))) + (helm :sources 'helm-source-semantic + :candidate-number-limit 9999 + :preselect (if arg + (thing-at-point 'symbol) + tag) + :buffer "*helm semantic*"))) + +;;;###autoload +(defun helm-semantic-or-imenu (arg) + "Preconfigured helm for `semantic' or `imenu'. +If ARG is supplied, pre-select symbol at point instead of current +semantic tag in scope. + +If `semantic-mode' is active in the current buffer, then use +semantic for generating tags, otherwise fall back to `imenu'. +Fill in the symbol at point by default." + (interactive "P") + (unless helm-source-semantic + (setq helm-source-semantic + (helm-make-source "Semantic Tags" 'helm-semantic-source + :fuzzy-match helm-semantic-fuzzy-match))) + (unless helm-source-imenu + (setq helm-source-imenu + (helm-make-source "Imenu" 'helm-imenu-source + :fuzzy-match helm-imenu-fuzzy-match))) + (let* ((source (if (semantic-active-p) + 'helm-source-semantic + 'helm-source-imenu)) + (imenu-p (eq source 'helm-source-imenu)) + (imenu-auto-rescan imenu-p) + (str (thing-at-point 'symbol)) + (helm-execute-action-at-once-if-one + (and imenu-p + helm-imenu-execute-action-at-once-if-one)) + (tag (helm-aif (car (semantic-current-tag-parent)) + (let ((curtag (car (semantic-current-tag)))) + (if (string= it curtag) + (format "\\_<%s\\_>" curtag) + (cons (format "\\_<%s\\_>" it) + (format "\\_<%s\\_>" curtag)))) + (format "\\_<%s\\_>" (car (semantic-current-tag)))))) + (helm :sources source + :candidate-number-limit 9999 + :default (and imenu-p (list (concat "\\_<" (and str (regexp-quote str)) "\\_>") str)) + :preselect (if (or arg imenu-p) str tag) + :buffer "*helm semantic/imenu*"))) + +(provide 'helm-semantic) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-semantic.el ends here diff --git a/elpa/helm-20181113.923/helm-sys.el b/elpa/helm-20181113.923/helm-sys.el new file mode 100644 index 00000000..9ec918d2 --- /dev/null +++ b/elpa/helm-20181113.923/helm-sys.el @@ -0,0 +1,461 @@ +;;; helm-sys.el --- System related functions for helm. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'helm-utils) + + +(defgroup helm-sys nil + "System related helm library." + :group 'helm) + +(defface helm-top-columns + '((t :inherit helm-header)) + "Face for helm help string in minibuffer." + :group 'helm-sys) + + +(defcustom helm-top-command + (cl-case system-type + (darwin "env COLUMNS=%s ps -axo pid,user,pri,nice,ucomm,tty,start_time,vsz,%%cpu,%%mem,etime,command") + (t "env COLUMNS=%s top -b -n 1")) + "Top command used to display output of top. +A format string where %s will be replaced with `frame-width'. + +To use 'top' command, a version supporting batch mode (-b option) is needed. +On Mac OSX 'top' command doesn't support this, so ps command +is used instead by default. +Normally 'top' command output have 12 columns, but in some versions you may +have less than this, so you can either customize top to use 12 columns with the +interactives 'f' and 'W' commands of top, or modify +`helm-top-sort-columns-alist' to fit with the number of columns +your 'top' command is using. + +If you modify 'ps' command be sure that 'pid' comes in first +and \"env COLUMNS=%s\" is specified at beginning of command. +Ensure also that no elements contain spaces (e.g use start_time and not start). +Same as for 'top' you can customize `helm-top-sort-columns-alist' to make sort commands +working properly according to your settings." + :group 'helm-sys + :type 'string) + +(defcustom helm-top-sort-columns-alist '((com . 11) + (mem . 9) + (cpu . 8) + (user . 1)) + "Allow defining which column to use when sorting output of top/ps command. +Only com, mem, cpu and user are sorted, so no need to put something else there, +it will have no effect. +Note that column numbers are counted from zero, i.e column 1 is the nth 0 column." + :group 'helm-sys + :type '(alist :key-type symbol :value-type (integer :tag "Column number"))) + +(defcustom helm-top-poll-delay 1.5 + "Helm top poll after this delay when `helm-top-poll-mode' is enabled. +The minimal delay allowed is 1.5, if less than this helm-top will use 1.5." + :group 'helm-sys + :type 'float) + +(defcustom helm-top-poll-delay-post-command 1.0 + "Helm top stop polling during this delay. +This delay is additioned to `helm-top-poll-delay' after emacs stop +being idle." + :group 'helm-sys + :type 'float) + +(defcustom helm-top-poll-preselection 'linum + "Stay on same line or follow candidate when `helm-top-poll' update display. +Possible values are 'candidate or 'linum. +This affect also sorting functions in the same way." + :group'helm-sys + :type '(radio :tag "Preferred preselection action for helm-top" + (const :tag "Follow candidate" candidate) + (const :tag "Stay on same line" linum))) + +;;; Top (process) +;; +;; +(defvar helm-top-sort-fn nil) +(defvar helm-top-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-P") 'helm-top-run-sort-by-cpu) + (define-key map (kbd "M-C") 'helm-top-run-sort-by-com) + (define-key map (kbd "M-M") 'helm-top-run-sort-by-mem) + (define-key map (kbd "M-U") 'helm-top-run-sort-by-user) + map)) + +(defvar helm-top-after-init-hook nil + "Local hook for helm-top.") + +(defvar helm-top--poll-timer nil) + +(defun helm-top-poll (&optional no-update delay) + (when helm-top--poll-timer + (cancel-timer helm-top--poll-timer)) + (condition-case nil + (progn + (when (and (helm--alive-p) (null no-update)) + ;; Fix quitting while process is running + ;; by binding `with-local-quit' in init function + ;; Issue #1521. + (helm-force-update + (cl-ecase helm-top-poll-preselection + (candidate (replace-regexp-in-string + "[0-9]+" "[0-9]+" + (regexp-quote (helm-get-selection nil t)))) + (linum `(lambda () + (goto-char (point-min)) + (forward-line ,(helm-candidate-number-at-point))))))) + (setq helm-top--poll-timer + (run-with-idle-timer + (helm-aif (current-idle-time) + (time-add it (seconds-to-time + (or delay (helm-top--poll-delay)))) + (or delay (helm-top--poll-delay))) + nil + 'helm-top-poll))) + (quit (cancel-timer helm-top--poll-timer)))) + +(defun helm-top--poll-delay () + (max 1.5 helm-top-poll-delay)) + +(defun helm-top-poll-no-update () + (helm-top-poll t (+ (helm-top--poll-delay) + helm-top-poll-delay-post-command))) + +(defun helm-top-initialize-poll-hooks () + ;; When emacs is idle during say 20s + ;; the idle timer will run in 20+1.5 s. + ;; This is fine when emacs stays idle, because the next timer + ;; will run at 21.5+1.5 etc... so the display will be updated + ;; at every 1.5 seconds. + ;; But as soon as emacs looses its idleness, the next update + ;; will occur at say 21+1.5 s, so we have to reinitialize + ;; the timer at 0+1.5. + (add-hook 'post-command-hook 'helm-top-poll-no-update) + (add-hook 'focus-in-hook 'helm-top-poll-no-update)) + +;;;###autoload +(define-minor-mode helm-top-poll-mode + "Refresh automatically helm top buffer once enabled." + :group 'helm-top + :global t + (if helm-top-poll-mode + (progn + (add-hook 'helm-top-after-init-hook 'helm-top-poll-no-update) + (add-hook 'helm-top-after-init-hook 'helm-top-initialize-poll-hooks)) + (remove-hook 'helm-top-after-init-hook 'helm-top-poll-no-update) + (remove-hook 'helm-top-after-init-hook 'helm-top-initialize-poll-hooks))) + +(defvar helm-source-top + (helm-build-in-buffer-source "Top" + :header-name (lambda (name) + (concat name (if helm-top-poll-mode + " (auto updating)" + " (Press C-c C-u to refresh)"))) + :init #'helm-top-init + :after-init-hook 'helm-top-after-init-hook + :cleanup (lambda () + (when helm-top--poll-timer + (cancel-timer helm-top--poll-timer)) + (remove-hook 'post-command-hook 'helm-top-poll-no-update) + (remove-hook 'focus-in-hook 'helm-top-poll-no-update)) + :display-to-real #'helm-top-display-to-real + :persistent-action '(helm-top-sh-persistent-action . never-split) + :persistent-help "SIGTERM" + :help-message 'helm-top-help-message + :mode-line 'helm-top-mode-line + :follow 'never + :keymap helm-top-map + :filtered-candidate-transformer #'helm-top-sort-transformer + :action-transformer #'helm-top-action-transformer + :group 'helm-sys)) + +(defvar helm-top--line nil) +(defun helm-top-transformer (candidates _source) + "Transformer for `helm-top'. +Return empty string for non--valid candidates." + (cl-loop for disp in candidates collect + (cond ((string-match "^ *[0-9]+" disp) disp) + ((string-match "^ *PID" disp) + (setq helm-top--line (cons (propertize disp 'face 'helm-top-columns) ""))) + (t (cons disp ""))) + into lst + finally return (or (member helm-top--line lst) + (cons helm-top--line lst)))) + +(defun helm-top--skip-top-line () + (let* ((src (helm-get-current-source)) + (src-name (assoc-default 'name src))) + (helm-aif (and (stringp src-name) + (string= src-name "Top") + (helm-get-selection nil t src)) + (when (string-match-p "^ *PID" it) + (helm-next-line))))) + +(defun helm-top-action-transformer (actions _candidate) + "Action transformer for `top'. +Show actions only on line starting by a PID." + (let ((disp (helm-get-selection nil t))) + (cond ((string-match "\\` *[0-9]+" disp) + (list '("kill (SIGTERM)" . (lambda (_pid) + (helm-top-sh "TERM" (helm-top--marked-pids)))) + '("kill (SIGKILL)" . (lambda (_pid) + (helm-top-sh "KILL" (helm-top--marked-pids)))) + '("kill (SIGINT)" . (lambda (_pid) + (helm-top-sh "INT" (helm-top--marked-pids)))) + '("kill (Choose signal)" + . (lambda (_pid) + (let ((pids (helm-top--marked-pids))) + (helm-top-sh + (helm-comp-read (format "Kill %d pids with signal: " + (length pids)) + '("ALRM" "HUP" "INT" "KILL" "PIPE" "POLL" + "PROF" "TERM" "USR1" "USR2" "VTALRM" + "STKFLT" "PWR" "WINCH" "CHLD" "URG" + "TSTP" "TTIN" "TTOU" "STOP" "CONT" + "ABRT" "FPE" "ILL" "QUIT" "SEGV" + "TRAP" "SYS" "EMT" "BUS" "XCPU" "XFSZ") + :must-match t) + pids)))))) + (t actions)))) + +(defun helm-top--marked-pids () + (helm-remove-if-not-match "\\`[0-9]+\\'" (helm-marked-candidates))) + +(defun helm-top-sh (sig pids) + "Run kill shell command with signal SIG on PIDS for `helm-top'." + (message "kill -%s %s exited with status %s" + sig (mapconcat 'identity pids " ") + (apply #'call-process + "kill" nil nil nil (format "-%s" sig) pids))) + +(defun helm-top-sh-persistent-action (pid) + (helm-top-sh "TERM" (list pid)) + (helm-delete-current-selection)) + +(defun helm-top-init () + "Insert output of top command in candidate buffer." + (with-local-quit + (unless helm-top-sort-fn (helm-top-set-mode-line "CPU")) + (with-current-buffer (helm-candidate-buffer 'global) + (call-process-shell-command + (format helm-top-command (frame-width)) + nil (current-buffer))))) + +(defun helm-top-display-to-real (line) + "Return pid only from LINE." + (car (split-string line))) + +;; Sort top command + +(defun helm-top-set-mode-line (str) + (if (string-match "Sort:\\[\\(.*\\)\\] " helm-top-mode-line) + (setq helm-top-mode-line (replace-match str nil nil helm-top-mode-line 1)) + (setq helm-top-mode-line (concat (format "Sort:[%s] " str) helm-top-mode-line)))) + +(defun helm-top-sort-transformer (candidates source) + (helm-top-transformer + (if helm-top-sort-fn + (cl-loop for c in candidates + if (string-match "^ *[0-9]+" c) + collect c into pid-cands + else collect c into header-cands + finally return (append + header-cands + (sort pid-cands helm-top-sort-fn))) + candidates) + source)) + +(defun helm-top-sort-by-com (s1 s2) + (let* ((split-1 (split-string s1)) + (split-2 (split-string s2)) + (col (cdr (assq 'com helm-top-sort-columns-alist))) + (com-1 (nth col split-1)) + (com-2 (nth col split-2))) + (string< com-1 com-2))) + +(defun helm-top-sort-by-mem (s1 s2) + (let* ((split-1 (split-string s1)) + (split-2 (split-string s2)) + (col (cdr (assq 'mem helm-top-sort-columns-alist))) + (mem-1 (string-to-number (nth col split-1))) + (mem-2 (string-to-number (nth col split-2)))) + (> mem-1 mem-2))) + +(defun helm-top-sort-by-cpu (s1 s2) + (let* ((split-1 (split-string s1)) + (split-2 (split-string s2)) + (col (cdr (assq 'cpu helm-top-sort-columns-alist))) + (cpu-1 (string-to-number (nth col split-1))) + (cpu-2 (string-to-number (nth col split-2)))) + (> cpu-1 cpu-2))) + +(defun helm-top-sort-by-user (s1 s2) + (let* ((split-1 (split-string s1)) + (split-2 (split-string s2)) + (col (cdr (assq 'user helm-top-sort-columns-alist))) + (user-1 (nth col split-1)) + (user-2 (nth col split-2))) + (string< user-1 user-2))) + +(defun helm-top--preselect-fn () + (if (eq helm-top-poll-preselection 'linum) + `(lambda () + (goto-char (point-min)) + (forward-line ,(helm-candidate-number-at-point))) + (replace-regexp-in-string + "[0-9]+" "[0-9]+" + (regexp-quote (helm-get-selection nil t))))) + +(defun helm-top-run-sort-by-com () + (interactive) + (helm-top-set-mode-line "COM") + (setq helm-top-sort-fn 'helm-top-sort-by-com) + (helm-update (helm-top--preselect-fn))) + +(defun helm-top-run-sort-by-cpu () + (interactive) + (helm-top-set-mode-line "CPU") + ;; Force sorting by CPU even if some versions of top are using by + ;; default CPU sorting (Issue #1908). + (setq helm-top-sort-fn 'helm-top-sort-by-cpu) + (helm-update (helm-top--preselect-fn))) + +(defun helm-top-run-sort-by-mem () + (interactive) + (helm-top-set-mode-line "MEM") + (setq helm-top-sort-fn 'helm-top-sort-by-mem) + (helm-update (helm-top--preselect-fn))) + +(defun helm-top-run-sort-by-user () + (interactive) + (helm-top-set-mode-line "USER") + (setq helm-top-sort-fn 'helm-top-sort-by-user) + (helm-update (helm-top--preselect-fn))) + + +;;; X RandR resolution change +;; +;; +;;; FIXME I do not care multi-display. + +(defun helm-xrandr-info () + "Return a pair with current X screen number and current X display name." + (with-temp-buffer + (call-process "xrandr" nil (current-buffer) nil + "--current") + (let (screen output) + (goto-char (point-min)) + (save-excursion + (when (re-search-forward "\\(^Screen \\)\\([0-9]\\):" nil t) + (setq screen (match-string 2)))) + (when (re-search-forward "^\\(.*\\) connected" nil t) + (setq output (match-string 1))) + (list screen output)))) + +(defun helm-xrandr-screen () + "Return current X screen number." + (car (helm-xrandr-info))) + +(defun helm-xrandr-output () + "Return current X display name." + (cadr (helm-xrandr-info))) + +(defvar helm-source-xrandr-change-resolution + (helm-build-sync-source "Change Resolution" + :candidates + (lambda () + (with-temp-buffer + (call-process "xrandr" nil (current-buffer) nil + "--screen" (helm-xrandr-screen) "-q") + (goto-char 1) + (cl-loop while (re-search-forward " \\([0-9]+x[0-9]+\\)" nil t) + for mode = (match-string 1) + unless (member mode modes) + collect mode into modes + finally return modes))) + :action + (helm-make-actions "Change Resolution" + (lambda (mode) + (call-process "xrandr" nil nil nil + "--screen" (helm-xrandr-screen) + "--output" (helm-xrandr-output) + "--mode" mode))))) + + +;;; Emacs process +;; +;; +(defvar helm-source-emacs-process + (helm-build-sync-source "Emacs Process" + :init (lambda () + (let (tabulated-list-use-header-line) + (list-processes--refresh))) + :candidates (lambda () (mapcar #'process-name (process-list))) + :persistent-action (lambda (elm) + (delete-process (get-process elm)) + (helm-delete-current-selection)) + :persistent-help "Kill Process" + :action (helm-make-actions "Kill Process" + (lambda (_elm) + (cl-loop for p in (helm-marked-candidates) + do (delete-process (get-process p))))))) + + +;;;###autoload +(defun helm-top () + "Preconfigured `helm' for top command." + (interactive) + (add-hook 'helm-after-update-hook 'helm-top--skip-top-line) + (save-window-excursion + (unless helm-alive-p (delete-other-windows)) + (unwind-protect + (helm :sources 'helm-source-top + :buffer "*helm top*" :full-frame t + :candidate-number-limit 9999 + :preselect "^\\s-*[0-9]+" + :truncate-lines helm-show-action-window-other-window) + (remove-hook 'helm-after-update-hook 'helm-top--skip-top-line)))) + +;;;###autoload +(defun helm-list-emacs-process () + "Preconfigured `helm' for emacs process." + (interactive) + (helm-other-buffer 'helm-source-emacs-process "*helm process*")) + +;;;###autoload +(defun helm-xrandr-set () + "Preconfigured helm for xrandr." + (interactive) + (helm :sources 'helm-source-xrandr-change-resolution + :buffer "*helm xrandr*")) + +(provide 'helm-sys) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-sys.el ends here diff --git a/elpa/helm-20181113.923/helm-tags.el b/elpa/helm-20181113.923/helm-tags.el new file mode 100644 index 00000000..88fc9043 --- /dev/null +++ b/elpa/helm-20181113.923/helm-tags.el @@ -0,0 +1,345 @@ +;;; helm-tags.el --- Helm for Etags. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(require 'helm-utils) +(require 'helm-grep) + + +(defgroup helm-tags nil + "Tags related Applications and libraries for Helm." + :group 'helm) + +(defcustom helm-etags-tag-file-name "TAGS" + "Etags tag file name." + :type 'string + :group 'helm-tags) + +(defcustom helm-etags-tag-file-search-limit 10 + "The limit level of directory to search tag file. +Don't search tag file deeply if outside this value." + :type 'number + :group 'helm-tags) + +(defcustom helm-etags-match-part-only 'tag + "Allow choosing the tag part of CANDIDATE in `helm-source-etags-select'. +A tag looks like this: + filename: \(defun foo +You can choose matching against the tag part (i.e \"(defun foo\"), +or against the whole candidate (i.e \"(filename:5:(defun foo\")." + :type '(choice + (const :tag "Match only tag" tag) + (const :tag "Match all file+tag" all)) + :group 'helm-tags) + +(defcustom helm-etags-execute-action-at-once-if-one t + "Whether to jump straight to the selected tag if there's only +one match." + :type 'boolean + :group 'helm-tags) + + +(defgroup helm-tags-faces nil + "Customize the appearance of helm-tags faces." + :prefix "helm-" + :group 'helm-tags + :group 'helm-faces) + +(defface helm-etags-file + '((t (:foreground "Lightgoldenrod4" + :underline t))) + "Face used to highlight etags filenames." + :group 'helm-tags-faces) + + +;;; Etags +;; +;; +(defun helm-etags-run-switch-other-window () + "Run switch to other window action from `helm-source-etags-select'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action + (lambda (c) + (helm-etags-action-goto 'find-file-other-window c))))) +(put 'helm-etags-run-switch-other-window 'helm-only t) + +(defun helm-etags-run-switch-other-frame () + "Run switch to other frame action from `helm-source-etags-select'." + (interactive) + (with-helm-alive-p + (helm-exit-and-execute-action + (lambda (c) + (helm-etags-action-goto 'find-file-other-frame c))))) +(put 'helm-etags-run-switch-other-frame 'helm-only t) + +(defvar helm-etags-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "M-") 'helm-goto-next-file) + (define-key map (kbd "M-") 'helm-goto-precedent-file) + (define-key map (kbd "C-c o") 'helm-etags-run-switch-other-window) + (define-key map (kbd "C-c C-o") 'helm-etags-run-switch-other-frame) + map) + "Keymap used in Etags.") + +(defvar helm-etags-mtime-alist nil + "Store the last modification time of etags files here.") +(defvar helm-etags-cache (make-hash-table :test 'equal) + "Cache content of etags files used here for faster access.") + +(defun helm-etags-get-tag-file (&optional directory) + "Return the path of etags file if found. +Lookes recursively in parents directorys for a +`helm-etags-tag-file-name' file." + ;; Get tag file from `default-directory' or upper directory. + (let ((current-dir (helm-etags-find-tag-file-directory + (or directory default-directory)))) + ;; Return nil if not find tag file. + (when current-dir + (expand-file-name helm-etags-tag-file-name current-dir)))) + +(defun helm-etags-all-tag-files () + "Return files from the following sources; + 1) An automatically located file in the parent directories, by `helm-etags-get-tag-file'. + 2) `tags-file-name', which is commonly set by `find-tag' command. + 3) `tags-table-list' which is commonly set by `visit-tags-table' command." + (helm-fast-remove-dups + (delq nil + (append (list (helm-etags-get-tag-file) + tags-file-name) + tags-table-list)) + :test 'equal)) + +(defun helm-etags-find-tag-file-directory (current-dir) + "Try to find the directory containing tag file. +If not found in CURRENT-DIR search in upper directory." + (let ((file-exists? (lambda (dir) + (let ((tag-path (expand-file-name + helm-etags-tag-file-name dir))) + (and (stringp tag-path) + (file-regular-p tag-path) + (file-readable-p tag-path)))))) + (cl-loop with count = 0 + until (funcall file-exists? current-dir) + ;; Return nil if outside the value of + ;; `helm-etags-tag-file-search-limit'. + if (= count helm-etags-tag-file-search-limit) + do (cl-return nil) + ;; Or search upper directories. + else + do (cl-incf count) + (setq current-dir (expand-file-name (concat current-dir "../"))) + finally return current-dir))) + +(defun helm-etags-get-header-name (_x) + "Create header name for this helm etags session." + (concat "Etags in " + (with-helm-current-buffer + (helm-etags-get-tag-file)))) + +(defun helm-etags-create-buffer (file) + "Create the `helm-buffer' based on contents of etags tag FILE." + (let* (max + (split (with-temp-buffer + (insert-file-contents file) + (prog1 + (split-string (buffer-string) "\n" 'omit-nulls) + (setq max (line-number-at-pos (point-max)))))) + (progress-reporter (make-progress-reporter "Loading tag file..." 0 max))) + (cl-loop + with fname + with cand + for i in split for count from 0 + for elm = (unless (string-match "^\x0c" i) ;; "^L" + (helm-aif (string-match "\177" i) ;; "^?" + (substring i 0 it) + i)) + for linum = (when (string-match "[0-9]+,?[0-9]*$" i) + (car (split-string (match-string 0 i) ","))) + do (cond ((and elm (string-match "^\\([^,]+\\),[0-9]+$" elm)) + (setq fname (propertize (match-string 1 elm) + 'face 'helm-etags-file))) + (elm (setq cand (format "%s:%s:%s" fname linum elm))) + (t (setq cand nil))) + when cand do (progn + (insert (propertize (concat cand "\n") 'linum linum)) + (progress-reporter-update progress-reporter count))))) + +(defun helm-etags-init () + "Feed `helm-buffer' using `helm-etags-cache' or tag file. +If no entry in cache, create one." + (let ((tagfiles (helm-etags-all-tag-files))) + (when tagfiles + (with-current-buffer (helm-candidate-buffer 'global) + (dolist (f tagfiles) + (helm-aif (gethash f helm-etags-cache) + ;; An entry is present in cache, insert it. + (insert it) + ;; No entry, create a new buffer using content of tag file (slower). + (helm-etags-create-buffer f) + ;; Store content of buffer in cache. + (puthash f (buffer-string) helm-etags-cache) + ;; Store or set the last modification of tag file. + (helm-aif (assoc f helm-etags-mtime-alist) + ;; If an entry exists modify it. + (setcdr it (helm-etags-mtime f)) + ;; No entry create a new one. + (cl-pushnew (cons f (helm-etags-mtime f)) + helm-etags-mtime-alist + :test 'equal)))))))) + +(defvar helm-source-etags-select nil + "Helm source for Etags.") + +(defun helm-etags-build-source () + (helm-build-in-buffer-source "Etags" + :header-name 'helm-etags-get-header-name + :init 'helm-etags-init + :get-line 'buffer-substring + :match-part (lambda (candidate) + ;; Match only the tag part of CANDIDATE + ;; and not the filename. + (cl-case helm-etags-match-part-only + (tag (cl-caddr (helm-grep-split-line candidate))) + (t candidate))) + :fuzzy-match helm-etags-fuzzy-match + :help-message 'helm-etags-help-message + :keymap helm-etags-map + :action '(("Go to tag" . (lambda (c) + (helm-etags-action-goto 'find-file c))) + ("Go to tag in other window" . (lambda (c) + (helm-etags-action-goto + 'find-file-other-window + c))) + ("Go to tag in other frame" . (lambda (c) + (helm-etags-action-goto + 'find-file-other-frame + c)))) + :group 'helm-tags + :persistent-help "Go to line" + :persistent-action (lambda (candidate) + (helm-etags-action-goto 'find-file candidate) + (helm-highlight-current-line)))) + +(defcustom helm-etags-fuzzy-match nil + "Use fuzzy matching in `helm-etags-select'." + :group 'helm-tags + :type 'boolean + :set (lambda (var val) + (set var val) + (setq helm-source-etags-select + (helm-etags-build-source)))) + +(defvar find-tag-marker-ring) + +(defsubst helm-etags--file-from-tag (fname) + (cl-loop for ext in + (cons "" (remove "" tags-compression-info-list)) + for file = (concat fname ext) + when (file-exists-p file) + return file)) + +(defun helm-etags-action-goto (switcher candidate) + "Helm default action to jump to an etags entry in other window." + (require 'etags) + (deactivate-mark t) + (helm-log-run-hook 'helm-goto-line-before-hook) + (let* ((split (helm-grep-split-line candidate)) + (fname (cl-loop for tagf being the hash-keys of helm-etags-cache + for f = (expand-file-name + (car split) (file-name-directory tagf)) + ;; Try to find an existing file, possibly compressed. + when (helm-etags--file-from-tag f) + return it)) + (elm (cl-caddr split)) + (linum (string-to-number (cadr split)))) + (if (null fname) + (error "file %s not found" fname) + (ring-insert find-tag-marker-ring (point-marker)) + (funcall switcher fname) + (helm-goto-line linum t) + (when (search-forward elm nil t) + (goto-char (match-beginning 0)))))) + +(defun helm-etags-mtime (file) + "Last modification time of etags tag FILE." + (cadr (nth 5 (file-attributes file)))) + +(defun helm-etags-file-modified-p (file) + "Check if tag FILE have been modified in this session. +If FILE is nil return nil." + (let ((last-modif (and file + (assoc-default file helm-etags-mtime-alist)))) + (and last-modif + (/= last-modif (helm-etags-mtime file))))) + +;;;###autoload +(defun helm-etags-select (reinit) + "Preconfigured helm for etags. +If called with a prefix argument REINIT +or if any of the tag files have been modified, reinitialize cache. + +This function aggregates three sources of tag files: + + 1) An automatically located file in the parent directories, + by `helm-etags-get-tag-file'. + 2) `tags-file-name', which is commonly set by `find-tag' command. + 3) `tags-table-list' which is commonly set by `visit-tags-table' command." + (interactive "P") + (let ((tag-files (helm-etags-all-tag-files)) + (helm-execute-action-at-once-if-one + helm-etags-execute-action-at-once-if-one) + (str (if (region-active-p) + (buffer-substring-no-properties + (region-beginning) (region-end)) + (thing-at-point 'symbol)))) + (if (cl-notany 'file-exists-p tag-files) + (message "Error: No tag file found.\ +Create with etags shell command, or visit with `find-tag' or `visit-tags-table'.") + (cl-loop for k being the hash-keys of helm-etags-cache + unless (member k tag-files) + do (remhash k helm-etags-cache)) + (mapc (lambda (f) + (when (or (equal reinit '(4)) + (and helm-etags-mtime-alist + (helm-etags-file-modified-p f))) + (remhash f helm-etags-cache))) + tag-files) + (unless helm-source-etags-select + (setq helm-source-etags-select + (helm-etags-build-source))) + (helm :sources 'helm-source-etags-select + :keymap helm-etags-map + :default (if helm-etags-fuzzy-match + str + (list (concat "\\_<" str "\\_>") str)) + :buffer "*helm etags*")))) + +(provide 'helm-tags) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-tags.el ends here diff --git a/elpa/helm-20181113.923/helm-types.el b/elpa/helm-20181113.923/helm-types.el new file mode 100644 index 00000000..15de27e7 --- /dev/null +++ b/elpa/helm-20181113.923/helm-types.el @@ -0,0 +1,318 @@ +;;; helm-types.el --- Helm types classes and methods. -*- lexical-binding: t -*- + +;; Copyright (C) 2015 ~ 2018 Thierry Volpiatto + +;; Author: Thierry Volpiatto +;; URL: http://github.com/emacs-helm/helm + +;; 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 3 of the License, 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 this program. If not, see . + + +;;; Code: + +(require 'cl-lib) +(require 'eieio) + + +;; Files +(defclass helm-type-file (helm-source) () + "A class to define helm type file.") + +(defmethod helm-source-get-action-from-type ((object helm-type-file)) + (slot-value object 'action)) + +(defun helm-actions-from-type-file () + (let ((source (make-instance 'helm-type-file))) + (helm--setup-source source) + (helm-source-get-action-from-type source))) + +(defvar helm-generic-files-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map helm-map) + (define-key map (kbd "C-]") 'helm-ff-run-toggle-basename) + (define-key map (kbd "C-s") 'helm-ff-run-grep) + (define-key map (kbd "M-g s") 'helm-ff-run-grep) + (define-key map (kbd "M-g z") 'helm-ff-run-zgrep) + (define-key map (kbd "M-g p") 'helm-ff-run-pdfgrep) + (define-key map (kbd "C-c g") 'helm-ff-run-gid) + (define-key map (kbd "M-R") 'helm-ff-run-rename-file) + (define-key map (kbd "M-C") 'helm-ff-run-copy-file) + (define-key map (kbd "M-B") 'helm-ff-run-byte-compile-file) + (define-key map (kbd "M-L") 'helm-ff-run-load-file) + (define-key map (kbd "M-S") 'helm-ff-run-symlink-file) + (define-key map (kbd "M-H") 'helm-ff-run-hardlink-file) + (define-key map (kbd "M-D") 'helm-ff-run-delete-file) + (define-key map (kbd "C-=") 'helm-ff-run-ediff-file) + (define-key map (kbd "C-c =") 'helm-ff-run-ediff-merge-file) + (define-key map (kbd "C-c o") 'helm-ff-run-switch-other-window) + (define-key map (kbd "C-c r") 'helm-ff-run-find-file-as-root) + (define-key map (kbd "C-c C-o") 'helm-ff-run-switch-other-frame) + (define-key map (kbd "M-i") 'helm-ff-properties-persistent) + (define-key map (kbd "C-c C-x") 'helm-ff-run-open-file-externally) + (define-key map (kbd "C-c X") 'helm-ff-run-open-file-with-default-tool) + (define-key map (kbd "M-.") 'helm-ff-run-etags) + (define-key map (kbd "C-c @") 'helm-ff-run-insert-org-link) + (define-key map (kbd "C-x C-q") 'helm-ff-run-marked-files-in-dired) + (define-key map (kbd "C-c C-a") 'helm-ff-run-mail-attach-files) + map) + "Generic Keymap for files.") + +(defcustom helm-type-file-actions + (helm-make-actions + "Find file" 'helm-find-many-files + "Find file as root" 'helm-find-file-as-root + "Find file other window" 'helm-find-files-other-window + "Find file other frame" 'find-file-other-frame + "Open dired in file's directory" 'helm-open-dired + "Attach file(s) to mail buffer `C-c C-a'" 'helm-ff-mail-attach-files + "Marked files in dired" 'helm-marked-files-in-dired + "Grep File(s) `C-u recurse'" 'helm-find-files-grep + "Zgrep File(s) `C-u Recurse'" 'helm-ff-zgrep + "Pdfgrep File(s)" 'helm-ff-pdfgrep + "Insert as org link" 'helm-files-insert-as-org-link + "Checksum File" 'helm-ff-checksum + "Ediff File" 'helm-find-files-ediff-files + "Ediff Merge File" 'helm-find-files-ediff-merge-files + "Etags `M-., C-u reload tag file'" 'helm-ff-etags-select + "View file" 'view-file + "Insert file" 'insert-file + "Add marked files to file-cache" 'helm-ff-cache-add-file + "Delete file(s)" 'helm-ff-delete-files + "Copy file(s) `M-C, C-u to follow'" 'helm-find-files-copy + "Rename file(s) `M-R, C-u to follow'" 'helm-find-files-rename + "Symlink files(s) `M-S, C-u to follow'" 'helm-find-files-symlink + "Relsymlink file(s) `C-u to follow'" 'helm-find-files-relsymlink + "Hardlink file(s) `M-H, C-u to follow'" 'helm-find-files-hardlink + "Open file externally (C-u to choose)" 'helm-open-file-externally + "Open file with default tool" 'helm-open-file-with-default-tool + "Find file in hex dump" 'hexl-find-file) + "Default actions for type files." + :group 'helm-files + :type '(alist :key-type string :value-type function)) + +(defmethod helm--setup-source :primary ((_source helm-type-file))) + +(defmethod helm--setup-source :before ((source helm-type-file)) + (setf (slot-value source 'action) 'helm-type-file-actions) + (setf (slot-value source 'persistent-help) "Show this file") + (setf (slot-value source 'action-transformer) + '(helm-transform-file-load-el + helm-transform-file-browse-url + helm-transform-file-cache)) + (setf (slot-value source 'candidate-transformer) + '(helm-skip-boring-files + helm-w32-pathname-transformer)) + (setf (slot-value source 'filtered-candidate-transformer) + 'helm-highlight-files) + (setf (slot-value source 'help-message) 'helm-generic-file-help-message) + (setf (slot-value source 'mode-line) (list "File(s)" helm-mode-line-string)) + (setf (slot-value source 'keymap) helm-generic-files-map) + (setf (slot-value source 'group) 'helm-files)) + + +;; Bookmarks +(defclass helm-type-bookmark (helm-source) () + "A class to define type bookmarks.") + +(defcustom helm-type-bookmark-actions + (helm-make-actions + "Jump to bookmark" 'helm-bookmark-jump + "Jump to BM other window" 'helm-bookmark-jump-other-window + "Jump to BM other frame" 'helm-bookmark-jump-other-frame + "Bookmark edit annotation" 'bookmark-edit-annotation + "Bookmark show annotation" 'bookmark-show-annotation + "Delete bookmark(s)" 'helm-delete-marked-bookmarks + "Edit Bookmark" 'helm-bookmark-edit-bookmark + "Rename bookmark" 'helm-bookmark-rename + "Relocate bookmark" 'bookmark-relocate) + "Default actions for type bookmarks." + :group 'helm-bookmark + :type '(alist :key-type string + :value-type function)) + +(defmethod helm-source-get-action-from-type ((object helm-type-bookmark)) + (slot-value object 'action)) + +(defmethod helm--setup-source :primary ((_source helm-type-bookmark))) + +(defmethod helm--setup-source :before ((source helm-type-bookmark)) + (setf (slot-value source 'action) 'helm-type-bookmark-actions) + (setf (slot-value source 'keymap) helm-bookmark-map) + (setf (slot-value source 'mode-line) (list "Bookmark(s)" helm-mode-line-string)) + (setf (slot-value source 'help-message) 'helm-bookmark-help-message) + (setf (slot-value source 'migemo) t) + (setf (slot-value source 'follow) 'never) + (setf (slot-value source 'group) 'helm-bookmark)) + + +;; Buffers +(defclass helm-type-buffer (helm-source) () + "A class to define type buffer.") + +(defcustom helm-type-buffer-actions + (helm-make-actions + "Switch to buffer(s)" 'helm-buffer-switch-buffers + "Switch to buffer(s) other window `C-c o'" + 'helm-buffer-switch-buffers-other-window + "Switch to buffer other frame `C-c C-o'" + 'switch-to-buffer-other-frame + "Browse project from buffer" + 'helm-buffers-browse-project + "Query replace regexp `C-M-%'" + 'helm-buffer-query-replace-regexp + "Query replace `M-%'" 'helm-buffer-query-replace + "View buffer" 'view-buffer + "Display buffer" 'display-buffer + "Rename buffer" 'helm-buffers-rename-buffer + "Grep buffers `M-g s' (C-u grep all buffers)" + 'helm-zgrep-buffers + "Multi occur buffer(s) `C-s'" 'helm-multi-occur-as-action + "Revert buffer(s) `M-U'" 'helm-revert-marked-buffers + "Insert buffer" 'insert-buffer + "Kill buffer(s) `M-D'" 'helm-kill-marked-buffers + "Diff with file `C-='" 'diff-buffer-with-file + "Ediff Marked buffers `C-c ='" 'helm-ediff-marked-buffers + "Ediff Merge marked buffers `M-='" + (lambda (candidate) + (helm-ediff-marked-buffers candidate t))) + "Default actions for type buffers." + :group 'helm-buffers + :type '(alist :key-type string :value-type function)) + +(defmethod helm-source-get-action-from-type ((object helm-type-buffer)) + (slot-value object 'action)) + +(defmethod helm--setup-source :primary ((_source helm-type-buffer))) + +(defmethod helm--setup-source :before ((source helm-type-buffer)) + (setf (slot-value source 'action) 'helm-type-buffer-actions) + (setf (slot-value source 'persistent-help) "Show this buffer") + (setf (slot-value source 'mode-line) (list "Buffer(s)" helm-mode-line-string)) + (setf (slot-value source 'filtered-candidate-transformer) + '(helm-skip-boring-buffers + helm-buffers-sort-transformer + helm-highlight-buffers)) + (setf (slot-value source 'group) 'helm-buffers)) + +;; Functions +(defclass helm-type-function (helm-source) () + "A class to define helm type function.") + +(defcustom helm-type-function-actions + (helm-make-actions + "Describe command" 'describe-function + "Add command to kill ring" 'helm-kill-new + "Go to command's definition" 'find-function + "Debug on entry" 'debug-on-entry + "Cancel debug on entry" 'cancel-debug-on-entry + "Trace function" 'trace-function + "Trace function (background)" 'trace-function-background + "Untrace function" 'untrace-function) + "Default actions for type functions." + :group 'helm-elisp + :type '(alist :key-type string :value-type function)) + +(defmethod helm-source-get-action-from-type ((object helm-type-function)) + (slot-value object 'action)) + +(defun helm-actions-from-type-function () + (let ((source (make-instance 'helm-type-function))) + (helm--setup-source source) + (helm-source-get-action-from-type source))) + +(defmethod helm--setup-source :primary ((_source helm-type-function))) + +(defmethod helm--setup-source :before ((source helm-type-function)) + (setf (slot-value source 'action) 'helm-type-function-actions) + (setf (slot-value source 'action-transformer) + 'helm-transform-function-call-interactively) + (setf (slot-value source 'candidate-transformer) + 'helm-mark-interactive-functions) + (setf (slot-value source 'coerce) 'helm-symbolify)) + + +;; Commands +(defclass helm-type-command (helm-source) () + "A class to define helm type command.") + +(defun helm-actions-from-type-command () + (let ((source (make-instance 'helm-type-command))) + (helm--setup-source source) + (helm-source-get-action-from-type source))) + +(defcustom helm-type-command-actions + (append (helm-make-actions + "Call interactively" 'helm-call-interactively) + (helm-actions-from-type-function)) + "Default actions for type command." + :group 'helm-command + :type '(alist :key-type string :value-type function)) + +(defmethod helm--setup-source :primary ((_source helm-type-command))) + +(defmethod helm--setup-source :before ((source helm-type-command)) + (setf (slot-value source 'action) 'helm-type-command-actions) + (setf (slot-value source 'coerce) 'helm-symbolify) + (setf (slot-value source 'persistent-action) 'describe-function) + (setf (slot-value source 'group) 'helm-command)) + +;; Timers +(defclass helm-type-timers (helm-source) () + "A class to define helm type timers.") + +(defcustom helm-type-timers-actions + '(("Cancel Timer" . (lambda (_timer) + (let ((mkd (helm-marked-candidates))) + (cl-loop for timer in mkd + do (cancel-timer timer))))) + ("Describe Function" . (lambda (tm) + (describe-function (timer--function tm)))) + ("Find Function" . (lambda (tm) + (helm-aif (timer--function tm) + (if (byte-code-function-p it) + (message "Can't find anonymous function `%s'" it) + (find-function it)))))) + "Default actions for type timers." + :group 'helm-elisp + :type '(alist :key-type string :value-type function)) + +(defmethod helm--setup-source :primary ((_source helm-type-timers))) + +(defmethod helm--setup-source :before ((source helm-type-timers)) + (setf (slot-value source 'action) 'helm-type-timers-actions) + (setf (slot-value source 'persistent-action) + (lambda (tm) + (describe-function (timer--function tm)))) + (setf (slot-value source 'persistent-help) "Describe Function") + (setf (slot-value source 'group) 'helm-elisp)) + +;; Builders. +(defun helm-build-type-file () + (helm-make-type 'helm-type-file)) + +(defun helm-build-type-function () + (helm-make-type 'helm-type-function)) + +(defun helm-build-type-command () + (helm-make-type 'helm-type-command)) + +(provide 'helm-types) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-types.el ends here diff --git a/elpa/helm-20181113.923/helm-utils.el b/elpa/helm-20181113.923/helm-utils.el new file mode 100644 index 00000000..bfa5e07a --- /dev/null +++ b/elpa/helm-20181113.923/helm-utils.el @@ -0,0 +1,1011 @@ +;;; helm-utils.el --- Utilities Functions for helm. -*- lexical-binding: t -*- + +;; Copyright (C) 2012 ~ 2018 Thierry Volpiatto + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm) +(require 'helm-help) +(eval-when-compile (require 'dired)) + +(declare-function helm-find-files-1 "helm-files.el" (fname &optional preselect)) +(declare-function popup-tip "ext:popup") +(defvar winner-boring-buffers) +(defvar helm-show-completion-overlay) + + +(defgroup helm-utils nil + "Utilities routines for Helm." + :group 'helm) + +(defcustom helm-su-or-sudo "sudo" + "What command to use for root access." + :type 'string + :group 'helm-utils) + +(defcustom helm-default-kbsize 1024.0 + "Default Kbsize to use for showing files size. +It is a float, usually 1024.0 but could be 1000.0 on some systems." + :group 'helm-utils + :type 'float) + +(define-obsolete-variable-alias + 'helm-highlight-number-lines-around-point + 'helm-highlight-matches-around-point-max-lines + "20160119") + +(defcustom helm-highlight-matches-around-point-max-lines 15 + "Number of lines around point where matched items are highlighted." + :group 'helm-utils + :type 'integer) + +(defcustom helm-buffers-to-resize-on-pa nil + "A list of helm buffers where the helm-window should be reduced on persistent actions." + :group 'helm-utils + :type '(repeat (choice string))) + +(defcustom helm-resize-on-pa-text-height 12 + "The size of the helm-window when resizing on persistent action." + :group 'helm-utils + :type 'integer) + +(defcustom helm-sources-using-help-echo-popup '("Moccur" "Imenu in all buffers" + "Ack-Grep" "AG" "RG" "Gid" "Git-Grep") + "Show the buffer name or the filename in a popup at selection." + :group 'helm-utils + :type '(repeat (choice string))) + +(defcustom helm-html-decode-entities-function #'helm-html-decode-entities-string + "Function used to decode html entities in html bookmarks. +Helm comes by default with `helm-html-decode-entities-string', if you need something +more sophisticated you can use `w3m-decode-entities-string' if available. + +In emacs itself org-entities seems broken and `xml-substitute-numeric-entities' +supports only numeric entities." + :group 'helm-utils + :type 'function) + + +(defvar helm-goto-line-before-hook '(helm-save-current-pos-to-mark-ring) + "Run before jumping to line. +This hook run when jumping from `helm-goto-line', `helm-etags-default-action', +and `helm-imenu-default-action'. +This allow you to retrieve a previous position after using the different helm +tools for searching (etags, grep, gid, (m)occur etc...). +By default positions are added to `mark-ring' you can also add to register +by using instead (or adding) `helm-save-pos-to-register-before-jump'. +In this case last position is added to the register +`helm-save-pos-before-jump-register'.") + +(defvar helm-save-pos-before-jump-register ?_ + "The register where `helm-save-pos-to-register-before-jump' save position.") + +(defconst helm-html-entities-alist + '((""" . 34) ;; " + (">" . 62) ;; > + ("<" . 60) ;; < + ("&" . 38) ;; & + ("€" . 8364) ;; € + ("Ÿ" . 89) ;; Y + ("¡" . 161) ;; ¡ + ("¢" . 162) ;; ¢ + ("£" . 163) ;; £ + ("¤" . 164) ;; ¤ + ("¥" . 165) ;; Â¥ + ("¦" . 166) ;; ¦ + ("§" . 167) ;; § + ("¨" . 32) ;; SPC + ("©" . 169) ;; © + ("ª" . 97) ;; a + ("«" . 171) ;; « + ("¬" . 172) ;; ¬ + ("&masr;" . 174) ;; ® + ("°" . 176) ;; ° + ("±" . 177) ;; ± + ("²" . 50) ;; 2 + ("³" . 51) ;; 3 + ("´" . 39) ;; ' + ("µ" . 956) ;; μ + ("¶" . 182) ;; ¶ + ("·" . 183) ;; · + ("¸" . 32) ;; SPC + ("¹" . 49) ;; 1 + ("º" . 111) ;; o + ("»" . 187) ;; » + ("¼" . 49) ;; 1 + ("½" . 49) ;; 1 + ("¾" . 51) ;; 3 + ("¿" . 191) ;; ¿ + ("À" . 192) ;; À + ("Á" . 193) ;; Á + ("Â" . 194) ;;  + ("Ã" . 195) ;; à + ("Ä" . 196) ;; Ä + ("Å" . 197) ;; Å + ("&Aelig" . 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) ;; ÿ + ("®" . 174) ;; ® + ("­" . 173)) ;; ­ + + "Table of html character entities and values.") + +(defvar helm-find-many-files-after-hook nil + "Hook that run at end of `helm-find-many-files'.") + +;;; Faces. +;; +(defface helm-selection-line + '((t (:inherit highlight :distant-foreground "black"))) + "Face used in the `helm-current-buffer' when jumping to candidate." + :group 'helm-faces) + +(defface helm-match-item + '((t (:inherit isearch))) + "Face used to highlight item matched in a selected line." + :group 'helm-faces) + + +;;; Utils functions +;; +;; +(defcustom helm-window-prefer-horizontal-split nil + "Maybe switch to other window vertically when non nil. + +Possible values are t, nil and `decide'. + +When t switch vertically. +When nil switch horizontally. +When `decide' try to guess if it is possible to switch vertically +according to the setting of `split-width-threshold' and the size of +the window from where splitting is done. + +Note that when using `decide' and `split-width-threshold' is nil, the +behavior is the same that with a nil value." + :group 'helm-utils + :type '(choice + (const :tag "Split window vertically" t) + (const :tag "Split window horizontally" nil) + (symbol :tag "Guess how to split window" 'decide))) + +(defcustom helm-window-show-buffers-function #'helm-window-default-split-fn + "The default function to use when opening several buffers at once. +It is typically used to rearrange windows." + :group 'helm-utils + :type '(choice + (function :tag "Split windows vertically or horizontally" + helm-window-default-split-fn) + (function :tag "Split in alternate windows" + helm-window-alternate-split-fn) + (function :tag "Split windows in mosaic" + helm-window-mosaic-fn))) + +(defun helm-window-show-buffers (buffers &optional other-window) + "Show BUFFERS. + +If more than one buffer marked switch to these buffers in separate windows. +If OTHER-WINDOW is non-nil, keep current buffer and switch to others buffers +in separate windows. +If a prefix arg is given split windows vertically." + (let ((initial-ow-fn (if (cdr (window-list)) + #'switch-to-buffer-other-window + #'helm-window-other-window))) + (if (cdr buffers) + (funcall helm-window-show-buffers-function buffers + (and other-window initial-ow-fn)) + (if other-window + (funcall initial-ow-fn (car buffers)) + (switch-to-buffer (car buffers)))))) + +(defun helm-window-default-split-fn (candidates &optional other-window-fn) + "Split windows in one direction and balance them. + +Direction can be controlled via `helm-window-prefer-horizontal-split'. +If a prefix arg is given split windows the other direction. +This function is suitable for `helm-window-show-buffers-function'." + (if other-window-fn + (funcall other-window-fn (car candidates)) + (switch-to-buffer (car candidates))) + (save-selected-window + (cl-loop with nosplit + for b in (cdr candidates) + when nosplit return + (message "Too many buffers to visit simultaneously") + do (condition-case _err + (helm-window-other-window b 'balance) + (error (setq nosplit t) nil))))) + +(defun helm-window-alternate-split-fn (candidates &optional other-window-fn) + "Split windows horizontally and vertically in alternate fashion. + +Direction can be controlled via `helm-window-prefer-horizontal-split'. +If a prefix arg is given split windows the other direction. +This function is suitable for `helm-window-show-buffers-function'." + (if other-window-fn + (funcall other-window-fn (car candidates)) + (switch-to-buffer (car candidates))) + (let (right-side) + (save-selected-window + (cl-loop with nosplit + for b in (cdr candidates) + when nosplit return + (message "Too many buffers to visit simultaneously") + do (condition-case _err + (let ((helm-current-prefix-arg right-side)) + (helm-window-other-window b) + (setq right-side (not right-side))) + (error (setq nosplit t) nil)))))) + +(defun helm-window-mosaic-fn (candidates &optional other-window-fn) + "Make an as-square-as-possible window mosaic of the CANDIDATES buffers. + +If rectangular, the long side is in the direction given by +`helm-window-prefer-horizontal-split': if non-nil, it is horizontal, vertical +otherwise. +If OTHER-WINDOW-FN is non-nil, current windows are included in the mosaic. +This function is suitable for `helm-window-show-buffers-function'." + (when other-window-fn + (setq candidates (append (mapcar 'window-buffer (window-list)) candidates))) + (delete-other-windows) + (let* ((helm-window-prefer-horizontal-split + (if (eq helm-window-prefer-horizontal-split 'decide) + (and (numberp split-width-threshold) + (>= (window-width (selected-window)) + split-width-threshold)) + helm-window-prefer-horizontal-split)) + mosaic-length-tile-count + mosaic-width-tile-count + mosaic-length-tile-size + mosaic-width-tile-size + next-window) + ;; If 4 tiles, make 2x2 mosaic. + ;; If 5-6 tiles, make 2x3 mosaic with direction depending on `helm-window-prefer-horizontal-split'. + ;; If 7-9 tiles, make 3x3 mosaic. And so on. + (setq mosaic-length-tile-count (ceiling (sqrt (length candidates)))) + (setq mosaic-width-tile-count + (if (<= (length candidates) (* mosaic-length-tile-count (1- mosaic-length-tile-count))) + (1- mosaic-length-tile-count) + mosaic-length-tile-count)) + ;; We lower-bound the tile size, otherwise the function would + ;; fail during the first inner split. + ;; There is consequently no need to check for errors when + ;; splitting. + (let ((frame-mosaic-length-direction-size (frame-height)) + (frame-mosaic-width-direction-size (frame-width)) + (window-mosaic-length-direction-min-size window-min-height) + (window-mosaic-width-direction-min-size window-min-width)) + (if helm-window-prefer-horizontal-split + (setq frame-mosaic-length-direction-size (frame-width) + frame-mosaic-width-direction-size (frame-height) + window-mosaic-length-direction-min-size window-min-width + window-mosaic-width-direction-min-size window-min-height)) + (setq mosaic-length-tile-size (max + (/ frame-mosaic-length-direction-size mosaic-length-tile-count) + window-mosaic-length-direction-min-size) + mosaic-width-tile-size (max + (/ frame-mosaic-width-direction-size mosaic-width-tile-count) + window-mosaic-width-direction-min-size)) + ;; Shorten `candidates' to `max-tiles' elements. + (let ((max-tiles (* (/ frame-mosaic-length-direction-size mosaic-length-tile-size) + (/ frame-mosaic-width-direction-size mosaic-width-tile-size)))) + (when (> (length candidates) max-tiles) + (message "Too many buffers to visit simultaneously") + (setcdr (nthcdr (- max-tiles 1) candidates) nil)))) + ;; Make the mosaic. + (while candidates + (when (> (length candidates) mosaic-length-tile-count) + (setq next-window (split-window nil + mosaic-width-tile-size + (not helm-window-prefer-horizontal-split)))) + (switch-to-buffer (pop candidates)) + (dotimes (_ (min (1- mosaic-length-tile-count) (length candidates))) + (select-window (split-window nil + mosaic-length-tile-size + helm-window-prefer-horizontal-split)) + (switch-to-buffer (pop candidates))) + (when next-window + (select-window next-window))))) + +(defun helm-window-other-window (buffer-or-name &optional balance) + "Switch to BUFFER-OR-NAME in other window. +Direction can be controlled via `helm-window-prefer-horizontal-split'. +If a prefix arg is given split windows the other direction. +When argument BALANCE is provided `balance-windows'." + (let* ((helm-window-prefer-horizontal-split + (if (eq helm-window-prefer-horizontal-split 'decide) + (and (numberp split-width-threshold) + (>= (window-width (selected-window)) + split-width-threshold)) + helm-window-prefer-horizontal-split)) + (right-side (if helm-window-prefer-horizontal-split + (not helm-current-prefix-arg) + helm-current-prefix-arg))) + (select-window (split-window nil nil right-side)) + (and balance (balance-windows)) + (switch-to-buffer buffer-or-name))) + +(cl-defun helm-current-buffer-narrowed-p (&optional + (buffer helm-current-buffer)) + "Check if BUFFER is narrowed. +Default is `helm-current-buffer'." + (with-current-buffer buffer + (let ((beg (point-min)) + (end (point-max)) + (total (buffer-size))) + (or (/= beg 1) (/= end (1+ total)))))) + +(defun helm-goto-char (loc) + "Go to char, revealing if necessary." + (require 'org) ; On some old Emacs versions org may not be loaded. + (goto-char loc) + (let ((fn (cond ((eq major-mode 'org-mode) #'org-reveal) + ((and (boundp 'outline-minor-mode) + outline-minor-mode) + (lambda () (outline-flag-subtree nil)))))) + ;; outline may fail in some conditions e.g. with markdown enabled + ;; (issue #1919). + (condition-case nil + (and fn (funcall fn)) + (error nil)))) + +(defun helm-goto-line (lineno &optional noanim) + "Goto LINENO opening only outline headline if needed. +Animation is used unless NOANIM is non--nil." + (helm-log-run-hook 'helm-goto-line-before-hook) + (helm-match-line-cleanup) + (unless helm-alive-p + (with-helm-current-buffer + (unless helm-yank-point (setq helm-yank-point (point))))) + (goto-char (point-min)) + (helm-goto-char (point-at-bol lineno)) + (unless noanim + (helm-highlight-current-line))) + +(defun helm-save-pos-to-register-before-jump () + "Save current buffer position to `helm-save-pos-before-jump-register'. +To use this add it to `helm-goto-line-before-hook'." + (with-helm-current-buffer + (unless helm-in-persistent-action + (point-to-register helm-save-pos-before-jump-register)))) + +(defun helm-save-current-pos-to-mark-ring () + "Save current buffer position to mark ring. +To use this add it to `helm-goto-line-before-hook'." + (with-helm-current-buffer + (unless helm-in-persistent-action + (set-marker (mark-marker) (point)) + (push-mark (point) 'nomsg)))) + +(defun helm-show-all-in-this-source-only (arg) + "Show only current source of this helm session with all its candidates. +With a numeric prefix arg show only the ARG number of candidates." + (interactive "p") + (with-helm-alive-p + (with-helm-window + (with-helm-default-directory (helm-default-directory) + (let ((helm-candidate-number-limit (and (> arg 1) arg))) + (helm-set-source-filter + (list (assoc-default 'name (helm-get-current-source))))))))) +(put 'helm-show-all-in-this-source-only 'helm-only t) + +(defun helm-display-all-sources () + "Display all sources previously hidden by `helm-set-source-filter'." + (interactive) + (with-helm-alive-p + (helm-set-source-filter nil))) +(put 'helm-display-all-sources 'helm-only t) + +(defun helm-displaying-source-names () + "Return the list of sources name for this helm session." + (with-current-buffer helm-buffer + (goto-char (point-min)) + (cl-loop with pos + while (setq pos (next-single-property-change (point) 'helm-header)) + do (goto-char pos) + collect (buffer-substring-no-properties (point-at-bol)(point-at-eol)) + do (forward-line 1)))) + +(defun helm-handle-winner-boring-buffers () + "Add `helm-buffer' to `winner-boring-buffers' when quitting/exiting helm. +Add this function to `helm-cleanup-hook' when you don't want to see helm buffers +after running winner-undo/redo." + (require 'winner) + (cl-pushnew helm-buffer winner-boring-buffers :test 'equal)) +(add-hook 'helm-cleanup-hook #'helm-handle-winner-boring-buffers) + +(defun helm-quit-and-find-file () + "Drop into `helm-find-files' from `helm'. +If current selection is a buffer or a file, `helm-find-files' +from its directory." + (interactive) + (with-helm-alive-p + (require 'helm-grep) + (require 'helm-elisp) + (helm-run-after-exit + (lambda (f) + ;; Ensure specifics `helm-execute-action-at-once-if-one' + ;; fns don't run here. + (let (helm-execute-action-at-once-if-one + helm-actions-inherit-frame-settings) ; use this-command + (if (file-exists-p f) + (helm-find-files-1 (file-name-directory f) + (concat + "^" + (regexp-quote + (if helm-ff-transformer-show-only-basename + (helm-basename f) f)))) + (helm-find-files-1 f)))) + (let* ((sel (helm-get-selection)) + (marker (if (consp sel) (markerp (cdr sel)))) + (grep-line (and (stringp sel) + (helm-grep-split-line sel))) + (bmk-name (and (stringp sel) + (not grep-line) + (replace-regexp-in-string "\\`\\*" "" sel))) + (bmk (and bmk-name (assoc bmk-name bookmark-alist))) + (buf (helm-aif (and (bufferp sel) (get-buffer sel)) + (buffer-name it))) + (default-preselection (or (buffer-file-name helm-current-buffer) + default-directory))) + (cond + ;; Buffer. + (buf (or (buffer-file-name sel) + (car (rassoc buf dired-buffers)) + (and (with-current-buffer buf + (eq major-mode 'org-agenda-mode)) + org-directory + (expand-file-name org-directory)) + (with-current-buffer buf + (expand-file-name default-directory)))) + ;; imenu (marker). + (marker + (or (buffer-file-name (marker-buffer (cdr sel))) + default-preselection)) + ;; Bookmark. + (bmk (helm-aif (bookmark-get-filename bmk) + (if (and helm--url-regexp + (string-match helm--url-regexp it)) + it (expand-file-name it)) + (expand-file-name default-directory))) + ((and (stringp sel) (or (file-remote-p sel) + (file-exists-p sel))) + (expand-file-name sel)) + ;; Grep. + ((and grep-line (file-exists-p (car grep-line))) + (expand-file-name (car grep-line))) + ;; Occur. + (grep-line + (with-current-buffer (get-buffer (car grep-line)) + (expand-file-name (or (buffer-file-name) default-directory)))) + ;; Url. + ((and (stringp sel) helm--url-regexp (string-match helm--url-regexp sel)) sel) + ;; Exit brutally from a `with-helm-show-completion' + ((and helm-show-completion-overlay + (overlayp helm-show-completion-overlay)) + (delete-overlay helm-show-completion-overlay) + (remove-hook 'helm-move-selection-after-hook 'helm-show-completion) + (expand-file-name default-preselection)) + ;; Default. + (t (expand-file-name default-preselection))))))) +(put 'helm-quit-and-find-file 'helm-only t) + +(defun helm-generic-sort-fn (s1 s2) + "Sort predicate function for helm candidates. +Args S1 and S2 can be single or \(display . real\) candidates, +that is sorting is done against real value of candidate." + (let* ((qpattern (regexp-quote helm-pattern)) + (reg1 (concat "\\_<" qpattern "\\_>")) + (reg2 (concat "\\_<" qpattern)) + (reg3 helm-pattern) + (split (helm-mm-split-pattern helm-pattern)) + (str1 (if (consp s1) (cdr s1) s1)) + (str2 (if (consp s2) (cdr s2) s2)) + (score (lambda (str r1 r2 r3 lst) + (+ (if (string-match (concat "\\`" qpattern) str) 1 0) + (cond ((string-match r1 str) 5) + ((and (string-match " " qpattern) + (string-match + (concat "\\_<" (regexp-quote (car lst))) str) + (cl-loop for r in (cdr lst) + always (string-match r str))) 4) + ((and (string-match " " qpattern) + (cl-loop for r in lst + always (string-match r str))) 3) + ((string-match r2 str) 2) + ((string-match r3 str) 1) + (t 0))))) + (sc1 (funcall score str1 reg1 reg2 reg3 split)) + (sc2 (funcall score str2 reg1 reg2 reg3 split))) + (cond ((or (zerop (string-width qpattern)) + (and (zerop sc1) (zerop sc2))) + (string-lessp str1 str2)) + ((= sc1 sc2) + (< (length str1) (length str2))) + (t (> sc1 sc2))))) + +(cl-defun helm-file-human-size (size &optional (kbsize helm-default-kbsize)) + "Return a string showing SIZE of a file in human readable form. +SIZE can be an integer or a float depending it's value. +`file-attributes' will take care of that to avoid overflow error. +KBSIZE is a floating point number, defaulting to `helm-default-kbsize'." + (cl-loop with result = (cons "B" size) + for i in '("k" "M" "G" "T" "P" "E" "Z" "Y") + while (>= (cdr result) kbsize) + do (setq result (cons i (/ (cdr result) kbsize))) + finally return + (helm-acase (car result) + ("B" (format "%s" size)) + (t (format "%.1f%s" (cdr result) it))))) + +(cl-defun helm-file-attributes + (file &key type links uid gid access-time modif-time + status size mode gid-change inode device-num dired human-size + mode-type mode-owner mode-group mode-other (string t)) + "Return `file-attributes' elements of FILE separately according to key value. +Availables keys are: +- TYPE: Same as nth 0 `files-attributes' if STRING is nil + otherwise return either symlink, directory or file (default). +- LINKS: See nth 1 `files-attributes'. +- UID: See nth 2 `files-attributes'. +- GID: See nth 3 `files-attributes'. +- ACCESS-TIME: See nth 4 `files-attributes', however format time + when STRING is non--nil (the default). +- MODIF-TIME: See nth 5 `files-attributes', same as above. +- STATUS: See nth 6 `files-attributes', same as above. +- SIZE: See nth 7 `files-attributes'. +- MODE: See nth 8 `files-attributes'. +- GID-CHANGE: See nth 9 `files-attributes'. +- INODE: See nth 10 `files-attributes'. +- DEVICE-NUM: See nth 11 `files-attributes'. +- DIRED: A line similar to what 'ls -l' return. +- HUMAN-SIZE: The size in human form, see `helm-file-human-size'. +- MODE-TYPE, mode-owner,mode-group, mode-other: Split what + nth 7 `files-attributes' return in four categories. +- STRING: When non--nil (default) `helm-file-attributes' return + more friendly values. +If you want the same behavior as `files-attributes' , +\(but with return values in proplist\) use a nil value for STRING. +However when STRING is non--nil, time and type value are different from what +you have in `file-attributes'." + (helm-aif (file-attributes file string) + (let* ((all (cl-destructuring-bind + (type links uid gid access-time modif-time + status size mode gid-change inode device-num) + it + (list :type (if string + (cond ((stringp type) "symlink") ; fname + (type "directory") ; t + (t "file")) ; nil + type) + :links links + :uid uid + :gid gid + :access-time (if string + (format-time-string + "%Y-%m-%d %R" access-time) + access-time) + :modif-time (if string + (format-time-string + "%Y-%m-%d %R" modif-time) + modif-time) + :status (if string + (format-time-string + "%Y-%m-%d %R" status) + status) + :size size + :mode mode + :gid-change gid-change + :inode inode + :device-num device-num))) + (modes (helm-split-mode-file-attributes (cl-getf all :mode)))) + (cond (type (cl-getf all :type)) + (links (cl-getf all :links)) + (uid (cl-getf all :uid)) + (gid (cl-getf all :gid)) + (access-time (cl-getf all :access-time)) + (modif-time (cl-getf all :modif-time)) + (status (cl-getf all :status)) + (size (cl-getf all :size)) + (mode (cl-getf all :mode)) + (gid-change (cl-getf all :gid-change)) + (inode (cl-getf all :inode)) + (device-num (cl-getf all :device-num)) + (dired (concat + (helm-split-mode-file-attributes + (cl-getf all :mode) t) " " + (number-to-string (cl-getf all :links)) " " + (cl-getf all :uid) ":" + (cl-getf all :gid) " " + (if human-size + (helm-file-human-size (cl-getf all :size)) + (int-to-string (cl-getf all :size))) " " + (cl-getf all :modif-time))) + (human-size (helm-file-human-size (cl-getf all :size))) + (mode-type (cl-getf modes :mode-type)) + (mode-owner (cl-getf modes :user)) + (mode-group (cl-getf modes :group)) + (mode-other (cl-getf modes :other)) + (t (append all modes)))))) + +(defun helm-split-mode-file-attributes (str &optional string) + "Split mode file attributes STR into a proplist. +If STRING is non--nil return instead a space separated string." + (cl-loop with type = (substring str 0 1) + with cdr = (substring str 1) + for i across cdr + for count from 1 + if (<= count 3) + concat (string i) into user + if (and (> count 3) (<= count 6)) + concat (string i) into group + if (and (> count 6) (<= count 9)) + concat (string i) into other + finally return + (if string + (mapconcat 'identity (list type user group other) " ") + (list :mode-type type :user user :group group :other other)))) + +(defun helm-format-columns-of-files (files) + "Same as `dired-format-columns-of-files'. +Inlined here for compatibility." + (let ((beg (point))) + (completion--insert-strings files) + (put-text-property beg (point) 'mouse-face nil))) + +(defmacro with-helm-display-marked-candidates (buffer-or-name candidates &rest body) + (declare (indent 0) (debug t)) + (helm-with-gensyms (buffer window) + `(let* ((,buffer (temp-buffer-window-setup ,buffer-or-name)) + (helm-always-two-windows t) + (helm-split-window-default-side + (if (eq helm-split-window-default-side 'same) + 'below helm-split-window-default-side)) + helm-split-window-inside-p + helm-reuse-last-window-split-state + ,window) + (with-current-buffer ,buffer + (helm-format-columns-of-files ,candidates)) + (unwind-protect + (with-selected-window + (setq ,window (temp-buffer-window-show + ,buffer + '(display-buffer-below-selected + (window-height . fit-window-to-buffer)))) + (progn ,@body)) + (quit-window 'kill ,window))))) + +;;; Persistent Action Helpers +;; +;; +;; Internal +(defvar helm-match-line-overlay nil) +(defvar helm--match-item-overlays nil) + +(defun helm-highlight-current-line (&optional start end buf face) + "Highlight and underline current position" + (let* ((start (or start (line-beginning-position))) + (end (or end (1+ (line-end-position)))) + start-match end-match + (args (list start end buf)) + (case-fold-search (if helm-alive-p + (helm-set-case-fold-search) + case-fold-search))) + ;; Highlight the current line. + (if (not helm-match-line-overlay) + (setq helm-match-line-overlay (apply 'make-overlay args)) + (apply 'move-overlay helm-match-line-overlay args)) + (overlay-put helm-match-line-overlay + 'face (or face 'helm-selection-line)) + ;; Now highlight matches only if we are in helm session, we are + ;; maybe coming from helm-grep-mode or helm-moccur-mode buffers. + (when helm-alive-p + (if (or (null helm-highlight-matches-around-point-max-lines) + (zerop helm-highlight-matches-around-point-max-lines)) + (setq start-match start + end-match end) + (setq start-match + (save-excursion + (forward-line + (- helm-highlight-matches-around-point-max-lines)) + (point-at-bol)) + end-match + (save-excursion + (forward-line + helm-highlight-matches-around-point-max-lines) + (point-at-bol)))) + (catch 'empty-line + (cl-loop with ov + for r in (helm-remove-if-match + "\\`!" (helm-mm-split-pattern + (if (with-helm-buffer + ;; Needed for highlighting AG matches. + (assq 'pcre (helm-get-current-source))) + (helm--translate-pcre-to-elisp helm-input) + helm-input))) + do (save-excursion + (goto-char start-match) + (while (condition-case _err + (if helm-migemo-mode + (helm-mm-migemo-forward r end-match t) + (re-search-forward r end-match t)) + (invalid-regexp nil)) + (let ((s (match-beginning 0)) + (e (match-end 0))) + (if (= s e) + (throw 'empty-line nil) + (push (setq ov (make-overlay s e)) + helm--match-item-overlays) + (overlay-put ov 'face 'helm-match-item) + (overlay-put ov 'priority 1)))))))) + (recenter))) + +(defun helm--translate-pcre-to-elisp (regexp) + "Should translate pcre REGEXP to elisp regexp. +Assume regexp is a pcre based regexp." + (with-temp-buffer + (insert " " regexp " ") + (goto-char (point-min)) + (save-excursion + ;; match (){}| unquoted + (helm-awhile (and (re-search-forward "\\([(){}|]\\)" nil t) + (match-string 1)) + (let ((pos (match-beginning 1))) + (if (eql (char-before pos) ?\\) + (delete-region pos (1- pos)) + (replace-match (concat "\\" it) t t nil 1))))) + ;; match \s or \S + (helm-awhile (and (re-search-forward "\\S\\?\\(\\s\\[sS]\\)[^-]" nil t) + (match-string 1)) + (replace-match (concat it "-") t t nil 1)) + (buffer-substring (1+ (point-min)) (1- (point-max))))) + +(defun helm-match-line-cleanup () + (when helm-match-line-overlay + (delete-overlay helm-match-line-overlay) + (setq helm-match-line-overlay nil)) + (when helm--match-item-overlays + (mapc 'delete-overlay helm--match-item-overlays))) + +(defun helm-match-line-cleanup-maybe () + (when (helm-empty-buffer-p) + (helm-match-line-cleanup))) + +(defun helm-match-line-update () + (when helm-match-line-overlay + (delete-overlay helm-match-line-overlay) + (helm-highlight-current-line))) + +(defun helm-persistent-autoresize-hook () + (when (and helm-buffers-to-resize-on-pa + (member helm-buffer helm-buffers-to-resize-on-pa) + (eq helm-split-window-state 'vertical)) + (set-window-text-height (helm-window) helm-resize-on-pa-text-height))) + +(defun helm-match-line-cleanup-pulse () + (run-with-timer 0.3 nil #'helm-match-line-cleanup)) + +(add-hook 'helm-after-update-hook 'helm-match-line-cleanup-maybe) +(add-hook 'helm-after-persistent-action-hook 'helm-persistent-autoresize-hook) +(add-hook 'helm-cleanup-hook 'helm-match-line-cleanup) +(add-hook 'helm-after-action-hook 'helm-match-line-cleanup-pulse) +(add-hook 'helm-after-persistent-action-hook 'helm-match-line-update) + +;;; Popup buffer-name or filename in grep/moccur/imenu-all. +;; +(defvar helm--show-help-echo-timer nil) + +(defun helm-cancel-help-echo-timer () + (when helm--show-help-echo-timer + (cancel-timer helm--show-help-echo-timer) + (setq helm--show-help-echo-timer nil))) + +(defun helm-maybe-show-help-echo () + (when helm--show-help-echo-timer + (cancel-timer helm--show-help-echo-timer) + (setq helm--show-help-echo-timer nil)) + (when (and helm-alive-p + helm-popup-tip-mode + (member (assoc-default 'name (helm-get-current-source)) + helm-sources-using-help-echo-popup)) + (setq helm--show-help-echo-timer + (run-with-timer + 1 nil + (lambda () + (save-selected-window + (with-helm-window + (helm-aif (get-text-property (point-at-bol) 'help-echo) + (popup-tip (concat " " (abbreviate-file-name + (replace-regexp-in-string "\n.*" "" it))) + :around nil + :point (save-excursion + (end-of-visual-line) (point))))))))))) + +;;;###autoload +(define-minor-mode helm-popup-tip-mode + "Show help-echo informations in a popup tip at end of line." + :global t + (require 'popup) + (if helm-popup-tip-mode + (progn + (add-hook 'helm-move-selection-after-hook 'helm-maybe-show-help-echo) + (add-hook 'helm-cleanup-hook 'helm-cancel-help-echo-timer)) + (remove-hook 'helm-move-selection-after-hook 'helm-maybe-show-help-echo) + (remove-hook 'helm-cleanup-hook 'helm-cancel-help-echo-timer))) + +(defun helm-open-file-with-default-tool (file) + "Open FILE with the default tool on this platform." + (let (process-connection-type) + (if (eq system-type 'windows-nt) + (helm-w32-shell-execute-open-file file) + (start-process "helm-open-file-with-default-tool" + nil + (cond ((eq system-type 'gnu/linux) + "xdg-open") + ((or (eq system-type 'darwin) ;; Mac OS X + (eq system-type 'macos)) ;; Mac OS 9 + "open")) + file)))) + +(defun helm-open-dired (file) + "Opens a dired buffer in FILE's directory. If FILE is a +directory, open this directory." + (if (file-directory-p file) + (dired file) + (dired (file-name-directory file)) + (dired-goto-file file))) + +(defun helm-require-or-error (feature function) + (or (require feature nil t) + (error "Need %s to use `%s'." feature function))) + +(defun helm-find-file-as-root (candidate) + (let* ((buf (helm-basename candidate)) + (host (file-remote-p candidate 'host)) + (remote-path (format "/%s:%s:%s" + helm-su-or-sudo + (or host "") + (expand-file-name + (if host + (file-remote-p candidate 'localname) + candidate)))) + non-essential) + (if (buffer-live-p (get-buffer buf)) + (progn + (set-buffer buf) + (find-alternate-file remote-path)) + (find-file remote-path)))) + +(defun helm-find-many-files (_ignore) + "Simple action that run `find-file' on marked candidates. +Run `helm-find-many-files-after-hook' at end" + (let ((helm--reading-passwd-or-string t)) + (mapc 'find-file (helm-marked-candidates)) + (helm-log-run-hook 'helm-find-many-files-after-hook))) + +(defun helm-read-repeat-string (prompt &optional count) + "Prompt as many time PROMPT is not empty. +If COUNT is non--nil add a number after each prompt." + (cl-loop with elm + while (not (string= elm "")) + for n from 1 + do (when count + (setq prompt (concat prompt (int-to-string n) ": "))) + collect (setq elm (helm-read-string prompt)) into lis + finally return (remove "" lis))) + +(defun helm-html-bookmarks-to-alist (file url-regexp bmk-regexp) + "Parse html bookmark FILE and return an alist with (title . url) as elements." + (let (bookmarks-alist url title) + (with-temp-buffer + (insert-file-contents file) + (goto-char (point-min)) + (while (re-search-forward "href=\\|^ *

+ +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'helm-for-files) + + +;;; List of files gleaned from every dired buffer +;; +;; +(defun helm-files-in-all-dired-candidates () + (save-excursion + (cl-loop for (f . b) in dired-buffers + when (buffer-live-p b) + append (let ((dir (with-current-buffer b dired-directory))) + (if (listp dir) (cdr dir) + (directory-files f t dired-re-no-dot)))))) + +;; (dired '("~/" "~/.emacs.d/.emacs-custom.el" "~/.emacs.d/.emacs.bmk")) + +(defclass helm-files-dired-source (helm-source-sync helm-type-file) + ((candidates :initform #'helm-files-in-all-dired-candidates))) + +(defvar helm-source-files-in-all-dired + (helm-make-source "Files in all dired buffer." 'helm-files-dired-source)) + +;;; session.el files +;; +;; session (http://emacs-session.sourceforge.net/) is an alternative to +;; recentf that saves recent file history and much more. +(defvar session-file-alist) +(defclass helm-source-session-class (helm-source-sync) + ((candidates :initform (lambda () + (cl-delete-if-not + (lambda (f) + (or (string-match helm-tramp-file-name-regexp f) + (file-exists-p f))) + (mapcar 'car session-file-alist)))) + (keymap :initform helm-generic-files-map) + (help-message :initform helm-generic-file-help-message) + (action :initform 'helm-type-file-actions))) + +(defvar helm-source-session nil + "File list from emacs-session.") + +(defcustom helm-session-fuzzy-match nil + "Enable fuzzy matching in `helm-source-session' when non--nil." + :group 'helm-files + :type 'boolean + :set (lambda (var val) + (set var val) + (setq helm-source-session + (helm-make-source "Session" 'helm-source-session-class + :fuzzy-match val)))) + + +;;; External searching file tools. +;; +;; Tracker desktop search + +(defun helm-source-tracker-transformer (candidates _source) + ;; loop through tracker candidates selecting out file:// lines + ;; then select part after file:// and url decode to get straight filenames + (cl-loop for cand in candidates + when (and (stringp cand) + (string-match "\\`[[:space:]]*file://\\(.*\\)" cand)) + collect (url-unhex-string (match-string 1 cand)))) + +(defvar helm-source-tracker-search + (helm-build-async-source "Tracker Search" + :candidates-process + (lambda () + ;; the tracker-search command has been deprecated, now invoke via tracker + ;; also, disable the contextual snippets which we don't currently use + (start-process "tracker-search-process" nil + "tracker" "search" + "--disable-snippets" + "--disable-color" + "--limit=512" + helm-pattern)) + ;; new simplified transformer of tracker search results + :filtered-candidate-transformer #'helm-source-tracker-transformer + ;;(multiline) ; https://github.com/emacs-helm/helm/issues/529 + :keymap helm-generic-files-map + :action 'helm-type-file-actions + :action-transformer '(helm-transform-file-load-el + helm-transform-file-browse-url) + :requires-pattern 3) + "Source for retrieving files matching the current input pattern +with the tracker desktop search.") + +;; Spotlight (MacOS X desktop search) +(defclass helm-mac-spotlight-source (helm-source-async helm-type-file) + ((candidates-process :initform + (lambda () + (start-process + "mdfind-process" nil "mdfind" helm-pattern))) + (requires-pattern :initform 3))) + +(defvar helm-source-mac-spotlight + (helm-make-source "mdfind" 'helm-mac-spotlight-source) + "Source for retrieving files via Spotlight's command line +utility mdfind.") + +(provide 'helm-x-files) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-x-files.el ends here diff --git a/elpa/helm-core-20181114.621/helm-core-autoloads.el b/elpa/helm-core-20181114.621/helm-core-autoloads.el new file mode 100644 index 00000000..adc09a32 --- /dev/null +++ b/elpa/helm-core-20181114.621/helm-core-autoloads.el @@ -0,0 +1,261 @@ +;;; helm-core-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "helm" "helm.el" (0 0 0 0)) +;;; Generated autoloads from helm.el + +(autoload 'helm-define-multi-key "helm" "\ +In KEYMAP, define key sequence KEY for function list FUNCTIONS. +Each function runs sequentially for each KEY press. +If DELAY is specified, switch back to initial function of FUNCTIONS list +after DELAY seconds. +The functions in FUNCTIONS list take no args. +e.g + (defun foo () + (interactive) + (message \"Run foo\")) + (defun bar () + (interactive) + (message \"Run bar\")) + (defun baz () + (interactive) + (message \"Run baz\")) + +\(helm-define-multi-key global-map (kbd \" q\") '(foo bar baz) 2) + +Each time \" q\" is pressed, the next function is executed. Waiting +more than 2 seconds between key presses switches back to executing the first +function on the next hit. + +\(fn KEYMAP KEY FUNCTIONS &optional DELAY)" nil nil) + +(autoload 'helm-multi-key-defun "helm" "\ +Define NAME as a multi-key command running FUNS. +After DELAY seconds, the FUNS list is reinitialized. +See `helm-define-multi-key'. + +\(fn NAME DOCSTRING FUNS &optional DELAY)" nil t) + +(function-put 'helm-multi-key-defun 'lisp-indent-function '2) + +(autoload 'helm-define-key-with-subkeys "helm" "\ +Defines in MAP a KEY and SUBKEY to COMMAND. + +This allows typing KEY to call COMMAND the first time and +type only SUBKEY on subsequent calls. + +Arg MAP is the keymap to use, SUBKEY is the initial short key-binding to +call COMMAND. + +Arg OTHER-SUBKEYS is an alist specifying other short key-bindings +to use once started e.g: + + (helm-define-key-with-subkeys global-map + (kbd \"C-x v n\") ?n 'git-gutter:next-hunk '((?p . git-gutter:previous-hunk))) + + +In this example, `C-x v n' will run `git-gutter:next-hunk' +subsequent \"n\"'s run this command again +and subsequent \"p\"'s run `git-gutter:previous-hunk'. + +If specified PROMPT can be displayed in minibuffer to +describe SUBKEY and OTHER-SUBKEYS. +Arg EXIT-FN specifies a function to run on exit. + +For any other keys pressed, run their assigned command as defined +in MAP and then exit the loop running EXIT-FN, if specified. + +NOTE: SUBKEY and OTHER-SUBKEYS bindings support only char syntax and +vectors, so don't use strings to define them. + +\(fn MAP KEY SUBKEY COMMAND &optional OTHER-SUBKEYS PROMPT EXIT-FN)" nil nil) + +(function-put 'helm-define-key-with-subkeys 'lisp-indent-function '1) + +(autoload 'helm-debug-open-last-log "helm" "\ +Open helm log file or buffer of last helm session. + +\(fn)" t nil) + +(autoload 'helm "helm" "\ +Main function to execute helm sources. + +PLIST is a list like + +\(:key1 val1 :key2 val2 ...) + + or + +\(&optional sources input prompt resume preselect + buffer keymap default history allow-nest). + +** Keywords + +Keywords supported: + +- :sources +- :input +- :prompt +- :resume +- :preselect +- :buffer +- :keymap +- :default +- :history +- :allow-nest + +Extra LOCAL-VARS keywords are supported, see the \"** Other +keywords\" section below. + +Basic keywords are the following: + +*** :sources + +One of the following: + +- List of sources +- Symbol whose value is a list of sources +- Alist representing a Helm source. + - In this case the source has no name and is referenced in + `helm-sources' as a whole alist. + +*** :input + +Initial input of minibuffer (temporary value of `helm-pattern') + +*** :prompt + +Minibuffer prompt. Default value is `helm--prompt'. + +*** :resume + +If t, allow resumption of the previous session of this Helm +command, skipping initialization. + +If 'noresume, this instance of `helm' cannot be resumed. + +*** :preselect + +Initially selected candidate (string or regexp). + +*** :buffer + +Buffer name for this Helm session. `helm-buffer' will take this value. + +*** :keymap + +\[Obsolete] + +Keymap used at the start of this Helm session. + +It is overridden by keymaps specified in sources, and is kept +only for backward compatibility. + +Keymaps should be specified in sources using the :keymap slot +instead. See `helm-source'. + +This keymap is not restored by `helm-resume'. + +*** :default + +Default value inserted into the minibuffer with +\\\\[next-history-element]. + +It can be a string or a list of strings, in this case +\\\\[next-history-element] cycles through +the list items, starting with the first. + +If nil, `thing-at-point' is used. + +If `helm--maybe-use-default-as-input' is non-`nil', display is +updated using this value, unless :input is specified, in which +case that value is used instead. + +*** :history + +Minibuffer input, by default, is pushed to `minibuffer-history'. + +When an argument HISTORY is provided, input is pushed to +HISTORY. HISTORY should be a valid symbol. + +*** :allow-nest + +Allow running this Helm command in a running Helm session. + +** Other keywords + +Other keywords are interpreted as local variables of this Helm +session. The `helm-' prefix can be omitted. For example, + +\(helm :sources 'helm-source-buffers-list + :buffer \"*helm buffers*\" + :candidate-number-limit 10) + +starts a Helm session with the variable +`helm-candidate-number-limit' set to 10. + +** Backward compatibility + +For backward compatibility, positional parameters are +supported: + +\(helm sources input prompt resume preselect + buffer keymap default history allow-nest) + +However, the use of non-keyword args is deprecated. + +\(fn &key SOURCES INPUT PROMPT RESUME PRESELECT BUFFER KEYMAP DEFAULT HISTORY ALLOW-NEST OTHER-LOCAL-VARS)" nil nil) + +(autoload 'helm-cycle-resume "helm" "\ +Cycle in `helm-buffers' list and resume when waiting more than 1.2s. + +\(fn)" t nil) + +(autoload 'helm-other-buffer "helm" "\ +Simplified `helm' interface with other `helm-buffer'. +Call `helm' only with ANY-SOURCES and ANY-BUFFER as args. + +\(fn ANY-SOURCES ANY-BUFFER)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm" '("helm-" "with-helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-lib" "helm-lib.el" (0 0 0 0)) +;;; Generated autoloads from helm-lib.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-lib" '("helm-" "with-helm-"))) + +;;;*** + +;;;### (autoloads nil "helm-multi-match" "helm-multi-match.el" (0 +;;;;;; 0 0 0)) +;;; Generated autoloads from helm-multi-match.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-multi-match" '("helm-m"))) + +;;;*** + +;;;### (autoloads nil "helm-source" "helm-source.el" (0 0 0 0)) +;;; Generated autoloads from helm-source.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "helm-source" '("helm-"))) + +;;;*** + +;;;### (autoloads nil nil ("helm-core-pkg.el") (0 0 0 0)) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; helm-core-autoloads.el ends here diff --git a/elpa/helm-core-20181114.621/helm-core-pkg.el b/elpa/helm-core-20181114.621/helm-core-pkg.el new file mode 100644 index 00000000..c1e5d40c --- /dev/null +++ b/elpa/helm-core-20181114.621/helm-core-pkg.el @@ -0,0 +1,7 @@ +(define-package "helm-core" "20181114.621" "Development files for Helm" + '((emacs "24.4") + (async "1.9.3")) + :url "https://emacs-helm.github.io/helm/") +;; Local Variables: +;; no-byte-compile: t +;; End: diff --git a/elpa/helm-core-20181114.621/helm-lib.el b/elpa/helm-core-20181114.621/helm-lib.el new file mode 100644 index 00000000..4c74a809 --- /dev/null +++ b/elpa/helm-core-20181114.621/helm-lib.el @@ -0,0 +1,1379 @@ +;;; helm-lib.el --- Helm routines. -*- lexical-binding: t -*- + +;; Copyright (C) 2015 ~ 2018 Thierry Volpiatto + +;; Author: Thierry Volpiatto +;; URL: http://github.com/emacs-helm/helm + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Commentary: +;; All helm functions that don't require specific helm code should go here. + +;;; Code: + +(require 'cl-lib) +(eval-when-compile (require 'wdired)) + +(declare-function helm-get-sources "helm.el") +(declare-function helm-marked-candidates "helm.el") +(declare-function helm-follow-mode-p "helm.el") +(declare-function helm-attr "helm.el") +(declare-function helm-attrset "helm.el") +(declare-function org-open-at-point "org.el") +(declare-function org-content "org.el") +(declare-function org-mark-ring-goto "org.el") +(declare-function org-mark-ring-push "org.el") +(declare-function helm-interpret-value "helm.el") +(declare-function helm-get-current-source "helm.el") +(defvar helm-sources) +(defvar helm-initial-frame) +(defvar helm-current-position) +(defvar wdired-old-marks) +(defvar helm-persistent-action-display-window) + +;;; User vars. +;; +(defcustom helm-file-globstar t + "Same as globstar bash shopt option. +When non--nil a pattern beginning with two stars will expand recursively. +Directories expansion is not supported yet." + :group 'helm + :type 'boolean) + +(defcustom helm-yank-text-at-point-function nil + "The function used to forward point with `helm-yank-text-at-point'. +With a nil value, fallback to default `forward-word'. +The function should take one arg, an integer like `forward-word'. +NOTE: Using `forward-symbol' here is not very useful as it is already +provided by \\\\[next-history-element]." + :type 'function + :group 'helm) + +(defcustom helm-scroll-amount nil + "Scroll amount when scrolling other window in a helm session. +It is used by `helm-scroll-other-window' +and `helm-scroll-other-window-down'. + +If you prefer scrolling line by line, set this value to 1." + :group 'helm + :type 'integer) + +(defcustom helm-help-full-frame t + "Display help window in full frame when non nil. + +Even when `nil' probably the same result (full frame) +can be reach by tweaking `display-buffer-alist' but it is +much more convenient to use a simple boolean value here." + :type 'boolean + :group 'helm-help) + +(defvar helm-ff--boring-regexp nil) +(defun helm-ff--setup-boring-regex (var val) + (set var val) + (setq helm-ff--boring-regexp + (cl-loop with last = (car (last val)) + for r in (butlast val) + if (string-match "\\$\\'" r) + concat (concat r "\\|") into result + else concat (concat r "$\\|") into result + finally return + (concat result last + (if (string-match "\\$\\'" last) "" "$"))))) + +(defcustom helm-boring-file-regexp-list + (mapcar (lambda (f) + (let ((rgx (regexp-quote f))) + (if (string-match-p "[^/]$" f) + ;; files: e.g .o => \\.o$ + (concat rgx "$") + ;; directories: e.g .git/ => \.git\\(/\\|$\\) + (concat (substring rgx 0 -1) "\\(/\\|$\\)")))) + completion-ignored-extensions) + "A list of regexps matching boring files. + +This list is build by default on `completion-ignored-extensions'. +The directory names should end with \"/?\" e.g. \"\\.git/?\" and the +file names should end with \"$\" e.g. \"\\.o$\". + +These regexps may be used to match the entire path, not just the file +name, so for example to ignore files with a prefix \".bak.\", use +\"\\.bak\\..*$\" as the regexp. + +NOTE: When modifying this, be sure to use customize interface or the +customize functions e.g. `customize-set-variable' and NOT `setq'." + :group 'helm-files + :type '(repeat (choice regexp)) + :set 'helm-ff--setup-boring-regex) + + +;;; Internal vars +;; +(defvar helm-yank-point nil) +(defvar helm-pattern "" + "The input pattern used to update the helm buffer.") +(defvar helm-buffer "*helm*" + "Buffer showing completions.") +(defvar helm-current-buffer nil + "Current buffer when `helm' is invoked.") +(defvar helm-suspend-update-flag nil) +(defvar helm-action-buffer "*helm action*" + "Buffer showing actions.") + + +;;; Compatibility +;; +(defun helm-add-face-text-properties (beg end face &optional append object) + "Add the face property to the text from START to END. +It is a compatibility function which behave exactly like +`add-face-text-property' if available otherwise like `add-text-properties'. +When only `add-text-properties' is available APPEND is ignored." + (if (fboundp 'add-face-text-property) + (add-face-text-property beg end face append object) + (add-text-properties beg end `(face ,face) object))) + +;; Override `wdired-finish-edit'. +;; Fix emacs bug in `wdired-finish-edit' where +;; Wdired is not handling the case where `dired-directory' is a cons +;; cell instead of a string. +(defun helm--advice-wdired-finish-edit () + (interactive) + (wdired-change-to-dired-mode) + (let ((changes nil) + (errors 0) + files-deleted + files-renamed + some-file-names-unchanged + file-old file-new tmp-value) + (save-excursion + (when (and wdired-allow-to-redirect-links + (fboundp 'make-symbolic-link)) + (setq tmp-value (wdired-do-symlink-changes)) + (setq errors (cdr tmp-value)) + (setq changes (car tmp-value))) + (when (and wdired-allow-to-change-permissions + (boundp 'wdired-col-perm)) ; could have been changed + (setq tmp-value (wdired-do-perm-changes)) + (setq errors (+ errors (cdr tmp-value))) + (setq changes (or changes (car tmp-value)))) + (goto-char (point-max)) + (while (not (bobp)) + (setq file-old (wdired-get-filename nil t)) + (when file-old + (setq file-new (wdired-get-filename)) + (if (equal file-new file-old) + (setq some-file-names-unchanged t) + (setq changes t) + (if (not file-new) ;empty filename! + (push file-old files-deleted) + (when wdired-keep-marker-rename + (let ((mark (cond ((integerp wdired-keep-marker-rename) + wdired-keep-marker-rename) + (wdired-keep-marker-rename + (cdr (assoc file-old wdired-old-marks))) + (t nil)))) + (when mark + (push (cons (substitute-in-file-name file-new) mark) + wdired-old-marks)))) + (push (cons file-old (substitute-in-file-name file-new)) + files-renamed)))) + (forward-line -1))) + (when files-renamed + (setq errors (+ errors (wdired-do-renames files-renamed)))) + (if changes + (progn + ;; If we are displaying a single file (rather than the + ;; contents of a directory), change dired-directory if that + ;; file was renamed. (This ought to be generalized to + ;; handle the multiple files case, but that's less trivial) + ;; fixit [1]. + (cond ((and (stringp dired-directory) + (not (file-directory-p dired-directory)) + (null some-file-names-unchanged) + (= (length files-renamed) 1)) + (setq dired-directory (cdr (car files-renamed)))) + ;; Fix [1] i.e dired buffers created with + ;; (dired '(foo f1 f2 f3)). + ((and (consp dired-directory) + (cdr dired-directory) + files-renamed) + (setcdr dired-directory + ;; Replace in `dired-directory' files that have + ;; been modified with their new name keeping + ;; the ones that are unmodified at the same place. + (cl-loop with old-to-rename = (mapcar 'car files-renamed) + for f in (cdr dired-directory) + if (member f old-to-rename) + collect (assoc-default f files-renamed) + else collect f)))) + ;; Re-sort the buffer if all went well. + (unless (> errors 0) (revert-buffer)) + (let ((inhibit-read-only t)) + (dired-mark-remembered wdired-old-marks))) + (let ((inhibit-read-only t)) + (remove-text-properties (point-min) (point-max) + '(old-name nil end-name nil old-link nil + end-link nil end-perm nil + old-perm nil perm-changed nil)) + (message "(No changes to be performed)"))) + (when files-deleted + (wdired-flag-for-deletion files-deleted)) + (when (> errors 0) + (dired-log-summary (format "%d rename actions failed" errors) nil))) + (set-buffer-modified-p nil) + (setq buffer-undo-list nil)) + +;; Override `wdired-get-filename'. +;; Fix emacs bug in `wdired-get-filename' which returns the current +;; directory concatened with the filename i.e +;; "/home/you//home/you/foo" when filename is absolute in dired +;; buffer. +;; In consequence Wdired try to rename files even when buffer have +;; been modified and corrected, e.g delete one char and replace it so +;; that no change to file is done. +;; This also lead to ask confirmation for every files even when not +;; modified and when `wdired-use-interactive-rename' is nil. +(defun helm--advice-wdired-get-filename (&optional no-dir old) + ;; FIXME: Use dired-get-filename's new properties. + (let (beg end file) + (save-excursion + (setq end (line-end-position)) + (beginning-of-line) + (setq beg (next-single-property-change (point) 'old-name nil end)) + (unless (eq beg end) + (if old + (setq file (get-text-property beg 'old-name)) + ;; In the following form changed `(1+ beg)' to `beg' so that + ;; the filename end is found even when the filename is empty. + ;; Fixes error and spurious newlines when marking files for + ;; deletion. + (setq end (next-single-property-change beg 'end-name)) + (setq file (buffer-substring-no-properties (1+ beg) end))) + ;; Don't unquote the old name, it wasn't quoted in the first place + (and file (setq file (condition-case _err + ;; emacs-25+ + (apply #'wdired-normalize-filename + (list file (not old))) + (wrong-number-of-arguments + ;; emacs-24 + (wdired-normalize-filename file)))))) + (if (or no-dir old (and file (file-name-absolute-p file))) + file + (and file (> (length file) 0) + (expand-file-name file (dired-current-directory))))))) + +;;; Override `push-mark' +;; +;; Fix duplicates in `mark-ring' and `global-mark-ring' and update +;; buffers in `global-mark-ring' to recentest mark. +(defun helm--advice-push-mark (&optional location nomsg activate) + (unless (null (mark t)) + (let ((marker (copy-marker (mark-marker)))) + (setq mark-ring (cons marker (delete marker mark-ring)))) + (when (> (length mark-ring) mark-ring-max) + ;; Move marker to nowhere. + (set-marker (car (nthcdr mark-ring-max mark-ring)) nil) + (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil))) + (set-marker (mark-marker) (or location (point)) (current-buffer)) + ;; Now push the mark on the global mark ring. + (setq global-mark-ring (cons (copy-marker (mark-marker)) + ;; Avoid having multiple entries + ;; for same buffer in `global-mark-ring'. + (cl-loop with mb = (current-buffer) + for m in global-mark-ring + for nmb = (marker-buffer m) + unless (eq mb nmb) + collect m))) + (when (> (length global-mark-ring) global-mark-ring-max) + (set-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil) + (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)) + (or nomsg executing-kbd-macro (> (minibuffer-depth) 0) + (message "Mark set")) + (when (or activate (not transient-mark-mode)) + (set-mark (mark t))) + nil) + +(defcustom helm-advice-push-mark t + "Override `push-mark' with a version avoiding duplicates when non nil." + :group 'helm + :type 'boolean + :set (lambda (var val) + (set var val) + (if val + (advice-add 'push-mark :override #'helm--advice-push-mark) + (advice-remove 'push-mark #'helm--advice-push-mark)))) + +;;; Macros helper. +;; +(defmacro helm-with-gensyms (symbols &rest body) + "Bind the SYMBOLS to fresh uninterned symbols and eval BODY." + (declare (indent 1)) + `(let ,(mapcar (lambda (s) + ;; Use cl-gensym here instead of make-symbol + ;; to ensure a symbol that have a live that go + ;; beyond the live of its macro have different name. + ;; i.e symbols created with `with-helm-temp-hook' + ;; should have random names. + `(,s (cl-gensym (symbol-name ',s)))) + symbols) + ,@body)) + +;;; Command loop helper +;; +(defun helm-this-command () + "Returns the actual command in action. +Like `this-command' but return the real command, +and not `exit-minibuffer' or other unwanted functions." + (cl-loop with bl = '(helm-maybe-exit-minibuffer + helm-confirm-and-exit-minibuffer + helm-exit-minibuffer + exit-minibuffer) + for count from 1 to 50 + for btf = (backtrace-frame count) + for fn = (cl-second btf) + if (and + ;; In some case we may have in the way an + ;; advice compiled resulting in byte-code, + ;; ignore it (Issue #691). + (symbolp fn) + (commandp fn) + (not (memq fn bl))) + return fn + else + if (and (eq fn 'call-interactively) + (> (length btf) 2)) + return (cadr (cdr btf)))) + + +;;; Iterators +;; +(cl-defmacro helm-position (item seq &key test all) + "A simple and faster replacement of CL `position'. + +Returns ITEM first occurence position found in SEQ. +When SEQ is a string, ITEM have to be specified as a char. +Argument TEST when unspecified default to `eq'. +When argument ALL is non--nil return a list of all ITEM positions +found in SEQ." + (let ((key (if (stringp seq) 'across 'in))) + `(cl-loop with deftest = 'eq + for c ,key ,seq + for index from 0 + when (funcall (or ,test deftest) c ,item) + if ,all collect index into ls + else return index + finally return ls))) + +(defun helm-iter-list (seq) + "Return an iterator object from SEQ." + (let ((lis seq)) + (lambda () + (let ((elm (car lis))) + (setq lis (cdr lis)) + elm)))) + +(defun helm-iter-circular (seq) + "Infinite iteration on SEQ." + (let ((lis seq)) + (lambda () + (let ((elm (car lis))) + (setq lis (pcase lis (`(,_ . ,ll) (or ll seq)))) + elm)))) + +(cl-defun helm-iter-sub-next-circular (seq elm &key (test 'eq)) + "Infinite iteration of SEQ starting at ELM." + (let* ((pos (1+ (helm-position elm seq :test test))) + (sub (append (nthcdr pos seq) (cl-subseq seq 0 pos))) + (iterator (helm-iter-circular sub))) + (lambda () + (helm-iter-next iterator)))) + +(defun helm-iter-next (iterator) + "Return next elm of ITERATOR." + (and iterator (funcall iterator))) + + +;;; Anaphoric macros. +;; +(defmacro helm-aif (test-form then-form &rest else-forms) + "Anaphoric version of `if'. +Like `if' but set the result of TEST-FORM in a temporary variable called `it'. +THEN-FORM and ELSE-FORMS are then excuted just like in `if'." + (declare (indent 2) (debug t)) + `(let ((it ,test-form)) + (if it ,then-form ,@else-forms))) + +(defmacro helm-awhile (sexp &rest body) + "Anaphoric version of `while'. +Same usage as `while' except that SEXP is bound to +a temporary variable called `it' at each turn. +An implicit nil block is bound to the loop so usage +of `cl-return' is possible to exit the loop." + (declare (indent 1) (debug t)) + (helm-with-gensyms (flag) + `(let ((,flag t)) + (cl-block nil + (while ,flag + (helm-aif ,sexp + (progn ,@body) + (setq ,flag nil))))))) + +(defmacro helm-acond (&rest clauses) + "Anaphoric version of `cond'. +In each clause of CLAUSES, the result of the car of clause +is stored in a temporary variable called `it' and usable in the cdr +of this same clause. Each `it' variable is independent of its clause. +The usage is the same as `cond'." + (declare (debug cond)) + (unless (null clauses) + (helm-with-gensyms (sym) + (let ((clause1 (car clauses))) + `(let ((,sym ,(car clause1))) + (helm-aif ,sym + (if (cdr ',clause1) + (progn ,@(cdr clause1)) + it) + (helm-acond ,@(cdr clauses)))))))) + +(defmacro helm-aand (&rest conditions) + "Anaphoric version of `and'. +Each condition is bound to a temporary variable called `it' which is +usable in next condition." + (declare (debug (&rest form))) + (cond ((null conditions) t) + ((null (cdr conditions)) (car conditions)) + (t `(helm-aif ,(car conditions) + (helm-aand ,@(cdr conditions)))))) + +(defmacro helm-acase (expr &rest clauses) + "A simple anaphoric `cl-case' implementation handling strings. +EXPR is bound to a temporary variable called `it' which is usable in +CLAUSES to refer to EXPR. +NOTE: Duplicate keys in CLAUSES are deliberately not handled." + (declare (indent 1) (debug t)) + (unless (null clauses) + (let ((clause1 (car clauses))) + `(let ((key ',(car clause1)) + (it ,expr)) + (if (or (equal it key) + (eq key t) + (and (listp key) (member it key))) + (progn ,@(cdr clause1)) + (helm-acase it ,@(cdr clauses))))))) + +;;; Fuzzy matching routines +;; +(defsubst helm--mapconcat-pattern (pattern) + "Transform string PATTERN in regexp for further fuzzy matching. +e.g helm.el$ + => \"[^h]*h[^e]*e[^l]*l[^m]*m[^.]*[.][^e]*e[^l]*l$\" + ^helm.el$ + => \"helm[.]el$\"." + (let ((ls (split-string-and-unquote pattern ""))) + (if (string= "^" (car ls)) + ;; Exact match. + (mapconcat (lambda (c) + (if (and (string= c "$") + (string-match "$\\'" pattern)) + c (regexp-quote c))) + (cdr ls) "") + ;; Fuzzy match. + (mapconcat (lambda (c) + (if (and (string= c "$") + (string-match "$\\'" pattern)) + c (format "[^%s]*%s" c (regexp-quote c)))) + ls "")))) + +(defsubst helm--collect-pairs-in-string (string) + (cl-loop for str on (split-string string "" t) by 'cdr + when (cdr str) + collect (list (car str) (cadr str)))) + +;;; Help routines. +;; +(defun helm-help-internal (bufname insert-content-fn) + "Show long message during `helm' session in BUFNAME. +INSERT-CONTENT-FN is the function that insert +text to be displayed in BUFNAME." + (let ((winconf (current-frame-configuration)) + (hframe (selected-frame))) + (with-selected-frame helm-initial-frame + (select-frame-set-input-focus helm-initial-frame) + (unwind-protect + (progn + (setq helm-suspend-update-flag t) + (set-buffer (get-buffer-create bufname)) + (switch-to-buffer bufname) + (when helm-help-full-frame (delete-other-windows)) + (delete-region (point-min) (point-max)) + (org-mode) + (org-mark-ring-push) ; Put mark at bob + (save-excursion + (funcall insert-content-fn)) + (buffer-disable-undo) + (helm-help-event-loop)) + (raise-frame hframe) + (setq helm-suspend-update-flag nil) + (set-frame-configuration winconf))))) + +(defun helm-help-scroll-up (amount) + (condition-case _err + (scroll-up-command amount) + (beginning-of-buffer nil) + (end-of-buffer nil))) + +(defun helm-help-scroll-down (amount) + (condition-case _err + (scroll-down-command amount) + (beginning-of-buffer nil) + (end-of-buffer nil))) + +(defun helm-help-next-line () + (condition-case _err + (call-interactively #'next-line) + (beginning-of-buffer nil) + (end-of-buffer nil))) + +(defun helm-help-previous-line () + (condition-case _err + (call-interactively #'previous-line) + (beginning-of-buffer nil) + (end-of-buffer nil))) + +(defun helm-help-toggle-mark () + (if (region-active-p) + (deactivate-mark) + (push-mark nil nil t))) + +;; For movement of cursor in help buffer we need to call interactively +;; commands for impaired people using a synthetizer (#1347). +(defun helm-help-event-loop () + (let ((prompt (propertize + "[SPC,C-v,next:ScrollUp b,M-v,prior:ScrollDown TAB:Cycle M-TAB:All C-s/r:Isearch q:Quit]" + 'face 'helm-helper)) + scroll-error-top-bottom + (iter-org-state (helm-iter-circular '(1 (16) (64))))) + (helm-awhile (read-key prompt) + (cl-case it + ((?\C-v ? next) (helm-help-scroll-up helm-scroll-amount)) + ((?\M-v ?b prior) (helm-help-scroll-down helm-scroll-amount)) + (?\C-s (isearch-forward)) + (?\C-r (isearch-backward)) + (?\C-a (call-interactively #'move-beginning-of-line)) + (?\C-e (call-interactively #'move-end-of-line)) + ((?\C-f right) (call-interactively #'forward-char)) + ((?\C-b left) (call-interactively #'backward-char)) + ((?\C-n down) (helm-help-next-line)) + ((?\C-p up) (helm-help-previous-line)) + (?\M-a (call-interactively #'backward-sentence)) + (?\M-e (call-interactively #'forward-sentence)) + (?\M-f (call-interactively #'forward-word)) + (?\M-b (call-interactively #'backward-word)) + (?\M-> (call-interactively #'end-of-buffer)) + (?\M-< (call-interactively #'beginning-of-buffer)) + (?\C- (helm-help-toggle-mark)) + (?\t (org-cycle)) + (?\C-m (ignore-errors (call-interactively #'org-open-at-point))) + (?\C-& (ignore-errors (call-interactively #'org-mark-ring-goto))) + (?\C-% (call-interactively #'org-mark-ring-push)) + (?\M-\t (pcase (helm-iter-next iter-org-state) + ((pred numberp) (org-content)) + ((and state) (org-cycle state)))) + (?\M-w (copy-region-as-kill + (region-beginning) (region-end)) + (deactivate-mark)) + (?q (cl-return)) + (t (ignore)))))) + + +;;; Multiline transformer +;; +(defun helm-multiline-transformer (candidates _source) + (cl-loop with offset = (helm-interpret-value + (assoc-default 'multiline (helm-get-current-source))) + for i in candidates + if (numberp offset) + collect (cons (helm--multiline-get-truncated-candidate i offset) i) + else collect i)) + +(defun helm--multiline-get-truncated-candidate (candidate offset) + "Truncate CANDIDATE when its length is > than OFFSET." + (with-temp-buffer + (insert candidate) + (goto-char (point-min)) + (if (and offset + (> (buffer-size) offset)) + (let ((end-str "[...]")) + (concat + (buffer-substring + (point) + (save-excursion + (forward-char offset) + (setq end-str (if (looking-at "\n") + end-str (concat "\n" end-str))) + (point))) + end-str)) + (buffer-string)))) + +;;; List processing +;; +(defun helm-flatten-list (seq &optional omit-nulls) + "Return a list of all single elements of sublists in SEQ." + (let (result) + (cl-labels ((flatten (seq) + (cl-loop + for elm in seq + if (and (or elm + (null omit-nulls)) + (or (atom elm) + (functionp elm) + (and (consp elm) + (cdr elm) + (atom (cdr elm))))) + do (push elm result) + else do (flatten elm)))) + (flatten seq)) + (nreverse result))) + +(defun helm-mklist (obj) + "If OBJ is a list \(but not lambda\), return itself. +Otherwise make a list with one element." + (if (and (listp obj) (not (functionp obj))) + obj + (list obj))) + +(cl-defun helm-fast-remove-dups (seq &key (test 'eq)) + "Remove duplicates elements in list SEQ. + +This is same as `remove-duplicates' but with memoisation. +It is much faster, especially in large lists. +A test function can be provided with TEST argument key. +Default is `eq'. +NOTE: Comparison of special elisp objects (e.g. markers etc...) fails +because their printed representations which are stored in hash-table +can't be compared with with the real object in SEQ. +This is a bug in `puthash' which store the printable representation of +object instead of storing the object itself, this to provide at the +end a printable representation of hashtable itself." + (cl-loop with cont = (make-hash-table :test test) + for elm in seq + unless (gethash elm cont) + collect (puthash elm elm cont))) + +(defsubst helm--string-join (strings &optional separator) + "Join all STRINGS using SEPARATOR." + (mapconcat 'identity strings separator)) + +(defun helm--concat-regexps (regexp-list) + "Return a regexp which matches any of the regexps in REGEXP-LIST." + (if regexp-list + (concat "\\(?:" (helm--string-join regexp-list "\\)\\|\\(?:") "\\)") + "\\<\\>")) ; Match nothing + +(defun helm-skip-entries (seq black-regexp-list &optional white-regexp-list) + "Remove entries which matches one of REGEXP-LIST from SEQ." + (let ((black-regexp (helm--concat-regexps black-regexp-list)) + (white-regexp (helm--concat-regexps white-regexp-list))) + (cl-loop for i in seq + unless (and (stringp i) + (string-match-p black-regexp i) + (null + (string-match-p white-regexp i))) + collect i))) + +(defun helm-boring-directory-p (directory black-list) + "Check if one regexp in BLACK-LIST match DIRECTORY." + (helm-awhile (helm-basedir (directory-file-name + (expand-file-name directory))) + (when (string= it "/") (cl-return nil)) + (when (cl-loop for r in black-list + thereis (string-match-p + r (directory-file-name directory))) + (cl-return t)) + (setq directory it))) + +(defun helm-shadow-entries (seq regexp-list) + "Put shadow property on entries in SEQ matching a regexp in REGEXP-LIST." + (let ((face 'italic)) + (cl-loop for i in seq + if (cl-loop for regexp in regexp-list + thereis (and (stringp i) + (string-match regexp i))) + collect (propertize i 'face face) + else collect i))) + +(defun helm-remove-if-not-match (regexp seq) + "Remove all elements of SEQ that don't match REGEXP." + (cl-loop for s in seq + for str = (cond ((symbolp s) + (symbol-name s)) + ((consp s) + (car s)) + (t s)) + when (string-match-p regexp str) + collect s)) + +(defun helm-remove-if-match (regexp seq) + "Remove all elements of SEQ that match REGEXP." + (cl-loop for s in seq + for str = (cond ((symbolp s) + (symbol-name s)) + ((consp s) + (car s)) + (t s)) + unless (string-match-p regexp str) + collect s)) + +(defun helm-transform-mapcar (function args) + "`mapcar' for candidate-transformer. + +ARGS is (cand1 cand2 ...) or ((disp1 . real1) (disp2 . real2) ...) + +\(helm-transform-mapcar 'upcase '(\"foo\" \"bar\")) +=> (\"FOO\" \"BAR\") +\(helm-transform-mapcar 'upcase '((\"1st\" . \"foo\") (\"2nd\" . \"bar\"))) +=> ((\"1st\" . \"FOO\") (\"2nd\" . \"BAR\")) +" + (cl-loop for arg in args + if (consp arg) + collect (cons (car arg) (funcall function (cdr arg))) + else + collect (funcall function arg))) + +(defun helm-append-at-nth (seq elm index) + "Append ELM at INDEX in SEQ." + (let ((len (length seq))) + (cond ((> index len) (setq index len)) + ((< index 0) (setq index 0))) + (if (zerop index) + (append elm seq) + (cl-loop for i in seq + for count from 1 collect i + when (= count index) + if (listp elm) append elm + else collect elm)))) + +(defun helm-source-by-name (name &optional sources) + "Get a Helm source in SOURCES by NAME. + +Optional argument SOURCES is a list of Helm sources which default to +`helm-sources'." + (cl-loop with src-list = (if sources + (cl-loop for src in sources + collect (if (listp src) + src + (symbol-value src))) + helm-sources) + for source in src-list + thereis (and (string= name (assoc-default 'name source)) source))) + +(defun helm-make-actions (&rest args) + "Build an alist with (NAME . ACTION) elements with each pairs in ARGS. +Where NAME is a string or a function returning a string or nil and ACTION +a function. +If NAME returns nil the pair is skipped. + +\(fn NAME ACTION ...)" + (cl-loop for (name fn) on args by #'cddr + when (functionp name) + do (setq name (funcall name)) + when name + collect (cons name fn))) + +;;; Strings processing. +;; +(defun helm-stringify (elm) + "Return the representation of ELM as a string. +ELM can be a string, a number or a symbol." + (cl-typecase elm + (string elm) + (number (number-to-string elm)) + (symbol (symbol-name elm)))) + +(defun helm-substring (str width) + "Return the substring of string STR from 0 to WIDTH. +Handle multibyte characters by moving by columns." + (with-temp-buffer + (save-excursion + (insert str)) + (move-to-column width) + (buffer-substring (point-at-bol) (point)))) + +(defun helm-substring-by-width (str width &optional endstr) + "Truncate string STR to end at column WIDTH. +Similar to `truncate-string-to-width'. +Add ENDSTR at end of truncated STR. +Add spaces at end if needed to reach WIDTH when STR is shorter than WIDTH." + (cl-loop for ini-str = str + then (substring ini-str 0 (1- (length ini-str))) + for sw = (string-width ini-str) + when (<= sw width) return + (concat ini-str endstr (make-string (- width sw) ? )))) + +(defun helm-string-multibyte-p (str) + "Check if string STR contains multibyte characters." + (cl-loop for c across str + thereis (> (char-width c) 1))) + +(defun helm-get-pid-from-process-name (process-name) + "Get pid from running process PROCESS-NAME." + (cl-loop with process-list = (list-system-processes) + for pid in process-list + for process = (assoc-default 'comm (process-attributes pid)) + when (and process (string-match process-name process)) + return pid)) + +(defun helm-ff-find-printers () + "Return a list of available printers on Unix systems." + (when (executable-find "lpstat") + (let ((printer-list (with-temp-buffer + (call-process "lpstat" nil t nil "-a") + (split-string (buffer-string) "\n")))) + (cl-loop for p in printer-list + for printer = (car (split-string p)) + when printer + collect printer)))) + +(defun helm-region-active-p () + (and transient-mark-mode mark-active (/= (mark) (point)))) + +(defun helm-quote-whitespace (candidate) + "Quote whitespace, if some, in string CANDIDATE." + (replace-regexp-in-string " " "\\\\ " candidate)) + +(defun helm-current-line-contents () + "Current line string without properties." + (buffer-substring-no-properties (point-at-bol) (point-at-eol))) + +(defun helm--replace-regexp-in-buffer-string (regexp rep str &optional fixedcase literal subexp start) + "Replace REGEXP by REP in string STR. + +Same as `replace-regexp-in-string' but handle properly REP as +function with SUBEXP specified. + +e.g + + (helm--replace-regexp-in-buffer-string \"e\\\\(m\\\\)acs\" 'upcase \"emacs\" t nil 1) + => \"eMacs\" + + (replace-regexp-in-string \"e\\\\(m\\\\)acs\" 'upcase \"emacs\" t nil 1) + => \"eEMACSacs\" + +Also START argument behave as expected unlike +`replace-regexp-in-string'. + +e.g + + (helm--replace-regexp-in-buffer-string \"f\" \"r\" \"foofoo\" t nil nil 3) + => \"fooroo\" + + (replace-regexp-in-string \"f\" \"r\" \"foofoo\" t nil nil 3) + => \"roo\" + +Unlike `replace-regexp-in-string' this function is buffer-based +implemented i.e replacement is computed inside a temp buffer, so +REGEXP should be used differently than with +`replace-regexp-in-string'. + +NOTE: This function is used internally for +`helm-ff-query-replace-on-filenames' and builded for this. +You should use `replace-regexp-in-string' instead unless the behavior +of this function is really needed." + (with-temp-buffer + (insert str) + (goto-char (or start (point-min))) + (while (re-search-forward regexp nil t) + (replace-match (cond ((and (functionp rep) subexp) + (funcall rep (match-string subexp))) + ((functionp rep) + (funcall rep str)) + (t rep)) + fixedcase literal nil subexp)) + (buffer-string))) + +(defun helm-url-unhex-string (str) + "Same as `url-unhex-string' but ensure STR is completely decoded." + (setq str (or str "")) + (with-temp-buffer + (save-excursion (insert str)) + (while (re-search-forward "%[A-Za-z0-9]\\{2\\}" nil t) + (replace-match (byte-to-string (string-to-number + (substring (match-string 0) 1) + 16)) + t t) + ;; Restart from beginning until string is completely decoded. + (goto-char (point-min))) + (decode-coding-string (buffer-string) 'utf-8))) + +(defun helm-read-answer (prompt answer-list) + "Prompt user for an answer. +Arg PROMPT is the prompt to present user the different possible +answers, ANSWER-LIST is a list of strings. +If user enter an answer which is one of ANSWER-LIST return this +answer, otherwise keep prompting for a valid answer. +Note that answer should be a single char, only short answer are +accepted. + +Example: + + (let ((answer (helm-read-answer + \"answer [y,n,!,q]: \" + '(\"y\" \"n\" \"!\" \"q\")))) + (pcase answer + (\"y\" \"yes\") + (\"n\" \"no\") + (\"!\" \"all\") + (\"q\" \"quit\"))) + +" + (helm-awhile (string + (read-key (propertize prompt 'face 'minibuffer-prompt))) + (if (member it answer-list) + (cl-return it) + (message "Please answer by %s" (mapconcat 'identity answer-list ", ")) + (sit-for 1)))) + +;;; Symbols routines +;; +(defun helm-symbolify (str-or-sym) + "Get symbol of STR-OR-SYM." + (if (symbolp str-or-sym) + str-or-sym + (intern str-or-sym))) + +(defun helm-symbol-name (obj) + (if (or (and (consp obj) (functionp obj)) + (byte-code-function-p obj)) + "Anonymous" + (symbol-name obj))) + +(defun helm-describe-function (func) + "FUNC is symbol or string." + (cl-letf (((symbol-function 'message) #'ignore)) + (describe-function (helm-symbolify func)))) + +(defun helm-describe-variable (var) + "VAR is symbol or string." + (cl-letf (((symbol-function 'message) #'ignore)) + (describe-variable (helm-symbolify var)))) + +(defun helm-describe-face (face) + "FACE is symbol or string." + (let ((faces (helm-marked-candidates))) + (cl-letf (((symbol-function 'message) #'ignore)) + (describe-face (if (cdr faces) + (mapcar 'helm-symbolify faces) + (helm-symbolify face)))))) + +(defun helm-elisp--persistent-help (candidate fun &optional name) + "Used to build persistent actions describing CANDIDATE with FUN. +Argument NAME is used internally to know which command to use when +symbol CANDIDATE refers at the same time to variable and a function. +See `helm-elisp-show-help'." + (let ((hbuf (get-buffer (help-buffer)))) + (cond ((helm-follow-mode-p) + (if name + (funcall fun candidate name) + (funcall fun candidate))) + ((or (and (helm-attr 'help-running-p) + (string= candidate (helm-attr 'help-current-symbol)))) + (progn + ;; When started from a help buffer, + ;; Don't kill this buffer as it is helm-current-buffer. + (unless (equal hbuf helm-current-buffer) + (set-window-buffer (get-buffer-window hbuf) + helm-current-buffer) + (kill-buffer hbuf)) + (helm-attrset 'help-running-p nil))) + (t + (if name + (funcall fun candidate name) + (funcall fun candidate)) + (helm-attrset 'help-running-p t))) + (helm-attrset 'help-current-symbol candidate))) + +(defun helm-find-function (func) + "FUNC is symbol or string." + (find-function (helm-symbolify func))) + +(defun helm-find-variable (var) + "VAR is symbol or string." + (find-variable (helm-symbolify var))) + +(defun helm-find-face-definition (face) + "FACE is symbol or string." + (find-face-definition (helm-symbolify face))) + +(defun helm-kill-new (candidate &optional replace) + "CANDIDATE is symbol or string. +See `kill-new' for argument REPLACE." + (kill-new (helm-stringify candidate) replace)) + + +;;; Modes +;; +(defun helm-same-major-mode-p (start-buffer alist) + "Decide if current-buffer is related to START-BUFFER. +Argument ALIST is an alist of associated major modes." + ;; START-BUFFER is the current-buffer where we start searching. + ;; Determine the major-mode of START-BUFFER as `cur-maj-mode'. + ;; Each time the loop go in another buffer we try from this buffer + ;; to determine if its `major-mode' is: + ;; - same as the `cur-maj-mode' + ;; - derived from `cur-maj-mode' and from + ;; START-BUFFER if its mode is derived from the one in START-BUFFER. + ;; - have an assoc entry (major-mode . cur-maj-mode) + ;; - have an rassoc entry (cur-maj-mode . major-mode) + ;; - check if one of these entries inherit from another one in + ;; `alist'. + (let* ((cur-maj-mode (with-current-buffer start-buffer major-mode)) + (maj-mode major-mode) + (c-assoc-mode (assq cur-maj-mode alist)) + (c-rassoc-mode (rassq cur-maj-mode alist)) + (o-assoc-mode (assq major-mode alist)) + (o-rassoc-mode (rassq major-mode alist)) + (cdr-c-assoc-mode (cdr c-assoc-mode)) + (cdr-o-assoc-mode (cdr o-assoc-mode))) + (or (eq major-mode cur-maj-mode) + (derived-mode-p cur-maj-mode) + (with-current-buffer start-buffer + (derived-mode-p maj-mode)) + (or (eq cdr-c-assoc-mode major-mode) + (eq (car c-rassoc-mode) major-mode) + (eq (cdr (assq cdr-c-assoc-mode alist)) + major-mode) + (eq (car (rassq cdr-c-assoc-mode alist)) + major-mode)) + (or (eq cdr-o-assoc-mode cur-maj-mode) + (eq (car o-rassoc-mode) cur-maj-mode) + (eq (cdr (assq cdr-o-assoc-mode alist)) + cur-maj-mode) + (eq (car (rassq cdr-o-assoc-mode alist)) + cur-maj-mode))))) + +;;; Files routines +;; +(defun helm-file-name-sans-extension (filename) + "Same as `file-name-sans-extension' but remove all extensions." + (helm-aif (file-name-sans-extension filename) + ;; Start searching at index 1 for files beginning with a dot (#1335). + (if (string-match "\\." (helm-basename it) 1) + (helm-file-name-sans-extension it) + it))) + +(defun helm-basename (fname &optional ext) + "Print FNAME with any leading directory components removed. +If specified, also remove filename extension EXT. +Arg EXT can be specified as a string with or without dot, +in this case it should match file-name-extension. +It can also be non-nil (`t') in this case no checking +of file-name-extension is done and the extension is removed +unconditionally." + (let ((non-essential t)) + (if (and ext (or (string= (file-name-extension fname) ext) + (string= (file-name-extension fname t) ext) + (eq ext t)) + (not (file-directory-p fname))) + (file-name-sans-extension (file-name-nondirectory fname)) + (file-name-nondirectory (directory-file-name fname))))) + +(defun helm-basedir (fname) + "Return the base directory of filename ending by a slash." + (helm-aif (and fname + (or (and (string= fname "~") "~") + (file-name-directory fname))) + (file-name-as-directory it))) + +(defun helm-current-directory () + "Return current-directory name at point. +Useful in dired buffers when there is inserted subdirs." + (expand-file-name + (if (eq major-mode 'dired-mode) + (dired-current-directory) + default-directory))) + +(defun helm-shadow-boring-files (files) + "Files matching `helm-boring-file-regexp' will be +displayed with the `file-name-shadow' face if available." + (helm-shadow-entries files helm-boring-file-regexp-list)) + +(defun helm-skip-boring-files (files) + "Files matching `helm-boring-file-regexp' will be skipped." + (helm-skip-entries files helm-boring-file-regexp-list)) + +(defun helm-skip-current-file (files) + "Current file will be skipped." + (remove (buffer-file-name helm-current-buffer) files)) + +(defun helm-w32-pathname-transformer (args) + "Change undesirable features of windows pathnames to ones more acceptable to +other candidate transformers." + (if (eq system-type 'windows-nt) + (helm-transform-mapcar + (lambda (x) + (replace-regexp-in-string + "/cygdrive/\\(.\\)" "\\1:" + (replace-regexp-in-string "\\\\" "/" x))) + args) + args)) + +(defun helm-w32-prepare-filename (file) + "Convert filename FILE to something usable by external w32 executables." + (replace-regexp-in-string ; For UNC paths + "/" "\\" + (replace-regexp-in-string ; Strip cygdrive paths + "/cygdrive/\\(.\\)" "\\1:" + file nil nil) nil t)) + +(defun helm-w32-shell-execute-open-file (file) + (with-no-warnings + (w32-shell-execute "open" (helm-w32-prepare-filename file)))) + +;; Same as `vc-directory-exclusion-list'. +(defvar helm-walk-ignore-directories + '("SCCS/" "RCS/" "CVS/" "MCVS/" ".svn/" ".git/" ".hg/" ".bzr/" + "_MTN/" "_darcs/" "{arch}/" ".gvfs/")) + +(defsubst helm--dir-file-name (file dir) + (expand-file-name + (substring file 0 (1- (length file))) dir)) + +(defsubst helm--dir-name-p (str) + (char-equal (aref str (1- (length str))) ?/)) + +(cl-defun helm-walk-directory (directory &key (path 'basename) + directories + match skip-subdirs) + "Walk through DIRECTORY tree. + +Argument PATH can be one of basename, relative, full, or a function +called on file name, default to basename. + +Argument DIRECTORIES when non--nil (default) return also directories names, +otherwise skip directories names, with a value of 'only returns +only subdirectories, i.e files are skipped. + +Argument MATCH is a regexp matching files or directories. + +Argument SKIP-SUBDIRS when `t' will skip `helm-walk-ignore-directories' +otherwise if it is given as a list of directories, this list will be used +instead of `helm-walk-ignore-directories'." + (let ((fn (cl-case path + (basename 'file-name-nondirectory) + (relative 'file-relative-name) + (full 'identity) + (t path)))) ; A function. + (setq skip-subdirs (if (listp skip-subdirs) + skip-subdirs + helm-walk-ignore-directories)) + (cl-labels ((ls-rec (dir) + (unless (file-symlink-p dir) + (cl-loop for f in (sort (file-name-all-completions "" dir) + 'string-lessp) + unless (member f '("./" "../")) + ;; A directory. + ;; Use `helm--dir-file-name' to remove the final slash. + ;; Needed to avoid infloop on directory symlinks. + if (and (helm--dir-name-p f) + (helm--dir-file-name f dir)) + nconc + (unless (member f skip-subdirs) + (if (and directories + (or (null match) + (string-match match f))) + (nconc (list (concat (funcall fn it) "/")) + (ls-rec it)) + (ls-rec it))) + ;; A regular file. + else nconc + (when (and (null (eq directories 'only)) + (or (null match) (string-match match f))) + (list (funcall fn (expand-file-name f dir)))))))) + (ls-rec directory)))) + +(defun helm-file-expand-wildcards (pattern &optional full) + "Same as `file-expand-wildcards' but allow recursion. +Recursion happen when PATTERN starts with two stars. +Directories expansion is not supported." + (let ((bn (helm-basename pattern)) + (case-fold-search nil)) + (if (and helm-file-globstar + (string-match "\\`\\*\\{2\\}\\(.*\\)" bn)) + (helm-walk-directory (helm-basedir pattern) + :path (cl-case full + (full 'full) + (relative 'relative) + ((basename nil) 'basename) + (t 'full)) + :directories nil + :match (wildcard-to-regexp bn) + :skip-subdirs t) + (file-expand-wildcards pattern full)))) + +;;; helm internals +;; +(defun helm-set-pattern (pattern &optional noupdate) + "Set minibuffer contents to PATTERN. +if optional NOUPDATE is non-nil, helm buffer is not changed." + (with-selected-window (or (active-minibuffer-window) (minibuffer-window)) + (delete-minibuffer-contents) + (insert pattern)) + (when noupdate + (setq helm-pattern pattern))) + +(defun helm-minibuffer-completion-contents () + "Return the user input in a minibuffer before point as a string. +That is what completion commands operate on." + (buffer-substring (field-beginning) (point))) + +(defmacro with-helm-buffer (&rest body) + "Eval BODY inside `helm-buffer'." + (declare (indent 0) (debug t)) + `(with-current-buffer (helm-buffer-get) + ,@body)) + +(defmacro with-helm-current-buffer (&rest body) + "Eval BODY inside `helm-current-buffer'." + (declare (indent 0) (debug t)) + `(with-current-buffer (or (and (buffer-live-p helm-current-buffer) + helm-current-buffer) + (setq helm-current-buffer + (current-buffer))) + ,@body)) + +(defun helm-buffer-get () + "Return `helm-action-buffer' if shown otherwise `helm-buffer'." + (if (helm-action-window) + helm-action-buffer + helm-buffer)) + +(defun helm-window () + "Window of `helm-buffer'." + (get-buffer-window (helm-buffer-get) 0)) + +(defun helm-action-window () + "Window of `helm-action-buffer'." + (get-buffer-window helm-action-buffer 'visible)) + +(defmacro with-helm-window (&rest body) + "Be sure BODY is excuted in the helm window." + (declare (indent 0) (debug t)) + `(with-selected-window (helm-window) + ,@body)) + + +;; Yank text at point. +;; +;; +(defun helm-yank-text-at-point (arg) + "Yank text at point in `helm-current-buffer' into minibuffer." + (interactive "p") + (with-helm-current-buffer + (let ((fwd-fn (or helm-yank-text-at-point-function #'forward-word)) + diff) + ;; Start to initial point if C-w have never been hit. + (unless helm-yank-point + (setq helm-yank-point (car helm-current-position))) + (save-excursion + (goto-char helm-yank-point) + (helm-set-pattern + (if (< arg 0) + (with-temp-buffer + (insert helm-pattern) + (let ((end (point-max))) + (goto-char end) + (funcall fwd-fn -1) + (setq diff (- end (point))) + (delete-region (point) end) + (buffer-string))) + (funcall fwd-fn arg) + (concat + ;; Allow yankink beyond eol allow inserting e.g long + ;; urls in mail buffers. + helm-pattern (replace-regexp-in-string + "\\`\n" "" + (buffer-substring-no-properties + helm-yank-point (point)))))) + (setq helm-yank-point (if diff (- (point) diff) (point))))))) +(put 'helm-yank-text-at-point 'helm-only t) + +(defun helm-undo-yank-text-at-point () + "Undo last entry added by `helm-yank-text-at-point'." + (interactive) + (helm-yank-text-at-point -1)) +(put 'helm-undo-yank-text-at-point 'helm-only t) + +(defun helm-reset-yank-point () + (setq helm-yank-point nil)) + +(add-hook 'helm-cleanup-hook 'helm-reset-yank-point) +(add-hook 'helm-after-initialize-hook 'helm-reset-yank-point) + +;;; Ansi +;; +;; +(defvar helm--ansi-color-regexp + "\033\\[\\(K\\|[0-9;]*m\\)") +(defvar helm--ansi-color-drop-regexp + "\033\\[\\([ABCDsuK]\\|[12][JK]\\|=[0-9]+[hI]\\|[0-9;]*[Hf]\\)") +(defun helm--ansi-color-apply (string) + "A version of `ansi-color-apply' immune to upstream changes. + +Similar to the emacs-24.5 version without support to `ansi-color-context' +which is buggy in emacs. + +Modify also `ansi-color-regexp' by using own variable `helm--ansi-color-regexp' +that match whole STRING. + +This is needed to provide compatibility for both emacs-25 and emacs-24.5 +as emacs-25 version of `ansi-color-apply' is partially broken." + (let ((start 0) + codes end escape-sequence + result colorized-substring) + ;; Find the next escape sequence. + (while (setq end (string-match helm--ansi-color-regexp string start)) + (setq escape-sequence (match-string 1 string)) + ;; Colorize the old block from start to end using old face. + (when codes + (put-text-property + start end 'font-lock-face (ansi-color--find-face codes) string)) + (setq colorized-substring (substring string start end) + start (match-end 0)) + ;; Eliminate unrecognized ANSI sequences. + (while (string-match helm--ansi-color-drop-regexp colorized-substring) + (setq colorized-substring + (replace-match "" nil nil colorized-substring))) + (push colorized-substring result) + ;; Create new face, by applying escape sequence parameters. + (setq codes (ansi-color-apply-sequence escape-sequence codes))) + ;; If the rest of the string should have a face, put it there. + (when codes + (put-text-property + start (length string) + 'font-lock-face (ansi-color--find-face codes) string)) + ;; Save the remainder of the string to the result. + (if (string-match "\033" string start) + (push (substring string start (match-beginning 0)) result) + (push (substring string start) result)) + (apply 'concat (nreverse result)))) + +(provide 'helm-lib) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-lib ends here diff --git a/elpa/helm-core-20181114.621/helm-multi-match.el b/elpa/helm-core-20181114.621/helm-multi-match.el new file mode 100644 index 00000000..3d36bfea --- /dev/null +++ b/elpa/helm-core-20181114.621/helm-multi-match.el @@ -0,0 +1,373 @@ +;;; helm-multi-match.el --- Multiple regexp matching methods for helm -*- lexical-binding: t -*- + +;; Original Author: rubikitch + +;; Copyright (C) 2008 ~ 2011 rubikitch +;; Copyright (C) 2011 ~ 2018 Thierry Volpiatto + +;; Author: Thierry Volpiatto +;; URL: http://github.com/emacs-helm/helm + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'helm-lib) + + +(defgroup helm-multi-match nil + "Helm multi match." + :group 'helm) + +(defcustom helm-mm-matching-method 'multi3 + "Matching method for helm match plugin. +You can set here different methods to match candidates in helm. +Here are the possible value of this symbol and their meaning: +- multi1: Respect order, prefix of pattern must match. +- multi2: Same but with partial match. +- multi3: The best, multiple regexp match, allow negation. +- multi3p: Same but prefix must match. + +Default is multi3, you should keep this for a better experience. + +Note that multi1 and multi3p are incompatible with fuzzy matching +in file completion and by the way fuzzy matching will be disabled there +when these options are used." + :type '(radio :tag "Matching methods for helm" + (const :tag "Multiple regexp 1 ordered with prefix match" multi1) + (const :tag "Multiple regexp 2 ordered with partial match" multi2) + (const :tag "Multiple regexp 3 matching no order, partial, best." multi3) + (const :tag "Multiple regexp 3p matching with prefix match" multi3p)) + :group 'helm-multi-match) + + +;; Internal +(defvar helm-mm-default-match-functions + '(helm-mm-exact-match helm-mm-match)) +(defvar helm-mm-default-search-functions + '(helm-mm-exact-search helm-mm-search)) + + +;;; Build regexps +;; +;; +(defconst helm-mm-space-regexp "\\s\\\\s-" + "Regexp to represent space itself in multiple regexp match.") + +(defun helm-mm-split-pattern (pattern &optional grep-space) + "Split PATTERN if it contain spaces and return resulting list. +If spaces in PATTERN are escaped, don't split at this place. +i.e \"foo bar baz\"=> (\"foo\" \"bar\" \"baz\") +but \"foo\\ bar baz\"=> (\"foo\\s-bar\" \"baz\"). +If GREP-SPACE is used translate escaped space to \"\\s\" instead of \"\\s-\"." + (split-string + ;; Match spaces litteraly because candidate buffer syntax-table + ;; doesn't understand "\s-" properly. + (replace-regexp-in-string + helm-mm-space-regexp + (if grep-space "\\s" "\\s-") pattern nil t))) + +(defun helm-mm-1-make-regexp (pattern) + "Replace spaces in PATTERN with \"\.*\"." + (mapconcat 'identity (helm-mm-split-pattern pattern) ".*")) + + +;;; Exact match. +;; +;; +;; Internal. +(defvar helm-mm-exact-pattern-str nil) +(defvar helm-mm-exact-pattern-real nil) + +(defun helm-mm-exact-get-pattern (pattern) + (unless (equal pattern helm-mm-exact-pattern-str) + (setq helm-mm-exact-pattern-str pattern + helm-mm-exact-pattern-real (concat "\n" pattern "\n"))) + helm-mm-exact-pattern-real) + + +(cl-defun helm-mm-exact-match (str &optional (pattern helm-pattern)) + (if case-fold-search + (progn + (setq str (downcase str) + pattern (downcase pattern)) + (string= str pattern)) + (string= str pattern))) + +(defun helm-mm-exact-search (pattern &rest _ignore) + (and (search-forward (helm-mm-exact-get-pattern pattern) nil t) + (forward-line -1))) + + +;;; Prefix match +;; +;; +;; Internal +(defvar helm-mm-prefix-pattern-str nil) +(defvar helm-mm-prefix-pattern-real nil) + +(defun helm-mm-prefix-get-pattern (pattern) + (unless (equal pattern helm-mm-prefix-pattern-str) + (setq helm-mm-prefix-pattern-str pattern + helm-mm-prefix-pattern-real (concat "\n" pattern))) + helm-mm-prefix-pattern-real) + +(defun helm-mm-prefix-match (str &optional pattern) + ;; In filename completion basename and basedir may be + ;; quoted, unquote them for string comparison (Issue #1283). + (setq pattern (replace-regexp-in-string + "\\\\" "" (or pattern helm-pattern))) + (let ((len (length pattern))) + (and (<= len (length str)) + (string= (substring str 0 len) pattern )))) + +(defun helm-mm-prefix-search (pattern &rest _ignore) + (search-forward (helm-mm-prefix-get-pattern pattern) nil t)) + + +;;; Multiple regexp patterns 1 (order is preserved / prefix). +;; +;; +;; Internal +(defvar helm-mm-1-pattern-str nil) +(defvar helm-mm-1-pattern-real nil) + +(defun helm-mm-1-get-pattern (pattern) + (unless (equal pattern helm-mm-1-pattern-str) + (setq helm-mm-1-pattern-str pattern + helm-mm-1-pattern-real + (concat "^" (helm-mm-1-make-regexp pattern)))) + helm-mm-1-pattern-real) + +(cl-defun helm-mm-1-match (str &optional (pattern helm-pattern)) + (string-match (helm-mm-1-get-pattern pattern) str)) + +(defun helm-mm-1-search (pattern &rest _ignore) + (re-search-forward (helm-mm-1-get-pattern pattern) nil t)) + + +;;; Multiple regexp patterns 2 (order is preserved / partial). +;; +;; +;; Internal +(defvar helm-mm-2-pattern-str nil) +(defvar helm-mm-2-pattern-real nil) + +(defun helm-mm-2-get-pattern (pattern) + (unless (equal pattern helm-mm-2-pattern-str) + (setq helm-mm-2-pattern-str pattern + helm-mm-2-pattern-real + (concat "^.*" (helm-mm-1-make-regexp pattern)))) + helm-mm-2-pattern-real) + +(cl-defun helm-mm-2-match (str &optional (pattern helm-pattern)) + (string-match (helm-mm-2-get-pattern pattern) str)) + +(defun helm-mm-2-search (pattern &rest _ignore) + (re-search-forward (helm-mm-2-get-pattern pattern) nil t)) + + +;;; Multiple regexp patterns 3 (permutation). +;; +;; +;; Internal +(defvar helm-mm-3-pattern-str nil) +(defvar helm-mm-3-pattern-list nil) + +(defun helm-mm-3-get-patterns (pattern) + "Return `helm-mm-3-pattern-list', a list of predicate/regexp cons cells. +e.g ((identity . \"foo\") (identity . \"bar\")). +This is done only if `helm-mm-3-pattern-str' is same as PATTERN." + (unless (equal pattern helm-mm-3-pattern-str) + (setq helm-mm-3-pattern-str pattern + helm-mm-3-pattern-list + (helm-mm-3-get-patterns-internal pattern))) + helm-mm-3-pattern-list) + +(defun helm-mm-3-get-patterns-internal (pattern) + "Return a list of predicate/regexp cons cells. +e.g ((identity . \"foo\") (identity . \"bar\"))." + (unless (string= pattern "") + (cl-loop for pat in (helm-mm-split-pattern pattern) + collect (if (string= "!" (substring pat 0 1)) + (cons 'not (substring pat 1)) + (cons 'identity pat))))) + +(cl-defun helm-mm-3-match (str &optional (pattern helm-pattern)) + "Check if PATTERN match STR. +When PATTERN contain a space, it is splitted and matching is done +with the several resulting regexps against STR. +e.g \"bar foo\" will match \"foobar\" and \"barfoo\". +Argument PATTERN, a string, is transformed in a list of +cons cell with `helm-mm-3-get-patterns' if it contain a space. +e.g \"foo bar\"=>((identity . \"foo\") (identity . \"bar\")). +Then each predicate of cons cell(s) is called with regexp of same +cons cell against STR (a candidate). +i.e (identity (string-match \"foo\" \"foo bar\")) => t." + (let ((pat (helm-mm-3-get-patterns pattern))) + (cl-loop for (predicate . regexp) in pat + always (funcall predicate + (condition-case _err + ;; FIXME: Probably do nothing when + ;; using fuzzy leaving the job + ;; to the fuzzy fn. + (string-match regexp str) + (invalid-regexp nil)))))) + +(defun helm-mm-3-search-base (pattern searchfn1 searchfn2) + "Try to find PATTERN in `helm-buffer' with SEARCHFN1 and SEARCHFN2. +This is the search function for `candidates-in-buffer' enabled sources. +Use the same method as `helm-mm-3-match' except it search in buffer +instead of matching on a string. +i.e (identity (re-search-forward \"foo\" (point-at-eol) t)) => t." + (cl-loop with pat = (if (stringp pattern) + (helm-mm-3-get-patterns pattern) + pattern) + when (eq (caar pat) 'not) return + ;; Pass the job to `helm-search-match-part'. + (prog1 (list (point-at-bol) (point-at-eol)) + (forward-line 1)) + while (condition-case _err + (funcall searchfn1 (or (cdar pat) "") nil t) + (invalid-regexp nil)) + for bol = (point-at-bol) + for eol = (point-at-eol) + if (cl-loop for (pred . str) in (cdr pat) always + (progn (goto-char bol) + (funcall pred (condition-case _err + (funcall searchfn2 str eol t) + (invalid-regexp nil))))) + do (goto-char eol) and return t + else do (goto-char eol) + finally return nil)) + +(defun helm-mm-3-search (pattern &rest _ignore) + (when (stringp pattern) + (setq pattern (helm-mm-3-get-patterns pattern))) + (helm-mm-3-search-base + pattern 're-search-forward 're-search-forward)) + +;;; mp-3 with migemo +;; +;; +(defvar helm-mm--previous-migemo-info nil + "[Internal] Cache previous migemo query.") +(make-local-variable 'helm-mm--previous-migemo-info) + +(declare-function migemo-get-pattern "ext:migemo.el") +(declare-function migemo-search-pattern-get "ext:migemo.el") + +(define-minor-mode helm-migemo-mode + "Enable migemo in helm. +It will be available in the sources handling it, +i.e the sources which have the slot :migemo with non--nil value." + :lighter " Hmio" + :group 'helm + :global t + (cl-assert (featurep 'migemo) + nil "No feature called migemo found, install migemo.el.")) + +(defun helm-mm-migemo-get-pattern (pattern) + (let ((regex (migemo-get-pattern pattern))) + (if (ignore-errors (string-match regex "") t) + (concat regex "\\|" pattern) pattern))) + +(defun helm-mm-migemo-search-pattern-get (pattern) + (let ((regex (migemo-search-pattern-get pattern))) + (if (ignore-errors (string-match regex "") t) + (concat regex "\\|" pattern) pattern))) + +(defun helm-mm-migemo-string-match (pattern str) + "Migemo version of `string-match'." + (unless (assoc pattern helm-mm--previous-migemo-info) + (with-helm-buffer + (setq helm-mm--previous-migemo-info + (push (cons pattern (helm-mm-migemo-get-pattern pattern)) + helm-mm--previous-migemo-info)))) + (string-match (assoc-default pattern helm-mm--previous-migemo-info) str)) + +(cl-defun helm-mm-3-migemo-match (str &optional (pattern helm-pattern)) + (and helm-migemo-mode + (cl-loop for (pred . re) in (helm-mm-3-get-patterns pattern) + always (funcall pred (helm-mm-migemo-string-match re str))))) + +(defun helm-mm-migemo-forward (word &optional bound noerror count) + (with-helm-buffer + (unless (assoc word helm-mm--previous-migemo-info) + (setq helm-mm--previous-migemo-info + (push (cons word (if (delq 'ascii (find-charset-string word)) + word + (helm-mm-migemo-search-pattern-get word))) + helm-mm--previous-migemo-info)))) + (re-search-forward + (assoc-default word helm-mm--previous-migemo-info) bound noerror count)) + +(defun helm-mm-3-migemo-search (pattern &rest _ignore) + (and helm-migemo-mode + (helm-mm-3-search-base + pattern 'helm-mm-migemo-forward 'helm-mm-migemo-forward))) + + +;;; mp-3p- (multiple regexp pattern 3 with prefix search) +;; +;; +(defun helm-mm-3p-match (str &optional pattern) + "Check if PATTERN match STR. +Same as `helm-mm-3-match' but more strict, matching against prefix also. +e.g \"bar foo\" will match \"barfoo\" but not \"foobar\" contrarily to +`helm-mm-3-match'." + (let* ((pat (helm-mm-3-get-patterns (or pattern helm-pattern))) + (first (car pat))) + (and (funcall (car first) (helm-mm-prefix-match str (cdr first))) + (cl-loop for (predicate . regexp) in (cdr pat) + always (funcall predicate (string-match regexp str)))))) + +(defun helm-mm-3p-search (pattern &rest _ignore) + (when (stringp pattern) + (setq pattern (helm-mm-3-get-patterns pattern))) + (helm-mm-3-search-base + pattern 'helm-mm-prefix-search 're-search-forward)) + + +;;; Generic multi-match/search functions +;; +;; +(cl-defun helm-mm-match (str &optional (pattern helm-pattern)) + (let ((fun (cl-ecase helm-mm-matching-method + (multi1 #'helm-mm-1-match) + (multi2 #'helm-mm-2-match) + (multi3 #'helm-mm-3-match) + (multi3p #'helm-mm-3p-match)))) + (funcall fun str pattern))) + +(defun helm-mm-search (pattern &rest _ignore) + (let ((fun (cl-ecase helm-mm-matching-method + (multi1 #'helm-mm-1-search) + (multi2 #'helm-mm-2-search) + (multi3 #'helm-mm-3-search) + (multi3p #'helm-mm-3p-search)))) + (funcall fun pattern))) + + +(provide 'helm-multi-match) + + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-multi-match.el ends here diff --git a/elpa/helm-core-20181114.621/helm-source.el b/elpa/helm-core-20181114.621/helm-source.el new file mode 100644 index 00000000..f656cc27 --- /dev/null +++ b/elpa/helm-core-20181114.621/helm-source.el @@ -0,0 +1,1129 @@ +;;; helm-source.el --- Helm source creation. -*- lexical-binding: t -*- + +;; Copyright (C) 2015 ~ 2018 Thierry Volpiatto + +;; Author: Thierry Volpiatto +;; URL: http://github.com/emacs-helm/helm + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Commentary: + +;; Interface to create helm sources easily. +;; Actually the eieo objects are transformed in alist for compatibility. +;; In the future this package should allow creating source as eieo objects +;; without conversion to alist, teaching helm to read such a structure. +;; The compatibility with alists would be kept. + +;;; Code: + +(require 'cl-lib) +(require 'eieio) +(require 'helm-lib) + +(defvar helm-fuzzy-sort-fn) +(defvar helm-fuzzy-match-fn) +(defvar helm-fuzzy-search-fn) + +(declare-function helm-init-candidates-in-buffer "helm.el") +(declare-function helm-interpret-value "helm.el") +(declare-function helm-fuzzy-highlight-matches "helm.el") + + +(defgeneric helm--setup-source (source) + "Prepare slots and handle slot errors before creating a helm source.") + +(defgeneric helm-setup-user-source (source) + "Allow users modifying slots in SOURCE just before creation.") + + +;;; Classes for sources +;; +;; +(defclass helm-source () + ((name + :initarg :name + :initform nil + :custom string + :documentation + " The name of the source. + A string which is also the heading which appears + above the list of matches from the source. Must be unique.") + + (header-name + :initarg :header-name + :initform nil + :custom function + :documentation + " A function returning the display string of the header. + Its argument is the name of the source. This attribute is useful to + add an additional information with the source name. + It doesn't modify the name of the source.") + + (init + :initarg :init + :initform nil + :custom function + :documentation + " Function called with no parameters when helm is started. + It is useful for collecting current state information which can be + used to create the list of candidates later. + Initialization of `candidates-in-buffer' is done here + with `helm-init-candidates-in-buffer'.") + + (candidates + :initarg :candidates + :initform nil + :custom (choice function list) + :documentation + " Specifies how to retrieve candidates from the source. + It can either be a variable name, a function called with no parameters + or the actual list of candidates. + + The list must be a list whose members are strings, symbols + or (DISPLAY . REAL) pairs. + + In case of (DISPLAY . REAL) pairs, the DISPLAY string is shown + in the Helm buffer, but the REAL one is used as action + argument when the candidate is selected. This allows a more + readable presentation for candidates which would otherwise be, + for example, too long or have a common part shared with other + candidates which can be safely replaced with an abbreviated + string for display purposes. + + Note that if the (DISPLAY . REAL) form is used then pattern + matching is done on the displayed string, not on the real + value.") + + (update + :initarg :update + :initform nil + :custom function + :documentation + " Function called with no parameters at before \"init\" function + when `helm-force-update' is called.") + + (cleanup + :initarg :cleanup + :initform nil + :custom function + :documentation + " Function called with no parameters when *helm* buffer is + closed. It is useful for killing unneeded candidates buffer. + + Note that the function is executed BEFORE performing action.") + + (keymap + :initarg :keymap + :initform helm-map + :custom sexp + :documentation + " Specific keymap for this source. + default value is `helm-map'.") + + (action + :initarg :action + :initform 'identity + :custom (alist :key-type string + :value-type function) + :documentation + " An alist of (DISPLAY . FUNCTION) pairs, a variable name or a function. + FUNCTION is called with one parameter: the selected candidate. + + An action other than the default can be chosen from this list + of actions for the currently selected candidate (by default + with TAB). The DISPLAY string is shown in the completions + buffer and the FUNCTION is invoked when an action is + selected. The first action of the list is the default. + + You should use `helm-make-actions' to build this alist easily.") + + (persistent-action + :initarg :persistent-action + :initform nil + :custom function + :documentation + " Can be a either a Function called with one parameter (the + selected candidate) or a cons cell where first element is this + same function and second element a symbol (e.g never-split) + that inform `helm-execute-persistent-action' to not split his + window to execute this persistent action. + Example: + + (defun foo-persistent-action (candidate) + (do-something candidate)) + + :persistent-action '(foo-persistent-action . never-split) ; Don't split + or + :persistent-action 'foo-persistent-action ; Split + + When specifying :persistent-action by slot directly, foo-persistent-action + will be executed without quitting helm when hitting `C-j'. + + Note that other persistent actions can be defined using other + bindings than `C-j' by simply defining an interactive function bound + to a key in the keymap source. + The function should create a new attribute in source before calling + `helm-execute-persistent-action' on this attribute. + Example: + + (defun helm-ff-persistent-delete () + \"Delete current candidate without quitting.\" + (interactive) + (with-helm-alive-p + (helm-attrset 'quick-delete '(helm-ff-quick-delete . never-split)) + (helm-execute-persistent-action 'quick-delete))) + + This function is then bound in `helm-find-files-map'.") + + (persistent-action-if + :initarg :persistent-action-if + :initform nil + :custom function + :documentation + " Similar from persistent action but it is a function that should + return an object suitable for persistent action when called , i.e. a + function or a cons cell. + Example: + + (defun foo-persistent-action (candidate) + (cond (something + ;; Don't split helm-window. + (cons (lambda (_ignore) + (do-something candidate)) + 'no-split)) + ;; Split helm-window. + (something-else + (lambda (_ignore) + (do-something-else candidate))))) + + :persistent-action-if 'foo-persistent-action + + Here when hitting `C-j' one of the lambda's will be executed + depending on something or something-else condition, splitting or not + splitting as needed. + See `helm-find-files-persistent-action-if' definition as another example.") + + (persistent-help + :initarg :persistent-help + :initform nil + :custom string + :documentation + " A string to explain persistent-action of this source. It also + accepts a function or a variable name. + It will be displayed in `header-line' or in `minibuffer' depending + of value of `helm-echo-input-in-header-line' and `helm-display-header-line'.") + + (help-message + :initarg :help-message + :initform nil + :custom (choice string function) + :documentation + " Help message for this source. + If not present, `helm-help-message' value will be used.") + + (multiline + :initarg :multiline + :initform nil + :custom (choice boolean integer) + :documentation + " Allow multiline candidates. + When non-nil candidates will be separated by `helm-candidate-separator'. + You can customize the color of this separator with `helm-separator' face. + Value of multiline can be an integer which specify the maximum size of the + multiline string to display, if multiline string is longer than this value + it will be truncated.") + + (requires-pattern + :initarg :requires-pattern + :initform nil + :custom integer + :documentation + " If present matches from the source are shown only if the + pattern is not empty. Optionally, it can have an integer + parameter specifying the required length of input which is + useful in case of sources with lots of candidates.") + + (candidate-transformer + :initarg :candidate-transformer + :initform nil + :custom (choice function list) + :documentation + " It's a function or a list of functions called with one argument + when the completion list from the source is built. The argument + is the list of candidates retrieved from the source. The + function should return a transformed list of candidates which + will be used for the actual completion. If it is a list of + functions, it calls each function sequentially. + + This can be used to transform or remove items from the list of + candidates. + + Note that `candidates' is run already, so the given transformer + function should also be able to handle candidates with (DISPLAY + . REAL) format.") + + (filtered-candidate-transformer + :initarg :filtered-candidate-transformer + :initform nil + :custom (choice function list) + :documentation + " It has the same format as `candidate-transformer', except the + function is called with two parameters: the candidate list and + the source. + + This transformer is run on the candidate list which is already + filtered by the current pattern. While `candidate-transformer' + is run only once, it is run every time the input pattern is + changed. + + It can be used to transform the candidate list dynamically, for + example, based on the current pattern. + + In some cases it may also be more efficent to perform candidate + transformation here, instead of with `candidate-transformer' + even if this transformation is done every time the pattern is + changed. For example, if a candidate set is very large then + `candidate-transformer' transforms every candidate while only + some of them will actually be displayed due to the limit + imposed by `helm-candidate-number-limit'. + + Note that `candidates' and `candidate-transformer' is run + already, so the given transformer function should also be able + to handle candidates with (DISPLAY . REAL) format.") + + (filter-one-by-one + :initarg :filter-one-by-one + :initform nil + :custom (choice function list) + :documentation + " A transformer function that treat candidates one by one. + It is called with one arg the candidate. + It is faster than `filtered-candidate-transformer' or + `candidate-transformer', but should be used only in sources + that recompute constantly their candidates, e.g `helm-source-find-files'. + Filtering happen early and candidates are treated + one by one instead of re-looping on the whole list. + If used with `filtered-candidate-transformer' or `candidate-transformer' + these functions should treat the candidates transformed by the + `filter-one-by-one' function in consequence.") + + (display-to-real + :initarg :display-to-real + :initform nil + :custom function + :documentation + " Transform the selected candidate when passing it to action. + + Function called with one parameter, the selected candidate. + + Avoid recomputing all candidates with candidate-transformer + or filtered-candidate-transformer to give a new value to REAL, + instead the selected candidate is transformed only when passing it + to action. + + Note that this is NOT a transformer, + so the display will not be modified by this function.") + + (real-to-display + :initarg :real-to-display + :initform nil + :custom function + :documentation + " Recompute all candidates computed previously with other transformers. + + Function called with one parameter, the selected candidate. + + The real value of candidates will be shown in display. + Note: This have nothing to do with display-to-real. + It is unuseful as the same can be performed by using more than + one function in transformers, it is kept only for backward compatibility.") + + (marked-with-props + :initarg :marked-with-props + :initform nil + :custom (choice boolean symbol) + :documentation + " Get candidates with their properties in `helm-marked-candidates'. + Allow using the FORCE-DISPLAY-PART of `helm-get-selection' in marked + candidates, use t or 'withprop to pass it to `helm-get-selection'.") + + (action-transformer + :initarg :action-transformer + :initform nil + :custom (choice function list) + :documentation + " It's a function or a list of functions called with two + arguments when the action list from the source is + assembled. The first argument is the list of actions, the + second is the current selection. If it is a list of functions, + it calls each function sequentially. + + The function should return a transformed action list. + + This can be used to customize the list of actions based on the + currently selected candidate.") + + (pattern-transformer + :initarg :pattern-transformer + :initform nil + :custom (choice function list) + :documentation + " It's a function or a list of functions called with one argument + before computing matches. Its argument is `helm-pattern'. + Functions should return transformed `helm-pattern'. + + It is useful to change interpretation of `helm-pattern'.") + + (candidate-number-limit + :initarg :candidate-number-limit + :initform nil + :custom integer + :documentation + " Override `helm-candidate-number-limit' only for this source.") + + (volatile + :initarg :volatile + :initform nil + :custom boolean + :documentation + " Indicates the source assembles the candidate list dynamically, + so it shouldn't be cached within a single Helm + invocation. It is only applicable to synchronous sources, + because asynchronous sources are not cached.") + + (match + :initarg :match + :initform nil + :custom (choice function list) + :documentation + " List of functions called with one parameter: a candidate. The + function should return non-nil if the candidate matches the + current pattern (see variable `helm-pattern'). + + When using `candidates-in-buffer' its default value is `identity' and + don't have to be changed, use the `search' slot instead. + + This attribute allows the source to override the default + pattern matching based on `string-match'. It can be used, for + example, to implement a source for file names and do the + pattern matching on the basename of files, since it's more + likely one is typing part of the basename when searching for a + file, instead of some string anywhere else in its path. + + If the list contains more than one function then the list of + matching candidates from the source is constructed by appending + the results after invoking the first function on all the + potential candidates, then the next function, and so on. The + matching candidates supplied by the first function appear first + in the list of results and then results from the other + functions, respectively. + + This attribute has no effect for asynchronous sources (see + attribute `candidates'), since they perform pattern matching + themselves. + + Note that FUZZY-MATCH slot will overhide value of this slot.") + + (fuzzy-match + :initarg :fuzzy-match + :initform nil + :custom boolean + :documentation + " Enable fuzzy matching in this source. + This will overwrite settings in MATCH slot, and for + sources built with child class `helm-source-in-buffer' the SEARCH slot. + This is an easy way of enabling fuzzy matching, but you can use the MATCH + or SEARCH slots yourself if you want something more elaborated, mixing + different type of match (See `helm-source-buffers' class for example). + + This attribute is not supported for asynchronous sources + since they perform pattern matching themselves.") + + (redisplay + :initarg :redisplay + :initform 'identity + :custom (choice list function) + :documentation + " A function or a list of functions to apply to current list + of candidates when redisplaying buffer with `helm-redisplay-buffer'. + This is only interesting for modifying and redisplaying the whole list + of candidates in async sources. + It uses `identity' by default for when async sources are mixed with + normal sources, in this case these normal sources are not modified and + redisplayed as they are.") + + (nomark + :initarg :nomark + :initform nil + :custom boolean + :documentation + " Don't allow marking candidates when this attribute is present.") + + (nohighlight + :initarg :nohighlight + :initform nil + :custom boolean + :documentation + " Disable highlighting matches in this source. + This will disable generic highlighting of matches, + but some specialized highlighting can be done from elsewhere, + i.e from `filtered-candidate-transformer' or `filter-one-by-one' slots. + So use this to either disable completely highlighting in your source, + or to disable highlighting and use a specialized highlighting matches + function for this source. + Remember that this function should run AFTER all filter functions if those + filter functions are modifying face properties, though it is possible to + avoid this by using new `add-face-text-property' in your filter functions.") + + (allow-dups + :initarg :allow-dups + :initform nil + :custom boolean + :documentation + " Allow helm collecting duplicates candidates.") + + (history + :initarg :history + :initform nil + :custom symbol + :documentation + " Allow passing history variable to helm from source. + It should be a quoted symbol. + Passing the history variable here have no effect + so add it also in the `helm' call with the :history keyword. + The main point of adding the variable here + is to make it available when resuming.") + + (coerce + :initarg :coerce + :initform nil + :custom function + :documentation + " It's a function called with one argument: the selected candidate. + This function is intended for type convertion. In normal case, + the selected candidate (string) is passed to action + function. If coerce function is specified, it is called just + before action function. + + Example: converting string to symbol + (coerce . intern)") + + (mode-line + :initarg :mode-line + :initform nil + :custom (choice string sexp) + :documentation + " Source local `helm-mode-line-string' (included in + `mode-line-format'). It accepts also variable/function name.") + + (header-line + :initarg :header-line + :initform nil + :custom (choice string function) + :documentation + " Source local `header-line-format'. + It will be displayed in `header-line' or in `minibuffer' depending + of value of `helm-echo-input-in-header-line' and `helm-display-header-line'. + It accepts also variable/function name.") + + (resume + :initarg :resume + :initform nil + :custom function + :documentation + " Function called with no parameters at end of initialization + when `helm-resume' is started. + If this function try to do something against `helm-buffer', \(e.g updating, + searching etc...\) probably you should run it in a timer to ensure + `helm-buffer' is ready.") + + (follow + :initarg :follow + :initform nil + :custom integer + :documentation + " Enable `helm-follow-mode' for this source only. +With a value of 1 enable, a value of -1 or nil disable the mode. + See `helm-follow-mode' for more infos.") + + (follow-delay + :initarg :follow-delay + :initform nil + :custom integer + :documentation + " `helm-follow-mode' will execute persistent-action after this delay. + Otherwise value of `helm-follow-input-idle-delay' is used if non--nil, + If none of these are found fallback to `helm-input-idle-delay'.") + + (multimatch + :initarg :multimatch + :initform t + :custom boolean + :documentation + " Use the multi-match algorithm when non-nil. + I.e Allow specifying multiple patterns separated by spaces. + When a pattern is prefixed by \"!\" the negation of this pattern is used, + i.e match anything but this pattern. + It is the standard way of matching in helm and is enabled by default. + It can be used with fuzzy-matching enabled, but as soon helm detect a space, + each pattern will match by regexp and will not be fuzzy.") + + (match-part + :initarg :match-part + :initform nil + :custom function + :documentation + " Allow matching only one part of candidate. + If source contain match-part attribute, match is computed only + on part of candidate returned by the call of function provided + by this attribute. The function should have one arg, candidate, + and return only a specific part of candidate. + On async sources, as matching is done by the backend, this have + no effect apart for highlighting matches.") + + (before-init-hook + :initarg :before-init-hook + :initform nil + :custom symbol + :documentation + " A local hook that run at beginning of initilization of this source. + i.e Before the creation of `helm-buffer'. + + Should be a variable (defined with defvar). + Can be also an anonymous function or a list of functions + directly added to slot, this is not recommended though.") + + (after-init-hook + :initarg :after-init-hook + :initform nil + :custom symbol + :documentation + " A local hook that run at end of initilization of this source. + i.e After the creation of `helm-buffer'. + + Should be a variable. + Can be also an anonymous function or a list of functions + directly added to slot, this is not recommended though.") + + (delayed + :initarg :delayed + :initform nil + :custom (choice null integer) + :documentation + " This slot have no more effect and is just kept for backward compatibility. + Please don't use it.") + + (group + :initarg :group + :initform helm + :custom symbol + :documentation + " The current source group, default to `helm' when not specified.")) + + "Main interface to define helm sources." + :abstract t) + +(defclass helm-source-sync (helm-source) + ((candidates + :initform '("ERROR: You must specify the `candidates' slot, either with a list or a function")) + + (migemo + :initarg :migemo + :initform nil + :custom boolean + :documentation + " Enable migemo. + When multimatch is disabled, you can give the symbol 'nomultimatch as value + to force not using generic migemo matching function. + In this case you have to provide your own migemo matching funtion + that kick in when `helm-migemo-mode' is enabled. + Otherwise it will be available for this source once `helm-migemo-mode' + is enabled when non-nil.") + + (match-strict + :initarg :match-strict + :initform nil + :custom function + :documentation + " When specifying a match function within a source and + helm-multi-match is enabled, the result of all matching + functions will be concatened, which in some cases is not what + is wanted. When using `match-strict' only this or these + functions will be used. You can specify those functions as a + list of functions or a single symbol function. + + NOTE: This have the same effect as using :MULTIMATCH nil.")) + + "Use this class to make helm sources using a list of candidates. +This list should be given as a normal list, a variable handling a list +or a function returning a list. +Matching is done basically with `string-match' against each candidate.") + +(defclass helm-source-async (helm-source) + ((candidates-process + :initarg :candidates-process + :initform nil + :custom function + :documentation + " This attribute is used to define a process as candidate. + The value must be a process. + + NOTE: + When building the source at runtime you can give directly a process + as value, otherwise wrap the process call into a function. + The process buffer should be nil, otherwise, if you use + `helm-buffer' give to the process a sentinel.") + + (multimatch :initform nil)) + + "Use this class to define a helm source calling an external process. +The :candidates slot is not allowed even if described because this class +inherit from `helm-source'.") + +(defclass helm-source-in-buffer (helm-source) + ((init + :initform 'helm-default-init-source-in-buffer-function) + + (data + :initarg :data + :initform nil + :custom (choice list string) + :documentation + " A string, a list or a buffer that will be used to feed the `helm-candidates-buffer'. + This data will be passed in a function added to the init slot and + the buffer will be build with `helm-init-candidates-in-buffer' or directly + with `helm-candidates-buffer' if data is a buffer. + This is an easy and fast method to build a `candidates-in-buffer' source.") + + (migemo + :initarg :migemo + :initform nil + :custom boolean + :documentation + " Enable migemo. + When multimatch is disabled, you can give the symbol 'nomultimatch as value + to force not using generic migemo matching function. + In this case you have to provide your own migemo matching funtion + that kick in when `helm-migemo-mode' is enabled. + Otherwise it will be available for this source once `helm-migemo-mode' + is enabled when non-nil.") + + (candidates + :initform 'helm-candidates-in-buffer) + + (volatile + :initform t) + + (match + :initform '(identity)) + + (get-line + :initarg :get-line + :initform 'buffer-substring-no-properties + :custom function + :documentation + " A function like `buffer-substring-no-properties' or `buffer-substring'. + This function converts region from point at line-beginning and point + at line-end in the `helm-candidate-buffer' to a string which will be displayed + in the `helm-buffer', it takes two args BEG and END. + By default, `helm-candidates-in-buffer' uses + `buffer-substring-no-properties' which does no conversion and doesn't carry + text properties.") + + (search + :initarg :search + :initform '(helm-candidates-in-buffer-search-default-fn) + :custom (choice function list) + :documentation + " List of functions like `re-search-forward' or `search-forward'. + Buffer search function used by `helm-candidates-in-buffer'. + By default, `helm-candidates-in-buffer' uses `re-search-forward'. + The function should take one arg PATTERN. + If your search function needs to handle negation like multimatch, + this function should returns in such case a cons cell of two integers defining + the beg and end positions to match in the line previously matched by + `re-search-forward' or similar, and move point to next line + (See how the `helm-mm-3-search-base' and `helm-fuzzy-search' functions are working). + + NOTE: FUZZY-MATCH slot will overhide value of this slot.") + + (search-strict + :initarg :search-strict + :initform nil + :custom function + :documentation + " When specifying a search function within a source and + helm-multi-match is enabled, the result of all searching + functions will be concatened, which in some cases is not what + is wanted. When using `search-strict' only this or these + functions will be used. You can specify those functions as a + list of functions or a single symbol function. + + NOTE: This have the same effect as using a nil value for + :MULTIMATCH slot.")) + + "Use this source to make helm sources storing candidates inside a buffer. + +The buffer storing candidates is generated by `helm-candidate-buffer' function +and all search are done in this buffer, results are transfered to the `helm-buffer' +when done. +Contrarily to `helm-source-sync' candidates are matched using a function +like `re-search-forward' (see below documentation of `:search' slot) which makes +the search much faster than matching candidates one by one. +If you want to add search functions to your sources, don't use `:match' which +will raise an error, but `:search'. +See `helm-candidates-in-buffer' for more infos.") + +(defclass helm-source-dummy (helm-source) + ((candidates + :initform '("dummy")) + + (filtered-candidate-transformer + :initform (lambda (_candidates _source) (list helm-pattern))) + + (multimatch + :initform nil) + + (accept-empty + :initarg :accept-empty + :initform t + :custom boolean + :documentation + " Allow exiting with an empty string. + You should keep the default value.") + + (match + :initform 'identity) + + (volatile + :initform t))) + +(defclass helm-source-in-file (helm-source-in-buffer) + ((init :initform (lambda () + (let ((file (helm-attr 'candidates-file)) + (count 1)) + (with-current-buffer (helm-candidate-buffer 'global) + (insert-file-contents file) + (goto-char (point-min)) + (while (not (eobp)) + (add-text-properties + (point-at-bol) (point-at-eol) + `(helm-linum ,count)) + (cl-incf count) + (forward-line 1)))))) + (get-line :initform #'buffer-substring) + (candidates-file + :initarg :candidates-file + :initform nil + :custom string + :documentation + " A filename. + Each line number of FILE is accessible with helm-linum property + from candidate display part.")) + + "The contents of the FILE will be used as candidates in buffer.") + + +;;; Error functions +;; +;; +(defun helm-default-init-source-in-buffer-function () + (helm-init-candidates-in-buffer 'global + '("ERROR: No buffer handling your data, use either the `init' slot or the `data' slot."))) + + +;;; Internal Builder functions. +;; +;; +(defun helm--create-source (object) + "[INTERNAL] Build a helm source from OBJECT. +Where OBJECT is an instance of an eieio class." + (cl-loop for s in (object-slots object) + for slot-val = (slot-value object s) + when slot-val + collect (cons s (unless (eq t slot-val) slot-val)))) + +(defun helm-make-source (name class &rest args) + "Build a `helm' source named NAME with ARGS for CLASS. +Argument NAME is a string which define the source name, so no need to use +the keyword :name in your source, NAME will be used instead. +Argument CLASS is an eieio class object. +Arguments ARGS are keyword value pairs as defined in CLASS." + (declare (indent 2)) + (let ((source (apply #'make-instance class name args))) + (setf (slot-value source 'name) name) + (helm--setup-source source) + (helm-setup-user-source source) + (helm--create-source source))) + +(defun helm-make-type (class &rest args) + (let ((source (apply #'make-instance class args))) + (setf (slot-value source 'name) nil) + (helm--setup-source source) + (helm--create-source source))) + +(defvar helm-mm-default-search-functions) +(defvar helm-mm-default-match-functions) + +(defun helm-source-mm-get-search-or-match-fns (source method) + (let ((defmatch (helm-aif (slot-value source 'match) + (helm-mklist it))) + (defmatch-strict (helm-aif (and (eq method 'match) + (slot-value source 'match-strict)) + (helm-mklist it))) + (defsearch (helm-aif (and (eq method 'search) + (slot-value source 'search)) + (helm-mklist it))) + (defsearch-strict (helm-aif (and (eq method 'search-strict) + (slot-value source 'search-strict)) + (helm-mklist it))) + (migemo (slot-value source 'migemo))) + (cl-case method + (match (cond (defmatch-strict) + (migemo + (append helm-mm-default-match-functions + defmatch '(helm-mm-3-migemo-match))) + (defmatch + (append helm-mm-default-match-functions defmatch)) + (t helm-mm-default-match-functions))) + (search (cond (defsearch-strict) + (migemo + (append helm-mm-default-search-functions + defsearch '(helm-mm-3-migemo-search))) + (defsearch + (append helm-mm-default-search-functions defsearch)) + (t helm-mm-default-search-functions)))))) + + +;;; Modifiers +;; +(cl-defun helm-source-add-action-to-source-if (name fn source predicate + &optional (index 4)) + "Same as `helm-add-action-to-source-if' but for SOURCE defined as eieio object. +You can use this inside a `helm--setup-source' method for a SOURCE defined as +an eieio class." + (let* ((actions (slot-value source 'action)) + (action-transformers (slot-value source 'action-transformer)) + (new-action (list (cons name fn))) + (transformer (lambda (actions candidate) + (cond ((funcall predicate candidate) + (helm-append-at-nth + actions new-action index)) + (t actions))))) + (cond ((functionp actions) + (setf (slot-value source 'action) (list (cons "Default action" actions)))) + ((listp actions) + (setf (slot-value source 'action) (helm-interpret-value actions source)))) + (when (or (symbolp action-transformers) (functionp action-transformers)) + (setq action-transformers (list action-transformers))) + (setf (slot-value source 'action-transformer) + (delq nil (append (list transformer) action-transformers))))) + + +;;; Methods to build sources. +;; +;; +(defun helm-source--persistent-help-string (string source) + (substitute-command-keys + (concat "\\\\[helm-execute-persistent-action]: " + (or (format "%s (keeping session)" string) + (slot-value source 'header-line))))) + +(defun helm-source--header-line (source) + (substitute-command-keys + (concat "\\\\[helm-execute-persistent-action]: " + (helm-aif (or (slot-value source 'persistent-action) + (slot-value source 'action)) + (cond ((and (symbolp it) + (functionp it) + (eq it 'identity)) + "Do Nothing") + ((and (symbolp it) + (boundp it) + (listp (symbol-value it)) + (stringp (caar (symbol-value it)))) + (caar (symbol-value it))) + ((or (symbolp it) (functionp it)) + (helm-symbol-name it)) + ((listp it) + (let ((action (car it))) + ;; It comes from :action ("foo" . function). + (if (stringp (car action)) + (car action) + ;; It comes from :persistent-action + ;; (function . 'nosplit) Fix Issue #788. + (if (or (symbolp action) + (functionp action)) + (helm-symbol-name action))))) + (t "")) + "") + " (keeping session)"))) + +(defmethod helm--setup-source :primary ((_source helm-source))) + +(defmethod helm--setup-source :before ((source helm-source)) + (when (slot-value source 'delayed) + (warn "Deprecated usage of helm `delayed' slot in `%s'" + (slot-value source 'name))) + (helm-aif (slot-value source 'keymap) + (and (symbolp it) (setf (slot-value source 'keymap) (symbol-value it)))) + (helm-aif (slot-value source 'persistent-help) + (setf (slot-value source 'header-line) + (helm-source--persistent-help-string it source)) + (setf (slot-value source 'header-line) (helm-source--header-line source))) + (when (and (slot-value source 'fuzzy-match) helm-fuzzy-sort-fn) + (setf (slot-value source 'filtered-candidate-transformer) + (helm-aif (slot-value source 'filtered-candidate-transformer) + (append (helm-mklist it) + (list helm-fuzzy-sort-fn)) + (list helm-fuzzy-sort-fn)))) + (unless (slot-value source 'nohighlight) + (setf (slot-value source 'filtered-candidate-transformer) + (helm-aif (slot-value source 'filtered-candidate-transformer) + (append (helm-mklist it) + (list #'helm-fuzzy-highlight-matches)) + (list #'helm-fuzzy-highlight-matches)))) + (when (numberp (helm-interpret-value (slot-value source 'multiline))) + (setf (slot-value source 'filtered-candidate-transformer) + (helm-aif (slot-value source 'filtered-candidate-transformer) + (append (helm-mklist it) + (list #'helm-multiline-transformer)) + (list #'helm-multiline-transformer))))) + +(defmethod helm-setup-user-source ((_source helm-source))) + +(defmethod helm--setup-source ((source helm-source-sync)) + (when (slot-value source 'fuzzy-match) + (helm-aif (slot-value source 'match) + (setf (slot-value source 'match) + (append (helm-mklist it) + (list helm-fuzzy-match-fn))) + (setf (slot-value source 'match) helm-fuzzy-match-fn))) + (when (slot-value source 'multimatch) + (setf (slot-value source 'match) + (helm-source-mm-get-search-or-match-fns source 'match))) + (helm-aif (and (null (slot-value source 'multimatch)) + (slot-value source 'migemo)) + (unless (eq it 'nomultimatch) ; Use own migemo fn. + (setf (slot-value source 'match) + (append (helm-mklist (slot-value source 'match)) + '(helm-mm-3-migemo-match)))))) + +(defmethod helm--setup-source ((source helm-source-in-buffer)) + (let ((cur-init (slot-value source 'init))) + (helm-aif (slot-value source 'data) + (setf (slot-value source 'init) + (delq + nil + (list + (and (null (eq 'helm-default-init-source-in-buffer-function + cur-init)) + cur-init) + (lambda () + (helm-init-candidates-in-buffer + 'global + (cond ((functionp it) (funcall it)) + ((and (bufferp it) (buffer-live-p it)) + (with-current-buffer it (buffer-string))) + (t it))))))))) + (when (slot-value source 'fuzzy-match) + (helm-aif (slot-value source 'search) + (setf (slot-value source 'search) + (append (helm-mklist it) + (list helm-fuzzy-search-fn))) + (setf (slot-value source 'search) (list helm-fuzzy-search-fn)))) + (when (slot-value source 'multimatch) + (setf (slot-value source 'search) + (helm-source-mm-get-search-or-match-fns source 'search))) + (helm-aif (and (null (slot-value source 'multimatch)) + (slot-value source 'migemo)) + (unless (eq it 'nomultimatch) + (setf (slot-value source 'search) + (append (helm-mklist (slot-value source 'search)) + '(helm-mm-3-migemo-search))))) + (let ((mtc (slot-value source 'match))) + (cl-assert (or (equal '(identity) mtc) + (eq 'identity mtc)) + nil "Invalid slot value for `match'") + (cl-assert (eq (slot-value source 'volatile) t) + nil "Invalid slot value for `volatile'"))) + +(defmethod helm--setup-source ((source helm-source-async)) + (cl-assert (null (slot-value source 'candidates)) + nil "Incorrect use of `candidates' use `candidates-process' instead") + (cl-assert (null (slot-value source 'multimatch)) + nil "`multimatch' not allowed in async sources.") + (cl-assert (null (slot-value source 'fuzzy-match)) + nil "`fuzzy-match' not supported in async sources.")) + +(defmethod helm--setup-source ((source helm-source-dummy)) + (let ((mtc (slot-value source 'match))) + (cl-assert (or (equal '(identity) mtc) + (eq 'identity mtc)) + nil "Invalid slot value for `match'") + (cl-assert (eq (slot-value source 'volatile) t) + nil "Invalid slot value for `volatile'") + (cl-assert (equal (slot-value source 'candidates) '("dummy")) + nil "Invalid slot value for `candidates'") + (cl-assert (eq (slot-value source 'accept-empty) t) + nil "Invalid slot value for `accept-empty'"))) + + +;;; User functions +;; +;; Sources +(defmacro helm-build-sync-source (name &rest args) + "Build a synchronous helm source with name NAME. +Args ARGS are keywords provided by `helm-source-sync'." + (declare (indent 1)) + `(helm-make-source ,name 'helm-source-sync ,@args)) + +(defmacro helm-build-async-source (name &rest args) + "Build a asynchronous helm source with name NAME. +Args ARGS are keywords provided by `helm-source-async'." + (declare (indent 1)) + `(helm-make-source ,name 'helm-source-async ,@args)) + +(defmacro helm-build-in-buffer-source (name &rest args) + "Build a helm source with name NAME using `candidates-in-buffer' method. +Args ARGS are keywords provided by `helm-source-in-buffer'." + (declare (indent 1)) + `(helm-make-source ,name 'helm-source-in-buffer ,@args)) + +(defmacro helm-build-dummy-source (name &rest args) + "Build a helm source with name NAME using `dummy' method. +Args ARGS are keywords provided by `helm-source-dummy'." + (declare (indent 1)) + `(helm-make-source ,name 'helm-source-dummy ,@args)) + +(defmacro helm-build-in-file-source (name file &rest args) + "Build a helm source with NAME name using `candidates-in-files' method. +Arg FILE is a filename, the contents of this file will be +used as candidates in buffer. +Args ARGS are keywords provided by `helm-source-in-file'." + (declare (indent 1)) + `(helm-make-source ,name 'helm-source-in-file + :candidates-file ,file ,@args)) + + +(provide 'helm-source) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm-source ends here diff --git a/elpa/helm-core-20181114.621/helm.el b/elpa/helm-core-20181114.621/helm.el new file mode 100644 index 00000000..34154864 --- /dev/null +++ b/elpa/helm-core-20181114.621/helm.el @@ -0,0 +1,6786 @@ +;;; helm.el --- Emacs incremental and narrowing framework -*- lexical-binding: t -*- + +;; Copyright (C) 2007 Tamas Patrovics +;; 2008 ~ 2011 rubikitch +;; 2011 ~ 2018 Thierry Volpiatto + +;; This is a fork of anything.el wrote by Tamas Patrovics. + +;; Authors of anything.el: Tamas Patrovics +;; rubikitch +;; Thierry Volpiatto + +;; Author: Thierry Volpiatto +;; URL: http://github.com/emacs-helm/helm + +;; 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 3 of the License, 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 this program. If not, see . + +;;; Code: + +(require 'cl-lib) +(require 'async) +(require 'advice) ; Shutup byte compiler about ad-deactivate. +(require 'helm-lib) +(require 'helm-multi-match) +(require 'helm-source) + + +;;; Multi keys +;; +;; +;;;###autoload +(defun helm-define-multi-key (keymap key functions &optional delay) + "In KEYMAP, define key sequence KEY for function list FUNCTIONS. +Each function runs sequentially for each KEY press. +If DELAY is specified, switch back to initial function of FUNCTIONS list +after DELAY seconds. +The functions in FUNCTIONS list take no args. +e.g + (defun foo () + (interactive) + (message \"Run foo\")) + (defun bar () + (interactive) + (message \"Run bar\")) + (defun baz () + (interactive) + (message \"Run baz\")) + +\(helm-define-multi-key global-map (kbd \" q\") '(foo bar baz) 2) + +Each time \" q\" is pressed, the next function is executed. Waiting +more than 2 seconds between key presses switches back to executing the first +function on the next hit." + (define-key keymap key (helm-make-multi-command functions delay))) + +;;;###autoload +(defmacro helm-multi-key-defun (name docstring funs &optional delay) + "Define NAME as a multi-key command running FUNS. +After DELAY seconds, the FUNS list is reinitialized. +See `helm-define-multi-key'." + (declare (indent 2)) + (setq docstring (if docstring (concat docstring "\n\n") + "This is a helm-ish multi-key command.")) + `(defalias (quote ,name) (helm-make-multi-command ,funs ,delay) ,docstring)) + +(defun helm-make-multi-command (functions &optional delay) + "Return an anonymous multi-key command running FUNCTIONS. +Run each function in the FUNCTIONS list in turn when called within DELAY seconds." + (declare (indent 1)) + (let ((funs functions) + (iter (cl-gensym "helm-iter-key")) + (timeout delay)) + (eval (list 'defvar iter nil)) + (lambda () + (interactive) + (helm-run-multi-key-command funs iter timeout)))) + +(defun helm-run-multi-key-command (functions iterator delay) + (let ((fn (lambda () + (cl-loop for count from 1 to (length functions) + collect count))) + next) + (unless (and (symbol-value iterator) + ;; Reset iterator when another key is pressed. + (eq this-command real-last-command)) + (set iterator (helm-iter-list (funcall fn)))) + (setq next (helm-iter-next (symbol-value iterator))) + (unless next + (set iterator (helm-iter-list (funcall fn))) + (setq next (helm-iter-next (symbol-value iterator)))) + (and next (symbol-value iterator) + (call-interactively (nth (1- next) functions))) + (when delay (run-with-idle-timer + delay nil (lambda () + (set iterator nil)))))) + +(helm-multi-key-defun helm-toggle-resplit-and-swap-windows + "Multi key command to re-split and swap helm window. +First call runs `helm-toggle-resplit-window', +and second call within 0.5s runs `helm-swap-windows'." + '(helm-toggle-resplit-window helm-swap-windows) 1) +(put 'helm-toggle-resplit-and-swap-windows 'helm-only t) + +;;;###autoload +(defun helm-define-key-with-subkeys (map key subkey command + &optional other-subkeys prompt exit-fn) + "Defines in MAP a KEY and SUBKEY to COMMAND. + +This allows typing KEY to call COMMAND the first time and +type only SUBKEY on subsequent calls. + +Arg MAP is the keymap to use, SUBKEY is the initial short key-binding to +call COMMAND. + +Arg OTHER-SUBKEYS is an alist specifying other short key-bindings +to use once started e.g: + + \(helm-define-key-with-subkeys global-map + \(kbd \"C-x v n\") ?n 'git-gutter:next-hunk '((?p . git-gutter:previous-hunk))\) + + +In this example, `C-x v n' will run `git-gutter:next-hunk' +subsequent \"n\"'s run this command again +and subsequent \"p\"'s run `git-gutter:previous-hunk'. + +If specified PROMPT can be displayed in minibuffer to +describe SUBKEY and OTHER-SUBKEYS. +Arg EXIT-FN specifies a function to run on exit. + +For any other keys pressed, run their assigned command as defined +in MAP and then exit the loop running EXIT-FN, if specified. + +NOTE: SUBKEY and OTHER-SUBKEYS bindings support only char syntax and +vectors, so don't use strings to define them." + (declare (indent 1)) + (define-key map key + (lambda () + (interactive) + (unwind-protect + (progn + (call-interactively command) + (while (let ((input (read-key prompt)) other kb com) + (setq last-command-event input) + (cond + ((eq input subkey) + (call-interactively command) + t) + ((setq other (assoc input other-subkeys)) + (call-interactively (cdr other)) + t) + (t + (setq kb (vector last-command-event)) + (setq com (lookup-key map kb)) + (if (commandp com) + (call-interactively com) + (setq unread-command-events + (nconc (mapcar 'identity kb) + unread-command-events))) + nil))))) + (and exit-fn (funcall exit-fn)))))) + +;;; Keymap +;; +;; +(defvar helm-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map minibuffer-local-map) + (define-key map (kbd "") 'helm-next-line) + (define-key map (kbd "") 'helm-previous-line) + (define-key map (kbd "C-n") 'helm-next-line) + (define-key map (kbd "C-p") 'helm-previous-line) + (define-key map (kbd "") 'helm-follow-action-forward) + (define-key map (kbd "") 'helm-follow-action-backward) + (define-key map (kbd "") 'helm-previous-page) + (define-key map (kbd "") 'helm-next-page) + (define-key map (kbd "M-v") 'helm-previous-page) + (define-key map (kbd "C-v") 'helm-next-page) + (define-key map (kbd "M-<") 'helm-beginning-of-buffer) + (define-key map (kbd "M->") 'helm-end-of-buffer) + (define-key map (kbd "C-g") 'helm-keyboard-quit) + (define-key map (kbd "") 'helm-next-source) + (define-key map (kbd "") 'helm-previous-source) + (define-key map (kbd "") 'helm-maybe-exit-minibuffer) + (define-key map (kbd "C-i") 'helm-select-action) + (define-key map (kbd "C-z") 'helm-execute-persistent-action) + (define-key map (kbd "C-j") 'helm-execute-persistent-action) + (define-key map (kbd "C-o") 'helm-next-source) + (define-key map (kbd "M-o") 'helm-previous-source) + (define-key map (kbd "C-l") 'helm-recenter-top-bottom-other-window) + (define-key map (kbd "M-C-l") 'helm-reposition-window-other-window) + (define-key map (kbd "C-M-v") 'helm-scroll-other-window) + (define-key map (kbd "M-") 'helm-scroll-other-window) + (define-key map (kbd "C-M-y") 'helm-scroll-other-window-down) + (define-key map (kbd "C-M-S-v") 'helm-scroll-other-window-down) + (define-key map (kbd "M-") 'helm-scroll-other-window-down) + (define-key map (kbd "") 'helm-scroll-other-window) + (define-key map (kbd "") 'helm-scroll-other-window-down) + (define-key map (kbd "C-@") 'helm-toggle-visible-mark) + (define-key map (kbd "C-SPC") 'helm-toggle-visible-mark) + (define-key map (kbd "M-SPC") 'helm-toggle-visible-mark) + (define-key map (kbd "M-[") nil) + (define-key map (kbd "M-(") 'helm-prev-visible-mark) + (define-key map (kbd "M-)") 'helm-next-visible-mark) + (define-key map (kbd "C-k") 'helm-delete-minibuffer-contents) + (define-key map (kbd "C-x C-f") 'helm-quit-and-find-file) + (define-key map (kbd "M-m") 'helm-toggle-all-marks) + (define-key map (kbd "M-a") 'helm-mark-all) + (define-key map (kbd "M-U") 'helm-unmark-all) + (define-key map (kbd "C-M-a") 'helm-show-all-in-this-source-only) + (define-key map (kbd "C-M-e") 'helm-display-all-sources) + (define-key map (kbd "C-s") 'undefined) + (define-key map (kbd "M-s") 'undefined) + (define-key map (kbd "C-}") 'helm-narrow-window) + (define-key map (kbd "C-{") 'helm-enlarge-window) + (define-key map (kbd "C-c -") 'helm-swap-windows) + (define-key map (kbd "C-c _") 'helm-toggle-full-frame) + (define-key map (kbd "C-c %") 'helm-exchange-minibuffer-and-header-line) + (define-key map (kbd "C-c C-y") 'helm-yank-selection) + (define-key map (kbd "C-c C-k") 'helm-kill-selection-and-quit) + (define-key map (kbd "C-c C-i") 'helm-copy-to-buffer) + (define-key map (kbd "C-c C-f") 'helm-follow-mode) + (define-key map (kbd "C-c C-u") 'helm-refresh) + (define-key map (kbd "C-c >") 'helm-toggle-truncate-line) + (define-key map (kbd "M-p") 'previous-history-element) + (define-key map (kbd "M-n") 'next-history-element) + (define-key map (kbd "C-!") 'helm-toggle-suspend-update) + (define-key map (kbd "C-x b") 'helm-resume-previous-session-after-quit) + (define-key map (kbd "C-x C-b") 'helm-resume-list-buffers-after-quit) + (helm-define-key-with-subkeys map (kbd "C-c n") ?n 'helm-run-cycle-resume) + ;; Disable `file-cache-minibuffer-complete'. + (define-key map (kbd "") 'undefined) + ;; Multi keys + (define-key map (kbd "C-t") 'helm-toggle-resplit-and-swap-windows) + ;; Debugging command + (define-key map (kbd "C-h C-d") 'undefined) + (define-key map (kbd "C-h C-d") 'helm-enable-or-switch-to-debug) + (define-key map (kbd "C-h c") 'helm-customize-group) + ;; Allow to eval keymap without errors. + (define-key map [f1] nil) + (define-key map (kbd "C-h C-h") 'undefined) + (define-key map (kbd "C-h h") 'undefined) + (helm-define-key-with-subkeys map + (kbd "C-w") ?\C-w 'helm-yank-text-at-point + '((?\C-_ . helm-undo-yank-text-at-point))) + ;; Use `describe-mode' key in `global-map'. + (cl-dolist (k (where-is-internal 'describe-mode global-map)) + (define-key map k 'helm-help)) + (define-key map (kbd "C-c ?") 'helm-help) + ;; Bind all actions from 1 to 12 to their corresponding nth index+1. + (cl-loop for n from 0 to 12 do + (define-key map (kbd (format "" (1+ n))) + `(lambda () + (interactive) + (helm-select-nth-action ,n)))) + map) + "Keymap for helm.") + +(defun helm-customize-group () + "Jump to customization group of current source. + +Default to `helm' when group is not defined in source." + (interactive) + (helm-run-after-exit 'customize-group (helm-attr 'group))) +(put 'helm-customize-group 'helm-only t) + +(defun helm--action-at-nth-set-fn-1 (value &optional negative) + (cl-loop for n from 1 to 9 + for key = (format value n) + for sym = (make-symbol (format "helm-execute-selection-action-at-nth-+%d" n)) + for fn = `(lambda () + (interactive) + (helm-execute-selection-action-at-nth ,(if negative (- n) n))) + do (progn + (defalias sym fn) + (define-key helm-map (kbd key) sym)))) + +(defun helm--action-at-nth-set-fn- (var val) + (set var val) + (helm--action-at-nth-set-fn-1 val 'negative)) + +(defun helm--action-at-nth-set-fn+ (var val) + (set var val) + (helm--action-at-nth-set-fn-1 val)) + +(defcustom helm-action-at-nth-negative-prefix-key "C-x %d" + "The prefix key to execute default action on nth <-n> candidate. + +This is a format spec where %d will be replaced by the candidate +number. + +NOTE: `setq' have no effect until you restart emacs, use customize for +immediate effect." + :group 'helm + :type 'string + :set #'helm--action-at-nth-set-fn-) + +(defcustom helm-action-at-nth-positive-prefix-key "C-c %d" + "The prefix key to execute default action on nth <+n> candidate. + +This is a format spec where %d will be replaced by the candidate +number. + +NOTE: `setq' have no effect until you restart emacs, use customize for +immediate effect." + :group 'helm + :type 'string + :set #'helm--action-at-nth-set-fn+) + + +(defgroup helm nil + "Open helm." + :prefix "helm-" :group 'convenience) + +(defcustom helm-completion-window-scroll-margin 5 + " `scroll-margin' to use for helm completion window. +Set to 0 to disable. +NOTE: This has no effect when `helm-display-source-at-screen-top' +id is non-`nil'." + :group 'helm + :type 'integer) + +(defcustom helm-display-source-at-screen-top t + "Display candidates at the top of screen. +This happens with `helm-next-source' and `helm-previous-source'. +NOTE: When non-`nil' (default), disable `helm-completion-window-scroll-margin'." + :group 'helm + :type 'boolean) + +(defcustom helm-candidate-number-limit 100 + "Global limit for number of candidates displayed. +When the pattern is empty, the number of candidates shown will be +as set here instead of the entire list, which may be hundreds or +thousands. Since narrowing and filtering rapidly reduces +available candidates, having a small list will keep the interface +responsive. + +Set this value to nil for no limit." + :group 'helm + :type '(choice (const :tag "Disabled" nil) integer)) + +(defcustom helm-input-idle-delay 0.01 + "Idle time before updating, specified in seconds." + :group 'helm + :type 'float) + +(defcustom helm-exit-idle-delay 0 + "Idle time before exiting minibuffer while helm is updating. +Has no affect when helm-buffer is up to date \(i.e exit without +delay in this condition\)." + :group 'helm + :type 'float) + +(defvaralias 'helm-samewindow 'helm-full-frame) +(make-obsolete-variable 'helm-samewindow 'helm-full-frame "1.4.8.1") +(defcustom helm-full-frame nil + "Use current window for showing candidates. +If t, then Helm does not pop-up new window." + :group 'helm + :type 'boolean) + +(defcustom helm-candidate-separator + "--------------------" + "Candidates separator of `multiline' source." + :group 'helm + :type 'string) + +(defcustom helm-save-configuration-functions + '(set-window-configuration . current-window-configuration) + "Functions used to restore or save configurations for frames and windows. +Specified as a pair of functions, where car is the restore function and cdr +is the save function. + +To save and restore frame configuration, set this variable to +'\(set-frame-configuration . current-frame-configuration\) + +NOTE: This may not work properly with own-frame minibuffer +settings. Older versions saves/restores frame configuration, but +the default has changed now to avoid flickering." + :group 'helm + :type 'sexp) + +(defcustom helm-display-function 'helm-default-display-buffer + "Function used to display `helm-buffer'. + +Local value in `helm-buffer' will take precedence on this default +value. Commands that are in `helm-commands-using-frame' will have +`helm-buffer' displayed in frame, `helm-display-function' being +ignored. +If no local value found and current command is not one of +`helm-commands-using-frame' use this default value. +Function in charge of deciding which value use is +`helm-resolve-display-function'. + +To set it locally to `helm-buffer' in helm sources use +`helm-set-local-variable' in init function or use +:display-function slot in `helm' call." + :group 'helm + :type 'symbol) + +(defcustom helm-case-fold-search 'smart + "Adds 'smart' option to `case-fold-search'. +Smart option ignores case for searches as long as there are no +upper case characters in the pattern. + +Use nil or t to turn off smart behavior and use +`case-fold-search' behavior. + +Default is smart. + +NOTE: Case fold search has no effect when searching asynchronous +sources, which rely on customized features implemented directly +into their execution process. See helm-grep.el for an example." + :group 'helm + :type '(choice (const :tag "Ignore case" t) + (const :tag "Respect case" nil) + (other :tag "Smart" 'smart))) + +(defcustom helm-file-name-case-fold-search + (if (memq system-type + '(cygwin windows-nt ms-dos darwin)) + t + helm-case-fold-search) + "Local setting of `helm-case-fold-search' for reading filenames. + +See `helm-case-fold-search' for more info." + :group 'helm + :type 'symbol) + +(defcustom helm-reuse-last-window-split-state nil + "Use the same state of window split, vertical or horizontal. +`helm-toggle-resplit-window' for the next helm session will use +the same window scheme as the previous session unless +`helm-split-window-default-side' is 'same or 'other." + :group 'helm + :type 'boolean) + +(defcustom helm-split-window-preferred-function 'helm-split-window-default-fn + "Default function used for splitting window." + :group 'helm + :type 'function) + +(defcustom helm-split-window-default-side 'below + "The default side to display `helm-buffer'. +Must be one acceptable arg for `split-window' SIDE, +that is `below', `above', `left' or `right'. + +Other acceptable values are `same' which always display +`helm-buffer' in current window and `other' that display +`helm-buffer' below if only one window or in +`other-window-for-scrolling' when available. + +A nil value has same effect as `below'. +If `helm-full-frame' is non-`nil', it take precedence over this setting. + +See also `helm-split-window-inside-p' and `helm-always-two-windows' that +take precedence over this. + +NOTE: this have no effect if `helm-split-window-preferred-function' is not +`helm-split-window-default-fn' unless this new function can handle this." + :group 'helm + :type 'symbol) + +(defcustom helm-display-buffer-default-height nil + "Initial height of `helm-buffer', specified as an integer or a function. + +The function should take one arg and the responsibility for +re-sizing the window; function's return value is ignored. +Note that this have no effect when the split is vertical. +See `display-buffer' for more info." + :group 'helm + :type '(choice integer function)) + +(defcustom helm-display-buffer-default-width nil + "Initial width of `helm-buffer', specified as an integer or a function. + +The function should take one arg and the responsibility for +re-sizing the window; function's return value is ignored. +Note that this have no effect when the split is horizontal. +See `display-buffer' for more info." + :group 'helm + :type '(choice integer function)) + +(defvaralias 'helm-split-window-in-side-p 'helm-split-window-inside-p) +(make-obsolete-variable 'helm-split-window-in-side-p 'helm-split-window-inside-p "2.8.6") +(defcustom helm-split-window-inside-p nil + "Forces split inside selected window when non-`nil'. +See also `helm-split-window-default-side'. + +NOTE: this has no effect if +`helm-split-window-preferred-function' is not +`helm-split-window-default-fn' unless this new function can +handle this." + :group 'helm + :type 'boolean) + +(defcustom helm-always-two-windows nil + "When non-`nil' helm uses two windows in this frame. +To display `helm-buffer' in one window and `helm-current-buffer' +in the other. + +Note: this has no effect when `helm-split-window-inside-p' is non-`nil', +or when `helm-split-window-default-side' is set to 'same. + +When `helm-autoresize-mode' is enabled, setting this to nil +will have no effect. + +Also when non-`nil' it overrides the effect of `helm-split-window-default-side' +set to `other'." + :group 'helm + :type 'boolean) + +(defcustom helm-display-buffer-width 72 + "Frame width when displaying helm-buffer in own frame." + :group 'helm + :type 'integer) + +(defcustom helm-display-buffer-height 20 + "Frame height when displaying helm-buffer in own frame." + :group 'helm + :type 'integer) + +(defcustom helm-default-display-buffer-functions nil + "Action functions to pass to `display-buffer'. +See (info \"(elisp) Display Action Functions\"). + +Have no effect when `helm-always-two-windows' is non-nil and may +override other settings like `helm-split-window-inside-p'." + :group 'helm + :type '(repeat symbol)) + +(defcustom helm-default-display-buffer-alist nil + "Additional alist to pass to `display-buffer' action. +See (info \"(elisp) Display Action Functions\"). + +Have no effect when `helm-always-two-windows' is non-nil and may +override other settings like `helm-split-window-inside-p'. +Note that window-height and window-width have to be configured in +`helm-display-buffer-height' and `helm-display-buffer-width'." + :group 'helm + :type '(alist :key-type symbol :value-type sexp)) + +(defcustom helm-sources-using-default-as-input '(helm-source-imenu + helm-source-imenu-all + helm-source-info-elisp + helm-source-etags-select + helm-source-man-pages + helm-source-occur + helm-source-moccur + helm-source-grep-ag + helm-source-grep-git + helm-source-grep) + "List of helm sources that need to use `helm--maybe-use-default-as-input'. +When a source is a member of this list, default `thing-at-point' +will be used as input." + :group 'helm + :type '(repeat (choice symbol))) + +(defcustom helm-delete-minibuffer-contents-from-point t + "When non-`nil', `helm-delete-minibuffer-contents' delete region from `point'. +Otherwise delete `minibuffer-contents'. +See documentation for `helm-delete-minibuffer-contents'." + :group 'helm + :type 'boolean) + +(defcustom helm-follow-mode-persistent nil + "When non-`nil', save last state of `helm-follow-mode' for the next emacs sessions. + +Each time you turn on or off `helm-follow-mode', the current source name will be stored +or removed from `helm-source-names-using-follow'. + +Note that this may be disabled in some places where it is unsafe to use +because persistent action is changing according to context." + :group 'helm + :type 'boolean) + +(defcustom helm-source-names-using-follow nil + "A list of source names to have follow enabled. +This list of source names will be used only +when `helm-follow-mode-persistent' is non-nil. + +You don't have to customize this yourself unless you really want and +know what you are doing, instead just set +`helm-follow-mode-persistent' to non-nil and as soon you turn on or +off `helm-follow-mode' (C-c C-f) in a source, helm will save or remove +source name in this variable." + :group 'helm + :type '(repeat (choice string))) + +(defcustom helm-prevent-escaping-from-minibuffer t + "Prevent escaping from minibuffer with `other-window' during the helm session." + :group 'helm + :type 'boolean) + +(defcustom helm-allow-mouse nil + "Allow mouse usage during the helm session when non-nil. + +Note that this also allow moving out of minibuffer when clicking +outside of `helm-buffer', up to you to get back to helm by clicking +back in `helm-buffer' of minibuffer." + :group 'helm + :type 'boolean) + +(defcustom helm-move-to-line-cycle-in-source nil + "Cycle to the beginning or end of the list after reaching the bottom or top. +This applies when using `helm-next/previous-line'." + :group 'helm + :type 'boolean) + +(defcustom helm-fuzzy-match-fn 'helm-fuzzy-match + "The function for fuzzy matching in `helm-source-sync' based sources." + :group 'helm + :type 'function) + +(defcustom helm-fuzzy-search-fn 'helm-fuzzy-search + "The function for fuzzy matching in `helm-source-in-buffer' based sources." + :group 'helm + :type 'function) + +(defcustom helm-fuzzy-sort-fn 'helm-fuzzy-matching-default-sort-fn + "The sort transformer function used in fuzzy matching. +When nil, sorting is not done." + :group 'helm + :type 'function) + +(defcustom helm-fuzzy-matching-highlight-fn 'helm-fuzzy-default-highlight-match + "The function to highlight fuzzy matches. +When nil, no highlighting is done." + :group 'helm + :type 'function) + +(defcustom helm-autoresize-max-height 40 + "Specifies maximum height and defaults to percent of helm window's frame height. + +See `fit-window-to-buffer' for more infos." + :group 'helm + :type 'integer) + +(defcustom helm-autoresize-min-height 10 + "Specifies minimum height and defaults to percent of helm window's frame height. + +If nil, `window-min-height' is used. +See `fit-window-to-buffer' for details." + :group 'helm + :type 'integer) + +(defcustom helm-input-method-verbose-flag nil + "The default value for `input-method-verbose-flag' used in helm minibuffer. +It is nil by default, which does not turn off input method. Helm +updates and exits without interruption -- necessary for complex methods. + +If set to any other value as per `input-method-verbose-flag', +then use `C-\\' to disable the `current-input-method' to exit or update helm" + :group 'helm + :type '(radio :tag "A flag to control extra guidance for input methods in helm." + (const :tag "Never provide guidance" nil) + (const :tag "Always provide guidance" t) + (const :tag "Provide guidance only for complex methods" complex-only))) + +(defcustom helm-display-header-line t + "Display header-line when non nil." + :group 'helm + :type 'boolean) + +(defcustom helm-inherit-input-method t + "Inherit `current-input-method' from `current-buffer' when non-`nil'. +The default is to enable this by default and then toggle +`toggle-input-method'." + :group 'helm + :type 'boolean) + +(defcustom helm-echo-input-in-header-line nil + "Send current input in header-line when non-nil." + :group 'helm + :type 'boolean) + +(defcustom helm-header-line-space-before-prompt 'left-fringe + "Specify the space before prompt in header-line. + +This will be used when `helm-echo-input-in-header-line' is non-nil. + +Value can be one of the symbols 'left-fringe or 'left-margin or an +integer specifying the number of spaces before prompt. +Note that on input longer that `window-width' the continuation string +will be shown on left side of window without taking care of this." + :group 'helm + :type '(choice + (symbol + (const :tag "Fringe" 'left-fringe) + (const :tag "Margin" 'left-margin)) + integer)) + +(defcustom helm-tramp-connection-min-time-diff 5 + "Value of `tramp-connection-min-time-diff' for helm remote processes. +If set to zero helm remote processes are not delayed. +Setting this to a value less than 5 or disabling it with a zero value +is risky, however on emacs versions starting at 24.5 it seems +it is now possible to disable it. +Anyway at any time in helm you can suspend your processes while typing +by hitting \\ `\\[helm-toggle-suspend-update]'. +Only async sources than use a sentinel calling +`helm-process-deferred-sentinel-hook' are affected by this." + :type 'integer + :group 'helm) + +(defcustom helm-debug-root-directory nil + "When non-`nil', saves helm log messages to a file in this directory. +When `nil' log messages are saved to a buffer instead. +Log message are saved only when `helm-debug' is non-nil, so setting this +doesn't enable debugging by itself. + +See `helm-log-save-maybe' for more info." + :type 'string + :group 'helm) + +(defcustom helm-show-action-window-other-window nil + "Show action buffer beside `helm-buffer' when non-nil. + +If nil don't split and replace helm-buffer by the action buffer +in same window. +If left display the action buffer at the left of helm-buffer. +If right or any other value, split at right. + +Note that this may not fit well with some helm window configurations, +so it have only effect when `helm-always-two-windows' is non-nil." + :group 'helm + :type '(choice + (const :tag "Split at left" left) + (const :tag "Don't split" nil) + (other :tag "Split at right" right))) + +(defcustom helm-cycle-resume-delay 1.0 + "Delay used before resuming in `helm-run-cycle-resume'." + :type 'float + :group 'helm) + +(defcustom helm-display-buffer-reuse-frame nil + "When non nil helm frame is not deleted and reused in next sessions. + +This was used to workaround a bug in emacs where frames where +popping up slowly, now that the bug have been fixed upstream probably +you don't want to use this anymore." + :group 'helm + :type 'boolean) + +(defcustom helm-commands-using-frame nil + "A list of commands where `helm-buffer' is displayed in a frame." + :group 'helm + :type '(repeat symbol)) + +(defcustom helm-actions-inherit-frame-settings t + "Actions inherit helm frame settings of initial command when non nil." + :group 'helm + :type 'boolean) + +(defcustom helm-use-undecorated-frame-option nil + "Display helm frame undecorated when non nil. + +This option have no effect with emacs versions lower than 26." + :group 'helm + :type 'boolean) + +(defcustom helm-use-frame-when-more-than-two-windows nil + "Display helm buffer in frame when more than two windows." + :group 'helm + :type 'boolean) + +(defcustom helm-default-prompt-display-function + #'helm-set-default-prompt-display + "The function to use to set face of fake cursor in header-line." + :group 'helm + :type 'function) + +;;; Faces +;; +;; +(defgroup helm-faces nil + "Customize the appearance of helm." + :prefix "helm-" + :group 'faces + :group 'helm) + +(defface helm-source-header + '((((background dark)) + :background "#22083397778B" + :foreground "white" + :weight bold :height 1.3 :family "Sans Serif") + (((background light)) + :background "#abd7f0" + :foreground "black" + :weight bold :height 1.3 :family "Sans Serif")) + "Face for source header in the helm buffer." + :group 'helm-faces) + +(defface helm-visible-mark + '((((min-colors 88) (background dark)) + (:background "green1" :foreground "black")) + (((background dark)) + (:background "green" :foreground "black")) + (((background light)) :background "#d1f5ea") + (((min-colors 88)) + (:background "green1")) + (t (:background "green"))) + "Face for visible mark." + :group 'helm-faces) + +(defface helm-header + '((t (:inherit header-line))) + "Face for header lines in the helm buffer." + :group 'helm-faces) + +(defface helm-candidate-number + '((((background dark)) :background "Yellow" :foreground "black") + (((background light)) :background "#faffb5" :foreground "black")) + "Face for candidate number in mode-line." + :group 'helm-faces) + +(defface helm-candidate-number-suspended + '((t (:inherit helm-candidate-number :inverse-video t))) + "Face for candidate number in mode-line when helm is suspended." + :group 'helm-faces) + +(defface helm-selection + '((((background dark)) :background "ForestGreen" + :distant-foreground "black") + (((background light)) :background "#b5ffd1" + :distant-foreground "black")) + "Face for currently selected item in the helm buffer." + :group 'helm-faces) + +(defface helm-separator + '((((background dark)) :foreground "red") + (((background light)) :foreground "#ffbfb5")) + "Face for multiline source separator." + :group 'helm-faces) + +(defface helm-action + '((t (:underline t))) + "Face for action lines in the helm action buffer." + :group 'helm-faces) + +(defface helm-prefarg + '((((background dark)) :foreground "green") + (((background light)) :foreground "red")) + "Face for showing prefix arg in mode-line." + :group 'helm-faces) + +(defface helm-match + '((((background light)) :foreground "#b00000") + (((background dark)) :foreground "gold1")) + "Face used to highlight matches." + :group 'helm-faces) + +(defface helm-header-line-left-margin + '((t (:foreground "black" :background "yellow"))) + "Face used to highlight helm-header sign in left-margin." + :group 'helm-faces) + +(defface helm-minibuffer-prompt + '((t (:inherit minibuffer-prompt))) + "Face used for the minibuffer/headline prompt (such as Pattern:) in helm." + :group 'helm-faces) + + +;;; Variables. +;; +;; +(defvar helm-selection-overlay nil + "Overlay used to highlight the currently selected item.") + +(defvar helm-async-processes nil + "List of information about asynchronous processes managed by helm.") + +(defvar helm-before-initialize-hook nil + "Runs before helm initialization. +This hook runs before init functions in `helm-sources', which is +before creation of `helm-buffer'. Set local variables for +`helm-buffer' that need a value from `current-buffer' with +`helm-set-local-variable'.") + +(defvar helm-after-initialize-hook nil + "Runs after helm initialization. +This hook runs after `helm-buffer' is created but not from +`helm-buffer'. The hook needs to specify in which buffer to run.") + +(defvaralias 'helm-update-hook 'helm-after-update-hook) +(make-obsolete-variable 'helm-update-hook 'helm-after-update-hook "1.9.9") + +(defvar helm-after-update-hook nil + "Runs after updating the helm buffer with the new input pattern.") + +(defvar helm-cleanup-hook nil + "Runs after exiting the minibuffer and before performing an +action. + +This hook runs even if helm exits the minibuffer abnormally (e.g. +via `helm-keyboard-quit').") + +(defvar helm-select-action-hook nil + "Runs when opening the action buffer.") + +(defvar helm-before-action-hook nil + "Runs before executing action. +Unlike `helm-cleanup-hook', this hook runs before helm closes the +minibuffer and also before performing an action.") + +(defvar helm-after-action-hook nil + "Runs after executing action.") + +(defvar helm-exit-minibuffer-hook nil + "Runs just before exiting the minibuffer. + +This hook runs when helm exits the minibuffer normally (e.g. via +candidate selection), but does NOT run if helm exits the +minibuffer abnormally (e.g. via `helm-keyboard-quit').") + +(defvar helm-after-persistent-action-hook nil + "Runs after executing persistent action.") + +(defvar helm-move-selection-before-hook nil + "Runs before moving selection in `helm-buffer'.") + +(defvar helm-move-selection-after-hook nil + "Runs after moving selection in `helm-buffer'.") + +(defvar helm-after-preselection-hook nil + "Runs after pre-selection in `helm-buffer'.") + +(defvar helm-window-configuration-hook nil + "Runs when switching to and from the action buffer.") + +(defvar helm-execute-action-at-once-if-one nil + "When non--nil executes the default action and then exits if only one candidate. +If symbol 'current-source is given as value exit if only one candidate +in current source. +This variable accepts a function with no args that should returns a boolean +value or 'current-source.") + +(defvar helm-quit-if-no-candidate nil + "When non-`nil', quits if there are no candidates. +This variable accepts a function.") + +(defvar helm-debug-variables nil + "A list of helm variables that `helm-debug-output' displays. +If `nil', `helm-debug-output' includes only variables with +`helm-' prefixes.") + +(defvar helm-debug-buffer "*Debug Helm Log*") + +(defvar helm-debug nil + "If non-`nil', write log message to `helm-debug-buffer'. +Default is `nil', which disables writing log messages because the +size of `helm-debug-buffer' grows quickly.") + +(defvar helm-mode-line-string "\ +\\\ +\\[helm-help]:Help \ +\\[helm-select-action]:Act \ +\\[helm-maybe-exit-minibuffer]/\ +f1/f2/f-n:NthAct \ +\\[helm-toggle-suspend-update]:Tog.suspend" + "Help string displayed by helm in the mode-line. +It is either a string or a list of two string arguments where the +first string is the name and the second string is displayed in +the mode-line. When `nil', uses default `mode-line-format'.") + +(defvar helm-minibuffer-set-up-hook nil + "Hook that runs at minibuffer initialization. +A hook useful for modifying minibuffer settings in helm. + +An example that hides the minibuffer when using +`helm-echo-input-in-header-line': + + (add-hook 'helm-minibuffer-set-up-hook #'helm-hide-minibuffer-maybe) + +Note that we check `helm-echo-input-in-header-line' value +from `helm-buffer' which allow detecting possible local +value of this var.") + +(defvar helm-help-message + "* Helm Generic Help +** Basics + +Helm narrows down the list of candidates as you type a filter pattern. + +Helm accepts multiple space-separated patterns, each pattern can be negated with \"!\". + +Helm also supports fuzzy matching in some places when specified, you will find +several variables to enable fuzzy matching in diverse sources, +see [[https://github.com/emacs-helm/helm/wiki/Fuzzy-matching][fuzzy-matching]] in helm-wiki for more infos. + +Helm generally uses familiar Emacs keys to navigate the list. +Here follow some of the less obvious bindings: + +- `\\[helm-maybe-exit-minibuffer]' selects the candidate from the list, executes the default action +upon exiting the Helm session. + +- `\\[helm-execute-persistent-action]' executes the default action but without exiting the Helm session. +Not all sources support this. + +- `\\[helm-select-action]' displays a list of actions available on current candidate or all marked candidates. +The default binding is ordinarily used for completion, but that would be +redundant since Helm completes upon every character entered in the prompt. +See [[https://github.com/emacs-helm/helm/wiki#helm-completion-vs-emacs-completion][Helm wiki]]. + +Note: In addition to the default actions list, additional actions appear +depending of the type of the selected candidate(s). They are called filtered +actions. + +** Helm mode + +`helm-mode' toggles Helm completion in native Emacs functions, +so when you turn `helm-mode' on, commands like `switch-to-buffer' will use +Helm completion instead of the usual Emacs completion buffer. + +*** What gets or does not get \"helmized\" when `helm-mode' is enabled? + +Helm provides generic completion on all Emacs functions using `completing-read', +`completion-in-region' and their derivatives, e.g. `read-file-name'. Helm +exposes a user variable to control which function to use for a specific Emacs +command: `helm-completing-read-handlers-alist'. If the function for a specific +command is nil, it turns off Helm completion. See the variable documentation +for more infos. + +*** Helm functions vs helmized Emacs functions + +While there are Helm functions that perform the same completion as other +helmized Emacs functions, e.g. `switch-to-buffer' and `helm-buffers-list', the +native Helm functions like `helm-buffers-list' can receive new features, the +allow marking candidates, they have several actions, etc. Whereas the helmized +Emacs functions only have Helm completion, one action and no more then Emacs can +provide for this function. This is the intended behavior. + +Generally you are better off using the native Helm command +than the helmized Emacs equivalent. + +** Helm help + +\\[helm-documentation]: Show all helm documentations concatenated in one org file. + +From a Helm session, just hit \\\\[helm-help] to have the +documentation for the current source followed by the global Helm documentation. + +While in the help buffer, most of the regular keybindings are available in an +Emacs buffers; the most important ones are shown in minibuffer. However due to +the implementation restrictions, no regular Emacs keymap is used (it runs in a +loop when reading the help buffer) they are hardcoded and not modifiable. + +The hard-coded documentation bindings are: + +| Key | Alternative keys | Command | +|-----------+------------------+---------------------| +| C-v | Space next | Scroll up | +| M-v | b prior | Scroll down | +| C-s | | Isearch forward | +| C-r | | Isearch backward | +| C-a | | Beginning of line | +| C-e | | End of line | +| C-f | right | Forward char | +| C-b | left | Backward char | +| C-n | down | Next line | +| C-p | up | Previous line | +| M-a | | Backward sentence | +| M-e | | Forward sentence | +| M-f | | Forward word | +| M-b | | Backward word | +| M-> | | End of buffer | +| M-< | | Beginning of buffer | +| C- | | Toggle mark | +| RET | | Follow org link | +| C-% | | Push org mark | +| C-& | | Goto org mark-ring | +| TAB | | Org cycle | +| M- | | Toggle visibility | +| M-w | | Copy region | +| q | | Quit | + +** Customize Helm + +Helm provides a lot of user variables for extensive customization. +From any Helm session, type \\\\[helm-customize-group] to jump to the current source `custom' group. +Helm also has a special group for faces you can access via `M-x customize-group RET helm-faces'. + +Note: Some sources may not have their group set and default to the `helm' group. + +** Helm's basic operations and default key bindings + +| Key | Alternative Keys | Command | +|---------+------------------+----------------------------------------------------------------------| +| C-p | Up | Previous line | +| C-n | Down | Next line | +| M-v | prior | Previous page | +| C-v | next | Next page | +| Enter | | Execute first (default) action / Select | +| M-< | | First line | +| M-> | | Last line | +| C-M-S-v | M-prior, C-M-y | Previous page (other-window) | +| C-M-v | M-next | Next page (other-window) | +| Tab | C-i | Show action list | +| Left | | Previous source | +| Right | C-o | Next source | +| C-k | | Delete pattern (with prefix arg delete from point to end or all [1]) | +| C-j | C-z | Persistent action (Execute and keep Helm session) | + +\[1] Delete from point to end or all depending on the value of +`helm-delete-minibuffer-contents-from-point'. + +** Shortcuts for n-th action + +f1-f12: Execute n-th action where n is 1 to 12. + +** Shortcuts for executing the default action on the n-th candidate + +C-x : Execute default action on the n-th candidate before currently selected candidate. + +C-c : Execute default action on the n-th candidate after current selected candidate. + +\"n\" is limited to 1-9. For larger jumps use other navigation keys. Helm does +not display line numbers by default: enable them with the +\[[https://github.com/coldnew/linum-relative][linum-relative]] package and +`helm-linum-relative-mode'. +If you are using Emacs-26+ version you can use `global-display-line-numbers-mode' +which seems even better (don't forget to customize `display-line-numbers-type' to relative). + +** Mouse control in Helm + +A basic support for the mouse is provided when the user sets `helm-allow-mouse' to non-nil. + +- mouse-1 selects the candidate. +- mouse-2 executes the default action on selected candidate. +- mouse-3 pops up the action menu. + +Note: When mouse control is enabled in Helm, it also lets you click around and lose +the minibuffer focus: you'll have to click on the Helm buffer or the minibuffer +to retrieve control of your Helm session. + +** Marked candidates + +You can mark candidates to execute an action on all of them instead of the +current selected candidate only. (See bindings below.) Most Helm actions +operate on marked candidates unless candidate-marking is explicitely forbidden +for a specific source. + +- To mark/unmark a candidate, use \\[helm-toggle-visible-mark]. (See bindings below.) +With a numeric prefix arg mark ARG candidates forward, if ARG is negative +mark ARG candidates backward. + +- To mark all visible unmarked candidates at once in current source use \\[helm-mark-all]. +With a prefix argument, mark all candidates in all sources. + +- To unmark all visible marked candidates at once use \\[helm-unmark-all]. + +- To mark/unmark all candidates at once use \\[helm-toggle-all-marks]. +With a prefix argument, mark/unmark all candidates in all sources. + +Note: When multiple candidates are selected across different sources, only the +candidates of the current source will be used when executing most actions (as +different sources can have different actions). Some actions support +multi-source marking however. + +** Follow candidates + +When `helm-follow-mode' is on (\\\\[helm-follow-mode] to toggle it), +moving up and down the Helm session or updating the list of candidates will +automatically execute the persistent-action as specified for the current source. + +If `helm-follow-mode-persistent' is non-nil, the state of the mode will be +restored for the following Helm sessions. + +If you just want to follow candidates occasionally without enabling +`helm-follow-mode', you can use \\\\[helm-follow-action-forward] or \\[helm-follow-action-backward] instead. +Conversely, when `helm-follow-mode' is enabled, those commands +go to previous/next line without executing the persistent action. + +** Frequently Used Commands + +\\[helm-toggle-resplit-and-swap-windows]\t\tToggle vertical/horizontal split on first hit and swap Helm window on second hit. +\\[helm-quit-and-find-file]\t\tDrop into `helm-find-files'. +\\[helm-kill-selection-and-quit]\t\tKill display value of candidate and quit (with prefix arg, kill the real value). +\\[helm-yank-selection]\t\tYank current selection into pattern. +\\[helm-copy-to-buffer]\t\tCopy selected candidate at point in current buffer. +\\[helm-follow-mode]\t\tToggle automatic execution of persistent action. +\\[helm-follow-action-forward]\tRun persistent action then select next line. +\\[helm-follow-action-backward]\t\tRun persistent action then select previous line. +\\[helm-refresh]\t\tRecalculate and redisplay candidates. +\\[helm-toggle-suspend-update]\t\tToggle candidate updates. + +** Special yes, no or yes for all answers + +You may be prompted in the minibuffer to answer by [y,n,!,q] in some places +for confirmation. + +- y mean yes +- no mean no +- ! mean yes for all +- q mean quit or abort current operation. + +When using ! you will not be prompted anymore for the same thing in current operation +e.g. file deletion, file copy etc... + +** Moving in `helm-buffer' + +You can move in `helm-buffer' with the usual commands used in Emacs: +\(\\\\[helm-next-line], \\\\[helm-previous-line], etc. See above basic commands. +When `helm-buffer' contains more than one source, change source with \\\\[helm-next-source]. + +Note: When reaching the end of a source, \\\\[helm-next-line] will *not* go to the next source unless +variable `helm-move-to-line-cycle-in-source' is non-nil, so you will have to use \\\\[helm-next-source]. + +** Resume previous session from current Helm session + +You can use `C-c n' (`helm-run-cycle-resume') to cycle in resumables sources. +`C-c n' is a special key set with `helm-define-key-with-subkeys' which, after pressing it, allows you +to keep cycling with further `n'. + +Tip: You can bound the same key in `global-map' to `helm-cycle-resume' + with `helm-define-key-with-subkeys' to let you transparently cycle + sessions, Helm fired up or not. + You can also bind the cycling commands to single key presses (e.g. `S-') this time + with a simple `define-key'. (Note that `S-' is not available in terminals.) + +Note: `helm-define-key-with-subkeys' is available only once Helm is loaded. + +You can also use \\\\[helm-resume-previous-session-after-quit] to resume +the previous session, or \\\\[helm-resume-list-buffers-after-quit] +to have completion on all resumable buffers. + +** Global commands + +*** Resume Helm session from outside Helm + +\\\\[helm-resume] revives the last `helm' session. Binding a key to +this command will greatly improve `helm' interactivity, e.g. when quitting Helm +accidentally. + +You can call \\\\[helm-resume] with a prefix argument to choose +\(with completion!) which session you'd like to resume. You can also cycle in +these sources with `helm-cycle-resume' (see above). + +** Debugging Helm + +Helm exposes the special variable `helm-debug': setting it to non-nil +will enable Helm logging in a special outline-mode buffer. +Helm resets the variable to nil at the end of each session. + +For convenience, \\\\[helm-enable-or-switch-to-debug] +allows you to turn on debugging for this session only. +To avoid accumulating log entries while you are typing patterns, you can use +\\\\[helm-toggle-suspend-update] to turn off updating. When you +are ready turn it on again to resume logging. + +Once you exit your Helm session you can access the debug buffer with +`helm-debug-open-last-log'. It is possible to save logs to dated files when +`helm-debug-root-directory' is set to a valid directory. + +Note: Be aware that Helm log buffers grow really fast, so use `helm-debug' only +when needed. + +** Writing your own Helm sources + +Writing simple sources for your own usage is easy. When calling the `helm' +function, the sources are added the :sources slot which can be a symbol or a +list of sources. Sources can be built with different EIEIO classes depending +what you want to do. To simplify this, several `helm-build-*' macros are +provided. Below, simple examples to start with. + +We will not go further here, see [[https://github.com/emacs-helm/helm/wiki/Developing][Helm wiki]] and the source +code for more information and more complex exapmles. + +#+begin_src elisp + + ;; Candidates are stored in a list. + (helm :sources (helm-build-sync-source \"test\" + ;; A function can be used as well + ;; to provide candidates. + :candidates '(\"foo\" \"bar\" \"baz\")) + :buffer \"*helm test*\") + + ;; Candidates are stored in a buffer. + ;; Generally faster but doesn't allow a dynamic updating + ;; of the candidates list i.e the list is fixed on start. + (helm :sources (helm-build-in-buffer-source \"test\" + :data '(\"foo\" \"bar\" \"baz\")) + :buffer \"*helm test*\") + +#+end_src + +** Helm Map +\\{helm-map}" + "Message string containing detailed help for `helm'. +It also accepts function or variable symbol.") + +(defvar helm-autoresize-mode) ;; Undefined in `helm-default-display-buffer'. + +(defvar helm-async-outer-limit-hook nil + "A hook that run in async sources when process output comes out of `candidate-number-limit'. +Should be set locally to `helm-buffer' with `helm-set-local-variable'.") + +(defvar helm-quit-hook nil + "A hook that run when quitting helm.") + +(defvar helm-resume-after-hook nil + "A hook that run after resuming a helm session. +The hook should take one arg SOURCES.") + +;;; Internal Variables +;; +;; +(defvar helm-source-filter nil + "A list of source names to be displayed. +Other sources won't appear in the search results. +If nil, no filtering is done. +Don't set this directly, use `helm-set-source-filter' during helm session +to modify it.") +(defvar helm-current-prefix-arg nil + "Record `current-prefix-arg' when exiting minibuffer.") +(defvar helm-saved-action nil + "Saved value of the currently selected action by key.") +(defvar helm-saved-current-source nil + "Value of the current source when the action list is shown.") +(defvar helm-in-persistent-action nil + "Flag whether in persistent-action or not.") +(defvar helm-last-buffer nil + "`helm-buffer' of previously `helm' session.") +(defvar helm-saved-selection nil + "Value of the currently selected object when the action list is shown.") +(defvar helm-sources nil + "[INTERNAL] Value of current sources in use, a list.") +(defvar helm-buffer-file-name nil + "Variable `buffer-file-name' when `helm' is invoked.") +(defvar helm-candidate-cache (make-hash-table :test 'equal) + "Holds the available candidate within a single helm invocation.") +(defvar helm--candidate-buffer-alist nil) +(defvar helm-input "" + "The input typed in the candidates panel.") +(defvar helm-input-local nil + "Internal, store locally `helm-pattern' value for later use in `helm-resume'.") +(defvar helm--source-name nil) +(defvar helm-current-source nil) +(defvar helm-tick-hash (make-hash-table :test 'equal)) +(defvar helm-issued-errors nil) +(defvar helm--last-log-file nil + "The name of the log file of the last helm session.") +(defvar helm--local-variables nil) +(defvar helm-split-window-state nil) +(defvar helm--window-side-state nil) +(defvar helm-selection-point nil) +(defvar helm-alive-p nil) +(defvar helm-visible-mark-overlays nil) +(defvar helm-update-blacklist-regexps '("^" "^ *" "$" "!" " " "\\b" + "\\<" "\\>" "\\_<" "\\_>" ".*" + "??" "?*" "*?" "?")) +(defvar helm--force-updating-p nil + "[INTERNAL] Don't use this in your programs.") +(defvar helm-exit-status 0 + "Flag to inform if helm did exit or quit. +0 means helm did exit when executing an action. +1 means helm did quit with \\[keyboard-quit] +Knowing this exit-status could help restore a window config when helm aborts +in some special circumstances. +See `helm-exit-minibuffer' and `helm-keyboard-quit'.") +(defvar helm-minibuffer-confirm-state nil) +(defvar helm-quit nil) +(defvar helm-buffers nil + "Helm buffers listed in order of most recently used.") +(defvar helm-current-position nil + "Cons of \(point . window-start\) when `helm' is invoked. +`helm-current-buffer' uses this to restore position after +`helm-keyboard-quit'") +(defvar helm-last-frame-or-window-configuration nil + "Used to store window or frame configuration at helm start.") +(defvar helm-onewindow-p nil) +(defvar helm-types nil) +(defvar helm--mode-line-string-real nil) ; The string to display in mode-line. +(defvar helm-persistent-action-display-window nil) +(defvar helm-marked-candidates nil + "Marked candidates. List of \(source . real\) pair.") +(defvar helm--mode-line-display-prefarg nil) +(defvar helm--temp-follow-flag nil + "[INTERNAL] A simple flag to notify persistent action we are following.") +(defvar helm--reading-passwd-or-string nil) +(defvar helm--in-update nil) +(defvar helm--in-fuzzy nil) +(defvar helm--maybe-use-default-as-input nil + "Flag to notify the use of use-default-as-input. +Use only in let-bindings. +Use :default arg of `helm' as input to update display. +Note that if also :input is specified as `helm' arg, it will take +precedence on :default.") +(defvar helm--temp-hooks nil + "Store temporary hooks added by `with-helm-temp-hook'.") +(defvar helm-truncate-lines nil + "[Internal] Don't set this globally, it is used as a local var.") +(defvar helm--prompt nil) +(defvar helm--file-completion-sources + '("Find Files" "Read File Name") + "Sources that use the *find-files mechanism can be added here. +Sources generated by `helm-mode' don't need to be added here +because they are automatically added. + +You should not modify this yourself unless you know what you are doing.") +(defvar helm--completing-file-name nil + "Non nil when `helm-read-file-name' is running. +Used for `helm-file-completion-source-p'.") +;; Same as `ffap-url-regexp' but keep it here to ensure `ffap-url-regexp' is not nil. +(defvar helm--url-regexp "\\`\\(news\\(post\\)?:\\|mailto:\\|file:\\|\\(ftp\\|https?\\|telnet\\|gopher\\|www\\|wais\\)://\\)") +(defvar helm--ignore-errors nil + "Flag to prevent helm popping up errors in candidates functions. +Should be set in candidates functions if needed, will be restored +at end of session.") +(defvar helm--action-prompt "Select action: ") +(defvar helm--cycle-resume-iterator nil) +(defvar helm--buffer-in-new-frame-p nil) +(defvar helm-initial-frame nil + "[INTERNAL] The selected frame before starting helm. +Helm use this internally to know in which frame it started, don't +modify this yourself.") +(defvar helm-popup-frame nil + "The frame where helm is displayed. + +This is only used when helm is using +`helm-display-buffer-in-own-frame' as `helm-display-function' and +`helm-display-buffer-reuse-frame' is non nil.") +(defvar helm--nested nil) +(defconst helm--frame-default-attributes + '(width height tool-bar-lines left top + title undecorated vertical-scroll-bars + visibility fullscreen menu-bar-lines undecorated) + "Frame parameters to save in `helm--last-frame-parameters'.") +(defvar helm--last-frame-parameters nil + "Frame parameters to save for later resuming. +Local to `helm-buffer'.") +(defvar helm--executing-helm-action nil + "Non nil when action is triggering a new helm-session. +This may be let bounded in other places to notify the display function +to reuse the same frame parameters as the previous helm session just +like resume would do.") +(defvar helm--current-buffer-narrowed nil) +(defvar helm--suspend-update-interactive-flag nil) + +;; Utility: logging +(defun helm-log (format-string &rest args) + "Log message `helm-debug' is non-`nil'. +Messages are written to the `helm-debug-buffer' buffer. + +Argument FORMAT-STRING is a string to use with `format'. +Use optional arguments ARGS like in `format'." + (when helm-debug + (with-current-buffer (get-buffer-create helm-debug-buffer) + (outline-mode) + (buffer-disable-undo) + (let ((inhibit-read-only t)) + (goto-char (point-max)) + (insert (let ((tm (current-time))) + (format (concat (if (string-match "Start session" format-string) + "* " "** ") + "%s.%06d (%s)\n %s\n") + (format-time-string "%H:%M:%S" tm) + (nth 2 tm) + (helm-log-get-current-function) + (apply #'format (cons format-string args))))))))) + +(defun helm-log-run-hook (hook) + "Run HOOK like `run-hooks' but write these actions to helm log buffer." + (helm-log "Executing %s with value = %S" hook (symbol-value hook)) + (helm-log "Executing %s with global value = %S" hook (default-value hook)) + (run-hooks hook) + (helm-log "executed %s" hook)) + +(defun helm-log-get-current-function () + "Get name of function that is calling `helm-log'. +The original idea is from `tramp-debug-message'." + (cl-loop with exclude-func-re = "^helm-\\(?:interpret\\|log\\|.*funcall\\)" + for btn from 1 to 40 + for btf = (cl-second (backtrace-frame btn)) + for fn = (if (symbolp btf) (symbol-name btf) "") + if (and (string-match "^helm" fn) + (not (string-match exclude-func-re fn))) + return fn)) + +(defun helm-log-error (&rest args) + "Accumulate error messages into `helm-issued-errors'. +ARGS are args given to `format'. +e.g (helm-log-error \"Error %s: %s\" (car err) (cdr err))." + (apply 'helm-log (concat "ERROR: " (car args)) (cdr args)) + (let ((msg (apply 'format args))) + (unless (member msg helm-issued-errors) + (cl-pushnew msg helm-issued-errors :test 'equal)))) + +(defun helm-log-save-maybe () + "Save log buffer when `helm-debug-root-directory' is non nil. +Create `helm-debug-root-directory' directory if necessary. +Messages are logged to a file named with todays date and time in this directory." + (when (and (stringp helm-debug-root-directory) + (not (file-directory-p helm-debug-root-directory))) + (make-directory helm-debug-root-directory t)) + (when helm-debug + (let ((logdir (expand-file-name (concat "helm-debug-" + (format-time-string "%Y%m%d")) + helm-debug-root-directory))) + (make-directory logdir t) + (with-current-buffer (get-buffer-create helm-debug-buffer) + (write-region (point-min) (point-max) + (setq helm--last-log-file + (expand-file-name + (format-time-string "%Y%m%d-%H%M%S") + logdir)) + nil 'silent) + (kill-buffer)))) + (setq helm-debug nil)) + +;;;###autoload +(defun helm-debug-open-last-log () + "Open helm log file or buffer of last helm session." + (interactive) + (if helm--last-log-file + (progn + (find-file helm--last-log-file) + (outline-mode) (view-mode 1) (visual-line-mode 1)) + (switch-to-buffer helm-debug-buffer) + (view-mode 1) (visual-line-mode 1))) + +(defun helm-print-error-messages () + "Print error messages in `helm-issued-errors'." + (and helm-issued-errors + (message "Helm issued errors: %s" + (mapconcat 'identity (reverse helm-issued-errors) "\n")))) + + +;; Test tools +(defmacro with-helm-time-after-update (&rest body) + (helm-with-gensyms (start-time time-elapsed) + `(let ((,start-time (float-time)) ,time-elapsed) + (add-hook 'helm-after-update-hook + (lambda () + (setq ,time-elapsed (- (float-time) ,start-time)) + (keyboard-quit))) + (unwind-protect ,@body + (remove-hook 'helm-after-update-hook + (lambda () + (setq ,time-elapsed (- (float-time) ,start-time)) + (keyboard-quit)))) + ,time-elapsed))) + + +;; Helm API +(defmacro with-helm-default-directory (directory &rest body) + (declare (indent 2) (debug t)) + `(let ((default-directory (or (and ,directory + (file-name-as-directory ,directory)) + default-directory))) + ,@body)) + +(defun helm-default-directory () + "Return the local value of `default-directory' in `helm-buffer'." + (buffer-local-value 'default-directory (get-buffer helm-buffer))) + +(defmacro with-helm-temp-hook (hook &rest body) + "Execute temporarily BODY as a function for HOOK." + (declare (indent 1) (debug t)) + (helm-with-gensyms (helm--hook) + `(progn + (defun ,helm--hook () + (unwind-protect + (progn ,@body) + (remove-hook ,hook (quote ,helm--hook)) + (fmakunbound (quote ,helm--hook)))) + (push (cons ',helm--hook ,hook) helm--temp-hooks) + (add-hook ,hook (quote ,helm--hook))))) + +(defmacro with-helm-after-update-hook (&rest body) + "Execute BODY at end of `helm-update'." + (declare (indent 0) (debug t)) + `(with-helm-temp-hook 'helm-after-update-hook ,@body)) + +(defmacro with-helm-alive-p (&rest body) + "Return error when BODY run outside helm context." + (declare (indent 0) (debug t)) + `(progn + (if helm-alive-p + (progn ,@body) + (error "Running helm command outside of context")))) + +(defmacro with-helm-in-frame (&rest body) + "Execute helm function in BODY displaying `helm-buffer' in separate frame." + (declare (debug t) (indent 0)) + `(progn + (helm-set-local-variable + 'helm-display-function 'helm-display-buffer-in-own-frame) + ,@body)) + +;;; helm-attributes +;; +(defun helm-attr (attribute-name &optional source compute) + "Get the value of ATTRIBUTE-NAME of SRC. + +If SRC is omitted, use current source. + +If COMPUTE is non-`nil' compute value of ATTRIBUTE-NAME with +`helm-interpret-value'. COMPUTE can have also 'ignorefn as value, in +this case `helm-interpret-value' will return a function as value +unchanged, but will eval a symbol which is bound. + +You can use `setf' to modify value of ATTRIBUTE-NAME unless COMPUTE is +specified, if attribute ATTRIBUTE-NAME is not found in SOURCE `setf' +will create new attribute ATTRIBUTE-NAME with specified value. +You can also use `helm-attrset' to modify ATTRIBUTE-NAME." + (declare (gv-setter + (lambda (val) + `(let* ((src (or ,source (helm-get-current-source))) + (attr (assq ,attribute-name src))) + (cl-assert (null ,compute) nil + "`setf' can't set the computed value of attribute `%s'" + ,attribute-name) + (if attr + (setcdr attr ,val) + (and (setcdr src (cons (cons ,attribute-name ,val) + (cdr src))) + ,val)))))) + (let ((src (or source (helm-get-current-source)))) + (helm-aif (assq attribute-name src) + (if compute + (helm-interpret-value (cdr it) src compute) + (cdr it))))) + +(cl-defun helm-attrset (attribute-name value + &optional + (src (helm-get-current-source))) + "Set the value of ATTRIBUTE-NAME of source SRC to VALUE. + +If ATTRIBUTE-NAME doesn't exists in source it is created with value VALUE.. +If SRC is omitted, use current source. +If operation succeed, return value, otherwise nil. + +Note that `setf' on `helm-attr' can be used instead of this function." + (setf (helm-attr attribute-name src) value)) + +(defun helm-add-action-to-source (name fn source &optional index) + "Add new action NAME linked to function FN to SOURCE. +Function FN should be a valid function that takes one arg i.e candidate, +argument NAME is a string that will appear in action menu +and SOURCE should be an existing helm source already loaded. +If INDEX is specified, action is added to the action list at INDEX, +otherwise added at end. +This allows users to add specific actions to an existing source +without modifying source code." + (let ((actions (helm-attr 'action source 'ignorefn)) + (new-action (list (cons name fn)))) + (when (functionp actions) + (setq actions (list (cons "Default action" actions)))) + (helm-attrset 'action + (if index + (helm-append-at-nth actions new-action index) + (append actions new-action)) + source))) + +(defun helm-delete-action-from-source (action-or-name source) + "Delete ACTION-OR-NAME from SOURCE. +ACTION-OR-NAME can either be the name of action or the symbol function +associated to name." + (let* ((actions (helm-attr 'action source 'ignorefn)) + (del-action (if (symbolp action-or-name) + (rassoc action-or-name actions) + (assoc action-or-name actions)))) + (helm-attrset 'action (delete del-action actions) source))) + +(cl-defun helm-add-action-to-source-if (name fn source predicate + &optional (index 4) test-only) + "Add new action NAME linked to function FN to SOURCE. +Action NAME will be available when the current candidate matches PREDICATE. +This function adds an entry in the `action-transformer' attribute +of SOURCE (or creates one if not found). +Function PREDICATE must take one candidate as arg. +Function FN should be a valid function that takes one arg i.e. candidate, +argument NAME is a string that will appear in action menu +and SOURCE should be an existing helm source already loaded. +If INDEX is specified, action is added in action list at INDEX. +Value of INDEX should be always >=1, default to 4. +This allow user to add a specific `action-transformer' +to an existing source without modifying source code. +E.g +Add the action \"Byte compile file async\" linked to +function 'async-byte-compile-file to source `helm-source-find-files' +only when predicate helm-ff-candidates-lisp-p return non-`nil': + +\(helm-add-action-to-source-if \"Byte compile file async\" + 'async-byte-compile-file + helm-source-find-files + 'helm-ff-candidates-lisp-p\)." + (let* ((actions (helm-attr 'action source 'ignorefn)) + (action-transformers (helm-attr 'action-transformer source)) + (new-action (list (cons name fn))) + (transformer (lambda (actions candidate) + (cond ((funcall predicate candidate) + (helm-append-at-nth + actions new-action index)) + (t actions))))) + (when (functionp actions) + (helm-attrset 'action (list (cons "Default action" actions)) source)) + (when (or (symbolp action-transformers) (functionp action-transformers)) + (setq action-transformers (list action-transformers))) + (if test-only ; debug + (delq nil (append (list transformer) action-transformers)) + (helm-attrset 'action-transformer + (helm-fast-remove-dups + (delq nil (append (list transformer) action-transformers)) + :test 'equal) + source)))) + + +;;; Source filter +;; +(defun helm-set-source-filter (sources) + "Set the value of `helm-source-filter' to SOURCES and update. + +This function sets a filter for helm sources and it may be +called while helm is running. It can be used to toggle +displaying of sources dynamically. For example, additional keys +can be bound into `helm-map' to display only the file-related +results if there are too many matches from other sources and +you're after files only: + +Shift+F shows only file results from some sources: + +\(define-key helm-map \"F\" 'helm-my-show-files-only) + +\(defun helm-my-show-files-only () + (interactive) + (helm-set-source-filter '(\"File Name History\" + \"Files from Current Directory\"))) + +Shift+A shows all results: + +\(define-key helm-map \"A\" 'helm-my-show-all) + +\(defun helm-my-show-all () + (interactive) + (helm-set-source-filter nil)) + +The -my- part is added to avoid collisions with +existing Helm function names." + (with-helm-buffer + (let ((cur-disp-sel (helm-get-selection nil t))) + (set (make-local-variable 'helm-source-filter) + (helm--normalize-filter-sources sources)) + (helm-log "helm-source-filter = %S" helm-source-filter) + ;; Use force-update to run init/update functions. + (helm-force-update (and (stringp cur-disp-sel) + (regexp-quote cur-disp-sel)))))) + +(defun helm--normalize-filter-sources (sources) + (cl-loop for s in sources collect + (cl-typecase s + (symbol (assoc-default 'name (symbol-value s))) + (list (assoc-default 'name s)) + (string s)))) + +(defun helm-set-sources (sources &optional no-init no-update) + "Set SOURCES during `helm' invocation. +If NO-INIT is non-`nil', skip executing init functions of SOURCES. +If NO-UPDATE is non-`nil', skip executing `helm-update'." + (with-current-buffer helm-buffer + (setq helm-sources (helm-get-sources sources)) + (helm-log "helm-sources = %S" helm-sources)) + (unless no-init (helm-compute-attr-in-sources 'init)) + (unless no-update (helm-update))) + +(defun helm-get-selection (&optional buffer force-display-part source) + "Return the currently selected item or nil. + +if BUFFER is nil or unspecified, use helm-buffer as default value. +If FORCE-DISPLAY-PART is non-`nil', return the display string. +If FORCE-DISPLAY-PART value is `withprop' the display string is returned +with its properties." + (setq buffer (or buffer helm-buffer)) + (unless (or (helm-empty-buffer-p buffer) + (helm-pos-header-line-p)) + (with-current-buffer buffer + (let* ((disp-fn (if (eq force-display-part 'withprop) + 'buffer-substring + 'buffer-substring-no-properties)) + (selection + (or (and (not force-display-part) + (get-text-property (overlay-start + helm-selection-overlay) + 'helm-realvalue)) + ;; It is needed to return properties of DISP in some case, + ;; e.g for `helm-confirm-and-exit-minibuffer', + ;; so use `buffer-substring' here when 'withprop is specified. + (let* ((beg (overlay-start helm-selection-overlay)) + (end (overlay-end helm-selection-overlay)) + ;; If there is no selection at point, the + ;; overlay is at its initial pos, (point-min) + ;; (point-min), that's mean the helm-buffer + ;; is not empty but have no selection yet, + ;; this happen with grep sentinel sending an + ;; error message in helm-buffer when no matches. + (disp (unless (= beg end) (funcall disp-fn beg (1- end)))) + (src (or source (helm-get-current-source)))) + (helm-aif (and src disp + (not force-display-part) + (assoc-default 'display-to-real src)) + (helm-apply-functions-from-source source it disp) + disp))))) + (unless (equal selection "") + (helm-log "selection = %S" selection) + selection))))) + +(defun helm-get-actions-from-current-source (&optional source) + "Return the associated action for the selected candidate. +It is a function symbol (sole action) or list +of (action-display . function)." + (unless (helm-empty-buffer-p (helm-buffer-get)) + (let ((src (helm-get-current-source))) + (helm-aif (helm-attr 'action-transformer) + (helm-apply-functions-from-source + (or source src) it + (helm-attr 'action nil 'ignorefn) + ;; Check if the first given transformer + ;; returns the same set of actions for each + ;; candidate in marked candidates. + ;; If so use the car of marked to determine + ;; the set of actions, otherwise use the selection. + (if (cl-loop with marked = (helm-marked-candidates) + with act = (car (helm-mklist it)) + with acts = (funcall act nil (car marked)) + for c in marked + always (equal (funcall act nil c) acts)) + (car (helm-marked-candidates)) + (helm-get-selection nil nil src))) + (helm-attr 'action nil 'ignorefn))))) + +(defun helm-get-current-source () + "Return the source for the current selection. +Return nil when `helm-buffer' is empty." + (or helm-current-source + (with-helm-buffer + (or (get-text-property (point) 'helm-cur-source) + (progn + ;; This is needed to not loose selection. + (goto-char (overlay-start helm-selection-overlay)) + (let ((header-pos (or (helm-get-previous-header-pos) + (helm-get-next-header-pos)))) + ;; Return nil when no--candidates. + (when header-pos + (cl-loop with source-name = (save-excursion + (goto-char header-pos) + (helm-current-line-contents)) + for source in helm-sources thereis + (and (equal (assoc-default 'name source) source-name) + source))))))))) + +(defun helm-buffer-is-modified (buffer) + "Return non-`nil' when BUFFER is modified since `helm' was invoked." + (let* ((buf (get-buffer buffer)) + (key (concat (buffer-name buf) "/" (helm-attr 'name))) + (source-tick (or (gethash key helm-tick-hash) 0)) + (buffer-tick (buffer-chars-modified-tick buf)) + (modifiedp (/= source-tick buffer-tick))) + (puthash key buffer-tick helm-tick-hash) + (helm-log "buffer = %S" buffer) + (helm-log "modifiedp = %S" modifiedp) + modifiedp)) + +(defun helm-current-buffer-is-modified () + "Check if `helm-current-buffer' is modified since `helm' was invoked." + (helm-buffer-is-modified helm-current-buffer)) + +(defun helm-run-after-exit (function &rest args) + "Execute FUNCTION with ARGS after exiting `helm'. +The action is to call FUNCTION with arguments ARGS. +Unlike `helm-exit-and-execute-action', this can be used +to call non--actions functions with any ARGS or no ARGS at all. + +Use this on commands invoked from key-bindings, but not +on action functions invoked as action from the action menu, +i.e. functions called with RET." + (helm-kill-async-processes) + (helm-log "function = %S" function) + (helm-log "args = %S" args) + (helm-exit-and-execute-action + (lambda (_candidate) + (apply function args)))) + +(defun helm-exit-and-execute-action (action) + "Exit current helm session and execute ACTION. +Argument ACTION is a function called with one arg (candidate) +and part of the actions of current source. + +Use this on commands invoked from key-bindings, but not +on action functions invoked as action from the action menu, +i.e functions called with RET." + ;; If ACTION is not an action available in source 'action attribute, + ;; return an error. This allow to remove unneeded actions from + ;; source that inherit actions from type, note that ACTION have to + ;; be bound to a symbol and not to be an anonymous action + ;; i.e. lambda or byte-code. + (let ((actions (helm-attr 'action nil t))) + (when actions + (cl-assert (or (eq action actions) + (rassq action actions) + ;; Compiled lambda + (byte-code-function-p action) + ;; Lambdas + (and (listp action) (functionp action))) + nil "No such action `%s' for this source" action))) + (setq helm-saved-action action) + (setq helm-saved-selection (or (helm-get-selection) "")) + (setq helm--executing-helm-action t) + ;; When toggling minibuffer and header-line, we want next action + ;; inherit this setting. + (helm-set-local-variable 'helm-echo-input-in-header-line + (with-helm-buffer helm-echo-input-in-header-line)) + ;; Ensure next action use same display function as initial helm-buffer when + ;; helm-actions-inherit-frame-settings is non nil. + (when (and helm-actions-inherit-frame-settings + helm--buffer-in-new-frame-p) + (helm-set-local-variable 'helm-display-function + (with-helm-buffer helm-display-function) + 'helm--last-frame-parameters + (with-helm-buffer + (helm--get-frame-parameters))) + ;; The helm-buffer keeps `helm-display-function' and + ;; `helm--get-frame-parameters' values during 0.5 seconds, just + ;; the time to execute the possible helm action with those values. + ;; If no helm based action run within 0.5 seconds, the next helm + ;; session will have to resolve again those variable values. + (run-with-idle-timer 0.5 nil + (lambda () (helm-set-local-variable 'helm-display-function nil + 'helm--last-frame-parameters nil)))) + (helm-exit-minibuffer)) + +(defun helm--get-frame-parameters (&optional frame) + (cl-loop with params = (frame-parameters frame) + for p in helm--frame-default-attributes + when (assq p params) collect it)) + +(defalias 'helm-run-after-quit 'helm-run-after-exit) +(make-obsolete 'helm-run-after-quit 'helm-run-after-exit "1.7.7") +(defalias 'helm-quit-and-execute-action 'helm-exit-and-execute-action) +(make-obsolete 'helm-quit-and-execute-action 'helm-exit-and-execute-action "1.7.7") + +(defun helm-interpret-value (value &optional source compute) + "Interpret VALUE as variable, function or literal and return it. +If VALUE is a function, call it with no arguments and return the value +unless COMPUTE value is 'ignorefn. +If SOURCE compute VALUE for this source. +If VALUE is a variable, return the value. +If VALUE is a symbol, but it is not a function or a variable, cause an error. +Otherwise, return VALUE itself." + (cond ((and source (functionp value) (not (eq compute 'ignorefn))) + (helm-apply-functions-from-source source value)) + ((and (functionp value) (not (eq compute 'ignorefn))) + (funcall value)) + ((and (symbolp value) (boundp value)) + (symbol-value value)) + ((and (symbolp value) (not (functionp value))) + (error + "helm-interpret-value: Symbol must be a function or a variable")) + (t + value))) + +(defun helm-set-local-variable (&rest args) + "Bind each pair in ARGS locally to `helm-buffer'. + +Use this to set local vars before calling helm. + +When used from an init or update function +(i.e when `helm-force-update' is running) the variables are set +using `make-local-variable' within the `helm-buffer'. + +Usage: helm-set-local-variable ([VAR VALUE]...) +Just like `setq' except that the vars are not set sequentially. +IOW Don't use VALUE of previous VAR to set the VALUE of next VAR. + +\(fn VAR VALUE ...)" + (if helm--force-updating-p + (with-helm-buffer + (cl-loop for i on args by #'cddr + do (set (make-local-variable (car i)) (cadr i)))) + (setq helm--local-variables + (append (cl-loop for i on args by #'cddr + collect (cons (car i) (cadr i))) + helm--local-variables)))) + +(defun helm--set-local-variables-internal () + (cl-loop for (var . val) in helm--local-variables + ;; If `helm-set-local-variable' is called twice or more + ;; on same variable use the last value entered which is + ;; the first on stack e.g. + ;; (helm-set-local-variable 'helm-foo 1) + ;; (helm-set-local-variable 'helm-foo 2) + ;; helm--local-variables => + ;; '((helm-foo . 2) (helm-foo. 1)) + ;; (helm-foo . 2) is retained and (helm-foo . 1) + ;; ignored. + unless (memq var computed) + do (set (make-local-variable var) val) + collect var into computed + finally (setq helm--local-variables nil))) + + +;; API helper +(cl-defun helm-empty-buffer-p (&optional (buffer helm-buffer)) + "Check if BUFFER have candidates. +Default value for BUFFER is `helm-buffer'." + (zerop (buffer-size (and buffer (get-buffer buffer))))) + +(defun helm-empty-source-p () + "Check if current source contains candidates. +This could happen when for example the last element of a source +was deleted and the candidates list not updated." + (when (helm-window) + (with-helm-window + (or (helm-empty-buffer-p) + (and (helm-end-of-source-p) + (eq (point-at-bol) (point-at-eol)) + (or + (save-excursion + (forward-line -1) + (helm-pos-header-line-p)) + (bobp))))))) + + +;; Tools +;; +(defun helm-apply-functions-from-source (source functions &rest args) + "From SOURCE apply FUNCTIONS on ARGS. + +This function is used to process filter functions, when filter is a +\`filtered-candidate-transformer', we pass to ARGS candidates+source +whereas when the filter is `candidate-transformer' we pass to ARGS +candidates only. +This function is used also to process functions called with no args, +e.g. init functions, in this case it is called without ARGS. +See `helm-process-filtered-candidate-transformer' +\`helm-compute-attr-in-sources' and +\`helm-process-candidate-transformer'. + +Arg FUNCTIONS is either a symbol or a list of functions, each function being +applied on ARGS and called on the result of the precedent function. +Return the result of last function call." + (let ((helm--source-name (assoc-default 'name source)) + (helm-current-source source) + (funs (if (functionp functions) (list functions) functions))) + (helm-log "helm--source-name = %S" helm--source-name) + (helm-log "functions = %S" functions) + (helm-log "args = %S" args) + (cl-loop with result + for fn in funs + do (setq result (apply fn args)) + when (and args (cdr funs)) + ;; In filter functions, ARGS is a list of one or two elements where + ;; the first element is the list of candidates and the second + ;; a list containing the source. + ;; When more than one fn, set the candidates list to what returns + ;; this fn to compute the modified candidates with the next fn + ;; and so on. + do (setcar args result) + finally return result))) + +(defalias 'helm-funcall-with-source 'helm-apply-functions-from-source) +(make-obsolete 'helm-funcall-with-source 'helm-apply-functions-from-source "2.9.7") + +(defun helm-compute-attr-in-sources (attr &optional sources) + "Call the associated function(s) to ATTR for each source if any." + (let ((sources (or (helm-get-sources sources) + ;; Fix error no buffer named *helm... by checking + ;; if helm-buffer exists. + (and (buffer-live-p (get-buffer (helm-buffer-get))) + ;; `helm-sources' are local to helm-buffer. + (with-helm-buffer helm-sources))))) + (when sources + (cl-dolist (source sources) + (helm-aif (assoc-default attr source) + (helm-apply-functions-from-source source it)))))) + +(defalias 'helm-funcall-foreach 'helm-compute-attr-in-sources) +(make-obsolete 'helm-funcall-foreach 'helm-compute-attr-in-sources "2.9.7") + +(defun helm-normalize-sources (sources) + "If SOURCES is only one source, make a list of one element." + (if (or (and sources (symbolp sources)) + (and (listp sources) (assq 'name sources))) + (list sources) + sources)) + +(defun helm-get-candidate-number (&optional in-current-source) + "Return candidates number in `helm-buffer'. +If IN-CURRENT-SOURCE is provided return number of candidates of current source +only." + (with-helm-buffer + (if (or (helm-empty-buffer-p) + (helm-empty-source-p)) + 0 + (save-excursion + (helm-aif (and in-current-source (helm-get-previous-header-pos)) + (goto-char it) + (goto-char (point-min))) + (forward-line 1) + (if (helm-pos-multiline-p) + (cl-loop with count-multi = 1 + while (and (not (if in-current-source + (save-excursion + (forward-line 2) + (or (helm-pos-header-line-p) (eobp))) + (eobp))) + (search-forward helm-candidate-separator nil t)) + do (cl-incf count-multi) + finally return count-multi) + (cl-loop with ln = 0 + while (not (if in-current-source + (or (helm-pos-header-line-p) (eobp)) + (eobp))) + ;; Don't count empty lines maybe added by popup (#1370). + unless (or (eq (point-at-bol) (point-at-eol)) + (helm-pos-header-line-p)) + do (cl-incf ln) + do (forward-line 1) finally return ln)))))) + +(defmacro with-helm-quittable (&rest body) + "If an error occurs in execution of BODY, safely quit helm." + (declare (indent 0) (debug t)) + `(condition-case _v + (let (inhibit-quit) + ,@body) + (quit (setq quit-flag t) + (setq helm-quit t) + (exit-minibuffer) + (keyboard-quit) + ;; See comment about this in `with-local-quit'. + (eval '(ignore nil))))) + +;; Entry point +;; `:allow-nest' is not in this list because it is treated before. +(defconst helm-argument-keys + '(:sources :input :prompt :resume + :preselect :buffer :keymap :default :history)) + +;;;###autoload +(defun helm (&rest plist) + "Main function to execute helm sources. + +PLIST is a list like + +\(:key1 val1 :key2 val2 ...\) + + or + +\(&optional sources input prompt resume preselect + buffer keymap default history allow-nest\). + +** Keywords + +Keywords supported: + +- :sources +- :input +- :prompt +- :resume +- :preselect +- :buffer +- :keymap +- :default +- :history +- :allow-nest + +Extra LOCAL-VARS keywords are supported, see the \"** Other +keywords\" section below. + +Basic keywords are the following: + +*** :sources + +One of the following: + +- List of sources +- Symbol whose value is a list of sources +- Alist representing a Helm source. + - In this case the source has no name and is referenced in + `helm-sources' as a whole alist. + +*** :input + +Initial input of minibuffer (temporary value of `helm-pattern') + +*** :prompt + +Minibuffer prompt. Default value is `helm--prompt'. + +*** :resume + +If t, allow resumption of the previous session of this Helm +command, skipping initialization. + +If 'noresume, this instance of `helm' cannot be resumed. + +*** :preselect + +Initially selected candidate (string or regexp). + +*** :buffer + +Buffer name for this Helm session. `helm-buffer' will take this value. + +*** :keymap + +\[Obsolete] + +Keymap used at the start of this Helm session. + +It is overridden by keymaps specified in sources, and is kept +only for backward compatibility. + +Keymaps should be specified in sources using the :keymap slot +instead. See `helm-source'. + +This keymap is not restored by `helm-resume'. + +*** :default + +Default value inserted into the minibuffer \ with +\\\\[next-history-element]. + +It can be a string or a list of strings, in this case +\\\\[next-history-element] cycles through +the list items, starting with the first. + +If nil, `thing-at-point' is used. + +If `helm--maybe-use-default-as-input' is non-`nil', display is +updated using this value, unless :input is specified, in which +case that value is used instead. + +*** :history + +Minibuffer input, by default, is pushed to `minibuffer-history'. + +When an argument HISTORY is provided, input is pushed to +HISTORY. HISTORY should be a valid symbol. + +*** :allow-nest + +Allow running this Helm command in a running Helm session. + +** Other keywords + +Other keywords are interpreted as local variables of this Helm +session. The `helm-' prefix can be omitted. For example, + +\(helm :sources 'helm-source-buffers-list + :buffer \"*helm buffers*\" + :candidate-number-limit 10\) + +starts a Helm session with the variable +`helm-candidate-number-limit' set to 10. + +** Backward compatibility + +For backward compatibility, positional parameters are +supported: + +\(helm sources input prompt resume preselect + buffer keymap default history allow-nest\) + +However, the use of non-keyword args is deprecated. + +\(fn &key SOURCES INPUT PROMPT RESUME PRESELECT BUFFER KEYMAP DEFAULT HISTORY ALLOW-NEST OTHER-LOCAL-VARS)" + (let ((fn (cond ((or (and helm-alive-p (plist-get plist :allow-nest)) + (and helm-alive-p (memq 'allow-nest plist))) + #'helm--nest) + ((keywordp (car plist)) + #'helm) + (t #'helm-internal)))) + (if (and helm-alive-p (eq fn #'helm)) + (if (helm--alive-p) + ;; A helm session is normally running. + (error "Error: Trying to run helm within a running helm session") + ;; A helm session is already running and user jump somewhere else + ;; without deactivating it. + (with-helm-buffer + (prog1 + (message "Aborting an helm session running in background") + ;; `helm-alive-p' will be reset in unwind-protect forms. + (helm-keyboard-quit)))) + (if (keywordp (car plist)) + ;; Parse `plist' and move not regular `helm-argument-keys' + ;; to `helm--local-variables', then calling helm on itself + ;; with normal arguments (the non--arguments-keys removed) + ;; will end up in [1]. + (progn + (setq helm--local-variables + (append helm--local-variables + ;; Vars passed by keyword on helm call + ;; take precedence on same vars + ;; that may have been passed before helm call. + (helm-parse-keys plist))) + (apply fn (mapcar (lambda (key) (plist-get plist key)) + helm-argument-keys))) + (apply fn plist))))) ; [1] fn == helm-internal. + +(defun helm--alive-p () + "[Internal] Check if `helm' is alive. +An `helm' session is considered alive if `helm-alive-p' value is +non-`nil', the `helm-buffer' is visible, and cursor is in the +minibuffer." + (and helm-alive-p + (get-buffer-window (helm-buffer-get) 'visible) + (minibuffer-window-active-p (minibuffer-window)) + (minibufferp (current-buffer)))) + +(defun helm-parse-keys (keys) + "Parse the KEYS arguments of `helm'. +Return only those keys not in `helm-argument-keys', prefix them +with \"helm\", and then convert them to an alist. This allows +adding arguments that are not part of `helm-argument-keys', but +are valid helm variables nevertheless. For +example, :candidate-number-limit is bound to +`helm-candidate-number-limit' in the source. + + (helm-parse-keys '(:sources ((name . \"test\") + (candidates . (a b c))) + :buffer \"toto\" + :candidate-number-limit 4)) + ==> ((helm-candidate-number-limit . 4))." + + (cl-loop for (key value) on keys by #'cddr + for symname = (substring (symbol-name key) 1) + for sym = (intern (if (string-match "^helm-" symname) + symname + (concat "helm-" symname))) + unless (memq key helm-argument-keys) + collect (cons sym value))) + +;;; Entry point helper +(defun helm-internal (&optional + any-sources any-input + any-prompt any-resume + any-preselect any-buffer + any-keymap any-default any-history) + "The internal helm function called by `helm'. +For ANY-SOURCES ANY-INPUT ANY-PROMPT ANY-RESUME ANY-PRESELECT ANY-BUFFER and +ANY-KEYMAP ANY-DEFAULT ANY-HISTORY See `helm'." + (unless helm--nested (setq helm-initial-frame (selected-frame))) + ;; Activate the advices. + ;; Advices will be available only in >=emacs-24.4, but + ;; allow compiling without errors on lower emacs. + (when (fboundp 'advice-add) + (advice-add 'tramp-read-passwd :around #'helm--suspend-read-passwd) + (advice-add 'ange-ftp-get-passwd :around #'helm--suspend-read-passwd) + (advice-add 'epa-passphrase-callback-function + :around #'helm--suspend-read-passwd) + ;; Ensure linum-mode is disabled in Helm buffers to preserve + ;; performances (Issue #1894). + (advice-add 'linum-on :override #'helm--advice-linum-on)) + (helm-log (concat "[Start session] " (make-string 41 ?+))) + (helm-log "any-prompt = %S" any-prompt) + (helm-log "any-preselect = %S" any-preselect) + (helm-log "any-buffer = %S" any-buffer) + (helm-log "any-keymap = %S" any-keymap) + (helm-log "any-default = %S" any-default) + (helm-log "any-history = %S" any-history) + (setq helm--prompt (or any-prompt "pattern: ")) + (let ((non-essential t) + ;; Prevent mouse jumping to the upper-right + ;; hand corner of the frame (#1538). + mouse-autoselect-window + focus-follows-mouse + mode-line-in-non-selected-windows + (input-method-verbose-flag helm-input-method-verbose-flag) + (helm--maybe-use-default-as-input + (and (null any-input) + (or helm--maybe-use-default-as-input ; it is let-bounded so use it. + (cl-loop for s in (helm-normalize-sources any-sources) + thereis (memq s helm-sources-using-default-as-input)))))) + (unwind-protect + (condition-case-unless-debug _v + (let ( ;; `helm--source-name' is non-`nil' + ;; when `helm' is invoked by action, reset it. + helm--source-name + helm-current-source + helm-in-persistent-action + helm-quit + (helm-buffer (or any-buffer helm-buffer))) + (helm-initialize + any-resume any-input any-default any-sources) + ;; We don't display helm-buffer here to avoid popping + ;; up a window or a frame when exiting immediately when + ;; only one candidate (this avoid having the helm frame + ;; flashing), lets first compute candidates and if more + ;; than one display helm-buffer (this is done later in + ;; helm-read-pattern-maybe). + (unless helm-execute-action-at-once-if-one + (helm-display-buffer helm-buffer any-resume) + (select-window (helm-window))) + ;; We are now in helm-buffer. + (unless helm-allow-mouse + (helm--remap-mouse-mode 1)) ; Disable mouse bindings. + (add-hook 'post-command-hook 'helm--maybe-update-keymap) + ;; Add also to update hook otherwise keymap is not updated + ;; until a key is hitted (Issue #1670). + (add-hook 'helm-after-update-hook 'helm--maybe-update-keymap) + (add-hook 'post-command-hook 'helm--update-header-line) + (helm-log "show prompt") + (unwind-protect + (helm-read-pattern-maybe + any-prompt any-input any-preselect + any-resume any-keymap any-default any-history) + (helm-cleanup)) + (prog1 + (unless helm-quit (helm-execute-selection-action)) + (helm-log (concat "[End session] " (make-string 41 ?-))))) + (quit + (helm-restore-position-on-quit) + (helm-log-run-hook 'helm-quit-hook) + (helm-log (concat "[End session (quit)] " (make-string 34 ?-))) + nil)) + (when (fboundp 'advice-remove) + (advice-remove 'tramp-read-passwd #'helm--suspend-read-passwd) + (advice-remove 'ange-ftp-get-passwd #'helm--suspend-read-passwd) + (advice-remove 'epa-passphrase-callback-function #'helm--suspend-read-passwd) + (advice-remove 'linum-on #'helm--advice-linum-on)) + (helm-log "helm-alive-p = %S" (setq helm-alive-p nil)) + (helm--remap-mouse-mode -1) ; Reenable mouse bindings. + (setq helm-alive-p nil) + ;; Prevent error "No buffer named *helm*" triggered by + ;; `helm-set-local-variable'. + (setq helm--force-updating-p nil) + (setq helm--buffer-in-new-frame-p nil) + ;; Reset helm-pattern so that lambda's using it + ;; before running helm will not start with its old value. + (setq helm-pattern "") + (setq helm--ignore-errors nil) + (helm-log-save-maybe)))) + +(defun helm--advice-linum-on () + (unless (or (minibufferp) + (string-match "\\`\\*helm" (buffer-name)) + (and (daemonp) (null (frame-parameter nil 'client)))) + (linum-mode 1))) + +;;; Helm resume +;; +;; +(defun helm-resume (arg) + "Resume a previous `helm' session. +Call with a prefix arg to choose among existing helm +buffers (sessions). When calling from lisp, specify a buffer-name +as a string with ARG." + (interactive "P") + (let (any-buffer + cur-dir + narrow-pos + (helm-full-frame (default-value 'helm-full-frame)) + sources) + (if arg + (if (and (stringp arg) (bufferp (get-buffer arg))) + (setq any-buffer arg) + (setq any-buffer (helm-resume-select-buffer))) + (setq any-buffer helm-last-buffer)) + (cl-assert any-buffer nil + "helm-resume: No helm buffers found to resume") + (setq sources (buffer-local-value + 'helm-sources (get-buffer any-buffer))) + ;; Reset `cursor-type' to nil as it have been set to t + ;; when quitting previous session. + (with-current-buffer any-buffer (setq cursor-type nil)) + (setq helm-full-frame (buffer-local-value + 'helm-full-frame (get-buffer any-buffer))) + (setq cur-dir (buffer-local-value + 'default-directory (get-buffer any-buffer))) + (setq helm-saved-selection nil + helm-saved-action nil) + (unless (buffer-live-p helm-current-buffer) + ;; `helm-current-buffer' may have been killed. + (setq helm-current-buffer (current-buffer))) + (helm-aif (with-current-buffer any-buffer + helm--current-buffer-narrowed) + (progn + (set-buffer (car it)) + (setq narrow-pos (cdr it)))) + (save-restriction + (when narrow-pos (apply #'narrow-to-region narrow-pos)) + ;; Restart with same `default-directory' value this session + ;; was initially started with. + (with-helm-default-directory cur-dir + (unwind-protect + (helm + :sources sources + :input (buffer-local-value 'helm-input-local (get-buffer any-buffer)) + :prompt (buffer-local-value 'helm--prompt (get-buffer any-buffer)) + :resume t + :buffer any-buffer) + (run-hook-with-args 'helm-resume-after-hook sources)))))) + +(defun helm-resume-previous-session-after-quit (arg) + "Resume previous helm session within a running helm." + (interactive "p") + (with-helm-alive-p + (if (> (length helm-buffers) arg) + (helm-run-after-exit (lambda () (helm-resume (nth arg helm-buffers)))) + (message "No previous helm sessions available for resuming!")))) +(put 'helm-resume-previous-session-after-quit 'helm-only t) + +(defun helm-resume-list-buffers-after-quit () + "List resumable helm buffers within running helm." + (interactive) + (with-helm-alive-p + (if (> (length helm-buffers) 0) + (helm-run-after-exit (lambda () (helm-resume t))) + (message "No previous helm sessions available for resuming!")))) +(put 'helm-resume-list-buffers-after-quit 'helm-only t) + +(defun helm-resume-p (any-resume) + "Whether current helm session is resumed or not." + (eq any-resume t)) + +(defun helm-resume-select-buffer () + "Select an `helm-buffer' in `helm-buffers' list to resume a helm session. +Return nil if no `helm-buffer' found." + (when helm-buffers + (or (helm :sources (helm-build-sync-source "Resume helm buffer" + :candidates helm-buffers) + :resume 'noresume + :buffer "*helm resume*") + (keyboard-quit)))) + +;;;###autoload +(defun helm-cycle-resume () + "Cycle in `helm-buffers' list and resume when waiting more than 1.2s." + (interactive) + (cl-assert (and helm-buffers helm-last-buffer) + nil "No helm buffers to resume") + ;; Setup a new iterator only on first hit on + ;; `helm-run-cycle-resume', subsequents hits should reuse same + ;; iterator. + (unless (and (eq last-command 'helm-cycle-resume) + helm--cycle-resume-iterator) + (setq helm--cycle-resume-iterator + (helm-iter-sub-next-circular + helm-buffers helm-last-buffer :test 'equal))) + (helm--resume-or-iter)) + +(defun helm--resume-or-iter (&optional from-helm) + (message "Resuming helm buffer `%s'" helm-last-buffer) + (if (sit-for helm-cycle-resume-delay) + ;; Delay expire, run helm-resume. + (if from-helm + (helm-run-after-exit (lambda () (helm-resume helm-last-buffer))) + (helm-resume helm-last-buffer)) + ;; key pressed before delay, cycle. + (unless from-helm ; cycling to next item already done. + (message "Resuming helm buffer `%s'" + (setq helm-last-buffer + (helm-iter-next helm--cycle-resume-iterator)))))) + +(defun helm-run-cycle-resume () + "Same as `helm-cycle-resume' but intended to be called only from helm." + (interactive) + (when (cdr helm-buffers) ; only one session registered. + ;; Setup a new iterator only on first hit on + ;; `helm-run-cycle-resume', subsequents hits should reuse same + ;; iterator. + (unless (and (eq last-command 'helm-run-cycle-resume) + helm--cycle-resume-iterator) + (setq helm--cycle-resume-iterator + (helm-iter-sub-next-circular + helm-buffers helm-last-buffer :test 'equal))) + ;; start at next buffer as we already are at `helm-last-buffer'. + (setq helm-last-buffer + (helm-iter-next helm--cycle-resume-iterator)) + (helm--resume-or-iter 'from-helm))) +(put 'helm-run-cycle-resume 'helm-only t) + + +;;;###autoload +(defun helm-other-buffer (any-sources any-buffer) + "Simplified `helm' interface with other `helm-buffer'. +Call `helm' only with ANY-SOURCES and ANY-BUFFER as args." + (helm :sources any-sources :buffer any-buffer)) + +;;; Nested sessions +;; +;; +(defun helm--nest (&rest same-as-helm) + "[internal]Allows calling `helm' within a running helm session. + +Arguments SAME-AS-HELM are the same as `helm'. + +Don't use this directly, use instead `helm' with the keyword +:allow-nest. + +\(fn &key SOURCES INPUT PROMPT RESUME PRESELECT BUFFER KEYMAP DEFAULT HISTORY OTHER-LOCAL-VARS)" + (with-helm-window + (let ((orig-helm-current-buffer helm-current-buffer) + (orig-helm-buffer helm-buffer) + (orig-helm--prompt helm--prompt) + (orig-helm-sources helm-sources) + (orig-helm--in-fuzzy helm--in-fuzzy) + (orig-helm--display-frame helm--buffer-in-new-frame-p) + (orig-helm-last-frame-or-window-configuration + helm-last-frame-or-window-configuration) + (orig-one-window-p helm-onewindow-p) + (helm--nested t)) + ;; FIXME Using helm-full-frame here allow showing the new + ;; helm-buffer in the same window as old helm-buffer, why? + (helm-set-local-variable 'helm-full-frame t) + (unwind-protect + (let (helm-current-position + helm-current-buffer + helm-pattern + (helm-buffer (or (cl-getf same-as-helm :buffer) + (nth 5 same-as-helm) + "*Helm*")) + (enable-recursive-minibuffers t)) + (setq helm-sources nil) + (apply #'helm same-as-helm)) + (with-current-buffer orig-helm-buffer + (setq helm-sources orig-helm-sources) + (setq helm--nested nil) + (setq helm--buffer-in-new-frame-p orig-helm--display-frame) + (setq helm-alive-p t) ; Nested session set this to nil on exit. + (setq helm-buffer orig-helm-buffer) + (setq helm-full-frame nil) + (setq helm--prompt orig-helm--prompt) + (setq helm--in-fuzzy orig-helm--in-fuzzy) + (helm-initialize-overlays helm-buffer) + (unless (helm-empty-buffer-p) (helm-mark-current-line t)) + (setq helm-last-frame-or-window-configuration + orig-helm-last-frame-or-window-configuration) + (setq cursor-type nil) + (setq helm-current-buffer orig-helm-current-buffer) + (setq helm-onewindow-p orig-one-window-p) + ;; Be sure advices, hooks, and local modes keep running. + (if (fboundp 'advice-add) + (progn + (advice-add 'tramp-read-passwd + :around #'helm--suspend-read-passwd) + (advice-add 'ange-ftp-get-passwd + :around #'helm--suspend-read-passwd) + (advice-add 'epa-passphrase-callback-function + :around #'helm--suspend-read-passwd)) + (ad-activate 'tramp-read-passwd) + (ad-activate 'ange-ftp-get-passwd)) + (unless helm-allow-mouse + (helm--remap-mouse-mode 1)) + (unless (cl-loop for h in post-command-hook + thereis (memq h '(helm--maybe-update-keymap + helm--update-header-line))) + (add-hook 'post-command-hook 'helm--maybe-update-keymap) + (add-hook 'post-command-hook 'helm--update-header-line)) + (helm-display-mode-line (helm-get-current-source))))))) + + +;;; Accessors +;; +(defun helm-current-position (save-or-restore) + "Save or restore current position in `helm-current-buffer'. +Argument SAVE-OR-RESTORE is either save or restore." + (cl-case save-or-restore + (save + (helm-log "Save position at %S" (cons (point) (window-start))) + (setq helm-current-position (cons (point) (window-start)))) + (restore + ;; Maybe `helm-current-buffer' have been deleted + ;; during helm session so check if it is here + ;; otherwise position in underlying buffer will be lost. + (when (get-buffer-window helm-current-buffer 'visible) + (helm-log "Restore position at %S in buffer %s" + helm-current-position + (buffer-name (current-buffer))) + (goto-char (car helm-current-position)) + ;; Fix this position with the NOFORCE arg of `set-window-start' + ;; otherwise, if there is some other buffer than `helm-current-buffer' + ;; one, position will be lost. + (set-window-start (selected-window) (cdr helm-current-position) t))))) + + +(defun helm-frame-or-window-configuration (save-or-restore) + "Save or restore last frame or window configuration. +Argument SAVE-OR-RESTORE is either save or restore of window or +frame configuration as per `helm-save-configuration-functions'." + (helm-log "helm-save-configuration-functions = %S" + helm-save-configuration-functions) + (let ((window-persistent-parameters (append '((no-other-window . t)) + window-persistent-parameters))) + (cl-case save-or-restore + (save (setq helm-last-frame-or-window-configuration + (funcall (cdr helm-save-configuration-functions)))) + (restore (funcall (car helm-save-configuration-functions) + helm-last-frame-or-window-configuration) + ;; Restore frame focus. + ;; This is needed for minibuffer own-frame config + ;; when recursive minibuffers are in use. + ;; e.g M-: + helm-minibuffer-history. + (cl-letf ((frame (if (minibufferp helm-current-buffer) + (selected-frame) + (last-nonminibuffer-frame))) + ;; This is a workaround, because the i3 window + ;; manager developers are refusing to fix their + ;; broken timestamp and event handling. + ;; + ;; We basically just disable the part of + ;; select-frame-set-input-focus that would call + ;; XSetInputFocus in Xlib (x-focus-frame), that + ;; resets a timestamp in the xserver which the i3 + ;; developers fail to notice. + ;; + ;; Since they don't know about the new timestamp, + ;; their keyboard handling can break after a helm + ;; user quits emacs, as reported in #1641. + ;; + ;; Fortunately for us, we really don't need this + ;; XSetInputFocus call, since we already have focus + ;; for Emacs, the user is just using helm! We call + ;; select-frame-set-input-focus for the other + ;; side-effects, not for x-focus-frame. + ((symbol-function 'x-focus-frame) #'ignore)) + (select-frame-set-input-focus frame)))))) + +(defun helm-split-window-default-fn (window) + "Default function to split windows before displaying `helm-buffer'. + +It is used as default value for +`helm-split-window-preferred-function' which is then the let-bounded +value of `split-window-preferred-function' in `helm-display-buffer'. +When `helm-display-function' which default to +`helm-default-display-buffer' is called from `helm-display-buffer' the +value of `split-window-preferred-function' will be used by `display-buffer'." + (let (split-width-threshold) + (if (and (fboundp 'window-in-direction) + ;; Don't try to split when starting in a minibuffer + ;; e.g M-: and try to use helm-show-kill-ring. + (not (minibufferp helm-current-buffer))) + (if (or (one-window-p t) + helm-split-window-inside-p) + (split-window + (selected-window) nil (if (eq helm-split-window-default-side 'other) + 'below helm-split-window-default-side)) + ;; If more than one window reuse one of them. + (cl-case helm-split-window-default-side + (left (or (helm-window-in-direction 'left) + (helm-window-in-direction 'above) + (selected-window))) + (above (or (helm-window-in-direction 'above) + (helm-window-in-direction 'left) + (selected-window))) + (right (or (helm-window-in-direction 'right) + (helm-window-in-direction 'below) + (selected-window))) + (below (or (helm-window-in-direction 'below) + (helm-window-in-direction 'right) + (selected-window))) + (same (selected-window)) + (other (other-window-for-scrolling)) + (t (or (window-next-sibling) (selected-window))))) + (split-window-sensibly window)))) + +(defun helm-window-in-direction (direction) + "Same as `window-in-direction' but check if window is dedicated." + (helm-aif (window-in-direction direction) + (and (not (window-dedicated-p it)) it))) + + +;;; Display helm buffer +;; +;; +(defun helm-resolve-display-function (com) + "Decide which display function use according to `helm-commands-using-frame'. + +The `helm-display-function' buffer local value takes precedence on +`helm-commands-using-frame'. +If `helm-initial-frame' has no minibuffer, use +`helm-display-buffer-in-own-frame' function. +Fallback to global value of `helm-display-function' when no local +value found and current command is not in `helm-commands-using-frame'." + (or (with-helm-buffer helm-display-function) + (and (or (memq com helm-commands-using-frame) + (and helm-use-frame-when-more-than-two-windows + (null helm--nested) + (> (length (window-list)) 2)) + ;; Frame parameter is unreliable for minibuffer on emacs-26. + (null (member helm-initial-frame (minibuffer-frame-list)))) + #'helm-display-buffer-in-own-frame) + (default-value 'helm-display-function))) + +(defun helm-display-buffer (buffer &optional resume) + "Display BUFFER. + +The function used to display `helm-buffer' by calling +`helm-display-function' which split window with +`helm-split-window-preferred-function'." + (let ((split-window-preferred-function + helm-split-window-preferred-function) + (helm-split-window-default-side + (if (and (not helm-full-frame) + helm-reuse-last-window-split-state) + (cond ((eq helm-split-window-default-side 'same) 'same) + ((eq helm-split-window-default-side 'other) 'other) + (helm--window-side-state) + (t helm-split-window-default-side)) + helm-split-window-default-side)) + (disp-fn (with-current-buffer buffer + (helm-resolve-display-function + (if helm-actions-inherit-frame-settings + (helm-this-command) this-command))))) + (prog1 + (funcall disp-fn buffer (or (helm-resume-p resume) + (and helm-actions-inherit-frame-settings + helm--executing-helm-action))) + (with-helm-buffer (setq-local helm-display-function disp-fn)) + (setq helm-onewindow-p (one-window-p t)) + ;; Don't allow other-window and friends switching out of minibuffer. + (when helm-prevent-escaping-from-minibuffer + (helm-prevent-switching-other-window))))) + +(cl-defun helm-prevent-switching-other-window (&key (enabled t)) + "Allow setting `no-other-window' parameter for all windows. +Arg ENABLE is the value of `no-other-window' window property." + (walk-windows + (lambda (w) + (unless (window-dedicated-p w) + (set-window-parameter w 'no-other-window enabled))) + 0)) + +(defun helm-default-display-buffer (buffer &optional _resume) + "Default function to display `helm-buffer' BUFFER. + +It is the default value of `helm-display-function' +It uses `switch-to-buffer' or `display-buffer' depending on the +value of `helm-full-frame' or `helm-split-window-default-side'." + (let (pop-up-frames) + (if (or (buffer-local-value 'helm-full-frame (get-buffer buffer)) + (and (eq helm-split-window-default-side 'same) + (one-window-p t))) + (progn (and (not (minibufferp helm-current-buffer)) + (delete-other-windows)) + (switch-to-buffer buffer)) + (when (and (or helm-always-two-windows helm-autoresize-mode) + (not (eq helm-split-window-default-side 'same)) + (not (minibufferp helm-current-buffer)) + (not helm-split-window-inside-p)) + (delete-other-windows)) + (display-buffer + buffer `(,helm-default-display-buffer-functions + . ,(append helm-default-display-buffer-alist + `((window-height . ,helm-display-buffer-default-height) + (window-width . ,helm-display-buffer-default-width))))) + (helm-log-run-hook 'helm-window-configuration-hook)))) + +(defun helm-display-buffer-in-own-frame (buffer &optional resume) + "Display helm buffer BUFFER in a separate frame. + +Function suitable for `helm-display-function', +`helm-completion-in-region-display-function' +and/or `helm-show-completion-default-display-function'. + +See `helm-display-buffer-height' and `helm-display-buffer-width' to +configure frame size. + +Note that this feature is available only with emacs-25+." + (cl-assert (and (fboundp 'window-absolute-pixel-edges) + (fboundp 'frame-geometry)) + nil "Helm buffer in own frame is only available starting at emacs-25+") + (if (not (display-graphic-p)) + ;; Fallback to default when frames are not usable. + (helm-default-display-buffer buffer) + (setq helm--buffer-in-new-frame-p t) + (let* ((pos (window-absolute-pixel-position)) + (half-screen-size (/ (display-pixel-height x-display-name) 2)) + (frame-info (frame-geometry)) + (prmt-size (length helm--prompt)) + (line-height (frame-char-height)) + (default-frame-alist + (if resume + (buffer-local-value 'helm--last-frame-parameters + (get-buffer buffer)) + `((width . ,helm-display-buffer-width) + (height . ,helm-display-buffer-height) + (tool-bar-lines . 0) + (left . ,(- (car pos) + (* (frame-char-width) + (if (< (- (point) (point-at-bol)) prmt-size) + (- (point) (point-at-bol)) + prmt-size)))) + ;; Try to put frame at the best possible place. + ;; Frame should be below point if enough + ;; place, otherwise above point and + ;; current line should not be hidden + ;; by helm frame. + (top . ,(if (> (cdr pos) half-screen-size) + ;; Above point + (- (cdr pos) + ;; add 2 lines to make sure there is always a gap + (* (+ helm-display-buffer-height 2) line-height) + ;; account for title bar height too + (cddr (assq 'title-bar-size frame-info))) + ;; Below point + (+ (cdr pos) line-height))) + (title . "Helm") + (undecorated . ,helm-use-undecorated-frame-option) + (vertical-scroll-bars . nil) + (menu-bar-lines . 0) + (fullscreen . nil) + (visibility . ,(null helm-display-buffer-reuse-frame)) + (minibuffer . t)))) + display-buffer-alist) + ;; Display minibuffer above or below only in initial session, + ;; not on a session triggered by action, this way if user have + ;; toggled minibuffer and header-line manually she keeps this + ;; setting in next action. + (unless (or helm--executing-helm-action resume) + ;; Add the hook inconditionally, if + ;; helm-echo-input-in-header-line is nil helm-hide-minibuffer-maybe + ;; will have anyway no effect so no need to remove the hook. + (add-hook 'helm-minibuffer-set-up-hook 'helm-hide-minibuffer-maybe) + (with-helm-buffer + (setq-local helm-echo-input-in-header-line + (not (> (cdr pos) half-screen-size))))) + (helm-display-buffer-popup-frame buffer default-frame-alist) + ;; When frame size have been modified manually by user restore + ;; it to default value unless resuming or not using + ;; `helm-display-buffer-reuse-frame'. + ;; This have to be done AFTER raising the frame otherwise + ;; minibuffer visibility is lost until next session. + (unless (or resume (not helm-display-buffer-reuse-frame)) + (set-frame-size helm-popup-frame + helm-display-buffer-width + helm-display-buffer-height))) + (helm-log-run-hook 'helm-window-configuration-hook))) + +(defun helm-display-buffer-popup-frame (buffer frame-alist) + (if helm-display-buffer-reuse-frame + (let* ((x (cdr (assoc 'left frame-alist))) + (y (cdr (assoc 'top frame-alist)))) + (unless (and helm-popup-frame + (frame-live-p helm-popup-frame)) + (setq helm-popup-frame (make-frame frame-alist))) + (select-frame helm-popup-frame) + (set-frame-position helm-popup-frame x y) + (switch-to-buffer buffer) + (select-frame-set-input-focus helm-popup-frame t)) + ;; If user have changed `helm-display-buffer-reuse-frame' to nil + ;; maybe kill the frame. + (when (and helm-popup-frame + (frame-live-p helm-popup-frame)) + (delete-frame helm-popup-frame)) + (display-buffer + buffer '(display-buffer-pop-up-frame . nil)))) + +;; Ensure to quit helm when user delete helm frame manually. +;; If user deletes another frame keep session running. +(defun helm--delete-frame-function (frame) + (when (and helm-alive-p + ;; FRAME is handling helm-buffer + (get-buffer-window helm-buffer frame)) + (helm-keyboard-quit))) +(add-hook 'delete-frame-functions 'helm--delete-frame-function) + +;;; Initialize +;; +(defun helm-get-sources (sources) + "Transform each element of SOURCES in alist. +Returns the resulting list." + (when sources + (mapcar (lambda (source) + (if (listp source) + source (symbol-value source))) + (helm-normalize-sources sources)))) + +(defun helm-initialize (any-resume any-input any-default any-sources) + "Start initialization of `helm' session. +For ANY-RESUME ANY-INPUT ANY-DEFAULT and ANY-SOURCES See `helm'." + (helm-log "start initialization: any-resume=%S any-input=%S" + any-resume any-input) + (helm-frame-or-window-configuration 'save) + (let ((sources (helm-get-sources any-sources))) + (setq helm--in-fuzzy + (cl-loop for s in sources + for matchfns = (helm-match-functions s) + for searchfns = (helm-search-functions s) + when (or (memq 'helm-fuzzy-match matchfns) + (memq 'helm-fuzzy-search searchfns)) + return t)) + (helm-log "sources = %S" sources) + (helm-set-local-variable 'helm-sources sources) + ;; Once `helm-buffer' is created `helm-sources' will be a local + ;; variable which value is a list of alists. + (helm-current-position 'save) + (if (helm-resume-p any-resume) + (helm-initialize-overlays (helm-buffer-get)) + (helm-initial-setup any-default sources)) + (setq helm-alive-p t) + (unless (eq any-resume 'noresume) + (helm--push-and-remove-dups helm-buffer 'helm-buffers) + (setq helm-last-buffer helm-buffer)) + (when any-input + (setq helm-input any-input + helm-pattern any-input) + (helm--fuzzy-match-maybe-set-pattern)) + ;; If a `resume' attribute is present `helm-compute-attr-in-sources' + ;; will run its function. + (when (helm-resume-p any-resume) + (helm-compute-attr-in-sources 'resume)) + (helm-log "end initialization"))) + +(defun helm-initialize-overlays (buffer) + "Initialize helm overlays in BUFFER." + (helm-log "overlay setup") + (if helm-selection-overlay + ;; make sure the overlay belongs to the helm buffer if + ;; it's newly created + (move-overlay helm-selection-overlay (point-min) (point-min) + (get-buffer buffer)) + + (setq helm-selection-overlay + (make-overlay (point-min) (point-min) (get-buffer buffer))) + (overlay-put helm-selection-overlay 'face 'helm-selection) + (overlay-put helm-selection-overlay 'priority 1))) + +(defun helm-restore-position-on-quit () + "Restore position in `helm-current-buffer' when quitting." + (helm-current-position 'restore)) + +(defun helm--push-and-remove-dups (elm sym) + "Move ELM of SYM value on top and set SYM to this new value." + (set sym (cons elm (delete elm (symbol-value sym))))) + +(defun helm--current-buffer () + "[internal] Return `current-buffer' BEFORE `helm-buffer' is initialized. +Note that it returns the minibuffer in use after helm has started +and is intended for `helm-initial-setup'. To get the buffer where +helm was started, use `helm-current-buffer' instead." + (if (minibuffer-window-active-p (minibuffer-window)) + ;; If minibuffer is active be sure to use it's buffer + ;; as `helm-current-buffer', this allow to use helm + ;; from an already active minibuffer (M-: etc...) + (window-buffer (active-minibuffer-window)) + ;; Fix Issue #456 + ;; Use this instead of `current-buffer' to ensure + ;; helm session started in helm-mode from a completing-read + ;; Use really the buffer where we started and not the one + ;; where the completing-read is wrapped. i.e + ;; (with-current-buffer SOME-OTHER-BUFFER (completing-read [...]) + (window-buffer (with-selected-window (minibuffer-window) + (minibuffer-selected-window))))) + +(defun helm--run-init-hooks (hook sources) + "Run after and before init hooks local to source. +See :after-init-hook and :before-init-hook in `helm-source'." + (cl-loop with sname = (cl-ecase hook + (before-init-hook "h-before-init-hook") + (after-init-hook "h-after-init-hook")) + with h = (cl-gensym sname) + for s in sources + for hv = (assoc-default hook s) + if (and hv (not (symbolp hv))) + do (set h hv) + and do (helm-log-run-hook h) + else do (helm-log-run-hook hv))) + +(defun helm-initial-setup (any-default sources) + "Initialize helm settings and set up the helm buffer." + ;; Run global hook. + (helm-log-run-hook 'helm-before-initialize-hook) + ;; Run local source hook. + (helm--run-init-hooks 'before-init-hook sources) + ;; For initialization of helm locals vars that need + ;; a value from current buffer, it is here. + (helm-set-local-variable 'current-input-method current-input-method) + (setq helm-current-prefix-arg nil + helm-saved-action nil + helm-saved-selection nil + helm-suspend-update-flag nil + ;; Ensure this is called BEFORE selecting helm-window. + helm-current-buffer (helm--current-buffer) + helm-buffer-file-name buffer-file-name + helm-issued-errors nil + helm-saved-current-source nil + helm--suspend-update-interactive-flag nil) + (when (and (with-helm-current-buffer + (and (buffer-narrowed-p) + (use-region-p))) + (not helm--nested)) + (helm-set-local-variable 'helm--current-buffer-narrowed + (list (current-buffer) + (region-beginning) (region-end)))) + (unless (and (or helm-split-window-state + helm--window-side-state) + helm-reuse-last-window-split-state) + (setq helm-split-window-state + (if (or (null split-width-threshold) + (and (integerp split-width-threshold) + (>= split-width-threshold (+ (frame-width) 4)))) + 'vertical 'horizontal)) + (setq helm--window-side-state + (or helm-split-window-default-side 'below))) + ;; Call the init function for sources where appropriate + (helm-compute-attr-in-sources 'init sources) + (setq helm-pattern (or (and helm--maybe-use-default-as-input + (or (if (listp any-default) + (car any-default) any-default) + (with-helm-current-buffer + (thing-at-point 'symbol)))) + "")) + (setq helm-input "") + (clrhash helm-candidate-cache) + (helm-create-helm-buffer) + (helm-clear-visible-mark) + ;; Run global hook. + (helm-log-run-hook 'helm-after-initialize-hook) + ;; Run local source hook. + (helm--run-init-hooks 'after-init-hook sources)) + +(define-derived-mode helm-major-mode + fundamental-mode "Hmm" + "[Internal] Provide major-mode name in helm buffers. +Unuseful when used outside helm, don't use it.") +(put 'helm-major-mode 'mode-class 'special) +(put 'helm-major-mode 'helm-only t) + +(defun helm-create-helm-buffer () + "Create and setup `helm-buffer'." + (let ((root-dir default-directory) + (inhibit-read-only t)) + (with-current-buffer (get-buffer-create helm-buffer) + (helm-log "Enabling major-mode %S" major-mode) + (helm-log "kill local variables: %S" (buffer-local-variables)) + (kill-all-local-variables) + (helm-major-mode) + (set (make-local-variable 'buffer-read-only) nil) + (buffer-disable-undo) + (erase-buffer) + (set (make-local-variable 'helm-map) helm-map) + (set (make-local-variable 'helm-source-filter) nil) + (make-local-variable 'helm-sources) + (set (make-local-variable 'helm-display-function) nil) + (set (make-local-variable 'helm-selection-point) nil) + (set (make-local-variable 'scroll-margin) + (if helm-display-source-at-screen-top + 0 helm-completion-window-scroll-margin)) + (set (make-local-variable 'default-directory) root-dir) + (set (make-local-variable 'helm-marked-candidates) nil) + (set (make-local-variable 'helm--prompt) helm--prompt) + (helm-initialize-persistent-action) + (helm-log "helm-display-function = %S" helm-display-function) + (helm-log "helm--local-variables = %S" helm--local-variables) + (helm--set-local-variables-internal) + (setq truncate-lines helm-truncate-lines) ; already local. + (setq cursor-type nil)) + (helm-initialize-overlays helm-buffer) + (get-buffer helm-buffer))) + +(define-minor-mode helm--minor-mode + "[INTERNAL] Enable keymap in helm minibuffer. +Since this mode has no effect when run outside of helm context, +please don't use it outside helm. + +\\{helm-map}" + :group 'helm + :keymap (and helm-alive-p helm-map) + (unless helm-alive-p (setq helm--minor-mode nil))) +(put 'helm--minor-mode 'helm-only t) + +(defun helm--reset-default-pattern () + (setq helm-pattern "") + (setq helm--maybe-use-default-as-input nil)) + +(defun helm-read-pattern-maybe (any-prompt any-input + any-preselect any-resume any-keymap + any-default any-history) + "Read pattern with prompt ANY-PROMPT and initial input ANY-INPUT. +For ANY-PRESELECT ANY-RESUME ANY-KEYMAP ANY-DEFAULT ANY-HISTORY, See `helm'." + (with-helm-buffer + (if (and (helm-resume-p any-resume) + ;; When no source, helm-buffer is empty + ;; or contain non--candidate lines (e.g grep exit status) + (helm-get-current-source)) + (helm-mark-current-line t) + (helm-update any-preselect)) + (let* ((src (helm-get-current-source)) + (src-keymap (assoc-default 'keymap src)) + (hist (or (and any-history (symbolp any-history) any-history) + ;; Needed for resuming. + (assoc-default 'history src))) + (timer nil) + blink-matching-paren + (resize-mini-windows (and (null helm-echo-input-in-header-line) + resize-mini-windows)) + (first-src (car helm-sources)) + (source-process-p (or (assq 'candidates-process src) + (assq 'candidates-process first-src)))) + (helm-log "helm-get-candidate-number => %S" + (helm-get-candidate-number)) + (helm-log "helm-execute-action-at-once-if-one = %S" + helm-execute-action-at-once-if-one) + (helm-log "helm-quit-if-no-candidate = %S" helm-quit-if-no-candidate) + (when (and src (helm-resume-p any-resume)) + (helm-display-mode-line src)) + ;; Reset `helm-pattern' and update + ;; display if no result found with precedent value of `helm-pattern' + ;; unless `helm-quit-if-no-candidate' is non-`nil', in this case + ;; Don't force update with an empty pattern. + ;; Reset also `helm--maybe-use-default-as-input' as this checking + ;; happen only on startup. + (when helm--maybe-use-default-as-input + ;; Store value of `default' temporarily here waiting next update + ;; to allow actions like helm-moccur-action matching pattern + ;; at the place it jump to. + (setq helm-input helm-pattern) + (if source-process-p + ;; Reset pattern to next update. + (with-helm-after-update-hook + (helm--reset-default-pattern)) + ;; Reset pattern right now. + (helm--reset-default-pattern)) + ;; Ensure force-update when no candidates + ;; when we start with an empty pattern. + (and (helm-empty-buffer-p) + (null helm-quit-if-no-candidate) + (helm-force-update))) + ;; Handle `helm-execute-action-at-once-if-one' and + ;; `helm-quit-if-no-candidate' now. + (cond ((and (if (functionp helm-execute-action-at-once-if-one) + (funcall helm-execute-action-at-once-if-one) + helm-execute-action-at-once-if-one) + (= (helm-get-candidate-number + (eq helm-execute-action-at-once-if-one 'current-source)) + 1)) + (ignore)) ; Don't enter the minibuffer loop. + ((and helm-quit-if-no-candidate + (= (helm-get-candidate-number) 0)) + (setq helm-quit t) + (and (functionp helm-quit-if-no-candidate) + (funcall helm-quit-if-no-candidate))) + (t ; Enter now minibuffer and wait for input. + (let ((tap (or any-default + (with-helm-current-buffer + (thing-at-point 'symbol))))) + (when helm-execute-action-at-once-if-one + (helm-display-buffer helm-buffer any-resume) + (select-window (helm-window))) + (unwind-protect + (minibuffer-with-setup-hook + (lambda () + ;; Start minor-mode with global value of helm-map. + (helm--minor-mode 1) + ;; Now override the global value of `helm-map' with + ;; the local one which is in this order: + ;; - The keymap of current source. + ;; - The value passed in ANY-KEYMAP + ;; - Or fallback to the global value of helm-map. + (helm--maybe-update-keymap + (or src-keymap any-keymap helm-map)) + (helm-log-run-hook 'helm-minibuffer-set-up-hook) + (setq timer + (run-with-idle-timer + (max (with-helm-buffer helm-input-idle-delay) + 0.001) + 'repeat + (lambda () + ;; Stop updating in persistent action + ;; or when `helm-suspend-update-flag' + ;; is non-`nil'. + (unless (or helm-in-persistent-action + helm-suspend-update-flag) + (save-selected-window + (helm-check-minibuffer-input) + (helm-print-error-messages)))))) + ;; minibuffer has already been filled here. + (helm--update-header-line)) + (read-from-minibuffer (propertize (or any-prompt "pattern: ") + 'face 'helm-minibuffer-prompt) + any-input helm-map + nil hist tap + helm-inherit-input-method)) + (when timer (cancel-timer timer) (setq timer nil))))))))) + +(defun helm-toggle-suspend-update () + "Enable or disable display update in helm. +This can be useful for example for quietly writing a complex regexp +without helm constantly updating." + (interactive) + (helm-suspend-update (not helm-suspend-update-flag) t) + (setq helm--suspend-update-interactive-flag + (not helm--suspend-update-interactive-flag))) +(put 'helm-toggle-suspend-update 'helm-only t) + +(defun helm-suspend-update (arg &optional verbose) + "Enable or disable display update in helm. +If ARG is 1 or non nil suspend update, if it is -1 or nil reenable +updating. When VERBOSE is specified display a message." + (with-helm-buffer + (when (setq helm-suspend-update-flag + (helm-acase arg + (1 t) + (-1 nil) + (t it))) + (helm-kill-async-processes) + (setq helm-pattern "")) + (when verbose + (message (if helm-suspend-update-flag + "Helm update suspended!" + "Helm update re-enabled!"))) + (helm-aif (helm-get-current-source) + (helm-display-mode-line it t)))) + +(defun helm-delete-backward-no-update (arg) + "Disable update and delete ARG chars backward. +Update is reenabled when idle 1s." + (interactive "p") + (with-helm-alive-p + (unless helm--suspend-update-interactive-flag + (helm-suspend-update 1)) + (backward-delete-char arg) + (run-with-idle-timer + 1 nil + (lambda () + (unless helm--suspend-update-interactive-flag + (helm-suspend-update -1) + (helm-check-minibuffer-input) + (helm-force-update)))))) +(put 'helm-delete-backward-no-update 'helm-only t) + +(defun helm--suspend-read-passwd (old--fn &rest args) + "Suspend helm while reading password. +This is used to advice `tramp-read-passwd', `ange-ftp-get-passwd' and +`epa-passphrase-callback-function'." + ;; Suspend update when prompting for a tramp password. + (setq helm-suspend-update-flag t) + (setq overriding-terminal-local-map nil) + (setq helm--reading-passwd-or-string t) + (unwind-protect + ;; No need to suspend timer in emacs-24.4 + ;; it is fixed upstream. + (apply old--fn args) + (setq helm--reading-passwd-or-string nil) + (setq helm-suspend-update-flag nil))) + +(defun helm--maybe-update-keymap (&optional map) + "Handle different keymaps in multiples sources. + +Overrides `helm-map' with the local map of current source. If no +map is found in current source, does nothing (keeps previous +map)." + (with-helm-buffer + (helm-aif (or map (assoc-default 'keymap (helm-get-current-source))) + ;; We used a timer in the past to leave + ;; enough time to helm to setup its keymap + ;; when changing source from a recursive minibuffer. + ;; e.g C-x C-f M-y C-g + ;; => *find-files have now the bindings of *kill-ring. + ;; It is no more true now we are using `minor-mode-overriding-map-alist' + ;; and `helm--minor-mode' thus it fix issue #1076 for emacs-24.3 + ;; where concurrent timers are not supported. + ;; i.e update keymap+check input. + (with-current-buffer (window-buffer (minibuffer-window)) + (setq minor-mode-overriding-map-alist `((helm--minor-mode . ,it))))))) + +;;; Prevent loosing focus when using mouse. +;; +(defvar helm--remap-mouse-mode-map + (let ((map (make-sparse-keymap))) + (cl-loop for k in '([mouse-1] [mouse-2] [mouse-3] + [down-mouse-1] [down-mouse-2] [down-mouse-3] + [drag-mouse-1] [drag-mouse-2] [drag-mouse-3] + [double-mouse-1] [double-mouse-2] [double-mouse-3] + [triple-mouse-1] [triple-mouse-2] [triple-mouse-3]) + do (define-key map k 'ignore)) + map)) + +(define-minor-mode helm--remap-mouse-mode + "[INTERNAL] Prevent escaping helm minibuffer with mouse clicks. +Do nothing when used outside of helm context. + +WARNING: Do not use this mode yourself, it is internal to helm." + :group 'helm + :global t + :keymap helm--remap-mouse-mode-map + (unless helm-alive-p + (setq helm--remap-mouse-mode-map nil))) +(put 'helm--remap-mouse-mode 'helm-only t) + +;; Clean up + +(defun helm-cleanup () + "Clean up the mess when helm exit or quit." + (helm-log "start cleanup") + (with-current-buffer helm-buffer + (let ((frame (selected-frame))) + (setq cursor-type t) + (remove-hook 'post-command-hook 'helm--maybe-update-keymap) + (remove-hook 'post-command-hook 'helm--update-header-line) + ;; Be sure we call cleanup functions from helm-buffer. + (helm-compute-attr-in-sources 'cleanup) + ;; Delete or make invisible helm frame. + (if (and helm--buffer-in-new-frame-p (null helm--nested)) + (progn + (setq-local helm--last-frame-parameters + (helm--get-frame-parameters)) + (bury-buffer) + (if helm-display-buffer-reuse-frame + (make-frame-invisible frame) (delete-frame frame))) + ;; bury-buffer from this window [1]. + ;; Do it at end to make sure buffer is still current. + (bury-buffer)))) + (helm-kill-async-processes) + ;; Remove the temporary hooks added + ;; by `with-helm-temp-hook' that + ;; may not have been consumed. + (when helm--temp-hooks + (cl-loop for (fn . hook) in helm--temp-hooks + do (set hook (delete fn (symbol-value hook))))) + ;; When running helm from a dedicated frame + ;; with no minibuffer, helm will run in the main frame + ;; which have a minibuffer, so be sure to disable + ;; the `no-other-window' prop there. + (helm-prevent-switching-other-window :enabled nil) + (helm-log-run-hook 'helm-cleanup-hook) + (helm-frame-or-window-configuration 'restore) + ;; [1] now bury-buffer from underlying windows otherwise, + ;; if this window is killed the underlying buffer will + ;; be a helm buffer. + (replace-buffer-in-windows helm-buffer) + (setq helm-alive-p nil) + ;; Prevent error "No buffer named *helm*" triggered by + ;; `helm-set-local-variable'. + (setq helm--force-updating-p nil) + (setq helm--buffer-in-new-frame-p nil) + ;; This is needed in some cases where last input + ;; is yielded infinitely in minibuffer after helm session. + (helm-clean-up-minibuffer)) + +(defun helm-clean-up-minibuffer () + "Remove contents of minibuffer." + (let ((miniwin (minibuffer-window))) + ;; Clean only current minibuffer used by helm. + ;; i.e The precedent one is active. + (unless (minibuffer-window-active-p miniwin) + (with-current-buffer (window-buffer miniwin) + (delete-minibuffer-contents))))) + + +;;; Input handling +;; +;; +(defun helm-check-minibuffer-input () + "Check minibuffer content." + (with-helm-quittable + (with-selected-window (or (active-minibuffer-window) + (minibuffer-window)) + (helm-check-new-input (minibuffer-contents))))) + +(defun helm-check-new-input (input) + "Check INPUT string and update the helm buffer if necessary." + (unless (equal input helm-pattern) + (setq helm-pattern input) + (unless (helm-action-window) + (setq helm-input helm-pattern)) + (helm-log "helm-pattern = %S" helm-pattern) + (helm-log "helm-input = %S" helm-input) + (setq helm--in-update t) + (helm-update))) + +(defun helm--reset-update-flag () + (run-with-idle-timer + helm-exit-idle-delay nil + (lambda () (setq helm--in-update nil)))) + +;; (add-hook 'helm-after-update-hook #'helm--reset-update-flag) + + +;; All candidates + +(defun helm-get-candidates (source) + "Retrieve and return the list of candidates from SOURCE." + (let* (inhibit-quit + (candidate-fn (assoc-default 'candidates source)) + (candidate-proc (assoc-default 'candidates-process source)) + cfn-error + (notify-error + (lambda (&optional e) + (error + "In `%s' source: `%s' %s %s" + (assoc-default 'name source) + (or candidate-fn candidate-proc) + (if e "\n" "must be a list, a symbol bound to a list, or a function returning a list") + (if e (prin1-to-string e) "")))) + (candidates (condition-case-unless-debug err + ;; Process candidates-(process) function + ;; It may return a process or a list of candidates. + (if candidate-proc + ;; Calling `helm-interpret-value' with no + ;; SOURCE arg force the use of `funcall' + ;; and not `helm-apply-functions-from-source'. + (helm-interpret-value candidate-proc) + (helm-interpret-value candidate-fn source)) + (error (helm-log "Error: %S" (setq cfn-error err)) nil)))) + (cond ((and (processp candidates) (not candidate-proc)) + (warn "Candidates function `%s' should be called in a `candidates-process' attribute" + candidate-fn)) + ((and candidate-proc (not (processp candidates))) + (error "Candidates function `%s' should run a process" candidate-proc))) + (cond ((processp candidates) + ;; Candidates will be filtered later in process filter. + candidates) + ;; An error occured in candidates function. + (cfn-error (unless helm--ignore-errors + (funcall notify-error cfn-error))) + ;; Candidates function returns no candidates. + ((or (null candidates) + ;; Can happen when the output of a process + ;; is empty, and the candidates function call + ;; something like (split-string (buffer-string) "\n") + ;; which result in a list of one empty string (Issue #938). + ;; e.g (completing-read "test: " '("")) + (equal candidates '(""))) + nil) + ((listp candidates) + ;; Transform candidates with `candidate-transformer' functions or + ;; `real-to-display' functions if those are found, + ;; otherwise return candidates unmodified. + ;; `filtered-candidate-transformer' is NOT called here. + (helm-transform-candidates candidates source)) + (t (funcall notify-error))))) + +(defmacro helm-while-no-input (&rest body) + "Same as `while-no-input' but without the `input-pending-p' test." + (declare (debug t) (indent 0)) + (let ((catch-sym (make-symbol "input"))) + `(with-local-quit + (catch ',catch-sym + (let ((throw-on-input ',catch-sym)) + ,@body))))) + +(defun helm-get-cached-candidates (source) + "Return the cached value of candidates for SOURCE. +Cache the candidates if there is no cached value yet." + (let* ((name (assoc-default 'name source)) + (candidate-cache (gethash name helm-candidate-cache))) + (helm-aif candidate-cache + (prog1 it (helm-log "Use cached candidates")) + (helm-log "No cached candidates, calculate candidates") + (let ((candidates (helm-get-candidates source))) + (cond ((processp candidates) + (push (cons candidates + (append source + (list (cons 'item-count 0) + (cons 'incomplete-line "")))) + helm-async-processes) + (set-process-filter candidates 'helm-output-filter) + (setq candidates nil)) + ((not (assq 'volatile source)) + (puthash name candidates helm-candidate-cache))) + candidates)))) + + +;;; Candidate transformers + +(defun helm-process-candidate-transformer (candidates source) + "Execute `candidate-transformer' function(s) on CANDIDATES in SOURCE." + (helm-aif (assoc-default 'candidate-transformer source) + (helm-apply-functions-from-source source it candidates) + candidates)) + +(defun helm-process-filtered-candidate-transformer (candidates source) + "Execute `filtered-candidate-transformer' function(s) on CANDIDATES in SOURCE." + (helm-aif (assoc-default 'filtered-candidate-transformer source) + (helm-apply-functions-from-source source it candidates source) + candidates)) + +(defmacro helm--maybe-process-filter-one-by-one-candidate (candidate source) + "Execute `filter-one-by-one' function(s) on real value of CANDIDATE in SOURCE." + `(helm-aif (assoc-default 'filter-one-by-one ,source) + (let ((real (if (consp ,candidate) + (cdr ,candidate) + ,candidate))) + (if (and (listp it) + (not (functionp it))) ;; Don't treat lambda's as list. + (cl-loop for f in it + do (setq ,candidate (funcall f real)) + finally return ,candidate) + (setq ,candidate (funcall it real)))) + ,candidate)) + +(defun helm--initialize-one-by-one-candidates (candidates source) + "Process the CANDIDATES with the `filter-one-by-one' function in SOURCE. +Return CANDIDATES unchanged when pattern is not empty." + (helm-aif (and (string= helm-pattern "") + (assoc-default 'filter-one-by-one source)) + (cl-loop for cand in candidates collect + (helm--maybe-process-filter-one-by-one-candidate cand source)) + candidates)) + +(defun helm-process-filtered-candidate-transformer-maybe + (candidates source process-p) + "Execute `filtered-candidate-transformer' function(s) on CANDIDATES in SOURCE. +When PROCESS-P is non-`nil' execute `filtered-candidate-transformer' +functions if some, otherwise return CANDIDATES." + (if process-p + ;; When no filter return CANDIDATES unmodified. + (helm-process-filtered-candidate-transformer candidates source) + candidates)) + +(defun helm-process-real-to-display (candidates source) + "Execute real-to-display function on all CANDIDATES of SOURCE." + (helm-aif (assoc-default 'real-to-display source) + (setq candidates (helm-apply-functions-from-source + source 'mapcar + (lambda (cand) + (if (consp cand) + ;; override DISPLAY from candidate-transformer + (cons (funcall it (cdr cand)) (cdr cand)) + (cons (funcall it cand) cand))) + candidates)) + candidates)) + +(defun helm-transform-candidates (candidates source &optional process-p) + "Transform CANDIDATES from SOURCE according to candidate transformers. + +When PROCESS-P is non-`nil' executes the +`filtered-candidate-transformer' functions, otherwise processes +`candidate-transformer' functions only, +`filtered-candidate-transformer' functions being processed later, +after the candidates have been narrowed by +`helm-candidate-number-limit', see `helm-compute-matches'. When +`real-to-display' attribute is present, execute its functions on all +maybe filtered CANDIDATES." + (helm-process-real-to-display + (helm-process-filtered-candidate-transformer-maybe + (helm-process-candidate-transformer + candidates source) + source process-p) + source)) + + +;; Narrowing candidates +(defun helm-candidate-number-limit (source) + "Apply candidate-number-limit attribute value. +This overrides `helm-candidate-number-limit' variable. + +e.g: +If \(candidate-number-limit\) is in SOURCE, show all candidates in SOURCE. +If \(candidate-number-limit . 123\) is in SOURCE limit candidate to 123." + (helm-aif (assq 'candidate-number-limit source) + ;; When assoc value is nil use by default 99999999 otherwise use + ;; the assoc value, when it is a symbol interpret its value (#1831). + (or (helm-aand (cdr it) (helm-interpret-value it)) 99999999) + (or helm-candidate-number-limit 99999999))) + +(defun helm-candidate-get-display (candidate) + "Get searched display part from CANDIDATE. +CANDIDATE is either a string, a symbol, or a \(DISPLAY . REAL\) +cons cell." + (cond ((car-safe candidate)) + ((symbolp candidate) + (symbol-name candidate)) + ((numberp candidate) + (number-to-string candidate)) + (t candidate))) + +(defun helm-process-pattern-transformer (pattern source) + "Execute pattern-transformer attribute function(s) on PATTERN in SOURCE." + (helm-aif (assoc-default 'pattern-transformer source) + (helm-apply-functions-from-source source it pattern) + pattern)) + +(defun helm-default-match-function (candidate) + "Check if `helm-pattern' match CANDIDATE. +Default function to match candidates according to `helm-pattern'." + (string-match helm-pattern candidate)) + + +;;; Fuzzy matching +;; +;; +(defvar helm--fuzzy-regexp-cache (make-hash-table :test 'eq)) +(defun helm--fuzzy-match-maybe-set-pattern () + ;; Computing helm-pattern with helm--mapconcat-pattern + ;; is costly, so cache it once time for all and reuse it + ;; until pattern change. + (when helm--in-fuzzy + (let ((fun (if (string-match "\\`\\^" helm-pattern) + #'identity + #'helm--mapconcat-pattern))) + (clrhash helm--fuzzy-regexp-cache) + ;; FIXME: Splitted part are not handled here, + ;; I must compute them in `helm-search-match-part' + ;; when negation and in-buffer are used. + (if (string-match "\\`!" helm-pattern) + (puthash 'helm-pattern + (if (> (length helm-pattern) 1) + (list (funcall fun (substring helm-pattern 1 2)) + (funcall fun (substring helm-pattern 1))) + '("" "")) + helm--fuzzy-regexp-cache) + (puthash 'helm-pattern + (if (> (length helm-pattern) 0) + (list (funcall fun (substring helm-pattern 0 1)) + (funcall fun helm-pattern)) + '("" "")) + helm--fuzzy-regexp-cache))))) + +(defun helm-fuzzy-match (candidate) + "Check if `helm-pattern' fuzzy matches CANDIDATE. +This function is used with sources built with `helm-source-sync'." + (unless (string-match " " helm-pattern) + ;; When pattern have one or more spaces, let + ;; multi-match doing the job with no fuzzy matching.[1] + (let ((regexp (cadr (gethash 'helm-pattern helm--fuzzy-regexp-cache)))) + (if (string-match "\\`!" helm-pattern) + (not (string-match regexp candidate)) + (string-match regexp candidate))))) + +(defun helm-fuzzy-search (pattern) + "Same as `helm-fuzzy-match' but for sources built with +`helm-source-in-buffer'." + (unless (string-match " " helm-pattern) + ;; Same as in `helm-fuzzy-match' ref[1]. + (let* ((regexps (gethash 'helm-pattern helm--fuzzy-regexp-cache)) + (partial-regexp (car regexps)) + (regexp (cadr regexps))) + (if (string-match "\\`!" pattern) + ;; Don't try to search here, just return + ;; the position of line and go ahead, + ;; letting `helm-search-match-part' checking if + ;; pattern match against this line. + (prog1 (list (point-at-bol) (point-at-eol)) + (forward-line 1)) + ;; We could use here directly `re-search-forward' + ;; on the regexp produced by `helm--mapconcat-pattern', + ;; but it is very slow because emacs have to do an incredible + ;; amount of loops to match e.g "[^f]*f[^o]*o..." in the whole buffer, + ;; more the regexp is long more the amount of loops grow. + ;; (Probably leading to a max-lisp-eval-depth error if both + ;; regexp and buffer are too big) + ;; So just search the first bit of pattern e.g "[^f]*f", and + ;; then search the corresponding line with the whole regexp, + ;; which increase dramatically the speed of the search. + (cl-loop while (re-search-forward partial-regexp nil t) + for bol = (point-at-bol) + for eol = (point-at-eol) + if (progn (goto-char bol) + (re-search-forward regexp eol t)) + do (goto-char eol) and return t + else do (goto-char eol) + finally return nil))))) + +(defun helm-score-candidate-for-pattern (candidate pattern) + "Assign score to CANDIDATE according to PATTERN. +Score is calculated for contiguous matches found with PATTERN. +Score is 100 (maximum) if PATTERN is fully matched in CANDIDATE. +One point bonus is added to score when PATTERN prefix matches +CANDIDATE. Contiguous matches get a coefficient of 2." + (let* ((cand (if (stringp candidate) + candidate (helm-stringify candidate))) + (pat-lookup (helm--collect-pairs-in-string pattern)) + (str-lookup (helm--collect-pairs-in-string cand)) + (bonus (cond ((equal (car pat-lookup) (car str-lookup)) + 1) + ((and (null pat-lookup) ; length = 1 + (string= pattern (substring cand 0 1))) + 150) + (t 0))) + (bonus1 (and (string-match (concat "\\<" (regexp-quote pattern) "\\>") + cand) + 100))) + (+ bonus (or bonus1 + ;; Give a coefficient of 2 for contiguous matches. + ;; That's mean that "wiaaaki" will not take precedence + ;; on "aaawiki" when matching on "wiki" even if "wiaaaki" + ;; starts by "wi". + (* (length (cl-nintersection + pat-lookup str-lookup :test 'equal)) + 2))))) + +(defun helm-fuzzy-matching-default-sort-fn-1 (candidates &optional use-real basename preserve-tie-order) + "The transformer for sorting candidates in fuzzy matching. +It sorts on the display part by default. + +Sorts CANDIDATES by their scores as calculated by +`helm-score-candidate-for-pattern'. Set USE-REAL to non-`nil' to +sort on the real part. If BASENAME is non-nil assume we are +completing filenames and sort on basename of candidates. If +PRESERVE-TIE-ORDER is nil, ties in scores are sorted by length of +the candidates." + (if (string= helm-pattern "") + candidates + (let ((table-scr (make-hash-table :test 'equal))) + (sort candidates + (lambda (s1 s2) + ;; Score and measure the length on real or display part of candidate + ;; according to `use-real'. + (let* ((real-or-disp-fn (if use-real #'cdr #'car)) + (cand1 (cond ((and basename (consp s1)) + (helm-basename (funcall real-or-disp-fn s1))) + ((consp s1) (funcall real-or-disp-fn s1)) + (basename (helm-basename s1)) + (t s1))) + (cand2 (cond ((and basename (consp s2)) + (helm-basename (funcall real-or-disp-fn s2))) + ((consp s2) (funcall real-or-disp-fn s2)) + (basename (helm-basename s2)) + (t s2))) + (data1 (or (gethash cand1 table-scr) + (puthash cand1 + (list (helm-score-candidate-for-pattern + cand1 helm-pattern) + (length (helm-stringify cand1))) + table-scr))) + (data2 (or (gethash cand2 table-scr) + (puthash cand2 + (list (helm-score-candidate-for-pattern + cand2 helm-pattern) + (length (helm-stringify cand2))) + table-scr))) + (len1 (cadr data1)) + (len2 (cadr data2)) + (scr1 (car data1)) + (scr2 (car data2))) + (cond ((= scr1 scr2) + (unless preserve-tie-order + (< len1 len2))) + ((> scr1 scr2))))))))) + +(defun helm-fuzzy-matching-default-sort-fn (candidates _source) + "Default `filtered-candidate-transformer' to sort candidates in fuzzy matching." + (helm-fuzzy-matching-default-sort-fn-1 candidates)) + +(defun helm-fuzzy-matching-sort-fn-preserve-ties-order (candidates _source) + "`filtered-candidate-transformer' to sort candidates in fuzzy matching, preserving order of ties. +The default function, `helm-fuzzy-matching-default-sort-fn', +sorts ties by length, shortest first. This function may be more +useful when the order of the candidates is meaningful, e.g. with +`recentf-list'." + (helm-fuzzy-matching-default-sort-fn-1 candidates nil t)) + +(defun helm--maybe-get-migemo-pattern (pattern) + (or (and helm-migemo-mode + (assoc-default pattern helm-mm--previous-migemo-info)) + pattern)) + +(defun helm-fuzzy-default-highlight-match (candidate) + "The default function to highlight matches in fuzzy matching. +Highlight elements in CANDIDATE matching `helm-pattern' according +to the matching method in use." + (if (string= helm-pattern "") + ;; Empty pattern, do nothing. + candidate + ;; Else start highlighting. + (let* ((pair (and (consp candidate) candidate)) + (display (helm-stringify (if pair (car pair) candidate))) + (real (cdr pair)) + (regex (helm--maybe-get-migemo-pattern helm-pattern)) + (mp (pcase (get-text-property 0 'match-part display) + ((pred (string= display)) nil) + (str str))) + (count 0) + beg-str end-str) + ;; Extract all parts of display keeping original properties. + (when (and mp (string-match (regexp-quote mp) display)) + (setq beg-str (substring display 0 (match-beginning 0)) + end-str (substring display (match-end 0) (length display)) + mp (substring display (match-beginning 0) (match-end 0)))) + (with-temp-buffer + ;; Insert the whole display part and remove non--match-part + ;; to keep their original face properties. + (insert (propertize (or mp display) 'read-only nil)) ; Fix (#1176) + (goto-char (point-min)) + (condition-case nil + (progn + ;; Try first matching against whole pattern. + (while (re-search-forward regex nil t) + (cl-incf count) + (helm-add-face-text-properties + (match-beginning 0) (match-end 0) 'helm-match)) + ;; If no matches start matching against multiples or fuzzy matches. + (when (zerop count) + (cl-loop with multi-match = (string-match-p " " helm-pattern) + with patterns = (if multi-match + (mapcar #'helm--maybe-get-migemo-pattern + (helm-mm-split-pattern helm-pattern)) + (split-string helm-pattern "" t)) + for p in patterns + ;; Multi matches (regexps patterns). + if multi-match do + (progn + (while (re-search-forward p nil t) + (helm-add-face-text-properties + (match-beginning 0) (match-end 0) + 'helm-match)) + (goto-char (point-min))) + ;; Fuzzy matches (literal patterns). + else do + (when (search-forward p nil t) + (helm-add-face-text-properties + (match-beginning 0) (match-end 0) + 'helm-match))))) + (invalid-regexp nil)) + ;; Now replace the original match-part with the part + ;; with face properties added. + (setq display (if mp (concat beg-str (buffer-string) end-str) (buffer-string)))) + (if real (cons display real) display)))) + +(defun helm-fuzzy-highlight-matches (candidates _source) + "The filtered-candidate-transformer function to highlight fuzzy matches. +See `helm-fuzzy-default-highlight-match'." + (cl-loop for c in candidates + collect (funcall helm-fuzzy-matching-highlight-fn c))) + + +;;; Matching candidates +;; +;; +(defun helm-match-functions (source) + (let ((matchfns (or (assoc-default 'match source) + (assoc-default 'match-strict source) + #'helm-default-match-function))) + (if (and (listp matchfns) (not (functionp matchfns))) + matchfns (list matchfns)))) + +(defun helm-search-functions (source) + (let ((searchfns (assoc-default 'search source))) + (if (and (listp searchfns) (not (functionp searchfns))) + searchfns (list searchfns)))) + +(defun helm-take-first-elements (seq n) + "Return the first N elements of SEQ if SEQ is longer than N. +It is used for narrowing list of candidates to the +`helm-candidate-number-limit'." + (if (> (length seq) n) (cl-subseq seq 0 n) seq)) + +(defun helm-match-from-candidates (cands matchfns match-part-fn limit source) + (condition-case-unless-debug err + (cl-loop with hash = (make-hash-table :test 'equal) + with allow-dups = (assq 'allow-dups source) + with case-fold-search = (helm-set-case-fold-search) + with count = 0 + for iter from 1 + for fn in matchfns + when (< count limit) nconc + (cl-loop for c in cands + for dup = (gethash c hash) + while (< count limit) + for target = (helm-candidate-get-display c) + for prop-part = (get-text-property 0 'match-part target) + for part = (and match-part-fn + (or prop-part + (funcall match-part-fn target))) + ;; When allowing dups check if DUP + ;; have been already found in previous loop + ;; by comparing its value with ITER. + when (and (or (and allow-dups dup (= dup iter)) + (null dup)) + (condition-case nil + (funcall fn (or part target)) + (invalid-regexp nil))) + do + (progn + ;; Give as value the iteration number of + ;; inner loop to be able to check if + ;; the duplicate have not been found in previous loop. + (puthash c iter hash) + (helm--maybe-process-filter-one-by-one-candidate c source) + (cl-incf count)) + ;; Filter out nil candidates maybe returned by + ;; `helm--maybe-process-filter-one-by-one-candidate'. + and when c collect + (if (and part (not prop-part)) + (if (consp c) + (cons (propertize target 'match-part part) (cdr c)) + (propertize c 'match-part part)) + c))) + (error (unless (eq (car err) 'invalid-regexp) ; Always ignore regexps errors. + (helm-log-error "helm-match-from-candidates in source `%s': %s %s" + (assoc-default 'name source) (car err) (cdr err))) + nil))) + +(defun helm-compute-matches (source) + "Start computing candidates in SOURCE." + (save-current-buffer + (let ((matchfns (helm-match-functions source)) + (matchpartfn (assoc-default 'match-part source)) + (helm--source-name (assoc-default 'name source)) + (helm-current-source source) + (limit (helm-candidate-number-limit source)) + (helm-pattern (helm-process-pattern-transformer + helm-pattern source))) + (helm--fuzzy-match-maybe-set-pattern) + ;; If source have a `filtered-candidate-transformer' attr + ;; Filter candidates with this func, otherwise just compute + ;; candidates. + ;; NOTE that this next block of code is returning nil on async sources, + ;; the candidates being processed directly in `helm-output-filter' + ;; process-filter. + (helm-process-filtered-candidate-transformer + ;; Using in-buffer method or helm-pattern is empty + ;; in this case compute all candidates. + (if (or (equal helm-pattern "") + (helm--candidates-in-buffer-p matchfns)) + ;; Compute all candidates up to LIMIT. + ;; one-by-one are computed here only for sources that + ;; display a list of candidates even with an empty + ;; pattern. + (helm--initialize-one-by-one-candidates + (helm-take-first-elements + (helm-get-cached-candidates source) limit) + source) + ;; Compute candidates according to pattern with their match + ;; fns. + ;; one-by-one filtered candidates are computed during the + ;; execution of next loop in `helm-match-from-candidates'. + (helm-match-from-candidates + (helm-get-cached-candidates source) matchfns matchpartfn limit source)) + source)))) + +(defun helm--candidates-in-buffer-p (matchfns) + (equal matchfns '(identity))) + +(defun helm-render-source (source matches) + "Display MATCHES from SOURCE according to its settings." + (helm-log "Source name = %S" (assoc-default 'name source)) + (when matches + (helm-insert-header-from-source source) + (cl-loop with separate = nil + with start = (point) + with singleline = (null (assq 'multiline source)) + for m in matches + for count from 1 + if singleline + do (helm-insert-match m 'insert count source) + else + do (progn + (if separate + (helm-insert-candidate-separator) + (setq separate t)) + (helm-insert-match m 'insert count source)) + finally (and (null singleline) + (put-text-property start (point) + 'helm-multiline t))))) + +(defmacro helm--maybe-use-while-no-input (&rest body) + "Wrap BODY in `helm-while-no-input' unless initializing a remote connection." + `(progn + (if (and (file-remote-p helm-pattern) + (not (file-remote-p helm-pattern nil t))) + ;; Tramp will ask for passwd, don't use `helm-while-no-input'. + ,@body + (helm-log "Using here `helm-while-no-input'") + (helm-while-no-input ,@body)))) + +(defun helm--collect-matches (src-list) + "Returns a list of matches for each source in SRC-LIST. + +The resulting value is a list of lists, e.g ((a b c) (c d) (e f)) or +\(nil nil nil) for three sources when no matches found, however this +function can be interrupted by new input and in this case returns a +plain `nil' i.e not (nil), in this case `helm-update' is not rendering +the source, keeping previous candidates in display." + (let ((matches (helm--maybe-use-while-no-input + (cl-loop for src in src-list + collect (helm-compute-matches src))))) + (unless (eq matches t) matches))) + + +;;; Case fold search +;; +;; +(cl-defun helm-set-case-fold-search (&optional (pattern helm-pattern)) + "Used to set the value of `case-fold-search' in helm. +Return t or nil depending on the value of `helm-case-fold-search' +and `helm-pattern'." + (let ((helm-case-fold-search + (helm-aif (assq 'case-fold-search (helm-get-current-source)) + (cdr it) + helm-case-fold-search)) + ;; Only parse basename for filenames + ;; to avoid setting case sensitivity + ;; when expanded directories contains upcase + ;; characters. + (bn-or-pattern (if (string-match "[~/]*" pattern) + (helm-basename pattern) + pattern))) + (helm-set-case-fold-search-1 bn-or-pattern))) + +(defun helm-set-case-fold-search-1 (pattern) + (cl-case helm-case-fold-search + (smart (let ((case-fold-search nil)) + (if (string-match "[[:upper:]]" pattern) nil t))) + (t helm-case-fold-search))) + + +;;; Helm update +;; +(defun helm-update (&optional preselect source candidates) + "Update candidates list in `helm-buffer' based on `helm-pattern'. +Argument PRESELECT is a string or regexp used to move selection +to a particular place after finishing update. +When SOURCE is provided update mode-line for this source, otherwise +the current source will be used. +Argument CANDIDATES when provided is used to redisplay these candidates +without recomputing them, it should be a list of lists." + (helm-log "Start updating") + (helm-kill-async-processes) + ;; When persistent action have been called + ;; we have two windows even with `helm-full-frame'. + ;; So go back to one window when updating if `helm-full-frame' + ;; is non-`nil'. + (when (with-helm-buffer + (and helm-onewindow-p + ;; We are not displaying helm-buffer in a frame and + ;; helm-window is already displayed. + (not helm--buffer-in-new-frame-p) + (helm-window) + (not (helm-action-window)))) + (with-helm-window (delete-other-windows))) + (with-current-buffer (helm-buffer-get) + (set (make-local-variable 'helm-input-local) helm-pattern) + (unwind-protect + (let (sources matches) + ;; Collect sources ready to be updated. + (setq sources + (cl-loop for src in helm-sources + when (helm-update-source-p src) + collect src)) + ;; When no sources to update erase buffer + ;; to avoid duplication of header and candidates + ;; when next chunk of update will arrive, + ;; otherwise the buffer is erased AFTER [1] the results + ;; are computed. + (unless sources (erase-buffer)) + ;; Compute matches without rendering the sources. + ;; This prevent the helm-buffer flickering when constantly + ;; updating. + (helm-log "Matches: %S" + (setq matches (or candidates (helm--collect-matches sources)))) + ;; If computing matches finished and is not interrupted + ;; erase the helm-buffer and render results (Fix #1157). + (when matches ;; nil only when interrupted by helm-while-no-input. + (erase-buffer) ; [1] + (cl-loop for src in sources + for mtc in matches + do (helm-render-source src mtc)) + ;; Move to first line only when there is matches + ;; to avoid cursor moving upside down (issue #1703). + (helm--update-move-first-line) + (helm--reset-update-flag))) + ;; When there is only one async source, update mode-line and run + ;; `helm-after-update-hook' in `helm-output-filter--post-process', + ;; when there is more than one source, update mode-line and run + ;; `helm-after-update-hook' now even if an async source is + ;; present and running in BG. + (let ((src (or source (helm-get-current-source)))) + (unless (assq 'candidates-process src) + (and src (helm-display-mode-line src 'force)) + (helm-log-run-hook 'helm-after-update-hook))) + (when preselect + (helm-log "Update preselect candidate %s" preselect) + (if (helm-window) + (with-helm-window (helm-preselect preselect source)) + (helm-preselect preselect source))) + (setq helm--force-updating-p nil)) + (helm-log "end update"))) + +(defun helm-update-source-p (source) + "Whether SOURCE needs updating or not." + (let ((len (string-width + (if (assq 'multimatch source) + ;; Don't count spaces entered when using + ;; multi-match. + (replace-regexp-in-string " " "" helm-pattern) + helm-pattern)))) + (and (or (not helm-source-filter) + (member (assoc-default 'name source) helm-source-filter)) + (>= len + (helm-aif (assq 'requires-pattern source) (or (cdr it) 1) 0)) + ;; Entering repeatedly these strings (*, ?) takes 100% CPU + ;; and hang emacs on MacOs preventing deleting backward those + ;; characters (issue #1802). + (not (string-match-p "\\`[*]+\\'" helm-pattern)) + ;; These incomplete regexps hang helm forever + ;; so defer update. Maybe replace spaces quoted when using + ;; multi-match. + (not (member (replace-regexp-in-string "\\s\\ " " " helm-pattern) + helm-update-blacklist-regexps))))) + +(defun helm--update-move-first-line () + "Goto first line of `helm-buffer'." + (goto-char (point-min)) + (if (helm-window) + (helm-move-selection-common :where 'line + :direction 'next + :follow t) + (forward-line 1) + (helm-mark-current-line) + (helm-follow-execute-persistent-action-maybe))) + +(cl-defun helm-force-update (&optional preselect (recenter t)) + "Force recalculation and update of candidates. + +Unlike `helm-update', this function re-evaluates `init' and +`update' attributes when present; also `helm-candidate-cache' is +not reinitialized, meaning candidates are not recomputed unless +pattern has changed. + +Selection is preserved to current candidate if it still exists after +update or moved to PRESELECT, if specified. +The helm-window is recentered at the end when RECENTER is `t' +which is the default, RECENTER can be also a number in this case it is +passed as argument to `recenter'." + (with-helm-buffer + (let* ((source (helm-get-current-source)) + (selection (helm-aif (helm-get-selection nil t source) + (regexp-quote it)))) + (setq helm--force-updating-p t) + (mapc 'helm-force-update--reinit helm-sources) + (helm-update (or preselect selection) source) + (when (and (helm-window) recenter) + (with-helm-window + (recenter (and (numberp recenter) recenter))))))) + +(defun helm-refresh () + "Force recalculation and update of candidates." + (interactive) + (with-helm-alive-p + (helm-force-update))) +(put 'helm-refresh 'helm-only t) + +(defun helm-force-update--reinit (source) + "Reinit SOURCE by calling its update and init functions." + ;; When using a specific buffer as cache, don't kill it. + (helm-aif (and (null (bufferp (assoc-default + (helm-attr 'name source) + helm--candidate-buffer-alist))) + (helm-apply-functions-from-source + source 'helm-candidate-buffer)) + (kill-buffer it)) + (cl-dolist (attr '(update init)) + (helm-aif (assoc-default attr source) + (helm-apply-functions-from-source source it))) + (helm-remove-candidate-cache source)) + +(defun helm-redisplay-buffer () + "Redisplay candidates in `helm-buffer'. + +Candidates are not recomputed, only redisplayed after modifying the +whole list of candidates in each source with functions found in +`redisplay' attribute of current source. Note that candidates are +redisplayed with their display part with all properties included only. +This function is used in async sources to transform the whole list of +candidates from the sentinel functions (i.e when all candidates have +been computed) because other filters like `candidate-transformer' are +modifying only each chunk of candidates from process-filter as they +come in and not the whole list. Use this for e.g sorting the whole +list of async candidates once computed. +Note: To ensure redisplay is done in async sources after helm +reached `candidate-number-limit' you will have also to redisplay your +candidates from `helm-async-outer-limit-hook'." + (with-helm-buffer + (let ((get-cands (lambda (source) + (let ((fns (assoc-default 'redisplay source)) + candidates + helm-move-to-line-cycle-in-source + helm-allow-mouse) + (helm-goto-source source) + (helm-next-line) + (helm-awhile (condition-case-unless-debug nil + (and (not (helm-pos-header-line-p)) + (helm-get-selection + nil 'withprop source)) + (error nil)) + (push it candidates) + (when (save-excursion + (forward-line 1) (helm-end-of-source-p t)) + (cl-return nil)) + (helm-next-line)) + (helm-apply-functions-from-source + source fns (nreverse candidates))))) + (get-sources (lambda () + (let (sources helm-move-to-line-cycle-in-source) + (helm-awhile (helm-get-current-source) + (push it sources) + (when (save-excursion + (helm-move--end-of-source) + (forward-line 1) (eobp)) + (cl-return nil)) + (helm-next-source)) + (nreverse sources))))) + (goto-char (point-min)) + (helm-update nil (helm-get-current-source) + (cl-loop with sources = (funcall get-sources) + for s in helm-sources + for name = (assoc-default 'name s) collect + (when (cl-loop for src in sources thereis + (string= name + (assoc-default 'name src))) + (funcall get-cands s))))))) + +(defun helm-remove-candidate-cache (source) + "Remove SOURCE from `helm-candidate-cache'." + (remhash (assoc-default 'name source) helm-candidate-cache)) + +(defun helm-insert-match (match insert-function &optional num source) + "Insert MATCH into `helm-buffer' with INSERT-FUNCTION. +If MATCH is a cons cell then insert the car as display with +the cdr stored as real value in a `helm-realvalue' text property. +Args NUM and SOURCE are also stored as text property when specified as +respectively `helm-cand-num' and `helm-cur-source'." + (let ((start (point-at-bol (point))) + (dispvalue (helm-candidate-get-display match)) + (realvalue (cdr-safe match)) + (map (when helm-allow-mouse (make-sparse-keymap))) + (inhibit-read-only t) + end) + (when (and (stringp dispvalue) + (not (zerop (length dispvalue)))) + (funcall insert-function dispvalue) + (setq end (point-at-eol)) + ;; Some strings may handle another keymap prop. + (remove-text-properties start end '(keymap nil)) + (put-text-property start end 'read-only nil) + ;; Some sources with candidates-in-buffer have already added + ;; 'helm-realvalue property when creating candidate buffer. + (unless (get-text-property start 'helm-realvalue) + (and realvalue + (put-text-property start end + 'helm-realvalue realvalue))) + (when map + (define-key map [mouse-1] 'helm-mouse-select-candidate) + (define-key map [mouse-2] 'ignore) + (define-key map [mouse-3] 'helm-select-action) + (add-text-properties + start end + `(mouse-face highlight + keymap ,map + help-echo ,(pcase (get-text-property start 'help-echo) + ((and it (pred stringp)) + (concat it "\nmouse-1: select candidate\nmouse-3: menu actions")) + (_ "mouse-1: select candidate\nmouse-3: menu actions"))))) + (when num + (put-text-property start end 'helm-cand-num num)) + (when source + (put-text-property start end 'helm-cur-source source)) + (funcall insert-function "\n")))) + +(defun helm--mouse-reset-selection-help-echo () + (let* ((inhibit-read-only t) + (start (overlay-start helm-selection-overlay)) + (end (overlay-end helm-selection-overlay)) + (help-echo (get-text-property start 'help-echo))) + (when (and (stringp help-echo) + (string-match "mouse-2: execute action" help-echo)) + (put-text-property + start end + 'help-echo (replace-match "mouse-1: select candidate" + t t help-echo))))) + +(defun helm--bind-mouse-for-selection (pos) + (let ((inhibit-read-only t) + (map (get-text-property pos 'keymap))) + (when map + (define-key map [mouse-2] 'helm-maybe-exit-minibuffer) + (put-text-property + helm-selection-point + (overlay-end helm-selection-overlay) + 'help-echo (helm-aif (get-text-property pos 'help-echo) + (if (and (stringp it) + (string-match "mouse-1: select candidate" it)) + (replace-match "mouse-2: execute action" t t it) + "mouse-2: execute action\nmouse-3: menu actions") + "mouse-2: execute action\nmouse-3: menu actions"))))) + +(defun helm-mouse-select-candidate (event) + (interactive "e") + (let* ((window (posn-window (event-end event))) + (pos (posn-point (event-end event)))) + (unwind-protect + (with-current-buffer (window-buffer window) + (if (and (helm-action-window) + (eql window (get-buffer-window helm-buffer))) + (user-error "selection in helm-window not available while selecting action") + (helm--mouse-reset-selection-help-echo) + (goto-char pos) + (when (helm-pos-multiline-p) + (goto-char (or (helm-get-previous-candidate-separator-pos) + (helm-get-previous-header-pos))) + (forward-line 1))) + (helm-mark-current-line) + (helm-follow-execute-persistent-action-maybe)) + (select-window (minibuffer-window)) + (set-buffer (window-buffer window))))) +(put 'helm-mouse-select-candidate 'helm-only t) + +(defun helm-insert-header-from-source (source) + "Insert SOURCE name in `helm-buffer' header. +Maybe insert, by overlay, additional info after the source name +if SOURCE has header-name attribute." + (let ((name (assoc-default 'name source))) + (helm-insert-header + name + (helm-aif (assoc-default 'header-name source) + (helm-apply-functions-from-source source it name))))) + +(defun helm-insert-header (name &optional display-string) + "Insert header of source NAME into the helm buffer. +If DISPLAY-STRING is non-`nil' and a string value then display +this additional info after the source name by overlay." + (unless (bobp) + (let ((start (point))) + (insert "\n") + (put-text-property start (point) 'helm-header-separator t))) + (let ((start (point))) + (insert name) + (put-text-property (point-at-bol) + (point-at-eol) 'helm-header t) + (when display-string + (overlay-put (make-overlay (point-at-bol) (point-at-eol)) + 'display display-string)) + (insert "\n") + (put-text-property start (point) 'face 'helm-source-header))) + +(defun helm-insert-candidate-separator () + "Insert separator of candidates into the helm buffer." + (insert (propertize helm-candidate-separator 'face 'helm-separator)) + (put-text-property (point-at-bol) + (point-at-eol) 'helm-candidate-separator t) + (insert "\n")) + + +;;; Async process +;; +(defun helm-output-filter (process output-string) + "The `process-filter' function for helm async sources." + (with-helm-quittable + (helm-output-filter-1 (assoc process helm-async-processes) output-string))) + +(defun helm-output-filter-1 (process-assoc output-string) + (helm-log "output-string = %S" output-string) + (with-current-buffer helm-buffer + (let ((source (cdr process-assoc))) + (save-excursion + (helm-aif (assoc-default 'insertion-marker source) + (goto-char it) + (goto-char (point-max)) + (helm-insert-header-from-source source) + (setcdr process-assoc + (append source `((insertion-marker . ,(point-marker)))))) + (helm-output-filter--process-source + (car process-assoc) output-string source + (helm-candidate-number-limit source)))) + (helm-output-filter--post-process))) + +(defun helm-output-filter--process-source (process output-string source limit) + (cl-dolist (candidate (helm-transform-candidates + (helm-output-filter--collect-candidates + (split-string output-string "\n") + (assq 'incomplete-line source)) + source t)) + (setq candidate + (helm--maybe-process-filter-one-by-one-candidate candidate source)) + (if (assq 'multiline source) + (let ((start (point))) + (helm-insert-candidate-separator) + (helm-insert-match candidate 'insert-before-markers + (1+ (cdr (assq 'item-count source))) + source) + (put-text-property start (point) 'helm-multiline t)) + (helm-insert-match candidate 'insert-before-markers + (1+ (cdr (assq 'item-count source))) + source)) + (cl-incf (cdr (assq 'item-count source))) + (when (>= (assoc-default 'item-count source) limit) + (helm-kill-async-process process) + (helm-log-run-hook 'helm-async-outer-limit-hook) + (cl-return)))) + +(defun helm-output-filter--collect-candidates (lines incomplete-line-info) + "Collect LINES maybe completing the truncated first and last lines." + ;; The output of process may come in chunks of any size, so the last + ;; line of LINES could be truncated, this truncated line is stored + ;; in INCOMPLETE-LINE-INFO to be concatenated with the first + ;; incomplete line of the next arriving chunk. INCOMPLETE-LINE-INFO + ;; is an attribute of source; it is created with an empty string + ;; when the source is computed => (incomplete-line . "") + (helm-log "incomplete-line-info = %S" (cdr incomplete-line-info)) + (butlast + (cl-loop for line in lines + ;; On start `incomplete-line-info' value is empty string. + for newline = (helm-aif (cdr incomplete-line-info) + (prog1 + (concat it line) + (setcdr incomplete-line-info nil)) + line) + collect newline + ;; Store last incomplete line (last chunk truncated) until + ;; new output arrives. Previously storing 'line' in + ;; incomplete-line-info assumed output was truncated in + ;; only two chunks. But output could be large and + ;; truncated in more than two chunks. Therefore store + ;; 'newline' to contain the previous chunks (Issue #1187). + finally do (setcdr incomplete-line-info newline)))) + +(defun helm-output-filter--post-process () + (helm-aif (get-buffer-window helm-buffer 'visible) + (with-selected-window it + (helm-skip-noncandidate-line 'next) + (helm-mark-current-line nil 'nomouse) + ;; FIXME Don't hardcode follow delay. + (helm-follow-execute-persistent-action-maybe 0.5) + (helm-display-mode-line (helm-get-current-source)) + (helm-log-run-hook 'helm-after-update-hook) + (helm--reset-update-flag)))) + +(defun helm-process-deferred-sentinel-hook (process event file) + "Defer remote processes in sentinels. +Meant to be called at the beginning of a sentinel process +function." + (when (and (not (zerop helm-tramp-connection-min-time-diff)) + (string= event "finished\n") + (or (file-remote-p file) + ;; `helm-suspend-update-flag' + ;; is non-`nil' here only during a + ;; running process, this will never be called + ;; when user set it explicitly with `C-!'. + helm-suspend-update-flag)) + (setq helm-suspend-update-flag t) + ;; Kill the process but don't delete entry in + ;; `helm-async-processes'. + (helm-kill-async-process process) + ;; When tramp opens the same connection twice in less than 5 + ;; seconds, it throws 'suppress, which calls the real-handler on + ;; the main "Emacs". To avoid this [1] helm waits for 5 seconds + ;; before updates yet allows user input during this delay. [1] In + ;; recent Emacs versions, this has been fixed so tramp returns nil + ;; in such conditions. Note: `tramp-connection-min-time-diff' cannot + ;; have values less than 5 seconds otherwise the process dies. + (run-at-time helm-tramp-connection-min-time-diff + nil (lambda () + (when helm-alive-p ; Don't run timer fn after quit. + (setq helm-suspend-update-flag nil) + (helm-check-minibuffer-input)))))) + +(defun helm-kill-async-processes () + "Kill all asynchronous processes registered in `helm-async-processes'." + (while helm-async-processes + (helm-kill-async-process (caar helm-async-processes)) + (setq helm-async-processes (cdr helm-async-processes)))) + +(defun helm-kill-async-process (process) + "Stop output from `helm-output-filter' and kill associated PROCESS." + (set-process-filter process nil) + (delete-process process)) + + +;;; Actions +;; +(defun helm-execute-selection-action () + "Execute current action." + (helm-log-run-hook 'helm-before-action-hook) + ;; Position can be change when `helm-current-buffer' + ;; is split, so jump to this position before executing action. + (helm-current-position 'restore) + (unwind-protect + (prog1 (helm-execute-selection-action-1) + (helm-log-run-hook 'helm-after-action-hook)) + (setq helm--executing-helm-action nil))) + +(defun helm-execute-selection-action-1 (&optional + selection action + preserve-saved-action) + "Execute ACTION on current SELECTION. +If PRESERVE-SAVED-ACTION is non-`nil', then save the action." + (helm-log "executing action") + (setq action (helm-get-default-action + (or action + helm-saved-action + (if (get-buffer helm-action-buffer) + (helm-get-selection helm-action-buffer) + (helm-get-actions-from-current-source))))) + (helm-aif (and (not helm-in-persistent-action) + (get-buffer helm-action-buffer)) + (kill-buffer it)) + (let ((source (or helm-saved-current-source + (helm-get-current-source))) + non-essential) + (setq selection (helm-coerce-selection + (or selection + helm-saved-selection + (helm-get-selection nil nil source) + (and (assq 'accept-empty source) "")) + source)) + (unless preserve-saved-action (setq helm-saved-action nil)) + (when (and selection action) (funcall action selection)))) + +(defun helm-coerce-selection (selection source) + "Apply coerce attribute function to SELECTION in SOURCE. +Coerce source with coerce function." + (helm-aif (assoc-default 'coerce source) + (helm-apply-functions-from-source source it selection) + selection)) + +(defun helm-get-default-action (action) + "Get the first ACTION value of action list in source." + (if (and (listp action) (not (functionp action))) + (cdar action) + action)) + +(defun helm--show-action-window-other-window-p () + (and helm-show-action-window-other-window + (or helm-always-two-windows + helm--buffer-in-new-frame-p) + (eq helm-split-window-state 'vertical))) + +(defun helm-select-action () + "Select an action for the currently selected candidate. +If action buffer is selected, back to the helm buffer." + (interactive) + (with-helm-alive-p + (let ((src (helm-get-current-source))) + (helm-log-run-hook 'helm-select-action-hook) + (setq helm-saved-selection (helm-get-selection nil nil src)) + (with-selected-frame (with-helm-window (selected-frame)) + (prog1 + (helm-acond ((get-buffer-window helm-action-buffer 'visible) + (set-window-buffer it helm-buffer) + (helm--set-action-prompt 'restore) + (when (helm--show-action-window-other-window-p) + (delete-window it)) + (kill-buffer helm-action-buffer) + (setq helm-saved-selection nil) + (helm-set-pattern helm-input 'noupdate)) + (helm-saved-selection + (setq helm-saved-current-source src) + (let ((actions (helm-get-actions-from-current-source src)) + helm-onewindow-p) + (if (functionp actions) + (message "Sole action: %s" + (if (or (consp actions) + (byte-code-function-p actions)) + "Anonymous" actions)) + (helm-show-action-buffer actions) + ;; Be sure the minibuffer is entirely deleted (#907). + (helm--delete-minibuffer-contents-from "") + (helm--set-action-prompt) + (helm-check-minibuffer-input)))) + (t (message "No Actions available"))) + (helm-display-mode-line (helm-get-current-source)) + (run-hooks 'helm-window-configuration-hook)))))) +(put 'helm-select-action 'helm-only t) + +(defun helm--set-action-prompt (&optional restore) + (with-selected-window (minibuffer-window) + (let ((inhibit-read-only t) + (props '(face minibuffer-prompt + field t + read-only t + rear-nonsticky t + front-sticky t)) + (prt (if restore helm--prompt helm--action-prompt))) + (erase-buffer) + (insert (apply #'propertize prt props))))) + +(defun helm-show-action-buffer (actions) + (with-current-buffer (get-buffer-create helm-action-buffer) + (erase-buffer) + (buffer-disable-undo) + (setq cursor-type nil) + (set-window-buffer (if (helm--show-action-window-other-window-p) + (split-window (get-buffer-window helm-buffer) + nil helm-show-action-window-other-window) + (get-buffer-window helm-buffer)) + helm-action-buffer) + (set (make-local-variable 'helm-sources) + (list + (helm-build-sync-source "Actions" + :volatile t + :nomark t + :persistent-action #'ignore + :persistent-help "DoNothing" + :keymap 'helm-map + :candidates actions + :mode-line '("Action(s)" "\\\\[helm-select-action]:BackToCands RET/f1/f2/fn:NthAct") + :candidate-transformer + (lambda (candidates) + (cl-loop for (i . j) in candidates + for count from 1 + collect + (cons (concat (cond ((> count 12) + " ") + ((< count 10) + (format "[f%s] " count)) + (t (format "[f%s] " count))) + (propertize i 'face 'helm-action)) + j))) + :candidate-number-limit nil))) + (set (make-local-variable 'helm-source-filter) nil) + (set (make-local-variable 'helm-selection-overlay) nil) + (helm-initialize-overlays helm-action-buffer))) + + +;; Selection of candidates + +(defun helm-display-source-at-screen-top-maybe (unit) + "Display source at the top of screen when UNIT value is 'source. +Returns nil for any other value of UNIT." + (when (and helm-display-source-at-screen-top (eq unit 'source)) + (set-window-start (selected-window) + (save-excursion (forward-line -1) (point))))) + +(defun helm-skip-noncandidate-line (direction) + "Skip source header or candidates separator when going in DIRECTION. +DIRECTION is either 'next or 'previous. +Same as `helm-skip-header-and-separator-line' but ensure +point is moved to the right place when at bob or eob." + (helm-skip-header-and-separator-line direction) + (and (bobp) (forward-line 1)) ; Skip first header. + (and (eobp) (forward-line -1))) ; Avoid last empty line. + +(defun helm-skip-header-and-separator-line (direction) + "Skip source header or candidate separator when going to next/previous line. +DIRECTION is either 'next or 'previous." + (let ((fn (cl-ecase direction + (next 'eobp) + (previous 'bobp)))) + (while (and (not (funcall fn)) + (or (helm-pos-header-line-p) + (helm-pos-candidate-separator-p))) + (forward-line (if (and (eq direction 'previous) + (not (eq (point-at-bol) (point-min)))) + -1 1))))) + +(defun helm-display-mode-line (source &optional force) + "Set up mode line and header line for `helm-buffer'. + +SOURCE is a Helm source object. + +Optional argument FORCE forces redisplay of the Helm buffer's +mode and header lines." + (set (make-local-variable 'helm-mode-line-string) + (helm-interpret-value (or (and (listp source) ; Check if source is empty. + (assoc-default 'mode-line source)) + (default-value 'helm-mode-line-string)) + source)) + (let ((follow (and (or (helm-follow-mode-p source) + (and helm-follow-mode-persistent + (member (assoc-default 'name source) + helm-source-names-using-follow))) + " (HF)")) + (marked (and helm-marked-candidates + (cl-loop with cur-name = (assoc-default 'name source) + for c in helm-marked-candidates + for name = (assoc-default 'name (car c)) + when (string= name cur-name) + collect c)))) + ;; Setup mode-line. + (if helm-mode-line-string + (setq mode-line-format + `(:propertize + (" " mode-line-buffer-identification " " + (:eval (format "L%-3d" (helm-candidate-number-at-point))) + ,follow + " " + (:eval ,(and marked + (propertize + (format "M%d" (length marked)) + 'face 'helm-visible-mark))) + (:eval (when ,helm--mode-line-display-prefarg + (let ((arg (prefix-numeric-value + (or prefix-arg current-prefix-arg)))) + (unless (= arg 1) + (propertize (format " [prefarg:%s]" arg) + 'face 'helm-prefarg))))) + " " + (:eval (with-helm-buffer + (helm-show-candidate-number + (car-safe helm-mode-line-string)))) + " " helm--mode-line-string-real " " + (:eval (make-string (window-width) ? ))) + keymap (keymap (mode-line keymap + (mouse-1 . ignore) + (down-mouse-1 . ignore) + (drag-mouse-1 . ignore) + (mouse-2 . ignore) + (down-mouse-2 . ignore) + (drag-mouse-2 . ignore) + (mouse-3 . ignore) + (down-mouse-3 . ignore) + (drag-mouse-3 . ignore)))) + helm--mode-line-string-real + (substitute-command-keys (if (listp helm-mode-line-string) + (cadr helm-mode-line-string) + helm-mode-line-string))) + (setq mode-line-format (default-value 'mode-line-format))) + ;; Setup header-line. + (cond (helm-echo-input-in-header-line + (setq force t) + (helm--set-header-line)) + (helm-display-header-line + (let ((hlstr (helm-interpret-value + (and (listp source) + (assoc-default 'header-line source)) + source)) + (endstr (make-string (window-width) ? ))) + (setq header-line-format + (propertize (concat " " hlstr endstr) + 'face 'helm-header)))))) + (when force (force-mode-line-update))) + +(defun helm--set-header-line (&optional update) + (with-selected-window (minibuffer-window) + (when helm-display-header-line + ;; Prevent cursor movement over the overlay displaying + ;; persistent-help in minibuffer (issue #2108). + (setq-local disable-point-adjustment t)) + (let* ((beg (save-excursion (vertical-motion 0 (helm-window)) (point))) + (end (save-excursion (end-of-visual-line) (point))) + ;; The visual line where the cursor is. + (cont (buffer-substring beg end)) + (pref (propertize + " " + 'display (if (string-match-p (regexp-opt `(,helm--prompt + ,helm--action-prompt)) + cont) + `(space :width ,helm-header-line-space-before-prompt) + (propertize + "->" + 'face 'helm-header-line-left-margin)))) + (pos (- (point) beg))) + ;; Increment pos each time we find a "%" up to current-pos (#1648). + (cl-loop for c across (buffer-substring-no-properties beg (point)) + when (eql c ?%) do (cl-incf pos)) + ;; Increment pos when cursor is on a "%" to make it visible in header-line + ;; i.e "%%|" and not "%|%" (#1649). + (when (eql (char-after) ?%) (setq pos (1+ pos))) + (setq cont (replace-regexp-in-string "%" "%%" cont)) + (with-helm-buffer + (setq header-line-format (concat pref cont " ")) + (funcall helm-default-prompt-display-function pos) + (when update (force-mode-line-update)))))) + +(defun helm-set-default-prompt-display (pos) + (put-text-property + ;; Increment pos to handle the space before prompt (i.e `pref'). + (+ 1 pos) (+ 2 pos) + 'face + ;; Don't just use cursor face, this can hide the current character. + (list :inverse-video t + :foreground (face-background 'cursor) + :background (face-background 'default)) + header-line-format)) + +(defun helm-exchange-minibuffer-and-header-line () + "Display minibuffer in header-line and vice versa for current helm session. + +This is a toggle command." + (interactive) + (with-helm-window + (add-hook 'helm-minibuffer-set-up-hook 'helm-hide-minibuffer-maybe) + (setq-local helm-echo-input-in-header-line + (not helm-echo-input-in-header-line)) + (with-selected-window (minibuffer-window) + (if (with-helm-buffer helm-echo-input-in-header-line) + (helm-hide-minibuffer-maybe) + (remove-overlays) + (setq cursor-type t))) + (helm-display-mode-line (helm-get-current-source) t))) +(put 'helm-exchange-minibuffer-and-header-line 'helm-only t) + +(defun helm--update-header-line () + ;; This should be used in `post-command-hook', + ;; nowhere else. + (when (with-helm-buffer helm-echo-input-in-header-line) + (helm--set-header-line t))) + +(defun helm-hide-minibuffer-maybe () + "Hide minibuffer contents in a Helm session. +This function should normally go to `helm-minibuffer-set-up-hook'. +It has no effect if `helm-echo-input-in-header-line' is nil." + (when (with-helm-buffer helm-echo-input-in-header-line) + (let ((ov (make-overlay (point-min) (point-max) nil nil t))) + (overlay-put ov 'window (selected-window)) + (helm-aif (and helm-display-header-line + (helm-attr 'persistent-help)) + (progn + (overlay-put ov 'display + (truncate-string-to-width + (substitute-command-keys + (concat "\\\\[helm-execute-persistent-action]: " + (format "%s (keeping session)" it))) + (- (window-width) 1))) + (overlay-put ov 'face 'helm-header)) + (overlay-put ov 'face (let ((bg-color (face-background 'default nil))) + `(:background ,bg-color :foreground ,bg-color)))) + + (setq cursor-type nil)))) + +(defun helm-show-candidate-number (&optional name) + "Used to display candidate number in mode-line. +You can specify NAME of candidates e.g \"Buffers\" otherwise +it is \"Candidate\(s\)\" by default." + (when helm-alive-p + (unless (helm-empty-source-p) + ;; Build a fixed width string when candidate-number < 1000 + (let* ((cand-name (or name "Candidate(s)")) + (width (length (format "[999 %s]" cand-name)))) + (propertize + (format (concat "%-" (number-to-string width) "s") + (format "[%s %s]" + (helm-get-candidate-number 'in-current-source) + cand-name)) + 'face (if helm-suspend-update-flag + 'helm-candidate-number-suspended + 'helm-candidate-number)))))) + +(cl-defun helm-move-selection-common (&key where direction (follow t)) + "Move the selection marker to a new position. +Position is determined by WHERE and DIRECTION. +Key arg WHERE can be one of: + - line + - page + - edge + - source +Key arg DIRECTION can be one of: + - previous + - next + - A source or a source name when used with :WHERE 'source." + (let ((move-func (cl-case where + (line (cl-ecase direction + (previous 'helm-move--previous-line-fn) + (next 'helm-move--next-line-fn))) + (page (cl-ecase direction + (previous 'helm-move--previous-page-fn) + (next 'helm-move--next-page-fn))) + (edge (cl-ecase direction + (previous 'helm-move--beginning-of-buffer-fn) + (next 'helm-move--end-of-buffer-fn))) + (source (cl-case direction + (previous 'helm-move--previous-source-fn) + (next 'helm-move--next-source-fn) + (t (lambda () ; A source is passed as DIRECTION arg. + (helm-move--goto-source-fn direction)))))))) + (unless (or (helm-empty-buffer-p (helm-buffer-get)) + (not (helm-window))) + (with-helm-window + (when helm-allow-mouse + (helm--mouse-reset-selection-help-echo)) + (helm-log-run-hook 'helm-move-selection-before-hook) + (funcall move-func) + (and (memq direction '(next previous)) + (helm-skip-noncandidate-line direction)) + (when (helm-pos-multiline-p) + (helm-move--beginning-of-multiline-candidate)) + (helm-display-source-at-screen-top-maybe where) + (helm-mark-current-line) + (when follow + (helm-follow-execute-persistent-action-maybe)) + (helm-display-mode-line (helm-get-current-source)) + (helm-log-run-hook 'helm-move-selection-after-hook))))) + +(defun helm-move--beginning-of-multiline-candidate () + (let ((header-pos (helm-get-previous-header-pos)) + (separator-pos (helm-get-previous-candidate-separator-pos))) + (when header-pos + (goto-char (if (or (null separator-pos) + (< separator-pos header-pos)) + header-pos + separator-pos)) + (forward-line 1)))) + +(defun helm-move--previous-multi-line-fn () + (forward-line -1) + (unless (helm-pos-header-line-p) + (helm-skip-header-and-separator-line 'previous) + (helm-move--beginning-of-multiline-candidate))) + +(defun helm-move--previous-line-fn () + (if (not (helm-pos-multiline-p)) + (forward-line -1) + (helm-move--previous-multi-line-fn)) + (when (and helm-move-to-line-cycle-in-source + (helm-pos-header-line-p)) + (forward-line 1) + (helm-move--end-of-source) + ;; We are at end of helm-buffer + ;; check if last candidate is a multiline candidate + ;; and jump to it + (when (and (eobp) + (save-excursion (forward-line -1) (helm-pos-multiline-p))) + (helm-move--previous-multi-line-fn)))) + +(defun helm-move--next-multi-line-fn () + (let ((header-pos (helm-get-next-header-pos)) + (separator-pos (helm-get-next-candidate-separator-pos))) + (cond ((and separator-pos + (or (null header-pos) (< separator-pos header-pos))) + (goto-char separator-pos)) + (header-pos + (goto-char header-pos))))) + +(defun helm-move--next-line-fn () + (if (not (helm-pos-multiline-p)) + (forward-line 1) + (helm-move--next-multi-line-fn)) + (when (and helm-move-to-line-cycle-in-source + (or (save-excursion (and (helm-pos-multiline-p) + (goto-char (overlay-end + helm-selection-overlay)) + (helm-end-of-source-p t))) + (helm-end-of-source-p t))) + (helm-move--beginning-of-source))) + +(defun helm-move--previous-page-fn () + (condition-case nil + (scroll-down) + (beginning-of-buffer (goto-char (point-min))))) + +(defun helm-move--next-page-fn () + (condition-case nil + (scroll-up) + (end-of-buffer (goto-char (point-max))))) + +(defun helm-move--beginning-of-buffer-fn () + (goto-char (point-min))) + +(defun helm-move--end-of-buffer-fn () + (goto-char (point-max))) + +(defun helm-move--end-of-source () + (helm-aif (helm-get-next-header-pos) + (progn (goto-char it) (forward-line -2)) + (goto-char (point-max)))) + +(defun helm-move--beginning-of-source () + (helm-aif (helm-get-previous-header-pos) + (progn (goto-char it) + (forward-line 1)) + (goto-char (point-min)))) + +(defun helm-move--previous-source-fn () + (forward-line -1) + (if (bobp) + (goto-char (point-max)) + (helm-skip-header-and-separator-line 'previous)) + (goto-char (helm-get-previous-header-pos)) + (forward-line 1)) + +(defun helm-move--next-source-fn () + (goto-char (or (and (not (save-excursion + (forward-line 1) (eobp))) + ;; Empty source at eob are just + ;; not displayed unless they are dummy. + ;; Issue #1117. + (helm-get-next-header-pos)) + (point-min)))) + +(defun helm-move--goto-source-fn (source-or-name) + (goto-char (point-min)) + (let ((name (if (stringp source-or-name) + source-or-name + (assoc-default 'name source-or-name)))) + (if (or (null name) (string= name "")) + (forward-line 1) + (condition-case err + (while (not (string= name (helm-current-line-contents))) + (goto-char (helm-get-next-header-pos))) + (error (helm-log "%S" err)))))) + +(defun helm-candidate-number-at-point () + (if helm-alive-p + (with-helm-buffer + (or (get-text-property (point) 'helm-cand-num) 1)) + (or (get-text-property (point) 'helm-cand-num) 1))) + +(defun helm--next-or-previous-line (direction &optional arg) + ;; Be sure to not use this in non--interactives calls. + (let ((helm-move-to-line-cycle-in-source + (and helm-move-to-line-cycle-in-source arg))) + (if (and arg (> arg 1)) + (cl-loop with pos = (helm-candidate-number-at-point) + with cand-num = (helm-get-candidate-number t) + with iter = (min arg (if (eq direction 'next) + (- cand-num pos) + (min arg (1- pos)))) + for count from 1 + while (<= count iter) + do + (helm-move-selection-common :where 'line :direction direction)) + (helm-move-selection-common :where 'line :direction direction)))) + +(defun helm-previous-line (&optional arg) + "Move selection to the ARG previous line(s). +Same behavior as `helm-next-line' when called with a numeric prefix arg." + (interactive "p") + (with-helm-alive-p + (helm--next-or-previous-line 'previous arg))) +(put 'helm-previous-line 'helm-only t) + +(defun helm-next-line (&optional arg) + "Move selection to the next ARG line(s). +When numeric prefix arg is > than the number of candidates, then +move to the last candidate of current source (i.e. don't move to +next source)." + (interactive "p") + (with-helm-alive-p + (helm--next-or-previous-line 'next arg))) +(put 'helm-next-line 'helm-only t) + +(defun helm-previous-page () + "Move selection back with a pageful." + (interactive) + (with-helm-alive-p + (helm-move-selection-common :where 'page :direction 'previous))) +(put 'helm-previous-page 'helm-only t) + +(defun helm-next-page () + "Move selection forward with a pageful." + (interactive) + (with-helm-alive-p + (helm-move-selection-common :where 'page :direction 'next))) +(put 'helm-next-page 'helm-only t) + +(defun helm-beginning-of-buffer () + "Move selection at the top." + (interactive) + (with-helm-alive-p + (helm-move-selection-common :where 'edge :direction 'previous))) +(put 'helm-beginning-of-buffer 'helm-only t) + +(defun helm-end-of-buffer () + "Move selection at the bottom." + (interactive) + (with-helm-alive-p + (helm-move-selection-common :where 'edge :direction 'next))) +(put 'helm-end-of-buffer 'helm-only t) + +(defun helm-previous-source () + "Move selection to the previous source." + (interactive) + (with-helm-alive-p + (helm-move-selection-common :where 'source :direction 'previous))) +(put 'helm-previous-source 'helm-only t) + +(defun helm-next-source () + "Move selection to the next source." + (interactive) + (with-helm-alive-p + (helm-move-selection-common :where 'source :direction 'next))) +(put 'helm-next-source 'helm-only t) + +(defun helm-goto-source (&optional source-or-name) + "Move the selection to the source named SOURCE-OR-NAME. + +If SOURCE-OR-NAME is empty string or nil go to the first candidate of +first source." + (helm-move-selection-common :where 'source :direction source-or-name)) + +(defun helm--follow-action (arg) + (let ((helm--temp-follow-flag t) ; Needed in HFF. + (in-follow-mode (helm-follow-mode-p))) + ;; When follow-mode is already enabled, just go to next or + ;; previous line. + (when (or (eq last-command 'helm-follow-action-forward) + (eq last-command 'helm-follow-action-backward) + (eq last-command 'helm-execute-persistent-action) + in-follow-mode) + (if (> arg 0) + (helm-move-selection-common :where 'line + :direction 'next + :follow nil) + (helm-move-selection-common :where 'line + :direction 'previous + :follow nil))) + (unless in-follow-mode + (helm-execute-persistent-action)))) + +(defun helm-follow-action-forward () + "Go to next line and execute persistent action." + (interactive) + (with-helm-alive-p (helm--follow-action 1))) +(put 'helm-follow-action-forward 'helm-only t) + +(defun helm-follow-action-backward () + "Go to previous line and execute persistent action." + (interactive) + (with-helm-alive-p (helm--follow-action -1))) +(put 'helm-follow-action-backward 'helm-only t) + +(defun helm-mark-current-line (&optional resumep nomouse) + "Move `helm-selection-overlay' to current line. +When RESUMEP is non nil move overlay to `helm-selection-point'. +When NOMOUSE is specified do not set mouse bindings. + +Note that selection is unrelated to visible marks used for marking +candidates." + (with-helm-buffer + (when resumep + (goto-char helm-selection-point)) + (move-overlay + helm-selection-overlay (point-at-bol) + (if (helm-pos-multiline-p) + (let ((header-pos (helm-get-next-header-pos)) + (separator-pos (helm-get-next-candidate-separator-pos))) + (or (and (null header-pos) separator-pos) + (and header-pos separator-pos + (< separator-pos header-pos) + separator-pos) + header-pos + (point-max))) + (1+ (point-at-eol)))) + (setq helm-selection-point (overlay-start helm-selection-overlay)) + (when (and helm-allow-mouse (null nomouse)) + (helm--bind-mouse-for-selection helm-selection-point)))) + +(defun helm-confirm-and-exit-minibuffer () + "Maybe ask for confirmation when exiting helm. +It is similar to `minibuffer-complete-and-exit' adapted to helm. +If `minibuffer-completion-confirm' value is 'confirm, +send minibuffer confirm message and exit on next hit. +If `minibuffer-completion-confirm' value is t, +don't exit and send message 'no match'." + (interactive) + (with-helm-alive-p + (if (and (helm--updating-p) + (null helm--reading-passwd-or-string)) + (progn (message "[Display not ready]") + (sit-for 0.5) (message nil)) + (let* ((src (helm-get-current-source)) + (empty-buffer-p (with-current-buffer helm-buffer + (eq (point-min) (point-max)))) + (sel (helm-get-selection nil nil src)) + (unknown (and (not empty-buffer-p) + (string= (get-text-property + 0 'display + (helm-get-selection nil 'withprop src)) + "[?]")))) + (cond ((and (or empty-buffer-p unknown) + (eq minibuffer-completion-confirm 'confirm)) + (setq helm-minibuffer-confirm-state + 'confirm) + (setq minibuffer-completion-confirm nil) + (minibuffer-message " [confirm]")) + ((and (or empty-buffer-p + (unless (if minibuffer-completing-file-name + (and minibuffer-completion-predicate + (funcall minibuffer-completion-predicate sel)) + (and (stringp sel) + ;; SEL may be a cons cell when helm-comp-read + ;; is called directly with a collection composed + ;; of (display . real) and real is a cons cell. + (try-completion sel minibuffer-completion-table + minibuffer-completion-predicate))) + unknown)) + (eq minibuffer-completion-confirm t)) + (minibuffer-message " [No match]")) + (t + (setq helm-minibuffer-confirm-state nil) + (helm-exit-minibuffer))))))) +(put 'helm-confirm-and-exit-minibuffer 'helm-only t) + +(add-hook 'helm-after-update-hook 'helm-confirm-and-exit-hook) + +(defun helm-confirm-and-exit-hook () + "Restore `minibuffer-completion-confirm' when helm update." + (unless (or (eq minibuffer-completion-confirm t) + (not helm-minibuffer-confirm-state)) + (setq minibuffer-completion-confirm + helm-minibuffer-confirm-state))) + +(defun helm-read-string (prompt &optional initial-input history + default-value inherit-input-method) + "Same as `read-string' but for reading string from a helm session." + (let ((helm--reading-passwd-or-string t)) + (read-string + prompt initial-input history default-value inherit-input-method))) + +(defun helm--updating-p () + ;; helm timer is between two cycles. + ;; IOW `helm-check-minibuffer-input' haven't yet compared input + ;; and `helm-pattern'. + (or (not (equal (minibuffer-contents) helm-pattern)) + ;; `helm-check-minibuffer-input' have launched `helm-update'. + helm--in-update)) + +(defun helm-maybe-exit-minibuffer () + (interactive) + (with-helm-alive-p + (if (and (helm--updating-p) + (null helm--reading-passwd-or-string)) + (progn + (message "[Display not ready]") + (sit-for 0.5) (message nil) + (helm-update)) + (helm-exit-minibuffer)))) +(put 'helm-maybe-exit-minibuffer 'helm-only t) + +(defun helm-exit-minibuffer () + "Select the current candidate by exiting the minibuffer." + (unless helm-current-prefix-arg + (setq helm-current-prefix-arg current-prefix-arg)) + (setq helm-exit-status 0) + (helm-log-run-hook 'helm-exit-minibuffer-hook) + (exit-minibuffer)) + +(defun helm-keyboard-quit () + "Quit minibuffer in helm. +If action buffer is displayed, kill it." + (interactive) + (with-helm-alive-p + (when (get-buffer-window helm-action-buffer 'visible) + (kill-buffer helm-action-buffer)) + (setq helm-exit-status 1) + (abort-recursive-edit))) +(put 'helm-keyboard-quit 'helm-only t) + +(defun helm-get-next-header-pos () + "Return the position of the next header from point." + (next-single-property-change (point) 'helm-header)) + +(defun helm-get-previous-header-pos () + "Return the position of the previous header from point." + (previous-single-property-change (point) 'helm-header)) + +(defun helm-pos-multiline-p () + "Return non-`nil' if the current position is in the multiline source region." + (get-text-property (point) 'helm-multiline)) + +(defun helm-get-next-candidate-separator-pos () + "Return the position of the next candidate separator from point." + (let ((hp (helm-get-next-header-pos))) + (helm-aif (next-single-property-change (point) 'helm-candidate-separator) + (or + ;; Be sure we don't catch + ;; the separator of next source. + (and hp (< it hp) it) + ;; The separator found is in next source + ;; we are at last cand, so use the header pos. + (and hp (< hp it) hp) + ;; A single source, just try next separator. + it)))) + +(defun helm-get-previous-candidate-separator-pos () + "Return the position of the previous candidate separator from point." + (previous-single-property-change (point) 'helm-candidate-separator)) + +(defun helm-pos-header-line-p () + "Return t if the current line is a header line." + (or (get-text-property (point-at-bol) 'helm-header) + (get-text-property (point-at-bol) 'helm-header-separator))) + +(defun helm-pos-candidate-separator-p () + "Return t if the current line is a candidate separator." + (get-text-property (point-at-bol) 'helm-candidate-separator)) + + +;;; Debugging +;; +;; +(defun helm-debug-output () + "Show all helm-related variables at this time." + (interactive) + (with-helm-alive-p + (helm-help-internal " *Helm Debug*" 'helm-debug-output-function))) +(put 'helm-debug-output 'helm-only t) + +(defun helm-debug-output-function (&optional vars) + (message "Calculating all helm-related values...") + (insert "If you debug some variables or forms, set `helm-debug-variables' +to a list of forms.\n\n") + (cl-dolist (v (or vars + helm-debug-variables + (apropos-internal "^helm-" 'boundp))) + (insert "** " + (pp-to-string v) "\n" + (pp-to-string (with-current-buffer helm-buffer (eval v))) "\n")) + (message "Calculating all helm-related values...Done")) + +(defun helm-enable-or-switch-to-debug () + "First hit enable helm debugging, second hit switch to debug buffer." + (interactive) + (with-helm-alive-p + (if helm-debug + (helm-run-after-exit + #'helm-debug-open-last-log) + (setq helm-debug t) + (with-helm-buffer (setq truncate-lines nil)) + (message "Debugging enabled")))) +(put 'helm-enable-or-switch-to-debug 'helm-only t) + + +;; Misc +(defun helm-kill-buffer-hook () + "Remove tick entry from `helm-tick-hash' and remove buffer from +`helm-buffers' when killing a buffer." + (cl-loop for key being the hash-keys in helm-tick-hash + if (string-match (format "^%s/" (regexp-quote (buffer-name))) key) + do (remhash key helm-tick-hash)) + (setq helm-buffers (remove (buffer-name) helm-buffers))) +(add-hook 'kill-buffer-hook 'helm-kill-buffer-hook) + +(defun helm-preselect (candidate-or-regexp &optional source) + "Move selection to CANDIDATE-OR-REGEXP on Helm start. + +CANDIDATE-OR-REGEXP can be a: + +- String +- Cons cell of two strings +- Nullary function, which moves to a candidate + +When CANDIDATE-OR-REGEXP is a cons cell, tries moving to first +element of the cons cell, then the second, and so on. This allows +selection of duplicate candidates after the first. + +Optional argument SOURCE is a Helm source object." + (with-helm-buffer + (when candidate-or-regexp + (if source + (helm-goto-source source) + (goto-char (point-min)) + (forward-line 1)) + (if (functionp candidate-or-regexp) + (funcall candidate-or-regexp) + (let ((start (point)) mp) + (helm-awhile (if (consp candidate-or-regexp) + (and (re-search-forward (car candidate-or-regexp) nil t) + (re-search-forward (cdr candidate-or-regexp) nil t)) + (re-search-forward candidate-or-regexp nil t)) + ;; If search fall on an header line continue loop + ;; until it match or fail (Issue #1509). + (unless (helm-pos-header-line-p) (cl-return (setq mp it)))) + (goto-char (or mp start))))) + (forward-line 0) ; Avoid scrolling right on long lines. + (when (helm-pos-multiline-p) + (helm-move--beginning-of-multiline-candidate)) + (when (helm-pos-header-line-p) (forward-line 1)) + (when helm-allow-mouse + (helm--mouse-reset-selection-help-echo)) + (helm-mark-current-line) + (helm-display-mode-line (or source (helm-get-current-source))) + (helm-log-run-hook 'helm-after-preselection-hook))) + +(defun helm-delete-current-selection () + "Delete the currently selected item." + (with-helm-window + (cond ((helm-pos-multiline-p) + (helm-aif (helm-get-next-candidate-separator-pos) + (delete-region (point-at-bol) + (1+ (progn (goto-char it) (point-at-eol)))) + ;; last candidate + (goto-char (helm-get-previous-candidate-separator-pos)) + (delete-region (point-at-bol) (point-max))) + (when (helm-end-of-source-p) + (goto-char (or (helm-get-previous-candidate-separator-pos) + (point-min))) + (forward-line 1))) + (t + (delete-region (point-at-bol) (1+ (point-at-eol))) + (when (helm-end-of-source-p t) + (let ((headp (save-excursion + (forward-line -1) + (not (helm-pos-header-line-p))))) + (and headp (forward-line -1)))))) + (unless (helm-end-of-source-p t) + (helm-mark-current-line)))) + +(defun helm-end-of-source-1 (n at-point) + (save-excursion + (if (and (helm-pos-multiline-p) (null at-point)) + (null (helm-get-next-candidate-separator-pos)) + (forward-line (if at-point 0 n)) + (or (eq (point-at-bol) (point-at-eol)) + (helm-pos-header-line-p) + (if (< n 0) (bobp) (eobp)))))) + +(defun helm-end-of-source-p (&optional at-point) + "Return non-`nil' if we are at eob or end of source." + (helm-end-of-source-1 1 at-point)) + +(defun helm-beginning-of-source-p (&optional at-point) + "Return non-`nil' if we are at bob or beginning of source." + (helm-end-of-source-1 -1 at-point)) + +(defun helm--edit-current-selection-internal (func) + (with-helm-window + (forward-line 0) + (let ((realvalue (get-text-property (point) 'helm-realvalue)) + (multiline (get-text-property (point) 'helm-multiline))) + (funcall func) + (forward-line 0) + (and realvalue + (put-text-property (point) (point-at-eol) + 'helm-realvalue realvalue)) + (and multiline + (put-text-property (point) + (or (helm-get-next-candidate-separator-pos) + (point-max)) + 'helm-multiline multiline)) + (helm-mark-current-line)))) + +(defmacro helm-edit-current-selection (&rest forms) + "Evaluate FORMS at current selection in the helm buffer. +Used generally to modify current selection." + (declare (indent 0) (debug t)) + `(helm--edit-current-selection-internal + (lambda () ,@forms))) + +(defun helm--delete-minibuffer-contents-from (from-str) + ;; Giving an empty string value to FROM-STR delete all. + (let ((input (minibuffer-contents))) + (helm-reset-yank-point) + (if (> (length input) 0) + ;; minibuffer is not empty, delete contents from end + ;; of FROM-STR and update. + (helm-set-pattern from-str) + ;; minibuffer is already empty, force update. + (helm-force-update)))) + +(defun helm-delete-minibuffer-contents (&optional arg) + "Delete minibuffer contents. +When `helm-delete-minibuffer-contents-from-point' is non-`nil', +delete minibuffer contents from point instead of deleting all. +Giving a prefix arg reverses this behavior. +When at the end of minibuffer, deletes all." + (interactive "P") + (let ((str (if helm-delete-minibuffer-contents-from-point + (if (or arg (eobp)) + "" (helm-minibuffer-completion-contents)) + (if (and arg (not (eobp))) + (helm-minibuffer-completion-contents) "")))) + (helm--delete-minibuffer-contents-from str))) + + +;;; helm-source-in-buffer. +;; +(defun helm-candidates-in-buffer (&optional source) + "The top level function used to store candidates with `helm-source-in-buffer'. + +Candidates are stored in a buffer generated internally +by `helm-candidate-buffer' function. +Each candidate must be placed in one line. + +The buffer is created and fed in the init attribute function of helm. + +e.g: + + (helm-build-in-buffer-source \"test\" + :init (lambda () + (helm-init-candidates-in-buffer + 'global '(foo foa fob bar baz)))) + +A shortcut can be used to simplify: + + (helm-build-in-buffer-source \"test\" + :data '(foo foa fob bar baz)) + +By default, `helm' makes candidates by evaluating the +candidates function, then narrows them by `string-match' for each +candidate. + +But this is slow for large number of candidates. The new way is +to store all candidates in a buffer and then narrow +with `re-search-forward'. Search function is customizable by search +attribute. The important point is that buffer processing is MUCH +FASTER than string list processing and is the Emacs way. + +The init function writes all candidates to a newly-created +candidate buffer. The candidates buffer is created or specified +by `helm-candidate-buffer'. Candidates are stored in a line. + +The candidates function narrows all candidates, IOW creates a +subset of candidates dynamically. + +Class `helm-source-in-buffer' is implemented with three attributes: + + (candidates . helm-candidates-in-buffer) + (volatile) + (match identity) + +The volatile attribute is needed because `helm-candidates-in-buffer' +creates candidates dynamically and need to be called every +time `helm-pattern' changes. + +Because `helm-candidates-in-buffer' plays the role of `match' attribute +function, specifying `(match identity)' makes the source slightly faster. + +However if source contains `match-part' attribute, match is computed only +on part of candidate returned by the call of function provided by this attribute. +The function should have one arg, candidate, and return only +a specific part of candidate. + +To customize `helm-candidates-in-buffer' behavior, +use `search', `get-line' and `match-part' attributes." + (let ((src (or source (helm-get-current-source)))) + (helm-candidates-in-buffer-1 + (helm-candidate-buffer) + helm-pattern + (or (assoc-default 'get-line src) + #'buffer-substring-no-properties) + (or (assoc-default 'search src) + '(helm-candidates-in-buffer-search-default-fn)) + (helm-candidate-number-limit src) + (helm-attr 'match-part) + src))) + +(defun helm-candidates-in-buffer-search-default-fn (pattern) + "Search PATTERN with `re-search-forward' with bound and noerror args." + (condition-case _err + (re-search-forward pattern nil t) + (invalid-regexp nil))) + +(defun helm-candidates-in-buffer-1 (buffer pattern get-line-fn + search-fns limit + match-part-fn source) + "Return the list of candidates inserted in BUFFER matching PATTERN." + ;; buffer == nil when candidates buffer does not exist. + (when buffer + (with-current-buffer buffer + (let ((inhibit-point-motion-hooks t) + (start-point (1- (point-min)))) + (goto-char start-point) + (if (string= pattern "") + (helm-initial-candidates-from-candidate-buffer + get-line-fn limit) + (helm-search-from-candidate-buffer + pattern get-line-fn search-fns limit + start-point match-part-fn source)))))) + + +(defun helm-search-from-candidate-buffer (pattern get-line-fn search-fns + limit start-point match-part-fn source) + (let ((inhibit-read-only t)) + (helm--search-from-candidate-buffer-1 + (lambda () + (cl-loop with hash = (make-hash-table :test 'equal) + with allow-dups = (assq 'allow-dups source) + with case-fold-search = (helm-set-case-fold-search) + with count = 0 + for iter from 1 + for searcher in search-fns + do (progn + (goto-char start-point) + ;; The character at start-point is a newline, + ;; if pattern match it that's mean we are + ;; searching for newline in buffer, in this + ;; case skip this false line. + ;; See comment >>>[1] in + ;; `helm--search-from-candidate-buffer-1'. + (and (condition-case nil + (looking-at pattern) + (invalid-regexp nil)) + (forward-line 1))) + nconc + (cl-loop with pos-lst + while (and (setq pos-lst (funcall searcher pattern)) + (not (eobp)) + (< count limit)) + for cand = (apply get-line-fn + (if (and pos-lst (listp pos-lst)) + pos-lst + (list (point-at-bol) (point-at-eol)))) + when (and match-part-fn + (not (get-text-property 0 'match-part cand))) + do (setq cand + (propertize cand 'match-part (funcall match-part-fn cand))) + for dup = (gethash cand hash) + when (and (or (and allow-dups dup (= dup iter)) + (null dup)) + (or + ;; Always collect when cand is matched + ;; by searcher funcs and match-part attr + ;; is not present. + (and (not match-part-fn) + (not (consp pos-lst))) + ;; If match-part attr is present, or if SEARCHER fn + ;; returns a cons cell, collect PATTERN only if it + ;; match the part of CAND specified by + ;; the match-part func. + (helm-search-match-part cand pattern))) + do (progn + (puthash cand iter hash) + (helm--maybe-process-filter-one-by-one-candidate cand source) + (cl-incf count)) + and collect cand)))))) + +(defun helm-search-match-part (candidate pattern) + "Match PATTERN only on match-part property value of CANDIDATE. + +Because `helm-search-match-part' maybe called even if unspecified +in source (negation or fuzzy), the part to match fallback to the whole +candidate even if match-part haven't been computed by match-part-fn +and stored in the match-part property." + (let ((part (or (get-text-property 0 'match-part candidate) + candidate)) + (fuzzy-regexp (cadr (gethash 'helm-pattern helm--fuzzy-regexp-cache))) + (matchfn (if helm-migemo-mode + 'helm-mm-migemo-string-match 'string-match))) + (if (string-match " " pattern) + (cl-loop for i in (helm-mm-split-pattern pattern) always + (if (string-match "\\`!" i) + (not (funcall matchfn (substring i 1) part)) + (funcall matchfn i part))) + (if (string-match "\\`!" pattern) + (if helm--in-fuzzy + ;; Fuzzy regexp have already been + ;; computed with substring 1. + (not (string-match fuzzy-regexp part)) + (not (funcall matchfn (substring pattern 1) part))) + (funcall matchfn (if helm--in-fuzzy fuzzy-regexp pattern) part))))) + +(defun helm-initial-candidates-from-candidate-buffer (get-line-fn limit) + (delq nil (cl-loop for i from 1 to limit + until (eobp) + collect (funcall get-line-fn + (point-at-bol) (point-at-eol)) + do (forward-line 1)))) + +(defun helm--search-from-candidate-buffer-1 (search-fn) + ;; We are adding a newline at bob and at eol + ;; and removing these newlines afterward. + ;; This is a bad hack that should be removed. + ;; To avoid matching the empty line at first line + ;; when searching with e.g occur and "^$" just + ;; forward-line before searching (See >>>[1] above). + (goto-char (point-min)) + (insert "\n") + (goto-char (point-max)) + (insert "\n") + (unwind-protect + (funcall search-fn) + (goto-char (point-min)) + (delete-char 1) + (goto-char (1- (point-max))) + (delete-char 1) + (set-buffer-modified-p nil))) + +(defun helm-candidate-buffer (&optional buffer-spec) + "Register and return a buffer storing candidates of current source. + +This is used to initialize a buffer for storing candidates for a +candidates-in-buffer source, candidates will be searched in this +buffer and displayed in `helm-buffer'. +This should be used only in init functions, don't relay on this in +other places unless you know what you are doing. + +This function is still in public API only for backward compatibility, +you should use instead `helm-init-candidates-in-buffer' for +initializing your sources. + +Internally, this function is called without argument and returns the +buffer corresponding to current source i.e `helm--source-name' which +is available in only some places. + +Acceptable values of BUFFER-SPEC: + +- global (a symbol) + Create a new global candidates buffer, + named \" *helm candidates:SOURCE*\". + This is used by `helm-init-candidates-in-buffer' and it is + the most common usage of BUFFER-SPEC. + The buffer will be killed and recreated at each new helm-session. + +- local (a symbol) + Create a new local candidates buffer, + named \" *helm candidates:SOURCE*HELM-CURRENT-BUFFER\". + You may want to use this when you want to have a different buffer + each time source is used from a different `helm-current-buffer'. + The buffer is erased and refilled at each new session but not killed. + You probably don't want to use this value for BUFFER-SPEC. + +- nil (omit) + Only return the candidates buffer of current source if found. + +- A buffer + Register a buffer as a candidates buffer. + The buffer needs to exists, it is not created. + This allow you to use the buffer as a cache, it is faster because + the buffer is already drawn, but be careful when using this as you + may mangle your buffer depending what you write in your init(s) + function, IOW don't modify the contents of the buffer in init(s) + function but in a transformer. + The buffer is not erased nor deleted. + Generally it is safer to use a copy of buffer inserted + in a global or local buffer. + +If for some reasons a global buffer and a local buffer exist and are +belonging to the same source, the local buffer takes precedence on the +global one and is used instead. + +When forcing update only the global and local buffers are killed +before running again the init function." + (let ((global-bname (format " *helm candidates:%s*" + helm--source-name)) + (local-bname (format " *helm candidates:%s*%s" + helm--source-name + (buffer-name helm-current-buffer)))) + (when buffer-spec + ;; Register buffer in `helm--candidate-buffer-alist'. + ;; This is used only to retrieve buffer associated to current source + ;; when using named buffer as value of BUFFER-SPEC. + (setq helm--candidate-buffer-alist + (cons (cons helm--source-name buffer-spec) + (delete (assoc helm--source-name + helm--candidate-buffer-alist) + helm--candidate-buffer-alist))) + ;; When using global or local as value of CREATE-OR-BUFFER + ;; create the buffer global-bname or local-bname, otherwise + ;; reuse the named buffer. + (unless (bufferp buffer-spec) + ;; Global buffers are killed and recreated. + (and (eq buffer-spec 'global) + (buffer-live-p (get-buffer global-bname)) + (kill-buffer global-bname)) + ;; Create global or local buffer. + ;; Local buffer, once created are reused and a new one + ;; is created when `helm-current-buffer' change across sessions. + (with-current-buffer (get-buffer-create + (cl-ecase buffer-spec + (global global-bname) + (local local-bname))) + ;; We need a buffer not read-only to perhaps insert later + ;; text coming from read-only buffers (issue #1176). + (set (make-local-variable 'buffer-read-only) nil) + ;; Undo is automatically disabled in buffer names starting + ;; with a space, so no need to disable it. + (erase-buffer) + (font-lock-mode -1)))) + ;; Finally return the candidates buffer. + (helm-acond ((get-buffer local-bname)) + ((get-buffer global-bname)) + ((assoc-default helm--source-name helm--candidate-buffer-alist) + (and (or (stringp it) (bufferp it)) + (buffer-live-p (get-buffer it)) + it))))) + +(defun helm-init-candidates-in-buffer (buffer-spec data) + "Register BUFFER-SPEC with DATA for a helm candidates-in-buffer session. + +Arg BUFFER-SPEC can be a buffer-name (stringp), a buffer-spec object +\(bufferp), or a symbol, either 'local or 'global which is passed to +`helm-candidate-buffer'. +The most common usage of BUFFER-SPEC is 'global. + +Arg DATA can be either a list or a plain string. +Returns the resulting buffer. + +Use this in your init function to register a buffer for a +`helm-source-in-buffer' session and feed it with DATA. +You probably don't want to bother with this and use the :data slot +when initializing a source with `helm-source-in-buffer' class." + (declare (indent 1)) + (let ((caching (and (or (stringp buffer-spec) + (bufferp buffer-spec)) + (buffer-live-p (get-buffer buffer-spec)))) + (buf (helm-candidate-buffer + (if (or (stringp buffer-spec) + (bufferp buffer-spec)) + (get-buffer-create buffer-spec) + buffer-spec)))) ; a symbol 'global or 'local. + (unless caching + (with-current-buffer buf + (erase-buffer) + (cond ((listp data) + (insert (mapconcat (lambda (i) + (cond ((symbolp i) (symbol-name i)) + ((numberp i) (number-to-string i)) + (t i))) + data "\n"))) + ((stringp data) (insert data)))) + buf))) + + +;;; Resplit helm window +;; +;; +(defun helm-toggle-resplit-window () + "Toggle resplit helm window, vertically or horizontally." + (interactive) + (with-helm-alive-p + (if (= (length (window-list nil 1)) 2) + (progn + (when helm-prevent-escaping-from-minibuffer + (helm-prevent-switching-other-window :enabled nil)) + (unwind-protect + (with-helm-window + (cond ((or helm-full-frame (one-window-p t)) + (user-error "Attempt to resplit a single window")) + ((helm-action-window) + (user-error "Can't resplit while selecting actions")) + (t + (let ((before-height (window-height))) + (delete-window) + (set-window-buffer + (select-window + (if (= (window-height) before-height) ; initial split was horizontal. + ;; Split window vertically with `helm-buffer' placed + ;; on the good side according to actual value of + ;; `helm-split-window-default-side'. + (prog1 + (cond ((or (eq helm-split-window-default-side 'above) + (eq helm-split-window-default-side 'left)) + (split-window + (selected-window) nil 'above)) + (t (split-window-vertically))) + (setq helm-split-window-state 'vertical)) + ;; Split window vertically, same comment as above. + (setq helm-split-window-state 'horizontal) + (cond ((or (eq helm-split-window-default-side 'left) + (eq helm-split-window-default-side 'above)) + (split-window (selected-window) nil 'left)) + (t (split-window-horizontally))))) + helm-buffer)))) + (setq helm--window-side-state (helm--get-window-side-state))) + (when helm-prevent-escaping-from-minibuffer + (helm-prevent-switching-other-window :enabled t)))) + (error "current window configuration not suitable for splitting")))) +(put 'helm-toggle-resplit-window 'helm-only t) + +;; Utility: Resize helm window. +(defun helm-enlarge-window-1 (n) + "Enlarge or narrow helm window. +If N is positive enlarge, if negative narrow." + (unless helm-full-frame + (let ((horizontal-p (eq helm-split-window-state 'horizontal))) + (with-helm-window + (enlarge-window n horizontal-p))))) + +(defun helm-narrow-window () + "Narrow helm window." + (interactive) + (with-helm-alive-p + (helm-enlarge-window-1 -1))) +(put 'helm-narrow-window 'helm-only t) + +(defun helm-enlarge-window () + "Enlarge helm window." + (interactive) + (with-helm-alive-p + (helm-enlarge-window-1 1))) +(put 'helm-enlarge-window 'helm-only t) + +(defun helm-toggle-full-frame (&optional arg) + "Toggle helm-buffer full-frame view." + (interactive "p") + (cl-assert (null (helm-action-window)) + nil "Unable to toggle full frame from action window") + (when arg ; Called interactively + (cl-assert (null helm--buffer-in-new-frame-p) + nil "Can't toggle full frame when using helm own frame")) + (if (or helm-onewindow-p + (buffer-local-value 'helm-full-frame (get-buffer helm-buffer))) + (with-helm-window + (setq-local helm-full-frame nil) + (setq helm-onewindow-p nil) + (let ((split-window-preferred-function + helm-split-window-preferred-function)) + (switch-to-buffer helm-current-buffer) + (helm-display-buffer helm-buffer) + (select-window (minibuffer-window)))) + (with-helm-window + (delete-other-windows) + (setq-local helm-full-frame t) + (setq helm-onewindow-p t)))) +(put 'helm-toggle-full-frame 'helm-only t) + +(defun helm-swap-windows () + "Swap window holding `helm-buffer' with other window." + (interactive) + (with-helm-alive-p + (if (= (length (window-list nil 1)) 2) + (cond ((and helm-full-frame (one-window-p t)) + (user-error "Can't swap windows in a single window")) + ((helm-action-window) + (user-error "Can't resplit while selecting actions")) + (t + (let* ((w1 (helm-window)) + (split-state (eq helm-split-window-state 'horizontal)) + (w1size (window-total-size w1 split-state)) + (b1 (window-buffer w1)) ; helm-buffer + (s1 (window-start w1)) + (cur-frame (window-frame w1)) + (w2 (with-selected-window (helm-window) + ;; Don't try to display helm-buffer + ;; in a dedicated window. + (get-window-with-predicate + (lambda (w) (not (window-dedicated-p w))) + 1 cur-frame))) + (w2size (window-total-size w2 split-state)) + (b2 (window-buffer w2)) ; probably helm-current-buffer + (s2 (window-start w2)) + resize) + (with-selected-frame (window-frame w1) + (helm-replace-buffer-in-window w1 b1 b2) + (helm-replace-buffer-in-window w2 b2 b1) + (setq resize + (cond ( ;; helm-window is smaller than other window. + (< w1size w2size) + (- (- (max w2size w1size) + (min w2size w1size)))) + ( ;; helm-window is larger than other window. + (> w1size w2size) + (- (max w2size w1size) + (min w2size w1size))) + ( ;; windows have probably same size. + t nil))) + ;; Maybe resize the window holding helm-buffer. + (and resize (window-resize w2 resize split-state)) + (set-window-start w1 s2 t) + (set-window-start w2 s1 t)) + (setq helm--window-side-state (helm--get-window-side-state))))) + (error "current window configuration not suitable for splitting")))) +(put 'helm-swap-windows 'helm-only t) + +(defun helm--get-window-side-state () + "Return the position of `helm-window' from `helm-current-buffer'. +Possible values are 'left 'right 'below or 'above." + (let ((side-list '(left right below above))) + (cl-loop for side in side-list + thereis (and (equal (helm-window) + (window-in-direction + side (get-buffer-window helm-current-buffer t) + t)) + side)))) + +(defun helm-replace-buffer-in-window (window buffer1 buffer2) + "Replace BUFFER1 by BUFFER2 in WINDOW registering BUFFER1." + (when (get-buffer-window buffer1) + (unrecord-window-buffer window buffer1) + (set-window-buffer window buffer2))) + +;; Utility: select another action by key +(defun helm-select-nth-action (n) + "Select the N nth action for the currently selected candidate." + (let ((src (helm-get-current-source))) + (setq helm-saved-selection (helm-get-selection nil nil src)) + (unless helm-saved-selection + (error "Nothing is selected")) + (setq helm-saved-action + (helm-get-nth-action + n + (if (get-buffer-window helm-action-buffer 'visible) + (assoc-default 'candidates src) + (helm-get-actions-from-current-source src)))) + (helm-maybe-exit-minibuffer))) + +(defun helm-get-nth-action (n action) + (cond ((and (zerop n) (functionp action)) + action) + ((listp action) + (or (cdr (elt action n)) + (error "No such action"))) + ((and (functionp action) (< 0 n)) + (error "Sole action")) + (t + (error "Error in `helm-select-nth-action'")))) + +(defun helm-execute-selection-action-at-nth (linum) + "Execute default action on candidate at LINUM lines from selection." + (let ((prefarg current-prefix-arg)) + (if (>= linum 0) + (helm-next-line linum) + (helm-previous-line (lognot (1- linum)))) + (setq current-prefix-arg prefarg) + (helm-exit-minibuffer))) + +;;; Persistent Action +;; +(defun helm-initialize-persistent-action () + (set (make-local-variable 'helm-persistent-action-display-window) nil)) + +(cl-defun helm-execute-persistent-action (&optional attr split-onewindow) + "Perform the associated action ATTR without quitting helm. +Arg ATTR default will be `persistent-action' or `persistent-action-if' +if unspecified depending on what's found in source, but it can be +anything else. +In this case you have to add this new attribute to your source. +See `persistent-action' and `persistent-action-if' slot documentation +in `helm-source'. + +When `helm-full-frame' or SPLIT-ONEWINDOW are non-`nil', and +`helm-buffer' is displayed in only one window, the helm window is +split to display `helm-select-persistent-action-window' in other +window to maintain visibility." + (interactive) + (with-helm-alive-p + (let ((source (helm-get-current-source))) + (unless attr + (setq attr (or (car (assq 'persistent-action source)) + (car (assq 'persistent-action-if source))))) + (helm-log "executing persistent-action") + (let* ((selection (and source (helm-get-selection nil nil source))) + (attr-val (if (eq attr 'persistent-action-if) + (funcall (assoc-default attr source) selection) + (assoc-default attr source))) + ;; If attr value is a cons, use its car as persistent function + ;; and its car to decide if helm window should be splitted. + (fn (if (and (consp attr-val) + ;; maybe a lambda. + (not (functionp attr-val))) + (car attr-val) attr-val)) + (no-split (and (consp attr-val) + (not (functionp attr-val)) + (cdr attr-val))) + (cursor-in-echo-area t) + mode-line-in-non-selected-windows) + (progn + (when (and helm-onewindow-p (null no-split) + (null helm--buffer-in-new-frame-p)) + (helm-toggle-full-frame)) + (when (eq fn 'ignore) + (cl-return-from helm-execute-persistent-action nil)) + (when source + (with-helm-window + (save-selected-window + (if no-split + (helm-select-persistent-action-window) + (helm-select-persistent-action-window + (or split-onewindow helm-onewindow-p))) + (helm-log "current-buffer = %S" (current-buffer)) + (let ((helm-in-persistent-action t) + (same-window-regexps '(".")) + display-buffer-function pop-up-windows pop-up-frames + special-display-regexps special-display-buffer-names) + (helm-execute-selection-action-1 + selection (or fn (helm-get-actions-from-current-source source)) t) + (unless (helm-action-window) + (helm-log-run-hook 'helm-after-persistent-action-hook))) + ;; A typical case is when a persistent action delete + ;; the buffer already displayed in + ;; `helm-persistent-action-display-window' and `helm-full-frame' + ;; is enabled, we end up with the `helm-buffer' + ;; displayed in two windows. + (when (and helm-onewindow-p + (> (length (window-list)) 1) + (equal (buffer-name + (window-buffer + helm-persistent-action-display-window)) + (helm-buffer-get))) + (delete-other-windows)))))))))) +(put 'helm-execute-persistent-action 'helm-only t) + +(defun helm-persistent-action-display-window (&optional split-onewindow) + "Return the window that will be used for persistent action. +If SPLIT-ONEWINDOW is non-`nil' window is split in persistent action." + (with-helm-window + (let (next-win cur-win) + (setq helm-persistent-action-display-window + (cond ((and (window-live-p helm-persistent-action-display-window) + (not (member helm-persistent-action-display-window + (get-buffer-window-list helm-buffer)))) + helm-persistent-action-display-window) + ((and helm--buffer-in-new-frame-p helm-initial-frame) + (with-selected-frame helm-initial-frame (selected-window))) + (split-onewindow (split-window)) + ;; Fix Issue #2050 with dedicated window. + ((window-dedicated-p + (setq next-win (next-window (selected-window) 1))) + (with-helm-after-update-hook + (and (window-live-p helm-persistent-action-display-window) + (delete-window helm-persistent-action-display-window))) + (split-window)) + ((window-dedicated-p + (setq cur-win (get-buffer-window helm-current-buffer))) + (split-window)) + (cur-win) + (t next-win)))))) + +(defun helm-select-persistent-action-window (&optional split-onewindow) + "Select the window that will be used for persistent action. +See `helm-persistent-action-display-window' for how to use SPLIT-ONEWINDOW." + (select-window (get-buffer-window (helm-buffer-get))) + (prog1 + (select-window + (setq minibuffer-scroll-window + (helm-persistent-action-display-window split-onewindow))) + (helm-log "Selected window is %S" minibuffer-scroll-window))) + +;;; Scrolling - recentering +;; +;; +(defun helm-other-window-base (command &optional arg) + (let ((minibuffer-scroll-window + (helm-persistent-action-display-window))) + (funcall command (or arg helm-scroll-amount)))) + +(defun helm-scroll-other-window (&optional arg) + "Scroll other window upward ARG many lines. +When arg is not provided scroll `helm-scroll-amount' lines. +See `scroll-other-window'." + (interactive "P") + (with-helm-alive-p (helm-other-window-base 'scroll-other-window arg))) +(put 'helm-scroll-other-window 'helm-only t) + +(defun helm-scroll-other-window-down (&optional arg) + "Scroll other window downward ARG many lines. +When arg is not provided scroll `helm-scroll-amount' lines. +See `scroll-other-window-down'." + (interactive "P") + (with-helm-alive-p (helm-other-window-base 'scroll-other-window-down arg))) +(put 'helm-scroll-other-window-down 'helm-only t) + +(defun helm-recenter-top-bottom-other-window (&optional arg) + "Run `recenter-top-bottom' in other window. +Meaning of prefix ARG is the same as in `recenter-top-bottom'." + (interactive "P") + (with-helm-alive-p + (with-helm-window + (with-selected-window (helm-persistent-action-display-window) + (recenter-top-bottom arg))))) +(put 'helm-recenter-top-bottom-other-window 'helm-only t) + +(defun helm-reposition-window-other-window (&optional arg) + "Run `reposition-window' in other window. +Meaning of prefix ARG is the same as in `reposition-window'." + (interactive "P") + (with-helm-alive-p + (with-helm-window + (with-selected-window (helm-persistent-action-display-window) + (reposition-window arg))))) +(put 'helm-reposition-window-other-window 'helm-only t) + + +;; Utility: Visible Mark + +(defun helm-clear-visible-mark () + (with-current-buffer (helm-buffer-get) + (mapc 'delete-overlay helm-visible-mark-overlays) + (set (make-local-variable 'helm-visible-mark-overlays) nil))) + +(defun helm-this-visible-mark () + (cl-loop for o in (overlays-at (point)) + when (overlay-get o 'visible-mark) + return o)) + +(defun helm-delete-visible-mark (overlay) + (let ((src (helm-get-current-source))) + (setq helm-marked-candidates + (remove + (cons src (helm-get-selection nil nil src)) + helm-marked-candidates)) + (delete-overlay overlay) + (setq helm-visible-mark-overlays + (delq overlay helm-visible-mark-overlays)))) + +(defun helm-make-visible-mark (&optional src selection) + (let* ((source (or src (helm-get-current-source))) + (sel (or selection (helm-get-selection + nil (helm-attr 'marked-with-props source) + source))) + (selection-end (if (helm-pos-multiline-p) + ;; Stays within source + (or (helm-get-next-candidate-separator-pos) + (helm-get-next-header-pos) + (point-max)) + ;; Not multiline + (1+ (point-at-eol)))) + (o (make-overlay (point-at-bol) selection-end))) + (overlay-put o 'priority 0) + (overlay-put o 'face 'helm-visible-mark) + (overlay-put o 'source (assoc-default 'name source)) + (overlay-put o 'string (buffer-substring (overlay-start o) (overlay-end o))) + (overlay-put o 'real sel) + (overlay-put o 'visible-mark t) + (cl-pushnew o helm-visible-mark-overlays) + (push (cons source sel) helm-marked-candidates))) + +(defun helm-toggle-visible-mark (arg) + "Toggle helm visible mark at point ARG times. +If ARG is negative toggle backward." + (interactive "p") + (with-helm-alive-p + (with-helm-window + (let ((nomark (assq 'nomark (helm-get-current-source))) + (next-fns (if (< arg 0) + '(helm-beginning-of-source-p . helm-previous-line) + '(helm-end-of-source-p . helm-next-line)))) + (if nomark + (message "Marking not allowed in this source") + (cl-loop with n = (if (< arg 0) (* arg -1) arg) + repeat n do + (progn + (helm-aif (helm-this-visible-mark) + (helm-delete-visible-mark it) + (helm-make-visible-mark)) + (if (funcall (car next-fns)) + (progn + (helm-display-mode-line (helm-get-current-source)) + (cl-return nil)) + (funcall (cdr next-fns)))))))))) +(put 'helm-toggle-visible-mark 'helm-only t) + +(defun helm-file-completion-source-p (&optional source) + "Return non-`nil' if current source is a file completion source." + (or helm--completing-file-name ; helm-read-file-name + (let ((cur-source (cdr (assq 'name + (or source (helm-get-current-source)))))) + (cl-loop for i in helm--file-completion-sources + thereis (string= cur-source i))))) + +(defun helm-mark-all (&optional all) + "Mark all visible unmarked candidates in current source. + +With a prefix arg mark all visible unmarked candidates in all sources." + (interactive "P") + (with-helm-alive-p + (with-helm-window ; Using `with-helm-buffer' for some unknow reasons infloop. + (if (null all) + (helm-mark-all-1 t) + (let ((pos (point))) + (goto-char (point-min)) + (helm-awhile (helm-get-next-header-pos) + (goto-char it) + (forward-line 1) + (helm-mark-current-line) + (helm-mark-all-1)) + ;; `save-excursion' seems confused if used in addition of + ;; the one used in `helm-mark-all-1', so save POS and back + ;; to it when loop is finished. + (goto-char pos) + (helm-mark-current-line) + (helm-display-mode-line (helm-get-current-source) t)))))) +(put 'helm-mark-all 'helm-only t) + +(defun helm-mark-all-1 (&optional ensure-beg-of-source) + "Mark all visible unmarked candidates in current source. +Need to be wrapped in `with-helm-window'. +Arg ENSURE-BEG-OF-SOURCE ensure we are at beginning of source when +starting to mark candidates, if handled elsewhere before starting it +is not needed." + (let* ((src (helm-get-current-source)) + (follow (if (helm-follow-mode-p src) 1 -1)) + (nomark (assq 'nomark src)) + (src-name (assoc-default 'name src)) + (filecomp-p (or (helm-file-completion-source-p src) + (string= src-name "Files from Current Directory"))) + (remote-p (and filecomp-p (file-remote-p helm-pattern)))) + ;; Note that `cl-letf' prevents edebug working properly. + (cl-letf (((symbol-function 'message) #'ignore)) + (helm-follow-mode -1) + (unwind-protect + (if nomark + (message "Marking not allowed in this source") + (save-excursion + (when ensure-beg-of-source + (goto-char (helm-get-previous-header-pos)) + (forward-line 1)) + (let* ((next-head (helm-get-next-header-pos)) + (end (and next-head + (save-excursion + (goto-char next-head) + (forward-line -1) + (point)))) + (maxpoint (or end (point-max)))) + (while (< (point) maxpoint) + (helm-mark-current-line) + (let* ((prefix (get-text-property (point-at-bol) 'display)) + (cand (helm-get-selection nil nil src)) + (bn (and filecomp-p (helm-basename cand)))) + ;; Don't mark possibles directories ending with . or .. + ;; autosave files/links and non--existent files. + (unless + (or (helm-this-visible-mark) + (string= prefix "[?]") ; doesn't match + (and filecomp-p + (or + ;; autosave files + (string-match-p "^[.]?#.*#?$" bn) + ;; dot files + (member bn '("." "..")) + ;; We need to test here when not using + ;; a transformer that put a prefix tag + ;; before candidate. + ;; (i.e no [?] prefix on tramp). + (and remote-p (not (file-exists-p cand)))))) + (helm-make-visible-mark src cand))) + (when (helm-pos-multiline-p) + (goto-char + (or (helm-get-next-candidate-separator-pos) + (point-max)))) + (forward-line 1)))) + (helm-mark-current-line)) + (helm-follow-mode follow))))) + +(defun helm-unmark-all () + "Unmark all candidates in all sources of current helm session." + (interactive) + (with-helm-alive-p + (with-helm-window + (save-excursion + (helm-clear-visible-mark)) + (setq helm-marked-candidates nil) + (helm-mark-current-line) + (helm-display-mode-line (helm-get-current-source))))) +(put 'helm-unmark-all 'helm-only t) + +(defun helm-toggle-all-marks (&optional all) + "Toggle all marks. + +Mark all visible candidates of current source or unmark all candidates +visible or invisible in all sources of current helm session. + +With a prefix argument mark all candidates in all sources." + (interactive "P") + (with-helm-alive-p + (let ((marked (helm-marked-candidates))) + (if (and (>= (length marked) 1) + (with-helm-window helm-visible-mark-overlays)) + (helm-unmark-all) + (helm-mark-all all))))) +(put 'helm-toggle-all-marks 'helm-only t) + +(defun helm--compute-marked (real source &optional wildcard) + (let* ((coerced (helm-coerce-selection real source)) + (wilds (and wildcard + (condition-case nil + (helm-file-expand-wildcards + coerced t) + (error nil))))) + ;; Avoid returning a not expanded wilcard fname. + ;; e.g assuming "/tmp" doesn't contain "*.el" + ;; return nil when coerced is "/tmp/*.el". + (unless (or wilds (null wildcard) + (string-match-p helm--url-regexp coerced) + (file-exists-p coerced) + (and (stringp coerced) + (null (string-match-p "[[*?]" coerced)))) + (setq coerced nil)) + (or wilds (and coerced (list coerced))))) + +(cl-defun helm-marked-candidates (&key with-wildcard all-sources) + "Return marked candidates of current source, if any. + +Otherwise return one element list consisting of the current +selection. When key WITH-WILDCARD is specified, expand it. +When ALL-SOURCES key value is non-nil returns marked candidates of all +sources." + (with-current-buffer helm-buffer + (let* ((current-src (helm-get-current-source)) + (candidates + (cl-loop for (source . real) in (reverse helm-marked-candidates) + for use-wc = (and with-wildcard + (string-match-p "\\*" real) + (null (file-exists-p real))) + when (or all-sources + (equal (assq 'name source) + (assq 'name current-src))) + append (helm--compute-marked real source use-wc))) + sel) + (unless candidates + (setq sel (helm-get-selection + nil (helm-attr 'marked-with-props + current-src) + current-src)) + (setq candidates + (helm--compute-marked + sel current-src + (and with-wildcard (null (file-exists-p sel)))))) + (helm-log "Marked candidates = %S" candidates) + candidates))) + +(defun helm--remove-marked-and-update-mode-line (elm) + (with-helm-buffer + (setq helm-marked-candidates + (delete (rassoc elm helm-marked-candidates) + helm-marked-candidates)) + (helm-display-mode-line (helm-get-current-source)))) + +(defun helm-current-source-name= (name) + (save-excursion + (goto-char (helm-get-previous-header-pos)) + (equal name (helm-current-line-contents)))) + +(defun helm-revive-visible-mark () + "Restore marked candidates when helm updates display." + (with-current-buffer helm-buffer + (save-excursion + (cl-dolist (o helm-visible-mark-overlays) + (let ((o-src-str (overlay-get o 'source)) + (o-str (overlay-get o 'string)) + beg end) + ;; Move point to end of source header line. + (goto-char (point-min)) + (search-forward o-src-str nil t) + (while (and (search-forward o-str nil t) + (cl-loop for ov in (overlays-at (point-at-bol 0)) + never (overlay-get ov 'visible-mark)) + (helm-current-source-name= o-src-str)) + (setq beg (match-beginning 0) + end (match-end 0)) + ;; Calculate real value of candidate. + ;; It can be nil if candidate have only a display value. + (let ((real (get-text-property (point-at-bol 0) 'helm-realvalue))) + (if real + ;; Check if real value of current candidate is the same + ;; than the one stored in overlay. + ;; This is needed when some cands have same display names. + ;; Using equal allow testing any type of value for real cand. + ;; Issue (#706). + (and (equal (overlay-get o 'real) real) + (move-overlay o beg end)) + (and (equal o-str (buffer-substring beg end)) + (move-overlay o beg end)))))))))) +(add-hook 'helm-after-update-hook 'helm-revive-visible-mark) + +(defun helm-next-point-in-list (curpos points &optional prev) + (cond + ;; rule out special cases. + ((null points) curpos) + ((and prev (<= curpos (car points))) + (nth (1- (length points)) points)) + ((< (car (last points)) curpos) + (if prev (car (last points)) (nth 0 points))) + ((and (not prev) (>= curpos (car (last points)))) + (nth 0 points)) + (t + (nth (if prev + (cl-loop for pt in points + for i from 0 + if (<= curpos pt) return (1- i)) + (cl-loop for pt in points + for i from 0 + if (< curpos pt) return i)) + points)))) + +(defun helm-next-visible-mark (&optional prev) + "Move next helm visible mark. +If PREV is non-`nil' move to precedent." + (interactive) + (with-helm-alive-p + (with-helm-window + (ignore-errors + (goto-char (helm-next-point-in-list + (point) + (sort (mapcar 'overlay-start helm-visible-mark-overlays) '<) + prev))) + (helm-mark-current-line)))) +(put 'helm-next-visible-mark 'helm-only t) + +(defun helm-prev-visible-mark () + "Move previous helm visible mark." + (interactive) + (with-helm-alive-p + (helm-next-visible-mark t))) +(put 'helm-prev-visible-mark 'helm-only t) + +;;; Utility: Selection Paste +;; +(defun helm-yank-selection (arg) + "Set minibuffer contents to current display selection. +With a prefix arg set to real value of current selection." + (interactive "P") + (with-helm-alive-p + (let ((str (format "%s" (helm-get-selection nil (not arg))))) + (kill-new str) + (helm-set-pattern str)))) +(put 'helm-yank-selection 'helm-only t) + +(defun helm-kill-selection-and-quit (arg) + "Store display value of current selection to kill ring. +With a prefix arg use real value of current selection. +Display value is shown in `helm-buffer' and real value +is used to perform actions." + (interactive "P") + (with-helm-alive-p + (helm-run-after-exit + (lambda (sel) + (kill-new sel) + ;; Return nil to force `helm-mode--keyboard-quit' + ;; in `helm-comp-read' otherwise the value "Saved to kill-ring: foo" + ;; is used as exit value for `helm-comp-read'. + (prog1 nil (message "Saved to kill-ring: %s" sel) (sit-for 1))) + (format "%s" (helm-get-selection nil (not arg)))))) +(put 'helm-kill-selection-and-quit 'helm-only t) + +(defun helm-copy-to-buffer () + "Copy selection or marked candidates to `helm-current-buffer'. +Note that the real values of candidates are copied and not the +display values." + (interactive) + (with-helm-alive-p + (helm-run-after-exit + (lambda (cands) + (with-helm-current-buffer + (insert (mapconcat (lambda (c) + (format "%s" c)) + cands "\n")))) + (helm-marked-candidates)))) +(put 'helm-copy-to-buffer 'helm-only t) + + +;;; Follow-mode: Automatic execution of persistent-action +;; +;; +(defvar helm-follow-input-idle-delay nil + "`helm-follow-mode' will execute its persistent action after this delay. +Note that if the `follow-delay' attr is present in source, +it will take precedence over this.") + +(defun helm-follow-mode (&optional arg) + "Execute persistent action every time the cursor is moved. + +This mode is source local, i.e It apply on current source only. +\\ +This mode can be enabled or disabled interactively at anytime during +a helm session with \\[helm-follow-mode]. + +When enabling interactively `helm-follow-mode' in a source, you can keep it enabled +for next emacs sessions by setting `helm-follow-mode-persistent' to a non-nil value. + +When `helm-follow-mode' is called with a prefix arg and `helm-follow-mode-persistent' +is non-nil `helm-follow-mode' will be persistent only for this emacs session, +but not for next emacs sessions, i.e the current source will not be saved +to `helm-source-names-using-follow'. +A prefix arg with `helm-follow-mode' already enabled will have no effect. + +Note that you can use instead of this mode the commands `helm-follow-action-forward' +and `helm-follow-action-backward' at anytime in all helm sessions. + +They are bound by default to \\[helm-follow-action-forward] and \\[helm-follow-action-backward]." + (interactive (list (helm-aif (and current-prefix-arg + (prefix-numeric-value current-prefix-arg)) + (unless (helm-follow-mode-p) it)))) + (with-helm-alive-p + (with-current-buffer helm-buffer + (let* ((src (helm-get-current-source)) + (name (assoc-default 'name src)) + (fol-attr (assq 'follow src)) + (enabled (or (helm-follow-mode-p src) + (and helm-follow-mode-persistent + (member (assoc-default 'name src) + helm-source-names-using-follow))))) + (if src + (progn + (if (eq (cdr fol-attr) 'never) + (message "helm-follow-mode not allowed in this source") + ;; Make follow attr persistent for this emacs session. + (helm-follow-mode-set-source + (if (or enabled (and (numberp arg) (< arg 0))) -1 1) + src) + ;; When arg is nil assume the call is interactive. + ;; However if user call helm-follow-mode with a prefix arg, + ;; the call will be considered non--interactive and + ;; src-name will NOT be saved to helm-source-names-using-follow. + ;; When called from lisp (non--interactive) src-name + ;; will never be saved. + (when (and helm-follow-mode-persistent (null arg)) + (if (null enabled) + (unless (member name helm-source-names-using-follow) + (push name helm-source-names-using-follow) + (customize-save-variable 'helm-source-names-using-follow + helm-source-names-using-follow)) + (when (member name helm-source-names-using-follow) + (setq helm-source-names-using-follow + (delete name helm-source-names-using-follow)) + (customize-save-variable 'helm-source-names-using-follow + helm-source-names-using-follow)))) + (message "helm-follow-mode is %s" + (if (helm-follow-mode-p src) + "enabled" "disabled")) + (helm-display-mode-line src t))) + (message "Not enough candidates for helm-follow-mode")))))) +(put 'helm-follow-mode 'helm-only t) + +(defun helm-follow-execute-persistent-action-maybe (&optional delay) + "Execute persistent action in mode `helm-follow-mode'. + +This happen after: DELAY or the 'follow-attr value of current source +or `helm-follow-input-idle-delay' or `helm-input-idle-delay' secs." + (let* ((src (helm-get-current-source)) + (at (or delay + (assoc-default 'follow-delay src) + helm-follow-input-idle-delay + (or (and helm-input-idle-delay + (max helm-input-idle-delay 0.01)) + 0.01)))) + (when (and (not (get-buffer-window helm-action-buffer 'visible)) + (not (helm-pos-header-line-p)) + (or (helm-follow-mode-p src) + (and helm-follow-mode-persistent + (member (assoc-default 'name src) + helm-source-names-using-follow))) + (null (eq (assoc-default 'follow src) 'never)) + (helm-get-selection nil nil src)) + (helm-follow-mode-set-source 1 src) + (run-with-idle-timer at nil (lambda () + (when helm-alive-p + (helm-execute-persistent-action))))))) + +(defun helm-follow-mode-p (&optional source) + (with-helm-buffer + (eq (helm-attr 'follow (or source (helm-get-current-source))) 1))) + +(defun helm-follow-mode-set-source (value &optional source) + (with-helm-buffer + (helm-attrset 'follow value (or source (helm-get-current-source))))) + +;;; Auto-resize mode +;; +(defun helm--autoresize-hook (&optional max-height min-height) + (when (helm-window) + (with-helm-window + (fit-window-to-buffer nil + (/ (* (frame-height) + (or max-height helm-autoresize-max-height)) + 100) + (/ (* (frame-height) + (or min-height helm-autoresize-min-height)) + 100))))) + +(define-minor-mode helm-autoresize-mode + "Auto resize helm window when enabled. +Helm window is re-sized according to `helm-autoresize-max-height' +and `helm-autoresize-min-height'. Note that when this mode is +enabled, helm behaves as if `helm-always-two-windows' is +enabled. + +See `fit-window-to-buffer' for more infos." + :group 'helm + :global t + (if helm-autoresize-mode + (progn (add-hook 'helm-after-update-hook 'helm--autoresize-hook) + (add-hook 'helm-window-configuration-hook 'helm--autoresize-hook)) + (remove-hook 'helm-after-update-hook 'helm--autoresize-hook) + (remove-hook 'helm-window-configuration-hook 'helm--autoresize-hook))) + +(defun helm-help () + "Generate helm's help according to `help-message' attribute. + +If `helm-buffer' is empty, provide completions on `helm-sources' to +choose its local documentation. +If source doesn't have any `help-message' attribute, a generic message +explaining this is added instead. +The global `helm-help-message' is always added after this local help." + (interactive) + (with-helm-alive-p + (let ((source (or (helm-get-current-source) + (helm-comp-read + "Help for: " + (cl-loop for src in (with-helm-buffer helm-sources) + for src-val = (if (symbolp src) + (symbol-value src) + src) + collect `(,(assoc-default 'name src-val) . + ,src)) + :allow-nest t + :exec-when-only-one t)))) + (save-selected-window + (helm-help-internal + "*Helm Help*" + (lambda () + (helm-aif (assoc-default 'help-message source) + (insert (substitute-command-keys + (helm-interpret-value it))) + (insert "* No specific help for this source available.")) + (insert "\n\n" + (substitute-command-keys + (helm-interpret-value helm-help-message))))))))) +(put 'helm-help 'helm-only t) + +(defun helm-toggle-truncate-line () + "Toggle `truncate-lines' value in `helm-buffer'" + (interactive) + (with-helm-alive-p + (with-helm-buffer + (setq truncate-lines (not truncate-lines)) + (when (helm-get-previous-header-pos) + (helm-update (regexp-quote (helm-get-selection nil t))))))) +(put 'helm-toggle-truncate-line 'helm-only t) + +(provide 'helm) + +;; Local Variables: +;; byte-compile-warnings: (not obsolete) +;; coding: utf-8 +;; indent-tabs-mode: nil +;; End: + +;;; helm.el ends here diff --git a/elpa/magit-20181113.1837/AUTHORS.md b/elpa/magit-20181113.1837/AUTHORS.md new file mode 100644 index 00000000..1ff892fb --- /dev/null +++ b/elpa/magit-20181113.1837/AUTHORS.md @@ -0,0 +1,315 @@ +Authors +======= + +The following people have contributed to Magit, including the +libraries `git-commit.el`, `magit-popup.el`, and `with-editor.el` +which are distributed as separate Elpa packages. + +For statistics see https://magit.vc/stats/authors.html. + +Names below are sorted alphabetically. + +Author +------ + +- Marius Vollmer + +Maintainer +---------- + +- Jonas Bernoulli + +Developers +---------- + +- Kyle Meyer +- Noam Postavsky + +Retired Maintainers and Developers +---------------------------------- + +- Nicolas Dudebout +- Peter J. Weisberg +- Pieter Praet +- Phil Jackson +- Rémi Vanicat +- Yann Hodique + +Contributors +------------ + +- Aaron Culich +- Aaron Madlon-Kay +- Abdo Roig-Maranges +- Adam Benanti <0entropy@protonmail.com> +- Adam Porter +- Adam Spiers +- Adeodato Simó +- Ævar Arnfjörð Bjarmason +- Alan Falloon +- Alban Gruin +- Aleksey Uimanov +- Alexander Gramiak +- Alex Dunn +- Alexey Voinov +- Alex Kost +- Alex Ott +- Allen +- Allen Li +- Andreas Fuchs +- Andreas Liljeqvist +- Andreas Rottmann +- Andrei Chițu +- Andrew Kirkpatrick +- Andrew Schwartzmeyer +- Andrey Smirnov +- Andriy Kmit' +- Andy Sawyer +- Aria Edmonds +- Arialdo Martini +- Barak A. Pearlmutter +- Bar Magal +- Bart Bakker +- Basil L. Contovounesios +- Bastian Beischer +- Benjamin Motz +- Ben North +- Ben Walton +- Bob Uhl +- Bradley Wright +- Brandon W Maister +- Brian Warner +- Bryan Shell +- Buster Copley +- Carl Lieberman +- Chillar Anand +- Chris Bernard +- Chris Done +- Chris LaRose +- Chris Moore +- Chris Ring +- Chris Shoemaker +- Christian Dietrich +- Christian Kluge +- Christophe Junke +- Christopher Monsanto +- Cornelius Mika +- Craig Andera +- Dale Hagglund +- Damien Cassou +- Dan Erikson +- Daniel Brockman +- Daniel Farina +- Daniel Gröber +- Daniel Hackney +- Daniel Kraus +- Daniel Mai +- Dan LaManna +- Dato Simó +- David Abrahams +- David Ellison +- David Hull +- David L. Rager +- David Wallin +- Dean Kariniemi <8913263+d3k4r@users.noreply.github.com> +- Dennis Paskorz +- Divye Kapoor +- Dominique Quatravaux +- Duianto Vebotci +- Eli Barzilay +- Eric Davis +- Eric Prud'hommeaux +- Eric Schulte +- Erik Anderson +- Evgkeni Sampelnikof +- Eyal Lotem +- Fabian Wiget +- Felix Geller +- Felix Yan +- Feng Li +- Florian Ragwitz +- Fritz Grabo +- Fritz Stelzer +- Geoff Shannon +- George Kadianakis +- Graham Clark +- Graham Dobbins +- Greg A. Woods +- Greg Lucas +- Greg Sexton +- Guillaume Martres +- Hannu Koivisto +- Hans-Peter Deifel +- Ian Eure +- Ingo Lohmar +- Ioan-Adrian Ratiu +- Ivan Brennan +- Jan Tatarik +- Jasper St. Pierre +- Jeff Bellegarde +- Jeff Dairiki +- Jeremy Meng +- Jesse Alama +- Jim Blandy +- Joakim Jalap +- Johann Klähn +- John Mastro +- John Wiegley +- Jonas Bernoulli +- Jonathan Leech-Pepin +- Jonathan Roes +- Jon Vanderwijk +- Jordan Galby +- Jordan Greenberg +- Josiah Schwab +- Julien Danjou +- Justin Burkett +- Justin Caratzas +- Justin Guenther +- Justin Thomas +- Kan-Ru Chen +- Kenny Ballou +- Keshav Kini +- Kévin Le Gouguec +- Kimberly Wolk +- Kyle Meyer +- Laurent Laffont +- Laverne Schrock +- Leandro Facchinetti +- Lele Gaifax +- Leo Liu +- Leonardo Etcheverry +- Lingchao Xin +- Li-Yun Chang +- Lluís Vilanova +- Loic Dachary +- Louis Roché +- Luís Oliveira +- Luke Amdor +- Mak Kolybabi +- Manuel Vázquez Acosta +- Marcel Wolf +- Marc Herbert +- Marcin Bachry +- Marco Craveiro +- Marco Wahl +- Marc Sherry +- Marian Schubert +- Mario Rodas +- Marius Vollmer +- Mark Hepburn +- Mark Karpov +- Mark Oteiza +- Matthew Fluet +- Matthieu Hauglustaine +- Matus Goljer +- Michael Fogleman +- Michael Griffiths +- Michael Heerdegen +- Michal Sojka +- Miciah Masters +- Miles Bader +- Miloš Mošić +- Mitchel Humpherys +- Moritz Bunkus +- Natalie Weizenbaum +- Nguyễn Tuấn Anh +- Nic Ferier +- Nick Alcock +- Nick Alexander +- Nick Dimiduk +- Nicklas Lindgren +- Nicolas Dudebout +- Nicolas Petton +- Nicolas Richard +- Nikolay Martynov +- Noam Postavsky +- N. Troy de Freitas +- Ole Arndt +- Oleh Krehel +- Orivej Desh +- Óscar Fuentes +- Paul Stadig +- Pavel Holejsovsky +- Pekka Pessi +- Peter Eisentraut +- Peter Jaros +- Peter J. Weisberg +- Peter Vasil +- Philippe Vaucher +- Philipp Haselwarter +- Philipp Stephani +- Philip Weaver +- Phil Jackson +- Phil Sainty +- Pierre Neidhardt +- Pieter Praet +- Prathamesh Sonpatki +- rabio +- Radon Rosborough +- Rafael Laboissiere +- Raimon Grau +- Ramkumar Ramachandra +- Remco van 't Veer +- Rémi Vanicat +- René Stadler +- Richard Kim +- Robert Boone +- Robin Green +- Roger Crew +- Romain Francoise +- Ron Parker +- Roy Crihfield +- Rüdiger Sonderfeld +- Russell Black +- Ryan C. Thompson +- Samuel Bronson +- Samuel W. Flint +- Sanjoy Das +- Sean Allred +- Sean Bryant +- Sean Whitton +- Sebastian Wiesner +- Sébastien Gross +- Seong-Kook Shin +- Sergey Pashinin +- Sergey Vinokurov +- Servilio Afre Puentes +- Silent Sphere +- Štěpán Němec +- Steven Chow +- Steven E. Harris +- Steven Thomas +- Steven Vancoillie +- Steve Purcell +- Suhail Shergill +- Sylvain Rousseau +- Syohei Yoshida +- Takafumi Arakaki +- Teemu Likonen +- Teruki Shigitani +- Thierry Volpiatto +- Thomas A Caswell +- Thomas Frössman +- Thomas Jost +- Thomas Riccardi +- Tibor Simko +- Timo Juhani Lindfors +- Tim Perkins +- Tim Wraight +- Ting-Yu Lin +- Tom Feist +- Tunc Uzlu +- Vineet Naik +- Vladimir Panteleev +- Wei Huang +- Wilfred Hughes +- Win Treese +- Wouter Bolsterlee +- Xavier Noria +- Xu Chunyang +- Yann Hodique +- York Zhao +- Yuichi Higashi +- Yuri Khan +- Zach Latta diff --git a/elpa/magit-20181113.1837/LICENSE b/elpa/magit-20181113.1837/LICENSE new file mode 100644 index 00000000..44325404 --- /dev/null +++ b/elpa/magit-20181113.1837/LICENSE @@ -0,0 +1,676 @@ + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 3 of the License, 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 this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/elpa/magit-20181113.1837/dir b/elpa/magit-20181113.1837/dir new file mode 100644 index 00000000..dfdbd715 --- /dev/null +++ b/elpa/magit-20181113.1837/dir @@ -0,0 +1,18 @@ +This is the file .../info/dir, which contains the +topmost node of the Info hierarchy, called (dir)Top. +The first time you invoke Info you start off looking at this node. + +File: dir, Node: Top This is the top of the INFO tree + + This (the Directory node) gives a menu of major topics. + Typing "q" exits, "H" lists all Info commands, "d" returns here, + "h" gives a primer for first-timers, + "mEmacs" visits the Emacs manual, etc. + + In Emacs, you can click mouse button 2 on a menu item or cross reference + to select it. + +* Menu: + +Emacs +* Magit: (magit). Using Git from Emacs with Magit. diff --git a/elpa/magit-20181113.1837/git-rebase.el b/elpa/magit-20181113.1837/git-rebase.el new file mode 100644 index 00000000..07577c5b --- /dev/null +++ b/elpa/magit-20181113.1837/git-rebase.el @@ -0,0 +1,593 @@ +;;; git-rebase.el --- Edit Git rebase files -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Phil Jackson +;; Maintainer: Jonas Bernoulli + +;; 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 file 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 this file. If not, see . + +;;; Commentary: + +;; This package assists the user in editing the list of commits to be +;; rewritten during an interactive rebase. + +;; When the user initiates an interactive rebase, e.g. using "r e" in +;; a Magit buffer or on the command line using "git rebase -i REV", +;; Git invokes the `$GIT_SEQUENCE_EDITOR' (or if that is undefined +;; `$GIT_EDITOR' or even `$EDITOR') letting the user rearrange, drop, +;; reword, edit, and squash commits. + +;; This package provides the major-mode `git-rebase-mode' which makes +;; doing so much more fun, by making the buffer more colorful and +;; providing the following commands: +;; +;; C-c C-c Tell Git to make it happen. +;; C-c C-k Tell Git that you changed your mind, i.e. abort. +;; +;; p Move point to previous line. +;; n Move point to next line. +;; +;; M-p Move the commit at point up. +;; M-n Move the commit at point down. +;; +;; k Drop the commit at point. +;; c Don't drop the commit at point. +;; r Change the message of the commit at point. +;; e Edit the commit at point. +;; s Squash the commit at point, into the one above. +;; f Like "s" but don't also edit the commit message. +;; x Add a script to be run with the commit at point +;; being checked out. +;; z Add noop action at point. +;; +;; SPC Show the commit at point in another buffer. +;; RET Show the commit at point in another buffer and +;; select its window. +;; C-/ Undo last change. + +;; You should probably also read the `git-rebase' manpage. + +;;; Code: + +(require 'dash) +(require 'easymenu) +(require 'server) +(require 'with-editor) +(require 'magit) + +(and (require 'async-bytecomp nil t) + (memq 'magit (bound-and-true-p async-bytecomp-allowed-packages)) + (fboundp 'async-bytecomp-package-mode) + (async-bytecomp-package-mode 1)) + +(eval-when-compile (require 'recentf)) + +;;; Options +;;;; Variables + +(defgroup git-rebase nil + "Edit Git rebase sequences." + :link '(info-link "(magit)Editing Rebase Sequences") + :group 'tools) + +(defcustom git-rebase-auto-advance t + "Whether to move to next line after changing a line." + :group 'git-rebase + :type 'boolean) + +(defcustom git-rebase-show-instructions t + "Whether to show usage instructions inside the rebase buffer." + :group 'git-rebase + :type 'boolean) + +(defcustom git-rebase-confirm-cancel t + "Whether confirmation is required to cancel." + :group 'git-rebase + :type 'boolean) + +;;;; Faces + +(defgroup git-rebase-faces nil + "Faces used by Git-Rebase mode." + :group 'faces + :group 'git-rebase) + +(defface git-rebase-hash '((t (:inherit magit-hash))) + "Face for commit hashes." + :group 'git-rebase-faces) + +(defface git-rebase-description nil + "Face for commit descriptions." + :group 'git-rebase-faces) + +(defface git-rebase-killed-action + '((t (:inherit font-lock-comment-face :strike-through t))) + "Face for commented action and exec lines." + :group 'git-rebase-faces) + +(defface git-rebase-comment-hash + '((t (:inherit git-rebase-hash :weight bold))) + "Face for commit hashes in commit message comments." + :group 'git-rebase-faces) + +(defface git-rebase-comment-heading + '((t :inherit font-lock-keyword-face)) + "Face for headings in rebase message comments." + :group 'git-commit-faces) + +;;; Keymaps + +(defvar git-rebase-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map special-mode-map) + (cond ((featurep 'jkl) + (define-key map [return] 'git-rebase-show-commit) + (define-key map (kbd "i") 'git-rebase-backward-line) + (define-key map (kbd "k") 'forward-line) + (define-key map (kbd "M-i") 'git-rebase-move-line-up) + (define-key map (kbd "M-k") 'git-rebase-move-line-down) + (define-key map (kbd "p") 'git-rebase-pick) + (define-key map (kbd ",") 'git-rebase-kill-line)) + (t + (define-key map (kbd "C-m") 'git-rebase-show-commit) + (define-key map (kbd "p") 'git-rebase-backward-line) + (define-key map (kbd "n") 'forward-line) + (define-key map (kbd "M-p") 'git-rebase-move-line-up) + (define-key map (kbd "M-n") 'git-rebase-move-line-down) + (define-key map (kbd "c") 'git-rebase-pick) + (define-key map (kbd "k") 'git-rebase-kill-line) + (define-key map (kbd "C-k") 'git-rebase-kill-line))) + (define-key map (kbd "e") 'git-rebase-edit) + (define-key map (kbd "m") 'git-rebase-edit) + (define-key map (kbd "f") 'git-rebase-fixup) + (define-key map (kbd "q") 'undefined) + (define-key map (kbd "r") 'git-rebase-reword) + (define-key map (kbd "w") 'git-rebase-reword) + (define-key map (kbd "s") 'git-rebase-squash) + (define-key map (kbd "x") 'git-rebase-exec) + (define-key map (kbd "y") 'git-rebase-insert) + (define-key map (kbd "z") 'git-rebase-noop) + (define-key map (kbd "SPC") 'git-rebase-show-or-scroll-up) + (define-key map (kbd "DEL") 'git-rebase-show-or-scroll-down) + (define-key map (kbd "C-x C-t") 'git-rebase-move-line-up) + (define-key map [M-up] 'git-rebase-move-line-up) + (define-key map [M-down] 'git-rebase-move-line-down) + (define-key map [remap undo] 'git-rebase-undo) + map) + "Keymap for Git-Rebase mode.") + +(cond ((featurep 'jkl) + (put 'git-rebase-reword :advertised-binding "r") + (put 'git-rebase-move-line-up :advertised-binding (kbd "M-i")) + (put 'git-rebase-kill-line :advertised-binding ",")) + (t + (put 'git-rebase-reword :advertised-binding "r") + (put 'git-rebase-move-line-up :advertised-binding (kbd "M-p")) + (put 'git-rebase-kill-line :advertised-binding "k"))) + +(easy-menu-define git-rebase-mode-menu git-rebase-mode-map + "Git-Rebase mode menu" + '("Rebase" + ["Pick" git-rebase-pick t] + ["Reword" git-rebase-reword t] + ["Edit" git-rebase-edit t] + ["Squash" git-rebase-squash t] + ["Fixup" git-rebase-fixup t] + ["Kill" git-rebase-kill-line t] + ["Noop" git-rebase-noop t] + ["Execute" git-rebase-exec t] + ["Move Down" git-rebase-move-line-down t] + ["Move Up" git-rebase-move-line-up t] + "---" + ["Cancel" with-editor-cancel t] + ["Finish" with-editor-finish t])) + +(defvar git-rebase-command-descriptions + '((with-editor-finish . "tell Git to make it happen") + (with-editor-cancel . "tell Git that you changed your mind, i.e. abort") + (git-rebase-backward-line . "move point to previous line") + (forward-line . "move point to next line") + (git-rebase-move-line-up . "move the commit at point up") + (git-rebase-move-line-down . "move the commit at point down") + (git-rebase-show-or-scroll-up . "show the commit at point in another buffer") + (git-rebase-show-commit + . "show the commit at point in another buffer and select its window") + (undo . "undo last change") + (git-rebase-kill-line . "drop the commit at point") + (git-rebase-insert . "insert a line for an arbitrary commit") + (git-rebase-noop . "add noop action at point"))) + +;;; Commands + +(defun git-rebase-pick () + "Use commit on current line." + (interactive) + (git-rebase-set-action "pick")) + +(defun git-rebase-reword () + "Edit message of commit on current line." + (interactive) + (git-rebase-set-action "reword")) + +(defun git-rebase-edit () + "Stop at the commit on the current line." + (interactive) + (git-rebase-set-action "edit")) + +(defun git-rebase-squash () + "Meld commit on current line into previous commit, edit message." + (interactive) + (git-rebase-set-action "squash")) + +(defun git-rebase-fixup () + "Meld commit on current line into previous commit, discard its message." + (interactive) + (git-rebase-set-action "fixup")) + +(defvar-local git-rebase-line nil) +(defvar-local git-rebase-comment-re nil) + +(defun git-rebase-set-action (action) + (goto-char (line-beginning-position)) + (if (and (looking-at git-rebase-line) + (not (string-match-p "\\(e\\|exec\\|noop\\)$" (match-string 1)))) + (let ((inhibit-read-only t)) + (replace-match action t t nil 1) + (when git-rebase-auto-advance + (forward-line))) + (ding))) + +(defun git-rebase-line-p (&optional pos) + (save-excursion + (when pos (goto-char pos)) + (goto-char (line-beginning-position)) + (looking-at-p git-rebase-line))) + +(defun git-rebase-region-bounds () + (when (use-region-p) + (let ((beg (save-excursion (goto-char (region-beginning)) + (line-beginning-position))) + (end (save-excursion (goto-char (region-end)) + (line-end-position)))) + (when (and (git-rebase-line-p beg) + (git-rebase-line-p end)) + (list beg (1+ end)))))) + +(defun git-rebase-move-line-down (n) + "Move the current commit (or command) N lines down. +If N is negative, move the commit up instead. With an active +region, move all the lines that the region touches, not just the +current line." + (interactive "p") + (pcase-let* ((`(,beg ,end) + (or (git-rebase-region-bounds) + (list (line-beginning-position) + (1+ (line-end-position))))) + (pt-offset (- (point) beg)) + (mark-offset (and mark-active (- (mark) beg)))) + (save-restriction + (narrow-to-region + (point-min) + (1+ (save-excursion + (goto-char (point-min)) + (while (re-search-forward git-rebase-line nil t)) + (point)))) + (if (or (and (< n 0) (= beg (point-min))) + (and (> n 0) (= end (point-max))) + (> end (point-max))) + (ding) + (goto-char (if (< n 0) beg end)) + (forward-line n) + (atomic-change-group + (let ((inhibit-read-only t)) + (insert (delete-and-extract-region beg end))) + (let ((new-beg (- (point) (- end beg)))) + (when (use-region-p) + (setq deactivate-mark nil) + (set-mark (+ new-beg mark-offset))) + (goto-char (+ new-beg pt-offset)))))))) + +(defun git-rebase-move-line-up (n) + "Move the current commit (or command) N lines up. +If N is negative, move the commit down instead. With an active +region, move all the lines that the region touches, not just the +current line." + (interactive "p") + (git-rebase-move-line-down (- n))) + +(defun git-rebase-highlight-region (start end window rol) + (let ((inhibit-read-only t) + (deactivate-mark nil) + (bounds (git-rebase-region-bounds))) + (mapc #'delete-overlay magit-section-highlight-overlays) + (when bounds + (magit-section-make-overlay (car bounds) (cadr bounds) + 'magit-section-heading-selection)) + (if (and bounds (not magit-keep-region-overlay)) + (funcall (default-value 'redisplay-unhighlight-region-function) rol) + (funcall (default-value 'redisplay-highlight-region-function) + start end window rol)))) + +(defun git-rebase-unhighlight-region (rol) + (mapc #'delete-overlay magit-section-highlight-overlays) + (funcall (default-value 'redisplay-unhighlight-region-function) rol)) + +(defun git-rebase-kill-line () + "Kill the current action line." + (interactive) + (goto-char (line-beginning-position)) + (when (and (looking-at git-rebase-line) + (not (eq (char-after) (string-to-char comment-start)))) + (let ((inhibit-read-only t)) + (insert comment-start) + (insert " ")) + (when git-rebase-auto-advance + (forward-line)))) + +(defun git-rebase-insert (rev) + "Read an arbitrary commit and insert it below current line." + (interactive (list (magit-read-branch-or-commit "Insert revision"))) + (forward-line) + (--if-let (magit-rev-format "%h %s" rev) + (let ((inhibit-read-only t)) + (insert "pick " it ?\n)) + (user-error "Unknown revision"))) + +(defun git-rebase-exec (arg) + "Insert a shell command to be run after the proceeding commit. + +If there already is such a command on the current line, then edit +that instead. With a prefix argument insert a new command even +when there already is one on the current line. With empty input +remove the command on the current line, if any." + (interactive "P") + (let ((inhibit-read-only t) initial command) + (unless arg + (goto-char (line-beginning-position)) + (when (looking-at (concat git-rebase-comment-re "?" + "\\(e\\|exec\\) \\(.*\\)")) + (setq initial (match-string-no-properties 2)))) + (setq command (read-shell-command "Execute: " initial)) + (pcase (list command initial) + (`("" nil) (ding)) + (`("" ,_) + (delete-region (match-beginning 0) (1+ (match-end 0)))) + (`(,_ nil) + (forward-line) + (insert (concat "exec " command "\n")) + (unless git-rebase-auto-advance + (forward-line -1))) + (_ + (replace-match (concat "exec " command) t t) + (if git-rebase-auto-advance + (forward-line) + (goto-char (line-beginning-position))))))) + +(defun git-rebase-noop (&optional arg) + "Add noop action at point. + +If the current line already contains a a noop action, leave it +unchanged. If there is a commented noop action present, remove +the comment. Otherwise add a new noop action. With a prefix +argument insert a new noop action regardless what is already +present on the current line. + +A noop action can be used to make git perform a rebase even if +no commits are selected. Without the noop action present, git +would see an empty file and therefore do nothing." + (interactive "P") + (goto-char (line-beginning-position)) + ;; The extra space at the end is only there to make the action + ;; consistent with the others (action argument). This keeps + ;; the regexp `git-rebase-line' from getting complicated. + (let ((noop-string "noop \n")) + (when (or arg (not (looking-at noop-string))) + (let ((inhibit-read-only t)) + (if (and (not arg) + (looking-at (concat comment-start noop-string))) + (delete-char 1) + (insert noop-string)))))) + +(defun git-rebase-undo (&optional arg) + "Undo some previous changes. +Like `undo' but works in read-only buffers." + (interactive "P") + (let ((inhibit-read-only t)) + (undo arg))) + +(defun git-rebase--show-commit (&optional scroll) + (let ((disable-magit-save-buffers t)) + (save-excursion + (goto-char (line-beginning-position)) + (--if-let (and (looking-at git-rebase-line) + (match-string 2)) + (pcase scroll + (`up (magit-diff-show-or-scroll-up)) + (`down (magit-diff-show-or-scroll-down)) + (_ (apply #'magit-show-commit it (magit-diff-arguments)))) + (ding))))) + +(defun git-rebase-show-commit () + "Show the commit on the current line if any." + (interactive) + (git-rebase--show-commit)) + +(defun git-rebase-show-or-scroll-up () + "Update the commit buffer for commit on current line. + +Either show the commit at point in the appropriate buffer, or if +that buffer is already being displayed in the current frame and +contains information about that commit, then instead scroll the +buffer up." + (interactive) + (git-rebase--show-commit 'up)) + +(defun git-rebase-show-or-scroll-down () + "Update the commit buffer for commit on current line. + +Either show the commit at point in the appropriate buffer, or if +that buffer is already being displayed in the current frame and +contains information about that commit, then instead scroll the +buffer down." + (interactive) + (git-rebase--show-commit 'down)) + +(defun git-rebase-backward-line (&optional n) + "Move N lines backward (forward if N is negative). +Like `forward-line' but go into the opposite direction." + (interactive "p") + (forward-line (- (or n 1)))) + +;;; Mode + +;;;###autoload +(define-derived-mode git-rebase-mode special-mode "Git Rebase" + "Major mode for editing of a Git rebase file. + +Rebase files are generated when you run 'git rebase -i' or run +`magit-interactive-rebase'. They describe how Git should perform +the rebase. See the documentation for git-rebase (e.g., by +running 'man git-rebase' at the command line) for details." + :group 'git-rebase + (setq comment-start (or (magit-get "core.commentChar") "#")) + (setq git-rebase-comment-re (concat "^" (regexp-quote comment-start))) + (setq git-rebase-line + (concat "^\\(" (regexp-quote comment-start) "? *" + "\\(?:[fprse]\\|pick\\|reword\\|edit\\|squash\\|fixup\\|exec\\|noop\\)\\) " + "\\(?:\\([^ \n]+\\) \\(.*\\)\\)?")) + (setq font-lock-defaults (list (git-rebase-mode-font-lock-keywords) t t)) + (unless git-rebase-show-instructions + (let ((inhibit-read-only t)) + (flush-lines git-rebase-comment-re))) + (unless with-editor-mode + ;; Maybe already enabled when using `shell-command' or an Emacs shell. + (with-editor-mode 1)) + (when git-rebase-confirm-cancel + (add-hook 'with-editor-cancel-query-functions + 'git-rebase-cancel-confirm nil t)) + (setq-local redisplay-highlight-region-function 'git-rebase-highlight-region) + (setq-local redisplay-unhighlight-region-function 'git-rebase-unhighlight-region) + (add-hook 'with-editor-pre-cancel-hook 'git-rebase-autostash-save nil t) + (add-hook 'with-editor-post-cancel-hook 'git-rebase-autostash-apply nil t) + (setq imenu-prev-index-position-function + #'magit-imenu--rebase-prev-index-position-function) + (setq imenu-extract-index-name-function + #'magit-imenu--rebase-extract-index-name-function) + (when (boundp 'save-place) + (setq save-place nil))) + +(defun git-rebase-cancel-confirm (force) + (or (not (buffer-modified-p)) + force + (magit-confirm 'abort-rebase "Abort this rebase" nil 'noabort))) + +(defun git-rebase-autostash-save () + (--when-let (magit-file-line (magit-git-dir "rebase-merge/autostash")) + (push (cons 'stash it) with-editor-cancel-alist))) + +(defun git-rebase-autostash-apply () + (--when-let (cdr (assq 'stash with-editor-cancel-alist)) + (magit-stash-apply it))) + +(defun git-rebase-match-comment-line (limit) + (re-search-forward (concat git-rebase-comment-re ".*") limit t)) + +(defun git-rebase-mode-font-lock-keywords () + "Font lock keywords for Git-Rebase mode." + (let ((action-re "\ +\\([efprs]\\|pick\\|reword\\|edit\\|squash\\|fixup\\) \\([^ \n]+\\) \\(.*\\)")) + `((,(concat "^" action-re) + (1 'font-lock-keyword-face) + (2 'git-rebase-hash) + (3 'git-rebase-description)) + ("^\\(exec\\) \\(.*\\)" + (1 'font-lock-keyword-face) + (2 'git-rebase-description)) + ("^\\(noop\\)" + (1 'font-lock-keyword-face)) + (git-rebase-match-comment-line 0 'font-lock-comment-face) + (,(concat git-rebase-comment-re " *" action-re) + 0 'git-rebase-killed-action t) + ("\\[[^[]*\\]" + 0 'magit-keyword t) + (,(format "^%s Rebase \\([^ ]*\\) onto \\([^ ]*\\)" comment-start) + (1 'git-rebase-comment-hash t) + (2 'git-rebase-comment-hash t)) + (,(format "^%s \\(Commands:\\)" comment-start) + (1 'git-rebase-comment-heading t))))) + +(defun git-rebase-mode-show-keybindings () + "Modify the \"Commands:\" section of the comment Git generates +at the bottom of the file so that in place of the one-letter +abbreviation for the command, it shows the command's keybinding. +By default, this is the same except for the \"pick\" command." + (let ((inhibit-read-only t)) + (save-excursion + (goto-char (point-min)) + (when (and git-rebase-show-instructions + (re-search-forward + (concat git-rebase-comment-re "\\s-+p, pick") + nil t)) + (goto-char (line-beginning-position)) + (pcase-dolist (`(,cmd . ,desc) git-rebase-command-descriptions) + (insert (format "%s %-8s %s\n" + comment-start + (substitute-command-keys (format "\\[%s]" cmd)) + desc))) + (while (re-search-forward (concat git-rebase-comment-re + "\\( ?\\)\\([^\n,],\\) " + "\\([^\n ]+\\) ") + nil t) + (let ((cmd (intern (concat "git-rebase-" (match-string 3))))) + (if (not (fboundp cmd)) + (delete-region (line-beginning-position) (1+ (line-end-position))) + (replace-match " " t t nil 1) + (replace-match + (format "%-8s" + (mapconcat #'key-description + (--remove (eq (elt it 0) 'menu-bar) + (reverse (where-is-internal cmd))) + ", ")) + t t nil 2)))))))) + +(add-hook 'git-rebase-mode-hook 'git-rebase-mode-show-keybindings t) + +(defun git-rebase-mode-disable-before-save-hook () + (set (make-local-variable 'before-save-hook) nil)) + +(add-hook 'git-rebase-mode-hook 'git-rebase-mode-disable-before-save-hook) + +;;;###autoload +(defconst git-rebase-filename-regexp "/git-rebase-todo\\'") +;;;###autoload +(add-to-list 'auto-mode-alist + (cons git-rebase-filename-regexp 'git-rebase-mode)) + +(add-to-list 'with-editor-server-window-alist + (cons git-rebase-filename-regexp 'switch-to-buffer)) + +(eval-after-load 'recentf + '(add-to-list 'recentf-exclude git-rebase-filename-regexp)) + +(add-to-list 'with-editor-file-name-history-exclude git-rebase-filename-regexp) + +;;; _ +(provide 'git-rebase) +;;; git-rebase.el ends here diff --git a/elpa/magit-20181113.1837/magit-apply.el b/elpa/magit-20181113.1837/magit-apply.el new file mode 100644 index 00000000..b99057ee --- /dev/null +++ b/elpa/magit-20181113.1837/magit-apply.el @@ -0,0 +1,695 @@ +;;; magit-apply.el --- apply Git diffs -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements commands for applying Git diffs or parts +;; of such a diff. The supported "apply variants" are apply, stage, +;; unstage, discard, and reverse - more than Git itself knows about, +;; at least at the porcelain level. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit-core) +(require 'magit-diff) +(require 'magit-wip) + +;; For `magit-apply' +(declare-function magit-am-popup "magit-sequence" (&optional arg)) +(declare-function magit-patch-apply-popup "magit-files" (&optional arg)) +;; For `magit-discard-files' +(declare-function magit-checkout-stage "magit-merge" (file arg)) +(declare-function magit-checkout-read-stage "magit-merge" (file)) +(defvar auto-revert-verbose) +;; For `magit-stage-untracked' +(declare-function magit-submodule-add "magit-submodule" + (url &optional path name args)) +(declare-function magit-submodule-read-name-for-path "magit-submodule" + (path &optional prefer-short)) +(declare-function borg--maybe-absorb-gitdir "borg" (pkg)) +(declare-function borg--sort-submodule-sections "borg" (file)) +(defvar borg-user-emacs-directory) + +;;; Options + +(defcustom magit-delete-by-moving-to-trash t + "Whether Magit uses the system's trash can. + +You should absolutely not disable this and also remove `discard' +from `magit-no-confirm'. You shouldn't do that even if you have +all of the Magit-Wip modes enabled, because those modes do not +track any files that are not tracked in the proper branch." + :package-version '(magit . "2.1.0") + :group 'magit-essentials + :type 'boolean) + +(defcustom magit-unstage-committed t + "Whether unstaging a committed change reverts it instead. + +A committed change cannot be unstaged, because staging and +unstaging are actions that are concerned with the differences +between the index and the working tree, not with committed +changes. + +If this option is non-nil (the default), then typing \"u\" +\(`magit-unstage') on a committed change, causes it to be +reversed in the index but not the working tree. For more +information see command `magit-reverse-in-index'." + :package-version '(magit . "2.4.1") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-reverse-atomically nil + "Whether to reverse changes atomically. + +If some changes can be reversed while others cannot, then nothing +is reversed if the value of this option is non-nil. But when it +is nil, then the changes that can be reversed are reversed and +for the other changes diff files are created that contain the +rejected reversals." + :package-version '(magit . "2.7.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-post-stage-hook nil + "Hook run after staging changes. +This hook is run by `magit-refresh' if `this-command' +is a member of `magit-post-stage-hook-commands'." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type 'hook) + +(defvar magit-post-stage-hook-commands + '(magit-stage magit-stage-file magit-stage-modified)) + +(defcustom magit-post-unstage-hook nil + "Hook run after unstaging changes. +This hook is run by `magit-refresh' if `this-command' +is a member of `magit-post-unstage-hook-commands'." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type 'hook) + +(defvar magit-post-unstage-hook-commands + '(magit-unstage magit-unstage-file magit-unstage-all)) + +;;; Commands +;;;; Apply + +(defun magit-apply (&rest args) + "Apply the change at point to the working tree. +With a prefix argument fallback to a 3-way merge. Doing +so causes the change to be applied to the index as well." + (interactive (and current-prefix-arg (list "--3way"))) + (--when-let (magit-apply--get-selection) + (pcase (list (magit-diff-type) (magit-diff-scope)) + (`(,(or `unstaged `staged) ,_) + (user-error "Change is already in the working tree")) + (`(untracked ,(or `file `files)) + (magit-am-popup)) + (`(,_ region) (magit-apply-region it args)) + (`(,_ hunk) (magit-apply-hunk it args)) + (`(,_ hunks) (magit-apply-hunks it args)) + (`(rebase-sequence file) (magit-patch-apply-popup)) + (`(,_ file) (magit-apply-diff it args)) + (`(,_ files) (magit-apply-diffs it args))))) + +(defun magit-apply--section-content (section) + (buffer-substring-no-properties (if (magit-hunk-section-p section) + (oref section start) + (oref section content)) + (oref section end))) + +(defun magit-apply-diffs (sections &rest args) + (setq sections (magit-apply--get-diffs sections)) + (magit-apply-patch sections args + (mapconcat + (lambda (s) + (concat (magit-diff-file-header s) + (magit-apply--section-content s))) + sections ""))) + +(defun magit-apply-diff (section &rest args) + (setq section (car (magit-apply--get-diffs (list section)))) + (magit-apply-patch section args + (concat (magit-diff-file-header section) + (magit-apply--section-content section)))) + +(defun magit-apply-hunks (sections &rest args) + (let ((section (oref (car sections) parent))) + (when (string-match "^diff --cc" (oref section value)) + (user-error "Cannot un-/stage resolution hunks. Stage the whole file")) + (magit-apply-patch section args + (concat (oref section header) + (mapconcat 'magit-apply--section-content + sections ""))))) + +(defun magit-apply-hunk (section &rest args) + (when (string-match "^diff --cc" (magit-section-parent-value section)) + (user-error "Cannot un-/stage resolution hunks. Stage the whole file")) + (magit-apply-patch (oref section parent) args + (concat (magit-diff-file-header section) + (magit-apply--section-content section)))) + +(defun magit-apply-region (section &rest args) + (unless (magit-diff-context-p) + (user-error "Not enough context to apply region. Increase the context")) + (when (string-match "^diff --cc" (magit-section-parent-value section)) + (user-error "Cannot un-/stage resolution hunks. Stage the whole file")) + (magit-apply-patch (oref section parent) args + (concat (magit-diff-file-header section) + (magit-diff-hunk-region-patch section args)))) + +(defun magit-apply-patch (section:s args patch) + (let* ((files (if (atom section:s) + (list (oref section:s value)) + (--map (oref it value) section:s))) + (command (symbol-name this-command)) + (command (if (and command (string-match "^magit-\\([^-]+\\)" command)) + (match-string 1 command) + "apply")) + (no-context (not (magit-diff-context-p))) + (ignore-context (magit-diff-ignore-any-space-p))) + (when (and magit-wip-before-change-mode (not inhibit-magit-refresh)) + (magit-wip-commit-before-change files (concat " before " command))) + (with-temp-buffer + (insert patch) + (magit-run-git-with-input + "apply" args "-p0" + (and no-context "--unidiff-zero") + (and ignore-context "-C0") + "--ignore-space-change" "-")) + (unless inhibit-magit-refresh + (when magit-wip-after-apply-mode + (magit-wip-commit-after-apply files (concat " after " command))) + (magit-refresh)))) + +(defun magit-apply--get-selection () + (or (magit-region-sections '(hunk file module) t) + (let ((section (magit-current-section))) + (pcase (oref section type) + ((or `hunk `file `module) section) + ((or `staged `unstaged `untracked + `stashed-index `stashed-worktree `stashed-untracked) + (oref section children)) + (_ (user-error "Cannot apply this, it's not a change")))))) + +(defun magit-apply--get-diffs (sections) + (magit-section-case + ([file diffstat] + (--map (or (magit-get-section + (append `((file . ,(oref it value))) + (magit-section-ident magit-root-section))) + (error "Cannot get required diff headers")) + sections)) + (t sections))) + +(defun magit-apply--diff-ignores-whitespace-p () + (and (cl-intersection (if (derived-mode-p 'magit-diff-mode) + (nth 2 magit-refresh-args) + magit-diff-section-arguments) + '("--ignore-space-at-eol" + "--ignore-space-change" + "--ignore-all-space" + "--ignore-blank-lines") + :test #'equal) + t)) + +;;;; Stage + +(defun magit-stage (&optional intent) + "Add the change at point to the staging area. +With a prefix argument, INTENT, and an untracked file (or files) +at point, stage the file but not its content." + (interactive "P") + (--if-let (and (derived-mode-p 'magit-mode) (magit-apply--get-selection)) + (pcase (list (magit-diff-type) + (magit-diff-scope) + (magit-apply--diff-ignores-whitespace-p)) + (`(untracked ,_ ,_) (magit-stage-untracked intent)) + (`(unstaged region ,_) (magit-apply-region it "--cached")) + (`(unstaged hunk ,_) (magit-apply-hunk it "--cached")) + (`(unstaged hunks ,_) (magit-apply-hunks it "--cached")) + (`(unstaged file t) (magit-apply-diff it "--cached")) + (`(unstaged files t) (magit-apply-diffs it "--cached")) + (`(unstaged list t) (magit-apply-diffs it "--cached")) + (`(unstaged file nil) (magit-stage-1 "-u" (list (oref it value)))) + (`(unstaged files nil) (magit-stage-1 "-u" (magit-region-values nil t))) + (`(unstaged list nil) (magit-stage-modified)) + (`(staged ,_ ,_) (user-error "Already staged")) + (`(committed ,_ ,_) (user-error "Cannot stage committed changes")) + (`(undefined ,_ ,_) (user-error "Cannot stage this change"))) + (call-interactively 'magit-stage-file))) + +;;;###autoload +(defun magit-stage-file (file) + "Stage all changes to FILE. +With a prefix argument or when there is no file at point ask for +the file to be staged. Otherwise stage the file at point without +requiring confirmation." + (interactive + (let* ((atpoint (magit-section-value-if 'file)) + (current (magit-file-relative-name)) + (choices (nconc (magit-unstaged-files) + (magit-untracked-files))) + (default (car (member (or atpoint current) choices)))) + (list (if (or current-prefix-arg (not default)) + (magit-completing-read "Stage file" choices + nil t nil nil default) + default)))) + (magit-with-toplevel + (magit-stage-1 nil (list file)))) + +;;;###autoload +(defun magit-stage-modified (&optional all) + "Stage all changes to files modified in the worktree. +Stage all new content of tracked files and remove tracked files +that no longer exist in the working tree from the index also. +With a prefix argument also stage previously untracked (but not +ignored) files." + (interactive "P") + (when (magit-anything-staged-p) + (magit-confirm 'stage-all-changes)) + (magit-with-toplevel + (magit-stage-1 (if all "--all" "-u")))) + +(defun magit-stage-1 (arg &optional files) + (magit-wip-commit-before-change files " before stage") + (magit-run-git "add" arg (if files (cons "--" files) ".")) + (when magit-auto-revert-mode + (mapc #'magit-turn-on-auto-revert-mode-if-desired files)) + (magit-wip-commit-after-apply files " after stage")) + +(defun magit-stage-untracked (&optional intent) + (let* ((section (magit-current-section)) + (files (pcase (magit-diff-scope) + (`file (list (oref section value))) + (`files (magit-region-values nil t)) + (`list (magit-untracked-files)))) + plain repos) + (dolist (file files) + (if (and (not (file-symlink-p file)) + (magit-git-repo-p file t)) + (push file repos) + (push file plain))) + (magit-wip-commit-before-change files " before stage") + (when plain + (magit-run-git "add" (and intent "--intent-to-add") + "--" plain) + (when magit-auto-revert-mode + (mapc #'magit-turn-on-auto-revert-mode-if-desired plain))) + (dolist (repo repos) + (save-excursion + (goto-char (oref (magit-get-section + `((file . ,repo) (untracked) (status))) + start)) + (let* ((topdir (magit-toplevel)) + (package + (and (equal (bound-and-true-p borg-user-emacs-directory) + topdir) + (file-name-nondirectory (directory-file-name repo))))) + (magit-submodule-add + (let ((default-directory + (file-name-as-directory (expand-file-name repo)))) + (or (magit-get "remote" (magit-get-some-remote) "url") + (concat (file-name-as-directory ".") repo))) + repo + (magit-submodule-read-name-for-path repo package)) + (when package + (borg--sort-submodule-sections + (expand-file-name ".gitmodules" topdir)) + (let ((default-directory borg-user-emacs-directory)) + (borg--maybe-absorb-gitdir package)) + (when (and (y-or-n-p + (format "Also build and activate `%s' drone?" package)) + (fboundp 'borg-build) + (fboundp 'borg-activate)) + (borg-build package) + (borg-activate package)))))) + (magit-wip-commit-after-apply files " after stage"))) + +;;;; Unstage + +(defun magit-unstage () + "Remove the change at point from the staging area." + (interactive) + (--when-let (magit-apply--get-selection) + (pcase (list (magit-diff-type) + (magit-diff-scope) + (magit-apply--diff-ignores-whitespace-p)) + (`(untracked ,_ ,_) (user-error "Cannot unstage untracked changes")) + (`(unstaged ,_ ,_) (user-error "Already unstaged")) + (`(staged region ,_) (magit-apply-region it "--reverse" "--cached")) + (`(staged hunk ,_) (magit-apply-hunk it "--reverse" "--cached")) + (`(staged hunks ,_) (magit-apply-hunks it "--reverse" "--cached")) + (`(staged file t) (magit-apply-diff it "--reverse" "--cached")) + (`(staged files t) (magit-apply-diffs it "--reverse" "--cached")) + (`(staged list t) (magit-apply-diffs it "--reverse" "--cached")) + (`(staged file nil) (magit-unstage-1 (list (oref it value)))) + (`(staged files nil) (magit-unstage-1 (magit-region-values nil t))) + (`(staged list nil) (magit-unstage-all)) + (`(committed ,_ ,_) (if magit-unstage-committed + (magit-reverse-in-index) + (user-error "Cannot unstage committed changes"))) + (`(undefined ,_ ,_) (user-error "Cannot unstage this change"))))) + +;;;###autoload +(defun magit-unstage-file (file) + "Unstage all changes to FILE. +With a prefix argument or when there is no file at point ask for +the file to be unstaged. Otherwise unstage the file at point +without requiring confirmation." + (interactive + (let* ((atpoint (magit-section-value-if 'file)) + (current (magit-file-relative-name)) + (choices (magit-staged-files)) + (default (car (member (or atpoint current) choices)))) + (list (if (or current-prefix-arg (not default)) + (magit-completing-read "Unstage file" choices + nil t nil nil default) + default)))) + (magit-with-toplevel + (magit-unstage-1 (list file)))) + +(defun magit-unstage-1 (files) + (magit-wip-commit-before-change files " before unstage") + (if (magit-no-commit-p) + (magit-run-git "rm" "--cached" "--" files) + (magit-run-git "reset" "HEAD" "--" files)) + (magit-wip-commit-after-apply files " after unstage")) + +;;;###autoload +(defun magit-unstage-all () + "Remove all changes from the staging area." + (interactive) + (when (or (magit-anything-unstaged-p) + (magit-untracked-files)) + (magit-confirm 'unstage-all-changes)) + (magit-wip-commit-before-change nil " before unstage") + (magit-run-git "reset" "HEAD" "--") + (magit-wip-commit-after-apply nil " after unstage")) + +;;;; Discard + +(defun magit-discard () + "Remove the change at point." + (interactive) + (--when-let (magit-apply--get-selection) + (pcase (list (magit-diff-type) (magit-diff-scope)) + (`(committed ,_) (user-error "Cannot discard committed changes")) + (`(undefined ,_) (user-error "Cannot discard this change")) + (`(,_ region) (magit-discard-region it)) + (`(,_ hunk) (magit-discard-hunk it)) + (`(,_ hunks) (magit-discard-hunks it)) + (`(,_ file) (magit-discard-file it)) + (`(,_ files) (magit-discard-files it)) + (`(,_ list) (magit-discard-files it))))) + +(defun magit-discard-region (section) + (magit-confirm 'discard "Discard region") + (magit-discard-apply section 'magit-apply-region)) + +(defun magit-discard-hunk (section) + (magit-confirm 'discard "Discard hunk") + (magit-discard-apply section 'magit-apply-hunk)) + +(defun magit-discard-apply (section apply) + (if (eq (magit-diff-type section) 'unstaged) + (funcall apply section "--reverse") + (if (magit-anything-unstaged-p + nil (if (magit-file-section-p section) + (oref section value) + (magit-section-parent-value section))) + (progn (let ((inhibit-magit-refresh t)) + (funcall apply section "--reverse" "--cached") + (funcall apply section "--reverse" "--reject")) + (magit-refresh)) + (funcall apply section "--reverse" "--index")))) + +(defun magit-discard-hunks (sections) + (magit-confirm 'discard (format "Discard %s hunks from %s" + (length sections) + (magit-section-parent-value (car sections)))) + (magit-discard-apply-n sections 'magit-apply-hunks)) + +(defun magit-discard-apply-n (sections apply) + (let ((section (car sections))) + (if (eq (magit-diff-type section) 'unstaged) + (funcall apply sections "--reverse") + (if (magit-anything-unstaged-p + nil (if (magit-file-section-p section) + (oref section value) + (magit-section-parent-value section))) + (progn (let ((inhibit-magit-refresh t)) + (funcall apply sections "--reverse" "--cached") + (funcall apply sections "--reverse" "--reject")) + (magit-refresh)) + (funcall apply sections "--reverse" "--index"))))) + +(defun magit-discard-file (section) + (magit-discard-files (list section))) + +(defun magit-discard-files (sections) + (let ((auto-revert-verbose nil) + (type (magit-diff-type (car sections))) + (status (magit-file-status)) + files delete resurrect rename discard discard-new resolve) + (dolist (section sections) + (let ((file (oref section value))) + (push file files) + (pcase (cons (pcase type + (`staged ?X) + (`unstaged ?Y) + (`untracked ?Z)) + (cddr (assoc file status))) + (`(?Z) (dolist (f (magit-untracked-files nil file)) + (push f delete))) + ((or `(?Z ?? ??) `(?Z ?! ?!)) (push file delete)) + ((or `(?Z ?D ? ) `(,_ ?D ?D)) (push file delete)) + ((or `(,_ ?U ,_) `(,_ ,_ ?U)) (push file resolve)) + (`(,_ ?A ?A) (push file resolve)) + (`(?X ?M ,(or ? ?M ?D)) (push section discard)) + (`(?Y ,_ ?M ) (push section discard)) + (`(?X ?A ?M ) (push file discard-new)) + (`(?X ?C ?M ) (push file discard-new)) + (`(?X ?A ,(or ? ?D)) (push file delete)) + (`(?X ?C ,(or ? ?D)) (push file delete)) + (`(?X ?D ,(or ? ?M )) (push file resurrect)) + (`(?Y ,_ ?D ) (push file resurrect)) + (`(?X ?R ,(or ? ?M ?D)) (push file rename))))) + (unwind-protect + (let ((inhibit-magit-refresh t)) + (magit-wip-commit-before-change files " before discard") + (when resolve + (magit-discard-files--resolve (nreverse resolve))) + (when resurrect + (magit-discard-files--resurrect (nreverse resurrect))) + (when delete + (magit-discard-files--delete (nreverse delete) status)) + (when rename + (magit-discard-files--rename (nreverse rename) status)) + (when (or discard discard-new) + (magit-discard-files--discard (nreverse discard) + (nreverse discard-new))) + (magit-wip-commit-after-apply files " after discard")) + (magit-refresh)))) + +(defun magit-discard-files--resolve (files) + (if-let ((arg (and (cdr files) + (magit-read-char-case + (format "For these %i files\n%s\ncheckout:\n" + (length files) + (mapconcat (lambda (file) + (concat " " file)) + files "\n")) + t + (?o "[o]ur stage" "--ours") + (?t "[t]heir stage" "--theirs") + (?c "[c]onflict" "--merge") + (?i "decide [i]ndividually" nil))))) + (dolist (file files) + (magit-checkout-stage file arg)) + (dolist (file files) + (magit-checkout-stage file (magit-checkout-read-stage file))))) + +(defun magit-discard-files--resurrect (files) + (magit-confirm-files 'resurrect files) + (if (eq (magit-diff-type) 'staged) + (magit-call-git "reset" "--" files) + (magit-call-git "checkout" "--" files))) + +(defun magit-discard-files--delete (files status) + (magit-confirm-files (if magit-delete-by-moving-to-trash 'trash 'delete) + files) + (let ((delete-by-moving-to-trash magit-delete-by-moving-to-trash)) + (dolist (file files) + (if (memq (magit-diff-type) '(unstaged untracked)) + (progn (dired-delete-file file dired-recursive-deletes + magit-delete-by-moving-to-trash) + (dired-clean-up-after-deletion file)) + (pcase (nth 3 (assoc file status)) + (? (delete-file file t) + (magit-call-git "rm" "--cached" "--" file)) + (?M (let ((temp (magit-git-string "checkout-index" "--temp" file))) + (string-match + (format "\\(.+?\\)\t%s" (regexp-quote file)) temp) + (rename-file (match-string 1 temp) + (setq temp (concat file ".~{index}~"))) + (delete-file temp t)) + (magit-call-git "rm" "--cached" "--force" "--" file)) + (?D (magit-call-git "checkout" "--" file) + (delete-file file t) + (magit-call-git "rm" "--cached" "--force" "--" file))))))) + +(defun magit-discard-files--rename (files status) + (magit-confirm 'rename "Undo rename %s" "Undo %i renames" nil + (mapcar (lambda (file) + (setq file (assoc file status)) + (format "%s -> %s" (cadr file) (car file))) + files)) + (dolist (file files) + (let ((orig (cadr (assoc file status)))) + (if (file-exists-p file) + (progn + (--when-let (file-name-directory orig) + (make-directory it t)) + (magit-call-git "mv" file orig)) + (magit-call-git "rm" "--cached" "--" file) + (magit-call-git "reset" "--" orig))))) + +(defun magit-discard-files--discard (sections new-files) + (let ((files (--map (oref it value) sections))) + (magit-confirm-files 'discard (append files new-files) + (format "Discard %s changes in" (magit-diff-type))) + (if (eq (magit-diff-type (car sections)) 'unstaged) + (magit-call-git "checkout" "--" files) + (when new-files + (magit-call-git "add" "--" new-files) + (magit-call-git "reset" "--" new-files)) + (let ((binaries (magit-binary-files "--cached"))) + (when binaries + (setq sections + (--remove (member (oref it value) binaries) + sections))) + (cond ((= (length sections) 1) + (magit-discard-apply (car sections) 'magit-apply-diff)) + (sections + (magit-discard-apply-n sections 'magit-apply-diffs))) + (when binaries + (let ((modified (magit-unstaged-files t))) + (setq binaries (--separate (member it modified) binaries))) + (when (cadr binaries) + (magit-call-git "reset" "--" (cadr binaries))) + (when (car binaries) + (user-error + (concat + "Cannot discard staged changes to binary files, " + "which also have unstaged changes. Unstage instead.")))))))) + +;;;; Reverse + +(defun magit-reverse (&rest args) + "Reverse the change at point in the working tree. +With a prefix argument fallback to a 3-way merge. Doing +so causes the change to be applied to the index as well." + (interactive (and current-prefix-arg (list "--3way"))) + (--when-let (magit-apply--get-selection) + (pcase (list (magit-diff-type) (magit-diff-scope)) + (`(untracked ,_) (user-error "Cannot reverse untracked changes")) + (`(unstaged ,_) (user-error "Cannot reverse unstaged changes")) + (`(,_ region) (magit-reverse-region it args)) + (`(,_ hunk) (magit-reverse-hunk it args)) + (`(,_ hunks) (magit-reverse-hunks it args)) + (`(,_ file) (magit-reverse-file it args)) + (`(,_ files) (magit-reverse-files it args)) + (`(,_ list) (magit-reverse-files it args))))) + +(defun magit-reverse-region (section args) + (magit-confirm 'reverse "Reverse region") + (magit-reverse-apply section 'magit-apply-region args)) + +(defun magit-reverse-hunk (section args) + (magit-confirm 'reverse "Reverse hunk") + (magit-reverse-apply section 'magit-apply-hunk args)) + +(defun magit-reverse-hunks (sections args) + (magit-confirm 'reverse + (format "Reverse %s hunks from %s" + (length sections) + (magit-section-parent-value (car sections)))) + (magit-reverse-apply sections 'magit-apply-hunks args)) + +(defun magit-reverse-file (section args) + (magit-reverse-files (list section) args)) + +(defun magit-reverse-files (sections args) + (pcase-let ((`(,binaries ,sections) + (let ((bs (magit-binary-files + (cond ((derived-mode-p 'magit-revision-mode) + (let ((rev (car magit-refresh-args))) + (format "%s^..%s" rev rev))) + ((derived-mode-p 'magit-diff-mode) + (car magit-refresh-args)) + (t + "--cached"))))) + (--separate (member (oref it value) bs) + sections)))) + (magit-confirm-files 'reverse (--map (oref it value) sections)) + (cond ((= (length sections) 1) + (magit-reverse-apply (car sections) 'magit-apply-diff args)) + (sections + (magit-reverse-apply sections 'magit-apply-diffs args))) + (when binaries + (user-error "Cannot reverse binary files")))) + +(defun magit-reverse-apply (section:s apply args) + (funcall apply section:s "--reverse" args + (and (not magit-reverse-atomically) + (not (member "--3way" args)) + "--reject"))) + +(defun magit-reverse-in-index (&rest args) + "Reverse the change at point in the index but not the working tree. + +Use this command to extract a change from `HEAD', while leaving +it in the working tree, so that it can later be committed using +a separate commit. A typical workflow would be: + +0. Optionally make sure that there are no uncommitted changes. +1. Visit the `HEAD' commit and navigate to the change that should + not have been included in that commit. +2. Type \"u\" (`magit-unstage') to reverse it in the index. + This assumes that `magit-unstage-committed-changes' is non-nil. +3. Type \"c e\" to extend `HEAD' with the staged changes, + including those that were already staged before. +4. Optionally stage the remaining changes using \"s\" or \"S\" + and then type \"c c\" to create a new commit." + (interactive) + (magit-reverse (cons "--cached" args))) + +;;; _ +(provide 'magit-apply) +;;; magit-apply.el ends here diff --git a/elpa/magit-20181113.1837/magit-autoloads.el b/elpa/magit-20181113.1837/magit-autoloads.el new file mode 100644 index 00000000..baea3487 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-autoloads.el @@ -0,0 +1,2695 @@ +;;; magit-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "git-rebase" "git-rebase.el" (0 0 0 0)) +;;; Generated autoloads from git-rebase.el + +(autoload 'git-rebase-mode "git-rebase" "\ +Major mode for editing of a Git rebase file. + +Rebase files are generated when you run 'git rebase -i' or run +`magit-interactive-rebase'. They describe how Git should perform +the rebase. See the documentation for git-rebase (e.g., by +running 'man git-rebase' at the command line) for details. + +\(fn)" t nil) + +(defconst git-rebase-filename-regexp "/git-rebase-todo\\'") + +(add-to-list 'auto-mode-alist (cons git-rebase-filename-regexp 'git-rebase-mode)) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "git-rebase" '("git-rebase-"))) + +;;;*** + +;;;### (autoloads nil "magit" "magit.el" (0 0 0 0)) +;;; Generated autoloads from magit.el + (autoload 'magit-dispatch-popup "magit" nil t) + (autoload 'magit-run-popup "magit" nil t) + +(autoload 'magit-git-command "magit" "\ +Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. \"git \" is +used as initial input, but can be deleted to run another command. + +With a prefix argument COMMAND is run in the top-level directory +of the current working tree, otherwise in `default-directory'. + +\(fn COMMAND)" t nil) + +(autoload 'magit-git-command-topdir "magit" "\ +Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. \"git \" is +used as initial input, but can be deleted to run another command. + +COMMAND is run in the top-level directory of the current +working tree. + +\(fn COMMAND)" t nil) + +(autoload 'magit-shell-command "magit" "\ +Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. With a +prefix argument COMMAND is run in the top-level directory of +the current working tree, otherwise in `default-directory'. + +\(fn COMMAND)" t nil) + +(autoload 'magit-shell-command-topdir "magit" "\ +Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. COMMAND +is run in the top-level directory of the current working tree. + +\(fn COMMAND)" t nil) + +(autoload 'magit-version "magit" "\ +Return the version of Magit currently in use. +If optional argument PRINT-DEST is non-nil, output +stream (interactively, the echo area, or the current buffer with +a prefix argument), also print the used versions of Magit, Git, +and Emacs to it. + +\(fn &optional PRINT-DEST)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-apply" "magit-apply.el" (0 0 0 0)) +;;; Generated autoloads from magit-apply.el + +(autoload 'magit-stage-file "magit-apply" "\ +Stage all changes to FILE. +With a prefix argument or when there is no file at point ask for +the file to be staged. Otherwise stage the file at point without +requiring confirmation. + +\(fn FILE)" t nil) + +(autoload 'magit-stage-modified "magit-apply" "\ +Stage all changes to files modified in the worktree. +Stage all new content of tracked files and remove tracked files +that no longer exist in the working tree from the index also. +With a prefix argument also stage previously untracked (but not +ignored) files. + +\(fn &optional ALL)" t nil) + +(autoload 'magit-unstage-file "magit-apply" "\ +Unstage all changes to FILE. +With a prefix argument or when there is no file at point ask for +the file to be unstaged. Otherwise unstage the file at point +without requiring confirmation. + +\(fn FILE)" t nil) + +(autoload 'magit-unstage-all "magit-apply" "\ +Remove all changes from the staging area. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-apply" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-autorevert" "magit-autorevert.el" (0 +;;;;;; 0 0 0)) +;;; Generated autoloads from magit-autorevert.el + +(defvar magit-auto-revert-mode (and (not global-auto-revert-mode) (not noninteractive)) "\ +Non-nil if Magit-Auto-Revert mode is enabled. +See the `magit-auto-revert-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `magit-auto-revert-mode'.") + +(custom-autoload 'magit-auto-revert-mode "magit-autorevert" nil) + +(autoload 'magit-auto-revert-mode "magit-autorevert" "\ +Toggle Auto-Revert mode in all buffers. +With prefix ARG, enable Magit-Auto-Revert mode if ARG is positive; +otherwise, disable it. If called from Lisp, enable the mode if +ARG is omitted or nil. + +Auto-Revert mode is enabled in all buffers where +`magit-turn-on-auto-revert-mode-if-desired' would do it. +See `auto-revert-mode' for more information on Auto-Revert mode. + +\(fn &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-autorevert" '("auto-revert-buffer" "magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-bisect" "magit-bisect.el" (0 0 0 0)) +;;; Generated autoloads from magit-bisect.el + (autoload 'magit-bisect-popup "magit-bisect" nil t) + +(autoload 'magit-bisect-start "magit-bisect" "\ +Start a bisect session. + +Bisecting a bug means to find the commit that introduced it. +This command starts such a bisect session by asking for a know +good and a bad commit. To move the session forward use the +other actions from the bisect popup (\\\\[magit-bisect-popup]). + +\(fn BAD GOOD)" t nil) + +(autoload 'magit-bisect-reset "magit-bisect" "\ +After bisecting, cleanup bisection state and return to original `HEAD'. + +\(fn)" t nil) + +(autoload 'magit-bisect-good "magit-bisect" "\ +While bisecting, mark the current commit as good. +Use this after you have asserted that the commit does not contain +the bug in question. + +\(fn)" t nil) + +(autoload 'magit-bisect-bad "magit-bisect" "\ +While bisecting, mark the current commit as bad. +Use this after you have asserted that the commit does contain the +bug in question. + +\(fn)" t nil) + +(autoload 'magit-bisect-skip "magit-bisect" "\ +While bisecting, skip the current commit. +Use this if for some reason the current commit is not a good one +to test. This command lets Git choose a different one. + +\(fn)" t nil) + +(autoload 'magit-bisect-run "magit-bisect" "\ +Bisect automatically by running commands after each step. + +Unlike `git bisect run' this can be used before bisecting has +begun. In that case it behaves like `git bisect start; git +bisect run'. + +\(fn CMDLINE &optional BAD GOOD)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-bisect" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-blame" "magit-blame.el" (0 0 0 0)) +;;; Generated autoloads from magit-blame.el + +(autoload 'magit-blame-echo "magit-blame" "\ +For each line show the revision in which it was added. +Show the information about the chunk at point in the echo area +when moving between chunks. Unlike other blaming commands, do +not turn on `read-only-mode'. + +\(fn)" t nil) + +(autoload 'magit-blame-addition "magit-blame" "\ +For each line show the revision in which it was added. + +\(fn)" t nil) + +(autoload 'magit-blame-removal "magit-blame" "\ +For each line show the revision in which it was removed. + +\(fn)" t nil) + +(autoload 'magit-blame-reverse "magit-blame" "\ +For each line show the last revision in which it still exists. + +\(fn)" t nil) + (autoload 'magit-blame-popup "magit-blame" nil t) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-blame" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-bookmark" "magit-bookmark.el" (0 0 0 +;;;;;; 0)) +;;; Generated autoloads from magit-bookmark.el + +(autoload 'magit-bookmark--status-jump "magit-bookmark" "\ +Handle a Magit status BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--status-make-record "magit-bookmark" "\ +Create a Magit status bookmark. + +\(fn)" nil nil) + +(autoload 'magit-bookmark--refs-jump "magit-bookmark" "\ +Handle a Magit refs BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--refs-make-record "magit-bookmark" "\ +Create a Magit refs bookmark. + +\(fn)" nil nil) + +(autoload 'magit-bookmark--log-jump "magit-bookmark" "\ +Handle a Magit log BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--log-make-record "magit-bookmark" "\ +Create a Magit log bookmark. + +\(fn)" nil nil) + +(autoload 'magit-bookmark--reflog-jump "magit-bookmark" "\ +Handle a Magit reflog BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--reflog-make-record "magit-bookmark" "\ +Create a Magit reflog bookmark. + +\(fn)" nil nil) + +(autoload 'magit-bookmark--stashes-jump "magit-bookmark" "\ +Handle a Magit stash list BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--stashes-make-record "magit-bookmark" "\ +Create a Magit stash list bookmark. + +\(fn)" nil nil) + +(autoload 'magit-bookmark--cherry-jump "magit-bookmark" "\ +Handle a Magit cherry BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--cherry-make-record "magit-bookmark" "\ +Create a Magit cherry bookmark. + +\(fn)" nil nil) + +(autoload 'magit-bookmark--diff-jump "magit-bookmark" "\ +Handle a Magit diff BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--diff-make-record "magit-bookmark" "\ +Create a Magit diff bookmark. + +\(fn)" nil nil) + +(autoload 'magit-bookmark--revision-jump "magit-bookmark" "\ +Handle a Magit revision BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--revision-make-record "magit-bookmark" "\ +Create a Magit revision bookmark. + +\(fn)" nil nil) + +(autoload 'magit-bookmark--stash-jump "magit-bookmark" "\ +Handle a Magit stash BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--stash-make-record "magit-bookmark" "\ +Create a Magit stash bookmark. + +\(fn)" nil nil) + +(autoload 'magit-bookmark--submodules-jump "magit-bookmark" "\ +Handle a Magit submodule list BOOKMARK. + +\(fn BOOKMARK)" nil nil) + +(autoload 'magit-bookmark--submodules-make-record "magit-bookmark" "\ +Create a Magit submodule list bookmark. + +\(fn)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-bookmark" '("magit-bookmark--"))) + +;;;*** + +;;;### (autoloads nil "magit-branch" "magit-branch.el" (0 0 0 0)) +;;; Generated autoloads from magit-branch.el + (autoload 'magit-branch-popup "magit" nil t) + +(autoload 'magit-checkout "magit-branch" "\ +Checkout REVISION, updating the index and the working tree. +If REVISION is a local branch, then that becomes the current +branch. If it is something else, then `HEAD' becomes detached. +Checkout fails if the working tree or the staging area contain +changes. + +\(git checkout REVISION). + +\(fn REVISION)" t nil) + +(autoload 'magit-branch-create "magit-branch" "\ +Create BRANCH at branch or revision START-POINT. + +\(git branch [ARGS] BRANCH START-POINT). + +\(fn BRANCH START-POINT &optional ARGS)" t nil) + +(autoload 'magit-branch-and-checkout "magit-branch" "\ +Create and checkout BRANCH at branch or revision START-POINT. + +\(git checkout [ARGS] -b BRANCH START-POINT). + +\(fn BRANCH START-POINT &optional ARGS)" t nil) + +(autoload 'magit-branch-or-checkout "magit-branch" "\ +Hybrid between `magit-checkout' and `magit-branch-and-checkout'. + +Ask the user for an existing branch or revision. If the user +input actually can be resolved as a branch or revision, then +check that out, just like `magit-checkout' would. + +Otherwise create and checkout a new branch using the input as +its name. Before doing so read the starting-point for the new +branch. This is similar to what `magit-branch-and-checkout' +does. + +\(fn ARG &optional START-POINT)" t nil) + +(autoload 'magit-branch-checkout "magit-branch" "\ +Checkout an existing or new local branch. + +Read a branch name from the user offering all local branches and +a subset of remote branches as candidates. Omit remote branches +for which a local branch by the same name exists from the list +of candidates. The user can also enter a completely new branch +name. + +- If the user selects an existing local branch, then check that + out. + +- If the user selects a remote branch, then create and checkout + a new local branch with the same name. Configure the selected + remote branch as push target. + +- If the user enters a new branch name, then create and check + that out, after also reading the starting-point from the user. + +In the latter two cases the upstream is also set. Whether it is +set to the chosen START-POINT or something else depends on the +value of `magit-branch-adjust-remote-upstream-alist', just like +when using `magit-branch-and-checkout'. + +\(fn BRANCH &optional START-POINT)" t nil) + +(autoload 'magit-branch-orphan "magit-branch" "\ +Create and checkout an orphan BRANCH with contents from revision START-POINT. + +\(git checkout --orphan [ARGS] BRANCH START-POINT). + +\(fn BRANCH START-POINT &optional ARGS)" t nil) + +(autoload 'magit-branch-pull-request "magit-branch" "\ +Create and configure a new branch from a pull-request. +Please see the manual for more information. + +\(fn PR)" t nil) + +(autoload 'magit-branch-spinoff "magit-branch" "\ +Create new branch from the unpushed commits. + +Create and checkout a new branch starting at and tracking the +current branch. That branch in turn is reset to the last commit +it shares with its upstream. If the current branch has no +upstream or no unpushed commits, then the new branch is created +anyway and the previously current branch is not touched. + +This is useful to create a feature branch after work has already +began on the old branch (likely but not necessarily \"master\"). + +If the current branch is a member of the value of option +`magit-branch-prefer-remote-upstream' (which see), then the +current branch will be used as the starting point as usual, but +the upstream of the starting-point may be used as the upstream +of the new branch, instead of the starting-point itself. + +If optional FROM is non-nil, then the source branch is reset +to `FROM~', instead of to the last commit it shares with its +upstream. Interactively, FROM is only ever non-nil, if the +region selects some commits, and among those commits, FROM is +the commit that is the fewest commits ahead of the source +branch. + +The commit at the other end of the selection actually does not +matter, all commits between FROM and `HEAD' are moved to the new +branch. If FROM is not reachable from `HEAD' or is reachable +from the source branch's upstream, then an error is raised. + +\(fn BRANCH &optional FROM &rest ARGS)" t nil) + +(autoload 'magit-branch-reset "magit-branch" "\ +Reset a branch to the tip of another branch or any other commit. + +When the branch being reset is the current branch, then do a +hard reset. If there are any uncommitted changes, then the user +has to confirm the reset because those changes would be lost. + +This is useful when you have started work on a feature branch but +realize it's all crap and want to start over. + +When resetting to another branch and a prefix argument is used, +then also set the target branch as the upstream of the branch +that is being reset. + +\(fn BRANCH TO &optional ARGS SET-UPSTREAM)" t nil) + +(autoload 'magit-branch-delete "magit-branch" "\ +Delete one or multiple branches. +If the region marks multiple branches, then offer to delete +those, otherwise prompt for a single branch to be deleted, +defaulting to the branch at point. + +\(fn BRANCHES &optional FORCE)" t nil) + +(autoload 'magit-branch-rename "magit-branch" "\ +Rename the branch named OLD to NEW. + +With a prefix argument FORCE, rename even if a branch named NEW +already exists. + +If `branch.OLD.pushRemote' is set, then unset it. Depending on +the value of `magit-branch-rename-push-target' (which see) maybe +set `branch.NEW.pushRemote' and maybe rename the push-target on +the remote. + +\(fn OLD NEW &optional FORCE)" t nil) + +(autoload 'magit-branch-shelve "magit-branch" "\ +Shelve a BRANCH. +Rename \"refs/heads/BRANCH\" to \"refs/shelved/BRANCH\", +and also rename the respective reflog file. + +\(fn BRANCH)" t nil) + +(autoload 'magit-branch-unshelve "magit-branch" "\ +Unshelve a BRANCH +Rename \"refs/shelved/BRANCH\" to \"refs/heads/BRANCH\", +and also rename the respective reflog file. + +\(fn BRANCH)" t nil) + +(autoload 'magit-branch-config-popup "magit-branch" "\ +Popup console for setting branch variables. + +\(fn BRANCH)" t nil) + +(autoload 'magit-edit-branch*description "magit-branch" "\ +Edit the description of the current branch. +With a prefix argument edit the description of another branch. + +The description for the branch named NAME is stored in the Git +variable `branch..description'. + +\(fn BRANCH)" t nil) + +(autoload 'magit-set-branch*merge/remote "magit-branch" "\ +Set or unset the upstream of the current branch. +With a prefix argument do so for another branch. + +When the branch in question already has an upstream then simply +unsets it. Invoke this command again to set another upstream. + +Together the Git variables `branch..remote' and +`branch..merge' define the upstream branch of the local +branch named NAME. The value of `branch..remote' is the +name of the upstream remote. The value of `branch..merge' +is the full reference of the upstream branch, on the remote. + +Non-interactively, when UPSTREAM is non-nil, then always set it +as the new upstream, regardless of whether another upstream was +already set. When nil, then always unset. + +\(fn BRANCH UPSTREAM)" t nil) + +(autoload 'magit-cycle-branch*rebase "magit-branch" "\ +Cycle the value of `branch..rebase' for the current branch. +With a prefix argument cycle the value for another branch. + +The Git variables `branch..rebase' controls whether pulling +into the branch named NAME is done by rebasing that branch onto +the fetched branch or by merging that branch. + +When `true' then pulling is done by rebasing. +When `false' then pulling is done by merging. + +When that variable is undefined then the value of `pull.rebase' +is used instead. It defaults to `false'. + +\(fn BRANCH)" t nil) + +(autoload 'magit-cycle-branch*pushRemote "magit-branch" "\ +Cycle the value of `branch..pushRemote' for the current branch. +With a prefix argument cycle the value for another branch. + +The Git variable `branch..pushRemote' specifies the remote +that the branch named NAME is usually pushed to. The value has +to be the name of an existing remote. + +If that variable is undefined, then the value of the Git variable +`remote.pushDefault' is used instead, provided that it is defined, +which by default it is not. + +\(fn BRANCH)" t nil) + +(autoload 'magit-cycle-pull\.rebase "magit-branch" "\ +Cycle the repository-local value of `pull.rebase'. + +The Git variable `pull.rebase' specifies whether pulling is done +by rebasing or by merging. It can be overwritten using the Git +variable `branch..rebase'. + +When `true' then pulling is done by rebasing. +When `false' (the default) then pulling is done by merging. + +\(fn)" t nil) + +(autoload 'magit-cycle-remote\.pushDefault "magit-branch" "\ +Cycle the repository-local value of `remote.pushDefault'. + +The Git variable `remote.pushDefault' specifies the remote that +local branches are usually pushed to. It can be overwritten +using the Git variable `branch..pushRemote'. + +\(fn)" t nil) + +(autoload 'magit-cycle-branch*autoSetupMerge "magit-branch" "\ +Cycle the repository-local value of `branch.autoSetupMerge'. + +The Git variable `branch.autoSetupMerge' under what circumstances +creating a branch (named NAME) should result in the variables +`branch..merge' and `branch..remote' being set +according to the starting point used to create the branch. If +the starting point isn't a branch, then these variables are never +set. + +When `always' then the variables are set regardless of whether +the starting point is a local or a remote branch. + +When `true' (the default) then the variable are set when the +starting point is a remote branch, but not when it is a local +branch. + +When `false' then the variables are never set. + +\(fn)" t nil) + +(autoload 'magit-cycle-branch*autoSetupRebase "magit-branch" "\ +Cycle the repository-local value of `branch.autoSetupRebase'. + +The Git variable `branch.autoSetupRebase' specifies whether +creating a branch (named NAME) should result in the variable +`branch..rebase' being set to `true'. + +When `always' then the variable is set regardless of whether the +starting point is a local or a remote branch. + +When `local' then the variable are set when the starting point +is a local branch, but not when it is a remote branch. + +When `remote' then the variable are set when the starting point +is a remote branch, but not when it is a local branch. + +When `never' (the default) then the variable is never set. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-branch" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-clone" "magit-clone.el" (0 0 0 0)) +;;; Generated autoloads from magit-clone.el + +(autoload 'magit-clone "magit-clone" "\ +Clone the REPOSITORY to DIRECTORY. +Then show the status buffer for the new repository. + +\(fn REPOSITORY DIRECTORY)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-clone" '("magit-clone-"))) + +;;;*** + +;;;### (autoloads nil "magit-collab" "magit-collab.el" (0 0 0 0)) +;;; Generated autoloads from magit-collab.el + +(autoload 'magit-browse-pull-request "magit-collab" "\ +Visit pull-request PR using `browse-url'. + +Currently this only supports Github, but that restriction will +be lifted eventually to support other Git forges. + +\(fn PR)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-collab" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-commit" "magit-commit.el" (0 0 0 0)) +;;; Generated autoloads from magit-commit.el + +(autoload 'magit-commit-create "magit-commit" "\ +Create a new commit on `HEAD'. +With a prefix argument, amend to the commit at `HEAD' instead. + +\(git commit [--amend] ARGS) + +\(fn &optional ARGS)" t nil) + +(autoload 'magit-commit-amend "magit-commit" "\ +Amend the last commit. + +\(git commit --amend ARGS) + +\(fn &optional ARGS)" t nil) + +(autoload 'magit-commit-extend "magit-commit" "\ +Amend the last commit, without editing the message. + +With a prefix argument keep the committer date, otherwise change +it. The option `magit-commit-extend-override-date' can be used +to inverse the meaning of the prefix argument. +\(git commit +--amend --no-edit) + +\(fn &optional ARGS OVERRIDE-DATE)" t nil) + +(autoload 'magit-commit-reword "magit-commit" "\ +Reword the last commit, ignoring staged changes. + +With a prefix argument keep the committer date, otherwise change +it. The option `magit-commit-reword-override-date' can be used +to inverse the meaning of the prefix argument. + +Non-interactively respect the optional OVERRIDE-DATE argument +and ignore the option. + +\(git commit --amend --only) + +\(fn &optional ARGS OVERRIDE-DATE)" t nil) + +(autoload 'magit-commit-fixup "magit-commit" "\ +Create a fixup commit. + +With a prefix argument the target COMMIT has to be confirmed. +Otherwise the commit at point may be used without confirmation +depending on the value of option `magit-commit-squash-confirm'. + +\(fn &optional COMMIT ARGS)" t nil) + +(autoload 'magit-commit-squash "magit-commit" "\ +Create a squash commit, without editing the squash message. + +With a prefix argument the target COMMIT has to be confirmed. +Otherwise the commit at point may be used without confirmation +depending on the value of option `magit-commit-squash-confirm'. + +\(fn &optional COMMIT ARGS)" t nil) + +(autoload 'magit-commit-augment "magit-commit" "\ +Create a squash commit, editing the squash message. + +With a prefix argument the target COMMIT has to be confirmed. +Otherwise the commit at point may be used without confirmation +depending on the value of option `magit-commit-squash-confirm'. + +\(fn &optional COMMIT ARGS)" t nil) + +(autoload 'magit-commit-instant-fixup "magit-commit" "\ +Create a fixup commit targeting COMMIT and instantly rebase. + +\(fn &optional COMMIT ARGS)" t nil) + +(autoload 'magit-commit-instant-squash "magit-commit" "\ +Create a squash commit targeting COMMIT and instantly rebase. + +\(fn &optional COMMIT ARGS)" t nil) + +(autoload 'magit-commit-reshelve "magit-commit" "\ +Change the committer date and possibly the author date of `HEAD'. + +If you are the author of `HEAD', then both dates are changed, +otherwise only the committer date. The current time is used +as the initial minibuffer input and the original author (if +that is you) or committer date is available as the previous +history element. + +\(fn DATE)" t nil) + (autoload 'magit-commit-absorb-popup "magit-commit" nil t) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-commit" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-diff" "magit-diff.el" (0 0 0 0)) +;;; Generated autoloads from magit-diff.el + +(autoload 'magit-diff-popup "magit-diff" "\ +Popup console for diff commands. + +\(fn ARG)" t nil) + +(autoload 'magit-diff-buffer-file-popup "magit-diff" "\ +Popup console for diff commands. + +This is a variant of `magit-diff-popup' which shows the same popup +but which limits the diff to the file being visited in the current +buffer. + +\(fn)" t nil) + +(autoload 'magit-diff-dwim "magit-diff" "\ +Show changes for the thing at point. + +\(fn &optional ARGS FILES)" t nil) + +(autoload 'magit-diff-range "magit-diff" "\ +Show differences between two commits. + +REV-OR-RANGE should be a range or a single revision. If it is a +revision, then show changes in the working tree relative to that +revision. If it is a range, but one side is omitted, then show +changes relative to `HEAD'. + +If the region is active, use the revisions on the first and last +line of the region as the two sides of the range. With a prefix +argument, instead of diffing the revisions, choose a revision to +view changes along, starting at the common ancestor of both +revisions (i.e., use a \"...\" range). + +\(fn REV-OR-RANGE &optional ARGS FILES)" t nil) + +(autoload 'magit-diff-working-tree "magit-diff" "\ +Show changes between the current working tree and the `HEAD' commit. +With a prefix argument show changes between the working tree and +a commit read from the minibuffer. + +\(fn &optional REV ARGS FILES)" t nil) + +(autoload 'magit-diff-staged "magit-diff" "\ +Show changes between the index and the `HEAD' commit. +With a prefix argument show changes between the index and +a commit read from the minibuffer. + +\(fn &optional REV ARGS FILES)" t nil) + +(autoload 'magit-diff-unstaged "magit-diff" "\ +Show changes between the working tree and the index. + +\(fn &optional ARGS FILES)" t nil) + +(autoload 'magit-diff-unmerged "magit-diff" "\ +Show changes that are being merged. + +\(fn &optional ARGS FILES)" t nil) + +(autoload 'magit-diff-while-committing "magit-diff" "\ +While committing, show the changes that are about to be committed. +While amending, invoking the command again toggles between +showing just the new changes or all the changes that will +be committed. + +\(fn &optional ARGS)" t nil) + +(autoload 'magit-diff-buffer-file "magit-diff" "\ +Show diff for the blob or file visited in the current buffer. + +\(fn)" t nil) + +(autoload 'magit-diff-paths "magit-diff" "\ +Show changes between any two files on disk. + +\(fn A B)" t nil) + +(autoload 'magit-show-commit "magit-diff" "\ +Visit the revision at point in another buffer. +If there is no revision at point or with a prefix argument prompt +for a revision. + +\(fn REV &optional ARGS FILES MODULE)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-diff" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-ediff" "magit-ediff.el" (0 0 0 0)) +;;; Generated autoloads from magit-ediff.el + (autoload 'magit-ediff-popup "magit-ediff" nil t) + +(autoload 'magit-ediff-resolve "magit-ediff" "\ +Resolve outstanding conflicts in FILE using Ediff. +FILE has to be relative to the top directory of the repository. + +In the rare event that you want to manually resolve all +conflicts, including those already resolved by Git, use +`ediff-merge-revisions-with-ancestor'. + +\(fn FILE)" t nil) + +(autoload 'magit-ediff-stage "magit-ediff" "\ +Stage and unstage changes to FILE using Ediff. +FILE has to be relative to the top directory of the repository. + +\(fn FILE)" t nil) + +(autoload 'magit-ediff-compare "magit-ediff" "\ +Compare REVA:FILEA with REVB:FILEB using Ediff. + +FILEA and FILEB have to be relative to the top directory of the +repository. If REVA or REVB is nil, then this stands for the +working tree state. + +If the region is active, use the revisions on the first and last +line of the region. With a prefix argument, instead of diffing +the revisions, choose a revision to view changes along, starting +at the common ancestor of both revisions (i.e., use a \"...\" +range). + +\(fn REVA REVB FILEA FILEB)" t nil) + +(autoload 'magit-ediff-dwim "magit-ediff" "\ +Compare, stage, or resolve using Ediff. +This command tries to guess what file, and what commit or range +the user wants to compare, stage, or resolve using Ediff. It +might only be able to guess either the file, or range or commit, +in which case the user is asked about the other. It might not +always guess right, in which case the appropriate `magit-ediff-*' +command has to be used explicitly. If it cannot read the user's +mind at all, then it asks the user for a command to run. + +\(fn)" t nil) + +(autoload 'magit-ediff-show-staged "magit-ediff" "\ +Show staged changes using Ediff. + +This only allows looking at the changes; to stage, unstage, +and discard changes using Ediff, use `magit-ediff-stage'. + +FILE must be relative to the top directory of the repository. + +\(fn FILE)" t nil) + +(autoload 'magit-ediff-show-unstaged "magit-ediff" "\ +Show unstaged changes using Ediff. + +This only allows looking at the changes; to stage, unstage, +and discard changes using Ediff, use `magit-ediff-stage'. + +FILE must be relative to the top directory of the repository. + +\(fn FILE)" t nil) + +(autoload 'magit-ediff-show-working-tree "magit-ediff" "\ +Show changes between `HEAD' and working tree using Ediff. +FILE must be relative to the top directory of the repository. + +\(fn FILE)" t nil) + +(autoload 'magit-ediff-show-commit "magit-ediff" "\ +Show changes introduced by COMMIT using Ediff. + +\(fn COMMIT)" t nil) + +(autoload 'magit-ediff-show-stash "magit-ediff" "\ +Show changes introduced by STASH using Ediff. +`magit-ediff-show-stash-with-index' controls whether a +three-buffer Ediff is used in order to distinguish changes in the +stash that were staged. + +\(fn STASH)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-ediff" '("magit-ediff-"))) + +;;;*** + +;;;### (autoloads nil "magit-extras" "magit-extras.el" (0 0 0 0)) +;;; Generated autoloads from magit-extras.el + +(autoload 'magit-run-git-gui "magit-extras" "\ +Run `git gui' for the current git repository. + +\(fn)" t nil) + +(autoload 'magit-run-git-gui-blame "magit-extras" "\ +Run `git gui blame' on the given FILENAME and COMMIT. +Interactively run it for the current file and the `HEAD', with a +prefix or when the current file cannot be determined let the user +choose. When the current buffer is visiting FILENAME instruct +blame to center around the line point is on. + +\(fn COMMIT FILENAME &optional LINENUM)" t nil) + +(autoload 'magit-run-gitk "magit-extras" "\ +Run `gitk' in the current repository. + +\(fn)" t nil) + +(autoload 'magit-run-gitk-branches "magit-extras" "\ +Run `gitk --branches' in the current repository. + +\(fn)" t nil) + +(autoload 'magit-run-gitk-all "magit-extras" "\ +Run `gitk --all' in the current repository. + +\(fn)" t nil) + +(autoload 'ido-enter-magit-status "magit-extras" "\ +Drop into `magit-status' from file switching. + +This command does not work in Emacs 26. It does work in Emacs 25 +and Emacs 27. See https://github.com/magit/magit/issues/3634 and +https://debbugs.gnu.org/cgi/bugreport.cgi?bug=31707. + +To make this command available use something like: + + (add-hook \\='ido-setup-hook + (lambda () + (define-key ido-completion-map + (kbd \"C-x g\") \\='ido-enter-magit-status))) + +Starting with Emacs 25.1 the Ido keymaps are defined just once +instead of every time Ido is invoked, so now you can modify it +like pretty much every other keymap: + + (define-key ido-common-completion-map + (kbd \"C-x g\") \\='ido-enter-magit-status) + +\(fn)" t nil) + +(autoload 'magit-dired-jump "magit-extras" "\ +Visit file at point using Dired. +With a prefix argument, visit in another window. If there +is no file at point, then instead visit `default-directory'. + +\(fn &optional OTHER-WINDOW)" t nil) + +(autoload 'magit-dired-log "magit-extras" "\ +Show log for all marked files, or the current file. + +\(fn &optional FOLLOW)" t nil) + +(autoload 'magit-do-async-shell-command "magit-extras" "\ +Open FILE with `dired-do-async-shell-command'. +Interactively, open the file at point. + +\(fn FILE)" t nil) + +(autoload 'magit-previous-line "magit-extras" "\ +Like `previous-line' but with Magit-specific shift-selection. + +Magit's selection mechanism is based on the region but selects an +area that is larger than the region. This causes `previous-line' +when invoked while holding the shift key to move up one line and +thereby select two lines. When invoked inside a hunk body this +command does not move point on the first invocation and thereby +it only selects a single line. Which inconsistency you prefer +is a matter of preference. + +\(fn &optional ARG TRY-VSCROLL)" t nil) + +(function-put 'magit-previous-line 'interactive-only '"use `forward-line' with negative argument instead.") + +(autoload 'magit-next-line "magit-extras" "\ +Like `next-line' but with Magit-specific shift-selection. + +Magit's selection mechanism is based on the region but selects +an area that is larger than the region. This causes `next-line' +when invoked while holding the shift key to move down one line +and thereby select two lines. When invoked inside a hunk body +this command does not move point on the first invocation and +thereby it only selects a single line. Which inconsistency you +prefer is a matter of preference. + +\(fn &optional ARG TRY-VSCROLL)" t nil) + +(function-put 'magit-next-line 'interactive-only 'forward-line) + +(autoload 'magit-clean "magit-extras" "\ +Remove untracked files from the working tree. +With a prefix argument also remove ignored files, +with two prefix arguments remove ignored files only. + +\(git clean -f -d [-x|-X]) + +\(fn &optional ARG)" t nil) + +(autoload 'magit-add-change-log-entry "magit-extras" "\ +Find change log file and add date entry and item for current change. +This differs from `add-change-log-entry' (which see) in that +it acts on the current hunk in a Magit buffer instead of on +a position in a file-visiting buffer. + +\(fn &optional WHOAMI FILE-NAME OTHER-WINDOW)" t nil) + +(autoload 'magit-add-change-log-entry-other-window "magit-extras" "\ +Find change log file in other window and add entry and item. +This differs from `add-change-log-entry-other-window' (which see) +in that it acts on the current hunk in a Magit buffer instead of +on a position in a file-visiting buffer. + +\(fn &optional WHOAMI FILE-NAME)" t nil) + +(autoload 'magit-edit-line-commit "magit-extras" "\ +Edit the commit that added the current line. + +With a prefix argument edit the commit that removes the line, +if any. The commit is determined using `git blame' and made +editable using `git rebase --interactive' if it is reachable +from `HEAD', or by checking out the commit (or a branch that +points at it) otherwise. + +\(fn &optional TYPE)" t nil) + +(autoload 'magit-reshelve-since "magit-extras" "\ +Change the author and committer dates of the commits since REV. + +Ask the user for the first reachable commit whose dates should +be changed. The read the new date for that commit. The initial +minibuffer input and the previous history element offer good +values. The next commit will be created one minute later and so +on. + +This command is only intended for interactive use and should only +be used on highly rearranged and unpublished history. + +\(fn REV)" t nil) + +(autoload 'magit-pop-revision-stack "magit-extras" "\ +Insert a representation of a revision into the current buffer. + +Pop a revision from the `magit-revision-stack' and insert it into +the current buffer according to `magit-pop-revision-stack-format'. +Revisions can be put on the stack using `magit-copy-section-value' +and `magit-copy-buffer-revision'. + +If the stack is empty or with a prefix argument, instead read a +revision in the minibuffer. By using the minibuffer history this +allows selecting an item which was popped earlier or to insert an +arbitrary reference or revision without first pushing it onto the +stack. + +When reading the revision from the minibuffer, then it might not +be possible to guess the correct repository. When this command +is called inside a repository (e.g. while composing a commit +message), then that repository is used. Otherwise (e.g. while +composing an email) then the repository recorded for the top +element of the stack is used (even though we insert another +revision). If not called inside a repository and with an empty +stack, or with two prefix arguments, then read the repository in +the minibuffer too. + +\(fn REV TOPLEVEL)" t nil) + +(autoload 'magit-copy-section-value "magit-extras" "\ +Save the value of the current section for later use. + +Save the section value to the `kill-ring', and, provided that +the current section is a commit, branch, or tag section, push +the (referenced) revision to the `magit-revision-stack' for use +with `magit-pop-revision-stack'. + +When the current section is a branch or a tag, and a prefix +argument is used, then save the revision at its tip to the +`kill-ring' instead of the reference name. + +When the region is active, then save that to the `kill-ring', +like `kill-ring-save' would, instead of behaving as described +above. + +\(fn)" t nil) + +(autoload 'magit-copy-buffer-revision "magit-extras" "\ +Save the revision of the current buffer for later use. + +Save the revision shown in the current buffer to the `kill-ring' +and push it to the `magit-revision-stack'. + +This command is mainly intended for use in `magit-revision-mode' +buffers, the only buffers where it is always unambiguous exactly +which revision should be saved. + +Most other Magit buffers usually show more than one revision, in +some way or another, so this command has to select one of them, +and that choice might not always be the one you think would have +been the best pick. + +In such buffers it is often more useful to save the value of +the current section instead, using `magit-copy-section-value'. + +When the region is active, then save that to the `kill-ring', +like `kill-ring-save' would, instead of behaving as described +above. + +\(fn)" t nil) + +(autoload 'magit-abort-dwim "magit-extras" "\ +Abort current operation. +Depending on the context, this will abort a merge, a rebase, a +patch application, a cherry-pick, a revert, or a bisect. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-extras" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-fetch" "magit-fetch.el" (0 0 0 0)) +;;; Generated autoloads from magit-fetch.el + (autoload 'magit-fetch-popup "magit-fetch" nil t) + +(autoload 'magit-fetch-from-pushremote "magit-fetch" "\ +Fetch from the push-remote of the current branch. + +\(fn ARGS)" t nil) + +(autoload 'magit-fetch-from-upstream "magit-fetch" "\ +Fetch from the upstream repository of the current branch. + +\(fn ARGS)" t nil) + +(autoload 'magit-fetch-other "magit-fetch" "\ +Fetch from another repository. + +\(fn REMOTE ARGS)" t nil) + +(autoload 'magit-fetch-branch "magit-fetch" "\ +Fetch a BRANCH from a REMOTE. + +\(fn REMOTE BRANCH ARGS)" t nil) + +(autoload 'magit-fetch-refspec "magit-fetch" "\ +Fetch a REFSPEC from a REMOTE. + +\(fn REMOTE REFSPEC ARGS)" t nil) + +(autoload 'magit-fetch-all "magit-fetch" "\ +Fetch from all remotes. + +\(fn ARGS)" t nil) + +(autoload 'magit-fetch-all-prune "magit-fetch" "\ +Fetch from all remotes, and prune. +Prune remote tracking branches for branches that have been +removed on the respective remote. + +\(fn)" t nil) + +(autoload 'magit-fetch-all-no-prune "magit-fetch" "\ +Fetch from all remotes. + +\(fn)" t nil) + +(autoload 'magit-fetch-modules "magit-fetch" "\ +Fetch all submodules. + +Option `magit-fetch-modules-jobs' controls how many submodules +are being fetched in parallel. Also fetch the super-repository, +because `git-fetch' does not support not doing that. With a +prefix argument fetch all remotes. + +\(fn &optional ALL)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-fetch" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-files" "magit-files.el" (0 0 0 0)) +;;; Generated autoloads from magit-files.el + +(autoload 'magit-find-file "magit-files" "\ +View FILE from REV. +Switch to a buffer visiting blob REV:FILE, +creating one if none already exists. + +\(fn REV FILE)" t nil) + +(autoload 'magit-find-file-other-window "magit-files" "\ +View FILE from REV, in another window. +Like `magit-find-file', but create a new window or reuse an +existing one. + +\(fn REV FILE)" t nil) + (autoload 'magit-file-popup "magit" nil t) + +(defvar global-magit-file-mode t "\ +Non-nil if Global Magit-File mode is enabled. +See the `global-magit-file-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `global-magit-file-mode'.") + +(custom-autoload 'global-magit-file-mode "magit-files" nil) + +(autoload 'global-magit-file-mode "magit-files" "\ +Toggle Magit-File mode in all buffers. +With prefix ARG, enable Global Magit-File mode if ARG is positive; +otherwise, disable it. If called from Lisp, enable the mode if +ARG is omitted or nil. + +Magit-File mode is enabled in all buffers where +`magit-file-mode-turn-on' would do it. +See `magit-file-mode' for more information on Magit-File mode. + +\(fn &optional ARG)" t nil) + +(autoload 'magit-file-checkout "magit-files" "\ +Checkout FILE from REV. + +\(fn REV FILE)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-files" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-git" "magit-git.el" (0 0 0 0)) +;;; Generated autoloads from magit-git.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-git" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-gitignore" "magit-gitignore.el" (0 0 +;;;;;; 0 0)) +;;; Generated autoloads from magit-gitignore.el + (autoload 'magit-gitignore-popup "magit-gitignore" nil t) + +(autoload 'magit-gitignore-globally "magit-gitignore" "\ +Instruct Git to globally ignore FILE-OR-PATTERN. + +\(fn FILE-OR-PATTERN)" t nil) + +(autoload 'magit-gitignore-locally "magit-gitignore" "\ +Instruct Git to locally ignore FILE-OR-PATTERN. + +\(fn FILE-OR-PATTERN)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-gitignore" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-imenu" "magit-imenu.el" (0 0 0 0)) +;;; Generated autoloads from magit-imenu.el + +(autoload 'magit-imenu--log-prev-index-position-function "magit-imenu" "\ +Move point to previous line in current buffer. +This function is used as a value for +`imenu-prev-index-position-function'. + +\(fn)" nil nil) + +(autoload 'magit-imenu--log-extract-index-name-function "magit-imenu" "\ +Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line. + +\(fn)" nil nil) + +(autoload 'magit-imenu--diff-prev-index-position-function "magit-imenu" "\ +Move point to previous file line in current buffer. +This function is used as a value for +`imenu-prev-index-position-function'. + +\(fn)" nil nil) + +(autoload 'magit-imenu--diff-extract-index-name-function "magit-imenu" "\ +Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line. + +\(fn)" nil nil) + +(autoload 'magit-imenu--status-create-index-function "magit-imenu" "\ +Return an alist of all imenu entries in current buffer. +This function is used as a value for +`imenu-create-index-function'. + +\(fn)" nil nil) + +(autoload 'magit-imenu--refs-create-index-function "magit-imenu" "\ +Return an alist of all imenu entries in current buffer. +This function is used as a value for +`imenu-create-index-function'. + +\(fn)" nil nil) + +(autoload 'magit-imenu--cherry-create-index-function "magit-imenu" "\ +Return an alist of all imenu entries in current buffer. +This function is used as a value for +`imenu-create-index-function'. + +\(fn)" nil nil) + +(autoload 'magit-imenu--submodule-prev-index-position-function "magit-imenu" "\ +Move point to previous line in magit-submodule-list buffer. +This function is used as a value for +`imenu-prev-index-position-function'. + +\(fn)" nil nil) + +(autoload 'magit-imenu--submodule-extract-index-name-function "magit-imenu" "\ +Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line. + +\(fn)" nil nil) + +(autoload 'magit-imenu--repolist-prev-index-position-function "magit-imenu" "\ +Move point to previous line in magit-repolist buffer. +This function is used as a value for +`imenu-prev-index-position-function'. + +\(fn)" nil nil) + +(autoload 'magit-imenu--repolist-extract-index-name-function "magit-imenu" "\ +Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line. + +\(fn)" nil nil) + +(autoload 'magit-imenu--process-prev-index-position-function "magit-imenu" "\ +Move point to previous process in magit-process buffer. +This function is used as a value for +`imenu-prev-index-position-function'. + +\(fn)" nil nil) + +(autoload 'magit-imenu--process-extract-index-name-function "magit-imenu" "\ +Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line. + +\(fn)" nil nil) + +(autoload 'magit-imenu--rebase-prev-index-position-function "magit-imenu" "\ +Move point to previous commit in git-rebase buffer. +This function is used as a value for +`imenu-prev-index-position-function'. + +\(fn)" nil nil) + +(autoload 'magit-imenu--rebase-extract-index-name-function "magit-imenu" "\ +Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line. + +\(fn)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-imenu" '("magit-imenu--index-function"))) + +;;;*** + +;;;### (autoloads nil "magit-log" "magit-log.el" (0 0 0 0)) +;;; Generated autoloads from magit-log.el + +(autoload 'magit-log-buffer-file-popup "magit-log" "\ +Popup console for log commands. + +This is a variant of `magit-log-popup' which shows the same popup +but which limits the log to the file being visited in the current +buffer. + +\(fn)" t nil) + +(autoload 'magit-log-current "magit-log" "\ +Show log for the current branch. +When `HEAD' is detached or with a prefix argument show log for +one or more revs read from the minibuffer. + +\(fn REVS &optional ARGS FILES)" t nil) + +(autoload 'magit-log-other "magit-log" "\ +Show log for one or more revs read from the minibuffer. +The user can input any revision or revisions separated by a +space, or even ranges, but only branches and tags, and a +representation of the commit at point, are available as +completion candidates. + +\(fn REVS &optional ARGS FILES)" t nil) + +(autoload 'magit-log-head "magit-log" "\ +Show log for `HEAD'. + +\(fn &optional ARGS FILES)" t nil) + +(autoload 'magit-log-branches "magit-log" "\ +Show log for all local branches and `HEAD'. + +\(fn &optional ARGS FILES)" t nil) + +(autoload 'magit-log-all-branches "magit-log" "\ +Show log for all local and remote branches and `HEAD'. + +\(fn &optional ARGS FILES)" t nil) + +(autoload 'magit-log-all "magit-log" "\ +Show log for all references and `HEAD'. + +\(fn &optional ARGS FILES)" t nil) + +(autoload 'magit-log-buffer-file "magit-log" "\ +Show log for the blob or file visited in the current buffer. +With a prefix argument or when `--follow' is part of +`magit-log-arguments', then follow renames. When the region is +active, restrict the log to the lines that the region touches. + +\(fn &optional FOLLOW BEG END)" t nil) + +(autoload 'magit-log-trace-definition "magit-log" "\ +Show log for the definition at point. + +\(fn FILE FN REV)" t nil) + +(autoload 'magit-log-merged "magit-log" "\ +Show log for the merge of COMMIT into BRANCH. +More precisely, find merge commit M that brought COMMIT into +BRANCH, and show the log of the range \"M^..M\". This command +requires git-when-merged, which is available from +https://github.com/mhagger/git-when-merged. + +\(fn COMMIT BRANCH &optional ARGS FILES)" t nil) + +(autoload 'magit-reflog-current "magit-log" "\ +Display the reflog of the current branch. + +\(fn ARGS)" t nil) + +(autoload 'magit-reflog-other "magit-log" "\ +Display the reflog of a branch or another ref. + +\(fn REF ARGS)" t nil) + +(autoload 'magit-reflog-head "magit-log" "\ +Display the `HEAD' reflog. + +\(fn ARGS)" t nil) + +(autoload 'magit-log-move-to-parent "magit-log" "\ +Move to the Nth parent of the current commit. + +\(fn &optional N)" t nil) + +(autoload 'magit-cherry "magit-log" "\ +Show commits in a branch that are not merged in the upstream branch. + +\(fn HEAD UPSTREAM)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-log" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-margin" "magit-margin.el" (0 0 0 0)) +;;; Generated autoloads from magit-margin.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-margin" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-merge" "magit-merge.el" (0 0 0 0)) +;;; Generated autoloads from magit-merge.el + (autoload 'magit-merge-popup "magit" nil t) + +(autoload 'magit-merge-plain "magit-merge" "\ +Merge commit REV into the current branch; using default message. + +Unless there are conflicts or a prefix argument is used create a +merge commit using a generic commit message and without letting +the user inspect the result. With a prefix argument pretend the +merge failed to give the user the opportunity to inspect the +merge. + +\(git merge --no-edit|--no-commit [ARGS] REV) + +\(fn REV &optional ARGS NOCOMMIT)" t nil) + +(autoload 'magit-merge-editmsg "magit-merge" "\ +Merge commit REV into the current branch; and edit message. +Perform the merge and prepare a commit message but let the user +edit it. + +\(git merge --edit --no-ff [ARGS] REV) + +\(fn REV &optional ARGS)" t nil) + +(autoload 'magit-merge-nocommit "magit-merge" "\ +Merge commit REV into the current branch; pretending it failed. +Pretend the merge failed to give the user the opportunity to +inspect the merge and change the commit message. + +\(git merge --no-commit --no-ff [ARGS] REV) + +\(fn REV &optional ARGS)" t nil) + +(autoload 'magit-merge-into "magit-merge" "\ +Merge the current branch into BRANCH and remove the former. + +Before merging, force push the source branch to its push-remote, +provided the respective remote branch already exists, ensuring +that the respective pull-request (if any) won't get stuck on some +obsolete version of the commits that are being merged. Finally +if `magit-branch-pull-request' was used to create the merged +branch, then also remove the respective remote branch. + +\(fn BRANCH &optional ARGS)" t nil) + +(autoload 'magit-merge-absorb "magit-merge" "\ +Merge BRANCH into the current branch and remove the former. + +Before merging, force push the source branch to its push-remote, +provided the respective remote branch already exists, ensuring +that the respective pull-request (if any) won't get stuck on some +obsolete version of the commits that are being merged. Finally +if `magit-branch-pull-request' was used to create the merged +branch, then also remove the respective remote branch. + +\(fn BRANCH &optional ARGS)" t nil) + +(autoload 'magit-merge-squash "magit-merge" "\ +Squash commit REV into the current branch; don't create a commit. + +\(git merge --squash REV) + +\(fn REV)" t nil) + +(autoload 'magit-merge-preview "magit-merge" "\ +Preview result of merging REV into the current branch. + +\(fn REV)" t nil) + +(autoload 'magit-merge-abort "magit-merge" "\ +Abort the current merge operation. + +\(git merge --abort) + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-merge" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-mode" "magit-mode.el" (0 0 0 0)) +;;; Generated autoloads from magit-mode.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-mode" '("magit-" "disable-magit-save-buffers" "inhibit-magit-refresh"))) + +;;;*** + +;;;### (autoloads nil "magit-notes" "magit-notes.el" (0 0 0 0)) +;;; Generated autoloads from magit-notes.el + (autoload 'magit-notes-popup "magit" nil t) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-notes" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-patch" "magit-patch.el" (0 0 0 0)) +;;; Generated autoloads from magit-patch.el + (autoload 'magit-patch-popup "magit-patch" nil t) + +(autoload 'magit-format-patch "magit-patch" "\ +Create patches for the commits in RANGE. +When a single commit is given for RANGE, create a patch for the +changes introduced by that commit (unlike 'git format-patch' +which creates patches for all commits that are reachable from +`HEAD' but not from the specified commit). + +\(fn RANGE ARGS FILES)" t nil) + +(autoload 'magit-request-pull "magit-patch" "\ +Request upstream to pull from you public repository. + +URL is the url of your publically accessible repository. +START is a commit that already is in the upstream repository. +END is the last commit, usually a branch name, which upstream +is asked to pull. START has to be reachable from that commit. + +\(fn URL START END)" t nil) + (autoload 'magit-patch-apply-popup "magit-patch" nil t) + +(autoload 'magit-patch-apply "magit-patch" "\ +Apply the patch file FILE. + +\(fn FILE &rest ARGS)" t nil) + +(autoload 'magit-patch-save "magit-patch" "\ +Write current diff into patch FILE. + +What arguments are used to create the patch depends on the value +of `magit-patch-save-arguments' and whether a prefix argument is +used. + +If the value is the symbol `buffer', then use the same arguments +as the buffer. With a prefix argument use no arguments. + +If the value is a list beginning with the symbol `exclude', then +use the same arguments as the buffer except for those matched by +entries in the cdr of the list. The comparison is done using +`string-prefix-p'. With a prefix argument use the same arguments +as the buffer. + +If the value is a list of strings (including the empty list), +then use those arguments. With a prefix argument use the same +arguments as the buffer. + +Of course the arguments that are required to actually show the +same differences as those shown in the buffer are always used. + +\(fn FILE &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-patch" '("magit-patch-save-arguments"))) + +;;;*** + +;;;### (autoloads nil "magit-process" "magit-process.el" (0 0 0 0)) +;;; Generated autoloads from magit-process.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-process" '("magit-" "tramp-sh-handle-"))) + +;;;*** + +;;;### (autoloads nil "magit-pull" "magit-pull.el" (0 0 0 0)) +;;; Generated autoloads from magit-pull.el + (autoload 'magit-pull-popup "magit-pull" nil t) + (autoload 'magit-pull-and-fetch-popup "magit-pull" nil t) + +(autoload 'magit-pull-from-pushremote "magit-pull" "\ +Pull from the push-remote of the current branch. + +\(fn ARGS)" t nil) + +(autoload 'magit-pull-from-upstream "magit-pull" "\ +Pull from the upstream of the current branch. + +\(fn ARGS)" t nil) + +(autoload 'magit-pull-branch "magit-pull" "\ +Pull from a branch read in the minibuffer. + +\(fn SOURCE ARGS)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-pull" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-push" "magit-push.el" (0 0 0 0)) +;;; Generated autoloads from magit-push.el + (autoload 'magit-push-popup "magit-push" nil t) + +(autoload 'magit-push-current-to-pushremote "magit-push" "\ +Push the current branch to `branch..pushRemote'. +If that variable is unset, then push to `remote.pushDefault'. + +When `magit-push-current-set-remote-if-missing' is non-nil and +the push-remote is not configured, then read the push-remote from +the user, set it, and then push to it. With a prefix argument +the push-remote can be changed before pushed to it. + +\(fn ARGS &optional PUSH-REMOTE)" t nil) + +(autoload 'magit-push-current-to-upstream "magit-push" "\ +Push the current branch to its upstream branch. + +When `magit-push-current-set-remote-if-missing' is non-nil and +the upstream is not configured, then read the upstream from the +user, set it, and then push to it. With a prefix argument the +upstream can be changed before pushed to it. + +\(fn ARGS &optional UPSTREAM)" t nil) + +(autoload 'magit-push-current "magit-push" "\ +Push the current branch to a branch read in the minibuffer. + +\(fn TARGET ARGS)" t nil) + +(autoload 'magit-push-other "magit-push" "\ +Push an arbitrary branch or commit somewhere. +Both the source and the target are read in the minibuffer. + +\(fn SOURCE TARGET ARGS)" t nil) + +(autoload 'magit-push-refspecs "magit-push" "\ +Push one or multiple REFSPECS to a REMOTE. +Both the REMOTE and the REFSPECS are read in the minibuffer. To +use multiple REFSPECS, separate them with commas. Completion is +only available for the part before the colon, or when no colon +is used. + +\(fn REMOTE REFSPECS ARGS)" t nil) + +(autoload 'magit-push-matching "magit-push" "\ +Push all matching branches to another repository. +If multiple remotes exist, then read one from the user. +If just one exists, use that without requiring confirmation. + +\(fn REMOTE &optional ARGS)" t nil) + +(autoload 'magit-push-tags "magit-push" "\ +Push all tags to another repository. +If only one remote exists, then push to that. Otherwise prompt +for a remote, offering the remote configured for the current +branch as default. + +\(fn REMOTE &optional ARGS)" t nil) + +(autoload 'magit-push-tag "magit-push" "\ +Push a tag to another repository. + +\(fn TAG REMOTE &optional ARGS)" t nil) + +(autoload 'magit-push-implicitly "magit-push" "\ +Push somewhere without using an explicit refspec. + +This command simply runs \"git push -v [ARGS]\". ARGS are the +arguments specified in the popup buffer. No explicit refspec +arguments are used. Instead the behavior depends on at least +these Git variables: `push.default', `remote.pushDefault', +`branch..pushRemote', `branch..remote', +`branch..merge', and `remote..push'. + +To add this command to the push popup add this to your init file: + + (with-eval-after-load \\='magit-remote + (magit-define-popup-action \\='magit-push-popup ?P + \\='magit-push-implicitly--desc + \\='magit-push-implicitly ?p t)) + +The function `magit-push-implicitly--desc' attempts to predict +what this command will do. The value it returns is displayed in +the popup buffer. + +\(fn ARGS)" t nil) + +(autoload 'magit-push-to-remote "magit-push" "\ +Push to REMOTE without using an explicit refspec. +The REMOTE is read in the minibuffer. + +This command simply runs \"git push -v [ARGS] REMOTE\". ARGS +are the arguments specified in the popup buffer. No refspec +arguments are used. Instead the behavior depends on at least +these Git variables: `push.default', `remote.pushDefault', +`branch..pushRemote', `branch..remote', +`branch..merge', and `remote..push'. + +To add this command to the push popup add this to your init file: + + (with-eval-after-load \\='magit-remote + (magit-define-popup-action \\='magit-push-popup ?r + \\='magit-push-to-remote--desc + \\='magit-push-to-remote ?p t)) + +\(fn REMOTE ARGS)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-push" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-refs" "magit-refs.el" (0 0 0 0)) +;;; Generated autoloads from magit-refs.el + +(autoload 'magit-show-refs-popup "magit-refs" "\ +Popup console for `magit-show-refs'. + +\(fn &optional ARG)" t nil) + +(autoload 'magit-show-refs-head "magit-refs" "\ +List and compare references in a dedicated buffer. +Refs are compared with `HEAD'. + +\(fn &optional ARGS)" t nil) + +(autoload 'magit-show-refs-current "magit-refs" "\ +List and compare references in a dedicated buffer. +Refs are compared with the current branch or `HEAD' if +it is detached. + +\(fn &optional ARGS)" t nil) + +(autoload 'magit-show-refs "magit-refs" "\ +List and compare references in a dedicated buffer. +Refs are compared with a branch read from the user. + +\(fn &optional REF ARGS)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-refs" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-remote" "magit-remote.el" (0 0 0 0)) +;;; Generated autoloads from magit-remote.el + (autoload 'magit-remote-popup "magit-remote" nil t) + +(autoload 'magit-remote-add "magit-remote" "\ +Add a remote named REMOTE and fetch it. + +\(fn REMOTE URL &optional ARGS)" t nil) + +(autoload 'magit-remote-rename "magit-remote" "\ +Rename the remote named OLD to NEW. + +\(fn OLD NEW)" t nil) + +(autoload 'magit-remote-remove "magit-remote" "\ +Delete the remote named REMOTE. + +\(fn REMOTE)" t nil) + +(autoload 'magit-remote-prune "magit-remote" "\ +Remove stale remote-tracking branches for REMOTE. + +\(fn REMOTE)" t nil) + +(autoload 'magit-remote-prune-refspecs "magit-remote" "\ +Remove stale refspecs for REMOTE. + +A refspec is stale if there no longer exists at least one branch +on the remote that would be fetched due to that refspec. A stale +refspec is problematic because its existence causes Git to refuse +to fetch according to the remaining non-stale refspecs. + +If only stale refspecs remain, then offer to either delete the +remote or to replace the stale refspecs with the default refspec. + +Also remove the remote-tracking branches that were created due to +the now stale refspecs. Other stale branches are not removed. + +\(fn REMOTE)" t nil) + +(autoload 'magit-remote-set-head "magit-remote" "\ +Set the local representation of REMOTE's default branch. +Query REMOTE and set the symbolic-ref refs/remotes//HEAD +accordingly. With a prefix argument query for the branch to be +used, which allows you to select an incorrect value if you fancy +doing that. + +\(fn REMOTE &optional BRANCH)" t nil) + +(autoload 'magit-remote-unset-head "magit-remote" "\ +Unset the local representation of REMOTE's default branch. +Delete the symbolic-ref \"refs/remotes//HEAD\". + +\(fn REMOTE)" t nil) + +(autoload 'magit-remote-config-popup "magit-remote" "\ +Popup console for setting remote variables. + +\(fn REMOTE)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-remote" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-repos" "magit-repos.el" (0 0 0 0)) +;;; Generated autoloads from magit-repos.el + +(autoload 'magit-list-repositories "magit-repos" "\ +Display a list of repositories. + +Use the options `magit-repository-directories' to control which +repositories are displayed. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-repos" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-reset" "magit-reset.el" (0 0 0 0)) +;;; Generated autoloads from magit-reset.el + (autoload 'magit-reset-popup "magit" nil t) + +(autoload 'magit-reset-mixed "magit-reset" "\ +Reset the `HEAD' and index to COMMIT, but not the working tree. + +\(git reset --mixed COMMIT) + +\(fn COMMIT)" t nil) + +(autoload 'magit-reset-soft "magit-reset" "\ +Reset the `HEAD' to COMMIT, but not the index and working tree. + +\(git reset --soft REVISION) + +\(fn COMMIT)" t nil) + +(autoload 'magit-reset-hard "magit-reset" "\ +Reset the `HEAD', index, and working tree to COMMIT. + +\(git reset --hard REVISION) + +\(fn COMMIT)" t nil) + +(autoload 'magit-reset-index "magit-reset" "\ +Reset the index to COMMIT. +Keep the `HEAD' and working tree as-is, so if COMMIT refers to the +head this effectively unstages all changes. + +\(git reset COMMIT .) + +\(fn COMMIT)" t nil) + +(autoload 'magit-reset-worktree "magit-reset" "\ +Reset the worktree to COMMIT. +Keep the `HEAD' and index as-is. + +\(fn COMMIT)" t nil) + +(autoload 'magit-reset-quickly "magit-reset" "\ +Reset the `HEAD' and index to COMMIT, and possibly the working tree. +With a prefix argument reset the working tree otherwise don't. + +\(git reset --mixed|--hard COMMIT) + +\(fn COMMIT &optional HARD)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-reset" '("magit-reset-"))) + +;;;*** + +;;;### (autoloads nil "magit-section" "magit-section.el" (0 0 0 0)) +;;; Generated autoloads from magit-section.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-section" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-sequence" "magit-sequence.el" (0 0 0 +;;;;;; 0)) +;;; Generated autoloads from magit-sequence.el + +(autoload 'magit-sequencer-continue "magit-sequence" "\ +Resume the current cherry-pick or revert sequence. + +\(fn)" t nil) + +(autoload 'magit-sequencer-skip "magit-sequence" "\ +Skip the stopped at commit during a cherry-pick or revert sequence. + +\(fn)" t nil) + +(autoload 'magit-sequencer-abort "magit-sequence" "\ +Abort the current cherry-pick or revert sequence. +This discards all changes made since the sequence started. + +\(fn)" t nil) + (autoload 'magit-cherry-pick-popup "magit-sequence" nil t) + +(autoload 'magit-cherry-copy "magit-sequence" "\ +Copy COMMITS from another branch onto the current branch. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then pick all of them, +without prompting. + +\(fn COMMITS &optional ARGS)" t nil) + +(autoload 'magit-cherry-apply "magit-sequence" "\ +Apply the changes in COMMITS but do not commit them. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then apply all of them, +without prompting. + +\(fn COMMITS &optional ARGS)" t nil) + +(autoload 'magit-cherry-harvest "magit-sequence" "\ +Move COMMITS from another BRANCH onto the current branch. +Remove the COMMITS from BRANCH and stay on the current branch. +If a conflict occurs, then you have to fix that and finish the +process manually. + +\(fn COMMITS BRANCH &optional ARGS)" t nil) + +(autoload 'magit-cherry-donate "magit-sequence" "\ +Move COMMITS from the current branch onto another existing BRANCH. +Remove COMMITS from the current branch and stay on that branch. +If a conflict occurs, then you have to fix that and finish the +process manually. + +\(fn COMMITS BRANCH &optional ARGS)" t nil) + +(autoload 'magit-cherry-spinout "magit-sequence" "\ +Move COMMITS from the current branch onto a new BRANCH. +Remove COMMITS from the current branch and stay on that branch. +If a conflict occurs, then you have to fix that and finish the +process manually. + +\(fn COMMITS BRANCH START-POINT &optional ARGS)" t nil) + +(autoload 'magit-cherry-spinoff "magit-sequence" "\ +Move COMMITS from the current branch onto a new BRANCH. +Remove COMMITS from the current branch and checkout BRANCH. +If a conflict occurs, then you have to fix that and finish +the process manually. + +\(fn COMMITS BRANCH START-POINT &optional ARGS)" t nil) + (autoload 'magit-revert-popup "magit-sequence" nil t) + +(autoload 'magit-revert-and-commit "magit-sequence" "\ +Revert COMMIT by creating a new commit. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then revert all of them, +without prompting. + +\(fn COMMIT &optional ARGS)" t nil) + +(autoload 'magit-revert-no-commit "magit-sequence" "\ +Revert COMMIT by applying it in reverse to the worktree. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then revert all of them, +without prompting. + +\(fn COMMIT &optional ARGS)" t nil) + (autoload 'magit-am-popup "magit-sequence" nil t) + +(autoload 'magit-am-apply-patches "magit-sequence" "\ +Apply the patches FILES. + +\(fn &optional FILES ARGS)" t nil) + +(autoload 'magit-am-apply-maildir "magit-sequence" "\ +Apply the patches from MAILDIR. + +\(fn &optional MAILDIR ARGS)" t nil) + +(autoload 'magit-am-continue "magit-sequence" "\ +Resume the current patch applying sequence. + +\(fn)" t nil) + +(autoload 'magit-am-skip "magit-sequence" "\ +Skip the stopped at patch during a patch applying sequence. + +\(fn)" t nil) + +(autoload 'magit-am-abort "magit-sequence" "\ +Abort the current patch applying sequence. +This discards all changes made since the sequence started. + +\(fn)" t nil) + (autoload 'magit-rebase-popup "magit-sequence" nil t) + +(autoload 'magit-rebase-onto-pushremote "magit-sequence" "\ +Rebase the current branch onto `branch..pushRemote'. +If that variable is unset, then rebase onto `remote.pushDefault'. + +\(fn ARGS)" t nil) + +(autoload 'magit-rebase-onto-upstream "magit-sequence" "\ +Rebase the current branch onto its upstream branch. + +\(fn ARGS)" t nil) + +(autoload 'magit-rebase-branch "magit-sequence" "\ +Rebase the current branch onto a branch read in the minibuffer. +All commits that are reachable from `HEAD' but not from the +selected branch TARGET are being rebased. + +\(fn TARGET ARGS)" t nil) + +(autoload 'magit-rebase-subset "magit-sequence" "\ +Rebase a subset of the current branch's history onto a new base. +Rebase commits from START to `HEAD' onto NEWBASE. +START has to be selected from a list of recent commits. + +\(fn NEWBASE START ARGS)" t nil) + +(autoload 'magit-rebase-interactive "magit-sequence" "\ +Start an interactive rebase sequence. + +\(fn COMMIT ARGS)" t nil) + +(autoload 'magit-rebase-autosquash "magit-sequence" "\ +Combine squash and fixup commits with their intended targets. + +\(fn ARGS)" t nil) + +(autoload 'magit-rebase-edit-commit "magit-sequence" "\ +Edit a single older commit using rebase. + +\(fn COMMIT ARGS)" t nil) + +(autoload 'magit-rebase-reword-commit "magit-sequence" "\ +Reword a single older commit using rebase. + +\(fn COMMIT ARGS)" t nil) + +(autoload 'magit-rebase-remove-commit "magit-sequence" "\ +Remove a single older commit using rebase. + +\(fn COMMIT ARGS)" t nil) + +(autoload 'magit-rebase-continue "magit-sequence" "\ +Restart the current rebasing operation. +In some cases this pops up a commit message buffer for you do +edit. With a prefix argument the old message is reused as-is. + +\(fn &optional NOEDIT)" t nil) + +(autoload 'magit-rebase-skip "magit-sequence" "\ +Skip the current commit and restart the current rebase operation. + +\(fn)" t nil) + +(autoload 'magit-rebase-edit "magit-sequence" "\ +Edit the todo list of the current rebase operation. + +\(fn)" t nil) + +(autoload 'magit-rebase-abort "magit-sequence" "\ +Abort the current rebase operation, restoring the original branch. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-sequence" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-stash" "magit-stash.el" (0 0 0 0)) +;;; Generated autoloads from magit-stash.el + (autoload 'magit-stash-popup "magit-stash" nil t) + +(autoload 'magit-stash-both "magit-stash" "\ +Create a stash of the index and working tree. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'. + +\(fn MESSAGE &optional INCLUDE-UNTRACKED)" t nil) + +(autoload 'magit-stash-index "magit-stash" "\ +Create a stash of the index only. +Unstaged and untracked changes are not stashed. The stashed +changes are applied in reverse to both the index and the +worktree. This command can fail when the worktree is not clean. +Applying the resulting stash has the inverse effect. + +\(fn MESSAGE)" t nil) + +(autoload 'magit-stash-worktree "magit-stash" "\ +Create a stash of unstaged changes in the working tree. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'. + +\(fn MESSAGE &optional INCLUDE-UNTRACKED)" t nil) + +(autoload 'magit-stash-keep-index "magit-stash" "\ +Create a stash of the index and working tree, keeping index intact. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'. + +\(fn MESSAGE &optional INCLUDE-UNTRACKED)" t nil) + +(autoload 'magit-snapshot-both "magit-stash" "\ +Create a snapshot of the index and working tree. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'. + +\(fn &optional INCLUDE-UNTRACKED)" t nil) + +(autoload 'magit-snapshot-index "magit-stash" "\ +Create a snapshot of the index only. +Unstaged and untracked changes are not stashed. + +\(fn)" t nil) + +(autoload 'magit-snapshot-worktree "magit-stash" "\ +Create a snapshot of unstaged changes in the working tree. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'. + +\(fn &optional INCLUDE-UNTRACKED)" t nil) + +(autoload 'magit-stash-apply "magit-stash" "\ +Apply a stash to the working tree. +Try to preserve the stash index. If that fails because there +are staged changes, apply without preserving the stash index. + +\(fn STASH)" t nil) + +(autoload 'magit-stash-drop "magit-stash" "\ +Remove a stash from the stash list. +When the region is active offer to drop all contained stashes. + +\(fn STASH)" t nil) + +(autoload 'magit-stash-clear "magit-stash" "\ +Remove all stashes saved in REF's reflog by deleting REF. + +\(fn REF)" t nil) + +(autoload 'magit-stash-branch "magit-stash" "\ +Create and checkout a new BRANCH from STASH. + +\(fn STASH BRANCH)" t nil) + +(autoload 'magit-stash-branch-here "magit-stash" "\ +Create and checkout a new BRANCH and apply STASH. +The branch is created using `magit-branch', using the current +branch or `HEAD' as the string-point. + +\(fn STASH BRANCH)" t nil) + +(autoload 'magit-stash-format-patch "magit-stash" "\ +Create a patch from STASH + +\(fn STASH)" t nil) + +(autoload 'magit-stash-list "magit-stash" "\ +List all stashes in a buffer. + +\(fn)" t nil) + +(autoload 'magit-stash-show "magit-stash" "\ +Show all diffs of a stash in a buffer. + +\(fn STASH &optional ARGS FILES)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-stash" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-status" "magit-status.el" (0 0 0 0)) +;;; Generated autoloads from magit-status.el + +(autoload 'magit-init "magit-status" "\ +Initialize a Git repository, then show its status. + +If the directory is below an existing repository, then the user +has to confirm that a new one should be created inside. If the +directory is the root of the existing repository, then the user +has to confirm that it should be reinitialized. + +Non-interactively DIRECTORY is (re-)initialized unconditionally. + +\(fn DIRECTORY)" t nil) + +(autoload 'magit-status "magit-status" "\ +Show the status of the current Git repository in a buffer. +With a prefix argument prompt for a repository to be shown. +With two prefix arguments prompt for an arbitrary directory. +If that directory isn't the root of an existing repository, +then offer to initialize it as a new repository. + +\(fn &optional DIRECTORY CACHE)" t nil) + +(autoload 'magit-status-internal "magit-status" "\ + + +\(fn DIRECTORY)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-status" '("magit"))) + +;;;*** + +;;;### (autoloads nil "magit-submodule" "magit-submodule.el" (0 0 +;;;;;; 0 0)) +;;; Generated autoloads from magit-submodule.el + (autoload 'magit-submodule-popup "magit-submodule" nil t) + +(autoload 'magit-submodule-add "magit-submodule" "\ +Add the repository at URL as a module. + +Optional PATH is the path to the module relative to the root of +the superproject. If it is nil, then the path is determined +based on the URL. Optional NAME is the name of the module. If +it is nil, then PATH also becomes the name. + +\(fn URL &optional PATH NAME ARGS)" t nil) + +(autoload 'magit-submodule-read-name-for-path "magit-submodule" "\ + + +\(fn PATH &optional PREFER-SHORT)" nil nil) + +(autoload 'magit-submodule-register "magit-submodule" "\ +Register MODULES. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user. + +\(fn MODULES)" t nil) + +(autoload 'magit-submodule-populate "magit-submodule" "\ +Create MODULES working directories, checking out the recorded commits. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user. + +\(fn MODULES)" t nil) + +(autoload 'magit-submodule-update "magit-submodule" "\ +Update MODULES by checking out the recorded commits. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user. + +\(fn MODULES ARGS)" t nil) + +(autoload 'magit-submodule-synchronize "magit-submodule" "\ +Synchronize url configuration of MODULES. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user. + +\(fn MODULES ARGS)" t nil) + +(autoload 'magit-submodule-unpopulate "magit-submodule" "\ +Remove working directories of MODULES. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user. + +\(fn MODULES ARGS)" t nil) + +(autoload 'magit-submodule-remove "magit-submodule" "\ +Unregister MODULES and remove their working directories. + +For safety reasons, do not remove the gitdirs and if a module has +uncomitted changes, then do not remove it at all. If a module's +gitdir is located inside the working directory, then move it into +the gitdir of the superproject first. + +With the \"--force\" argument offer to remove dirty working +directories and with a prefix argument offer to delete gitdirs. +Both actions are very dangerous and have to be confirmed. There +are additional safety precautions in place, so you might be able +to recover from making a mistake here, but don't count on it. + +\(fn MODULES ARGS TRASH-GITDIRS)" t nil) + +(autoload 'magit-insert-modules "magit-submodule" "\ +Insert submodule sections. +Hook `magit-module-sections-hook' controls which module sections +are inserted, and option `magit-module-sections-nested' controls +whether they are wrapped in an additional section. + +\(fn)" nil nil) + +(autoload 'magit-insert-modules-overview "magit-submodule" "\ +Insert sections for all modules. +For each section insert the path and the output of `git describe --tags', +or, failing that, the abbreviated HEAD commit hash. + +\(fn)" nil nil) + +(autoload 'magit-insert-modules-unpulled-from-upstream "magit-submodule" "\ +Insert sections for modules that haven't been pulled from the upstream. +These sections can be expanded to show the respective commits. + +\(fn)" nil nil) + +(autoload 'magit-insert-modules-unpulled-from-pushremote "magit-submodule" "\ +Insert sections for modules that haven't been pulled from the push-remote. +These sections can be expanded to show the respective commits. + +\(fn)" nil nil) + +(autoload 'magit-insert-modules-unpushed-to-upstream "magit-submodule" "\ +Insert sections for modules that haven't been pushed to the upstream. +These sections can be expanded to show the respective commits. + +\(fn)" nil nil) + +(autoload 'magit-insert-modules-unpushed-to-pushremote "magit-submodule" "\ +Insert sections for modules that haven't been pushed to the push-remote. +These sections can be expanded to show the respective commits. + +\(fn)" nil nil) + +(autoload 'magit-list-submodules "magit-submodule" "\ +Display a list of the current repository's submodules. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-submodule" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-subtree" "magit-subtree.el" (0 0 0 0)) +;;; Generated autoloads from magit-subtree.el + (autoload 'magit-subtree-popup "magit-subtree" nil t) + +(autoload 'magit-subtree-add "magit-subtree" "\ +Add REF from REPOSITORY as a new subtree at PREFIX. + +\(fn PREFIX REPOSITORY REF ARGS)" t nil) + +(autoload 'magit-subtree-add-commit "magit-subtree" "\ +Add COMMIT as a new subtree at PREFIX. + +\(fn PREFIX COMMIT ARGS)" t nil) + +(autoload 'magit-subtree-merge "magit-subtree" "\ +Merge COMMIT into the PREFIX subtree. + +\(fn PREFIX COMMIT ARGS)" t nil) + +(autoload 'magit-subtree-pull "magit-subtree" "\ +Pull REF from REPOSITORY into the PREFIX subtree. + +\(fn PREFIX REPOSITORY REF ARGS)" t nil) + +(autoload 'magit-subtree-push "magit-subtree" "\ +Extract the history of the subtree PREFIX and push it to REF on REPOSITORY. + +\(fn PREFIX REPOSITORY REF ARGS)" t nil) + +(autoload 'magit-subtree-split "magit-subtree" "\ +Extract the history of the subtree PREFIX. + +\(fn PREFIX COMMIT ARGS)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-subtree" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-tag" "magit-tag.el" (0 0 0 0)) +;;; Generated autoloads from magit-tag.el + (autoload 'magit-tag-popup "magit" nil t) + +(autoload 'magit-tag-create "magit-tag" "\ +Create a new tag with the given NAME at REV. +With a prefix argument annotate the tag. + +\(git tag [--annotate] NAME REV) + +\(fn NAME REV &optional ARGS)" t nil) + +(autoload 'magit-tag-delete "magit-tag" "\ +Delete one or more tags. +If the region marks multiple tags (and nothing else), then offer +to delete those, otherwise prompt for a single tag to be deleted, +defaulting to the tag at point. + +\(git tag -d TAGS) + +\(fn TAGS)" t nil) + +(autoload 'magit-tag-prune "magit-tag" "\ +Offer to delete tags missing locally from REMOTE, and vice versa. + +\(fn TAGS REMOTE-TAGS REMOTE)" t nil) + +(autoload 'magit-tag-release "magit-tag" "\ +Create an opinionated release tag. + +Assume version tags that match \"\\\\`v?[0-9]\\\\(\\\\.[0-9]\\\\)*\\\\'\". +Prompt for the name of the new tag using the highest existing tag +as initial input and call \"git tag --annotate --sign -m MSG\" TAG, +regardless of whether these arguments are enabled in the popup. +Given a TAG \"v1.2.3\" and a repository \"/path/to/foo-bar\", the +MESSAGE would be \"Foo-Bar 1.2.3\". + +Because it is so opinionated, this command is not available from +the tag popup by default. + +\(fn TAG)" t nil) + +;;;*** + +;;;### (autoloads nil "magit-utils" "magit-utils.el" (0 0 0 0)) +;;; Generated autoloads from magit-utils.el + +(autoload 'magit-emacs-Q-command "magit-utils" "\ +Show a shell command that runs an uncustomized Emacs with only Magit loaded. +See info node `(magit)Debugging Tools' for more information. + +\(fn)" t nil) + +(autoload 'Info-follow-nearest-node--magit-gitman "magit-utils" "\ + + +\(fn FN &optional FORK)" nil nil) + +(advice-add 'Info-follow-nearest-node :around 'Info-follow-nearest-node--magit-gitman) + +(autoload 'org-man-export--magit-gitman "magit-utils" "\ + + +\(fn FN LINK DESCRIPTION FORMAT)" nil nil) + +(advice-add 'org-man-export :around 'org-man-export--magit-gitman) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-utils" '("magit-" "whitespace-dont-turn-on-in-magit-mode"))) + +;;;*** + +;;;### (autoloads nil "magit-wip" "magit-wip.el" (0 0 0 0)) +;;; Generated autoloads from magit-wip.el + +(defvar magit-wip-after-save-mode nil "\ +Non-nil if Magit-Wip-After-Save mode is enabled. +See the `magit-wip-after-save-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `magit-wip-after-save-mode'.") + +(custom-autoload 'magit-wip-after-save-mode "magit-wip" nil) + +(autoload 'magit-wip-after-save-mode "magit-wip" "\ +Toggle Magit-Wip-After-Save-Local mode in all buffers. +With prefix ARG, enable Magit-Wip-After-Save mode if ARG is positive; +otherwise, disable it. If called from Lisp, enable the mode if +ARG is omitted or nil. + +Magit-Wip-After-Save-Local mode is enabled in all buffers where +`magit-wip-after-save-local-mode-turn-on' would do it. +See `magit-wip-after-save-local-mode' for more information on Magit-Wip-After-Save-Local mode. + +\(fn &optional ARG)" t nil) + +(defvar magit-wip-after-apply-mode nil "\ +Non-nil if Magit-Wip-After-Apply mode is enabled. +See the `magit-wip-after-apply-mode' command +for a description of this minor mode.") + +(custom-autoload 'magit-wip-after-apply-mode "magit-wip" nil) + +(autoload 'magit-wip-after-apply-mode "magit-wip" "\ +Commit to work-in-progress refs. + +After applying a change using any \"apply variant\" +command (apply, stage, unstage, discard, and reverse) commit the +affected files to the current wip refs. For each branch there +may be two wip refs; one contains snapshots of the files as found +in the worktree and the other contains snapshots of the entries +in the index. + +\(fn &optional ARG)" t nil) + +(defvar magit-wip-before-change-mode nil "\ +Non-nil if Magit-Wip-Before-Change mode is enabled. +See the `magit-wip-before-change-mode' command +for a description of this minor mode.") + +(custom-autoload 'magit-wip-before-change-mode "magit-wip" nil) + +(autoload 'magit-wip-before-change-mode "magit-wip" "\ +Commit to work-in-progress refs before certain destructive changes. + +Before invoking a revert command or an \"apply variant\" +command (apply, stage, unstage, discard, and reverse) commit the +affected tracked files to the current wip refs. For each branch +there may be two wip refs; one contains snapshots of the files +as found in the worktree and the other contains snapshots of the +entries in the index. + +Only changes to files which could potentially be affected by the +command which is about to be called are committed. + +\(fn &optional ARG)" t nil) + +(autoload 'magit-wip-commit-initial-backup "magit-wip" "\ +Before saving, commit current file to a worktree wip ref. + +The user has to add this function to `before-save-hook'. + +Commit the current state of the visited file before saving the +current buffer to that file. This backs up the same version of +the file as `backup-buffer' would, but stores the backup in the +worktree wip ref, which is also used by the various Magit Wip +modes, instead of in a backup file as `backup-buffer' would. + +This function ignores the variables that affect `backup-buffer' +and can be used along-side that function, which is recommended +because this function only backs up files that are tracked in +a Git repository. + +\(fn)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-wip" '("magit-"))) + +;;;*** + +;;;### (autoloads nil "magit-worktree" "magit-worktree.el" (0 0 0 +;;;;;; 0)) +;;; Generated autoloads from magit-worktree.el + (autoload 'magit-worktree-popup "magit-worktree" nil t) + +(autoload 'magit-worktree-checkout "magit-worktree" "\ +Checkout BRANCH in a new worktree at PATH. + +\(fn PATH BRANCH)" t nil) + +(autoload 'magit-worktree-branch "magit-worktree" "\ +Create a new BRANCH and check it out in a new worktree at PATH. + +\(fn PATH BRANCH START-POINT &optional FORCE)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-worktree" '("magit-"))) + +;;;*** + +;;;### (autoloads nil nil ("magit-core.el" "magit-obsolete.el" "magit-pkg.el") +;;;;;; (0 0 0 0)) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; magit-autoloads.el ends here diff --git a/elpa/magit-20181113.1837/magit-autorevert.el b/elpa/magit-20181113.1837/magit-autorevert.el new file mode 100644 index 00000000..9001b138 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-autorevert.el @@ -0,0 +1,261 @@ +;;; magit-autorevert.el --- revert buffers when files in repository change -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Code: + +(require 'cl-lib) +(require 'dash) + +(require 'magit-git) + +(require 'autorevert) + +;;; Options + +(defgroup magit-auto-revert nil + "Revert buffers when files in repository change." + :link '(custom-group-link auto-revert) + :link '(info-link "(magit)Automatic Reverting of File-Visiting Buffers") + :group 'auto-revert + :group 'magit-essentials + :group 'magit-modes) + +(defcustom auto-revert-buffer-list-filter nil + "Filter that determines which buffers `auto-revert-buffers' reverts. + +This option is provided by `magit', which also redefines +`auto-revert-buffers' to respect it. Magit users who do not turn +on the local mode `auto-revert-mode' themselves, are best served +by setting the value to `magit-auto-revert-repository-buffers-p'. + +However the default is nil, to not disturb users who do use the +local mode directly. If you experience delays when running Magit +commands, then you should consider using one of the predicates +provided by Magit - especially if you also use Tramp. + +Users who do turn on `auto-revert-mode' in buffers in which Magit +doesn't do that for them, should likely not use any filter. +Users who turn on `global-auto-revert-mode', do not have to worry +about this option, because it is disregarded if the global mode +is enabled." + :package-version '(magit . "2.4.2") + :group 'auto-revert + :group 'magit-auto-revert + :group 'magit-related + :type '(radio (const :tag "no filter" nil) + (function-item magit-auto-revert-buffer-p) + (function-item magit-auto-revert-repository-buffer-p) + function)) + +(defcustom magit-auto-revert-tracked-only t + "Whether `magit-auto-revert-mode' only reverts tracked files." + :package-version '(magit . "2.4.0") + :group 'magit-auto-revert + :type 'boolean + :set (lambda (var val) + (set var val) + (when (and (bound-and-true-p magit-auto-revert-mode) + (featurep 'magit-autorevert)) + (magit-auto-revert-mode -1) + (magit-auto-revert-mode)))) + +(defcustom magit-auto-revert-immediately t + "Whether Magit reverts buffers immediately. + +If this is non-nil and either `global-auto-revert-mode' or +`magit-auto-revert-mode' is enabled, then Magit immediately +reverts buffers by explicitly calling `auto-revert-buffers' +after running git for side-effects. + +If `auto-revert-use-notify' is non-nil (and file notifications +are actually supported), then `magit-auto-revert-immediately' +does not have to be non-nil, because the reverts happen +immediately anyway. + +If `magit-auto-revert-immediately' and `auto-revert-use-notify' +are both nil, then reverts happen after `auto-revert-interval' +seconds of user inactivity. That is not desirable." + :package-version '(magit . "2.4.0") + :group 'magit-auto-revert + :type 'boolean) + +;;; Mode + +(defun magit-turn-on-auto-revert-mode-if-desired (&optional file) + (if file + (--when-let (find-buffer-visiting file) + (with-current-buffer it + (magit-turn-on-auto-revert-mode-if-desired))) + (when (and buffer-file-name + (file-readable-p buffer-file-name) + (magit-toplevel) + (or (not magit-auto-revert-tracked-only) + (magit-file-tracked-p buffer-file-name)) + (not auto-revert-mode) ; see #3014 + (not global-auto-revert-mode)) ; see #3460 + (auto-revert-mode 1)))) + +;;;###autoload +(define-globalized-minor-mode magit-auto-revert-mode auto-revert-mode + magit-turn-on-auto-revert-mode-if-desired + :package-version '(magit . "2.4.0") + :link '(info-link "(magit)Automatic Reverting of File-Visiting Buffers") + :group 'magit-auto-revert + :group 'magit-essentials + ;; - When `global-auto-revert-mode' is enabled, then this mode is + ;; redundant. + ;; - In all other cases enable the mode because if buffers are not + ;; automatically reverted that would make many very common tasks + ;; much more cumbersome. + ;; - When `magit-revert-buffers' is nil, then the user has opted out + ;; of the automatic reverts while a very old implementation was + ;; still in use. We continued to respect that setting for another + ;; two and a half years, but no longer do so now. + :init-value (and (not global-auto-revert-mode) + (not noninteractive))) +;; - Unfortunately `:init-value t' only sets the value of the mode +;; variable but does not cause the mode function to be called. +;; - I don't think it works like this on purpose, but since one usually +;; should not enable global modes by default, it is understandable. +;; - If the user has set the variable `magit-auto-revert-mode' to nil +;; after loading magit (instead of doing so before loading magit or +;; by using the function), then we should still respect that setting. +;; - If the user has set the obsolete variable `magit-revert-buffers' +;; to nil before or after loading magit, then we should still respect +;; that setting. +;; - If the user sets one of these variables after loading magit and +;; after `after-init-hook' has run, then that won't have an effect +;; and there is nothing we can do about it. +(defun magit-auto-revert-mode--init-kludge () + "This is an internal kludge to be used on `after-init-hook'. +Do not use this function elsewhere, and don't remove it from +the `after-init-hook'. For more information see the comments +and code surrounding the definition of this function." + (if magit-auto-revert-mode + (let ((start (current-time))) + (magit-message "Turning on magit-auto-revert-mode...") + (magit-auto-revert-mode 1) + (magit-message + "Turning on magit-auto-revert-mode...done%s" + (let ((elapsed (float-time (time-subtract (current-time) start)))) + (if (> elapsed 0.2) + (format " (%.3fs, %s buffers checked)" elapsed + (length (buffer-list))) + "")))) + (magit-auto-revert-mode -1))) +(if after-init-time + ;; Since `after-init-hook' has already been + ;; run, turn the mode on or off right now. + (magit-auto-revert-mode--init-kludge) + ;; By the time the init file has been fully loaded the + ;; values of the relevant variables might have changed. + (add-hook 'after-init-hook #'magit-auto-revert-mode--init-kludge t)) + +(put 'magit-auto-revert-mode 'function-documentation + "Toggle Magit Auto Revert mode. +With a prefix argument ARG, enable Magit Auto Revert mode if ARG +is positive, and disable it otherwise. If called from Lisp, +enable the mode if ARG is omitted or nil. + +Magit Auto Revert mode is a global minor mode that reverts +buffers associated with a file that is located inside a Git +repository when the file changes on disk. Use `auto-revert-mode' +to revert a particular buffer. Or use `global-auto-revert-mode' +to revert all file-visiting buffers, not just those that visit +a file located inside a Git repository. + +This global mode works by turning on the buffer-local mode +`auto-revert-mode' at the time a buffer is first created. The +local mode is turned on if the visited file is being tracked in +a Git repository at the time when the buffer is created. + +If `magit-auto-revert-tracked-only' is non-nil (the default), +then only tracked files are reverted. But if you stage a +previously untracked file using `magit-stage', then this mode +notices that. + +Unlike `global-auto-revert-mode', this mode never reverts any +buffers that are not visiting files. + +The behavior of this mode can be customized using the options +in the `autorevert' and `magit-autorevert' groups. + +This function calls the hook `magit-auto-revert-mode-hook'.") + +(defun magit-auto-revert-buffers () + (when (and magit-auto-revert-immediately + (or global-auto-revert-mode + (and magit-auto-revert-mode auto-revert-buffer-list))) + (let ((auto-revert-buffer-list-filter + (or auto-revert-buffer-list-filter + 'magit-auto-revert-repository-buffer-p))) + (auto-revert-buffers)))) + +(defvar magit-auto-revert-toplevel nil) + +(when (< emacs-major-version 25) + (defvar auto-revert-buffers-counter 1 + "Incremented each time `auto-revert-buffers' is called")) + +(defun magit-auto-revert-buffer-p (buffer) + "Return t if BUFFER visits a file inside the current repository. +The current repository is the one in which `default-directory' is +located. If there is no current repository, then return t for +any BUFFER." + (magit-auto-revert-repository-buffer-p buffer t)) + +(defun magit-auto-revert-repository-buffer-p (buffer &optional fallback) + "Return t if BUFFER visits a file inside the current repository. +The current repository is the one in which `default-directory' is +located. If there is no current repository, then return FALLBACK +\(which defaults to nil) for any BUFFER." + ;; Call `magit-toplevel' just once per cycle. + (unless (and magit-auto-revert-toplevel + (= (cdr magit-auto-revert-toplevel) + auto-revert-buffers-counter)) + (setq magit-auto-revert-toplevel + (cons (or (magit-toplevel) 'no-repo) + auto-revert-buffers-counter))) + (let ((top (car magit-auto-revert-toplevel))) + (if (eq top 'no-repo) + fallback + (let ((dir (with-current-buffer buffer default-directory))) + (and (equal (file-remote-p dir) + (file-remote-p top)) + ;; ^ `tramp-handle-file-in-directory-p' lacks this optimization. + (file-in-directory-p dir top)))))) + +(defun auto-revert-buffers--buffer-list-filter () + (when (< emacs-major-version 25) + (cl-incf auto-revert-buffers-counter)) + (when auto-revert-buffer-list-filter + (setq auto-revert-buffer-list + (--filter auto-revert-buffer-list-filter + auto-revert-buffer-list)))) + +(advice-add 'auto-revert-buffers :before + 'auto-revert-buffers--buffer-list-filter) + +;;; _ +(provide 'magit-autorevert) +;;; magit-autorevert.el ends here diff --git a/elpa/magit-20181113.1837/magit-bisect.el b/elpa/magit-20181113.1837/magit-bisect.el new file mode 100644 index 00000000..735785b7 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-bisect.el @@ -0,0 +1,217 @@ +;;; magit-bisect.el --- bisect support for Magit -*- lexical-binding: t -*- + +;; Copyright (C) 2011-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; Use a binary search to find the commit that introduced a bug. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-bisect-show-graph t + "Whether to use `--graph' in the log showing commits yet to be bisected." + :package-version '(magit . "2.8.0") + :group 'magit-status + :type 'boolean) + +(defface magit-bisect-good + '((t :foreground "DarkOliveGreen")) + "Face for good bisect revisions." + :group 'magit-faces) + +(defface magit-bisect-skip + '((t :foreground "DarkGoldenrod")) + "Face for skipped bisect revisions." + :group 'magit-faces) + +(defface magit-bisect-bad + '((t :foreground "IndianRed4")) + "Face for bad bisect revisions." + :group 'magit-faces) + +;;; Commands + +;;;###autoload (autoload 'magit-bisect-popup "magit-bisect" nil t) +(magit-define-popup magit-bisect-popup + "Popup console for bisect commands." + :man-page "git-bisect" + :actions '((?B "Start" magit-bisect-start) + (?s "Start script" magit-bisect-run)) + :sequence-actions '((?b "Bad" magit-bisect-bad) + (?g "Good" magit-bisect-good) + (?k "Skip" magit-bisect-skip) + (?r "Reset" magit-bisect-reset) + (?s "Run script" magit-bisect-run)) + :sequence-predicate 'magit-bisect-in-progress-p) + +;;;###autoload +(defun magit-bisect-start (bad good) + "Start a bisect session. + +Bisecting a bug means to find the commit that introduced it. +This command starts such a bisect session by asking for a know +good and a bad commit. To move the session forward use the +other actions from the bisect popup (\ +\\\\[magit-bisect-popup])." + (interactive (if (magit-bisect-in-progress-p) + (user-error "Already bisecting") + (magit-bisect-start-read-args))) + (unless (magit-rev-ancestor-p good bad) + (user-error + "The good revision (%s) has to be an ancestor of the bad one (%s)" + good bad)) + (when (magit-anything-modified-p) + (user-error "Cannot bisect with uncommitted changes")) + (magit-git-bisect "start" (list bad good) t)) + +(defun magit-bisect-start-read-args () + (let ((b (magit-read-branch-or-commit "Start bisect with bad revision"))) + (list b (magit-read-other-branch-or-commit "Good revision" b)))) + +;;;###autoload +(defun magit-bisect-reset () + "After bisecting, cleanup bisection state and return to original `HEAD'." + (interactive) + (magit-confirm 'reset-bisect) + (magit-run-git "bisect" "reset") + (ignore-errors (delete-file (magit-git-dir "BISECT_CMD_OUTPUT")))) + +;;;###autoload +(defun magit-bisect-good () + "While bisecting, mark the current commit as good. +Use this after you have asserted that the commit does not contain +the bug in question." + (interactive) + (magit-git-bisect "good")) + +;;;###autoload +(defun magit-bisect-bad () + "While bisecting, mark the current commit as bad. +Use this after you have asserted that the commit does contain the +bug in question." + (interactive) + (magit-git-bisect "bad")) + +;;;###autoload +(defun magit-bisect-skip () + "While bisecting, skip the current commit. +Use this if for some reason the current commit is not a good one +to test. This command lets Git choose a different one." + (interactive) + (magit-git-bisect "skip")) + +;;;###autoload +(defun magit-bisect-run (cmdline &optional bad good) + "Bisect automatically by running commands after each step. + +Unlike `git bisect run' this can be used before bisecting has +begun. In that case it behaves like `git bisect start; git +bisect run'." + (interactive (let ((args (and (not (magit-bisect-in-progress-p)) + (magit-bisect-start-read-args)))) + (cons (read-shell-command "Bisect shell command: ") args))) + (when (and bad good) + (magit-bisect-start bad good)) + (magit-git-bisect "run" (list shell-file-name shell-command-switch cmdline))) + +(defun magit-git-bisect (subcommand &optional args no-assert) + (unless (or no-assert (magit-bisect-in-progress-p)) + (user-error "Not bisecting")) + (magit-with-toplevel + (magit-run-git-with-logfile + (magit-git-dir "BISECT_CMD_OUTPUT") "bisect" subcommand args))) + +;;; Sections + +(defun magit-bisect-in-progress-p () + (file-exists-p (magit-git-dir "BISECT_LOG"))) + +(defun magit-insert-bisect-output () + "While bisecting, insert section with output from `git bisect'." + (when (magit-bisect-in-progress-p) + (let* ((lines + (or (magit-file-lines (magit-git-dir "BISECT_CMD_OUTPUT")) + (list "Bisecting: (no saved bisect output)" + "It appears you have invoked `git bisect' from a shell." + "There is nothing wrong with that, we just cannot display" + "anything useful here. Consult the shell output instead."))) + (done-re "^\\([a-z0-9]\\{40\\}\\) is the first bad commit$") + (bad-line (or (and (string-match done-re (car lines)) + (pop lines)) + (--first (string-match done-re it) lines)))) + (magit-insert-section ((eval (if bad-line 'commit 'bisect-output)) + (and bad-line (match-string 1 bad-line))) + (magit-insert-heading + (propertize (or bad-line (pop lines)) + 'face 'magit-section-heading)) + (dolist (line lines) + (insert line "\n")))) + (insert "\n"))) + +(defun magit-insert-bisect-rest () + "While bisecting, insert section visualizing the bisect state." + (when (magit-bisect-in-progress-p) + (magit-insert-section (bisect-view) + (magit-insert-heading "Bisect Rest:") + (magit-git-wash (apply-partially 'magit-log-wash-log 'bisect-vis) + "bisect" "visualize" "git" "log" + "--format=%h%d%x00%s" "--decorate=full" + (and magit-bisect-show-graph "--graph"))))) + +(defun magit-insert-bisect-log () + "While bisecting, insert section logging bisect progress." + (when (magit-bisect-in-progress-p) + (magit-insert-section (bisect-log) + (magit-insert-heading "Bisect Log:") + (magit-git-wash #'magit-wash-bisect-log "bisect" "log") + (insert ?\n)))) + +(defun magit-wash-bisect-log (_args) + (let (beg) + (while (progn (setq beg (point-marker)) + (re-search-forward "^\\(git bisect [^\n]+\n\\)" nil t)) + (magit-bind-match-strings (heading) nil + (magit-delete-match) + (save-restriction + (narrow-to-region beg (point)) + (goto-char (point-min)) + (magit-insert-section (bisect-item heading t) + (insert (propertize heading 'face 'magit-section-secondary-heading)) + (magit-insert-heading) + (magit-wash-sequence + (apply-partially 'magit-log-wash-rev 'bisect-log + (magit-abbrev-length))) + (insert ?\n))))) + (when (re-search-forward + "# first bad commit: \\[\\([a-z0-9]\\{40\\}\\)\\] [^\n]+\n" nil t) + (magit-bind-match-strings (hash) nil + (magit-delete-match) + (magit-insert-section (bisect-item) + (insert hash " is the first bad commit\n")))))) + +;;; _ +(provide 'magit-bisect) +;;; magit-bisect.el ends here diff --git a/elpa/magit-20181113.1837/magit-blame.el b/elpa/magit-20181113.1837/magit-blame.el new file mode 100644 index 00000000..99351b75 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-blame.el @@ -0,0 +1,930 @@ +;;; magit-blame.el --- blame support for Magit -*- lexical-binding: t -*- + +;; Copyright (C) 2012-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; Annotates each line in file-visiting buffer with information from +;; the revision which last modified the line. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +;;; Options + +(defgroup magit-blame nil + "Blame support for Magit." + :link '(info-link "(magit)Blaming") + :group 'magit-modes) + +(defcustom magit-blame-styles + '((headings + (heading-format . "%-20a %C %s\n")) + (margin + (margin-format . (" %s%f" " %C %a" " %H")) + (margin-width . 42) + (margin-face . magit-blame-margin) + (margin-body-face . (magit-blame-dimmed))) + (highlight + (highlight-face . magit-blame-highlight)) + (lines + (show-lines . t))) + "List of styles used to visualize blame information. + +Each entry has the form (IDENT (KEY . VALUE)...). IDENT has +to be a symbol uniquely identifing the style. The following +KEYs are recognized: + + `show-lines' + Whether to prefix each chunk of lines with a thin line. + This has no effect if `heading-format' is non-nil. + `highlight-face' + Face used to highlight the first line of each chunk. + If this is nil, then those lines are not highlighted. + `heading-format' + String specifing the information to be shown above each + chunk of lines. It must end with a newline character. + `margin-format' + String specifing the information to be shown in the left + buffer margin. It must NOT end with a newline character. + This can also be a list of formats used for the lines at + the same positions within the chunk. If the chunk has + more lines than formats are specified, then the last is + repeated. + `margin-width' + Width of the margin, provided `margin-format' is non-nil. + `margin-face' + Face used in the margin, provided `margin-format' is + non-nil. This face is used in combination with the faces + that are specific to the used %-specs. If this is nil, + then `magit-blame-margin' is used. + `margin-body-face' + Face used in the margin for all but first line of a chunk. + This face is used in combination with the faces that are + specific to the used %-specs. This can also be a list of + faces (usually one face), in which case only these faces + are used and the %-spec faces are ignored. A good value + might be `(magit-blame-dimmed)'. If this is nil, then + the same face as for the first line is used. + +The following %-specs can be used in `heading-format' and +`margin-format': + + %H hash using face `magit-blame-hash' + %s summary using face `magit-blame-summary' + %a author using face `magit-blame-name' + %A author time using face `magit-blame-date' + %c committer using face `magit-blame-name' + %C committer time using face `magit-blame-date' + +Additionally if `margin-format' ends with %f, then the string +that is displayed in the margin is made at least `margin-width' +characters wide, which may be desirable if the used face sets +the background color. + +The style used in the current buffer can be cycled from the blame +popup. Blame commands (except `magit-blame-echo') use the first +style as the initial style when beginning to blame in a buffer." + :package-version '(magit . "2.13.0") + :group 'magit-blame + :type 'string) + +(defcustom magit-blame-echo-style 'lines + "The blame visualization style used by `magit-blame-echo'. +A symbol that has to be used as the identifier for one of the +styles defined in `magit-blame-styles'." + :package-version '(magit . "2.13.0") + :group 'magit-blame + :type 'symbol) + +(defcustom magit-blame-time-format "%F %H:%M" + "Format for time strings in blame headings." + :group 'magit-blame + :type 'string) + +(defcustom magit-blame-read-only t + "Whether to initially make the blamed buffer read-only." + :package-version '(magit . "2.13.0") + :group 'magit-blame + :type 'boolean) + +(defcustom magit-blame-disable-modes '(fci-mode yascroll-bar-mode) + "List of modes not compatible with Magit-Blame mode. +This modes are turned off when Magit-Blame mode is turned on, +and then turned on again when turning off the latter." + :group 'magit-blame + :type '(repeat (symbol :tag "Mode"))) + +(defcustom magit-blame-mode-lighter " Blame" + "The mode-line lighter of the Magit-Blame mode." + :group 'magit-blame + :type '(choice (const :tag "No lighter" "") string)) + +(defcustom magit-blame-goto-chunk-hook + '(magit-blame-maybe-update-revision-buffer + magit-blame-maybe-show-message) + "Hook run after point entered another chunk." + :package-version '(magit . "2.13.0") + :group 'magit-blame + :type 'hook + :get 'magit-hook-custom-get + :options '(magit-blame-maybe-update-revision-buffer + magit-blame-maybe-show-message)) + +;;; Faces + +(defface magit-blame-highlight + '((((class color) (background light)) + :background "grey80" + :foreground "black") + (((class color) (background dark)) + :background "grey25" + :foreground "white")) + "Face used for highlighting when blaming. +Also see option `magit-blame-styles'." + :group 'magit-faces) + +(defface magit-blame-margin + '((t :inherit magit-blame-highlight + :weight normal + :slant normal)) + "Face used for the blame margin by default when blaming. +Also see option `magit-blame-styles'." + :group 'magit-faces) + +(defface magit-blame-dimmed + '((t :inherit magit-dimmed + :weight normal + :slant normal)) + "Face used for the blame margin in some cases when blaming. +Also see option `magit-blame-styles'." + :group 'magit-faces) + +(defface magit-blame-heading + '((t :inherit magit-blame-highlight + :weight normal + :slant normal)) + "Face used for blame headings by default when blaming. +Also see option `magit-blame-styles'." + :group 'magit-faces) + +(defface magit-blame-summary nil + "Face used for commit summaries when blaming." + :group 'magit-faces) + +(defface magit-blame-hash nil + "Face used for commit hashes when blaming." + :group 'magit-faces) + +(defface magit-blame-name nil + "Face used for author and committer names when blaming." + :group 'magit-faces) + +(defface magit-blame-date nil + "Face used for dates when blaming." + :group 'magit-faces) + +;;; Chunks + +(defclass magit-blame-chunk () + (;; + (orig-rev :initarg :orig-rev) + (orig-line :initarg :orig-line) + (final-line :initarg :final-line) + (num-lines :initarg :num-lines) + ;; previous + (prev-rev :initform nil) + (prev-file :initform nil) + ;; filename + (orig-file))) + +(defun magit-current-blame-chunk (&optional type) + (or (and (not (and type (not (eq type magit-blame-type)))) + (magit-blame-chunk-at (point))) + (and type + (let ((rev (or magit-buffer-refname magit-buffer-revision)) + (file (magit-file-relative-name nil (not magit-buffer-file-name))) + (line (format "%i,+1" (line-number-at-pos)))) + (unless file + (error "Buffer does not visit a tracked file")) + (with-temp-buffer + (magit-with-toplevel + (magit-git-insert + "blame" "--porcelain" + (if (memq magit-blame-type '(final removal)) + (cons "--reverse" (magit-blame-arguments)) + (magit-blame-arguments)) + "-L" line rev "--" file) + (goto-char (point-min)) + (car (magit-blame--parse-chunk type)))))))) + +(defun magit-blame-chunk-at (pos) + (--some (overlay-get it 'magit-blame-chunk) + (overlays-at pos))) + +(defun magit-blame--overlay-at (&optional pos key) + (unless pos + (setq pos (point))) + (--first (overlay-get it (or key 'magit-blame-chunk)) + (nconc (overlays-at pos) + (overlays-in pos pos)))) + +;;; Keymaps + +(defvar magit-blame-mode-map + (let ((map (make-sparse-keymap))) + (define-key map (kbd "C-c C-q") 'magit-blame-quit) + map) + "Keymap for `magit-blame-mode'. +Note that most blaming key bindings are defined +in `magit-blame-read-only-mode-map' instead.") + +(defvar magit-blame-read-only-mode-map + (let ((map (make-sparse-keymap))) + (cond ((featurep 'jkl) + (define-key map [return] 'magit-show-commit) + (define-key map (kbd "i") 'magit-blame-previous-chunk) + (define-key map (kbd "I") 'magit-blame-previous-chunk-same-commit) + (define-key map (kbd "k") 'magit-blame-next-chunk) + (define-key map (kbd "K") 'magit-blame-next-chunk-same-commit) + (define-key map (kbd "j") 'magit-blame-addition) + (define-key map (kbd "l") 'magit-blame-removal) + (define-key map (kbd "f") 'magit-blame-reverse) + (define-key map (kbd "b") 'magit-blame-popup)) + (t + (define-key map (kbd "C-m") 'magit-show-commit) + (define-key map (kbd "p") 'magit-blame-previous-chunk) + (define-key map (kbd "P") 'magit-blame-previous-chunk-same-commit) + (define-key map (kbd "n") 'magit-blame-next-chunk) + (define-key map (kbd "N") 'magit-blame-next-chunk-same-commit) + (define-key map (kbd "b") 'magit-blame-addition) + (define-key map (kbd "r") 'magit-blame-removal) + (define-key map (kbd "f") 'magit-blame-reverse) + (define-key map (kbd "B") 'magit-blame-popup))) + (define-key map (kbd "c") 'magit-blame-cycle-style) + (define-key map (kbd "q") 'magit-blame-quit) + (define-key map (kbd "M-w") 'magit-blame-copy-hash) + (define-key map (kbd "SPC") 'magit-diff-show-or-scroll-up) + (define-key map (kbd "DEL") 'magit-diff-show-or-scroll-down) + map) + "Keymap for `magit-blame-read-only-mode'.") + +;;; Modes +;;;; Variables + +(defvar-local magit-blame-buffer-read-only nil) +(defvar-local magit-blame-cache nil) +(defvar-local magit-blame-disabled-modes nil) +(defvar-local magit-blame-process nil) +(defvar-local magit-blame-recursive-p nil) +(defvar-local magit-blame-type nil) +(defvar-local magit-blame-separator nil) +(defvar-local magit-blame-previous-chunk nil) + +(defvar-local magit-blame--style nil) + +(defsubst magit-blame--style-get (key) + (cdr (assoc key (cdr magit-blame--style)))) + +;;;; Base Mode + +(define-minor-mode magit-blame-mode + "Display blame information inline." + :lighter magit-blame-mode-lighter + (cond (magit-blame-mode + (when (called-interactively-p 'any) + (setq magit-blame-mode nil) + (user-error + (concat "Don't call `magit-blame-mode' directly; " + "instead use `magit-blame' or `magit-blame-popup'"))) + (add-hook 'after-save-hook 'magit-blame--run t t) + (add-hook 'post-command-hook 'magit-blame-goto-chunk-hook t t) + (add-hook 'before-revert-hook 'magit-blame--remove-overlays t t) + (add-hook 'after-revert-hook 'magit-blame--run t t) + (add-hook 'read-only-mode-hook 'magit-blame-toggle-read-only t t) + (setq magit-blame-buffer-read-only buffer-read-only) + (when (or magit-blame-read-only magit-buffer-file-name) + (read-only-mode 1)) + (dolist (mode magit-blame-disable-modes) + (when (and (boundp mode) (symbol-value mode)) + (funcall mode -1) + (push mode magit-blame-disabled-modes))) + (setq magit-blame-separator (magit-blame--format-separator)) + (unless magit-blame--style + (setq magit-blame--style (car magit-blame-styles))) + (magit-blame--update-margin)) + (t + (when (process-live-p magit-blame-process) + (kill-process magit-blame-process) + (while magit-blame-process + (sit-for 0.01))) ; avoid racing the sentinal + (remove-hook 'after-save-hook 'magit-blame--run t) + (remove-hook 'post-command-hook 'magit-blame-goto-chunk-hook t) + (remove-hook 'before-revert-hook 'magit-blame--remove-overlays t) + (remove-hook 'after-revert-hook 'magit-blame--run t) + (remove-hook 'read-only-mode-hook 'magit-blame-toggle-read-only t) + (unless magit-blame-buffer-read-only + (read-only-mode -1)) + (magit-blame-read-only-mode -1) + (dolist (mode magit-blame-disabled-modes) + (funcall mode 1)) + (kill-local-variable 'magit-blame-disabled-modes) + (kill-local-variable 'magit-blame-type) + (kill-local-variable 'magit-blame--style) + (magit-blame--update-margin) + (magit-blame--remove-overlays)))) + +(defun magit-blame-goto-chunk-hook () + (let ((chunk (magit-blame-chunk-at (point)))) + (when (cl-typep chunk 'magit-blame-chunk) + (unless (eq chunk magit-blame-previous-chunk) + (run-hooks 'magit-blame-goto-chunk-hook)) + (setq magit-blame-previous-chunk chunk)))) + +(defun magit-blame-toggle-read-only () + (magit-blame-read-only-mode (if buffer-read-only 1 -1))) + +;;;; Read-Only Mode + +(define-minor-mode magit-blame-read-only-mode + "Provide keybindings for Magit-Blame mode. + +This minor-mode provides the key bindings for Magit-Blame mode, +but only when Read-Only mode is also enabled because these key +bindings would otherwise conflict badly with regular bindings. + +When both Magit-Blame mode and Read-Only mode are enabled, then +this mode gets automatically enabled too and when one of these +modes is toggled, then this mode also gets toggled automatically. + +\\{magit-blame-read-only-mode-map}") + +;;;; Kludges + +(defun magit-blame-put-keymap-before-view-mode () + "Put `magit-blame-read-only-mode' ahead of `view-mode' in `minor-mode-map-alist'." + (--when-let (assq 'magit-blame-read-only-mode + (cl-member 'view-mode minor-mode-map-alist :key #'car)) + (setq minor-mode-map-alist + (cons it (delq it minor-mode-map-alist)))) + (remove-hook 'view-mode-hook #'magit-blame-put-keymap-before-view-mode)) + +(add-hook 'view-mode-hook #'magit-blame-put-keymap-before-view-mode) + +;;; Process + +(defun magit-blame--run () + (magit-with-toplevel + (unless magit-blame-mode + (magit-blame-mode 1)) + (message "Blaming...") + (magit-blame-run-process + (or magit-buffer-refname magit-buffer-revision) + (magit-file-relative-name nil (not magit-buffer-file-name)) + (if (memq magit-blame-type '(final removal)) + (cons "--reverse" (magit-blame-arguments)) + (magit-blame-arguments)) + (list (line-number-at-pos (window-start)) + (line-number-at-pos (1- (window-end nil t))))) + (set-process-sentinel magit-this-process + 'magit-blame-process-quickstart-sentinel))) + +(defun magit-blame-run-process (revision file args &optional lines) + (let ((process (magit-parse-git-async + "blame" "--incremental" args + (and lines (list "-L" (apply #'format "%s,%s" lines))) + revision "--" file))) + (set-process-filter process 'magit-blame-process-filter) + (set-process-sentinel process 'magit-blame-process-sentinel) + (process-put process 'arguments (list revision file args)) + (setq magit-blame-cache (make-hash-table :test 'equal)) + (setq magit-blame-process process))) + +(defun magit-blame-process-quickstart-sentinel (process event) + (when (memq (process-status process) '(exit signal)) + (magit-blame-process-sentinel process event t) + (magit-blame-assert-buffer process) + (with-current-buffer (process-get process 'command-buf) + (when magit-blame-mode + (let ((default-directory (magit-toplevel))) + (apply #'magit-blame-run-process + (process-get process 'arguments))))))) + +(defun magit-blame-process-sentinel (process _event &optional quiet) + (let ((status (process-status process))) + (when (memq status '(exit signal)) + (kill-buffer (process-buffer process)) + (if (and (eq status 'exit) + (zerop (process-exit-status process))) + (unless quiet + (message "Blaming...done")) + (magit-blame-assert-buffer process) + (with-current-buffer (process-get process 'command-buf) + (if magit-blame-mode + (progn (magit-blame-mode -1) + (message "Blaming...failed")) + (message "Blaming...aborted")))) + (kill-local-variable 'magit-blame-process)))) + +(defun magit-blame-process-filter (process string) + (internal-default-process-filter process string) + (let ((buf (process-get process 'command-buf)) + (pos (process-get process 'parsed)) + (mark (process-mark process)) + type cache) + (with-current-buffer buf + (setq type magit-blame-type) + (setq cache magit-blame-cache)) + (with-current-buffer (process-buffer process) + (goto-char pos) + (while (and (< (point) mark) + (save-excursion (re-search-forward "^filename .+\n" nil t))) + (pcase-let* ((`(,chunk ,revinfo) + (magit-blame--parse-chunk type)) + (rev (oref chunk orig-rev))) + (if revinfo + (puthash rev revinfo cache) + (setq revinfo + (or (gethash rev cache) + (puthash rev (magit-blame--commit-alist rev) cache)))) + (magit-blame--make-overlays buf chunk revinfo)) + (process-put process 'parsed (point)))))) + +(defun magit-blame--parse-chunk (type) + (let (chunk revinfo) + (looking-at "^\\(.\\{40\\}\\) \\([0-9]+\\) \\([0-9]+\\) \\([0-9]+\\)") + (with-slots (orig-rev orig-file prev-rev prev-file) + (setq chunk (magit-blame-chunk + :orig-rev (match-string 1) + :orig-line (string-to-number (match-string 2)) + :final-line (string-to-number (match-string 3)) + :num-lines (string-to-number (match-string 4)))) + (forward-line) + (let (done) + (while (not done) + (cond ((looking-at "^filename \\(.+\\)") + (setq done t) + (setf orig-file (match-string 1))) + ((looking-at "^previous \\(.\\{40\\}\\) \\(.+\\)") + (setf prev-rev (match-string 1)) + (setf prev-file (match-string 2))) + ((looking-at "^\\([^ ]+\\) \\(.+\\)") + (push (cons (match-string 1) + (match-string 2)) revinfo))) + (forward-line))) + (when (and (eq type 'removal) prev-rev) + (cl-rotatef orig-rev prev-rev) + (cl-rotatef orig-file prev-file) + (setq revinfo nil))) + (list chunk revinfo))) + +(defun magit-blame--commit-alist (rev) + (cl-mapcar 'cons + '("summary" + "author" "author-time" "author-tz" + "committer" "committer-time" "committer-tz") + (split-string (magit-rev-format "%s\v%an\v%ad\v%cn\v%cd" rev + "--date=format:%s\v%z") + "\v"))) + +(defun magit-blame-assert-buffer (process) + (unless (buffer-live-p (process-get process 'command-buf)) + (kill-process process) + (user-error "Buffer being blamed has been killed"))) + +;;; Display + +(defun magit-blame--make-overlays (buf chunk revinfo) + (with-current-buffer buf + (save-excursion + (save-restriction + (widen) + (goto-char (point-min)) + (forward-line (1- (oref chunk final-line))) + (let ((beg (point)) + (end (save-excursion + (forward-line (oref chunk num-lines)) + (point)))) + (magit-blame--remove-overlays beg end) + (magit-blame--make-margin-overlays chunk revinfo beg end) + (magit-blame--make-heading-overlay chunk revinfo beg end) + (magit-blame--make-highlight-overlay chunk beg)))))) + +(defun magit-blame--make-margin-overlays (chunk revinfo _beg end) + (save-excursion + (let ((line 0)) + (while (< (point) end) + (magit-blame--make-margin-overlay chunk revinfo line) + (forward-line) + (cl-incf line))))) + +(defun magit-blame--make-margin-overlay (chunk revinfo line) + (let* ((end (line-end-position)) + ;; If possible avoid putting this on the first character + ;; of the line to avoid a conflict with the line overlay. + (beg (min (1+ (line-beginning-position)) end)) + (ov (make-overlay beg end))) + (overlay-put ov 'magit-blame-chunk chunk) + (overlay-put ov 'magit-blame-revinfo revinfo) + (overlay-put ov 'magit-blame-margin line) + (magit-blame--update-margin-overlay ov))) + +(defun magit-blame--make-heading-overlay (chunk revinfo beg end) + (let ((ov (make-overlay beg end))) + (overlay-put ov 'magit-blame-chunk chunk) + (overlay-put ov 'magit-blame-revinfo revinfo) + (overlay-put ov 'magit-blame-heading t) + (magit-blame--update-heading-overlay ov))) + +(defun magit-blame--make-highlight-overlay (chunk beg) + (let ((ov (make-overlay beg (1+ (line-end-position))))) + (overlay-put ov 'magit-blame-chunk chunk) + (overlay-put ov 'magit-blame-highlight t) + (magit-blame--update-highlight-overlay ov))) + +(defun magit-blame--update-margin () + (setq left-margin-width (or (magit-blame--style-get 'margin-width) 0)) + (set-window-buffer (selected-window) (current-buffer))) + +(defun magit-blame--update-overlays () + (save-restriction + (widen) + (dolist (ov (overlays-in (point-min) (point-max))) + (cond ((overlay-get ov 'magit-blame-heading) + (magit-blame--update-heading-overlay ov)) + ((overlay-get ov 'magit-blame-margin) + (magit-blame--update-margin-overlay ov)) + ((overlay-get ov 'magit-blame-highlight) + (magit-blame--update-highlight-overlay ov)))))) + +(defun magit-blame--update-margin-overlay (ov) + (overlay-put + ov 'before-string + (and (magit-blame--style-get 'margin-width) + (propertize + "o" 'display + (list (list 'margin 'left-margin) + (let ((line (overlay-get ov 'magit-blame-margin)) + (format (magit-blame--style-get 'margin-format)) + (face (magit-blame--style-get 'margin-face))) + (magit-blame--format-string + ov + (or (and (atom format) + format) + (nth line format) + (car (last format))) + (or (and (not (zerop line)) + (magit-blame--style-get 'margin-body-face)) + face + 'magit-blame-margin)))))))) + +(defun magit-blame--update-heading-overlay (ov) + (overlay-put + ov 'before-string + (--if-let (magit-blame--style-get 'heading-format) + (magit-blame--format-string ov it 'magit-blame-heading) + (and (magit-blame--style-get 'show-lines) + (or (not (magit-blame--style-get 'margin-format)) + (save-excursion + (goto-char (overlay-start ov)) + ;; Special case of the special case described in + ;; `magit-blame--make-margin-overlay'. For empty + ;; lines it is not possible to show both overlays + ;; without the line being to high. + (not (= (point) (line-end-position))))) + magit-blame-separator)))) + +(defun magit-blame--update-highlight-overlay (ov) + (overlay-put ov 'face (magit-blame--style-get 'highlight-face))) + +(defun magit-blame--format-string (ov format face) + (let* ((chunk (overlay-get ov 'magit-blame-chunk)) + (revinfo (overlay-get ov 'magit-blame-revinfo)) + (key (list format face)) + (string (cdr (assoc key revinfo)))) + (unless string + (setq string + (and format + (magit-blame--format-string-1 (oref chunk orig-rev) + revinfo format face))) + (nconc revinfo (list (cons key string)))) + string)) + +(defun magit-blame--format-string-1 (rev revinfo format face) + (let ((str + (if (equal rev "0000000000000000000000000000000000000000") + (propertize (concat (if (string-prefix-p "\s" format) "\s" "") + "Not Yet Committed" + (if (string-suffix-p "\n" format) "\n" "")) + 'face face) + (magit--format-spec + (propertize format 'face face) + (cl-flet* ((p0 (s f) + (propertize s 'face (if face + (if (listp face) + face + (list f face)) + f))) + (p1 (k f) + (p0 (cdr (assoc k revinfo)) f)) + (p2 (k1 k2 f) + (p0 (magit-blame--format-time-string + (cdr (assoc k1 revinfo)) + (cdr (assoc k2 revinfo))) + f))) + `((?H . ,(p0 rev 'magit-blame-hash)) + (?s . ,(p1 "summary" 'magit-blame-summary)) + (?a . ,(p1 "author" 'magit-blame-name)) + (?c . ,(p1 "committer" 'magit-blame-name)) + (?A . ,(p2 "author-time" "author-tz" 'magit-blame-date)) + (?C . ,(p2 "committer-time" "committer-tz" 'magit-blame-date)) + (?f . ""))))))) + (if-let ((width (and (string-suffix-p "%f" format) + (magit-blame--style-get 'margin-width)))) + (concat str + (propertize (make-string (max 0 (- width (length str))) ?\s) + 'face face)) + str))) + +(defun magit-blame--format-separator () + (propertize + (concat (propertize "\s" 'display '(space :height (2))) + (propertize "\n" 'line-height t)) + 'face (list :background + (face-attribute 'magit-blame-heading :background nil t)))) + +(defun magit-blame--format-time-string (time tz) + (let* ((time-format (or (magit-blame--style-get 'time-format) + magit-blame-time-format)) + (tz-in-second (and (not (version< emacs-version "25")) + (string-match "%z" time-format) + (car (last (parse-time-string tz)))))) + (format-time-string time-format + (seconds-to-time (string-to-number time)) + tz-in-second))) + +(defun magit-blame--remove-overlays (&optional beg end) + (save-restriction + (widen) + (dolist (ov (overlays-in (or beg (point-min)) + (or end (point-max)))) + (when (overlay-get ov 'magit-blame-chunk) + (delete-overlay ov))))) + +(defun magit-blame-maybe-show-message () + (when (magit-blame--style-get 'show-message) + (let ((message-log-max 0)) + (if-let ((msg (cdr (assq 'heading + (gethash (oref (magit-current-blame-chunk) + orig-rev) + magit-blame-cache))))) + (progn (setq msg (substring msg 0 -1)) + (set-text-properties 0 (length msg) nil msg) + (message msg)) + (message "Commit data not available yet. Still blaming."))))) + +;;; Commands + +;;;###autoload +(defun magit-blame-echo () + "For each line show the revision in which it was added. +Show the information about the chunk at point in the echo area +when moving between chunks. Unlike other blaming commands, do +not turn on `read-only-mode'." + (interactive) + (when magit-buffer-file-name + (user-error "Blob buffers aren't supported")) + (setq-local magit-blame--style + (assq magit-blame-echo-style magit-blame-styles)) + (setq-local magit-blame-disable-modes + (cons 'eldoc-mode magit-blame-disable-modes)) + (if (not magit-blame-mode) + (let ((magit-blame-read-only nil)) + (magit-blame-addition)) + (read-only-mode -1) + (magit-blame--update-overlays))) + +;;;###autoload +(defun magit-blame-addition () + "For each line show the revision in which it was added." + (interactive) + (magit-blame--pre-blame-assert 'addition) + (magit-blame--pre-blame-setup 'addition) + (magit-blame--run)) + +;;;###autoload +(defun magit-blame-removal () + "For each line show the revision in which it was removed." + (interactive) + (unless magit-buffer-file-name + (user-error "Only blob buffers can be blamed in reverse")) + (magit-blame--pre-blame-assert 'removal) + (magit-blame--pre-blame-setup 'removal) + (magit-blame--run)) + +;;;###autoload +(defun magit-blame-reverse () + "For each line show the last revision in which it still exists." + (interactive) + (unless magit-buffer-file-name + (user-error "Only blob buffers can be blamed in reverse")) + (magit-blame--pre-blame-assert 'final) + (magit-blame--pre-blame-setup 'final) + (magit-blame--run)) + +(defun magit-blame--pre-blame-assert (type) + (unless (magit-toplevel) + (magit--not-inside-repository-error)) + (if (and magit-blame-mode + (eq type magit-blame-type)) + (if-let ((chunk (magit-current-blame-chunk))) + (unless (oref chunk prev-rev) + (user-error "Chunk has no further history")) + (user-error "Commit data not available yet. Still blaming.")) + (unless (magit-file-relative-name nil (not magit-buffer-file-name)) + (if buffer-file-name + (user-error "Buffer isn't visiting a tracked file") + (user-error "Buffer isn't visiting a file"))))) + +(defun magit-blame--pre-blame-setup (type) + (when magit-blame-mode + (if (eq type magit-blame-type) + (let ((style magit-blame--style)) + (magit-blame-visit-other-file) + (setq-local magit-blame--style style) + (setq-local magit-blame-recursive-p t) + ;; Set window-start for the benefit of quickstart. + (redisplay)) + (magit-blame--remove-overlays))) + (setq magit-blame-type type)) + +(defun magit-blame-visit-other-file () + "Visit another blob related to the current chunk." + (interactive) + (with-slots (prev-rev prev-file orig-line) + (magit-current-blame-chunk) + (unless prev-rev + (user-error "Chunk has no further history")) + (magit-with-toplevel + (magit-find-file prev-rev prev-file)) + ;; TODO Adjust line like magit-diff-visit-file. + (goto-char (point-min)) + (forward-line (1- orig-line)))) + +(defun magit-blame-visit-file () + "Visit the blob related to the current chunk." + (interactive) + (with-slots (orig-rev orig-file orig-line) + (magit-current-blame-chunk) + (magit-with-toplevel + (magit-find-file orig-rev orig-file)) + (goto-char (point-min)) + (forward-line (1- orig-line)))) + +(defun magit-blame-quit () + "Turn off Magit-Blame mode. +If the buffer was created during a recursive blame, +then also kill the buffer." + (interactive) + (magit-blame-mode -1) + (when magit-blame-recursive-p + (kill-buffer))) + +(defun magit-blame-next-chunk () + "Move to the next chunk." + (interactive) + (--if-let (next-single-char-property-change (point) 'magit-blame-chunk) + (goto-char it) + (user-error "No more chunks"))) + +(defun magit-blame-previous-chunk () + "Move to the previous chunk." + (interactive) + (--if-let (previous-single-char-property-change (point) 'magit-blame-chunk) + (goto-char it) + (user-error "No more chunks"))) + +(defun magit-blame-next-chunk-same-commit (&optional previous) + "Move to the next chunk from the same commit.\n\n(fn)" + (interactive) + (if-let ((rev (oref (magit-current-blame-chunk) orig-rev))) + (let ((pos (point)) ov) + (save-excursion + (while (and (not ov) + (not (= pos (if previous (point-min) (point-max)))) + (setq pos (funcall + (if previous + 'previous-single-char-property-change + 'next-single-char-property-change) + pos 'magit-blame-chunk))) + (--when-let (magit-blame--overlay-at pos) + (when (equal (oref (magit-blame-chunk-at pos) orig-rev) rev) + (setq ov it))))) + (if ov + (goto-char (overlay-start ov)) + (user-error "No more chunks from same commit"))) + (user-error "This chunk hasn't been blamed yet"))) + +(defun magit-blame-previous-chunk-same-commit () + "Move to the previous chunk from the same commit." + (interactive) + (magit-blame-next-chunk-same-commit 'previous-single-char-property-change)) + +(defun magit-blame-cycle-style () + "Change how blame information is visualized. +Cycle through the elements of option `magit-blame-styles'." + (interactive) + (setq magit-blame--style + (or (cadr (cl-member (car magit-blame--style) + magit-blame-styles :key #'car)) + (car magit-blame-styles))) + (magit-blame--update-margin) + (magit-blame--update-overlays)) + +(defun magit-blame-copy-hash () + "Save hash of the current chunk's commit to the kill ring. + +When the region is active, then save the region's content +instead of the hash, like `kill-ring-save' would." + (interactive) + (if (use-region-p) + (copy-region-as-kill nil nil 'region) + (kill-new (message "%s" (oref (magit-current-blame-chunk) orig-rev))))) + +;;; Popup + +;;;###autoload (autoload 'magit-blame-popup "magit-blame" nil t) +(magit-define-popup magit-blame-popup + "Popup console for blame commands." + :man-page "git-blame" + :switches '((?w "Ignore whitespace" "-w") + (?r "Do not treat root commits as boundaries" "--root")) + :options '((?M "Detect lines moved or copied within a file" "-M") + (?C "Detect lines moved or copied between files" "-C")) + :actions '("Actions" + (?b "Show commits adding lines" magit-blame-addition) + (?r (lambda () + (with-current-buffer magit-pre-popup-buffer + (and (not buffer-file-name) + (propertize "Show commits removing lines" + 'face 'default)))) + magit-blame-removal) + (?f (lambda () + (with-current-buffer magit-pre-popup-buffer + (and (not buffer-file-name) + (propertize "Show last commits that still have lines" + 'face 'default)))) + magit-blame-reverse) + (lambda () + (and (with-current-buffer magit-pre-popup-buffer + magit-blame-mode) + (propertize "Refresh" 'face 'magit-popup-heading))) + (?c "Cycle style" magit-blame-cycle-style)) + :default-arguments '("-w") + :max-action-columns 1 + :default-action 'magit-blame-addition) + +;;; Utilities + +(defun magit-blame-maybe-update-revision-buffer () + (unless magit--update-revision-buffer + (setq magit--update-revision-buffer nil) + (when-let ((chunk (magit-current-blame-chunk)) + (commit (oref chunk orig-rev)) + (buffer (magit-mode-get-buffer 'magit-revision-mode nil t))) + (setq magit--update-revision-buffer (list commit buffer)) + (run-with-idle-timer + magit-update-other-window-delay nil + (lambda () + (pcase-let ((`(,rev ,buf) magit--update-revision-buffer)) + (setq magit--update-revision-buffer nil) + (when (buffer-live-p buf) + (let ((magit-display-buffer-noselect t)) + (apply #'magit-show-commit rev (magit-diff-arguments)))))))))) + +;;; _ +(provide 'magit-blame) +;;; magit-blame.el ends here diff --git a/elpa/magit-20181113.1837/magit-bookmark.el b/elpa/magit-20181113.1837/magit-bookmark.el new file mode 100644 index 00000000..047132da --- /dev/null +++ b/elpa/magit-20181113.1837/magit-bookmark.el @@ -0,0 +1,371 @@ +;;; magit-bookmark.el --- bookmark support for Magit -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Yuri Khan +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; Support for bookmarks for most Magit buffers. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) +(require 'bookmark) + +;;; Supporting primitives + +(defun magit-bookmark--jump (bookmark fn &rest args) + "Handle a Magit BOOKMARK. + +This function will: + +1. Bind `default-directory' to the repository root directory + stored in the `filename' bookmark property. +2. Invoke the function FN with ARGS as arguments. This needs to + restore the buffer. +3. Restore the expanded/collapsed status of top level sections + and the point position." + (declare (indent 2)) + (let* ((default-directory (bookmark-get-filename bookmark))) + (if default-directory + (apply fn args) + (signal 'bookmark-error-no-filename (list 'stringp default-directory))) + (when (derived-mode-p 'magit-mode) + (when-let ((hidden-sections (bookmark-prop-get bookmark + 'magit-hidden-sections))) + (dolist (child (oref magit-root-section children)) + (if (member (cons (oref child type) + (oref child value)) + hidden-sections) + (magit-section-hide child) + (magit-section-show child))))) + (--when-let (bookmark-get-position bookmark) + (goto-char it)) + (--when-let (bookmark-get-front-context-string bookmark) + (when (search-forward it (point-max) t) + (goto-char (match-beginning 0)))) + (--when-let (bookmark-get-rear-context-string bookmark) + (when (search-backward it (point-min) t) + (goto-char (match-end 0)))) + nil)) + +(defun magit-bookmark--make-record (mode handler &optional make-props) + "Create a Magit bookmark. + +MODE specifies the expected major mode of current buffer. + +HANDLER should be a function that will be used to restore this +buffer. + +MAKE-PROPS should be either nil or a function that will be called +with `magit-refresh-args' as the argument list, and may return an +alist whose every element has the form (PROP . VALUE) and +specifies additional properties to store in the bookmark." + (declare (indent 1)) + (unless (eq major-mode mode) + (user-error "Not in a %s buffer" mode)) + (let ((bookmark (bookmark-make-record-default 'no-file))) + (bookmark-prop-set bookmark 'handler handler) + (bookmark-set-filename bookmark (magit-toplevel)) + (when (derived-mode-p 'magit-mode) + (bookmark-prop-set + bookmark 'magit-hidden-sections + (--map (cons (oref it type) + (oref it value)) + (--filter (oref it hidden) + (oref magit-root-section children))))) + (when make-props + (pcase-dolist (`(,prop . ,value) (apply make-props magit-refresh-args)) + (bookmark-prop-set bookmark prop value))) + bookmark)) + +;;; Status + +;;;###autoload +(defun magit-bookmark--status-jump (bookmark) + "Handle a Magit status BOOKMARK." + (magit-bookmark--jump bookmark + (lambda () (magit-status-internal default-directory)))) + +;;;###autoload +(defun magit-bookmark--status-make-record () + "Create a Magit status bookmark." + (magit-bookmark--make-record 'magit-status-mode + #'magit-bookmark--status-jump)) + +;;; Refs + +;;;###autoload +(defun magit-bookmark--refs-jump (bookmark) + "Handle a Magit refs BOOKMARK." + (magit-bookmark--jump bookmark #'magit-show-refs + (bookmark-prop-get bookmark 'magit-refs) + (bookmark-prop-get bookmark 'magit-args))) + +;;;###autoload +(defun magit-bookmark--refs-make-record () + "Create a Magit refs bookmark." + (magit-bookmark--make-record 'magit-refs-mode + #'magit-bookmark--refs-jump + (lambda (refs args) + `((magit-refs . ,refs) + (magit-args . ,args))))) + +;;; Log + +;;;###autoload +(defun magit-bookmark--log-jump (bookmark) + "Handle a Magit log BOOKMARK." + (magit-bookmark--jump bookmark #'magit-log-other + (bookmark-prop-get bookmark 'magit-revs) + (bookmark-prop-get bookmark 'magit-args) + (bookmark-prop-get bookmark 'magit-files))) + +(defun magit-bookmark--log-make-name (buffer-name revs _args files) + "Generate the default name for a log bookmark." + (concat + buffer-name " " (mapconcat #'identity revs " ") + (and files + (concat " touching " (mapconcat #'identity files " "))))) + +;;;###autoload +(defun magit-bookmark--log-make-record () + "Create a Magit log bookmark." + (magit-bookmark--make-record 'magit-log-mode + #'magit-bookmark--log-jump + (lambda (revs args files) + `((defaults . (,(magit-bookmark--log-make-name + (buffer-name) revs args files))) + (magit-revs . ,revs) + (magit-args . ,args) + (magit-files . ,files))))) + +;;; Reflog + +;;;###autoload +(defun magit-bookmark--reflog-jump (bookmark) + "Handle a Magit reflog BOOKMARK." + (magit-bookmark--jump bookmark + (lambda () + (let ((magit-reflog-arguments (bookmark-prop-get bookmark 'magit-args))) + (magit-git-reflog (bookmark-prop-get bookmark 'magit-ref) + magit-reflog-arguments))))) + +(defun magit-bookmark--reflog-make-name (buffer-name ref) + "Generate the default name for a reflog bookmark." + (concat buffer-name " " ref)) + +;;;###autoload +(defun magit-bookmark--reflog-make-record () + "Create a Magit reflog bookmark." + (magit-bookmark--make-record 'magit-reflog-mode + #'magit-bookmark--reflog-jump + (lambda (ref args) + `((defaults . (,(magit-bookmark--reflog-make-name (buffer-name) ref))) + (magit-ref . ,ref) + (magit-args . ,args))))) + +;;; Stashes + +;;;###autoload +(defun magit-bookmark--stashes-jump (bookmark) + "Handle a Magit stash list BOOKMARK." + (magit-bookmark--jump bookmark #'magit-stash-list)) + +;;;###autoload +(defun magit-bookmark--stashes-make-record () + "Create a Magit stash list bookmark." + (magit-bookmark--make-record 'magit-stashes-mode + #'magit-bookmark--stashes-jump)) + +;;; Cherry + +;;;###autoload +(defun magit-bookmark--cherry-jump (bookmark) + "Handle a Magit cherry BOOKMARK." + (magit-bookmark--jump bookmark #'magit-cherry + (bookmark-prop-get bookmark 'magit-head) + (bookmark-prop-get bookmark 'magit-upstream))) + +(defun magit-bookmark--cherry-make-name (buffer-name head upstream) + "Generate the default name for a cherry bookmark." + (concat buffer-name " " head " upstream " upstream)) + +;;;###autoload +(defun magit-bookmark--cherry-make-record () + "Create a Magit cherry bookmark." + (magit-bookmark--make-record 'magit-cherry-mode + #'magit-bookmark--cherry-jump + (lambda (upstream head) + `((defaults . (,(magit-bookmark--cherry-make-name + (buffer-name) head upstream))) + (magit-head . ,head) + (magit-upstream . ,upstream))))) + +;;; Diff + +;;;###autoload +(defun magit-bookmark--diff-jump (bookmark) + "Handle a Magit diff BOOKMARK." + (magit-bookmark--jump bookmark #'magit-diff-setup + (bookmark-prop-get bookmark 'magit-rev-or-range) + (bookmark-prop-get bookmark 'magit-const) + (bookmark-prop-get bookmark 'magit-args) + (bookmark-prop-get bookmark 'magit-files))) + +(defun magit-bookmark--resolve (rev-or-range) + "Return REV-OR-RANGE with ref names resolved to commit hashes." + (pcase (magit-git-lines "rev-parse" rev-or-range) + (`(,rev) + (magit-rev-abbrev rev)) + ((and `(,rev1 ,rev2) + (guard (/= ?^ (aref rev1 0))) + (guard (= ?^ (aref rev2 0)))) + (concat (magit-rev-abbrev (substring rev2 1)) + ".." + (magit-rev-abbrev rev1))) + ((and `(,rev1 ,rev2 ,rev3) + (guard (/= ?^ (aref rev1 0))) + (guard (/= ?^ (aref rev2 0))) + (guard (= ?^ (aref rev3 0)))) + (ignore rev3) + (concat (magit-rev-abbrev rev1) + "..." + (magit-rev-abbrev rev2))) + (_ + rev-or-range))) + +(defun magit-bookmark--diff-make-name + (buffer-name rev-or-range const _args files) + "Generate a default name for a diff bookmark." + (if (member "--no-index" const) + (apply #'format "*magit-diff %s %s" files) + (concat buffer-name " " + (cond (rev-or-range) + ((member "--cached" const) "staged") + (t "unstaged")) + (when files + (concat " in " (mapconcat #'identity files ", ")))))) + +;;;###autoload +(defun magit-bookmark--diff-make-record () + "Create a Magit diff bookmark." + (magit-bookmark--make-record 'magit-diff-mode + #'magit-bookmark--diff-jump + (lambda (rev-or-range const args files) + (let ((resolved (magit-bookmark--resolve rev-or-range))) + `((defaults . (,(magit-bookmark--diff-make-name + (buffer-name) resolved const args files))) + (magit-rev-or-range . ,resolved) + (magit-const . ,const) + (magit-args . ,args) + (magit-files . ,files)))))) + +;;; Revision + +;;;###autoload +(defun magit-bookmark--revision-jump (bookmark) + "Handle a Magit revision BOOKMARK." + (magit-bookmark--jump bookmark #'magit-show-commit + (bookmark-prop-get bookmark 'magit-rev) + (bookmark-prop-get bookmark 'args) + (bookmark-prop-get bookmark 'files))) + +(defun magit-bookmark--revision-make-name (buffer-name rev _args files) + "Generate a default name for a revision bookmark." + (let ((subject (magit-rev-format "%s" rev))) + (concat buffer-name " " + (magit-rev-abbrev rev) + (cond (files (concat " " (mapconcat #'identity files " "))) + (subject (concat " " subject)))))) + +;;;###autoload +(defun magit-bookmark--revision-make-record () + "Create a Magit revision bookmark." + ;; magit-refresh-args stores the revision in relative form. + ;; For bookmarks, the exact hash is more appropriate. + (magit-bookmark--make-record 'magit-revision-mode + #'magit-bookmark--revision-jump + (lambda (_rev _ args files) + `((defaults . (,(magit-bookmark--revision-make-name + (buffer-name) magit-buffer-revision-hash + args files))) + (magit-rev . ,magit-buffer-revision-hash) + (magit-args . ,args) + (magit-files . ,files))))) + +;;; Stash + +;;;###autoload +(defun magit-bookmark--stash-jump (bookmark) + "Handle a Magit stash BOOKMARK." + (magit-bookmark--jump bookmark #'magit-stash-show + (bookmark-prop-get bookmark 'magit-stash) + (bookmark-prop-get bookmark 'magit-args) + (bookmark-prop-get bookmark 'magit-files))) + +(defun magit-bookmark--stash-make-name (buffer-name stash _args files) + "Generate the default name for a stash bookmark." + (concat buffer-name " " stash " " + (if files + (mapconcat #'identity files " ") + (magit-rev-format "%s" stash)))) + +;;;###autoload +(defun magit-bookmark--stash-make-record () + "Create a Magit stash bookmark." + (magit-bookmark--make-record 'magit-stash-mode + #'magit-bookmark--stash-jump + (lambda (stash _ args files) + `((defaults . (,(magit-bookmark--stash-make-name + (buffer-name) + (magit-rev-abbrev magit-buffer-revision-hash) + args files))) + (magit-stash . ,magit-buffer-revision-hash) + (magit-args . ,args) + (magit-files . ,files) + (magit-hidden-sections + . ,(--map `(,(oref it type) + . ,(replace-regexp-in-string (regexp-quote stash) + magit-buffer-revision-hash + (oref it value))) + (--filter (oref it hidden) + (oref magit-root-section children)))))))) + +;;; Submodules + +;;;###autoload +(defun magit-bookmark--submodules-jump (bookmark) + "Handle a Magit submodule list BOOKMARK." + (magit-bookmark--jump bookmark #'magit-list-submodules)) + +;;;###autoload +(defun magit-bookmark--submodules-make-record () + "Create a Magit submodule list bookmark." + (magit-bookmark--make-record 'magit-submodule-list-mode + #'magit-bookmark--submodules-jump)) + +;;; _ +(provide 'magit-bookmark) +;;; magit-bookmark.el ends here diff --git a/elpa/magit-20181113.1837/magit-branch.el b/elpa/magit-20181113.1837/magit-branch.el new file mode 100644 index 00000000..7adea0d0 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-branch.el @@ -0,0 +1,1091 @@ +;;; magit-branch.el --- branch support -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements support for branches. It defines popups +;; and commands for creating, checking out, manipulating, and +;; configuring branches. Commands defined here are mainly concerned +;; with branches as pointers, commands that deal with what a branch +;; points at, are defined elsewhere. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) +(require 'magit-collab) +(require 'magit-reset) + +;;; Options + +(defcustom magit-branch-read-upstream-first t + "Whether to read upstream before name of new branch when creating a branch. + +`nil' Read the branch name first. +`t' Read the upstream first. +`fallback' Read the upstream first, but if it turns out that the chosen + value is not a valid upstream (because it cannot be resolved + as an existing revision), then treat it as the name of the + new branch and continue by reading the upstream next." + :package-version '(magit . "2.2.0") + :group 'magit-commands + :type '(choice (const :tag "read branch name first" nil) + (const :tag "read upstream first" t) + (const :tag "read upstream first, with fallback" fallback))) + +(defcustom magit-branch-prefer-remote-upstream nil + "Whether to favor remote upstreams when creating new branches. + +When a new branch is created, then the branch, commit, or stash +at point is suggested as the default starting point of the new +branch, or if there is no such revision at point the current +branch. In either case the user may choose another starting +point. + +If the chosen starting point is a branch, then it may also be set +as the upstream of the new branch, depending on the value of the +Git variable `branch.autoSetupMerge'. By default this is done +for remote branches, but not for local branches. + +You might prefer to always use some remote branch as upstream. +If the chosen starting point is (1) a local branch, (2) whose +name matches a member of the value of this option, (3) the +upstream of that local branch is a remote branch with the same +name, and (4) that remote branch can be fast-forwarded to the +local branch, then the chosen branch is used as starting point, +but its own upstream is used as the upstream of the new branch. + +Members of this option's value are treated as branch names that +have to match exactly unless they contain a character that makes +them invalid as a branch name. Recommended characters to use +to trigger interpretation as a regexp are \"*\" and \"^\". Some +other characters which you might expect to be invalid, actually +are not, e.g. \".+$\" are all perfectly valid. More precisely, +if `git check-ref-format --branch STRING' exits with a non-zero +status, then treat STRING as a regexp. + +Assuming the chosen branch matches these conditions you would end +up with with e.g.: + + feature --upstream--> origin/master + +instead of + + feature --upstream--> master --upstream--> origin/master + +Which you prefer is a matter of personal preference. If you do +prefer the former, then you should add branches such as \"master\", +\"next\", and \"maint\" to the value of this options." + :package-version '(magit . "2.4.0") + :group 'magit-commands + :type '(repeat string)) + +(defcustom magit-branch-adjust-remote-upstream-alist nil + "Alist of upstreams to be used when branching from remote branches. + +When creating a local branch from an ephemeral branch located +on a remote, e.g. a feature or hotfix branch, then that remote +branch should usually not be used as the upstream branch, since +the push-remote already allows accessing it and having both the +upstream and the push-remote reference the same related branch +would be wasteful. Instead a branch like \"maint\" or \"master\" +should be used as the upstream. + +This option allows specifing the branch that should be used as +the upstream when branching certain remote branches. The value +is an alist of the form ((UPSTREAM . RULE)...). The first +matching element is used, the following elements are ignored. + +UPSTREAM is the branch to be used as the upstream for branches +specified by RULE. It can be a local or a remote branch. + +RULE can either be a regular expression, matching branches whose +upstream should be the one specified by UPSTREAM. Or it can be +a list of the only branches that should *not* use UPSTREAM; all +other branches will. Matching is done after stripping the remote +part of the name of the branch that is being branched from. + +If you use a finite set of non-ephemeral branches across all your +repositories, then you might use something like: + + ((\"origin/master\" \"master\" \"next\" \"maint\")) + +Or if the names of all your ephemeral branches contain a slash, +at least in some repositories, then a good value could be: + + ((\"origin/master\" . \"/\")) + +Of course you can also fine-tune: + + ((\"origin/maint\" . \"\\\\\\=`hotfix/\") + (\"origin/master\" . \"\\\\\\=`feature/\")) + +If you use remote branches as UPSTREAM, then you might also want +to set `magit-branch-prefer-remote-upstream' to a non-nil value. +However, I recommend that you use local branches as UPSTREAM." + :package-version '(magit . "2.9.0") + :group 'magit-commands + :type '(repeat (cons (string :tag "Use upstream") + (choice :tag "for branches" + (regexp :tag "matching") + (repeat :tag "except" + (string :tag "branch")))))) + +(defcustom magit-branch-rename-push-target t + "Whether the push-remote setup is preserved when renaming a branch. + +The command `magit-branch-rename' renames a branch named OLD to +NEW. This option controls how much of the push-remote setup is +preserved when doing so. + +When nil, then preserve nothing and unset `branch.OLD.pushRemote'. + +When `local-only', then first set `branch.NEW.pushRemote' to the + same value as `branch.OLD.pushRemote', provided the latter is + actually set and unless the former already has another value. + +When t, then rename the branch named OLD on the remote specified + by `branch.OLD.pushRemote' to NEW, provided OLD exists on that + remote and unless NEW already exists on the remote. + +When `forge-only' and the `forge' package is available, then + behave like `t' if the remote points to a repository on a forge + (currently Github or Gitlab), otherwise like `local-only'. + +Another supported but obsolete value is `github-only'. It is a + misnomer because it now treated as an alias for `forge-only'." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type '(choice + (const :tag "Don't preserve push-remote setup" nil) + (const :tag "Preserve push-remote setup" local-only) + (const :tag "... and rename corresponding branch on remote" t) + (const :tag "... but only if remote is on a forge" forge-only))) + +(defcustom magit-branch-popup-show-variables t + "Whether the `magit-branch-popup' shows Git variables. +This defaults to t to avoid changing key bindings. When set to +nil, no variables are displayed directly in this popup, instead +the sub-popup `magit-branch-config-popup' has to be used to view +and change branch related variables." + :package-version '(magit . "2.7.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-published-branches '("origin/master") + "List of branches that are considered to be published." + :package-version '(magit . "2.13.0") + :group 'magit-commands + :type '(repeat string)) + +;;; Branch Popup + +(defvar magit-branch-config-variables) + +;;;###autoload (autoload 'magit-branch-popup "magit" nil t) +(magit-define-popup magit-branch-popup + "Popup console for branch commands." + :man-page "git-branch" + :variables (lambda () + (and magit-branch-popup-show-variables + magit-branch-config-variables)) + :actions `((?b "Checkout" magit-checkout) nil + (?C "Configure..." magit-branch-config-popup) + (?l "Checkout local branch" magit-branch-checkout) + (?s "Create new spin-off" magit-branch-spinoff) + (?m "Rename" magit-branch-rename) + (?c "Checkout new branch" magit-branch-and-checkout) + (?n "Create new branch" magit-branch-create) + (?x "Reset" magit-branch-reset) + (?w "Checkout new worktree" magit-worktree-checkout) + (?W "Create new worktree" magit-worktree-branch) + (?k "Delete" magit-branch-delete) + ,@(and (not (require (quote forge) nil t)) + '((?y "Checkout pull-request" magit-checkout-pull-request) + (?Y "Create from pull-request" magit-branch-pull-request)))) + :default-action 'magit-checkout + :max-action-columns 3 + :setup-function 'magit-branch-popup-setup) + +(defun magit-branch-popup-setup (val def) + (magit-popup-default-setup val def) + (use-local-map (copy-keymap magit-popup-mode-map)) + (dolist (ev (-filter #'magit-popup-event-p (magit-popup-get :variables))) + (local-set-key (vector (magit-popup-event-key ev)) + 'magit-invoke-popup-action))) + +;;; Branch Commands + +;;;###autoload +(defun magit-checkout (revision) + "Checkout REVISION, updating the index and the working tree. +If REVISION is a local branch, then that becomes the current +branch. If it is something else, then `HEAD' becomes detached. +Checkout fails if the working tree or the staging area contain +changes. +\n(git checkout REVISION)." + (interactive (list (magit-read-other-branch-or-commit "Checkout"))) + (when (string-match "\\`heads/\\(.+\\)" revision) + (setq revision (match-string 1 revision))) + (magit-run-git "checkout" revision)) + +;;;###autoload +(defun magit-branch-create (branch start-point &optional args) + "Create BRANCH at branch or revision START-POINT. +\n(git branch [ARGS] BRANCH START-POINT)." + (interactive (magit-branch-read-args "Create branch")) + (magit-call-git "branch" args branch start-point) + (magit-branch-maybe-adjust-upstream branch start-point) + (magit-refresh)) + +;;;###autoload +(defun magit-branch-and-checkout (branch start-point &optional args) + "Create and checkout BRANCH at branch or revision START-POINT. +\n(git checkout [ARGS] -b BRANCH START-POINT)." + (interactive (magit-branch-read-args "Create and checkout branch")) + (if (string-match-p "^stash@{[0-9]+}$" start-point) + (magit-run-git "stash" "branch" branch start-point) + (magit-call-git "checkout" args "-b" branch start-point) + (magit-branch-maybe-adjust-upstream branch start-point) + (magit-refresh))) + +;;;###autoload +(defun magit-branch-or-checkout (arg &optional start-point) + "Hybrid between `magit-checkout' and `magit-branch-and-checkout'. + +Ask the user for an existing branch or revision. If the user +input actually can be resolved as a branch or revision, then +check that out, just like `magit-checkout' would. + +Otherwise create and checkout a new branch using the input as +its name. Before doing so read the starting-point for the new +branch. This is similar to what `magit-branch-and-checkout' +does." + (interactive + (let ((arg (magit-read-other-branch-or-commit "Checkout"))) + (list arg + (and (not (magit-rev-verify-commit arg)) + (magit-read-starting-point "Create and checkout branch" arg))))) + (when (string-match "\\`heads/\\(.+\\)" arg) + (setq arg (match-string 1 arg))) + (if start-point + (magit-branch-and-checkout arg start-point (magit-branch-arguments)) + (magit-checkout arg))) + +;;;###autoload +(defun magit-branch-checkout (branch &optional start-point) + "Checkout an existing or new local branch. + +Read a branch name from the user offering all local branches and +a subset of remote branches as candidates. Omit remote branches +for which a local branch by the same name exists from the list +of candidates. The user can also enter a completely new branch +name. + +- If the user selects an existing local branch, then check that + out. + +- If the user selects a remote branch, then create and checkout + a new local branch with the same name. Configure the selected + remote branch as push target. + +- If the user enters a new branch name, then create and check + that out, after also reading the starting-point from the user. + +In the latter two cases the upstream is also set. Whether it is +set to the chosen START-POINT or something else depends on the +value of `magit-branch-adjust-remote-upstream-alist', just like +when using `magit-branch-and-checkout'." + (interactive + (let* ((current (magit-get-current-branch)) + (local (magit-list-local-branch-names)) + (remote (--filter (and (string-match "[^/]+/" it) + (not (member (substring it (match-end 0)) + (cons "HEAD" local)))) + (magit-list-remote-branch-names))) + (choices (nconc (delete current local) remote)) + (atpoint (magit-branch-at-point)) + (choice (magit-completing-read + "Checkout branch" choices + nil nil nil 'magit-revision-history + (or (car (member atpoint choices)) + (and atpoint + (car (member (and (string-match "[^/]+/" atpoint) + (substring atpoint (match-end 0))) + choices))))))) + (cond ((member choice remote) + (list (and (string-match "[^/]+/" choice) + (substring choice (match-end 0))) + choice)) + ((member choice local) + (list choice)) + (t + (list choice (magit-read-starting-point "Create" choice)))))) + (if (not start-point) + (magit-checkout branch) + (when (magit-anything-modified-p) + (user-error "Cannot checkout when there are uncommitted changes")) + (magit-branch-and-checkout branch start-point (magit-branch-arguments)) + (when (magit-remote-branch-p start-point) + (pcase-let ((`(,remote . ,remote-branch) + (magit-split-branch-name start-point))) + (when (and (equal branch remote-branch) + (not (equal remote (magit-get "remote.pushDefault")))) + (magit-set remote "branch" branch "pushRemote")))))) + +(defun magit-branch-maybe-adjust-upstream (branch start-point) + (--when-let + (or (and (magit-get-upstream-branch branch) + (magit-get-indirect-upstream-branch start-point)) + (and (magit-remote-branch-p start-point) + (let ((name (cdr (magit-split-branch-name start-point)))) + (car (--first (if (listp (cdr it)) + (not (member name (cdr it))) + (string-match-p (cdr it) name)) + magit-branch-adjust-remote-upstream-alist))))) + (magit-call-git "branch" (concat "--set-upstream-to=" it) branch))) + +;;;###autoload +(defun magit-branch-orphan (branch start-point &optional args) + "Create and checkout an orphan BRANCH with contents from revision START-POINT. +\n(git checkout --orphan [ARGS] BRANCH START-POINT)." + (interactive (magit-branch-read-args "Create and checkout orphan branch")) + (magit-run-git "checkout" "--orphan" args branch start-point)) + +;;;###autoload +(defun magit-branch-pull-request (pr) + "Create and configure a new branch from a pull-request. +Please see the manual for more information." + (interactive (list (magit-read-pull-request "Branch pull request"))) + (let-alist pr + (let* ((upstream (or (--first (magit--github-url-equal + (magit-get "remote" it "url") + .base.repo.ssh_url) + (magit-list-remotes)) + (user-error + "Upstream repository %s not available as a remote" + .base.repo.ssh_url))) + (upstream-url (magit-get "remote" upstream "url")) + (remote .head.repo.owner.login) + (branch (magit--pullreq-branch pr t)) + (pr-branch .head.ref)) + (if (magit--pullreq-from-upstream-p pr) + (let ((tracking (concat upstream "/" pr-branch))) + (unless (magit-branch-p tracking) + (magit-call-git "fetch" upstream)) + (let ((inhibit-magit-refresh t)) + (magit-branch-create branch tracking)) + (magit-set upstream "branch" branch "pushRemote") + (magit-set upstream "branch" branch "pullRequestRemote")) + (if (magit-remote-p remote) + (let ((url (magit-get "remote" remote "url")) + (fetch (magit-get-all "remote" remote "fetch"))) + (unless (magit--github-url-equal url .head.repo.ssh_url) + (user-error + "Remote `%s' already exists but does not point to %s" + remote url)) + (unless (member (format "+refs/heads/*:refs/remotes/%s/*" remote) + fetch) + (magit-call-git "remote" "set-branches" + "--add" remote pr-branch) + (magit-call-git "fetch" remote))) + (magit-call-git + "remote" "add" "-f" "--no-tags" + "-t" pr-branch remote + (cond ((or (string-prefix-p "git@" upstream-url) + (string-prefix-p "ssh://git@" upstream-url)) + .head.repo.ssh_url) + ((string-prefix-p "https://" upstream-url) + .head.repo.clone_url) + ((string-prefix-p "git://" upstream-url) + .head.repo.git_url) + (t (error "%s has an unexpected format" upstream-url))))) + (magit-call-git "branch" branch (concat remote "/" pr-branch)) + (if (or .locked (not (equal branch pr-branch))) + (magit-set upstream "branch" branch "pushRemote") + (magit-set remote "branch" branch "pushRemote")) + (magit-set remote "branch" branch "pullRequestRemote")) + (magit-set "true" "branch" branch "rebase") + (magit-call-git "branch" branch + (concat "--set-upstream-to=" + (if magit-branch-prefer-remote-upstream + (concat upstream "/" .base.ref) + .base.ref))) + (magit-set (number-to-string .number) "branch" branch "pullRequest") + (magit-set .title "branch" branch "description") + (magit-refresh) + branch))) + +(defun magit-checkout-pull-request (pr) + "Create, configure and checkout a new branch from a pull-request. +Please see the manual for more information." + (interactive (list (magit-read-pull-request "Checkout pull request"))) + (magit-checkout + (let ((inhibit-magit-refresh t)) + (magit-branch-pull-request pr)))) + +(defun magit-branch-read-args (prompt) + (let ((args (magit-branch-arguments))) + (if magit-branch-read-upstream-first + (let ((choice (magit-read-starting-point prompt))) + (if (magit-rev-verify choice) + (list (magit-read-string-ns + (if magit-completing-read--silent-default + (format "%s (starting at `%s')" prompt choice) + "Name for new branch") + (let ((def (mapconcat #'identity + (cdr (split-string choice "/")) + "/"))) + (and (member choice (magit-list-remote-branch-names)) + (not (member def (magit-list-local-branch-names))) + def))) + choice args) + (if (eq magit-branch-read-upstream-first 'fallback) + (list choice (magit-read-starting-point prompt choice) args) + (user-error "Not a valid starting-point: %s" choice)))) + (let ((branch (magit-read-string-ns (concat prompt " named")))) + (list branch + (magit-read-starting-point prompt branch) + args))))) + +;;;###autoload +(defun magit-branch-spinoff (branch &optional from &rest args) + "Create new branch from the unpushed commits. + +Create and checkout a new branch starting at and tracking the +current branch. That branch in turn is reset to the last commit +it shares with its upstream. If the current branch has no +upstream or no unpushed commits, then the new branch is created +anyway and the previously current branch is not touched. + +This is useful to create a feature branch after work has already +began on the old branch (likely but not necessarily \"master\"). + +If the current branch is a member of the value of option +`magit-branch-prefer-remote-upstream' (which see), then the +current branch will be used as the starting point as usual, but +the upstream of the starting-point may be used as the upstream +of the new branch, instead of the starting-point itself. + +If optional FROM is non-nil, then the source branch is reset +to `FROM~', instead of to the last commit it shares with its +upstream. Interactively, FROM is only ever non-nil, if the +region selects some commits, and among those commits, FROM is +the commit that is the fewest commits ahead of the source +branch. + +The commit at the other end of the selection actually does not +matter, all commits between FROM and `HEAD' are moved to the new +branch. If FROM is not reachable from `HEAD' or is reachable +from the source branch's upstream, then an error is raised." + (interactive (list (magit-read-string-ns "Spin off branch") + (car (last (magit-region-values 'commit))) + (magit-branch-arguments))) + (when (magit-branch-p branch) + (user-error "Cannot spin off %s. It already exists" branch)) + (if-let ((current (magit-get-current-branch))) + (let ((tracked (magit-get-upstream-branch current)) + base) + (when from + (unless (magit-rev-ancestor-p from current) + (user-error "Cannot spin off %s. %s is not reachable from %s" + branch from current)) + (when (and tracked + (magit-rev-ancestor-p from tracked)) + (user-error "Cannot spin off %s. %s is ancestor of upstream %s" + branch from tracked))) + (let ((magit-process-raise-error t)) + (magit-call-git "checkout" args "-b" branch current)) + (--when-let (magit-get-indirect-upstream-branch current) + (magit-call-git "branch" "--set-upstream-to" it branch)) + (when (and tracked + (setq base + (if from + (concat from "^") + (magit-git-string "merge-base" current tracked))) + (not (magit-rev-eq base current))) + (magit-call-git "update-ref" "-m" + (format "reset: moving to %s" base) + (concat "refs/heads/" current) base)) + (magit-refresh)) + (magit-run-git "checkout" "-b" branch))) + +;;;###autoload +(defun magit-branch-reset (branch to &optional args set-upstream) + "Reset a branch to the tip of another branch or any other commit. + +When the branch being reset is the current branch, then do a +hard reset. If there are any uncommitted changes, then the user +has to confirm the reset because those changes would be lost. + +This is useful when you have started work on a feature branch but +realize it's all crap and want to start over. + +When resetting to another branch and a prefix argument is used, +then also set the target branch as the upstream of the branch +that is being reset." + (interactive + (let* ((atpoint (magit-local-branch-at-point)) + (branch (magit-read-local-branch "Reset branch" atpoint))) + (list branch + (magit-completing-read (format "Reset %s to" branch) + (delete branch (magit-list-branch-names)) + nil nil nil 'magit-revision-history + (or (and (not (equal branch atpoint)) atpoint) + (magit-get-upstream-branch branch))) + (magit-branch-arguments) + current-prefix-arg))) + (unless (member "--force" args) + (setq args (cons "--force" args))) + (if (equal branch (magit-get-current-branch)) + (if (and (magit-anything-modified-p) + (not (yes-or-no-p "Uncommitted changes will be lost. Proceed? "))) + (user-error "Abort") + (magit-reset-hard to) + (when (and set-upstream (magit-branch-p to)) + (magit-set-upstream-branch branch to))) + (magit-branch-create branch to args))) + +;;;###autoload +(defun magit-branch-delete (branches &optional force) + "Delete one or multiple branches. +If the region marks multiple branches, then offer to delete +those, otherwise prompt for a single branch to be deleted, +defaulting to the branch at point." + ;; One would expect this to be a command as simple as, for example, + ;; `magit-branch-rename'; but it turns out everyone wants to squeeze + ;; a bit of extra functionality into this one, including myself. + (interactive + (let ((branches (magit-region-values 'branch t)) + (force current-prefix-arg)) + (if (> (length branches) 1) + (magit-confirm t nil "Delete %i branches" nil branches) + (setq branches + (list (magit-read-branch-prefer-other + (if force "Force delete branch" "Delete branch"))))) + (unless force + (when-let ((unmerged (-remove #'magit-branch-merged-p branches))) + (if (magit-confirm 'delete-unmerged-branch + "Delete unmerged branch %s" + "Delete %i unmerged branches" + 'noabort unmerged) + (setq force branches) + (or (setq branches (-difference branches unmerged)) + (user-error "Abort"))))) + (list branches force))) + (let* ((refs (mapcar #'magit-ref-fullname branches)) + (ambiguous (--remove it refs))) + (when ambiguous + (user-error + "%s ambiguous. Please cleanup using git directly." + (let ((len (length ambiguous))) + (cond + ((= len 1) + (format "%s is" (-first #'magit-ref-ambiguous-p branches))) + ((= len (length refs)) + (format "These %s names are" len)) + (t + (format "%s of these names are" len)))))) + (cond + ((string-match "^refs/remotes/\\([^/]+\\)" (car refs)) + (let* ((remote (match-string 1 (car refs))) + (offset (1+ (length remote)))) + ;; Assume the branches actually still exists on the remote. + (magit-run-git-async + "push" remote (--map (concat ":" (substring it offset)) branches)) + ;; If that is not the case, then this deletes the tracking branches. + (set-process-sentinel + magit-this-process + (apply-partially 'magit-delete-remote-branch-sentinel refs)))) + ((> (length branches) 1) + (setq branches (delete (magit-get-current-branch) branches)) + (mapc 'magit-branch-maybe-delete-pr-remote branches) + (mapc 'magit-branch-unset-pushRemote branches) + (magit-run-git "branch" (if force "-D" "-d") branches)) + (t ; And now for something completely different. + (let* ((branch (car branches)) + (prompt (format "Branch %s is checked out. " branch))) + (when (equal branch (magit-get-current-branch)) + (pcase (if (or (equal branch "master") + (not (magit-rev-verify "master"))) + (magit-read-char-case prompt nil + (?d "[d]etach HEAD & delete" 'detach) + (?a "[a]bort" 'abort)) + (magit-read-char-case prompt nil + (?d "[d]etach HEAD & delete" 'detach) + (?c "[c]heckout master & delete" 'master) + (?a "[a]bort" 'abort))) + (`detach (unless (or (equal force '(4)) + (member branch force) + (magit-branch-merged-p branch t)) + (magit-confirm 'delete-unmerged-branch + "Delete unmerged branch %s" "" + nil (list branch))) + (magit-call-git "checkout" "--detach")) + (`master (unless (or (equal force '(4)) + (member branch force) + (magit-branch-merged-p branch "master")) + (magit-confirm 'delete-unmerged-branch + "Delete unmerged branch %s" "" + nil (list branch))) + (magit-call-git "checkout" "master")) + (`abort (user-error "Abort"))) + (setq force t)) + (magit-branch-maybe-delete-pr-remote branch) + (magit-branch-unset-pushRemote branch) + (magit-run-git "branch" (if force "-D" "-d") branch)))))) + +(put 'magit-branch-delete 'interactive-only t) + +(defun magit-branch-maybe-delete-pr-remote (branch) + (when-let ((remote (magit-get "branch" branch "pullRequestRemote"))) + (let* ((variable (format "remote.%s.fetch" remote)) + (refspecs (magit-get-all variable))) + (unless (member (format "+refs/heads/*:refs/remotes/%s/*" remote) + refspecs) + (let ((refspec + (if (equal (magit-get "branch" branch "pushRemote") remote) + (format "+refs/heads/%s:refs/remotes/%s/%s" + branch remote branch) + (let ((merge (magit-get "branch" branch "merge"))) + (and merge + (string-prefix-p "refs/heads/" merge) + (setq merge (substring merge 11)) + (format "+refs/heads/%s:refs/remotes/%s/%s" + merge remote merge)))))) + (when (member refspec refspecs) + (if (and (= (length refspecs) 1) + (magit-confirm 'delete-pr-remote + (format "Also delete remote %s (%s)" remote + "no pull-request branch remains"))) + (magit-call-git "remote" "rm" remote) + (magit-call-git "config" "--unset" variable + (regexp-quote refspec))))))))) + +(defun magit-branch-unset-pushRemote (branch) + (magit-set nil "branch" branch "pushRemote")) + +(defun magit-delete-remote-branch-sentinel (refs process event) + (when (memq (process-status process) '(exit signal)) + (if (= (process-exit-status process) 0) + (magit-process-sentinel process event) + (if-let ((rest (-filter #'magit-ref-exists-p refs))) + (progn + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (setq magit-this-error nil) + (message "Some remote branches no longer exist. %s" + "Deleting just the local tracking refs instead...") + (dolist (ref rest) + (magit-call-git "update-ref" "-d" ref)) + (magit-refresh) + (message "Deleting local remote-tracking refs...done")) + (magit-process-sentinel process event))))) + +;;;###autoload +(defun magit-branch-rename (old new &optional force) + "Rename the branch named OLD to NEW. + +With a prefix argument FORCE, rename even if a branch named NEW +already exists. + +If `branch.OLD.pushRemote' is set, then unset it. Depending on +the value of `magit-branch-rename-push-target' (which see) maybe +set `branch.NEW.pushRemote' and maybe rename the push-target on +the remote." + (interactive + (let ((branch (magit-read-local-branch "Rename branch"))) + (list branch + (magit-read-string-ns (format "Rename branch '%s' to" branch) + nil 'magit-revision-history) + current-prefix-arg))) + (when (string-match "\\`heads/\\(.+\\)" old) + (setq old (match-string 1 old))) + (when (equal old new) + (user-error "Old and new branch names are the same")) + (magit-call-git "branch" (if force "-M" "-m") old new) + (when magit-branch-rename-push-target + (let ((remote (magit-get-push-remote old)) + (old-specific (magit-get "branch" old "pushRemote")) + (new-specific (magit-get "branch" new "pushRemote"))) + (when (and old-specific (or force (not new-specific))) + ;; Keep the target setting branch specific, even if that is + ;; redundant. But if a branch by the same name existed before + ;; and the rename isn't forced, then do not change a leftover + ;; setting. Such a leftover setting may or may not conform to + ;; what we expect here... + (magit-set old-specific "branch" new "pushRemote")) + (when (and (equal (magit-get-push-remote new) remote) + ;; ...and if it does not, then we must abort. + (not (eq magit-branch-rename-push-target 'local-only)) + (or (not (memq magit-branch-rename-push-target + '(forge-only github-only))) + (and (require (quote forge) nil t) + (fboundp 'forge--forge-remote-p) + (forge--forge-remote-p remote)))) + (let ((old-target (magit-get-push-branch old t)) + (new-target (magit-get-push-branch new t)) + (remote (magit-get-push-remote new))) + (when (and old-target + (not new-target) + (magit-y-or-n-p (format "Also rename %S to %S on %S" + old new remote))) + ;; Rename on (i.e. within) the remote, but only if the + ;; destination ref doesn't exist yet. If that ref already + ;; exists, then it probably is of some value and we better + ;; not touch it. Ignore what the local ref points at, + ;; i.e. if the local and the remote ref didn't point at + ;; the same commit before the rename then keep it that way. + (magit-call-git "push" "-v" remote + (format "%s:refs/heads/%s" old-target new) + (format ":refs/heads/%s" old))))))) + (magit-branch-unset-pushRemote old) + (magit-refresh)) + +;;;###autoload +(defun magit-branch-shelve (branch) + "Shelve a BRANCH. +Rename \"refs/heads/BRANCH\" to \"refs/shelved/BRANCH\", +and also rename the respective reflog file." + (interactive (list (magit-read-other-local-branch "Shelve branch"))) + (let ((old (concat "refs/heads/" branch)) + (new (concat "refs/shelved/" branch))) + (magit-git "update-ref" new old "") + (magit--rename-reflog-file old new) + (magit-branch-unset-pushRemote branch) + (magit-run-git "branch" "-D" branch))) + +;;;###autoload +(defun magit-branch-unshelve (branch) + "Unshelve a BRANCH +Rename \"refs/shelved/BRANCH\" to \"refs/heads/BRANCH\", +and also rename the respective reflog file." + (interactive + (list (magit-completing-read + "Unshelve branch" + (--map (substring it 8) + (magit-list-refnames "refs/shelved")) + nil t))) + (let ((old (concat "refs/shelved/" branch)) + (new (concat "refs/heads/" branch))) + (magit-git "update-ref" new old "") + (magit--rename-reflog-file old new) + (magit-run-git "update-ref" "-d" old))) + +(defun magit--rename-reflog-file (old new) + (let ((old (magit-git-dir (concat "logs/" old))) + (new (magit-git-dir (concat "logs/" new)))) + (when (file-exists-p old) + (make-directory (file-name-directory new) t) + (rename-file old new t)))) + +;;; Config Popup + +(defvar magit-branch-config-branch nil) + +;;;###autoload +(defun magit-branch-config-popup (branch) + "Popup console for setting branch variables." + (interactive + (list (if (or current-prefix-arg + (and (eq magit-current-popup 'magit-branch-popup) + magit-branch-popup-show-variables)) + (magit-read-local-branch "Configure branch") + (magit-get-current-branch)))) + (let ((magit-branch-config-branch branch)) + (magit-invoke-popup 'magit-branch-config-popup nil nil))) + +(defvar magit-branch-config-variables + '((lambda () + (concat + (propertize "Configure " 'face 'magit-popup-heading) + (propertize (magit-branch-config-branch) 'face 'magit-branch-local))) + (?d "branch.%s.description" + magit-edit-branch*description + magit-format-branch*description) + (?u "branch.%s.merge" + magit-set-branch*merge/remote + magit-format-branch*merge/remote) + (?r "branch.%s.rebase" + magit-cycle-branch*rebase + magit-format-branch*rebase) + (?p "branch.%s.pushRemote" + magit-cycle-branch*pushRemote + magit-format-branch*pushRemote) + "Configure repository defaults" + (?\M-r "pull.rebase" + magit-cycle-pull.rebase + magit-format-pull.rebase) + (?\M-p "remote.pushDefault" + magit-cycle-remote.pushDefault + magit-format-remote.pushDefault) + "Configure branch creation" + (?U "branch.autoSetupMerge" + magit-cycle-branch*autoSetupMerge + magit-format-branch*autoSetupMerge) + (?R "branch.autoSetupRebase" + magit-cycle-branch*autoSetupRebase + magit-format-branch*autoSetupRebase))) + +(defvar magit-branch-config-popup + `(:man-page "git-branch" + :variables ,magit-branch-config-variables + :setup-function magit-branch-config-popup-setup)) + +(defun magit-branch-config-popup-setup (val def) + (magit-popup-default-setup val def) + (setq-local magit-branch-config-branch magit-branch-config-branch) + (use-local-map (copy-keymap magit-popup-mode-map)) + (dolist (ev (-filter #'magit-popup-event-p (magit-popup-get :variables))) + (local-set-key (vector (magit-popup-event-key ev)) + 'magit-invoke-popup-action))) + +(defun magit-branch-config-branch (&optional prompt) + (if prompt + (or (and (not current-prefix-arg) + (or magit-branch-config-branch + (magit-get-current-branch))) + (magit-read-local-branch prompt)) + (or magit-branch-config-branch + (magit-get-current-branch) + ""))) + +;;; Config Commands and Inserters + +;;;###autoload +(defun magit-edit-branch*description (branch) + "Edit the description of the current branch. +With a prefix argument edit the description of another branch. + +The description for the branch named NAME is stored in the Git +variable `branch..description'." + (interactive (list (magit-branch-config-branch "Edit branch description"))) + (magit-run-git-with-editor "branch" "--edit-description" branch)) + +(defun magit-edit-branch*description-check-buffers () + (and buffer-file-name + (string-match-p "/\\(BRANCH\\|EDIT\\)_DESCRIPTION\\'" buffer-file-name) + (add-hook 'with-editor-post-finish-hook + (lambda () + (when (derived-mode-p 'magit-popup-mode) + (magit-refresh-popup-buffer))) + nil t))) + +(add-hook 'find-file-hook 'magit-edit-branch*description-check-buffers) + +(defun magit-format-branch*description () + (let* ((branch (magit-branch-config-branch)) + (width (+ (length branch) 19)) + (var (format "branch.%s.description" branch))) + (concat var " " (make-string (- width (length var)) ?\s) + (if-let ((value (magit-get var))) + (propertize (car (split-string value "\n")) + 'face 'magit-popup-option-value) + (propertize "unset" 'face 'magit-popup-disabled-argument))))) + +;;;###autoload +(defun magit-set-branch*merge/remote (branch upstream) + "Set or unset the upstream of the current branch. +With a prefix argument do so for another branch. + +When the branch in question already has an upstream then simply +unsets it. Invoke this command again to set another upstream. + +Together the Git variables `branch..remote' and +`branch..merge' define the upstream branch of the local +branch named NAME. The value of `branch..remote' is the +name of the upstream remote. The value of `branch..merge' +is the full reference of the upstream branch, on the remote. + +Non-interactively, when UPSTREAM is non-nil, then always set it +as the new upstream, regardless of whether another upstream was +already set. When nil, then always unset." + (interactive + (let ((branch (magit-branch-config-branch "Change upstream of branch"))) + (list branch (and (not (magit-get-upstream-branch branch)) + (magit-read-upstream-branch branch))))) + (magit-set-upstream-branch branch upstream) + (magit-refresh)) + +(defun magit-format-branch*merge/remote () + (let* ((branch (magit-branch-config-branch)) + (width (+ (length branch) 20)) + (varM (format "branch.%s.merge" branch)) + (varR (format "branch.%s.remote" branch)) + (face (if (equal (magit-get varR) ".") + 'magit-branch-local + 'magit-branch-remote))) + (concat varM (make-string (- width (length varM)) ?\s) + (if-let ((value (magit-get varM))) + (propertize value 'face face) + (propertize "unset" 'face 'magit-popup-disabled-argument)) + "\n " varR (make-string (- width (length varR)) ?\s) + (if-let ((value (magit-get varR))) + (propertize value 'face face) + (propertize "unset" 'face 'magit-popup-disabled-argument))))) + +;;;###autoload +(defun magit-cycle-branch*rebase (branch) + "Cycle the value of `branch..rebase' for the current branch. +With a prefix argument cycle the value for another branch. + +The Git variables `branch..rebase' controls whether pulling +into the branch named NAME is done by rebasing that branch onto +the fetched branch or by merging that branch. + +When `true' then pulling is done by rebasing. +When `false' then pulling is done by merging. + +When that variable is undefined then the value of `pull.rebase' +is used instead. It defaults to `false'." + (interactive (list (magit-branch-config-branch + "Cycle branch..rebase for"))) + (magit--set-popup-variable (format "branch.%s.rebase" branch) + '("true" "false") + "false" "pull.rebase")) + +(defun magit-format-branch*rebase () + (let ((branch (magit-branch-config-branch))) + (magit--format-popup-variable:choices + (format "branch.%s.rebase" branch) + '("true" "false") + "false" "pull.rebase" + (+ (length branch) 20)))) + +;;;###autoload +(defun magit-cycle-branch*pushRemote (branch) + "Cycle the value of `branch..pushRemote' for the current branch. +With a prefix argument cycle the value for another branch. + +The Git variable `branch..pushRemote' specifies the remote +that the branch named NAME is usually pushed to. The value has +to be the name of an existing remote. + +If that variable is undefined, then the value of the Git variable +`remote.pushDefault' is used instead, provided that it is defined, +which by default it is not." + (interactive (list (magit-branch-config-branch + "Cycle branch..pushRemote for"))) + (magit--set-popup-variable (format "branch.%s.pushRemote" branch) + (magit-list-remotes) + "remote.pushDefault")) + +(defun magit-format-branch*pushRemote () + (let ((branch (magit-branch-config-branch))) + (magit--format-popup-variable:choices + (format "branch.%s.pushRemote" branch) + (magit-list-remotes) + nil "remote.pushDefault" + (+ (length branch) 20)))) + +;;;###autoload +(defun magit-cycle-pull.rebase () + "Cycle the repository-local value of `pull.rebase'. + +The Git variable `pull.rebase' specifies whether pulling is done +by rebasing or by merging. It can be overwritten using the Git +variable `branch..rebase'. + +When `true' then pulling is done by rebasing. +When `false' (the default) then pulling is done by merging." + (interactive) + (magit--set-popup-variable "pull.rebase" '("true" "false") "false")) + +(defun magit-format-pull.rebase () + (magit--format-popup-variable:choices + "pull.rebase" '("true" "false") "false" nil 19)) + +;;;###autoload +(defun magit-cycle-remote.pushDefault () + "Cycle the repository-local value of `remote.pushDefault'. + +The Git variable `remote.pushDefault' specifies the remote that +local branches are usually pushed to. It can be overwritten +using the Git variable `branch..pushRemote'." + (interactive) + (magit--set-popup-variable "remote.pushDefault" (magit-list-remotes))) + +(defun magit-format-remote.pushDefault () + (magit--format-popup-variable:choices + "remote.pushDefault" (magit-list-remotes) nil nil 19)) + +;;;###autoload +(defun magit-cycle-branch*autoSetupMerge () + "Cycle the repository-local value of `branch.autoSetupMerge'. + +The Git variable `branch.autoSetupMerge' under what circumstances +creating a branch (named NAME) should result in the variables +`branch..merge' and `branch..remote' being set +according to the starting point used to create the branch. If +the starting point isn't a branch, then these variables are never +set. + +When `always' then the variables are set regardless of whether +the starting point is a local or a remote branch. + +When `true' (the default) then the variable are set when the +starting point is a remote branch, but not when it is a local +branch. + +When `false' then the variables are never set." + (interactive) + (magit--set-popup-variable "branch.autoSetupMerge" + '("always" "true" "false") "true")) + +(defun magit-format-branch*autoSetupMerge () + (magit--format-popup-variable:choices + "branch.autoSetupMerge" '("always" "true" "false") "true" nil 23)) + +;;;###autoload +(defun magit-cycle-branch*autoSetupRebase () + "Cycle the repository-local value of `branch.autoSetupRebase'. + +The Git variable `branch.autoSetupRebase' specifies whether +creating a branch (named NAME) should result in the variable +`branch..rebase' being set to `true'. + +When `always' then the variable is set regardless of whether the +starting point is a local or a remote branch. + +When `local' then the variable are set when the starting point +is a local branch, but not when it is a remote branch. + +When `remote' then the variable are set when the starting point +is a remote branch, but not when it is a local branch. + +When `never' (the default) then the variable is never set." + (interactive) + (magit--set-popup-variable "branch.autoSetupRebase" + '("always" "local" "remote" "never") "never")) + +(defun magit-format-branch*autoSetupRebase () + (magit--format-popup-variable:choices + "branch.autoSetupRebase" + '("always" "local" "remote" "never") + "never" nil 23)) + +;;; _ +(provide 'magit-branch) +;;; magit-branch.el ends here diff --git a/elpa/magit-20181113.1837/magit-clone.el b/elpa/magit-20181113.1837/magit-clone.el new file mode 100644 index 00000000..7afc1eac --- /dev/null +++ b/elpa/magit-20181113.1837/magit-clone.el @@ -0,0 +1,103 @@ +;;; magit-clone.el --- clone a repository -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements clone commands. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-clone-set-remote-head nil + "Whether cloning creates the symbolic-ref `/HEAD'." + :package-version '(magit . "2.4.2") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-clone-set-remote.pushDefault 'ask + "Whether to set the value of `remote.pushDefault' after cloning. + +If t, then set without asking. If nil, then don't set. If +`ask', then ask." + :package-version '(magit . "2.4.0") + :group 'magit-commands + :type '(choice (const :tag "set" t) + (const :tag "ask" ask) + (const :tag "don't set" nil))) + +(defcustom magit-clone-default-directory nil + "Default directory to use when `magit-clone' reads destination. +If nil (the default), then use the value of `default-directory'. +If a directory, then use that. If a function, then call that +with the remote url as only argument and use the returned value." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type '(choice (const :tag "value of default-directory") + (directory :tag "constant directory") + (function :tag "function's value"))) + +;;; Commands + +;;;###autoload +(defun magit-clone (repository directory) + "Clone the REPOSITORY to DIRECTORY. +Then show the status buffer for the new repository." + (interactive + (let ((url (magit-read-string-ns "Clone repository"))) + (list url (read-directory-name + "Clone to: " + (if (functionp magit-clone-default-directory) + (funcall magit-clone-default-directory url) + magit-clone-default-directory) + nil nil + (and (string-match "\\([^/:]+?\\)\\(/?\\.git\\)?$" url) + (match-string 1 url)))))) + (setq directory (file-name-as-directory (expand-file-name directory))) + (magit-run-git-async "clone" repository + (magit-convert-filename-for-git directory)) + ;; Don't refresh the buffer we're calling from. + (process-put magit-this-process 'inhibit-refresh t) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (let ((magit-process-raise-error t)) + (magit-process-sentinel process event))) + (when (and (eq (process-status process) 'exit) + (= (process-exit-status process) 0)) + (let ((default-directory directory)) + (when (or (eq magit-clone-set-remote.pushDefault t) + (and magit-clone-set-remote.pushDefault + (y-or-n-p "Set `remote.pushDefault' to \"origin\"? "))) + (setf (magit-get "remote.pushDefault") "origin")) + (unless magit-clone-set-remote-head + (magit-remote-unset-head "origin"))) + (with-current-buffer (process-get process 'command-buf) + (magit-status-internal directory)))))) + +;;; _ +(provide 'magit-clone) +;;; magit-clone.el ends here diff --git a/elpa/magit-20181113.1837/magit-collab.el b/elpa/magit-20181113.1837/magit-collab.el new file mode 100644 index 00000000..a637c7ae --- /dev/null +++ b/elpa/magit-20181113.1837/magit-collab.el @@ -0,0 +1,174 @@ +;;; magit-collab.el --- collaboration tools -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements various collaboration tools. These tools +;; are only early incarnation -- implementing collaboration tools is +;; a top priority for future development. + +;; Currently these tools (including `magit-branch-pull-request', which +;; is defined elsewhere) only support Github, but support for other +;; Git forges as well as mailing list based collaboration is in +;; planning. + +;;; Code: + +(require 'magit) +(require 'ghub) + +;;; Variables + +(defvar magit-github-token-scopes '(repo) + "The Github API scopes needed by Magit. + +`repo' is the only required scope. Without this scope none of +Magit's features that use the API work. Instead of this scope +you could use `public_repo' if you are only interested in public +repositories. + +`repo' Grants read/write access to code, commit statuses, + invitations, collaborators, adding team memberships, and + deployment statuses for public and private repositories + and organizations. + +`public_repo' Grants read/write access to code, commit statuses, + collaborators, and deployment statuses for public repositories + and organizations. Also required for starring public + repositories.") + +;;; Commands + +;;;###autoload +(defun magit-browse-pull-request (pr) + "Visit pull-request PR using `browse-url'. + +Currently this only supports Github, but that restriction will +be lifted eventually to support other Git forges." + (interactive (list (magit-read-pull-request "Visit pull request"))) + (browse-url (format "https://github.com/%s/pull/%s" + (--> pr + (cdr (assq 'base it)) + (cdr (assq 'repo it)) + (cdr (assq 'full_name it))) + (cdr (assq 'number pr))))) + +;;; Utilities + +(defun magit-read-pull-request (prompt) + "Read a pull request from the user, prompting with PROMPT. +Return the Git forge's API response. Currently this function +only supports Github, but that will change eventually." + (let* ((origin (magit-upstream-repository)) + (id (magit--forge-id origin)) + (fmtfun (lambda (pull-request) + (format "%s %s" + (cdr (assq 'number pull-request)) + (cdr (assq 'title pull-request))))) + (prs (ghub-get (format "/repos/%s/pulls" id) nil :auth 'magit)) + (choice (magit-completing-read + prompt (mapcar fmtfun prs) nil nil nil nil + (let ((default (thing-at-point 'github-pull-request))) + (and default (funcall fmtfun default))))) + (number (and (string-match "\\([0-9]+\\)" choice) + (string-to-number (match-string 1 choice))))) + (and number + ;; Don't reuse the pr from the list, it lacks some information + ;; that is only returned when requesting a single pr. #3371 + (ghub-get (format "/repos/%s/pulls/%s" id number) + nil :auth 'magit)))) + +(defun magit-upstream-repository () + "Return the remote name of the upstream repository. + +If the Git variable `magit.upstream' is set, then return its +value. Otherwise return \"origin\". If the remote does not +exist, then raise an error." + (let ((remote (or (magit-get "magit.upstream") "origin"))) + (unless (magit-remote-p remote) + (error "No remote named `%s' exists (consider setting `magit.upstream')" + remote)) + (unless (magit--github-remote-p remote) + (error "Currently only Github is supported")) + remote)) + +(defun magit--forge-id (remote) + (let ((url (magit-get "remote" remote "url"))) + (and (string-match "\\([^:/]+/[^/]+?\\)\\(?:\\.git\\)?\\'" url) + (match-string 1 url)))) + +(defconst magit--github-url-regexp "\ +\\`\\(?:git://\\|git@\\|ssh://git@\\|https://\\)\ +\\(.*?\\)[/:]\ +\\(\\([^:/]+\\)/\\([^/]+?\\)\\)\ +\\(?:\\.git\\)?\\'") + +(defun magit--github-url-p (url) + (save-match-data + (and url + (string-match magit--github-url-regexp url) + (let ((host (match-string 1 url))) + ;; Match values like "github.com-as-someone", which are + ;; translated to just "github.com" according to settings + ;; in "~/.ssh/config". Theoretically this could result + ;; in false-positives, but that's rather unlikely. #3392 + (and (or (string-match-p (regexp-quote "github.com") host) + (string-match-p + (regexp-quote (car (split-string (ghub--host) "/"))) + host)) + host))))) + +(defun magit--github-remote-p (remote) + (or (--when-let (magit-git-string "remote" "get-url" "--push" remote) + (magit--github-url-p it)) + (--when-let (magit-git-string "remote" "get-url" "--all" remote) + (magit--github-url-p it)))) + +(defun magit--github-url-equal (r1 r2) + (or (equal r1 r2) + (save-match-data + (let ((n1 (and (string-match magit--github-url-regexp r1) + (match-string 2 r1))) + (n2 (and (string-match magit--github-url-regexp r2) + (match-string 2 r2)))) + (and n1 n2 (equal n1 n2)))))) + +(defun magit--pullreq-from-upstream-p (pr) + (let-alist pr + (equal .head.repo.full_name + .base.repo.full_name))) + +(defun magit--pullreq-branch (pr &optional assert-new) + (let-alist pr + (let ((branch .head.ref)) + (when (and (not (magit--pullreq-from-upstream-p pr)) + (or (not .maintainer_can_modify) + (magit-branch-p branch))) + (setq branch (format "pr-%s" .number))) + (when (and assert-new (magit-branch-p branch)) + (user-error "Branch `%s' already exists" branch)) + branch))) + +;;; _ +(provide 'magit-collab) +;;; magit-collab.el ends here diff --git a/elpa/magit-20181113.1837/magit-commit.el b/elpa/magit-20181113.1837/magit-commit.el new file mode 100644 index 00000000..bbd49c88 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-commit.el @@ -0,0 +1,543 @@ +;;; magit-commit.el --- create Git commits -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements commands for creating Git commits. These +;; commands just initiate the commit, support for writing the commit +;; messages is implemented in `git-commit.el'. + +;;; Code: + +(require 'magit) +(require 'magit-sequence) + +(eval-when-compile (require 'epa)) ; for `epa-protocol' +(eval-when-compile (require 'epg)) +(eval-when-compile (require 'subr-x)) + +;;; Options + +(defcustom magit-commit-arguments nil + "The arguments used when committing." + :group 'magit-git-arguments + :type '(repeat (string :tag "Argument"))) + +(defcustom magit-commit-ask-to-stage 'verbose + "Whether to ask to stage all unstaged changes when committing and nothing is staged." + :package-version '(magit . "2.3.0") + :group 'magit-commands + :type '(choice (const :tag "Ask showing diff" verbose) + (const :tag "Ask" t) + (const :tag "Don't ask" nil))) + +(defcustom magit-commit-show-diff t + "Whether the relevant diff is automatically shown when committing." + :package-version '(magit . "2.3.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-commit-extend-override-date t + "Whether using `magit-commit-extend' changes the committer date." + :package-version '(magit . "2.3.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-commit-reword-override-date t + "Whether using `magit-commit-reword' changes the committer date." + :package-version '(magit . "2.3.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-commit-squash-confirm t + "Whether the commit targeted by squash and fixup has to be confirmed. +When non-nil then the commit at point (if any) is used as default +choice, otherwise it has to be confirmed. This option only +affects `magit-commit-squash' and `magit-commit-fixup'. The +\"instant\" variants always require confirmation because making +an error while using those is harder to recover from." + :package-version '(magit . "2.1.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-post-commit-hook nil + "Hook run after creating a commit without the user editing a message. + +This hook is run by `magit-refresh' if `this-command' is a member +of `magit-post-stage-hook-commands'. This only includes commands +named `magit-commit-*' that do *not* require that the user edits +the commit message in a buffer and then finishes by pressing +\\\\[with-editor-finish]. + +Also see `git-commit-post-finish-hook'." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type 'hook) + +(defvar magit-post-commit-hook-commands + '(magit-commit-extend + magit-commit-fixup + magit-commit-augment + magit-commit-instant-fixup + magit-commit-instant-squash)) + +;;; Popup + +(defun magit-commit-popup (&optional arg) + "Popup console for commit commands." + (interactive "P") + (--if-let (magit-commit-message-buffer) + (switch-to-buffer it) + (magit-invoke-popup 'magit-commit-popup nil arg))) + +(defvar magit-commit-popup + '(:variable magit-commit-arguments + :man-page "git-commit" + :switches ((?a "Stage all modified and deleted files" "--all") + (?e "Allow empty commit" "--allow-empty") + (?v "Show diff of changes to be committed" "--verbose") + (?h "Disable hooks" "--no-verify") + (?s "Add Signed-off-by line" "--signoff") + (?R "Claim authorship and reset author date" "--reset-author")) + :options ((?A "Override the author" "--author=") + (?S "Sign using gpg" "--gpg-sign=" magit-read-gpg-secret-key) + (?C "Reuse commit message" "--reuse-message=" + magit-read-reuse-message)) + :actions ((?c "Commit" magit-commit-create) + (?e "Extend" magit-commit-extend) + (?f "Fixup" magit-commit-fixup) + (?F "Instant Fixup" magit-commit-instant-fixup) nil + (?w "Reword" magit-commit-reword) + (?s "Squash" magit-commit-squash) + (?S "Instant Squash" magit-commit-instant-squash) nil + (?a "Amend" magit-commit-amend) + (?A "Augment" magit-commit-augment)) + :max-action-columns 4 + :default-action magit-commit-create)) + +(magit-define-popup-keys-deferred 'magit-commit-popup) + +(defun magit-commit-arguments nil + (if (eq magit-current-popup 'magit-commit-popup) + magit-current-popup-args + magit-commit-arguments)) + +(defvar magit-gpg-secret-key-hist nil) + +(defun magit-read-gpg-secret-key (prompt &optional _initial-input) + (require 'epa) + (let ((keys (--map (concat (epg-sub-key-id (car (epg-key-sub-key-list it))) + " " + (when-let ((id-obj (car (epg-key-user-id-list it)))) + (let ((id-str (epg-user-id-string id-obj))) + (if (stringp id-str) + id-str + (epg-decode-dn id-obj))))) + (epg-list-keys (epg-make-context epa-protocol) nil t)))) + (car (split-string (magit-completing-read + prompt keys nil nil nil 'magit-gpg-secret-key-hist + (car (or magit-gpg-secret-key-hist keys))) + " ")))) + +(defun magit-read-reuse-message (prompt &optional default) + (magit-completing-read prompt (magit-list-refnames) + nil nil nil 'magit-revision-history + (or default + (and (magit-rev-verify "ORIG_HEAD") + "ORIG_HEAD")))) + +;;; Commands + +;;;###autoload +(defun magit-commit-create (&optional args) + "Create a new commit on `HEAD'. +With a prefix argument, amend to the commit at `HEAD' instead. +\n(git commit [--amend] ARGS)" + (interactive (if current-prefix-arg + (list (cons "--amend" (magit-commit-arguments))) + (list (magit-commit-arguments)))) + (when (member "--all" args) + (setq this-command 'magit-commit-all)) + (when (setq args (magit-commit-assert args)) + (let ((default-directory (magit-toplevel))) + (magit-run-git-with-editor "commit" args)))) + +;;;###autoload +(defun magit-commit-amend (&optional args) + "Amend the last commit. +\n(git commit --amend ARGS)" + (interactive (list (magit-commit-arguments))) + (magit-commit-amend-assert) + (magit-run-git-with-editor "commit" "--amend" args)) + +;;;###autoload +(defun magit-commit-extend (&optional args override-date) + "Amend the last commit, without editing the message. + +With a prefix argument keep the committer date, otherwise change +it. The option `magit-commit-extend-override-date' can be used +to inverse the meaning of the prefix argument. \n(git commit +--amend --no-edit)" + (interactive (list (magit-commit-arguments) + (if current-prefix-arg + (not magit-commit-extend-override-date) + magit-commit-extend-override-date))) + (when (setq args (magit-commit-assert args (not override-date))) + (magit-commit-amend-assert) + (let ((process-environment process-environment)) + (unless override-date + (push (magit-rev-format "GIT_COMMITTER_DATE=%cD") process-environment)) + (magit-run-git-with-editor "commit" "--amend" "--no-edit" args)))) + +;;;###autoload +(defun magit-commit-reword (&optional args override-date) + "Reword the last commit, ignoring staged changes. + +With a prefix argument keep the committer date, otherwise change +it. The option `magit-commit-reword-override-date' can be used +to inverse the meaning of the prefix argument. + +Non-interactively respect the optional OVERRIDE-DATE argument +and ignore the option. +\n(git commit --amend --only)" + (interactive (list (magit-commit-arguments) + (if current-prefix-arg + (not magit-commit-reword-override-date) + magit-commit-reword-override-date))) + (magit-commit-amend-assert) + (let ((process-environment process-environment)) + (unless override-date + (push (magit-rev-format "GIT_COMMITTER_DATE=%cD") process-environment)) + (magit-run-git-with-editor "commit" "--amend" "--only" args))) + +;;;###autoload +(defun magit-commit-fixup (&optional commit args) + "Create a fixup commit. + +With a prefix argument the target COMMIT has to be confirmed. +Otherwise the commit at point may be used without confirmation +depending on the value of option `magit-commit-squash-confirm'." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--fixup" commit args)) + +;;;###autoload +(defun magit-commit-squash (&optional commit args) + "Create a squash commit, without editing the squash message. + +With a prefix argument the target COMMIT has to be confirmed. +Otherwise the commit at point may be used without confirmation +depending on the value of option `magit-commit-squash-confirm'." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--squash" commit args)) + +;;;###autoload +(defun magit-commit-augment (&optional commit args) + "Create a squash commit, editing the squash message. + +With a prefix argument the target COMMIT has to be confirmed. +Otherwise the commit at point may be used without confirmation +depending on the value of option `magit-commit-squash-confirm'." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--squash" commit args nil t)) + +;;;###autoload +(defun magit-commit-instant-fixup (&optional commit args) + "Create a fixup commit targeting COMMIT and instantly rebase." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--fixup" commit args t)) + +;;;###autoload +(defun magit-commit-instant-squash (&optional commit args) + "Create a squash commit targeting COMMIT and instantly rebase." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--squash" commit args t)) + +(defun magit-commit-squash-internal + (option commit &optional args rebase edit confirmed) + (when-let ((args (magit-commit-assert args t))) + (when commit + (when (and rebase (not (magit-rev-ancestor-p commit "HEAD"))) + (magit-read-char-case + (format "%s isn't an ancestor of HEAD. " commit) nil + (?c "[c]reate without rebasing" (setq rebase nil)) + (?s "[s]elect other" (setq commit nil)) + (?a "[a]bort" (user-error "Quit"))))) + (when commit + (setq commit (magit-rebase-interactive-assert commit t))) + (if (and commit + (or confirmed + (not (or rebase + current-prefix-arg + magit-commit-squash-confirm)))) + (let ((magit-commit-show-diff nil)) + (push (concat option "=" commit) args) + (unless edit + (push "--no-edit" args)) + (if rebase + (magit-with-editor + (magit-call-git + "commit" "--no-gpg-sign" + (-remove-first + (apply-partially #'string-match-p "\\`--gpg-sign=") + args))) + (magit-run-git-with-editor "commit" args)) + t) ; The commit was created; used by below lambda. + (magit-log-select + (lambda (commit) + (when (and (magit-commit-squash-internal option commit args + rebase edit t) + rebase) + (magit-commit-amend-assert commit) + (magit-rebase-interactive-1 commit + (list "--autosquash" "--autostash") + "" "true" nil t))) + (format "Type %%p on a commit to %s into it," + (substring option 2))) + (when magit-commit-show-diff + (let ((magit-display-buffer-noselect t)) + (apply #'magit-diff-staged nil (magit-diff-arguments))))))) + +(defun magit-commit-amend-assert (&optional commit) + (--when-let (magit-list-publishing-branches commit) + (let ((m1 "This commit has already been published to ") + (m2 ".\nDo you really want to modify it")) + (magit-confirm 'amend-published + (concat m1 "%s" m2) + (concat m1 "%i public branches" m2) + nil it)))) + +(defun magit-commit-assert (args &optional strict) + (cond + ((or (magit-anything-staged-p) + (and (magit-anything-unstaged-p) + ;; ^ Everything of nothing is still nothing. + (member "--all" args)) + (and (not strict) + ;; ^ For amend variants that don't make sense otherwise. + (or (member "--amend" args) + (member "--allow-empty" args)))) + (or args (list "--"))) + ((and (magit-rebase-in-progress-p) + (not (magit-anything-unstaged-p)) + (y-or-n-p "Nothing staged. Continue in-progress rebase? ")) + (setq this-command 'magit-rebase-continue) + (magit-run-git-sequencer "rebase" "--continue") + nil) + ((and (file-exists-p (magit-git-dir "MERGE_MSG")) + (not (magit-anything-unstaged-p))) + (or args (list "--"))) + ((not (magit-anything-unstaged-p)) + (user-error "Nothing staged (or unstaged)")) + (magit-commit-ask-to-stage + (when (eq magit-commit-ask-to-stage 'verbose) + (magit-diff-unstaged)) + (prog1 (when (y-or-n-p "Nothing staged. Stage and commit all unstaged changes? ") + (magit-run-git "add" "-u" ".") + (or args (list "--"))) + (when (and (eq magit-commit-ask-to-stage 'verbose) + (derived-mode-p 'magit-diff-mode)) + (magit-mode-bury-buffer)))) + (t + (user-error "Nothing staged")))) + +(defvar magit--reshelve-history nil) + +;;;###autoload +(defun magit-commit-reshelve (date) + "Change the committer date and possibly the author date of `HEAD'. + +If you are the author of `HEAD', then both dates are changed, +otherwise only the committer date. The current time is used +as the initial minibuffer input and the original author (if +that is you) or committer date is available as the previous +history element." + (interactive + (let ((author-p (magit-rev-author-p "HEAD"))) + (push (magit-rev-format (if author-p "%ad" "%cd") "HEAD" + (concat "--date=format:%F %T %z")) + magit--reshelve-history) + (list (read-string (if author-p + "Change author and committer dates to: " + "Change committer date to: ") + (cons (format-time-string "%F %T %z") 17) + 'magit--reshelve-history)))) + (let ((process-environment process-environment)) + (push (concat "GIT_COMMITTER_DATE=" date) process-environment) + (magit-run-git "commit" "--amend" "--no-edit" + (and (magit-rev-author-p "HEAD") + (concat "--date=" date))))) + +;;;###autoload (autoload 'magit-commit-absorb-popup "magit-commit" nil t) +(magit-define-popup magit-commit-absorb-popup + "Spread unstaged changes across recent commits. +Without a prefix argument just call `magit-commit-absorb'. +With a prefix argument use a popup buffer to select arguments." + :man-page "git-bisect" + :options '((?c "Diff context lines" "--context=") + (?s "Strictness" "--strict=")) + :actions '((?x "Absorb" magit-commit-absorb)) + :default-action 'magit-commit-absorb + :use-prefix 'popup) + +(defun magit-commit-absorb (&optional commit args confirmed) + "Spread unstaged changes across recent commits. +This command requires the git-autofixup script, which is +available from https://github.com/torbiak/git-autofixup." + (interactive (list (magit-get-upstream-branch) + (magit-commit-absorb-arguments))) + (unless (executable-find "git-autofixup") + (user-error "This command requires the git-autofixup script, which %s" + "is available from https://github.com/torbiak/git-autofixup")) + (when (magit-anything-staged-p) + (user-error "Cannot absorb when there are staged changes")) + (unless (magit-anything-unstaged-p) + (user-error "There are no unstaged changes that could be absorbed")) + (when commit + (setq commit (magit-rebase-interactive-assert commit t))) + (if (and commit confirmed) + (progn (magit-run-git-async "autofixup" "-vv" args commit) t) + (magit-log-select + (lambda (commit) + (magit-commit-absorb commit args t)) + nil nil nil nil commit))) + +;;; Pending Diff + +(defun magit-commit-diff () + (when (and git-commit-mode magit-commit-show-diff) + (when-let ((diff-buffer (magit-mode-get-buffer 'magit-diff-mode))) + ;; This window just started displaying the commit message + ;; buffer. Without this that buffer would immediately be + ;; replaced with the diff buffer. See #2632. + (unrecord-window-buffer nil diff-buffer)) + (condition-case nil + (let ((args (car (magit-diff-arguments))) + (magit-inhibit-save-previous-winconf 'unset) + (magit-display-buffer-noselect t) + (inhibit-quit nil)) + (message "Diffing changes to be committed (C-g to abort diffing)") + (if-let ((fn (cl-case last-command + (magit-commit + (apply-partially 'magit-diff-staged nil)) + (magit-commit-all + (apply-partially 'magit-diff-working-tree nil)) + ((magit-commit-amend + magit-commit-reword + magit-rebase-reword-commit) + 'magit-diff-while-amending)))) + (funcall fn args) + (if (magit-anything-staged-p) + (magit-diff-staged nil args) + (magit-diff-while-amending args)))) + (quit)))) + +;; Mention `magit-diff-while-committing' because that's +;; always what I search for when I try to find this line. +(add-hook 'server-switch-hook 'magit-commit-diff) + +(add-to-list 'with-editor-server-window-alist + (cons git-commit-filename-regexp 'switch-to-buffer)) + +;;; Message Utilities + +(defun magit-commit-message-buffer () + (let* ((find-file-visit-truename t) ; git uses truename of COMMIT_EDITMSG + (topdir (magit-toplevel))) + (--first (equal topdir (with-current-buffer it + (and git-commit-mode (magit-toplevel)))) + (append (buffer-list (selected-frame)) + (buffer-list))))) + +(defvar magit-commit-add-log-insert-function 'magit-commit-add-log-insert + "Used by `magit-commit-add-log' to insert a single entry.") + +(defun magit-commit-add-log () + "Add a stub for the current change into the commit message buffer. +If no commit is in progress, then initiate it. Use the function +specified by variable `magit-commit-add-log-insert-function' to +actually insert the entry." + (interactive) + (let ((hunk (and (magit-section-match 'hunk) + (magit-current-section))) + (log (magit-commit-message-buffer)) buf pos) + (save-window-excursion + (call-interactively #'magit-diff-visit-file) + (setq buf (current-buffer)) + (setq pos (point))) + (unless log + (unless (magit-commit-assert nil) + (user-error "Abort")) + (magit-commit-create) + (while (not (setq log (magit-commit-message-buffer))) + (sit-for 0.01))) + (save-excursion + (with-current-buffer buf + (goto-char pos) + (funcall magit-commit-add-log-insert-function log + (magit-file-relative-name) + (and hunk (add-log-current-defun))))))) + +(defun magit-commit-add-log-insert (buffer file defun) + (with-current-buffer buffer + (undo-boundary) + (goto-char (point-max)) + (while (re-search-backward (concat "^" comment-start) nil t)) + (save-restriction + (narrow-to-region (point-min) (point)) + (cond ((re-search-backward (format "* %s\\(?: (\\([^)]+\\))\\)?: " file) + nil t) + (when (equal (match-string 1) defun) + (setq defun nil)) + (re-search-forward ": ")) + (t + (when (re-search-backward "^[\\*(].+\n" nil t) + (goto-char (match-end 0))) + (while (re-search-forward "^[^\\*\n].*\n" nil t)) + (if defun + (progn (insert (format "* %s (%s): \n" file defun)) + (setq defun nil)) + (insert (format "* %s: \n" file))) + (backward-char) + (unless (looking-at "\n[\n\\']") + (insert ?\n) + (backward-char)))) + (when defun + (forward-line) + (let ((limit (save-excursion + (and (re-search-forward "^\\*" nil t) + (point))))) + (unless (or (looking-back (format "(%s): " defun) + (line-beginning-position)) + (re-search-forward (format "^(%s): " defun) limit t)) + (while (re-search-forward "^[^\\*\n].*\n" limit t)) + (insert (format "(%s): \n" defun)) + (backward-char))))))) + +;;; _ +(provide 'magit-commit) +;;; magit-commit.el ends here diff --git a/elpa/magit-20181113.1837/magit-core.el b/elpa/magit-20181113.1837/magit-core.el new file mode 100644 index 00000000..2bad54c1 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-core.el @@ -0,0 +1,132 @@ +;;; magit-core.el --- core functionality -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library requires several other libraries, so that yet other +;; libraries can just require this one, instead of having to require +;; all the other ones. In other words this separates the low-level +;; stuff from the rest. It also defines some Custom groups. + +;;; Code: + +(require 'magit-utils) +(require 'magit-section) +(require 'magit-git) +(require 'magit-mode) +(require 'magit-margin) +(require 'magit-process) +(require 'magit-autorevert) + +(defgroup magit nil + "Controlling Git from Emacs." + :link '(url-link "https://magit.vc") + :link '(info-link "(magit)FAQ") + :link '(info-link "(magit)") + :group 'tools) + +(defgroup magit-essentials nil + "Options that every Magit user should briefly think about. + +Each of these options falls into one or more of these categories: + +* Options that affect Magit's behavior in fundamental ways. +* Options that affect safety. +* Options that affect performance. +* Options that are of a personal nature." + :link '(info-link "(magit)Essential Settings") + :group 'magit) + +(defgroup magit-miscellaneous nil + "Miscellanous Magit options." + :group 'magit) + +(defgroup magit-commands nil + "Options controlling behavior of certain commands." + :group 'magit) + +(defgroup magit-git-arguments nil + "Options controlling what arguments are passed to Git. + +Most of these options can be set using the respective popup, +and it is recommended that you do that because then you can +be certain that Magit supports the arguments that you select. + +An option `magit-NAME-argument' specifies the arguments that +are enabled by default by the popup `magit-NAME-popup'." + :link '(info-link "(magit-popup)Customizing Existing Popups") + :link '(info-link "(magit-popup)Usage") + :group 'magit-commands) + +(defgroup magit-modes nil + "Modes used or provided by Magit." + :group 'magit) + +(defgroup magit-buffers nil + "Options concerning Magit buffers." + :link '(info-link "(magit)Modes and Buffers") + :group 'magit) + +(defgroup magit-refresh nil + "Options controlling how Magit buffers are refreshed." + :link '(info-link "(magit)Automatic Refreshing of Magit Buffers") + :group 'magit + :group 'magit-buffers) + +(defgroup magit-faces nil + "Faces used by Magit." + :group 'magit + :group 'faces) + +(defgroup magit-extensions nil + "Extensions to Magit." + :group 'magit) + +(custom-add-to-group 'magit-modes 'magit-popup 'custom-group) +(custom-add-to-group 'magit-faces 'magit-popup-faces 'custom-group) +(custom-add-to-group 'magit-modes 'git-commit 'custom-group) +(custom-add-to-group 'magit-faces 'git-commit-faces 'custom-group) +(custom-add-to-group 'magit-modes 'git-rebase 'custom-group) +(custom-add-to-group 'magit-faces 'git-rebase-faces 'custom-group) +(custom-add-to-group 'magit-process 'with-editor 'custom-group) + +(defgroup magit-related nil + "Options that are relevant to Magit but that are defined elsewhere." + :link '(custom-group-link vc) + :link '(custom-group-link smerge) + :link '(custom-group-link ediff) + :link '(custom-group-link auto-revert) + :group 'magit + :group 'magit-extensions + :group 'magit-essentials) + +(custom-add-to-group 'magit-related 'auto-revert-check-vc-info 'custom-variable) +(custom-add-to-group 'magit-auto-revert 'auto-revert-check-vc-info 'custom-variable) + +(custom-add-to-group 'magit-related 'ediff-window-setup-function 'custom-variable) +(custom-add-to-group 'magit-related 'smerge-refine-ignore-whitespace 'custom-variable) +(custom-add-to-group 'magit-related 'vc-follow-symlinks 'custom-variable) + +;;; _ +(provide 'magit-core) +;;; magit-core.el ends here diff --git a/elpa/magit-20181113.1837/magit-diff.el b/elpa/magit-20181113.1837/magit-diff.el new file mode 100644 index 00000000..67413086 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-diff.el @@ -0,0 +1,2831 @@ +;;; magit-diff.el --- inspect Git diffs -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements support for looking at Git diffs and +;; commits. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'git-commit) +(require 'magit-core) + +;; For `magit-diff-popup' +(declare-function magit-stash-show "magit-stash" (stash &optional args files)) +;; For `magit-diff-visit-file' +(declare-function dired-jump "dired-x" (&optional other-window file-name)) +(declare-function magit-find-file-noselect "magit-files" (rev file)) +(declare-function magit-status-internal "magit-status" (directory)) +;; For `magit-diff-while-committing' +(declare-function magit-commit-message-buffer "magit-commit" ()) +;; For `magit-insert-revision-gravatar' +(defvar gravatar-size) +;; For `magit-show-commit' and `magit-diff-show-or-scroll' +(declare-function magit-current-blame-chunk "magit-blame" ()) +(eval-when-compile + (cl-pushnew 'orig-rev eieio--known-slot-names)) +(declare-function magit-blame-mode "magit-blame" (&optional arg)) +(defvar magit-blame-mode) +(defvar git-rebase-line) +;; For `magit-diff-unmerged' +(declare-function magit-merge-in-progress-p "magit-merge" ()) +(declare-function magit--merge-range "magit-merge" (&optional head)) + +(require 'diff-mode) +(require 'smerge-mode) + +(defvar bookmark-make-record-function) + +;;; Options +;;;; Diff Mode + +(defgroup magit-diff nil + "Inspect and manipulate Git diffs." + :link '(info-link "(magit)Diffing") + :group 'magit-modes) + +(defcustom magit-diff-mode-hook nil + "Hook run after entering Magit-Diff mode." + :group 'magit-diff + :type 'hook) + +(defcustom magit-diff-arguments '("--stat" "--no-ext-diff") + "The diff arguments used in buffers whose mode derives from `magit-diff-mode'." + :group 'magit-git-arguments + :group 'magit-diff + :type '(repeat (string :tag "Argument"))) + +(defcustom magit-diff-sections-hook + '(magit-insert-diff + magit-insert-xref-buttons) + "Hook run to insert sections into a `magit-diff-mode' buffer." + :package-version '(magit . "2.3.0") + :group 'magit-diff + :type 'hook) + +(defcustom magit-diff-expansion-threshold 60 + "After how many seconds not to expand anymore diffs. + +Except in status buffers, diffs are usually start out fully +expanded. Because that can take a long time, all diffs that +haven't been fontified during a refresh before the threshold +defined here are instead displayed with their bodies collapsed. + +Note that this can cause sections that were previously expanded +to be collapsed. So you should not pick a very low value here. + +The hook function `magit-diff-expansion-threshold' has to be a +member of `magit-section-set-visibility-hook' for this option +to have any effect." + :package-version '(magit . "2.9.0") + :group 'magit-diff + :type 'float) + +(defcustom magit-diff-highlight-hunk-body t + "Whether to highlight bodies of selected hunk sections. +This only has an effect if `magit-diff-highlight' is a +member of `magit-section-highlight-hook', which see." + :package-version '(magit . "2.1.0") + :group 'magit-diff + :type 'boolean) + +(defcustom magit-diff-highlight-hunk-region-functions + '(magit-diff-highlight-hunk-region-dim-outside + magit-diff-highlight-hunk-region-using-overlays) + "The functions used to highlight the hunk-internal region. + +`magit-diff-highlight-hunk-region-dim-outside' overlays the outside +of the hunk internal selection with a face that causes the added and +removed lines to have the same background color as context lines. +This function should not be removed from the value of this option. + +`magit-diff-highlight-hunk-region-using-overlays' and +`magit-diff-highlight-hunk-region-using-underline' emphasize the +region by placing delimiting horizonal lines before and after it. +The underline variant was implemented because Eli said that is +how we should do it. However the overlay variant actually works +better. Also see https://github.com/magit/magit/issues/2758. + +Instead of, or in addition to, using delimiting horizontal lines, +to emphasize the boundaries, you may which to emphasize the text +itself, using `magit-diff-highlight-hunk-region-using-face'. + +In terminal frames it's not possible to draw lines as the overlay +and underline variants normally do, so there they fall back to +calling the face function instead." + :package-version '(magit . "2.9.0") + :set-after '(magit-diff-show-lines-boundaries) + :group 'magit-diff + :type 'hook + :options '(magit-diff-highlight-hunk-region-dim-outside + magit-diff-highlight-hunk-region-using-underline + magit-diff-highlight-hunk-region-using-overlays + magit-diff-highlight-hunk-region-using-face)) + +(defcustom magit-diff-unmarked-lines-keep-foreground t + "Whether `magit-diff-highlight-hunk-region-dim-outside' preserves foreground. +When this is set to nil, then that function only adjusts the +foreground color but added and removed lines outside the region +keep their distinct foreground colors." + :package-version '(magit . "2.9.0") + :group 'magit-diff + :type 'boolean) + +(defcustom magit-diff-refine-hunk nil + "Whether to show word-granularity differences within diff hunks. + +nil never show fine differences. +t show fine differences for the current diff hunk only. +`all' show fine differences for all displayed diff hunks." + :group 'magit-diff + :safe (lambda (val) (memq val '(nil t all))) + :type '(choice (const :tag "Never" nil) + (const :tag "Current" t) + (const :tag "All" all))) + +(put 'magit-diff-refine-hunk 'permanent-local t) + +(defcustom magit-diff-adjust-tab-width nil + "Whether to adjust the width of tabs in diffs. + +Determining the correct width can be expensive if it requires +opening large and/or many files, so the widths are cached in +the variable `magit-diff--tab-width-cache'. Set that to nil +to invalidate the cache. + +nil Never ajust tab width. Use `tab-width's value from + the Magit buffer itself instead. + +t If the corresponding file-visiting buffer exits, then + use `tab-width's value from that buffer. Doing this is + cheap, so this value is used even if a corresponding + cache entry exists. + +`always' If there is no such buffer, then temporarily visit the + file to determine the value. + +NUMBER Like `always', but don't visit files larger than NUMBER + bytes." + :package-version '(magit . "2.12.0") + :group 'magit-diff + :type '(choice (const :tag "Never" nil) + (const :tag "If file-visiting buffer exists" t) + (const :tag "... or file isn't larger than bytes" all) + (const :tag "Always" always))) + +(defcustom magit-diff-paint-whitespace t + "Specify where to highlight whitespace errors. +See `magit-diff-highlight-trailing', +`magit-diff-highlight-indentation'. The symbol t means in all +diffs, `status' means only in the status buffer, and nil means +nowhere." + :group 'magit-diff + :safe (lambda (val) (memq val '(t nil status))) + :type '(choice (const :tag "Always" t) + (const :tag "Never" nil) + (const :tag "In status buffer" status))) + +(defcustom magit-diff-highlight-trailing t + "Whether to highlight whitespace at the end of a line in diffs. +Used only when `magit-diff-paint-whitespace' is non-nil." + :group 'magit-diff + :safe 'booleanp + :type 'boolean) + +(defcustom magit-diff-highlight-indentation nil + "Highlight the \"wrong\" indentation style. +Used only when `magit-diff-paint-whitespace' is non-nil. + +The value is a list of cons cells. The car is a regular +expression, and the cdr is the value that applies to repositories +whose directory matches the regular expression. If more than one +element matches, then the *last* element in the list applies. +The default value should therefore come first in the list. + +If the value is `tabs', highlight indentation with tabs. If the +value is an integer, highlight indentation with at least that +many spaces. Otherwise, highlight neither." + :group 'magit-diff + :type `(repeat (cons (string :tag "Directory regexp") + (choice (const :tag "Tabs" tabs) + (integer :tag "Spaces" :value ,tab-width) + (const :tag "Neither" nil))))) + +(defcustom magit-diff-hide-trailing-cr-characters + (and (memq system-type '(ms-dos windows-nt)) t) + "Whether to hide ^M characters at the end of a line in diffs." + :package-version '(magit . "2.6.0") + :group 'magit-diff + :type 'boolean) + +(defcustom magit-diff-visit-previous-blob t + "Whether `magit-diff-visit-file' may visit the previous blob. + +When this is t and point is on a removed line in a diff for a +committed change, then `magit-diff-visit-file' visits the blob +from the last revision which still had that line. + +Currently this is only supported for committed changes, for +staged and unstaged changes `magit-diff-visit-file' always +visits the file in the working tree." + :package-version '(magit . "2.9.0") + :group 'magit-diff + :type 'boolean) + +(defcustom magit-diff-highlight-keywords t + "Whether to highlight bracketed keywords in commit messages." + :package-version '(magit . "2.12.0") + :group 'magit-diff + :type 'boolean) + +;;;; File Diff + +(defcustom magit-diff-buffer-file-locked t + "Whether `magit-diff-buffer-file' uses a dedicated buffer." + :package-version '(magit . "2.7.0") + :group 'magit-commands + :group 'magit-diff + :type 'boolean) + +;;;; Revision Mode + +(defgroup magit-revision nil + "Inspect and manipulate Git commits." + :link '(info-link "(magit)Revision Buffer") + :group 'magit-modes) + +(defcustom magit-revision-mode-hook '(bug-reference-mode) + "Hook run after entering Magit-Revision mode." + :group 'magit-revision + :type 'hook + :options '(bug-reference-mode)) + +(defcustom magit-revision-sections-hook + '(magit-insert-revision-tag + magit-insert-revision-headers + magit-insert-revision-message + magit-insert-revision-notes + magit-insert-revision-diff + magit-insert-xref-buttons) + "Hook run to insert sections into a `magit-revision-mode' buffer." + :package-version '(magit . "2.3.0") + :group 'magit-revision + :type 'hook) + +(defcustom magit-revision-headers-format "\ +Author: %aN <%aE> +AuthorDate: %ad +Commit: %cN <%cE> +CommitDate: %cd +" + "Format string used to insert headers in revision buffers. + +All headers in revision buffers are inserted by the section +inserter `magit-insert-revision-headers'. Some of the headers +are created by calling `git show --format=FORMAT' where FORMAT +is the format specified here. Other headers are hard coded or +subject to option `magit-revision-insert-related-refs'." + :package-version '(magit . "2.3.0") + :group 'magit-revision + :type 'string) + +(defcustom magit-revision-insert-related-refs t + "Whether to show related branches in revision buffers + +`nil' Don't show any related branches. +`t' Show related local branches. +`all' Show related local and remote branches. +`mixed' Show all containing branches and local merged branches." + :package-version '(magit . "2.1.0") + :group 'magit-revision + :type '(choice (const :tag "don't" nil) + (const :tag "local only" t) + (const :tag "all related" all) + (const :tag "all containing, local merged" mixed))) + +(defcustom magit-revision-use-hash-sections 'quicker + "Whether to turn hashes inside the commit message into sections. + +If non-nil, then hashes inside the commit message are turned into +`commit' sections. There is a trade off to be made between +performance and reliability: + +- `slow' calls git for every word to be absolutely sure. +- `quick' skips words less than seven characters long. +- `quicker' additionally skips words that don't contain a number. +- `quickest' uses all words that are at least seven characters + long and which contain at least one number as well as at least + one letter. + +If nil, then no hashes are turned into sections, but you can +still visit the commit at point using \"RET\"." + :package-version '(magit . "2.12.0") + :group 'magit-revision + :type '(choice (const :tag "Use sections, quickest" quickest) + (const :tag "Use sections, quicker" quicker) + (const :tag "Use sections, quick" quick) + (const :tag "Use sections, slow" slow) + (const :tag "Don't use sections" nil))) + +(defcustom magit-revision-show-gravatars nil + "Whether to show gravatar images in revision buffers. + +If nil, then don't insert any gravatar images. If t, then insert +both images. If `author' or `committer', then insert only the +respective image. + +If you have customized the option `magit-revision-header-format' +and want to insert the images then you might also have to specify +where to do so. In that case the value has to be a cons-cell of +two regular expressions. The car specifies where to insert the +author's image. The top half of the image is inserted right +after the matched text, the bottom half on the next line in the +same column. The cdr specifies where to insert the committer's +image, accordingly. Either the car or the cdr may be nil." + :package-version '(magit . "2.3.0") + :group 'magit-revision + :type '(choice (const :tag "Don't show gravatars" nil) + (const :tag "Show gravatars" t) + (const :tag "Show author gravatar" author) + (const :tag "Show committer gravatar" committer) + (cons :tag "Show gravatars using custom pattern." + (regexp :tag "Author regexp" "^Author: ") + (regexp :tag "Committer regexp" "^Commit: ")))) + +(defcustom magit-revision-use-gravatar-kludge nil + "Whether to work around a bug which affects display of gravatars. + +Gravatar images are spliced into two halves which are then +displayed on separate lines. On OS X the splicing has a bug in +some Emacs builds, which causes the top and bottom halves to be +interchanged. Enabling this option works around this issue by +interchanging the halves once more, which cancels out the effect +of the bug. + +See https://github.com/magit/magit/issues/2265 +and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=7847. + +Starting with Emacs 26.1 this kludge should not be required for +any build." + :package-version '(magit . "2.3.0") + :group 'magit-revision + :type 'boolean) + +(defcustom magit-revision-fill-summary-line nil + "Whether to fill excessively long summary lines. + +If this is an integer, then the summary line is filled if it is +longer than either the limit specified here or `window-width'. + +You may want to only set this locally in \".dir-locals-2.el\" for +repositories known to contain bad commit messages. + +The body of the message is left alone because (a) most people who +write excessively long summary lines usually don't add a body and +(b) even people who have the decency to wrap their lines may have +a good reason to include a long line in the body sometimes." + :package-version '(magit . "2.90.0") + :group 'magit-revision + :type '(choice (const :tag "Don't fill" nil) + (integer :tag "Fill if longer than"))) + +;;;; Diff Sections + +(defcustom magit-diff-section-arguments '("--no-ext-diff") + "The diff arguments used in buffers that show other things besides diffs." + :group 'magit-git-arguments + :group 'magit-diff + :group 'magit-status + :type '(repeat (string :tag "Argument"))) + +(put 'magit-diff-section-arguments 'permanent-local t) + +;;; Faces + +(defface magit-diff-file-heading + '((t :weight bold)) + "Face for diff file headings." + :group 'magit-faces) + +(defface magit-diff-file-heading-highlight + '((t :inherit (magit-section-highlight))) + "Face for current diff file headings." + :group 'magit-faces) + +(defface magit-diff-file-heading-selection + '((((class color) (background light)) + :inherit magit-diff-file-heading-highlight + :foreground "salmon4") + (((class color) (background dark)) + :inherit magit-diff-file-heading-highlight + :foreground "LightSalmon3")) + "Face for selected diff file headings." + :group 'magit-faces) + +(defface magit-diff-hunk-heading + '((((class color) (background light)) + :background "grey80" + :foreground "grey30") + (((class color) (background dark)) + :background "grey25" + :foreground "grey70")) + "Face for diff hunk headings." + :group 'magit-faces) + +(defface magit-diff-hunk-heading-highlight + '((((class color) (background light)) + :background "grey75" + :foreground "grey30") + (((class color) (background dark)) + :background "grey35" + :foreground "grey70")) + "Face for current diff hunk headings." + :group 'magit-faces) + +(defface magit-diff-hunk-heading-selection + '((((class color) (background light)) + :inherit magit-diff-hunk-heading-highlight + :foreground "salmon4") + (((class color) (background dark)) + :inherit magit-diff-hunk-heading-highlight + :foreground "LightSalmon3")) + "Face for selected diff hunk headings." + :group 'magit-faces) + +(defface magit-diff-hunk-region + '((t :inherit bold)) + "Face used by `magit-diff-highlight-hunk-region-using-face'. + +This face is overlayed over text that uses other hunk faces, +and those normally set the foreground and background colors. +The `:foreground' and especially the `:background' properties +should be avoided here. Setting the latter would cause the +lose of information. Good properties to set here are `:weight' +and `:slant'." + :group 'magit-faces) + +(defface magit-diff-lines-heading + '((((class color) (background light)) + :inherit magit-diff-hunk-heading-highlight + :background "LightSalmon3") + (((class color) (background dark)) + :inherit magit-diff-hunk-heading-highlight + :foreground "grey80" + :background "salmon4")) + "Face for diff hunk heading when lines are marked." + :group 'magit-faces) + +(defface magit-diff-lines-boundary + '((t :inherit magit-diff-lines-heading)) + "Face for boundary of marked lines in diff hunk." + :group 'magit-faces) + +(defface magit-diff-conflict-heading + '((t :inherit magit-diff-hunk-heading)) + "Face for conflict markers." + :group 'magit-faces) + +(defface magit-diff-added + '((((class color) (background light)) + :background "#ddffdd" + :foreground "#22aa22") + (((class color) (background dark)) + :background "#335533" + :foreground "#ddffdd")) + "Face for lines in a diff that have been added." + :group 'magit-faces) + +(defface magit-diff-removed + '((((class color) (background light)) + :background "#ffdddd" + :foreground "#aa2222") + (((class color) (background dark)) + :background "#553333" + :foreground "#ffdddd")) + "Face for lines in a diff that have been removed." + :group 'magit-faces) + +(defface magit-diff-our + '((t :inherit magit-diff-removed)) + "Face for lines in a diff for our side in a conflict." + :group 'magit-faces) + +(defface magit-diff-base + '((((class color) (background light)) + :background "#ffffcc" + :foreground "#aaaa11") + (((class color) (background dark)) + :background "#555522" + :foreground "#ffffcc")) + "Face for lines in a diff for the base side in a conflict." + :group 'magit-faces) + +(defface magit-diff-their + '((t :inherit magit-diff-added)) + "Face for lines in a diff for their side in a conflict." + :group 'magit-faces) + +(defface magit-diff-context + '((((class color) (background light)) :foreground "grey50") + (((class color) (background dark)) :foreground "grey70")) + "Face for lines in a diff that are unchanged." + :group 'magit-faces) + +(defface magit-diff-added-highlight + '((((class color) (background light)) + :background "#cceecc" + :foreground "#22aa22") + (((class color) (background dark)) + :background "#336633" + :foreground "#cceecc")) + "Face for lines in a diff that have been added." + :group 'magit-faces) + +(defface magit-diff-removed-highlight + '((((class color) (background light)) + :background "#eecccc" + :foreground "#aa2222") + (((class color) (background dark)) + :background "#663333" + :foreground "#eecccc")) + "Face for lines in a diff that have been removed." + :group 'magit-faces) + +(defface magit-diff-our-highlight + '((t :inherit magit-diff-removed-highlight)) + "Face for lines in a diff for our side in a conflict." + :group 'magit-faces) + +(defface magit-diff-base-highlight + '((((class color) (background light)) + :background "#eeeebb" + :foreground "#aaaa11") + (((class color) (background dark)) + :background "#666622" + :foreground "#eeeebb")) + "Face for lines in a diff for the base side in a conflict." + :group 'magit-faces) + +(defface magit-diff-their-highlight + '((t :inherit magit-diff-added-highlight)) + "Face for lines in a diff for their side in a conflict." + :group 'magit-faces) + +(defface magit-diff-context-highlight + '((((class color) (background light)) + :background "grey95" + :foreground "grey50") + (((class color) (background dark)) + :background "grey20" + :foreground "grey70")) + "Face for lines in the current context in a diff." + :group 'magit-faces) + +(defface magit-diff-whitespace-warning + '((t :inherit trailing-whitespace)) + "Face for highlighting whitespace errors added lines." + :group 'magit-faces) + +(defface magit-diffstat-added + '((((class color) (background light)) :foreground "#22aa22") + (((class color) (background dark)) :foreground "#448844")) + "Face for plus sign in diffstat." + :group 'magit-faces) + +(defface magit-diffstat-removed + '((((class color) (background light)) :foreground "#aa2222") + (((class color) (background dark)) :foreground "#aa4444")) + "Face for minus sign in diffstat." + :group 'magit-faces) + +;;; Commands +;;;; Diff popups + +(defconst magit-diff-popup-common-keywords + '(:variable magit-diff-arguments + :man-page "git-diff")) + +(defconst magit-diff-popup-common-options + '((?f "Limit to files" "-- " magit-read-files) + (?u "Context lines" "-U") + (?m "Detect renames" "-M") + (?c "Detect copies" "-C") + (?a "Diff algorithm" "--diff-algorithm=" magit-diff-select-algorithm) + (?i "Ignore submodules" "--ignore-submodules=" + magit-diff-select-ignore-submodules))) + +(defconst magit-diff-popup-common-switches + '((?f "Show surrounding functions" "--function-context") + (?b "Ignore whitespace changes" "--ignore-space-change") + (?w "Ignore all whitespace" "--ignore-all-space") + (?x "Disallow external diff drivers" "--no-ext-diff"))) + +(defvar magit-diff-popup + `(,@magit-diff-popup-common-keywords + :options ,magit-diff-popup-common-options + :switches (,@magit-diff-popup-common-switches + (?s "Show stats" "--stat")) + :actions ((?d "Dwim" magit-diff-dwim) + (?u "Diff unstaged" magit-diff-unstaged) + (?c "Show commit" magit-show-commit) + (?r "Diff range" magit-diff-range) + (?s "Diff staged" magit-diff-staged) + (?t "Show stash" magit-stash-show) + (?p "Diff paths" magit-diff-paths) + (?w "Diff worktree" magit-diff-working-tree)) + :default-action magit-diff-dwim + :max-action-columns 3)) + +(defvar magit-diff-refresh-popup + `(,@magit-diff-popup-common-keywords + :options ,magit-diff-popup-common-options + :switches ,magit-diff-popup-common-switches + :actions ((?g "Refresh" magit-diff-refresh) + (?t "Toggle hunk refinement" magit-diff-toggle-refine-hunk) + (?s "Set defaults" magit-diff-set-default-arguments) + (?F "Toggle file filter" magit-diff-toggle-file-filter) + (?w "Save defaults" magit-diff-save-default-arguments)) + :max-action-columns 2)) + +(defvar magit-diff-mode-refresh-popup + `(,@magit-diff-popup-common-keywords + :options ,magit-diff-popup-common-options + :switches (,@magit-diff-popup-common-switches + (?s "Show stats" "--stat")) + :actions ((?g "Refresh" magit-diff-refresh) + (?t "Toggle hunk refinement" magit-diff-toggle-refine-hunk) + (?s "Set defaults" magit-diff-set-default-arguments) + (?r "Switch range type" magit-diff-switch-range-type) + (?w "Save defaults" magit-diff-save-default-arguments) + (?f "Flip revisions" magit-diff-flip-revs) nil + (?F "Toggle file filter" magit-diff-toggle-file-filter)) + :max-action-columns 2)) + +(defvar magit-revision-mode-refresh-popup + `(,@magit-diff-popup-common-keywords + :options ,magit-diff-popup-common-options + :switches (,@magit-diff-popup-common-switches + (?s "Show stats" "--stat")) + :actions ((?g "Refresh" magit-diff-refresh) + (?t "Toggle hunk refinement" magit-diff-toggle-refine-hunk) + (?s "Set defaults" magit-diff-set-default-arguments) + (?F "Toggle file filter" magit-diff-toggle-file-filter) + (?w "Save defaults" magit-diff-save-default-arguments)) + :max-action-columns 2)) + +(magit-define-popup-keys-deferred 'magit-diff-popup) +(magit-define-popup-keys-deferred 'magit-diff-refresh-popup) +(magit-define-popup-keys-deferred 'magit-diff-mode-refresh-popup) +(magit-define-popup-keys-deferred 'magit-revision-mode-refresh-popup) + +(defvar magit-diff-section-file-args nil) +(put 'magit-diff-section-file-args 'permanent-local t) +(put 'magit-diff-section-file-args 'safe-local-variable + (lambda (val) + (and (listp val) + (-all-p #'stringp val)))) + +(defun magit-diff-get-buffer-args () + (cond ((and magit-use-sticky-arguments + (derived-mode-p 'magit-diff-mode)) + (list (nth 2 magit-refresh-args) + (nth 3 magit-refresh-args))) + ((and (eq magit-use-sticky-arguments t) + (--when-let (magit-mode-get-buffer 'magit-diff-mode) + (with-current-buffer it + (list (nth 2 magit-refresh-args) + (nth 3 magit-refresh-args)))))) + (t + (list (default-value 'magit-diff-arguments) nil)))) + +(defun magit-diff-arguments (&optional refresh) + (cond ((memq magit-current-popup '(magit-diff-popup magit-diff-refresh-popup)) + (magit-popup-export-file-args magit-current-popup-args)) + ((and refresh (not (derived-mode-p 'magit-diff-mode))) + (list magit-diff-section-arguments + magit-diff-section-file-args)) + (t + (magit-diff-get-buffer-args)))) + +;;;###autoload +(defun magit-diff-popup (arg) + "Popup console for diff commands." + (interactive "P") + (let ((magit-diff-arguments + ;; We cannot possibly know what suffix command the user is + ;; about to invoke, so we also don't know from which buffer + ;; we should get the current values. However it is much + ;; more likely that we will end up updating the diff buffer, + ;; and we therefore use the value from that buffer. + (apply #'magit-popup-import-file-args (magit-diff-get-buffer-args)))) + (magit-invoke-popup 'magit-diff-popup nil arg))) + +;;;###autoload +(defun magit-diff-buffer-file-popup () + "Popup console for diff commands. + +This is a variant of `magit-diff-popup' which shows the same popup +but which limits the diff to the file being visited in the current +buffer." + (interactive) + (if-let ((file (magit-file-relative-name))) + (let ((magit-diff-arguments + (magit-popup-import-file-args + (if-let ((buffer (magit-mode-get-buffer 'magit-diff-mode))) + (with-current-buffer buffer + (nth 3 magit-refresh-args)) + (default-value 'magit-diff-arguments)) + (list file)))) + (magit-invoke-popup 'magit-diff-popup nil nil)) + (user-error "Buffer isn't visiting a file"))) + +(defun magit-diff-refresh-popup (arg) + "Popup console for changing diff arguments in the current buffer." + (interactive "P") + (let ((magit-diff-refresh-popup + (pcase major-mode + (`magit-revision-mode magit-revision-mode-refresh-popup) + (`magit-diff-mode magit-diff-mode-refresh-popup) + (_ magit-diff-refresh-popup))) + (magit-diff-arguments + (if (derived-mode-p 'magit-diff-mode) + (magit-popup-import-file-args (nth 2 magit-refresh-args) + (nth 3 magit-refresh-args)) + (magit-popup-import-file-args magit-diff-section-arguments + magit-diff-section-file-args)))) + (magit-invoke-popup 'magit-diff-refresh-popup nil arg))) + +(defun magit-diff-select-algorithm (&rest _ignore) + (magit-read-char-case nil t + (?d "[d]efault" "default") + (?m "[m]inimal" "minimal") + (?p "[p]atience" "patience") + (?h "[h]istogram" "histogram"))) + +(defun magit-diff-select-ignore-submodules (&rest _ignored) + (magit-read-char-case "Ignore submodules " t + (?u "[u]ntracked" "untracked") + (?d "[d]irty" "dirty") + (?a "[a]ll" "all"))) + +;;;; Diff commands + +;;;###autoload +(defun magit-diff-dwim (&optional args files) + "Show changes for the thing at point." + (interactive (magit-diff-arguments)) + (pcase (magit-diff--dwim) + (`unmerged (magit-diff-unmerged args files)) + (`unstaged (magit-diff-unstaged args files)) + (`staged + (let ((file (magit-file-at-point))) + (if (and file (equal (cddr (car (magit-file-status file))) '(?D ?U))) + ;; File was deleted by us and modified by them. Show the latter. + (magit-diff-unmerged args (list file)) + (magit-diff-staged nil args files)))) + (`(commit . ,value) + (magit-diff-range (format "%s^..%s" value value) args files)) + (`(stash . ,value) (magit-stash-show value args)) + ((and range (pred stringp)) + (magit-diff-range range args files)) + (_ + (call-interactively #'magit-diff-range)))) + +(defun magit-diff--dwim () + "Return information for performing DWIM diff. + +The information can be in three forms: +1. TYPE + A symbol describing a type of diff where no additional information + is needed to generate the diff. Currently, this includes `staged', + `unstaged' and `unmerged'. +2. (TYPE . VALUE) + Like #1 but the diff requires additional information, which is + given by VALUE. Currently, this includes `commit' and `stash', + where VALUE is the given commit or stash, respectively. +3. RANGE + A string indicating a diff range. + +If no DWIM context is found, nil is returned." + (cond + ((--when-let (magit-region-values '(commit branch) t) + (deactivate-mark) + (concat (car (last it)) ".." (car it)))) + (magit-buffer-refname + (cons 'commit magit-buffer-refname)) + ((derived-mode-p 'magit-stash-mode) + (cons 'commit + (magit-section-case + (commit (oref it value)) + (file (-> it + (oref parent) + (oref value))) + (hunk (-> it + (oref parent) + (oref parent) + (oref value)))))) + ((derived-mode-p 'magit-revision-mode) + (cons 'commit (car magit-refresh-args))) + ((derived-mode-p 'magit-diff-mode) + (nth 0 magit-refresh-args)) + (t + (magit-section-case + ([* unstaged] 'unstaged) + ([* staged] 'staged) + (unmerged 'unmerged) + (unpushed (oref it value)) + (unpulled (oref it value)) + (branch (let ((current (magit-get-current-branch)) + (atpoint (oref it value))) + (if (equal atpoint current) + (--if-let (magit-get-upstream-branch) + (format "%s...%s" it current) + (if (magit-anything-modified-p) + current + (cons 'commit current))) + (format "%s...%s" + (or current "HEAD") + atpoint)))) + (commit (cons 'commit (oref it value))) + (stash (cons 'stash (oref it value))))))) + +(defun magit-diff-read-range-or-commit (prompt &optional secondary-default mbase) + "Read range or revision with special diff range treatment. +If MBASE is non-nil, prompt for which rev to place at the end of +a \"revA...revB\" range. Otherwise, always construct +\"revA..revB\" range." + (--if-let (magit-region-values '(commit branch) t) + (let ((revA (car (last it))) + (revB (car it))) + (deactivate-mark) + (if mbase + (let ((base (magit-git-string "merge-base" revA revB))) + (cond + ((string= (magit-rev-parse revA) base) + (format "%s..%s" revA revB)) + ((string= (magit-rev-parse revB) base) + (format "%s..%s" revB revA)) + (t + (let ((main (magit-completing-read "View changes along" + (list revA revB) + nil t nil nil revB))) + (format "%s...%s" + (if (string= main revB) revA revB) main))))) + (format "%s..%s" revA revB))) + (magit-read-range prompt + (or (pcase (magit-diff--dwim) + (`(commit . ,value) + (format "%s^..%s" value value)) + ((and range (pred stringp)) + range)) + secondary-default + (magit-get-current-branch))))) + +(defun magit-diff-setup (rev-or-range const args files) + (require 'magit) + (magit-mode-setup #'magit-diff-mode rev-or-range const args files)) + +;;;###autoload +(defun magit-diff-range (rev-or-range &optional args files) + "Show differences between two commits. + +REV-OR-RANGE should be a range or a single revision. If it is a +revision, then show changes in the working tree relative to that +revision. If it is a range, but one side is omitted, then show +changes relative to `HEAD'. + +If the region is active, use the revisions on the first and last +line of the region as the two sides of the range. With a prefix +argument, instead of diffing the revisions, choose a revision to +view changes along, starting at the common ancestor of both +revisions (i.e., use a \"...\" range)." + (interactive (cons (magit-diff-read-range-or-commit "Diff for range" + nil current-prefix-arg) + (magit-diff-arguments))) + (magit-diff-setup rev-or-range nil args files)) + +;;;###autoload +(defun magit-diff-working-tree (&optional rev args files) + "Show changes between the current working tree and the `HEAD' commit. +With a prefix argument show changes between the working tree and +a commit read from the minibuffer." + (interactive + (cons (and current-prefix-arg + (magit-read-branch-or-commit "Diff working tree and commit")) + (magit-diff-arguments))) + (magit-diff-setup (or rev "HEAD") nil args files)) + +;;;###autoload +(defun magit-diff-staged (&optional rev args files) + "Show changes between the index and the `HEAD' commit. +With a prefix argument show changes between the index and +a commit read from the minibuffer." + (interactive + (cons (and current-prefix-arg + (magit-read-branch-or-commit "Diff index and commit")) + (magit-diff-arguments))) + (magit-diff-setup rev (list "--cached") args files)) + +;;;###autoload +(defun magit-diff-unstaged (&optional args files) + "Show changes between the working tree and the index." + (interactive (magit-diff-arguments)) + (magit-diff-setup nil nil args files)) + +;;;###autoload +(defun magit-diff-unmerged (&optional args files) + "Show changes that are being merged." + (interactive (magit-diff-arguments)) + (unless (magit-merge-in-progress-p) + (user-error "No merge is in progress")) + (magit-diff-setup (magit--merge-range) nil args files)) + +;;;###autoload +(defun magit-diff-while-committing (&optional args) + "While committing, show the changes that are about to be committed. +While amending, invoking the command again toggles between +showing just the new changes or all the changes that will +be committed." + (interactive (list (car (magit-diff-arguments)))) + (unless (magit-commit-message-buffer) + (user-error "No commit in progress")) + (let ((magit-display-buffer-noselect t) + (diff-buf (magit-mode-get-buffer 'magit-diff-mode))) + (if (and diff-buf + (get-buffer-window diff-buf)) + (with-current-buffer diff-buf + (pcase-let ((`(,rev ,arg . ,_) magit-refresh-args)) + (cond ((and (equal rev "HEAD^") + (equal arg '("--cached"))) + (magit-diff-staged nil args)) + ((and (equal rev nil) + (equal arg '("--cached"))) + (magit-diff-while-amending args)) + ((magit-anything-staged-p) + (magit-diff-staged nil args)) + (t + (magit-diff-while-amending args))))) + (if (magit-anything-staged-p) + (magit-diff-staged nil args) + (magit-diff-while-amending args))))) + +(define-key git-commit-mode-map + (kbd "C-c C-d") 'magit-diff-while-committing) + +(defun magit-diff-while-amending (&optional args) + (magit-diff-setup "HEAD^" (list "--cached") args nil)) + +;;;###autoload +(defun magit-diff-buffer-file () + "Show diff for the blob or file visited in the current buffer." + (interactive) + (require 'magit) + (if-let ((file (magit-file-relative-name))) + (magit-mode-setup-internal #'magit-diff-mode + (list (or magit-buffer-refname + (magit-get-current-branch) + "HEAD") + nil + (cadr (magit-diff-arguments)) + (list file)) + magit-diff-buffer-file-locked) + (user-error "Buffer isn't visiting a file"))) + +;;;###autoload +(defun magit-diff-paths (a b) + "Show changes between any two files on disk." + (interactive (list (read-file-name "First file: " nil nil t) + (read-file-name "Second file: " nil nil t))) + (magit-diff-setup nil (list "--no-index") + nil (list (magit-convert-filename-for-git + (expand-file-name a)) + (magit-convert-filename-for-git + (expand-file-name b))))) + +(defvar-local magit-buffer-revision-hash nil) + +(defun magit-show-commit--arguments () + (pcase-let ((`(,args ,diff-files) (magit-diff-arguments))) + (list args (if (derived-mode-p 'magit-log-mode) + (and (not (member "--follow" (nth 1 magit-refresh-args))) + (nth 2 magit-refresh-args)) + diff-files)))) + +;;;###autoload +(defun magit-show-commit (rev &optional args files module) + "Visit the revision at point in another buffer. +If there is no revision at point or with a prefix argument prompt +for a revision." + (interactive + (pcase-let* ((mcommit (magit-section-value-if 'module-commit)) + (atpoint (or (and (bound-and-true-p magit-blame-mode) + (oref (magit-current-blame-chunk) orig-rev)) + mcommit + (magit-branch-or-commit-at-point))) + (`(,args ,files) (magit-show-commit--arguments))) + (list (or (and (not current-prefix-arg) atpoint) + (magit-read-branch-or-commit "Show commit" atpoint)) + args + files + (and mcommit + (magit-section-parent-value (magit-current-section)))))) + (require 'magit) + (magit-with-toplevel + (when module + (setq default-directory + (expand-file-name (file-name-as-directory module)))) + (unless (magit-rev-verify-commit rev) + (user-error "%s is not a commit" rev)) + (magit-mode-setup #'magit-revision-mode rev nil args files))) + +;;;; Setting commands + +(defun magit-diff-refresh (args files) + "Set the local diff arguments for the current buffer." + (interactive (magit-diff-arguments t)) + (cond ((derived-mode-p 'magit-diff-mode) + (setcdr (cdr magit-refresh-args) (list args files))) + (t + (setq-local magit-diff-section-arguments args) + (setq-local magit-diff-section-file-args files))) + (magit-refresh)) + +(defun magit-diff-set-default-arguments (args files) + "Set the global diff arguments for the current buffer." + (interactive (magit-diff-arguments t)) + (cond ((derived-mode-p 'magit-diff-mode) + (customize-set-variable 'magit-diff-arguments args) + (setcdr (cdr magit-refresh-args) (list args files))) + (t + (customize-set-variable 'magit-diff-section-arguments args) + (kill-local-variable 'magit-diff-section-arguments) + (kill-local-variable 'magit-diff-section-file-args))) + (magit-refresh)) + +(defun magit-diff-save-default-arguments (args files) + "Set and save the global diff arguments for the current buffer." + (interactive (magit-diff-arguments t)) + (cond ((derived-mode-p 'magit-diff-mode) + (customize-save-variable 'magit-diff-arguments args) + (setcdr (cdr magit-refresh-args) (list args files))) + (t + (customize-save-variable 'magit-diff-section-arguments args) + (kill-local-variable 'magit-diff-section-arguments) + (kill-local-variable 'magit-diff-section-file-args))) + (magit-refresh)) + +(defun magit-diff-switch-range-type () + "Convert diff range type. +Change \"revA..revB\" to \"revB...revA\", or vice versa." + (interactive) + (let ((range (car magit-refresh-args))) + (if (and range + (derived-mode-p 'magit-diff-mode) + (string-match magit-range-re range)) + (progn + (setcar magit-refresh-args + (concat (match-string 1 range) + (if (string= (match-string 2 range) "..") + "..." + "..") + (match-string 3 range))) + (magit-refresh)) + (user-error "No range to change")))) + +(defun magit-diff-flip-revs () + "Swap revisions in diff range. +Change \"revA..revB\" to \"revB..revA\"." + (interactive) + (let ((range (car magit-refresh-args))) + (if (and range + (derived-mode-p 'magit-diff-mode) + (string-match magit-range-re range)) + (progn + (setcar magit-refresh-args + (concat (match-string 3 range) + (match-string 2 range) + (match-string 1 range))) + (magit-refresh)) + (user-error "No range to swap")))) + +(defvar-local magit-diff--last-file-args nil) +(defun magit-diff--toggle-file-args (files) + (cond (files + (setq magit-diff--last-file-args files) + nil) + (magit-diff--last-file-args) + (t + (user-error "No diff file filter to toggle")))) + +(defun magit-diff-toggle-file-filter () + "Toggle the file restriction of the current buffer's diffs. +If the current buffer's mode is derived from `magit-log-mode', +toggle the file restriction in the repository's revision buffer +instead." + (interactive) + (--if-let (and (derived-mode-p 'magit-log-mode) + (magit-mode-get-buffer 'magit-revision-mode)) + (with-current-buffer it + (setf (nth 3 magit-refresh-args) + (magit-diff--toggle-file-args (nth 3 magit-refresh-args))) + (magit-refresh)) + (if (derived-mode-p 'magit-diff-mode) + (setf (nth 3 magit-refresh-args) + (magit-diff--toggle-file-args (nth 3 magit-refresh-args))) + (setq-local magit-diff-section-file-args + (magit-diff--toggle-file-args magit-diff-section-file-args))) + (magit-refresh))) + +(defun magit-diff-less-context (&optional count) + "Decrease the context for diff hunks by COUNT lines." + (interactive "p") + (magit-diff-set-context `(lambda (cur) (max 0 (- (or cur 0) ,count))))) + +(defun magit-diff-more-context (&optional count) + "Increase the context for diff hunks by COUNT lines." + (interactive "p") + (magit-diff-set-context `(lambda (cur) (+ (or cur 0) ,count)))) + +(defun magit-diff-default-context () + "Reset context for diff hunks to the default height." + (interactive) + (magit-diff-set-context #'ignore)) + +(defun magit-diff-set-context (fn) + (let* ((def (--if-let (magit-get "diff.context") (string-to-number it) 3)) + (val (car (magit-diff-arguments t))) + (arg (--first (string-match "^-U\\([0-9]+\\)?$" it) val)) + (num (--if-let (and arg (match-string 1 arg)) (string-to-number it) def)) + (val (delete arg val)) + (num (funcall fn num)) + (arg (and num (not (= num def)) (format "-U%i" num))) + (val (if arg (cons arg val) val))) + (if (derived-mode-p 'magit-diff-mode) + (setcar (cddr magit-refresh-args) val) + (setq magit-diff-section-arguments val))) + (magit-refresh)) + +(defun magit-diff-context-p () + (--if-let (--first (string-match "^-U\\([0-9]+\\)$" it) + (car (magit-diff-arguments t))) + (not (equal "-U0" it)) + t)) + +(defun magit-diff-ignore-any-space-p () + (let ((args (car (magit-diff-arguments t)))) + (--any-p (member it args) + '("--ignore-cr-at-eol" + "--ignore-space-at-eol" + "--ignore-space-change" "-b" + "--ignore-all-space" "-w" + "--ignore-blank-space")))) + +(defun magit-diff-toggle-refine-hunk (&optional style) + "Turn diff-hunk refining on or off. + +If hunk refining is currently on, then hunk refining is turned off. +If hunk refining is off, then hunk refining is turned on, in +`selected' mode (only the currently selected hunk is refined). + +With a prefix argument, the \"third choice\" is used instead: +If hunk refining is currently on, then refining is kept on, but +the refining mode (`selected' or `all') is switched. +If hunk refining is off, then hunk refining is turned on, in +`all' mode (all hunks refined). + +Customize variable `magit-diff-refine-hunk' to change the default mode." + (interactive "P") + (setq-local magit-diff-refine-hunk + (if style + (if (eq magit-diff-refine-hunk 'all) t 'all) + (not magit-diff-refine-hunk))) + (magit-diff-update-hunk-refinement)) + +;;;; Visit commands + +(defun magit-diff-visit-file + (file &optional other-window force-worktree display-fn) + "From a diff, visit the corresponding file at the appropriate position. + +If the diff shows changes in the worktree, the index, or `HEAD', +then visit the actual file. Otherwise, when the diff is about an +older commit or a range, then visit the appropriate blob. + +If point is on a removed line, then visit the blob for the first +parent of the commit which removed that line, i.e. the last +commit where that line still existed. Otherwise visit the blob +for the commit whose changes are being shown. + +Interactively, when the file or blob to be displayed is already +being displayed in another window of the same frame, then just +select that window and adjust point. Otherwise, or with a prefix +argument, display the buffer in another window. The meaning of +the prefix argument can be inverted or further modified using the +option `magit-display-file-buffer-function'. + +Non-interactively the optional OTHER-WINDOW argument is taken +literally. DISPLAY-FN can be used to specify the display +function explicitly, in which case OTHER-WINDOW is ignored. + +The optional FORCE-WORKTREE means to force visiting the worktree +version of the file. To do this interactively use the command +`magit-diff-visit-file-worktree' instead." + (interactive (list (--if-let (magit-file-at-point) + (expand-file-name it) + (user-error "No file at point")) + current-prefix-arg)) + (if (magit-file-accessible-directory-p file) + (magit-diff-visit-directory file other-window) + (let* ((hunk (magit-diff-visit--hunk)) + (last (and magit-diff-visit-previous-blob + (not force-worktree) + (magit-section-match 'hunk) + (save-excursion + (goto-char (line-beginning-position)) + (looking-at "-")))) + (line (and hunk (magit-diff-hunk-line hunk))) + (col (and hunk (magit-diff-hunk-column hunk last))) + (rev (if last + (magit-diff-visit--range-beginning) + (magit-diff-visit--range-end))) + (buf (if (and (not force-worktree) + (stringp rev)) + (magit-find-file-noselect rev file) + (or (get-file-buffer file) + (find-file-noselect file))))) + (cond ((called-interactively-p 'any) + (magit-display-file-buffer buf)) + (display-fn + (funcall display-fn buf)) + ((or other-window (get-buffer-window buf)) + (switch-to-buffer-other-window buf)) + (t + (pop-to-buffer buf))) + (with-selected-window + (or (get-buffer-window buf 'visible) + (error "File buffer is not visible")) + (when line + (setq line + (cond ((eq rev 'staged) + (apply 'magit-diff-visit--offset file nil line)) + ((and force-worktree + (stringp rev)) + (apply 'magit-diff-visit--offset file rev line)) + (t + (apply '+ line)))) + (let ((pos (save-restriction + (widen) + (goto-char (point-min)) + (forward-line (1- line)) + (move-to-column col) + (point)))) + (unless (<= (point-min) pos (point-max)) + (widen) + (goto-char pos)))) + (when (magit-anything-unmerged-p file) + (smerge-start-session)) + (run-hooks 'magit-diff-visit-file-hook))))) + +(defun magit-diff-visit-file-other-window (file) + "From a diff, visit the corresponding file at the appropriate position. +The file is shown in another window. + +If the diff shows changes in the worktree, the index, or `HEAD', +then visit the actual file. Otherwise, when the diff is about an +older commit or a range, then visit the appropriate blob. + +If point is on a removed line, then visit the blob for the first +parent of the commit which removed that line, i.e. the last +commit where that line still existed. Otherwise visit the blob +for the commit whose changes are being shown." + (interactive (list (--if-let (magit-file-at-point) + (expand-file-name it) + (user-error "No file at point")))) + (magit-diff-visit-file file t)) + +(defvar magit-display-file-buffer-function + 'magit-display-file-buffer-traditional + "The function used by `magit-diff-visit-file' to display blob buffers. + +Other commands such as `magit-find-file' do not use this +function. Instead they use high-level functions to select the +window to be used to display the buffer. This variable and the +related functions are an experimental feature and should be +treated as such.") + +(defun magit-display-file-buffer (buffer) + (funcall magit-display-file-buffer-function buffer)) + +(defun magit-display-file-buffer-traditional (buffer) + "Display BUFFER in the current window. +With a prefix argument display it in another window. +Option `magit-display-file-buffer-function' controls +whether `magit-diff-visit-file' uses this function." + (if (or current-prefix-arg (get-buffer-window buffer)) + (pop-to-buffer buffer) + (switch-to-buffer buffer))) + +(defun magit-display-file-buffer-other-window (buffer) + "Display BUFFER in another window. +With a prefix argument display it in the current window. +Option `magit-display-file-buffer-function' controls +whether `magit-diff-visit-file' uses this function." + (if current-prefix-arg + (switch-to-buffer buffer) + (pop-to-buffer buffer))) + +(defun magit-diff-visit-file-worktree (file &optional other-window) + "From a diff, visit the corresponding file at the appropriate position. + +When the file is already being displayed in another window of the +same frame, then just select that window and adjust point. With +a prefix argument also display in another window. + +The actual file in the worktree is visited. The positions in the +hunk headers get less useful the \"older\" the changes are, and +as a result, jumping to the appropriate position gets less +reliable. + +Also see `magit-diff-visit-file' which visits the respective +blob, unless the diff shows changes in the worktree, the index, +or `HEAD'." + (interactive (list (or (magit-file-at-point) + (user-error "No file at point")) + current-prefix-arg)) + (magit-diff-visit-file file other-window t)) + +(defun magit-diff-visit--range-end () + (let ((rev (magit-diff--dwim))) + (if (symbolp rev) + rev + (setq rev (if (consp rev) + (cdr rev) + (cdr (magit-split-range rev)))) + (if (magit-rev-head-p rev) + 'unstaged + rev)))) + +(defun magit-diff-visit--range-beginning () + (let ((rev (magit-diff--dwim))) + (cond ((consp rev) + (concat (cdr rev) "^")) + ((stringp rev) + (car (magit-split-range rev))) + (t + rev)))) + +(defun magit-diff-visit--hunk () + (when-let ((scope (magit-diff-scope))) + (let ((section (magit-current-section))) + (cl-case scope + ((file files) + (setq section (car (oref section children)))) + (list + (setq section (car (oref section children))) + (when section + (setq section (car (oref section children)))))) + (and + ;; Unmerged files appear in the list of staged changes + ;; but unlike in the list of unstaged changes no diffs + ;; are shown here. In that case `section' is nil. + section + ;; Currently the `hunk' type is also abused for file + ;; mode changes, which we are not interested in here. + ;; Such sections have no value. + (oref section value) + section)))) + +(defun magit-diff-visit--offset (file rev hunk-start line-offset) + (let ((offset 0)) + (with-temp-buffer + (save-excursion + (magit-with-toplevel + (magit-git-insert "diff" rev "--" file))) + (catch 'found + (while (re-search-forward + "^@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@" + nil t) + (let* ((abeg (string-to-number (match-string 1))) + (alen (string-to-number (match-string 2))) + (bbeg (string-to-number (match-string 3))) + (blen (string-to-number (match-string 4))) + (aend (+ abeg alen)) + (bend (+ bbeg blen)) + (hend (+ hunk-start line-offset))) + (if (<= abeg hunk-start) + (if (or (>= aend hend) + (>= bend hend)) + (let ((line 0)) + (while (<= line alen) + (forward-line 1) + (cl-incf line) + (cond ((looking-at "^\\+") (cl-incf offset)) + ((looking-at "^-") (cl-decf offset))))) + (cl-incf offset (- blen alen))) + (throw 'found nil)))))) + (+ hunk-start line-offset offset))) + +(defun magit-diff-hunk-line (section) + (let* ((value (oref section value)) + (prefix (- (length value) 2)) + (cpos (marker-position (oref section content))) + (stop (line-number-at-pos)) + (cstart (save-excursion (goto-char cpos) + (line-number-at-pos))) + (prior (and (= (length value) 3) + (save-excursion (goto-char (line-beginning-position)) + (looking-at "-")))) + (offset 0) + (line (if prior + (cadr value) + (car (last value))))) + (string-match (format "^%s\\([0-9]+\\)" (if prior "-" "\\+")) line) + (setq line (string-to-number (match-string 1 line))) + (when (> cstart stop) + (save-excursion + (goto-char cpos) + (re-search-forward "^[-+]") + (setq stop (line-number-at-pos)))) + (save-excursion + (goto-char cpos) + (while (< (line-number-at-pos) stop) + (unless (string-match-p + (if prior "\\+" "-") + (buffer-substring (point) (+ (point) prefix))) + (cl-incf offset)) + (forward-line))) + (list line offset))) + +(defun magit-diff-hunk-column (section visit-beginning) + (if (or (< (point) + (oref section content)) + (and (not visit-beginning) + (save-excursion (beginning-of-line) (looking-at-p "-")))) + 0 + (max 0 (- (+ (current-column) 2) + (length (oref section value)))))) + +(defun magit-diff-visit-directory (directory &optional other-window) + (if (equal (magit-toplevel directory) + (magit-toplevel)) + (dired-jump other-window (concat directory "/.")) + (let ((display-buffer-overriding-action + (if other-window + '(nil (inhibit-same-window t)) + '(display-buffer-same-window)))) + (magit-status-internal directory)))) + +;;;; Scroll commands + +(defun magit-diff-show-or-scroll-up () + "Update the commit or diff buffer for the thing at point. + +Either show the commit or stash at point in the appropriate +buffer, or if that buffer is already being displayed in the +current frame and contains information about that commit or +stash, then instead scroll the buffer up. If there is no +commit or stash at point, then prompt for a commit." + (interactive) + (magit-diff-show-or-scroll 'scroll-up)) + +(defun magit-diff-show-or-scroll-down () + "Update the commit or diff buffer for the thing at point. + +Either show the commit or stash at point in the appropriate +buffer, or if that buffer is already being displayed in the +current frame and contains information about that commit or +stash, then instead scroll the buffer down. If there is no +commit or stash at point, then prompt for a commit." + (interactive) + (magit-diff-show-or-scroll 'scroll-down)) + +(defun magit-diff-show-or-scroll (fn) + (let (rev cmd buf win) + (cond + (magit-blame-mode + (setq rev (oref (magit-current-blame-chunk) orig-rev)) + (setq cmd 'magit-show-commit) + (setq buf (magit-mode-get-buffer 'magit-revision-mode))) + ((derived-mode-p 'git-rebase-mode) + (save-excursion + (goto-char (line-beginning-position)) + (--if-let (and git-rebase-line + (looking-at git-rebase-line) + (match-string 2)) + (progn (setq rev it) + (setq cmd 'magit-show-commit) + (setq buf (magit-mode-get-buffer 'magit-revision-mode))) + (user-error "No commit on this line")))) + (t + (magit-section-case + (branch + (setq rev (magit-ref-maybe-qualify (oref it value))) + (setq cmd 'magit-show-commit) + (setq buf (magit-mode-get-buffer 'magit-revision-mode))) + (commit + (setq rev (oref it value)) + (setq cmd 'magit-show-commit) + (setq buf (magit-mode-get-buffer 'magit-revision-mode))) + (stash + (setq rev (oref it value)) + (setq cmd 'magit-stash-show) + (setq buf (magit-mode-get-buffer 'magit-stash-mode)))))) + (if rev + (if (and buf + (setq win (get-buffer-window buf)) + (with-current-buffer buf + (and (equal rev (car magit-refresh-args)) + (equal (magit-rev-parse rev) + magit-buffer-revision-hash)))) + (with-selected-window win + (condition-case nil + (funcall fn) + (error + (goto-char (pcase fn + (`scroll-up (point-min)) + (`scroll-down (point-max))))))) + (let ((magit-display-buffer-noselect t)) + (if (eq cmd 'magit-show-commit) + (apply #'magit-show-commit rev (magit-show-commit--arguments)) + (funcall cmd rev)))) + (call-interactively #'magit-show-commit)))) + +;;; Diff Mode + +(defvar magit-diff-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-mode-map) + (define-key map "\C-c\C-d" 'magit-diff-while-committing) + (define-key map "\C-c\C-b" 'magit-go-backward) + (define-key map "\C-c\C-f" 'magit-go-forward) + (define-key map "\s" 'scroll-up) + (define-key map "\d" 'scroll-down) + (define-key map "j" 'magit-jump-to-diffstat-or-diff) + (define-key map [remap write-file] 'magit-patch-save) + map) + "Keymap for `magit-diff-mode'.") + +(define-derived-mode magit-diff-mode magit-mode "Magit Diff" + "Mode for looking at a Git diff. + +This mode is documented in info node `(magit)Diff Buffer'. + +\\\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-section-toggle] to expand or hide the section at point. +Type \\[magit-visit-thing] to visit the hunk or file at point. + +Staging and applying changes is documented in info node +`(magit)Staging and Unstaging' and info node `(magit)Applying'. + +\\Type \ +\\[magit-apply] to apply the change at point, \ +\\[magit-stage] to stage, +\\[magit-unstage] to unstage, \ +\\[magit-discard] to discard, or \ +\\[magit-reverse] to reverse it. + +\\{magit-diff-mode-map}" + :group 'magit-diff + (hack-dir-local-variables-non-file-buffer) + (setq imenu-prev-index-position-function + 'magit-imenu--diff-prev-index-position-function) + (setq imenu-extract-index-name-function + 'magit-imenu--diff-extract-index-name-function) + (setq-local bookmark-make-record-function + 'magit-bookmark--diff-make-record)) + +(defun magit-diff-refresh-buffer (rev-or-range const _args files) + "Refresh the current `magit-diff-mode' buffer. + +In such buffers the buffer-local value of `magit-refresh-args' +has the same form as the arguments of this function. The value +is set in `magit-mode-setup'." + (magit-set-header-line-format + (if (member "--no-index" const) + (apply #'format "Differences between %s and %s" files) + (concat (if rev-or-range + (if (string-match-p "\\(\\.\\.\\|\\^-\\)" + rev-or-range) + (format "Changes in %s" rev-or-range) + (format "Changes from %s to working tree" rev-or-range)) + (if (member "--cached" const) + "Staged changes" + "Unstaged changes")) + (pcase (length files) + (0) + (1 (concat " in file " (car files))) + (_ (concat " in files " + (mapconcat #'identity files ", "))))))) + (magit-insert-section (diffbuf) + (magit-run-section-hook 'magit-diff-sections-hook rev-or-range))) + +(defun magit-insert-diff (rev-or-range) + "Insert the diff into this `magit-diff-mode' buffer." + (let ((magit-git-global-arguments + (remove "--literal-pathspecs" magit-git-global-arguments))) + (magit-git-wash #'magit-diff-wash-diffs + "diff" rev-or-range "-p" "--no-prefix" + (and (member "--stat" (nth 2 magit-refresh-args)) "--numstat") + (nth 1 magit-refresh-args) + (nth 2 magit-refresh-args) "--" + (nth 3 magit-refresh-args)))) + +(defvar magit-file-section-map + (let ((map (make-sparse-keymap))) + (unless (featurep 'jkl) + (define-key map (kbd "C-j") 'magit-diff-visit-file-worktree)) + (define-key map [C-return] 'magit-diff-visit-file-worktree) + (define-key map [remap magit-visit-thing] 'magit-diff-visit-file) + (define-key map [remap magit-delete-thing] 'magit-discard) + (define-key map [remap magit-revert-no-commit] 'magit-reverse) + (define-key map "a" 'magit-apply) + (define-key map "C" 'magit-commit-add-log) + (define-key map "s" 'magit-stage) + (define-key map "u" 'magit-unstage) + (define-key map "&" 'magit-do-async-shell-command) + (define-key map "\C-c\C-t" 'magit-diff-trace-definition) + (define-key map "\C-c\C-e" 'magit-diff-edit-hunk-commit) + map) + "Keymap for `file' sections.") + +(defvar magit-hunk-section-map + (let ((map (make-sparse-keymap))) + (unless (featurep 'jkl) + (define-key map (kbd "C-j") 'magit-diff-visit-file-worktree)) + (define-key map [C-return] 'magit-diff-visit-file-worktree) + (define-key map [remap magit-visit-thing] 'magit-diff-visit-file) + (define-key map [remap magit-delete-thing] 'magit-discard) + (define-key map [remap magit-revert-no-commit] 'magit-reverse) + (define-key map "a" 'magit-apply) + (define-key map "C" 'magit-commit-add-log) + (define-key map "s" 'magit-stage) + (define-key map "u" 'magit-unstage) + (define-key map "&" 'magit-do-async-shell-command) + (define-key map "\C-c\C-t" 'magit-diff-trace-definition) + (define-key map "\C-c\C-e" 'magit-diff-edit-hunk-commit) + map) + "Keymap for `hunk' sections.") + +(defconst magit-diff-headline-re + (concat "^\\(@@@?\\|diff\\|Submodule\\|" + "\\* Unmerged path\\|merged\\|changed in both\\|" + "added in remote\\|removed in remote\\)")) + +(defconst magit-diff-statline-re + (concat "^ ?" + "\\(.*\\)" ; file + "\\( +| +\\)" ; separator + "\\([0-9]+\\|Bin\\(?: +[0-9]+ -> [0-9]+ bytes\\)?$\\) ?" + "\\(\\+*\\)" ; add + "\\(-*\\)$")) ; del + +(defun magit-diff-wash-diffs (args &optional limit) + (when (member "--stat" args) + (magit-diff-wash-diffstat)) + (when (re-search-forward magit-diff-headline-re limit t) + (goto-char (line-beginning-position)) + (magit-wash-sequence (apply-partially 'magit-diff-wash-diff args)) + (insert ?\n))) + +(defun magit-jump-to-diffstat-or-diff () + "Jump to the diffstat or diff. +When point is on a file inside the diffstat section, then jump +to the respective diff section, otherwise jump to the diffstat +section or a child thereof." + (interactive) + (--if-let (magit-get-section + (append (magit-section-case + ([file diffstat] `((file . ,(oref it value)))) + (file `((file . ,(oref it value)) (diffstat))) + (t '((diffstat)))) + (magit-section-ident magit-root-section))) + (magit-section-goto it) + (user-error "No diffstat in this buffer"))) + +(defun magit-diff-wash-diffstat () + (let (heading (beg (point))) + (when (re-search-forward "^ ?\\([0-9]+ +files? change[^\n]*\n\\)" nil t) + (setq heading (match-string 1)) + (magit-delete-match) + (goto-char beg) + (magit-insert-section (diffstat) + (insert (propertize heading 'face 'magit-diff-file-heading)) + (magit-insert-heading) + (let (files) + (while (looking-at "^[-0-9]+\t[-0-9]+\t\\(.+\\)$") + (push (magit-decode-git-path + (let ((f (match-string 1))) + (if (string-match " => " f) + (substring f (match-end 0)) + f))) + files) + (magit-delete-line)) + (setq files (nreverse files)) + (while (looking-at magit-diff-statline-re) + (magit-bind-match-strings (file sep cnt add del) nil + (magit-delete-line) + (when (string-match " +$" file) + (setq sep (concat (match-string 0 file) sep)) + (setq file (substring file 0 (match-beginning 0)))) + (let ((le (length file)) ld) + (setq file (magit-decode-git-path file)) + (setq ld (length file)) + (when (> le ld) + (setq sep (concat (make-string (- le ld) ?\s) sep)))) + (magit-insert-section (file (pop files)) + (insert (propertize file 'face 'magit-filename) sep cnt " ") + (when add + (insert (propertize add 'face 'magit-diffstat-added))) + (when del + (insert (propertize del 'face 'magit-diffstat-removed))) + (insert "\n"))))) + (if (looking-at "^$") (forward-line) (insert "\n")))))) + +(defun magit-diff-wash-diff (args) + (cond + ((looking-at "^Submodule") + (magit-diff-wash-submodule)) + ((looking-at "^\\* Unmerged path \\(.*\\)") + (let ((file (magit-decode-git-path (match-string 1)))) + (magit-delete-line) + (unless (and (derived-mode-p 'magit-status-mode) + (not (member "--cached" args))) + (magit-insert-section (file file) + (insert (propertize + (format "unmerged %s%s" file + (pcase (cddr (car (magit-file-status file))) + (`(?D ?D) " (both deleted)") + (`(?D ?U) " (deleted by us)") + (`(?U ?D) " (deleted by them)") + (`(?A ?A) " (both added)") + (`(?A ?U) " (added by us)") + (`(?U ?A) " (added by them)") + (`(?U ?U) ""))) + 'face 'magit-diff-file-heading)) + (insert ?\n)))) + t) + ((looking-at (concat "^\\(merged\\|changed in both\\|" + "added in remote\\|removed in remote\\)")) + (let ((status (pcase (match-string 1) + ("merged" "merged") + ("changed in both" "conflict") + ("added in remote" "new file") + ("removed in remote" "deleted"))) + file orig base modes) + (magit-delete-line) + (while (looking-at + "^ \\([^ ]+\\) +[0-9]\\{6\\} \\([a-z0-9]\\{40\\}\\) \\(.+\\)$") + (magit-bind-match-strings (side _blob name) nil + (pcase side + ("result" (setq file name)) + ("our" (setq orig name)) + ("their" (setq file name)) + ("base" (setq base name)))) + (magit-delete-line)) + (when orig (setq orig (magit-decode-git-path orig))) + (when file (setq file (magit-decode-git-path file))) + (magit-diff-insert-file-section (or file base) orig status modes nil))) + ((looking-at + "^diff --\\(?:\\(git\\) \\(?:\\(.+?\\) \\2\\)?\\|\\(cc\\|combined\\) \\(.+\\)\\)") + (let ((status (cond ((equal (match-string 1) "git") "modified") + ((derived-mode-p 'magit-revision-mode) "resolved") + (t "unmerged"))) + (file (or (match-string 2) (match-string 4))) + (beg (point)) + orig header modes) + (save-excursion + (forward-line 1) + (setq header (buffer-substring + beg (if (re-search-forward magit-diff-headline-re nil t) + (match-beginning 0) + (point-max))))) + (magit-delete-line) + (while (not (or (eobp) (looking-at magit-diff-headline-re))) + (if (looking-at "^old mode \\([^\n]+\\)\nnew mode \\([^\n]+\\)\n") + (progn (setq modes (match-string 0)) + (magit-delete-match)) + (cond + ((looking-at "^--- \\([^/].*?\\)\t?$") ; i.e. not /dev/null + (setq orig (match-string 1))) + ((looking-at "^\\+\\+\\+ \\([^/].*?\\)\t?$") + (setq file (match-string 1))) + ((looking-at "^\\(copy\\|rename\\) from \\(.+\\)$") + (setq orig (match-string 2))) + ((looking-at "^\\(copy\\|rename\\) to \\(.+\\)$") + (setq file (match-string 2)) + (setq status (if (equal (match-string 1) "copy") "new file" "renamed"))) + ((looking-at "^\\(new file\\|deleted\\)") + (setq status (match-string 1)))) + (magit-delete-line))) + (when orig + (setq orig (magit-decode-git-path orig))) + (setq file (magit-decode-git-path file)) + ;; KLUDGE `git-log' ignores `--no-prefix' when `-L' is used. + (when (and (derived-mode-p 'magit-log-mode) + (--first (string-match-p "\\`-L" it) + (nth 1 magit-refresh-args))) + (setq file (substring file 2)) + (when orig + (setq orig (substring orig 2)))) + (magit-diff-insert-file-section file orig status modes header))))) + +(defun magit-diff-insert-file-section (file orig status modes header) + (magit-insert-section section + (file file (or (equal status "deleted") + (derived-mode-p 'magit-status-mode))) + (insert (propertize (format "%-10s %s\n" status + (if (or (not orig) (equal orig file)) + file + (format "%s -> %s" orig file))) + 'face 'magit-diff-file-heading)) + (magit-insert-heading) + (unless (equal orig file) + (oset section source orig)) + (oset section header header) + (when modes + (magit-insert-section (hunk) + (insert modes))) + (magit-wash-sequence #'magit-diff-wash-hunk))) + +(defun magit-diff-wash-submodule () + ;; See `show_submodule_summary' in submodule.c and "this" commit. + (when (looking-at "^Submodule \\([^ ]+\\)") + (let ((module (match-string 1)) + untracked modified) + (when (looking-at "^Submodule [^ ]+ contains untracked content$") + (magit-delete-line) + (setq untracked t)) + (when (looking-at "^Submodule [^ ]+ contains modified content$") + (magit-delete-line) + (setq modified t)) + (cond + ((and (looking-at "^Submodule \\([^ ]+\\) \\([^ :]+\\)\\( (rewind)\\)?:$") + (equal (match-string 1) module)) + (magit-bind-match-strings (_module range rewind) nil + (magit-delete-line) + (while (looking-at "^ \\([<>]\\) \\(.+\\)$") + (magit-delete-line)) + (when rewind + (setq range (replace-regexp-in-string "[^.]\\(\\.\\.\\)[^.]" + "..." range t t 1))) + (magit-insert-section (magit-module-section module t) + (magit-insert-heading + (propertize (concat "modified " module) + 'face 'magit-diff-file-heading) + " (" + (cond (rewind "rewind") + ((string-match-p "\\.\\.\\." range) "non-ff") + (t "new commits")) + (and (or modified untracked) + (concat ", " + (and modified "modified") + (and modified untracked " and ") + (and untracked "untracked") + " content")) + ")") + (let ((default-directory + (file-name-as-directory + (expand-file-name module (magit-toplevel))))) + (magit-git-wash (apply-partially 'magit-log-wash-log 'module) + "log" "--oneline" "--left-right" range) + (delete-char -1))))) + ((and (looking-at "^Submodule \\([^ ]+\\) \\([^ ]+\\) (\\([^)]+\\))$") + (equal (match-string 1) module)) + (magit-bind-match-strings (_module _range msg) nil + (magit-delete-line) + (magit-insert-section (magit-module-section module) + (magit-insert-heading + (propertize (concat "submodule " module) + 'face 'magit-diff-file-heading) + " (" msg ")")))) + (t + (magit-insert-section (magit-module-section module) + (magit-insert-heading + (propertize (concat "modified " module) + 'face 'magit-diff-file-heading) + " (" + (and modified "modified") + (and modified untracked " and ") + (and untracked "untracked") + " content)"))))))) + +(defun magit-diff-wash-hunk () + (when (looking-at "^@\\{2,\\} \\(.+?\\) @\\{2,\\}\\(?: \\(.*\\)\\)?") + (let ((heading (match-string 0)) + (value (cons (match-string 2) (split-string (match-string 1))))) + (magit-delete-line) + (magit-insert-section it (hunk value) + (insert (propertize (concat heading "\n") 'face 'magit-diff-hunk-heading)) + (magit-insert-heading) + (while (not (or (eobp) (looking-at "^[^-+\s\\]"))) + (forward-line)) + (oset it end (point)) + (oset it washer 'magit-diff-paint-hunk))) + t)) + +(defun magit-diff-expansion-threshold (section) + "Keep new diff sections collapsed if washing takes too long." + (and (magit-file-section-p section) + (> (float-time (time-subtract (current-time) magit-refresh-start-time)) + magit-diff-expansion-threshold) + 'hide)) + +;;; Revision Mode + +(define-derived-mode magit-revision-mode magit-diff-mode "Magit Rev" + "Mode for looking at a Git commit. + +This mode is documented in info node `(magit)Revision Buffer'. + +\\\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-section-toggle] to expand or hide the section at point. +Type \\[magit-visit-thing] to visit the hunk or file at point. + +Staging and applying changes is documented in info node +`(magit)Staging and Unstaging' and info node `(magit)Applying'. + +\\Type \ +\\[magit-apply] to apply the change at point, \ +\\[magit-stage] to stage, +\\[magit-unstage] to unstage, \ +\\[magit-discard] to discard, or \ +\\[magit-reverse] to reverse it. + +\\{magit-revision-mode-map}" + :group 'magit-revision + (hack-dir-local-variables-non-file-buffer) + (setq-local bookmark-make-record-function + 'magit-bookmark--revision-make-record)) + +(defun magit-revision-refresh-buffer (rev __const _args files) + (magit-set-header-line-format + (concat (capitalize (magit-object-type rev)) + " " + rev + (pcase (length files) + (0) + (1 (concat " limited to file " (car files))) + (_ (concat " limited to files " + (mapconcat #'identity files ", ")))))) + (setq magit-buffer-revision-hash (magit-rev-parse rev)) + (magit-insert-section (commitbuf) + (magit-run-section-hook 'magit-revision-sections-hook rev))) + +(defun magit-insert-revision-diff (rev) + "Insert the diff into this `magit-revision-mode' buffer." + (let ((magit-git-global-arguments + (remove "--literal-pathspecs" magit-git-global-arguments))) + ;; Before v2.2.0, "--format=" did not mean "no output". + ;; Instead the default format was used. So use "--format=%n" + ;; and then delete the empty lines. + (magit-git-wash (lambda (args) + (delete-region (point) (progn (forward-line 3) (point))) + (magit-diff-wash-diffs args)) + "show" "-p" "--cc" "--format=%n" "--no-prefix" + (and (member "--stat" (nth 2 magit-refresh-args)) "--numstat") + (nth 2 magit-refresh-args) (concat rev "^{commit}") "--" + (nth 3 magit-refresh-args)))) + +(defun magit-insert-revision-tag (rev) + "Insert tag message and headers into a revision buffer. +This function only inserts anything when `magit-show-commit' is +called with a tag as argument, when that is called with a commit +or a ref which is not a branch, then it inserts nothing." + (when (equal (magit-object-type rev) "tag") + (magit-insert-section (taginfo) + (let ((beg (point))) + ;; "git verify-tag -v" would output what we need, but the gpg + ;; output is send to stderr and we have no control over the + ;; order in which stdout and stderr are inserted, which would + ;; make parsing hard. We are forced to use "git cat-file tag" + ;; instead, which inserts the signature instead of verifying + ;; it. We remove that later and then insert the verification + ;; output using "git verify-tag" (without the "-v"). + (magit-git-insert "cat-file" "tag" rev) + (goto-char beg) + (forward-line 3) + (delete-region beg (point))) + (looking-at "^tagger \\([^<]+\\) <\\([^>]+\\)") + (let ((heading (format "Tagger: %s <%s>" + (match-string 1) + (match-string 2)))) + (magit-delete-line) + (insert (propertize heading 'face 'magit-section-secondary-heading))) + (magit-insert-heading) + (if (re-search-forward "-----BEGIN PGP SIGNATURE-----" nil t) + (progn + (let ((beg (match-beginning 0))) + (re-search-forward "-----END PGP SIGNATURE-----") + (delete-region beg (point))) + (insert ?\n) + (process-file magit-git-executable nil t nil "verify-tag" rev)) + (goto-char (point-max))) + (insert ?\n)))) + +(defvar magit-commit-message-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-show-commit) + map) + "Keymap for `commit-message' sections.") + +(defun magit-insert-revision-message (rev) + "Insert the commit message into a revision buffer." + (magit-insert-section section (commit-message) + (oset section heading-highlight-face 'magit-diff-hunk-heading-highlight) + (let ((beg (point))) + (insert (save-excursion ; The risky var query can move point. + (with-temp-buffer + (magit-rev-insert-format "%B" rev) + (magit-revision--wash-message)))) + (if (= (point) (+ beg 2)) + (progn (backward-delete-char 2) + (insert "(no message)\n")) + (goto-char beg) + (save-excursion + (while (search-forward "\r\n" nil t) ; Remove trailing CRs. + (delete-region (match-beginning 0) (1+ (match-beginning 0))))) + (when magit-revision-fill-summary-line + (let ((fill-column (min magit-revision-fill-summary-line + (window-width)))) + (fill-region (point) (line-end-position)))) + (when magit-revision-use-hash-sections + (save-excursion + (while (not (eobp)) + (re-search-forward "\\_<" nil 'move) + (let ((beg (point))) + (re-search-forward "\\_>" nil t) + (when (> (point) beg) + (let ((text (buffer-substring-no-properties beg (point)))) + (when (pcase magit-revision-use-hash-sections + (`quickest ; false negatives and positives + (and (>= (length text) 7) + (string-match-p "[0-9]" text) + (string-match-p "[a-z]" text))) + (`quicker ; false negatives (number-less hashes) + (and (>= (length text) 7) + (string-match-p "[0-9]" text) + (magit-rev-verify-commit text))) + (`quick ; false negatives (short hashes) + (and (>= (length text) 7) + (magit-rev-verify-commit text))) + (`slow + (magit-rev-verify-commit text))) + (put-text-property beg (point) 'face 'magit-hash) + (let ((end (point))) + (goto-char beg) + (magit-insert-section (commit text) + (goto-char end)))))))))) + (save-excursion + (forward-line) + (add-face-text-property beg (point) 'magit-diff-hunk-heading) + (magit-insert-heading)) + (when magit-diff-highlight-keywords + (save-excursion + (while (re-search-forward "\\[[^[]*\\]" nil t) + (let ((beg (match-beginning 0)) + (end (match-end 0))) + (put-text-property + beg end 'face + (if-let ((face (get-text-property beg 'face))) + (list face 'magit-keyword) + 'magit-keyword)))))) + (goto-char (point-max)))))) + +(defun magit-insert-revision-notes (rev) + "Insert commit notes into a revision buffer." + (let* ((var "core.notesRef") + (def (or (magit-get var) "refs/notes/commits"))) + (dolist (ref (or (magit-list-active-notes-refs))) + (magit-insert-section section (notes ref (not (equal ref def))) + (oset section heading-highlight-face 'magit-diff-hunk-heading-highlight) + (let ((beg (point))) + (insert (with-temp-buffer + (magit-git-insert "-c" (concat "core.notesRef=" ref) + "notes" "show" rev) + (magit-revision--wash-message))) + (if (= (point) beg) + (magit-cancel-section) + (goto-char beg) + (end-of-line) + (insert (format " (%s)" + (propertize (if (string-prefix-p "refs/notes/" ref) + (substring ref 11) + ref) + 'face 'magit-refname))) + (forward-char) + (add-face-text-property beg (point) 'magit-diff-hunk-heading) + (magit-insert-heading) + (goto-char (point-max)) + (insert ?\n))))))) + +(defun magit-revision--wash-message () + (let ((major-mode 'git-commit-mode)) + (hack-dir-local-variables) + (hack-local-variables-apply)) + (unless (memq git-commit-major-mode '(nil text-mode)) + (funcall git-commit-major-mode) + (font-lock-ensure)) + (buffer-string)) + +(defun magit-insert-revision-headers (rev) + "Insert headers about the commit into a revision buffer." + (magit-insert-section (headers) + ;; Before v2.2.0, "%D" was not supported. + (--when-let (magit-rev-format "%d" rev "--decorate=full") + (insert (magit-format-ref-labels it) ?\s)) + (insert (propertize (magit-rev-parse (concat rev "^{commit}")) + 'face 'magit-hash)) + (magit-insert-heading) + (let ((beg (point))) + (magit-rev-insert-format magit-revision-headers-format rev) + (magit-insert-revision-gravatars rev beg)) + (when magit-revision-insert-related-refs + (dolist (parent (magit-commit-parents rev)) + (magit-insert-section (commit parent) + (let ((line (magit-rev-format "%h %s" parent))) + (string-match "^\\([^ ]+\\) \\(.*\\)" line) + (magit-bind-match-strings (hash msg) line + (insert "Parent: ") + (insert (propertize hash 'face 'magit-hash)) + (insert " " msg "\n"))))) + (magit--insert-related-refs + rev "--merged" "Merged" + (eq magit-revision-insert-related-refs 'all)) + (magit--insert-related-refs + rev "--contains" "Contained" + (eq magit-revision-insert-related-refs '(all mixed))) + (when-let ((follows (magit-get-current-tag rev t))) + (let ((tag (car follows)) + (cnt (cadr follows))) + (magit-insert-section (tag tag) + (insert (format "Follows: %s (%s)\n" + (propertize tag 'face 'magit-tag) + (propertize (number-to-string cnt) + 'face 'magit-branch-local)))))) + (when-let ((precedes (magit-get-next-tag rev t))) + (let ((tag (car precedes)) + (cnt (cadr precedes))) + (magit-insert-section (tag tag) + (insert (format "Precedes: %s (%s)\n" + (propertize tag 'face 'magit-tag) + (propertize (number-to-string cnt) + 'face 'magit-tag)))))) + (insert ?\n)))) + +(defun magit--insert-related-refs (rev arg title remote) + (when-let ((refs (magit-list-related-branches arg rev (and remote "-a")))) + (insert title ":" (make-string (- 10 (length title)) ?\s)) + (dolist (branch refs) + (if (<= (+ (current-column) 1 (length branch)) + (window-width)) + (insert ?\s) + (insert ?\n (make-string 12 ?\s))) + (magit-insert-section (branch branch) + (insert (propertize branch 'face + (if (string-prefix-p "remotes/" branch) + 'magit-branch-remote + 'magit-branch-local))))) + (insert ?\n))) + +(defun magit-insert-revision-gravatars (rev beg) + (when (and magit-revision-show-gravatars + (window-system)) + (require 'gravatar) + (pcase-let ((`(,author . ,committer) + (pcase magit-revision-show-gravatars + (`t '("^Author: " . "^Commit: ")) + (`author '("^Author: " . nil)) + (`committer '(nil . "^Commit: ")) + (_ magit-revision-show-gravatars)))) + (--when-let (and author (magit-rev-format "%aE" rev)) + (magit-insert-revision-gravatar beg rev it author)) + (--when-let (and committer (magit-rev-format "%cE" rev)) + (magit-insert-revision-gravatar beg rev it committer))))) + +(defun magit-insert-revision-gravatar (beg rev email regexp) + (save-excursion + (goto-char beg) + (when (re-search-forward regexp nil t) + (let* ((column (length (match-string 0))) + (font-obj (query-font (font-at (point) (get-buffer-window)))) + (size (* 2 (+ (aref font-obj 4) + (aref font-obj 5)))) + (align-to (+ column + (ceiling (/ size (aref font-obj 7) 1.0)) + 1)) + (gravatar-size (- size 2))) + (ignore-errors ; service may be unreachable + (gravatar-retrieve email 'magit-insert-revision-gravatar-cb + (list rev (point-marker) align-to column))))))) + +(defun magit-insert-revision-gravatar-cb (image rev marker align-to column) + (unless (eq image 'error) + (when-let ((buffer (marker-buffer marker))) + (with-current-buffer buffer + (save-excursion + (goto-char marker) + ;; The buffer might display another revision by now or + ;; it might have been refreshed, in which case another + ;; process might already have inserted the image. + (when (and (equal rev (car magit-refresh-args)) + (not (eq (car-safe + (car-safe + (get-text-property (point) 'display))) + 'image))) + (let ((top `((,@image :ascent center :relief 1) + (slice 0.0 0.0 1.0 0.5))) + (bot `((,@image :ascent center :relief 1) + (slice 0.0 0.5 1.0 1.0))) + (align `((space :align-to ,align-to)))) + (when magit-revision-use-gravatar-kludge + (cl-rotatef top bot)) + (let ((inhibit-read-only t)) + (insert (propertize " " 'display top)) + (insert (propertize " " 'display align)) + (forward-line) + (forward-char column) + (insert (propertize " " 'display bot)) + (insert (propertize " " 'display align)))))))))) + +;;; Diff Sections + +(defvar magit-unstaged-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-diff-unstaged) + (define-key map [remap magit-delete-thing] 'magit-discard) + (define-key map "s" 'magit-stage) + (define-key map "u" 'magit-unstage) + map) + "Keymap for the `unstaged' section.") + +(magit-define-section-jumper magit-jump-to-unstaged "Unstaged changes" unstaged) + +(defun magit-insert-unstaged-changes () + "Insert section showing unstaged changes." + (magit-insert-section (unstaged) + (magit-insert-heading "Unstaged changes:") + (magit-git-wash #'magit-diff-wash-diffs + "diff" magit-diff-section-arguments "--no-prefix" + "--" magit-diff-section-file-args))) + +(defvar magit-staged-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-diff-staged) + (define-key map [remap magit-delete-thing] 'magit-discard) + (define-key map [remap magit-revert-no-commit] 'magit-reverse) + (define-key map "s" 'magit-stage) + (define-key map "u" 'magit-unstage) + map) + "Keymap for the `staged' section.") + +(magit-define-section-jumper magit-jump-to-staged "Staged changes" staged) + +(defun magit-insert-staged-changes () + "Insert section showing staged changes." + ;; Avoid listing all files as deleted when visiting a bare repo. + (unless (magit-bare-repo-p) + (magit-insert-section (staged) + (magit-insert-heading "Staged changes:") + (magit-git-wash #'magit-diff-wash-diffs + "diff" "--cached" magit-diff-section-arguments "--no-prefix" + "--" magit-diff-section-file-args)))) + +;;; Diff Type + +(defun magit-diff-type (&optional section) + "Return the diff type of SECTION. + +The returned type is one of the symbols `staged', `unstaged', +`committed', or `undefined'. This type serves a similar purpose +as the general type common to all sections (which is stored in +the `type' slot of the corresponding `magit-section' struct) but +takes additional information into account. When the SECTION +isn't related to diffs and the buffer containing it also isn't +a diff-only buffer, then return nil. + +Currently the type can also be one of `tracked' and `untracked' +but these values are not handled explicitly everywhere they +should be and a possible fix could be to just return nil here. + +The section has to be a `diff' or `hunk' section, or a section +whose children are of type `diff'. If optional SECTION is nil, +return the diff type for the current section. In buffers whose +major mode is `magit-diff-mode' SECTION is ignored and the type +is determined using other means. In `magit-revision-mode' +buffers the type is always `committed'. + +Do not confuse this with `magit-diff-scope' (which see)." + (--when-let (or section (magit-current-section)) + (cond ((derived-mode-p 'magit-revision-mode 'magit-stash-mode) 'committed) + ((derived-mode-p 'magit-diff-mode) + (let ((range (nth 0 magit-refresh-args)) + (const (nth 1 magit-refresh-args))) + (cond ((member "--no-index" const) 'undefined) + ((or (not range) + (magit-rev-eq range "HEAD")) + (if (member "--cached" const) + 'staged + 'unstaged)) + ((member "--cached" const) + (if (magit-rev-head-p range) + 'staged + 'undefined)) ; i.e. committed and staged + (t 'committed)))) + ((derived-mode-p 'magit-status-mode) + (let ((stype (oref it type))) + (if (memq stype '(staged unstaged tracked untracked)) + stype + (pcase stype + ((or `file `module) + (let* ((parent (oref it parent)) + (type (oref parent type))) + (if (memq type '(file module)) + (magit-diff-type parent) + type))) + (`hunk (-> it + (oref parent) + (oref parent) + (oref type))))))) + ((derived-mode-p 'magit-log-mode) + (if (or (and (magit-section-match 'commit section) + (oref section children)) + (magit-section-match [* file commit] section)) + 'committed + 'undefined)) + (t 'undefined)))) + +(cl-defun magit-diff-scope (&optional (section nil ssection) strict) + "Return the diff scope of SECTION or the selected section(s). + +A diff's \"scope\" describes what part of a diff is selected, it is +a symbol, one of `region', `hunk', `hunks', `file', `files', or +`list'. Do not confuse this with the diff \"type\", as returned by +`magit-diff-type'. + +If optional SECTION is non-nil, then return the scope of that, +ignoring the sections selected by the region. Otherwise return +the scope of the current section, or if the region is active and +selects a valid group of diff related sections, the type of these +sections, i.e. `hunks' or `files'. If SECTION, or if that is nil +the current section, is a `hunk' section; and the region region +starts and ends inside the body of a that section, then the type +is `region'. If the region is empty after a mouse click, then +`hunk' is returned instead of `region'. + +If optional STRICT is non-nil, then return nil if the diff type of +the section at point is `untracked' or the section at point is not +actually a `diff' but a `diffstat' section." + (let ((siblings (and (not ssection) (magit-region-sections nil t)))) + (setq section (or section (car siblings) (magit-current-section))) + (when (and section + (or (not strict) + (and (not (eq (magit-diff-type section) 'untracked)) + (not (eq (--when-let (oref section parent) + (oref it type)) + 'diffstat))))) + (pcase (list (oref section type) + (and siblings t) + (magit-diff-use-hunk-region-p) + ssection) + (`(hunk nil t ,_) + (if (magit-section-internal-region-p section) 'region 'hunk)) + (`(hunk t t nil) 'hunks) + (`(hunk ,_ ,_ ,_) 'hunk) + (`(file t t nil) 'files) + (`(file ,_ ,_ ,_) 'file) + (`(module t t nil) 'files) + (`(module ,_ ,_ ,_) 'file) + (`(,(or `staged `unstaged `untracked) + nil ,_ ,_) 'list))))) + +(defun magit-diff-use-hunk-region-p () + (and (region-active-p) + (not (and (if (version< emacs-version "25.1") + (eq this-command 'mouse-drag-region) + ;; TODO implement this from first principals + ;; currently it's trial-and-error + (or (eq this-command 'mouse-drag-region) + (eq last-command 'mouse-drag-region) + ;; When another window was previously + ;; selected then the last-command is + ;; some byte-code function. + (byte-code-function-p last-command))) + (eq (region-end) (region-beginning)))))) + +;;; Diff Highlight + +(defun magit-diff-unhighlight (section selection) + "Remove the highlighting of the diff-related SECTION." + (when (magit-hunk-section-p section) + (magit-diff-paint-hunk section selection nil) + t)) + +(defun magit-diff-highlight (section selection) + "Highlight the diff-related SECTION. +If SECTION is not a diff-related section, then do nothing and +return nil. If SELECTION is non-nil, then it is a list of sections +selected by the region, including SECTION. All of these sections +are highlighted." + (if (and (magit-section-match 'commit section) + (oref section children)) + (progn (if selection + (dolist (section selection) + (magit-diff-highlight-list section selection)) + (magit-diff-highlight-list section)) + t) + (when-let ((scope (magit-diff-scope section t))) + (cond ((eq scope 'region) + (magit-diff-paint-hunk section selection t)) + (selection + (dolist (section selection) + (magit-diff-highlight-recursive section selection))) + (t + (magit-diff-highlight-recursive section))) + t))) + +(defun magit-diff-highlight-recursive (section &optional selection) + (pcase (magit-diff-scope section) + (`list (magit-diff-highlight-list section selection)) + (`file (magit-diff-highlight-file section selection)) + (`hunk (magit-diff-highlight-heading section selection) + (magit-diff-paint-hunk section selection t)) + (_ (magit-section-highlight section nil)))) + +(defun magit-diff-highlight-list (section &optional selection) + (let ((beg (oref section start)) + (cnt (oref section content)) + (end (oref section end))) + (when (or (eq this-command 'mouse-drag-region) + (not selection)) + (unless (and (region-active-p) + (<= (region-beginning) beg)) + (magit-section-make-overlay beg cnt 'magit-section-highlight)) + (unless (oref section hidden) + (dolist (child (oref section children)) + (when (or (eq this-command 'mouse-drag-region) + (not (and (region-active-p) + (<= (region-beginning) + (oref child start))))) + (magit-diff-highlight-recursive child selection))))) + (when magit-diff-highlight-hunk-body + (magit-section-make-overlay (1- end) end 'magit-section-highlight)))) + +(defun magit-diff-highlight-file (section &optional selection) + (magit-diff-highlight-heading section selection) + (unless (oref section hidden) + (dolist (child (oref section children)) + (magit-diff-highlight-recursive child selection)))) + +(defun magit-diff-highlight-heading (section &optional selection) + (magit-section-make-overlay + (oref section start) + (or (oref section content) + (oref section end)) + (pcase (list (oref section type) + (and (member section selection) + (not (eq this-command 'mouse-drag-region)))) + (`(file t) 'magit-diff-file-heading-selection) + (`(file nil) 'magit-diff-file-heading-highlight) + (`(module t) 'magit-diff-file-heading-selection) + (`(module nil) 'magit-diff-file-heading-highlight) + (`(hunk t) 'magit-diff-hunk-heading-selection) + (`(hunk nil) 'magit-diff-hunk-heading-highlight)))) + +;;; Hunk Paint + +(cl-defun magit-diff-paint-hunk + (section &optional selection + (highlight (magit-section-selected-p section selection))) + (let (paint) + (unless magit-diff-highlight-hunk-body + (setq highlight nil)) + (cond (highlight + (unless (oref section hidden) + (add-to-list 'magit-section-highlighted-sections section) + (cond ((memq section magit-section-unhighlight-sections) + (setq magit-section-unhighlight-sections + (delq section magit-section-unhighlight-sections))) + (magit-diff-highlight-hunk-body + (setq paint t))))) + (t + (cond ((and (oref section hidden) + (memq section magit-section-unhighlight-sections)) + (add-to-list 'magit-section-highlighted-sections section) + (setq magit-section-unhighlight-sections + (delq section magit-section-unhighlight-sections))) + (t + (setq paint t))))) + (when paint + (save-excursion + (goto-char (oref section start)) + (let ((end (oref section end)) + (merging (looking-at "@@@")) + (stage nil) + (tab-width (magit-diff-tab-width + (magit-section-parent-value section)))) + (forward-line) + (while (< (point) end) + (when (and magit-diff-hide-trailing-cr-characters + (char-equal ?\r (char-before (line-end-position)))) + (put-text-property (1- (line-end-position)) (line-end-position) + 'invisible t)) + (put-text-property + (point) (1+ (line-end-position)) 'face + (cond + ((looking-at "^\\+\\+?\\([<=|>]\\)\\{7\\}") + (setq stage (pcase (list (match-string 1) highlight) + (`("<" nil) 'magit-diff-our) + (`("<" t) 'magit-diff-our-highlight) + (`("|" nil) 'magit-diff-base) + (`("|" t) 'magit-diff-base-highlight) + (`("=" nil) 'magit-diff-their) + (`("=" t) 'magit-diff-their-highlight) + (`(">" nil) nil))) + 'magit-diff-conflict-heading) + ((looking-at (if merging "^\\(\\+\\| \\+\\)" "^\\+")) + (magit-diff-paint-tab merging tab-width) + (magit-diff-paint-whitespace merging) + (or stage + (if highlight 'magit-diff-added-highlight 'magit-diff-added))) + ((looking-at (if merging "^\\(-\\| -\\)" "^-")) + (magit-diff-paint-tab merging tab-width) + (if highlight 'magit-diff-removed-highlight 'magit-diff-removed)) + (t + (magit-diff-paint-tab merging tab-width) + (if highlight 'magit-diff-context-highlight 'magit-diff-context)))) + (forward-line)))))) + (magit-diff-update-hunk-refinement section)) + +(defvar magit-diff--tab-width-cache nil) + +(defun magit-diff-tab-width (file) + (setq file (expand-file-name file)) + (cl-flet ((cache (value) + (let ((elt (assoc file magit-diff--tab-width-cache))) + (if elt + (setcdr elt value) + (setq magit-diff--tab-width-cache + (cons (cons file value) + magit-diff--tab-width-cache)))) + value)) + (cond + ((not magit-diff-adjust-tab-width) + tab-width) + ((--when-let (find-buffer-visiting file) + (cache (buffer-local-value 'tab-width it)))) + ((--when-let (assoc file magit-diff--tab-width-cache) + (or (cdr it) + tab-width))) + ((or (eq magit-diff-adjust-tab-width 'always) + (and (numberp magit-diff-adjust-tab-width) + (>= magit-diff-adjust-tab-width + (nth 7 (file-attributes file))))) + (cache (buffer-local-value 'tab-width (find-file-noselect file)))) + (t + (cache nil) + tab-width)))) + +(defun magit-diff-paint-tab (merging width) + (save-excursion + (forward-char (if merging 2 1)) + (while (= (char-after) ?\t) + (put-text-property (point) (1+ (point)) + 'display (list (list 'space :width width))) + (forward-char)))) + +(defun magit-diff-paint-whitespace (merging) + (when (and magit-diff-paint-whitespace + (or (derived-mode-p 'magit-status-mode) + (not (eq magit-diff-paint-whitespace 'status)))) + (let ((prefix (if merging "^[-\\+\s]\\{2\\}" "^[-\\+]")) + (indent + (if (local-variable-p 'magit-diff-highlight-indentation) + magit-diff-highlight-indentation + (setq-local + magit-diff-highlight-indentation + (cdr (--first (string-match-p (car it) default-directory) + (nreverse + (default-value + 'magit-diff-highlight-indentation)))))))) + (when (and magit-diff-highlight-trailing + (looking-at (concat prefix ".*?\\([ \t]+\\)$"))) + (let ((ov (make-overlay (match-beginning 1) (match-end 1) nil t))) + (overlay-put ov 'face 'magit-diff-whitespace-warning) + (overlay-put ov 'evaporate t))) + (when (or (and (eq indent 'tabs) + (looking-at (concat prefix "\\( *\t[ \t]*\\)"))) + (and (integerp indent) + (looking-at (format "%s\\([ \t]* \\{%s,\\}[ \t]*\\)" + prefix indent)))) + (let ((ov (make-overlay (match-beginning 1) (match-end 1) nil t))) + (overlay-put ov 'face 'magit-diff-whitespace-warning) + (overlay-put ov 'evaporate t)))))) + +(defun magit-diff-update-hunk-refinement (&optional section) + (if section + (unless (oref section hidden) + (pcase (list magit-diff-refine-hunk + (oref section refined) + (eq section (magit-current-section))) + ((or `(all nil ,_) `(t nil t)) + (oset section refined t) + (save-excursion + (goto-char (oref section start)) + ;; `diff-refine-hunk' does not handle combined diffs. + (unless (looking-at "@@@") + ;; Avoid fsyncing many small temp files + (let ((write-region-inhibit-fsync t)) + (diff-refine-hunk))))) + ((or `(nil t ,_) `(t t nil)) + (oset section refined nil) + (remove-overlays (oref section start) + (oref section end) + 'diff-mode 'fine)))) + (cl-labels ((recurse (section) + (if (magit-section-match 'hunk section) + (magit-diff-update-hunk-refinement section) + (dolist (child (oref section children)) + (recurse child))))) + (recurse magit-root-section)))) + + +;;; Hunk Region + +(defun magit-diff-hunk-region-beginning () + (save-excursion (goto-char (region-beginning)) + (line-beginning-position))) + +(defun magit-diff-hunk-region-end () + (save-excursion (goto-char (region-end)) + (line-end-position))) + +(defun magit-diff-update-hunk-region (section) + "Highlight the hunk-internal region if any." + (when (eq (magit-diff-scope section t) 'region) + (magit-diff--make-hunk-overlay + (oref section start) + (1- (oref section content)) + 'face 'magit-diff-lines-heading + 'display (magit-diff-hunk-region-header section) + 'after-string (magit-diff--hunk-after-string 'magit-diff-lines-heading)) + (run-hook-with-args 'magit-diff-highlight-hunk-region-functions section) + t)) + +(defun magit-diff-highlight-hunk-region-dim-outside (section) + "Dim the parts of the hunk that are outside the hunk-internal region. +This is done by using the same foreground and background color +for added and removed lines as for context lines." + (let ((face (if magit-diff-highlight-hunk-body + 'magit-diff-context-highlight + 'magit-diff-context))) + (when magit-diff-unmarked-lines-keep-foreground + (setq face (list :background (face-attribute face :background)))) + (magit-diff--make-hunk-overlay (oref section content) + (magit-diff-hunk-region-beginning) + 'face face + 'priority 2) + (magit-diff--make-hunk-overlay (1+ (magit-diff-hunk-region-end)) + (oref section end) + 'face face + 'priority 2))) + +(defun magit-diff-highlight-hunk-region-using-face (_section) + "Highlight the hunk-internal region by making it bold. +Or rather highlight using the face `magit-diff-hunk-region', though +changing only the `:weight' and/or `:slant' is recommended for that +face." + (magit-diff--make-hunk-overlay (magit-diff-hunk-region-beginning) + (1+ (magit-diff-hunk-region-end)) + 'face 'magit-diff-hunk-region)) + +(defun magit-diff-highlight-hunk-region-using-overlays (section) + "Emphasize the hunk-internal region using delimiting horizontal lines. +This is implemented as single-pixel newlines places inside overlays." + (if (window-system) + (let ((beg (magit-diff-hunk-region-beginning)) + (end (magit-diff-hunk-region-end)) + (str (propertize + (concat (propertize "\s" 'display '(space :height (1))) + (propertize "\n" 'line-height t)) + 'face 'magit-diff-lines-boundary))) + (magit-diff--make-hunk-overlay beg (1+ beg) 'before-string str) + (magit-diff--make-hunk-overlay end (1+ end) 'after-string str)) + (magit-diff-highlight-hunk-region-using-face section))) + +(defun magit-diff-highlight-hunk-region-using-underline (section) + "Emphasize the hunk-internal region using delimiting horizontal lines. +This is implemented by overlining and underlining the first and +last (visual) lines of the region." + (if (window-system) + (let* ((beg (magit-diff-hunk-region-beginning)) + (end (magit-diff-hunk-region-end)) + (beg-eol (save-excursion (goto-char beg) + (end-of-visual-line) + (point))) + (end-bol (save-excursion (goto-char end) + (beginning-of-visual-line) + (point))) + (color (face-background 'magit-diff-lines-boundary nil t))) + (cl-flet ((ln (b e &rest face) + (magit-diff--make-hunk-overlay + b e 'face face 'after-string + (magit-diff--hunk-after-string face)))) + (if (= beg end-bol) + (ln beg beg-eol :overline color :underline color) + (ln beg beg-eol :overline color) + (ln end-bol end :underline color)))) + (magit-diff-highlight-hunk-region-using-face section))) + +(defun magit-diff--make-hunk-overlay (start end &rest args) + (let ((ov (make-overlay start end nil t))) + (overlay-put ov 'evaporate t) + (while args (overlay-put ov (pop args) (pop args))) + (push ov magit-region-overlays) + ov)) + +(defun magit-diff--hunk-after-string (face) + (propertize "\s" + 'face face + 'display (list 'space :align-to + `(+ (0 . right) + ,(min (window-hscroll) + (- (line-end-position) + (line-beginning-position))))) + ;; This prevents the cursor from being rendered at the + ;; edge of the window. + 'cursor t)) + +;;; Hunk Utilities + +(defun magit-diff-inside-hunk-body-p () + "Return non-nil if point is inside the body of a hunk." + (and (magit-section-match 'hunk) + (> (point) + (oref (magit-current-section) content)))) + +;;; Diff Extract + +(defun magit-diff-file-header (section) + (when (magit-hunk-section-p section) + (setq section (oref section parent))) + (when (magit-file-section-p section) + (oref section header))) + +(defun magit-diff-hunk-region-header (section) + (let ((patch (magit-diff-hunk-region-patch section))) + (string-match "\n" patch) + (substring patch 0 (1- (match-end 0))))) + +(defun magit-diff-hunk-region-patch (section &optional args) + (let ((op (if (member "--reverse" args) "+" "-")) + (sbeg (oref section start)) + (rbeg (magit-diff-hunk-region-beginning)) + (rend (region-end)) + (send (oref section end)) + (patch nil)) + (save-excursion + (goto-char sbeg) + (while (< (point) send) + (looking-at "\\(.\\)\\([^\n]*\n\\)") + (cond ((or (string-match-p "[@ ]" (match-string-no-properties 1)) + (and (>= (point) rbeg) + (<= (point) rend))) + (push (match-string-no-properties 0) patch)) + ((equal op (match-string-no-properties 1)) + (push (concat " " (match-string-no-properties 2)) patch))) + (forward-line))) + (with-temp-buffer + (insert (mapconcat 'identity (reverse patch) "")) + (diff-fixup-modifs (point-min) (point-max)) + (setq patch (buffer-string))) + patch)) + +;;; _ +(provide 'magit-diff) +;;; magit-diff.el ends here diff --git a/elpa/magit-20181113.1837/magit-ediff.el b/elpa/magit-20181113.1837/magit-ediff.el new file mode 100644 index 00000000..41b3d83f --- /dev/null +++ b/elpa/magit-20181113.1837/magit-ediff.el @@ -0,0 +1,510 @@ +;;; magit-ediff.el --- Ediff extension for Magit -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library provides basic support for Ediff. + +;;; Code: + +(require 'magit) + +(require 'ediff) +(require 'smerge-mode) + +(defvar smerge-ediff-buf) +(defvar smerge-ediff-windows) + +;;; Options + +(defgroup magit-ediff nil + "Ediff support for Magit." + :link '(info-link "(magit)Ediffing") + :group 'magit-extensions) + +(defcustom magit-ediff-quit-hook + '(magit-ediff-cleanup-auxiliary-buffers + magit-ediff-restore-previous-winconf) + "Hooks to run after finishing Ediff, when that was invoked using Magit. +The hooks are run in the Ediff control buffer. This is similar +to `ediff-quit-hook' but takes the needs of Magit into account. +The `ediff-quit-hook' is ignored by Ediff sessions which were +invoked using Magit." + :package-version '(magit . "2.2.0") + :group 'magit-ediff + :type 'hook + :get 'magit-hook-custom-get + :options '(magit-ediff-cleanup-auxiliary-buffers + magit-ediff-restore-previous-winconf)) + +(defcustom magit-ediff-dwim-show-on-hunks nil + "Whether `magit-ediff-dwim' runs show variants on hunks. +If non-nil, `magit-ediff-show-staged' or +`magit-ediff-show-unstaged' are called based on what section the +hunk is in. Otherwise, `magit-ediff-dwim' runs +`magit-ediff-stage' when point is on an uncommitted hunk." + :package-version '(magit . "2.2.0") + :group 'magit-ediff + :type 'boolean) + +(defcustom magit-ediff-show-stash-with-index t + "Whether `magit-ediff-show-stash' shows the state of the index. + +If non-nil, use a third Ediff buffer to distinguish which changes +in the stash were staged. In cases where the stash contains no +staged changes, fall back to a two-buffer Ediff. + +More specifically, a stash is a merge commit, stash@{N}, with +potentially three parents. + +* stash@{N}^1 represents the `HEAD' commit at the time the stash + was created. + +* stash@{N}^2 records any changes that were staged when the stash + was made. + +* stash@{N}^3, if it exists, contains files that were untracked + when stashing. + +If this option is non-nil, `magit-ediff-show-stash' will run +Ediff on a file using three buffers: one for stash@{N}, another +for stash@{N}^1, and a third for stash@{N}^2. + +Otherwise, Ediff uses two buffers, comparing +stash@{N}^1..stash@{N}. Along with any unstaged changes, changes +in the index commit, stash@{N}^2, will be shown in this +comparison unless they conflicted with changes in the working +tree at the time of stashing." + :package-version '(magit . "2.6.0") + :group 'magit-ediff + :type 'boolean) + +;;; Commands + +(defvar magit-ediff-previous-winconf nil) + +;;;###autoload (autoload 'magit-ediff-popup "magit-ediff" nil t) +(magit-define-popup magit-ediff-popup + "Popup console for ediff commands." + :actions '((?E "Dwim" magit-ediff-dwim) + (?u "Show unstaged" magit-ediff-show-unstaged) + (?s "Stage" magit-ediff-stage) + (?i "Show staged" magit-ediff-show-staged) + (?m "Resolve" magit-ediff-resolve) + (?w "Show worktree" magit-ediff-show-working-tree) + (?r "Diff range" magit-ediff-compare) + (?c "Show commit" magit-ediff-show-commit) nil + (?z "Show stash" magit-ediff-show-stash)) + :max-action-columns 2) + +;;;###autoload +(defun magit-ediff-resolve (file) + "Resolve outstanding conflicts in FILE using Ediff. +FILE has to be relative to the top directory of the repository. + +In the rare event that you want to manually resolve all +conflicts, including those already resolved by Git, use +`ediff-merge-revisions-with-ancestor'." + (interactive + (let ((current (magit-current-file)) + (unmerged (magit-unmerged-files))) + (unless unmerged + (user-error "There are no unresolved conflicts")) + (list (magit-completing-read "Resolve file" unmerged nil t nil nil + (car (member current unmerged)))))) + (magit-with-toplevel + (with-current-buffer (find-file-noselect file) + (smerge-ediff) + (setq-local + ediff-quit-hook + (lambda () + (let ((bufC ediff-buffer-C) + (bufS smerge-ediff-buf)) + (with-current-buffer bufS + (when (yes-or-no-p (format "Conflict resolution finished; save %s? " + buffer-file-name)) + (erase-buffer) + (insert-buffer-substring bufC) + (save-buffer)))) + (when (buffer-live-p ediff-buffer-A) (kill-buffer ediff-buffer-A)) + (when (buffer-live-p ediff-buffer-B) (kill-buffer ediff-buffer-B)) + (when (buffer-live-p ediff-buffer-C) (kill-buffer ediff-buffer-C)) + (when (buffer-live-p ediff-ancestor-buffer) + (kill-buffer ediff-ancestor-buffer)) + (let ((magit-ediff-previous-winconf smerge-ediff-windows)) + (run-hooks 'magit-ediff-quit-hook))))))) + +;;;###autoload +(defun magit-ediff-stage (file) + "Stage and unstage changes to FILE using Ediff. +FILE has to be relative to the top directory of the repository." + (interactive + (list (magit-completing-read "Selectively stage file" + (magit-tracked-files) nil nil nil nil + (magit-current-file)))) + (magit-with-toplevel + (let* ((conf (current-window-configuration)) + (bufA (magit-get-revision-buffer "HEAD" file)) + (bufB (get-buffer (concat file ".~{index}~"))) + (bufBrw (and bufB (with-current-buffer bufB (not buffer-read-only)))) + (bufC (get-file-buffer file)) + (fileBufC (or bufC (find-file-noselect file))) + (coding-system-for-read + (with-current-buffer fileBufC buffer-file-coding-system))) + (ediff-buffers3 + (or bufA (magit-find-file-noselect "HEAD" file)) + (with-current-buffer (magit-find-file-index-noselect file t) + (setq buffer-read-only nil) + (current-buffer)) + fileBufC + `((lambda () + (setq-local + ediff-quit-hook + (lambda () + (and (buffer-live-p ediff-buffer-B) + (buffer-modified-p ediff-buffer-B) + (with-current-buffer ediff-buffer-B + (magit-update-index))) + (and (buffer-live-p ediff-buffer-C) + (buffer-modified-p ediff-buffer-C) + (with-current-buffer ediff-buffer-C + (when (y-or-n-p + (format "Save file %s? " buffer-file-name)) + (save-buffer)))) + ,@(unless bufA '((ediff-kill-buffer-carefully ediff-buffer-A))) + ,@(if bufB + (unless bufBrw '((with-current-buffer ediff-buffer-B + (setq buffer-read-only t)))) + '((ediff-kill-buffer-carefully ediff-buffer-B))) + ,@(unless bufC '((ediff-kill-buffer-carefully ediff-buffer-C))) + (let ((magit-ediff-previous-winconf ,conf)) + (run-hooks 'magit-ediff-quit-hook)))))) + 'ediff-buffers3)))) + +;;;###autoload +(defun magit-ediff-compare (revA revB fileA fileB) + "Compare REVA:FILEA with REVB:FILEB using Ediff. + +FILEA and FILEB have to be relative to the top directory of the +repository. If REVA or REVB is nil, then this stands for the +working tree state. + +If the region is active, use the revisions on the first and last +line of the region. With a prefix argument, instead of diffing +the revisions, choose a revision to view changes along, starting +at the common ancestor of both revisions (i.e., use a \"...\" +range)." + (interactive + (pcase-let ((`(,revA ,revB) (magit-ediff-compare--read-revisions + nil current-prefix-arg))) + (nconc (list revA revB) + (magit-ediff-read-files revA revB)))) + (magit-with-toplevel + (let ((conf (current-window-configuration)) + (bufA (if revA + (magit-get-revision-buffer revA fileA) + (get-file-buffer fileA))) + (bufB (if revB + (magit-get-revision-buffer revB fileB) + (get-file-buffer fileB)))) + (ediff-buffers + (or bufA (if revA + (magit-find-file-noselect revA fileA) + (find-file-noselect fileA))) + (or bufB (if revB + (magit-find-file-noselect revB fileB) + (find-file-noselect fileB))) + `((lambda () + (setq-local + ediff-quit-hook + (lambda () + ,@(unless bufA '((ediff-kill-buffer-carefully ediff-buffer-A))) + ,@(unless bufB '((ediff-kill-buffer-carefully ediff-buffer-B))) + (let ((magit-ediff-previous-winconf ,conf)) + (run-hooks 'magit-ediff-quit-hook)))))) + 'ediff-revision)))) + +(defun magit-ediff-compare--read-revisions (&optional arg mbase) + (let ((input (or arg (magit-diff-read-range-or-commit + "Compare range or commit" + nil mbase)))) + (--if-let (magit-split-range input) + (-cons-to-list it) + (list input nil)))) + +(defun magit-ediff-read-files (revA revB &optional fileB) + "Read file in REVB, return it and the corresponding file in REVA. +When FILEB is non-nil, use this as REVB's file instead of +prompting for it." + (unless fileB + (setq fileB (magit-read-file-choice + (format "File to compare between %s and %s" + revA (or revB "the working tree")) + (magit-changed-files revA revB) + (format "No changed files between %s and %s" + revA (or revB "the working tree"))))) + (list (or (car (member fileB (magit-revision-files revA))) + (cdr (assoc fileB (magit-renamed-files revB revA))) + (magit-read-file-choice + (format "File in %s to compare with %s in %s" + revA fileB (or revB "the working tree")) + (magit-changed-files revB revA) + (format "No files have changed between %s and %s" + revA revB))) + fileB)) + +;;;###autoload +(defun magit-ediff-dwim () + "Compare, stage, or resolve using Ediff. +This command tries to guess what file, and what commit or range +the user wants to compare, stage, or resolve using Ediff. It +might only be able to guess either the file, or range or commit, +in which case the user is asked about the other. It might not +always guess right, in which case the appropriate `magit-ediff-*' +command has to be used explicitly. If it cannot read the user's +mind at all, then it asks the user for a command to run." + (interactive) + (magit-section-case + (hunk (save-excursion + (goto-char (oref (oref it parent) start)) + (magit-ediff-dwim))) + (t + (let ((range (magit-diff--dwim)) + (file (magit-current-file)) + command revA revB) + (pcase range + ((and (guard (not magit-ediff-dwim-show-on-hunks)) + (or `unstaged `staged)) + (setq command (if (magit-anything-unmerged-p) + #'magit-ediff-resolve + #'magit-ediff-stage))) + (`unstaged (setq command #'magit-ediff-show-unstaged)) + (`staged (setq command #'magit-ediff-show-staged)) + (`(commit . ,value) + (setq command #'magit-ediff-show-commit) + (setq revB value)) + (`(stash . ,value) + (setq command #'magit-ediff-show-stash) + (setq revB value)) + ((pred stringp) + (pcase-let ((`(,a ,b) (magit-ediff-compare--read-revisions range))) + (setq command #'magit-ediff-compare) + (setq revA a) + (setq revB b))) + (_ + (when (derived-mode-p 'magit-diff-mode) + (pcase (magit-diff-type) + (`committed (pcase-let ((`(,a ,b) + (magit-ediff-compare--read-revisions + (car magit-refresh-args)))) + (setq revA a) + (setq revB b))) + ((guard (not magit-ediff-dwim-show-on-hunks)) + (setq command #'magit-ediff-stage)) + (`unstaged (setq command #'magit-ediff-show-unstaged)) + (`staged (setq command #'magit-ediff-show-staged)) + (`undefined (setq command nil)) + (_ (setq command nil)))))) + (cond ((not command) + (call-interactively + (magit-read-char-case + "Failed to read your mind; do you want to " t + (?c "[c]ommit" 'magit-ediff-show-commit) + (?r "[r]ange" 'magit-ediff-compare) + (?s "[s]tage" 'magit-ediff-stage) + (?v "resol[v]e" 'magit-ediff-resolve)))) + ((eq command 'magit-ediff-compare) + (apply 'magit-ediff-compare revA revB + (magit-ediff-read-files revA revB file))) + ((eq command 'magit-ediff-show-commit) + (magit-ediff-show-commit revB)) + ((eq command 'magit-ediff-show-stash) + (magit-ediff-show-stash revB)) + (file + (funcall command file)) + (t + (call-interactively command))))))) + +;;;###autoload +(defun magit-ediff-show-staged (file) + "Show staged changes using Ediff. + +This only allows looking at the changes; to stage, unstage, +and discard changes using Ediff, use `magit-ediff-stage'. + +FILE must be relative to the top directory of the repository." + (interactive + (list (magit-read-file-choice "Show staged changes for file" + (magit-staged-files) + "No staged files"))) + (let ((conf (current-window-configuration)) + (bufA (magit-get-revision-buffer "HEAD" file)) + (bufB (get-buffer (concat file ".~{index}~")))) + (ediff-buffers + (or bufA (magit-find-file-noselect "HEAD" file)) + (or bufB (magit-find-file-index-noselect file t)) + `((lambda () + (setq-local + ediff-quit-hook + (lambda () + ,@(unless bufA '((ediff-kill-buffer-carefully ediff-buffer-A))) + ,@(unless bufB '((ediff-kill-buffer-carefully ediff-buffer-B))) + (let ((magit-ediff-previous-winconf ,conf)) + (run-hooks 'magit-ediff-quit-hook)))))) + 'ediff-buffers))) + +;;;###autoload +(defun magit-ediff-show-unstaged (file) + "Show unstaged changes using Ediff. + +This only allows looking at the changes; to stage, unstage, +and discard changes using Ediff, use `magit-ediff-stage'. + +FILE must be relative to the top directory of the repository." + (interactive + (list (magit-read-file-choice "Show unstaged changes for file" + (magit-unstaged-files) + "No unstaged files"))) + (magit-with-toplevel + (let ((conf (current-window-configuration)) + (bufA (get-buffer (concat file ".~{index}~"))) + (bufB (get-file-buffer file))) + (ediff-buffers + (or bufA (magit-find-file-index-noselect file t)) + (or bufB (find-file-noselect file)) + `((lambda () + (setq-local + ediff-quit-hook + (lambda () + ,@(unless bufA '((ediff-kill-buffer-carefully ediff-buffer-A))) + ,@(unless bufB '((ediff-kill-buffer-carefully ediff-buffer-B))) + (let ((magit-ediff-previous-winconf ,conf)) + (run-hooks 'magit-ediff-quit-hook)))))) + 'ediff-buffers)))) + +;;;###autoload +(defun magit-ediff-show-working-tree (file) + "Show changes between `HEAD' and working tree using Ediff. +FILE must be relative to the top directory of the repository." + (interactive + (list (magit-read-file-choice "Show changes in file" + (magit-changed-files "HEAD") + "No changed files"))) + (magit-with-toplevel + (let ((conf (current-window-configuration)) + (bufA (magit-get-revision-buffer "HEAD" file)) + (bufB (get-file-buffer file))) + (ediff-buffers + (or bufA (magit-find-file-noselect "HEAD" file)) + (or bufB (find-file-noselect file)) + `((lambda () + (setq-local + ediff-quit-hook + (lambda () + ,@(unless bufA '((ediff-kill-buffer-carefully ediff-buffer-A))) + ,@(unless bufB '((ediff-kill-buffer-carefully ediff-buffer-B))) + (let ((magit-ediff-previous-winconf ,conf)) + (run-hooks 'magit-ediff-quit-hook)))))) + 'ediff-buffers)))) + +;;;###autoload +(defun magit-ediff-show-commit (commit) + "Show changes introduced by COMMIT using Ediff." + (interactive (list (magit-read-branch-or-commit "Revision"))) + (let ((revA (concat commit "^")) + (revB commit)) + (apply #'magit-ediff-compare + revA revB + (magit-ediff-read-files revA revB (magit-current-file))))) + +;;;###autoload +(defun magit-ediff-show-stash (stash) + "Show changes introduced by STASH using Ediff. +`magit-ediff-show-stash-with-index' controls whether a +three-buffer Ediff is used in order to distinguish changes in the +stash that were staged." + (interactive (list (magit-read-stash "Stash"))) + (pcase-let* ((revA (concat stash "^1")) + (revB (concat stash "^2")) + (revC stash) + (`(,fileA ,fileC) (magit-ediff-read-files revA revC)) + (fileB fileC)) + (if (and magit-ediff-show-stash-with-index + (member fileA (magit-changed-files revB revA))) + (let ((conf (current-window-configuration)) + (bufA (magit-get-revision-buffer revA fileA)) + (bufB (magit-get-revision-buffer revB fileB)) + (bufC (magit-get-revision-buffer revC fileC))) + (ediff-buffers3 + (or bufA (magit-find-file-noselect revA fileA)) + (or bufB (magit-find-file-noselect revB fileB)) + (or bufC (magit-find-file-noselect revC fileC)) + `((lambda () + (setq-local + ediff-quit-hook + (lambda () + ,@(unless bufA + '((ediff-kill-buffer-carefully ediff-buffer-A))) + ,@(unless bufB + '((ediff-kill-buffer-carefully ediff-buffer-B))) + ,@(unless bufC + '((ediff-kill-buffer-carefully ediff-buffer-C))) + (let ((magit-ediff-previous-winconf ,conf)) + (run-hooks 'magit-ediff-quit-hook)))))) + 'ediff-buffers3)) + (magit-ediff-compare revA revC fileA fileC)))) + +(defun magit-ediff-cleanup-auxiliary-buffers () + (let* ((ctl-buf ediff-control-buffer) + (ctl-win (ediff-get-visible-buffer-window ctl-buf)) + (ctl-frm ediff-control-frame) + (main-frame (cond ((window-live-p ediff-window-A) + (window-frame ediff-window-A)) + ((window-live-p ediff-window-B) + (window-frame ediff-window-B))))) + (ediff-kill-buffer-carefully ediff-diff-buffer) + (ediff-kill-buffer-carefully ediff-custom-diff-buffer) + (ediff-kill-buffer-carefully ediff-fine-diff-buffer) + (ediff-kill-buffer-carefully ediff-tmp-buffer) + (ediff-kill-buffer-carefully ediff-error-buffer) + (ediff-kill-buffer-carefully ediff-msg-buffer) + (ediff-kill-buffer-carefully ediff-debug-buffer) + (when (boundp 'ediff-patch-diagnostics) + (ediff-kill-buffer-carefully ediff-patch-diagnostics)) + (cond ((and (ediff-window-display-p) + (frame-live-p ctl-frm)) + (delete-frame ctl-frm)) + ((window-live-p ctl-win) + (delete-window ctl-win))) + (unless (ediff-multiframe-setup-p) + (ediff-kill-bottom-toolbar)) + (ediff-kill-buffer-carefully ctl-buf) + (when (frame-live-p main-frame) + (select-frame main-frame)))) + +(defun magit-ediff-restore-previous-winconf () + (set-window-configuration magit-ediff-previous-winconf)) + +;;; _ +(provide 'magit-ediff) +;;; magit-ediff.el ends here diff --git a/elpa/magit-20181113.1837/magit-extras.el b/elpa/magit-20181113.1837/magit-extras.el new file mode 100644 index 00000000..cd0649ab --- /dev/null +++ b/elpa/magit-20181113.1837/magit-extras.el @@ -0,0 +1,651 @@ +;;; magit-extras.el --- additional functionality for Magit -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; Additional functionality for Magit. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +(declare-function dired-read-shell-command "dired-aux" (prompt arg files)) + +(defgroup magit-extras nil + "Additional functionality for Magit." + :group 'magit-extensions) + +;;; External Tools + +(defcustom magit-gitk-executable + (or (and (eq system-type 'windows-nt) + (let ((exe (magit-git-string + "-c" "alias.X=!x() { which \"$1\" | cygpath -mf -; }; x" + "X" "gitk.exe"))) + (and exe (file-executable-p exe) exe))) + (executable-find "gitk") "gitk") + "The Gitk executable." + :group 'magit-extras + :set-after '(magit-git-executable) + :type 'string) + +;;;###autoload +(defun magit-run-git-gui () + "Run `git gui' for the current git repository." + (interactive) + (magit-with-toplevel + (magit-process-file magit-git-executable nil 0 nil "gui"))) + +;;;###autoload +(defun magit-run-git-gui-blame (commit filename &optional linenum) + "Run `git gui blame' on the given FILENAME and COMMIT. +Interactively run it for the current file and the `HEAD', with a +prefix or when the current file cannot be determined let the user +choose. When the current buffer is visiting FILENAME instruct +blame to center around the line point is on." + (interactive + (let (revision filename) + (when (or current-prefix-arg + (not (setq revision "HEAD" + filename (magit-file-relative-name nil 'tracked)))) + (setq revision (magit-read-branch-or-commit "Blame from revision")) + (setq filename (magit-read-file-from-rev revision "Blame file"))) + (list revision filename + (and (equal filename + (ignore-errors + (magit-file-relative-name buffer-file-name))) + (line-number-at-pos))))) + (magit-with-toplevel + (apply #'magit-process-file magit-git-executable nil 0 nil "gui" "blame" + `(,@(and linenum (list (format "--line=%d" linenum))) + ,commit + ,filename)))) + +;;;###autoload +(defun magit-run-gitk () + "Run `gitk' in the current repository." + (interactive) + (magit-process-file magit-gitk-executable nil 0)) + +;;;###autoload +(defun magit-run-gitk-branches () + "Run `gitk --branches' in the current repository." + (interactive) + (magit-process-file magit-gitk-executable nil 0 nil "--branches")) + +;;;###autoload +(defun magit-run-gitk-all () + "Run `gitk --all' in the current repository." + (interactive) + (magit-process-file magit-gitk-executable nil 0 nil "--all")) + +;;; Emacs Tools + +;;;###autoload +(defun ido-enter-magit-status () + "Drop into `magit-status' from file switching. + +This command does not work in Emacs 26. It does work in Emacs 25 +and Emacs 27. See https://github.com/magit/magit/issues/3634 and +https://debbugs.gnu.org/cgi/bugreport.cgi?bug=31707. + +To make this command available use something like: + + (add-hook \\='ido-setup-hook + (lambda () + (define-key ido-completion-map + (kbd \"C-x g\") \\='ido-enter-magit-status))) + +Starting with Emacs 25.1 the Ido keymaps are defined just once +instead of every time Ido is invoked, so now you can modify it +like pretty much every other keymap: + + (define-key ido-common-completion-map + (kbd \"C-x g\") \\='ido-enter-magit-status)" + (interactive) + (with-no-warnings ; FIXME these are internal variables + (setq ido-exit 'fallback) + (setq fallback 'magit-status) ; for Emacs 25 + (setq ido-fallback 'magit-status)) ; for Emacs 27 + (exit-minibuffer)) + +;;;###autoload +(defun magit-dired-jump (&optional other-window) + "Visit file at point using Dired. +With a prefix argument, visit in another window. If there +is no file at point, then instead visit `default-directory'." + (interactive "P") + (dired-jump other-window + (when-let ((file (magit-file-at-point))) + (expand-file-name (if (file-directory-p file) + (file-name-as-directory file) + file))))) + +;;;###autoload +(defun magit-dired-log (&optional follow) + "Show log for all marked files, or the current file." + (interactive "P") + (if-let ((topdir (magit-toplevel default-directory))) + (let ((args (car (magit-log-arguments))) + (files (dired-get-marked-files nil nil #'magit-file-tracked-p))) + (unless files + (user-error "No marked file is being tracked by Git")) + (when (and follow + (not (member "--follow" args)) + (not (cdr files))) + (push "--follow" args)) + (magit-mode-setup-internal + #'magit-log-mode + (list (list (or (magit-get-current-branch) "HEAD")) + args + (let ((default-directory topdir)) + (mapcar #'file-relative-name files))) + magit-log-buffer-file-locked)) + (magit--not-inside-repository-error))) + +;;;###autoload +(defun magit-do-async-shell-command (file) + "Open FILE with `dired-do-async-shell-command'. +Interactively, open the file at point." + (interactive (list (or (magit-file-at-point) + (completing-read "Act on file: " + (magit-list-files))))) + (require 'dired-aux) + (dired-do-async-shell-command + (dired-read-shell-command "& on %s: " current-prefix-arg (list file)) + nil (list file))) + +;;; Shift Selection + +(defun magit--turn-on-shift-select-mode-p () + (and shift-select-mode + this-command-keys-shift-translated + (not mark-active) + (not (eq (car-safe transient-mark-mode) 'only)))) + +;;;###autoload +(defun magit-previous-line (&optional arg try-vscroll) + "Like `previous-line' but with Magit-specific shift-selection. + +Magit's selection mechanism is based on the region but selects an +area that is larger than the region. This causes `previous-line' +when invoked while holding the shift key to move up one line and +thereby select two lines. When invoked inside a hunk body this +command does not move point on the first invocation and thereby +it only selects a single line. Which inconsistency you prefer +is a matter of preference." + (declare (interactive-only + "use `forward-line' with negative argument instead.")) + (interactive "p\np") + (unless arg (setq arg 1)) + (let ((stay (or (magit-diff-inside-hunk-body-p) + (magit-section-position-in-heading-p)))) + (if (and stay (= arg 1) (magit--turn-on-shift-select-mode-p)) + (push-mark nil nil t) + (with-no-warnings + (handle-shift-selection) + (previous-line (if stay (max (1- arg) 1) arg) try-vscroll))))) + +;;;###autoload +(defun magit-next-line (&optional arg try-vscroll) + "Like `next-line' but with Magit-specific shift-selection. + +Magit's selection mechanism is based on the region but selects +an area that is larger than the region. This causes `next-line' +when invoked while holding the shift key to move down one line +and thereby select two lines. When invoked inside a hunk body +this command does not move point on the first invocation and +thereby it only selects a single line. Which inconsistency you +prefer is a matter of preference." + (declare (interactive-only forward-line)) + (interactive "p\np") + (unless arg (setq arg 1)) + (let ((stay (or (magit-diff-inside-hunk-body-p) + (magit-section-position-in-heading-p)))) + (if (and stay (= arg 1) (magit--turn-on-shift-select-mode-p)) + (push-mark nil nil t) + (with-no-warnings + (handle-shift-selection) + (next-line (if stay (max (1- arg) 1) arg) try-vscroll))))) + +;;; Clean + +;;;###autoload +(defun magit-clean (&optional arg) + "Remove untracked files from the working tree. +With a prefix argument also remove ignored files, +with two prefix arguments remove ignored files only. +\n(git clean -f -d [-x|-X])" + (interactive "p") + (when (yes-or-no-p (format "Remove %s files? " + (pcase arg + (1 "untracked") + (4 "untracked and ignored") + (_ "ignored")))) + (magit-wip-commit-before-change) + (magit-run-git "clean" "-f" "-d" (pcase arg (4 "-x") (16 "-X"))))) + +(put 'magit-clean 'disabled t) + +;;; ChangeLog + +;;;###autoload +(defun magit-add-change-log-entry (&optional whoami file-name other-window) + "Find change log file and add date entry and item for current change. +This differs from `add-change-log-entry' (which see) in that +it acts on the current hunk in a Magit buffer instead of on +a position in a file-visiting buffer." + (interactive (list current-prefix-arg + (prompt-for-change-log-name))) + (let (buf pos) + (save-window-excursion + (call-interactively #'magit-diff-visit-file) + (setq buf (current-buffer)) + (setq pos (point))) + (save-excursion + (with-current-buffer buf + (goto-char pos) + (add-change-log-entry whoami file-name other-window))))) + +;;;###autoload +(defun magit-add-change-log-entry-other-window (&optional whoami file-name) + "Find change log file in other window and add entry and item. +This differs from `add-change-log-entry-other-window' (which see) +in that it acts on the current hunk in a Magit buffer instead of +on a position in a file-visiting buffer." + (interactive (and current-prefix-arg + (list current-prefix-arg + (prompt-for-change-log-name)))) + (magit-add-change-log-entry whoami file-name t)) + +;;; Edit Line Commit + +;;;###autoload +(defun magit-edit-line-commit (&optional type) + "Edit the commit that added the current line. + +With a prefix argument edit the commit that removes the line, +if any. The commit is determined using `git blame' and made +editable using `git rebase --interactive' if it is reachable +from `HEAD', or by checking out the commit (or a branch that +points at it) otherwise." + (interactive (list (and current-prefix-arg 'removal))) + (let* ((chunk (magit-current-blame-chunk (or type 'addition))) + (rev (oref chunk orig-rev))) + (if (equal rev "0000000000000000000000000000000000000000") + (message "This line has not been committed yet") + (let ((rebase (magit-rev-ancestor-p rev "HEAD")) + (file (expand-file-name (oref chunk orig-file) + (magit-toplevel)))) + (if rebase + (let ((magit--rebase-published-symbol 'edit-published)) + (magit-rebase-edit-commit rev (magit-rebase-arguments))) + (magit-checkout (or (magit-rev-branch rev) rev))) + (unless (and buffer-file-name + (file-equal-p file buffer-file-name)) + (let ((blame-type (and magit-blame-mode magit-blame-type))) + (if rebase + (set-process-sentinel + magit-this-process + (lambda (process event) + (magit-sequencer-process-sentinel process event) + (when (eq (process-status process) 'exit) + (find-file file) + (when blame-type + (magit-blame--pre-blame-setup blame-type) + (magit-blame--run))))) + (find-file file) + (when blame-type + (magit-blame--pre-blame-setup blame-type) + (magit-blame--run))))))))) + +(put 'magit-edit-line-commit 'disabled t) + +(defun magit-diff-edit-hunk-commit () + "From a hunk, edit the respective commit and visit the file. + +First visit the file being modified by the hunk at the correct +location using `magit-diff-visit-file'. This actually visits a +blob. When point is on a diff header, not within an individual +hunk, then this visits the blob the first hunk is about. + +Then invoke `magit-edit-line-commit', which uses an interactive +rebase to make the commit editable, or if that is not possible +because the commit is not reachable from `HEAD' by checking out +that commit directly. This also causes the actual worktree file +to be visited. + +Neither the blob nor the file buffer are killed when finishing +the rebase. If that is undesirable, then it might be better to +use `magit-rebase-edit-command' instead of this command." + (interactive) + (let ((magit-diff-visit-previous-blob nil)) + (magit-diff-visit-file (--if-let (magit-file-at-point) + (expand-file-name it) + (user-error "No file at point")) + nil 'switch-to-buffer)) + (magit-edit-line-commit)) + +(put 'magit-diff-edit-hunk-commit 'disabled t) + +;;; Reshelve + +;;;###autoload +(defun magit-reshelve-since (rev) + "Change the author and committer dates of the commits since REV. + +Ask the user for the first reachable commit whose dates should +be changed. The read the new date for that commit. The initial +minibuffer input and the previous history element offer good +values. The next commit will be created one minute later and so +on. + +This command is only intended for interactive use and should only +be used on highly rearranged and unpublished history." + (interactive (list nil)) + (cond + ((not rev) + (let ((backup (concat "refs/original/refs/heads/" + (magit-get-current-branch)))) + (when (and (magit-ref-p backup) + (not (magit-y-or-n-p + "Backup ref %s already exists. Override? " backup))) + (user-error "Abort"))) + (magit-log-select 'magit-reshelve-since + "Type %p on a commit to reshelve it and the commits above it,")) + (t + (cl-flet ((adjust (time offset) + (format-time-string + "%F %T %z" + (+ (floor time) + (* offset 60) + (- (car (decode-time time))))))) + (let* ((start (concat rev "^")) + (range (concat start ".." (magit-get-current-branch))) + (time-rev (adjust (float-time (string-to-number + (magit-rev-format "%at" start))) + 1)) + (time-now (adjust (float-time) + (- (string-to-number + (magit-git-string "rev-list" "--count" + range)))))) + (push time-rev magit--reshelve-history) + (let ((date (floor + (float-time + (date-to-time + (read-string "Date for first commit: " + time-now 'magit--reshelve-history)))))) + (magit-with-toplevel + (magit-run-git-async + "filter-branch" "--force" "--env-filter" + (format "case $GIT_COMMIT in %s\nesac" + (mapconcat (lambda (rev) + (prog1 (format "%s) \ +export GIT_AUTHOR_DATE=\"%s\"; \ +export GIT_COMMITTER_DATE=\"%s\";;" rev date date) + (cl-incf date 60))) + (magit-git-lines "rev-list" "--reverse" + range) + " ")) + range "--") + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (magit-run-git "update-ref" "-d" + (concat "refs/original/refs/heads/" + (magit-get-current-branch)))))))))))))) + +;;; Revision Stack + +(defvar magit-revision-stack nil) + +(defcustom magit-pop-revision-stack-format + '("[%N: %h] " "%N: %H\n %s\n" "\\[\\([0-9]+\\)[]:]") + "Control how `magit-pop-revision-stack' inserts a revision. + +The command `magit-pop-revision-stack' inserts a representation +of the revision last pushed to the `magit-revision-stack' into +the current buffer. It inserts text at point and/or near the end +of the buffer, and removes the consumed revision from the stack. + +The entries on the stack have the format (HASH TOPLEVEL) and this +option has the format (POINT-FORMAT EOB-FORMAT INDEX-REGEXP), all +of which may be nil or a string (though either one of EOB-FORMAT +or POINT-FORMAT should be a string, and if INDEX-REGEXP is +non-nil, then the two formats should be too). + +First INDEX-REGEXP is used to find the previously inserted entry, +by searching backward from point. The first submatch must match +the index number. That number is incremented by one, and becomes +the index number of the entry to be inserted. If you don't want +to number the inserted revisions, then use nil for INDEX-REGEXP. + +If INDEX-REGEXP is non-nil, then both POINT-FORMAT and EOB-FORMAT +should contain \"%N\", which is replaced with the number that was +determined in the previous step. + +Both formats, if non-nil and after removing %N, are then expanded +using `git show --format=FORMAT ...' inside TOPLEVEL. + +The expansion of POINT-FORMAT is inserted at point, and the +expansion of EOB-FORMAT is inserted at the end of the buffer (if +the buffer ends with a comment, then it is inserted right before +that)." + :package-version '(magit . "2.3.0") + :group 'magit-commands + :type '(list (choice (string :tag "Insert at point format") + (cons (string :tag "Insert at point format") + (repeat (string :tag "Argument to git show"))) + (const :tag "Don't insert at point" nil)) + (choice (string :tag "Insert at eob format") + (cons (string :tag "Insert at eob format") + (repeat (string :tag "Argument to git show"))) + (const :tag "Don't insert at eob" nil)) + (choice (regexp :tag "Find index regexp") + (const :tag "Don't number entries" nil)))) + +;;;###autoload +(defun magit-pop-revision-stack (rev toplevel) + "Insert a representation of a revision into the current buffer. + +Pop a revision from the `magit-revision-stack' and insert it into +the current buffer according to `magit-pop-revision-stack-format'. +Revisions can be put on the stack using `magit-copy-section-value' +and `magit-copy-buffer-revision'. + +If the stack is empty or with a prefix argument, instead read a +revision in the minibuffer. By using the minibuffer history this +allows selecting an item which was popped earlier or to insert an +arbitrary reference or revision without first pushing it onto the +stack. + +When reading the revision from the minibuffer, then it might not +be possible to guess the correct repository. When this command +is called inside a repository (e.g. while composing a commit +message), then that repository is used. Otherwise (e.g. while +composing an email) then the repository recorded for the top +element of the stack is used (even though we insert another +revision). If not called inside a repository and with an empty +stack, or with two prefix arguments, then read the repository in +the minibuffer too." + (interactive + (if (or current-prefix-arg (not magit-revision-stack)) + (let ((default-directory + (or (and (not (= (prefix-numeric-value current-prefix-arg) 16)) + (or (magit-toplevel) + (cadr (car magit-revision-stack)))) + (magit-read-repository)))) + (list (magit-read-branch-or-commit "Insert revision") + default-directory)) + (push (caar magit-revision-stack) magit-revision-history) + (pop magit-revision-stack))) + (if rev + (pcase-let ((`(,pnt-format ,eob-format ,idx-format) + magit-pop-revision-stack-format)) + (let ((default-directory toplevel) + (idx (and idx-format + (save-excursion + (if (re-search-backward idx-format nil t) + (number-to-string + (1+ (string-to-number (match-string 1)))) + "1")))) + pnt-args eob-args) + (when (listp pnt-format) + (setq pnt-args (cdr pnt-format)) + (setq pnt-format (car pnt-format))) + (when (listp eob-format) + (setq eob-args (cdr eob-format)) + (setq eob-format (car eob-format))) + (when pnt-format + (when idx-format + (setq pnt-format + (replace-regexp-in-string "%N" idx pnt-format t t))) + (magit-rev-insert-format pnt-format rev pnt-args) + (backward-delete-char 1)) + (when eob-format + (when idx-format + (setq eob-format + (replace-regexp-in-string "%N" idx eob-format t t))) + (save-excursion + (goto-char (point-max)) + (skip-syntax-backward ">s-") + (beginning-of-line) + (if (and comment-start (looking-at comment-start)) + (while (looking-at comment-start) + (forward-line -1)) + (forward-line) + (unless (= (current-column) 0) + (insert ?\n))) + (insert ?\n) + (magit-rev-insert-format eob-format rev eob-args) + (backward-delete-char 1))))) + (user-error "Revision stack is empty"))) + +(define-key git-commit-mode-map + (kbd "C-c C-w") 'magit-pop-revision-stack) + +;;;###autoload +(defun magit-copy-section-value () + "Save the value of the current section for later use. + +Save the section value to the `kill-ring', and, provided that +the current section is a commit, branch, or tag section, push +the (referenced) revision to the `magit-revision-stack' for use +with `magit-pop-revision-stack'. + +When the current section is a branch or a tag, and a prefix +argument is used, then save the revision at its tip to the +`kill-ring' instead of the reference name. + +When the region is active, then save that to the `kill-ring', +like `kill-ring-save' would, instead of behaving as described +above." + (interactive) + (if (use-region-p) + (copy-region-as-kill nil nil 'region) + (when-let ((section (magit-current-section)) + (value (oref section value))) + (magit-section-case + ((branch commit module-commit tag) + (let ((default-directory default-directory) ref) + (magit-section-case + ((branch tag) + (setq ref value)) + (module-commit + (setq default-directory + (file-name-as-directory + (expand-file-name (magit-section-parent-value section) + (magit-toplevel)))))) + (setq value (magit-rev-parse value)) + (push (list value default-directory) magit-revision-stack) + (kill-new (message "%s" (or (and current-prefix-arg ref) + value))))) + (t (kill-new (message "%s" value))))))) + +;;;###autoload +(defun magit-copy-buffer-revision () + "Save the revision of the current buffer for later use. + +Save the revision shown in the current buffer to the `kill-ring' +and push it to the `magit-revision-stack'. + +This command is mainly intended for use in `magit-revision-mode' +buffers, the only buffers where it is always unambiguous exactly +which revision should be saved. + +Most other Magit buffers usually show more than one revision, in +some way or another, so this command has to select one of them, +and that choice might not always be the one you think would have +been the best pick. + +In such buffers it is often more useful to save the value of +the current section instead, using `magit-copy-section-value'. + +When the region is active, then save that to the `kill-ring', +like `kill-ring-save' would, instead of behaving as described +above." + (interactive) + (if (use-region-p) + (copy-region-as-kill nil nil 'region) + (when-let ((rev (cond ((memq major-mode '(magit-cherry-mode + magit-log-select-mode + magit-reflog-mode + magit-refs-mode + magit-revision-mode + magit-stash-mode + magit-stashes-mode)) + (car magit-refresh-args)) + ((memq major-mode '(magit-diff-mode + magit-log-mode)) + (let ((r (caar magit-refresh-args))) + (if (string-match "\\.\\.\\.?\\(.+\\)" r) + (match-string 1 r) + r))) + ((eq major-mode 'magit-status-mode) "HEAD")))) + (when (magit-rev-verify-commit rev) + (setq rev (magit-rev-parse rev)) + (push (list rev default-directory) magit-revision-stack) + (kill-new (message "%s" rev)))))) + +;;; Miscellaneous + +;;;###autoload +(defun magit-abort-dwim () + "Abort current operation. +Depending on the context, this will abort a merge, a rebase, a +patch application, a cherry-pick, a revert, or a bisect." + (interactive) + (cond ((magit-merge-in-progress-p) (magit-merge-abort)) + ((magit-rebase-in-progress-p) (magit-rebase-abort)) + ((magit-am-in-progress-p) (magit-am-abort)) + ((magit-sequencer-in-progress-p) (magit-sequencer-abort)) + ((magit-bisect-in-progress-p) (magit-bisect-reset)))) + +;;; _ +(provide 'magit-extras) +;;; magit-extras.el ends here diff --git a/elpa/magit-20181113.1837/magit-fetch.el b/elpa/magit-20181113.1837/magit-fetch.el new file mode 100644 index 00000000..dc04233c --- /dev/null +++ b/elpa/magit-20181113.1837/magit-fetch.el @@ -0,0 +1,157 @@ +;;; magit-fetch.el --- download objects and refs -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements fetch commands. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-fetch-modules-jobs 4 + "Number of submodules to fetch in parallel. +Ignored for Git versions before v2.8.0." + :package-version '(magit . "2.12.0") + :group 'magit-commands + :type '(choice (const :tag "one at a time" nil) number)) + +;;; Commands + +;;;###autoload (autoload 'magit-fetch-popup "magit-fetch" nil t) +(magit-define-popup magit-fetch-popup + "Popup console for fetch commands." + :man-page "git-fetch" + :switches '((?p "Prune deleted branches" "--prune")) + :actions '("Configure" + (?C "variables..." magit-branch-config-popup) + "Fetch from" + (?p magit-get-push-remote magit-fetch-from-pushremote) + (?u magit-get-remote magit-fetch-from-upstream) + (?e "elsewhere" magit-fetch-other) + (?a "all remotes" magit-fetch-all) + "Fetch" + (?o "another branch" magit-fetch-branch) + (?r "explicit refspec" magit-fetch-refspec) + (?m "submodules" magit-fetch-modules)) + :default-action 'magit-fetch + :max-action-columns 1) + +(defun magit-git-fetch (remote args) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "fetch" remote args)) + +;;;###autoload +(defun magit-fetch-from-pushremote (args) + "Fetch from the push-remote of the current branch." + (interactive (list (magit-fetch-arguments))) + (--if-let (magit-get-push-remote) + (magit-git-fetch it args) + (--if-let (magit-get-current-branch) + (user-error "No push-remote is configured for %s" it) + (user-error "No branch is checked out")))) + +;;;###autoload +(defun magit-fetch-from-upstream (args) + "Fetch from the upstream repository of the current branch." + (interactive (list (magit-fetch-arguments))) + (--if-let (magit-get-remote) + (magit-git-fetch it args) + (--if-let (magit-get-current-branch) + (user-error "No upstream is configured for %s" it) + (user-error "No branch is checked out")))) + +;;;###autoload +(defun magit-fetch-other (remote args) + "Fetch from another repository." + (interactive (list (magit-read-remote "Fetch remote") + (magit-fetch-arguments))) + (magit-git-fetch remote args)) + +;;;###autoload +(defun magit-fetch-branch (remote branch args) + "Fetch a BRANCH from a REMOTE." + (interactive + (let ((remote (magit-read-remote-or-url "Fetch from remote or url"))) + (list remote + (magit-read-remote-branch "Fetch branch" remote) + (magit-fetch-arguments)))) + (magit-git-fetch remote (cons branch args))) + +;;;###autoload +(defun magit-fetch-refspec (remote refspec args) + "Fetch a REFSPEC from a REMOTE." + (interactive + (let ((remote (magit-read-remote-or-url "Fetch from remote or url"))) + (list remote + (magit-read-refspec "Fetch using refspec" remote) + (magit-fetch-arguments)))) + (magit-git-fetch remote (cons refspec args))) + +;;;###autoload +(defun magit-fetch-all (args) + "Fetch from all remotes." + (interactive (list (cl-intersection (magit-fetch-arguments) + (list "--verbose" "--prune") + :test #'equal))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "remote" "update" args)) + +;;;###autoload +(defun magit-fetch-all-prune () + "Fetch from all remotes, and prune. +Prune remote tracking branches for branches that have been +removed on the respective remote." + (interactive) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "remote" "update" "--prune")) + +;;;###autoload +(defun magit-fetch-all-no-prune () + "Fetch from all remotes." + (interactive) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "remote" "update")) + +;;;###autoload +(defun magit-fetch-modules (&optional all) + "Fetch all submodules. + +Option `magit-fetch-modules-jobs' controls how many submodules +are being fetched in parallel. Also fetch the super-repository, +because `git-fetch' does not support not doing that. With a +prefix argument fetch all remotes." + (interactive "P") + (magit-with-toplevel + (magit-run-git-async + "fetch" "--verbose" "--recurse-submodules" + (and magit-fetch-modules-jobs + (version<= "2.8.0" (magit-git-version)) + (list "-j" (number-to-string magit-fetch-modules-jobs))) + (and all "--all")))) + +;;; _ +(provide 'magit-fetch) +;;; magit-fetch.el ends here diff --git a/elpa/magit-20181113.1837/magit-files.el b/elpa/magit-20181113.1837/magit-files.el new file mode 100644 index 00000000..094539f2 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-files.el @@ -0,0 +1,493 @@ +;;; magit-files.el --- finding files -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements support for finding blobs, staged files, +;; and Git configuration files. It also implements modes useful in +;; buffers visiting files and blobs, and the commands used by those +;; modes. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +;;; Find Blob + +(defvar magit-find-file-hook nil) +(add-hook 'magit-find-file-hook #'magit-blob-mode) + +;;;###autoload +(defun magit-find-file (rev file) + "View FILE from REV. +Switch to a buffer visiting blob REV:FILE, +creating one if none already exists." + (interactive (magit-find-file-read-args "Find file")) + (switch-to-buffer (magit-find-file-noselect rev file))) + +;;;###autoload +(defun magit-find-file-other-window (rev file) + "View FILE from REV, in another window. +Like `magit-find-file', but create a new window or reuse an +existing one." + (interactive (magit-find-file-read-args "Find file in other window")) + (switch-to-buffer-other-window (magit-find-file-noselect rev file))) + +(defun magit-find-file-read-args (prompt) + (let ((rev (magit-read-branch-or-commit "Find file from revision"))) + (list rev (magit-read-file-from-rev rev prompt)))) + +(defun magit-find-file-noselect (rev file) + "Read FILE from REV into a buffer and return the buffer. +FILE must be relative to the top directory of the repository." + (magit-find-file-noselect-1 rev file 'magit-find-file-hook)) + +(defun magit-find-file-noselect-1 (rev file hookvar &optional revert) + "Read FILE from REV into a buffer and return the buffer. +FILE must be relative to the top directory of the repository. +An empty REV stands for index." + (let ((topdir (magit-toplevel))) + (when (file-name-absolute-p file) + (setq file (file-relative-name file topdir))) + (with-current-buffer (magit-get-revision-buffer-create rev file) + (when (or (not magit-buffer-file-name) + (if (eq revert 'ask-revert) + (y-or-n-p (format "%s already exists; revert it? " + (buffer-name)))) + revert) + (setq magit-buffer-revision + (if (string= rev "") "{index}" (magit-rev-format "%H" rev))) + (setq magit-buffer-refname rev) + (setq magit-buffer-file-name (expand-file-name file topdir)) + (setq default-directory + (let ((dir (file-name-directory magit-buffer-file-name))) + (if (file-exists-p dir) dir topdir))) + (setq-local revert-buffer-function #'magit-revert-rev-file-buffer) + (revert-buffer t t) + (run-hooks hookvar)) + (current-buffer)))) + +(defun magit-get-revision-buffer-create (rev file) + (magit-get-revision-buffer rev file t)) + +(defun magit-get-revision-buffer (rev file &optional create) + (funcall (if create 'get-buffer-create 'get-buffer) + (format "%s.~%s~" file (if (equal rev "") "index" + (subst-char-in-string ?/ ?_ rev))))) + +(defun magit-revert-rev-file-buffer (_ignore-auto noconfirm) + (when (or noconfirm + (and (not (buffer-modified-p)) + (catch 'found + (dolist (regexp revert-without-query) + (when (string-match regexp magit-buffer-file-name) + (throw 'found t))))) + (yes-or-no-p (format "Revert buffer from git %s? " + (if (equal magit-buffer-refname "") "{index}" + (concat "revision " magit-buffer-refname))))) + (let* ((inhibit-read-only t) + (default-directory (magit-toplevel)) + (file (file-relative-name magit-buffer-file-name)) + (coding-system-for-read (or coding-system-for-read 'undecided))) + (erase-buffer) + (magit-git-insert "cat-file" "-p" (concat magit-buffer-refname ":" file)) + (setq buffer-file-coding-system last-coding-system-used)) + (let ((buffer-file-name magit-buffer-file-name) + (after-change-major-mode-hook + (remq 'global-diff-hl-mode-enable-in-buffers + after-change-major-mode-hook))) + (normal-mode t)) + (setq buffer-read-only t) + (set-buffer-modified-p nil) + (goto-char (point-min)))) + +;;; Find Index + +(defvar magit-find-index-hook nil) + +(defun magit-find-file-index-noselect (file &optional revert) + "Read FILE from the index into a buffer and return the buffer. +FILE must to be relative to the top directory of the repository." + (magit-find-file-noselect-1 "" file 'magit-find-index-hook + (or revert 'ask-revert))) + +(defun magit-update-index () + "Update the index with the contents of the current buffer. +The current buffer has to be visiting a file in the index, which +is done using `magit-find-index-noselect'." + (interactive) + (let ((file (magit-file-relative-name))) + (unless (equal magit-buffer-refname "") + (user-error "%s isn't visiting the index" file)) + (if (y-or-n-p (format "Update index with contents of %s" (buffer-name))) + (let ((index (make-temp-file "index")) + (buffer (current-buffer))) + (when magit-wip-before-change-mode + (magit-wip-commit-before-change (list file) " before un-/stage")) + (let ((coding-system-for-write buffer-file-coding-system)) + (with-temp-file index + (insert-buffer-substring buffer))) + (magit-with-toplevel + (magit-call-git "update-index" "--cacheinfo" + (substring (magit-git-string "ls-files" "-s" file) + 0 6) + (magit-git-string "hash-object" "-t" "blob" "-w" + (concat "--path=" file) + "--" index) + file)) + (set-buffer-modified-p nil) + (when magit-wip-after-apply-mode + (magit-wip-commit-after-apply (list file) " after un-/stage"))) + (message "Abort"))) + (--when-let (magit-mode-get-buffer 'magit-status-mode) + (with-current-buffer it (magit-refresh))) + t) + +;;; Find Config File + +(defun magit-find-git-config-file (filename &optional wildcards) + "Edit a file located in the current repository's git directory. + +When \".git\", located at the root of the working tree, is a +regular file, then that makes it cumbersome to open a file +located in the actual git directory. + +This command is like `find-file', except that it temporarily +binds `default-directory' to the actual git directory, while +reading the FILENAME." + (interactive + (let ((default-directory (magit-git-dir))) + (find-file-read-args "Find file: " + (confirm-nonexistent-file-or-buffer)))) + (find-file filename wildcards)) + +(defun magit-find-git-config-file-other-window (filename &optional wildcards) + "Edit a file located in the current repository's git directory, in another window. + +When \".git\", located at the root of the working tree, is a +regular file, then that makes it cumbersome to open a file +located in the actual git directory. + +This command is like `find-file-other-window', except that it +temporarily binds `default-directory' to the actual git +directory, while reading the FILENAME." + (interactive + (let ((default-directory (magit-git-dir))) + (find-file-read-args "Find file in other window: " + (confirm-nonexistent-file-or-buffer)))) + (find-file-other-window filename wildcards)) + +(defun magit-find-git-config-file-other-frame (filename &optional wildcards) + "Edit a file located in the current repository's git directory, in another frame. + +When \".git\", located at the root of the working tree, is a +regular file, then that makes it cumbersome to open a file +located in the actual git directory. + +This command is like `find-file-other-frame', except that it +temporarily binds `default-directory' to the actual git +directory, while reading the FILENAME." + (interactive + (let ((default-directory (magit-git-dir))) + (find-file-read-args "Find file in other frame: " + (confirm-nonexistent-file-or-buffer)))) + (find-file-other-frame filename wildcards)) + +;;; File Mode + +(defvar magit-file-mode-map + (let ((map (make-sparse-keymap))) + (define-key map "\C-xg" 'magit-status) + (define-key map "\C-x\M-g" 'magit-dispatch-popup) + (define-key map "\C-c\M-g" 'magit-file-popup) + map) + "Keymap for `magit-file-mode'.") + +;;;###autoload (autoload 'magit-file-popup "magit" nil t) +(magit-define-popup magit-file-popup + "Popup console for Magit commands in file-visiting buffers." + :actions '((?s "Stage" magit-stage-file) + (?D "Diff..." magit-diff-buffer-file-popup) + (?L "Log..." magit-log-buffer-file-popup) + (?B "Blame..." magit-blame-popup) nil + (?u "Unstage" magit-unstage-file) + (?d "Diff" magit-diff-buffer-file) + (?l "Log" magit-log-buffer-file) + (?b "Blame" magit-blame-addition) + (?p "Prev blob" magit-blob-previous) + (?c "Commit" magit-commit-popup) nil + (?t "Trace" magit-log-trace-definition) + (?r (lambda () + (with-current-buffer magit-pre-popup-buffer + (and (not buffer-file-name) + (propertize "...removal" 'face 'default)))) + magit-blame-removal) + (?n "Next blob" magit-blob-next) + (?e "Edit line" magit-edit-line-commit) + nil nil + (?f (lambda () + (with-current-buffer magit-pre-popup-buffer + (and (not buffer-file-name) + (propertize "...reverse" 'face 'default)))) + magit-blame-reverse) + nil) + :max-action-columns 5) + +(defvar magit-file-mode-lighter "") + +(define-minor-mode magit-file-mode + "Enable some Magit features in a file-visiting buffer. + +Currently this only adds the following key bindings. +\n\\{magit-file-mode-map}" + :package-version '(magit . "2.2.0") + :lighter magit-file-mode-lighter + :keymap magit-file-mode-map) + +(defun magit-file-mode-turn-on () + (and buffer-file-name + (magit-inside-worktree-p t) + (magit-file-mode))) + +;;;###autoload +(define-globalized-minor-mode global-magit-file-mode + magit-file-mode magit-file-mode-turn-on + :package-version '(magit . "2.13.0") + :link '(info-link "(magit)Minor Mode for Buffers Visiting Files") + :group 'magit-essentials + :group 'magit-modes + :init-value t) +;; Unfortunately `:init-value t' only sets the value of the mode +;; variable but does not cause the mode function to be called, and we +;; cannot use `:initialize' to call that explicitly because the option +;; is defined before the functions, so we have to do it here. +(cl-eval-when (load) + (when global-magit-file-mode + (global-magit-file-mode 1))) + +;;; Blob Mode + +(defvar magit-blob-mode-map + (let ((map (make-sparse-keymap))) + (cond ((featurep 'jkl) + (define-key map "i" 'magit-blob-previous) + (define-key map "k" 'magit-blob-next) + (define-key map "j" 'magit-blame-addition) + (define-key map "l" 'magit-blame-removal) + (define-key map "f" 'magit-blame-reverse)) + (t + (define-key map "p" 'magit-blob-previous) + (define-key map "n" 'magit-blob-next) + (define-key map "b" 'magit-blame-addition) + (define-key map "r" 'magit-blame-removal) + (define-key map "f" 'magit-blame-reverse))) + (define-key map "q" 'magit-kill-this-buffer) + map) + "Keymap for `magit-blob-mode'.") + +(define-minor-mode magit-blob-mode + "Enable some Magit features in blob-visiting buffers. + +Currently this only adds the following key bindings. +\n\\{magit-blob-mode-map}" + :package-version '(magit . "2.3.0")) + +(defun magit-blob-next () + "Visit the next blob which modified the current file." + (interactive) + (if magit-buffer-file-name + (magit-blob-visit (or (magit-blob-successor magit-buffer-revision + magit-buffer-file-name) + magit-buffer-file-name) + (line-number-at-pos)) + (if (buffer-file-name (buffer-base-buffer)) + (user-error "You have reached the end of time") + (user-error "Buffer isn't visiting a file or blob")))) + +(defun magit-blob-previous () + "Visit the previous blob which modified the current file." + (interactive) + (if-let ((file (or magit-buffer-file-name + (buffer-file-name (buffer-base-buffer))))) + (--if-let (magit-blob-ancestor magit-buffer-revision file) + (magit-blob-visit it (line-number-at-pos)) + (user-error "You have reached the beginning of time")) + (user-error "Buffer isn't visiting a file or blob"))) + +(defun magit-blob-visit (blob-or-file line) + (if (stringp blob-or-file) + (find-file blob-or-file) + (pcase-let ((`(,rev ,file) blob-or-file)) + (magit-find-file rev file) + (apply #'message "%s (%s %s ago)" + (magit-rev-format "%s" rev) + (magit--age (magit-rev-format "%ct" rev))))) + (goto-char (point-min)) + (forward-line (1- line))) + +(defun magit-blob-ancestor (rev file) + (let ((lines (magit-with-toplevel + (magit-git-lines "log" "-2" "--format=%H" "--name-only" + "--follow" (or rev "HEAD") "--" file)))) + (if rev (cddr lines) (butlast lines 2)))) + +(defun magit-blob-successor (rev file) + (let ((lines (magit-with-toplevel + (magit-git-lines "log" "--format=%H" "--name-only" "--follow" + "HEAD" "--" file)))) + (catch 'found + (while lines + (if (equal (nth 2 lines) rev) + (throw 'found (list (nth 0 lines) (nth 1 lines))) + (setq lines (nthcdr 2 lines))))))) + +;;; File Commands + +(defun magit-file-rename (file newname) + "Rename the FILE to NEWNAME. +If FILE isn't tracked in Git, fallback to using `rename-file'." + (interactive + (let* ((file (magit-read-file "Rename file")) + (dir (file-name-directory file)) + (newname (read-file-name (format "Rename %s to file: " file) + (and dir (expand-file-name dir))))) + (list (expand-file-name file (magit-toplevel)) + (expand-file-name newname)))) + (if (magit-file-tracked-p (magit-convert-filename-for-git file)) + (let ((oldbuf (get-file-buffer file))) + (when (and oldbuf (buffer-modified-p oldbuf)) + (user-error "Save %s before moving it" file)) + (when (file-exists-p newname) + (user-error "%s already exists" newname)) + (magit-run-git "mv" + (magit-convert-filename-for-git file) + (magit-convert-filename-for-git newname)) + (when oldbuf + (with-current-buffer oldbuf + (let ((buffer-read-only buffer-read-only)) + (set-visited-file-name newname)) + (if (fboundp 'vc-refresh-state) + (vc-refresh-state) + (with-no-warnings + (vc-find-file-hook)))))) + (rename-file file newname current-prefix-arg) + (magit-refresh))) + +(defun magit-file-untrack (files &optional force) + "Untrack the selected FILES or one file read in the minibuffer. + +With a prefix argument FORCE do so even when the files have +staged as well as unstaged changes." + (interactive (list (or (--if-let (magit-region-values 'file t) + (progn + (unless (magit-file-tracked-p (car it)) + (user-error "Already untracked")) + (magit-confirm-files 'untrack it "Untrack")) + (list (magit-read-tracked-file "Untrack file")))) + current-prefix-arg)) + (magit-run-git "rm" "--cached" (and force "--force") "--" files)) + +(defun magit-file-delete (files &optional force) + "Delete the selected FILES or one file read in the minibuffer. + +With a prefix argument FORCE do so even when the files have +uncommitted changes. When the files aren't being tracked in +Git, then fallback to using `delete-file'." + (interactive (list (--if-let (magit-region-values 'file t) + (magit-confirm-files 'delete it "Delete") + (list (magit-read-file "Delete file"))) + current-prefix-arg)) + (if (magit-file-tracked-p (car files)) + (magit-call-git "rm" (and force "--force") "--" files) + (let ((topdir (magit-toplevel))) + (dolist (file files) + (delete-file (expand-file-name file topdir) t)))) + (magit-refresh)) + +;;;###autoload +(defun magit-file-checkout (rev file) + "Checkout FILE from REV." + (interactive + (let ((rev (magit-read-branch-or-commit + "Checkout from revision" magit-buffer-revision))) + (list rev (magit-read-file-from-rev rev "Checkout file")))) + (magit-with-toplevel + (magit-run-git "checkout" rev "--" file))) + +;;; Read File + +(defvar magit-read-file-hist nil) + +(defun magit-read-file-from-rev (rev prompt &optional default) + (let ((files (magit-revision-files rev))) + (magit-completing-read + prompt files nil t nil 'magit-read-file-hist + (car (member (or default (magit-current-file)) files))))) + +(defun magit-read-file (prompt &optional tracked-only) + (let ((choices (nconc (magit-list-files) + (unless tracked-only (magit-untracked-files))))) + (magit-completing-read + prompt choices nil t nil nil + (car (member (or (magit-section-value-if '(file submodule)) + (magit-file-relative-name nil tracked-only)) + choices))))) + +(defun magit-read-tracked-file (prompt) + (magit-read-file prompt t)) + +(defun magit-read-file-choice (prompt files &optional error default) + "Read file from FILES. + +If FILES has only one member, return that instead of prompting. +If FILES has no members, give a user error. ERROR can be given +to provide a more informative error. + +If DEFAULT is non-nil, use this as the default value instead of +`magit-current-file'." + (pcase (length files) + (0 (user-error (or error "No file choices"))) + (1 (car files)) + (_ (magit-completing-read + prompt files nil t nil 'magit-read-file-hist + (car (member (or default (magit-current-file)) files)))))) + +(defun magit-read-changed-file (rev-or-range prompt &optional default) + (magit-read-file-choice + prompt + (magit-changed-files rev-or-range) + default + (concat "No file changed in " rev-or-range))) + +(defun magit-read-files (prompt initial-contents) + (mapconcat 'identity + (completing-read-multiple (or prompt "File,s: ") + (magit-list-files) + nil nil initial-contents) ",")) + +;;; _ +(provide 'magit-files) +;;; magit-files.el ends here diff --git a/elpa/magit-20181113.1837/magit-git.el b/elpa/magit-20181113.1837/magit-git.el new file mode 100644 index 00000000..6ebf2981 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-git.el @@ -0,0 +1,2175 @@ +;;; magit-git.el --- Git functionality -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements wrappers for various Git plumbing commands. + +;;; Code: + +(require 'cl-lib) +(require 'dash) + +(eval-when-compile + (require 'subr-x)) + +(require 'magit-utils) +(require 'magit-section) + +(declare-function magit-call-git "magit-process" (&rest args)) +(declare-function magit-maybe-make-margin-overlay "magit-margin" ()) +(declare-function magit-process-buffer "magit-process" (&optional nodisplay)) +(declare-function magit-process-file "magit-process" (&rest args)) +(declare-function magit-process-insert-section "magit-process" + (pwe program args &optional errcode errlog)) +(declare-function magit-refresh "magit-mode" ()) +(defvar magit-process-error-message-regexps) +(defvar magit-refresh-args) ; from `magit-mode' for `magit-current-file' +(defvar magit-branch-prefer-remote-upstream) +(defvar magit-published-branches) +(defvar magit-diff-section-arguments) + +(defvar magit-tramp-process-environment nil) + +;;; Options + +;; For now this is shared between `magit-process' and `magit-git'. +(defgroup magit-process nil + "Git and other external processes used by Magit." + :group 'magit) + +(defvar magit-git-environment + (list (format "INSIDE_EMACS=%s,magit" emacs-version)) + "Prepended to `process-environment' while running git.") + +(defcustom magit-git-output-coding-system + (and (eq system-type 'windows-nt) 'utf-8) + "Coding system for receiving output from Git. + +If non-nil, the Git config value `i18n.logOutputEncoding' should +be set via `magit-git-global-arguments' to value consistent with +this." + :package-version '(magit . "2.9.0") + :group 'magit-process + :type '(choice (coding-system :tag "Coding system to decode Git output") + (const :tag "Use system default" nil))) + +(defvar magit-git-w32-path-hack nil + "Alist of (EXE . (PATHENTRY)). +This specifies what additional PATH setting needs to be added to +the environment in order to run the non-wrapper git executables +successfully.") + +(defcustom magit-git-executable + ;; Git might be installed in a different location on a remote, so + ;; it is better not to use the full path to the executable, except + ;; on Window were we would otherwise end up using one one of the + ;; wrappers "cmd/git.exe" or "cmd/git.cmd", which are much slower + ;; than using "bin/git.exe" directly. + (or (and (eq system-type 'windows-nt) + (--when-let (executable-find "git") + (ignore-errors + ;; Git for Windows 2.x provides cygpath so we can + ;; ask it for native paths. + (let* ((core-exe + (car + (process-lines + it "-c" + "alias.X=!x() { which \"$1\" | cygpath -mf -; }; x" + "X" "git"))) + (hack-entry (assoc core-exe magit-git-w32-path-hack)) + ;; Running the libexec/git-core executable + ;; requires some extra PATH entries. + (path-hack + (list (concat "PATH=" + (car (process-lines + it "-c" + "alias.P=!cygpath -wp \"$PATH\"" + "P")))))) + ;; The defcustom STANDARD expression can be + ;; evaluated many times, so make sure it is + ;; idempotent. + (if hack-entry + (setcdr hack-entry path-hack) + (push (cons core-exe path-hack) magit-git-w32-path-hack)) + core-exe)))) + "git") + "The Git executable used by Magit." + :group 'magit-process + :type 'string) + +(defcustom magit-git-global-arguments + `("--no-pager" "--literal-pathspecs" "-c" "core.preloadindex=true" + "-c" "log.showSignature=false" + ,@(and (eq system-type 'windows-nt) + (list "-c" "i18n.logOutputEncoding=UTF-8"))) + "Global Git arguments. + +The arguments set here are used every time the git executable is +run as a subprocess. They are placed right after the executable +itself and before the git command - as in `git HERE... COMMAND +REST'. See the manpage `git(1)' for valid arguments. + +Be careful what you add here, especially if you are using Tramp +to connect to servers with ancient Git versions. Never remove +anything that is part of the default value, unless you really +know what you are doing. And think very hard before adding +something; it will be used every time Magit runs Git for any +purpose." + :package-version '(magit . "2.9.0") + :group 'magit-git-arguments + :group 'magit-process + :type '(repeat string)) + +(defvar magit-git-debug nil + "Whether to enable additional reporting of git errors. + +Magit basically calls git for one of these two reasons: for +side-effects or to do something with its standard output. + +When git is run for side-effects then its output, including error +messages, go into the process buffer which is shown when using \ +\\\\[magit-process]. + +When git's output is consumed in some way, then it would be too +expensive to also insert it into this buffer, but when this +option is non-nil and git returns with a non-zero exit status, +then at least its standard error is inserted into this buffer. + +This is only intended for debugging purposes. Do not enable this +permanently, that would negatively affect performance.") + + +(defcustom magit-prefer-remote-upstream nil + "Whether to favor remote branches when reading the upstream branch. + +This controls whether commands that read a branch from the user +and then set it as the upstream branch, offer a local or a remote +branch as default completion candidate, when they have the choice. + +This affects all commands that use `magit-read-upstream-branch' +or `magit-read-starting-point', which includes all commands that +change the upstream and many which create new branches." + :package-version '(magit . "2.4.2") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-list-refs-sortby nil + "How to sort the ref collection in the prompt. + +This affects commands that read a ref. More specifically, it +controls the order of refs returned by `magit-list-refs', which +is called by functions like `magit-list-branch-names' to generate +the collection of refs. By default, refs are sorted according to +their full refname (i.e., 'refs/...'). + +Any value accepted by the `--sort' flag of `git for-each-ref' can +be used. For example, \"-creatordate\" places refs with more +recent committer or tagger dates earlier in the list. A list of +strings can also be given in order to pass multiple sort keys to +`git for-each-ref'. + +Note that, depending on the completion framework you use, this +may not be sufficient to change the order in which the refs are +displayed. It only controls the order of the collection passed +to `magit-completing-read' or, for commands that support reading +multiple strings, `read-from-minibuffer'. The completion +framework ultimately determines how the collection is displayed." + :package-version '(magit . "2.11.0") + :group 'magit-miscellanous + :type '(choice string (repeat string))) + +;;; Git + +(defvar magit--refresh-cache nil) + +(defmacro magit--with-refresh-cache (key &rest body) + (declare (indent 1) (debug (form body))) + (let ((k (cl-gensym))) + `(if magit--refresh-cache + (let ((,k ,key)) + (--if-let (assoc ,k (cdr magit--refresh-cache)) + (progn (cl-incf (caar magit--refresh-cache)) + (cdr it)) + (cl-incf (cdar magit--refresh-cache)) + (let ((value ,(macroexp-progn body))) + (push (cons ,k value) + (cdr magit--refresh-cache)) + value))) + ,@body))) + +(defvar magit-with-editor-envvar "GIT_EDITOR" + "The environment variable exported by `magit-with-editor'. +Set this to \"GIT_SEQUENCE_EDITOR\" if you do not want to use +Emacs to edit commit messages but would like to do so to edit +rebase sequences.") + +(defmacro magit-with-editor (&rest body) + "Like `with-editor' but let-bind some more variables. +Also respect the value of `magit-with-editor-envvar'." + (declare (indent 0) (debug (body))) + `(let ((magit-process-popup-time -1) + ;; The user may have customized `shell-file-name' to + ;; something which results in `w32-shell-dos-semantics' nil + ;; (which changes the quoting style used by + ;; `shell-quote-argument'), but Git for Windows expects shell + ;; quoting in the dos style. + (shell-file-name (if (and (eq system-type 'windows-nt) + ;; If we have Cygwin mount points, + ;; the git flavor is cygwin, so dos + ;; shell quoting is probably wrong. + (not magit-cygwin-mount-points)) + "cmdproxy" + shell-file-name))) + (with-editor* magit-with-editor-envvar + ,@body))) + +(defun magit-process-git-arguments (args) + "Prepare ARGS for a function that invokes Git. + +Magit has many specialized functions for running Git; they all +pass arguments through this function before handing them to Git, +to do the following. + +* Flatten ARGS, removing nil arguments. +* Prepend `magit-git-global-arguments' to ARGS. +* On w32 systems, encode to `w32-ansi-code-page'." + (setq args (append magit-git-global-arguments (-flatten args))) + (if (and (eq system-type 'windows-nt) (boundp 'w32-ansi-code-page)) + ;; On w32, the process arguments *must* be encoded in the + ;; current code-page (see #3250). + (mapcar (lambda (arg) + (encode-coding-string + arg (intern (format "cp%d" w32-ansi-code-page)))) + args) + args)) + +(defun magit-git-exit-code (&rest args) + "Execute Git with ARGS, returning its exit code." + (apply #'magit-process-file magit-git-executable nil nil nil + (magit-process-git-arguments args))) + +(defun magit-git-success (&rest args) + "Execute Git with ARGS, returning t if its exit code is 0." + (= (magit-git-exit-code args) 0)) + +(defun magit-git-failure (&rest args) + "Execute Git with ARGS, returning t if its exit code is 1." + (= (magit-git-exit-code args) 1)) + +(defun magit-git-str (&rest args) + "Execute Git with ARGS, returning the first line of its output. +If there is no output, return nil. If the output begins with a +newline, return an empty string. Like `magit-git-string' but +ignore `magit-git-debug'." + (setq args (-flatten args)) + (magit--with-refresh-cache (cons default-directory args) + (with-temp-buffer + (apply #'magit-process-file magit-git-executable nil (list t nil) nil + (magit-process-git-arguments args)) + (unless (bobp) + (goto-char (point-min)) + (buffer-substring-no-properties (point) (line-end-position)))))) + +(defun magit-git-output (&rest args) + "Execute Git with ARGS, returning its output." + (setq args (-flatten args)) + (magit--with-refresh-cache (cons default-directory args) + (with-temp-buffer + (apply #'magit-process-file magit-git-executable nil (list t nil) nil + (magit-process-git-arguments args)) + (buffer-substring-no-properties (point-min) (point-max))))) + +(define-error 'magit-invalid-git-boolean "Not a Git boolean") + +(defun magit-git-true (&rest args) + "Execute Git with ARGS, returning t if it prints \"true\". +If it prints \"false\", then return nil. For any other output +signal `magit-invalid-git-boolean'." + (pcase (magit-git-output args) + ((or "true" "true\n") t) + ((or "false" "false\n") nil) + (output (signal 'magit-invalid-git-boolean output)))) + +(defun magit-git-false (&rest args) + "Execute Git with ARGS, returning t if it prints \"false\". +If it prints \"true\", then return nil. For any other output +signal `magit-invalid-git-boolean'." + (pcase (magit-git-output args) + ((or "true" "true\n") nil) + ((or "false" "false\n") t) + (output (signal 'magit-invalid-git-boolean output)))) + +(defun magit-git-insert (&rest args) + "Execute Git with ARGS, inserting its output at point. +If Git exits with a non-zero exit status, then show a message and +add a section in the respective process buffer." + (setq args (magit-process-git-arguments args)) + (if magit-git-debug + (let (log) + (unwind-protect + (progn + (setq log (make-temp-file "magit-stderr")) + (delete-file log) + (let ((exit (apply #'magit-process-file magit-git-executable + nil (list t log) nil args))) + (when (> exit 0) + (let ((msg "Git failed")) + (when (file-exists-p log) + (setq msg (with-temp-buffer + (insert-file-contents log) + (goto-char (point-max)) + (cond + ((functionp magit-git-debug) + (funcall magit-git-debug (buffer-string))) + ((run-hook-wrapped + 'magit-process-error-message-regexps + (lambda (re) (re-search-backward re nil t))) + (match-string-no-properties 1))))) + (let ((magit-git-debug nil)) + (with-current-buffer (magit-process-buffer t) + (magit-process-insert-section default-directory + magit-git-executable + args exit log)))) + (message "%s" msg))) + exit)) + (ignore-errors (delete-file log)))) + (apply #'magit-process-file magit-git-executable + nil (list t nil) nil args))) + +(defun magit-git-string (&rest args) + "Execute Git with ARGS, returning the first line of its output. +If there is no output, return nil. If the output begins with a +newline, return an empty string." + (setq args (-flatten args)) + (magit--with-refresh-cache (cons default-directory args) + (with-temp-buffer + (apply #'magit-git-insert args) + (unless (bobp) + (goto-char (point-min)) + (buffer-substring-no-properties (point) (line-end-position)))))) + +(defun magit-git-lines (&rest args) + "Execute Git with ARGS, returning its output as a list of lines. +Empty lines anywhere in the output are omitted. + +If Git exits with a non-zero exit status, then report show a +message and add a section in the respective process buffer." + (with-temp-buffer + (apply #'magit-git-insert args) + (split-string (buffer-string) "\n" t))) + +(defun magit-git-items (&rest args) + "Execute Git with ARGS, returning its null-separated output as a list. +Empty items anywhere in the output are omitted. + +If Git exits with a non-zero exit status, then report show a +message and add a section in the respective process buffer." + (with-temp-buffer + (apply #'magit-git-insert args) + (split-string (buffer-string) "\0" t))) + +(defun magit-git-wash (washer &rest args) + "Execute Git with ARGS, inserting washed output at point. +Actually first insert the raw output at point. If there is no +output, call `magit-cancel-section'. Otherwise temporarily narrow +the buffer to the inserted text, move to its beginning, and then +call function WASHER with ARGS as its sole argument." + (declare (indent 1)) + (let ((beg (point))) + (setq args (-flatten args)) + (magit-git-insert args) + (if (= (point) beg) + (magit-cancel-section) + (unless (bolp) + (insert "\n")) + (save-restriction + (narrow-to-region beg (point)) + (goto-char beg) + (funcall washer args)) + (when (or (= (point) beg) + (= (point) (1+ beg))) + (magit-cancel-section)) + (magit-maybe-make-margin-overlay)))) + +(defun magit-git-version (&optional raw) + (--when-let (let (magit-git-global-arguments) + (ignore-errors (substring (magit-git-string "version") 12))) + (if raw it (and (string-match "^\\([0-9]+\\.[0-9]+\\.[0-9]+\\)" it) + (match-string 1 it))))) + +;;; Variables + +(defun magit-config-get-from-cached-list (key) + (gethash + ;; `git config --list' downcases first and last components of the key. + (--> key + (replace-regexp-in-string "\\`[^.]+" #'downcase it t t) + (replace-regexp-in-string "[^.]+\\'" #'downcase it t t)) + (magit--with-refresh-cache (cons (magit-toplevel) 'config) + (let ((configs (make-hash-table :test 'equal))) + (dolist (conf (magit-git-items "config" "--list" "-z")) + (let* ((nl-pos (cl-position ?\n conf)) + (key (substring conf 0 nl-pos)) + (val (if nl-pos (substring conf (1+ nl-pos)) ""))) + (puthash key (nconc (gethash key configs) (list val)) configs))) + configs)))) + +(defun magit-get (&rest keys) + "Return the value of the Git variable specified by KEYS." + (car (last (apply 'magit-get-all keys)))) + +(defun magit-get-all (&rest keys) + "Return all values of the Git variable specified by KEYS." + (let ((magit-git-debug nil) + (arg (and (or (null (car keys)) + (string-prefix-p "--" (car keys))) + (pop keys))) + (key (mapconcat 'identity keys "."))) + (if (and magit--refresh-cache (not arg)) + (magit-config-get-from-cached-list key) + (magit-git-items "config" arg "-z" "--get-all" key)))) + +(defun magit-get-boolean (&rest keys) + "Return the boolean value of the Git variable specified by KEYS." + (let ((key (mapconcat 'identity keys "."))) + (if magit--refresh-cache + (equal "true" (car (last (magit-config-get-from-cached-list key)))) + (equal (magit-git-str "config" "--bool" key) "true")))) + +(defun magit-set (value &rest keys) + "Set the value of the Git variable specified by KEYS to VALUE." + (let ((arg (and (or (null (car keys)) + (string-prefix-p "--" (car keys))) + (pop keys))) + (key (mapconcat 'identity keys "."))) + (if value + (magit-git-success "config" arg key value) + (magit-git-success "config" arg "--unset" key)) + value)) + +(gv-define-setter magit-get (val &rest keys) + `(magit-set ,val ,@keys)) + +(defun magit-set-all (values &rest keys) + "Set all values of the Git variable specified by KEYS to VALUES." + (let ((arg (and (or (null (car keys)) + (string-prefix-p "--" (car keys))) + (pop keys))) + (var (mapconcat 'identity keys "."))) + (when (magit-get var) + (magit-call-git "config" arg "--unset-all" var)) + (dolist (v values) + (magit-call-git "config" arg "--add" var v)))) + +;;; Files + +(defun magit--safe-default-directory (&optional file) + (catch 'unsafe-default-dir + (let ((dir (file-name-as-directory + (expand-file-name (or file default-directory)))) + (previous nil)) + (while (not (magit-file-accessible-directory-p dir)) + (setq dir (file-name-directory (directory-file-name dir))) + (when (equal dir previous) + (throw 'unsafe-default-dir nil)) + (setq previous dir)) + dir))) + +(defmacro magit--with-safe-default-directory (file &rest body) + (declare (indent 1) (debug (form body))) + `(when-let ((default-directory (magit--safe-default-directory ,file))) + ,@body)) + +(defun magit-gitdir (&optional directory) + "Return the absolute and resolved path of the .git directory. + +If the `GIT_DIR' environment variable is define then return that. +Otherwise return the .git directory for DIRECTORY, or if that is +nil, then for `default-directory' instead. If the directory is +not located inside a Git repository, then return nil." + (let ((default-directory (or directory default-directory))) + (magit-git-dir))) + +(defun magit-git-dir (&optional path) + "Return the absolute and resolved path of the .git directory. + +If the `GIT_DIR' environment variable is define then return that. +Otherwise return the .git directory for `default-directory'. If +the directory is not located inside a Git repository, then return +nil." + (magit--with-refresh-cache (list default-directory 'magit-git-dir path) + (magit--with-safe-default-directory nil + (when-let ((dir (magit-rev-parse-safe "--git-dir"))) + (setq dir (file-name-as-directory (magit-expand-git-file-name dir))) + (unless (file-remote-p dir) + (setq dir (concat (file-remote-p default-directory) dir))) + (if path (expand-file-name (convert-standard-filename path) dir) dir))))) + +(defvar magit--separated-gitdirs nil) + +(defun magit--record-separated-gitdir () + (let ((topdir (magit-toplevel)) + (gitdir (magit-git-dir))) + ;; Kludge: git-annex converts submodule gitdirs to symlinks. See #3599. + (when (file-symlink-p (directory-file-name gitdir)) + (setq gitdir (file-truename gitdir))) + ;; We want to delete the entry for `topdir' here, rather than within + ;; (unless ...), in case a `--separate-git-dir' repository was switched to + ;; the standard structure (i.e., "topdir/.git/"). + (setq magit--separated-gitdirs (cl-delete topdir + magit--separated-gitdirs + :key #'car :test #'equal)) + (unless (equal (file-name-as-directory (expand-file-name ".git" topdir)) + gitdir) + (push (cons topdir gitdir) magit--separated-gitdirs)))) + +(defun magit-toplevel (&optional directory) + "Return the absolute path to the toplevel of the current repository. + +From within the working tree or control directory of a repository +return the absolute path to the toplevel directory of the working +tree. As a special case, from within a bare repository return +the control directory instead. When called outside a repository +then return nil. + +When optional DIRECTORY is non-nil then return the toplevel for +that directory instead of the one for `default-directory'. + +Try to respect the option `find-file-visit-truename', i.e. when +the value of that option is nil, then avoid needlessly returning +the truename. When a symlink to a sub-directory of the working +tree is involved, or when called from within a sub-directory of +the gitdir or from the toplevel of a gitdir, which itself is not +located within the working tree, then it is not possible to avoid +returning the truename." + (magit--with-refresh-cache + (cons (or directory default-directory) 'magit-toplevel) + (magit--with-safe-default-directory directory + (if-let ((topdir (magit-rev-parse-safe "--show-toplevel"))) + (let (updir) + (setq topdir (magit-expand-git-file-name topdir)) + (if (and + ;; Always honor these settings. + (not find-file-visit-truename) + (not (getenv "GIT_WORK_TREE")) + ;; `--show-cdup' is the relative path to the toplevel + ;; from `(file-truename default-directory)'. Here we + ;; pretend it is relative to `default-directory', and + ;; go to that directory. Then we check whether + ;; `--show-toplevel' still returns the same value and + ;; whether `--show-cdup' now is the empty string. If + ;; both is the case, then we are at the toplevel of + ;; the same working tree, but also avoided needlessly + ;; following any symlinks. + (progn + (setq updir (file-name-as-directory + (magit-rev-parse-safe "--show-cdup"))) + (setq updir (if (file-name-absolute-p updir) + (concat (file-remote-p default-directory) updir) + (expand-file-name updir))) + (let ((default-directory updir)) + (and (string-equal (magit-rev-parse-safe "--show-cdup") "") + (--when-let (magit-rev-parse-safe "--show-toplevel") + (string-equal (magit-expand-git-file-name it) + topdir)))))) + updir + (concat (file-remote-p default-directory) + (file-name-as-directory topdir)))) + (when-let ((gitdir (magit-rev-parse-safe "--git-dir"))) + (setq gitdir (file-name-as-directory + (if (file-name-absolute-p gitdir) + ;; We might have followed a symlink. + (concat (file-remote-p default-directory) + (magit-expand-git-file-name gitdir)) + (expand-file-name gitdir)))) + (if (magit-bare-repo-p) + gitdir + (let* ((link (expand-file-name "gitdir" gitdir)) + (wtree (and (file-exists-p link) + (magit-file-line link)))) + (cond + ((and wtree + ;; Ignore .git/gitdir files that result from a + ;; Git bug. See #2364. + (not (equal wtree ".git"))) + ;; Return the linked working tree. + (file-name-directory wtree)) + ;; The working directory may not be the parent directory of + ;; .git if it was set up with `git init --separate-git-dir'. + ;; See #2955. + ((car (rassoc gitdir magit--separated-gitdirs))) + (t + ;; Step outside the control directory to enter the working tree. + (file-name-directory (directory-file-name gitdir))))))))))) + +(defmacro magit-with-toplevel (&rest body) + (declare (indent defun) (debug (body))) + (let ((toplevel (cl-gensym "toplevel"))) + `(let ((,toplevel (magit-toplevel))) + (if ,toplevel + (let ((default-directory ,toplevel)) + ,@body) + (magit--not-inside-repository-error))))) + +(define-error 'magit-outside-git-repo "Not inside Git repository") +(define-error 'magit-git-executable-not-found + "Git executable cannot be found (see https://magit.vc/goto/e6a78ed2)") + +(defun magit--not-inside-repository-error () + (if (executable-find magit-git-executable) + (signal 'magit-outside-git-repo default-directory) + (signal 'magit-git-executable-not-found magit-git-executable))) + +(defun magit-inside-gitdir-p (&optioal noerror) + "Return t if `default-directory' is below the repository directory. +If it is below the working directory, then return nil. +If it isn't below either, then signal an error unless NOERROR +is non-nil, in which case return nil." + (and (magit--assert-default-directory noerror) + ;; Below a repository directory that is not located below the + ;; working directory "git rev-parse --is-inside-git-dir" prints + ;; "false", which is wrong. + (let ((gitdir (magit-git-dir))) + (cond (gitdir (file-in-directory-p default-directory gitdir)) + (noerror nil) + (t (signal 'magit-outside-git-repo default-directory)))))) + +(defun magit-inside-worktree-p (&optional noerror) + "Return t if `default-directory' is below the working directory. +If it is below the repository directory, then return nil. +If it isn't below either, then signal an error unless NOERROR +is non-nil, in which case return nil." + (and (magit--assert-default-directory noerror) + (condition-case nil + (magit-rev-parse-true "--is-inside-work-tree") + (magit-invalid-git-boolean + (and (not noerror) + (signal 'magit-outside-git-repo default-directory)))))) + +(defun magit-bare-repo-p (&optional noerror) + "Return t if the current repository is bare. +If it is non-bare, then return nil. If `default-directory' +isn't below a Git repository, then signal an error unless +NOERROR is non-nil, in which case return nil." + (and (magit--assert-default-directory noerror) + (condition-case nil + (magit-rev-parse-true "--is-bare-repository") + (magit-invalid-git-boolean + (and (not noerror) + (signal 'magit-outside-git-repo default-directory)))))) + +(defun magit--assert-default-directory (&optional noerror) + (or (file-directory-p default-directory) + (and (not noerror) + (let ((exists (file-exists-p default-directory))) + (signal (if exists 'file-error 'file-missing) + (list "Running git in directory" + (if exists + "Not a directory" + "No such file or directory") + default-directory)))))) + +(defun magit-git-repo-p (directory &optional non-bare) + "Return t if DIRECTORY is a Git repository. +When optional NON-BARE is non-nil also return nil if DIRECTORY is +a bare repository." + (and (file-directory-p directory) ; Avoid archives, see #3397. + (or (file-regular-p (expand-file-name ".git" directory)) + (file-directory-p (expand-file-name ".git" directory)) + (and (not non-bare) + (file-regular-p (expand-file-name "HEAD" directory)) + (file-directory-p (expand-file-name "refs" directory)) + (file-directory-p (expand-file-name "objects" directory)))))) + +(defvar-local magit-buffer-revision nil) +(defvar-local magit-buffer-refname nil) +(defvar-local magit-buffer-file-name nil) +(put 'magit-buffer-revision 'permanent-local t) +(put 'magit-buffer-refname 'permanent-local t) +(put 'magit-buffer-file-name 'permanent-local t) + +(defun magit-file-relative-name (&optional file tracked) + "Return the path of FILE relative to the repository root. + +If optional FILE is nil or omitted, return the relative path of +the file being visited in the current buffer, if any, else nil. +If the file is not inside a Git repository, then return nil. + +If TRACKED is non-nil, return the path only if it matches a +tracked file." + (unless file + (with-current-buffer (or (buffer-base-buffer) + (current-buffer)) + (setq file (or magit-buffer-file-name buffer-file-name + (and (derived-mode-p 'dired-mode) default-directory))))) + (when (and file (or (not tracked) + (magit-file-tracked-p (file-relative-name file)))) + (--when-let (magit-toplevel + (magit--safe-default-directory + (directory-file-name (file-name-directory file)))) + (file-relative-name file it)))) + +(defun magit-file-tracked-p (file) + (magit-git-success "ls-files" "--error-unmatch" file)) + +(defun magit-list-files (&rest args) + (apply #'magit-git-items "ls-files" "-z" "--full-name" args)) + +(defun magit-tracked-files () + (magit-list-files "--cached")) + +(defun magit-untracked-files (&optional all files) + (magit-list-files "--other" (unless all "--exclude-standard") "--" files)) + +(defun magit-unstaged-files (&optional nomodules files) + (magit-git-items "diff-files" "-z" "--name-only" + (and nomodules "--ignore-submodules") + "--" files)) + +(defun magit-staged-files (&optional nomodules files) + (magit-git-items "diff-index" "-z" "--name-only" "--cached" + (and nomodules "--ignore-submodules") + (magit-headish) "--" files)) + +(defun magit-binary-files (&rest args) + (--mapcat (and (string-match "^-\t-\t\\(.+\\)" it) + (list (match-string 1 it))) + (apply #'magit-git-items + "diff" "-z" "--numstat" "--ignore-submodules" + args))) + +(defun magit-unmerged-files () + (magit-git-items "diff-files" "-z" "--name-only" "--diff-filter=U")) + +(defun magit-ignored-files () + (magit-git-items "ls-files" "-z" "--others" "--ignored" + "--exclude-standard" "--directory")) + +(defun magit-revision-files (rev) + (magit-with-toplevel + (magit-git-items "ls-tree" "-z" "-r" "--name-only" rev))) + +(defun magit-changed-files (rev-or-range &optional other-rev) + "Return list of files the have changed between two revisions. +If OTHER-REV is non-nil, REV-OR-RANGE should be a revision, not a +range. Otherwise, it can be any revision or range accepted by +\"git diff\" (i.e., , .., or ...)." + (magit-with-toplevel + (magit-git-items "diff" "-z" "--name-only" rev-or-range other-rev))) + +(defun magit-renamed-files (revA revB) + (--map (cons (nth 1 it) (nth 2 it)) + (-partition 3 (magit-git-items + "diff-tree" "-r" "--diff-filter=R" "-z" "-M" + revA revB)))) + +(defun magit-file-status (&rest args) + (with-temp-buffer + (save-excursion (magit-git-insert "status" "-z" args)) + (let ((pos (point)) status) + (while (> (skip-chars-forward "[:print:]") 0) + (let ((x (char-after pos)) + (y (char-after (1+ pos))) + (file (buffer-substring (+ pos 3) (point)))) + (forward-char) + (if (memq x '(?R ?C)) + (progn + (setq pos (point)) + (skip-chars-forward "[:print:]") + (push (list file (buffer-substring pos (point)) x y) status) + (forward-char)) + (push (list file nil x y) status))) + (setq pos (point))) + status))) + +(defcustom magit-cygwin-mount-points + (when (eq system-type 'windows-nt) + (cl-sort (--map (if (string-match "^\\(.*\\) on \\(.*\\) type" it) + (cons (file-name-as-directory (match-string 2 it)) + (file-name-as-directory (match-string 1 it))) + (lwarn '(magit) :error + "Failed to parse Cygwin mount: %S" it)) + ;; If --exec-path is not a native Windows path, + ;; then we probably have a cygwin git. + (let ((process-environment + (append magit-git-environment process-environment))) + (and (not (string-match-p + "\\`[a-zA-Z]:" + (car (process-lines + magit-git-executable "--exec-path")))) + (ignore-errors (process-lines "mount"))))) + #'> :key (pcase-lambda (`(,cyg . ,_win)) (length cyg)))) + "Alist of (CYGWIN . WIN32) directory names. +Sorted from longest to shortest CYGWIN name." + :package-version '(magit . "2.3.0") + :group 'magit-process + :type '(alist :key-type string :value-type directory)) + +(defun magit-expand-git-file-name (filename) + (unless (file-name-absolute-p filename) + (setq filename (expand-file-name filename))) + (-if-let ((cyg . win) + (cl-assoc filename magit-cygwin-mount-points + :test (lambda (f cyg) (string-prefix-p cyg f)))) + (concat win (substring filename (length cyg))) + filename)) + +(defun magit-convert-filename-for-git (filename) + "Convert FILENAME so that it can be passed to git. +1. If it's a remote filename, then remove the remote part. +2. Deal with an `windows-nt' Emacs vs. Cygwin Git incompatibility." + (if (file-name-absolute-p filename) + (-if-let ((cyg . win) + (cl-rassoc filename magit-cygwin-mount-points + :test (lambda (f win) (string-prefix-p win f)))) + (concat cyg (substring filename (length win))) + (or (file-remote-p filename 'localname) + filename)) + filename)) + +(defun magit-decode-git-path (path) + (if (eq (aref path 0) ?\") + (decode-coding-string (read path) + (or magit-git-output-coding-system + (car default-process-coding-system)) + t) + path)) + +(defun magit-file-at-point () + (magit-section-case + (file (oref it value)) + (hunk (magit-section-parent-value it)))) + +(defun magit-current-file () + (or (magit-file-relative-name) + (magit-file-at-point) + (and (derived-mode-p 'magit-log-mode) + (car (nth 2 magit-refresh-args))))) + +;;; Predicates + +(defun magit-no-commit-p () + "Return t if there is no commit in the current Git repository." + (not (magit-rev-verify "HEAD"))) + +(defun magit-merge-commit-p (commit) + "Return t if COMMIT is a merge commit." + (> (length (magit-commit-parents commit)) 1)) + +(defun magit-anything-staged-p (&optional ignore-submodules &rest files) + "Return t if there are any staged changes. +If optional FILES is non-nil, then only changes to those files +are considered." + (magit-git-failure "diff" "--quiet" "--cached" + (and ignore-submodules "--ignore-submodules") + "--" files)) + +(defun magit-anything-unstaged-p (&optional ignore-submodules &rest files) + "Return t if there are any unstaged changes. +If optional FILES is non-nil, then only changes to those files +are considered." + (magit-git-failure "diff" "--quiet" + (and ignore-submodules "--ignore-submodules") + "--" files)) + +(defun magit-anything-modified-p (&optional ignore-submodules &rest files) + "Return t if there are any staged or unstaged changes. +If optional FILES is non-nil, then only changes to those files +are considered." + (or (apply 'magit-anything-staged-p ignore-submodules files) + (apply 'magit-anything-unstaged-p ignore-submodules files))) + +(defun magit-anything-unmerged-p (&rest files) + "Return t if there are any merge conflicts. +If optional FILES is non-nil, then only conflicts in those files +are considered." + (and (magit-git-string "ls-files" "--unmerged" files) t)) + +(defun magit-module-worktree-p (module) + (magit-with-toplevel + (file-exists-p (expand-file-name (expand-file-name ".git" module))))) + +(defun magit-module-no-worktree-p (module) + (not (magit-module-worktree-p module))) + +(defun magit-ignore-submodules-p () + (cl-find-if (lambda (arg) + (string-prefix-p "--ignore-submodules" arg)) + magit-diff-section-arguments)) + +;;; Revisions and References + +(defun magit-rev-parse (&rest args) + "Execute `git rev-parse ARGS', returning first line of output. +If there is no output, return nil." + (apply #'magit-git-string "rev-parse" args)) + +(defun magit-rev-parse-safe (&rest args) + "Execute `git rev-parse ARGS', returning first line of output. +If there is no output, return nil. Like `magit-rev-parse' but +ignore `magit-git-debug'." + (apply #'magit-git-str "rev-parse" args)) + +(defun magit-rev-parse-true (&rest args) + "Execute `git rev-parse ARGS', returning t if it prints \"true\". +If it prints \"false\", then return nil. For any other output +signal an error." + (magit-git-true "rev-parse" args)) + +(defun magit-rev-parse-false (&rest args) + "Execute `git rev-parse ARGS', returning t if it prints \"false\". +If it prints \"true\", then return nil. For any other output +signal an error." + (magit-git-false "rev-parse" args)) + +(defun magit-rev-parse-p (&rest args) + "Execute `git rev-parse ARGS', returning t if it prints \"true\". +Return t if the first (and usually only) output line is the +string \"true\", otherwise return nil." + (equal (magit-git-str "rev-parse" args) "true")) + +(defun magit-rev-verify (rev) + (magit-rev-parse-safe "--verify" rev)) + +(defun magit-rev-verify-commit (rev) + "Return full hash for REV if it names an existing commit." + (magit-rev-verify (concat rev "^{commit}"))) + +(defun magit-rev-equal (a b) + (magit-git-success "diff" "--quiet" a b)) + +(defun magit-rev-eq (a b) + (let ((a (magit-rev-verify a)) + (b (magit-rev-verify b))) + (and a b (equal a b)))) + +(defun magit-rev-ancestor-p (a b) + "Return non-nil if commit A is an ancestor of commit B." + (magit-git-success "merge-base" "--is-ancestor" a b)) + +(defun magit-rev-head-p (rev) + (or (equal rev "HEAD") + (and rev + (not (string-match-p "\\.\\." rev)) + (equal (magit-rev-parse rev) + (magit-rev-parse "HEAD"))))) + +(defun magit-rev-author-p (rev) + "Return t if the user is the author of REV. +More precisely return t if `user.name' is equal to the author +name of REV and/or `user.email' is equal to the author email +of REV." + (or (equal (magit-get "user.name") (magit-rev-format "%an" rev)) + (equal (magit-get "user.email") (magit-rev-format "%ae" rev)))) + +(defun magit-rev-name (rev &optional pattern) + "Return a symbolic name for REV. +PATTERN is passed to the `--refs' flag of `git-name-rev' and can +be used to limit the result to a matching ref. When structured +as \"refs//*\", PATTERN is taken as a namespace. In this +case, the name returned by `git-name-rev' is discarded if it +corresponds to a ref outside of the namespace." + (--when-let (magit-git-string "name-rev" "--name-only" "--no-undefined" + (and pattern (concat "--refs=" pattern)) + rev) + ;; We can't use name-rev's --exclude to filter out "*/PATTERN" + ;; because --exclude wasn't added until Git v2.13.0. + (if (and pattern + (string-match-p "\\`refs/[^/]+/\\*\\'" pattern)) + (let ((namespace (substring pattern 0 -1))) + (unless (and (string-match-p namespace it) + (not (magit-rev-verify (concat namespace it)))) + it)) + it))) + +(defun magit-rev-branch (rev) + (--when-let (magit-rev-name rev "refs/heads/*") + (unless (string-match-p "[~^]" it) it))) + +(defun magit-get-shortname (rev) + (let* ((fn (apply-partially 'magit-rev-name rev)) + (name (or (funcall fn "refs/tags/*") + (funcall fn "refs/heads/*") + (funcall fn "refs/remotes/*")))) + (cond ((not name) + (magit-rev-parse "--short" rev)) + ((string-match "^\\(?:tags\\|remotes\\)/\\(.+\\)" name) + (if (magit-ref-ambiguous-p (match-string 1 name)) + name + (match-string 1 name))) + (t (magit-ref-maybe-qualify name))))) + +(defun magit-name-branch (rev &optional lax) + (or (magit-name-local-branch rev) + (magit-name-remote-branch rev) + (and lax (or (magit-name-local-branch rev t) + (magit-name-remote-branch rev t))))) + +(defun magit-name-local-branch (rev &optional lax) + (--when-let (magit-rev-name rev "refs/heads/*") + (and (or lax (not (string-match-p "[~^]" it))) it))) + +(defun magit-name-remote-branch (rev &optional lax) + (--when-let (magit-rev-name rev "refs/remotes/*") + (and (or lax (not (string-match-p "[~^]" it))) + (substring it 8)))) + +(defun magit-name-tag (rev &optional lax) + (--when-let (magit-rev-name rev "refs/tags/*") + (and (or lax (not (string-match-p "[~^]" it))) + (substring it 5)))) + +(defun magit-ref-fullname (name) + "Return fully qualified refname for NAME. +If NAME is ambiguous, return nil. NAME may include suffixes such +as \"^1\" and \"~3\". " + (save-match-data + (if (string-match "\\`\\([^^~]+\\)\\(.*\\)" name) + (--when-let (magit-rev-parse "--symbolic-full-name" + (match-string 1 name)) + (concat it (match-string 2 name))) + (error "`name' has an unrecognized format")))) + +(defun magit-ref-ambiguous-p (name) + (not (magit-ref-fullname name))) + +(cl-defun magit-ref-maybe-qualify (name &optional (prefix "heads/")) + "If NAME is ambiguous, prepend PREFIX to it." + (concat (and (magit-ref-ambiguous-p name) + prefix) + name)) + +(defun magit-ref-exists-p (ref) + (magit-git-success "show-ref" "--verify" ref)) + +(defun magit-ref-equal (a b) + "Return t if the refs A and B are `equal'. +A symbolic-ref pointing to some ref, is `equal' to that ref, +as are two symbolic-refs pointing to the same ref." + (equal (magit-ref-fullname a) + (magit-ref-fullname b))) + +(defun magit-ref-eq (a b) + "Return t if the refs A and B are `eq'. +A symbolic-ref is `eq' to itself, but not to the ref it points +to, or to some other symbolic-ref that points to the same ref." + (let ((symbolic-a (magit-symbolic-ref-p a)) + (symbolic-b (magit-symbolic-ref-p b))) + (or (and symbolic-a + symbolic-b + (equal a b)) + (and (not symbolic-a) + (not symbolic-b) + (magit-ref-equal a b))))) + +(defun magit-headish () + "Return \"HEAD\" or if that doesn't exist the hash of the empty tree." + (if (magit-no-commit-p) + (magit-git-string "mktree") + "HEAD")) + +(defun magit-branch-at-point () + (magit-section-case + (branch (oref it value)) + (commit (or (magit--painted-branch-at-point) + (magit-name-branch (oref it value)))))) + +(defun magit--painted-branch-at-point (&optional type) + (or (and (not (eq type 'remote)) + (memq (get-text-property (point) 'face) + (list 'magit-branch-local + 'magit-branch-current)) + (cdr (magit-split-branch-name + (thing-at-point 'git-revision t)))) + (and (not (eq type 'local)) + (memq (get-text-property (point) 'face) + (list 'magit-branch-remote + 'magit-branch-remote-head)) + (thing-at-point 'git-revision t)))) + +(defun magit-local-branch-at-point () + (magit-section-case + (branch (let ((branch (magit-ref-maybe-qualify (oref it value)))) + (when (member branch (magit-list-local-branch-names)) + branch))) + (commit (or (magit--painted-branch-at-point 'local) + (magit-name-local-branch (oref it value)))))) + +(defun magit-remote-branch-at-point () + (magit-section-case + (branch (let ((branch (oref it value))) + (when (member branch (magit-list-remote-branch-names)) + branch))) + (commit (or (magit--painted-branch-at-point 'remote) + (magit-name-remote-branch (oref it value)))))) + +(defun magit-commit-at-point () + (or (magit-section-value-if 'commit) + (and (derived-mode-p 'magit-revision-mode) + (car magit-refresh-args)))) + +(defun magit-branch-or-commit-at-point () + (or magit-buffer-refname + (magit-section-case + (branch (magit-ref-maybe-qualify (oref it value))) + (commit (or (magit--painted-branch-at-point) + (let ((rev (oref it value))) + (or (magit-name-branch rev) + (magit-get-shortname rev) + rev)))) + (tag (magit-ref-maybe-qualify (oref it value) "tags/"))) + (thing-at-point 'git-revision t) + (and (derived-mode-p 'magit-revision-mode + 'magit-merge-preview-mode) + (car magit-refresh-args)))) + +(defun magit-tag-at-point () + (magit-section-case + (tag (oref it value)) + (commit (magit-name-tag (oref it value))))) + +(defun magit-stash-at-point () + (magit-section-value-if 'stash)) + +(defun magit-remote-at-point () + (magit-section-case + (remote (oref it value)) + (branch (magit-section-parent-value it)))) + +(defun magit-module-at-point (&optional predicate) + (when (magit-section-match 'magit-module-section) + (let ((module (oref (magit-current-section) value))) + (and (or (not predicate) + (funcall predicate module)) + module)))) + +(defun magit-get-current-branch () + "Return the refname of the currently checked out branch. +Return nil if no branch is currently checked out." + (magit-git-string "symbolic-ref" "--short" "HEAD")) + +(defvar magit-get-previous-branch-timeout 0.5 + "Maximum time to spend in `magit-get-previous-branch'. +Given as a number of seconds.") + +(defun magit-get-previous-branch () + "Return the refname of the previously checked out branch. +Return nil if no branch can be found in the `HEAD' reflog +which is different from the current branch and still exists. +The amount of time spent searching is limited by +`magit-get-previous-branch-timeout'." + (let ((t0 (float-time)) + (current (magit-get-current-branch)) + (i 1) prev) + (while (if (> (- (float-time) t0) magit-get-previous-branch-timeout) + (setq prev nil) ;; Timed out. + (and (setq prev (magit-rev-verify (format "@{-%i}" i))) + (or (not (setq prev (magit-rev-branch prev))) + (equal prev current)))) + (cl-incf i)) + prev)) + +(defun magit-get-upstream-ref (&optional branch) + (and (or branch (setq branch (magit-get-current-branch))) + (let ((remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge"))) + (when (and remote merge) + (cond ((string-equal remote ".") merge) + ((string-prefix-p "refs/heads/" merge) + (concat "refs/remotes/" remote "/" (substring merge 11)))))))) + +(defun magit-set-upstream-branch (branch upstream) + (if upstream + (pcase-let ((`(,remote . ,merge) (magit-split-branch-name upstream))) + (setf (magit-get (format "branch.%s.remote" branch)) remote) + (setf (magit-get (format "branch.%s.merge" branch)) + (concat "refs/heads/" merge))) + (magit-call-git "branch" "--unset-upstream" branch))) + +(defun magit-get-upstream-branch (&optional branch verify) + (and (or branch (setq branch (magit-get-current-branch))) + (when-let ((remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge"))) + (and (string-prefix-p "refs/heads/" merge) + (let* ((upstream (substring merge 11)) + (upstream + (cond ((string-equal remote ".") + (propertize upstream 'face 'magit-branch-local)) + ((string-match-p "[@:]" remote) + (propertize (concat remote " " upstream) + 'face 'magit-branch-remote)) + (t + (propertize (concat remote "/" upstream) + 'face 'magit-branch-remote))))) + (and (or (not verify) + (magit-rev-verify upstream)) + upstream)))))) + +(defun magit-get-indirect-upstream-branch (branch &optional force) + (let ((remote (magit-get "branch" branch "remote"))) + (and remote (not (equal remote ".")) + ;; The user has opted in... + (or force + (--some (if (magit-git-success "check-ref-format" "--branch" it) + (equal it branch) + (string-match-p it branch)) + magit-branch-prefer-remote-upstream)) + ;; and local BRANCH tracks a remote branch... + (let ((upstream (magit-get-upstream-branch branch))) + ;; whose upstream... + (and upstream + ;; has the same name as BRANCH and... + (equal (substring upstream (1+ (length remote))) branch) + ;; and can be fast-forwarded to BRANCH. + (magit-rev-ancestor-p upstream branch) + upstream))))) + +(defun magit-get-upstream-remote (&optional branch non-local) + (unless branch + (setq branch (magit-get-current-branch))) + (and branch + (let ((remote (magit-get "branch" branch "remote"))) + (and (not (and non-local (equal remote "."))) + remote)))) + +(defun magit-get-push-remote (&optional branch) + (or (and (or branch (setq branch (magit-get-current-branch))) + (magit-get "branch" branch "pushRemote")) + (magit-get "remote.pushDefault"))) + +(defun magit-get-push-branch (&optional branch verify) + (and (or branch (setq branch (magit-get-current-branch))) + (when-let ((remote (magit-get-push-remote branch)) + (push-branch (concat remote "/" branch))) + (and (or (not verify) + (magit-rev-verify push-branch)) + (propertize push-branch 'face 'magit-branch-remote))))) + +(defun magit-get-@{push}-branch (&optional branch) + (let ((ref (magit-rev-parse "--symbolic-full-name" + (concat branch "@{push}")))) + (when (and ref (string-prefix-p "refs/remotes/" ref)) + (substring ref 13)))) + +(defun magit-get-remote (&optional branch) + (when (or branch (setq branch (magit-get-current-branch))) + (let ((remote (magit-get "branch" branch "remote"))) + (unless (equal remote ".") + remote)))) + +(defun magit-get-some-remote (&optional branch) + (or (magit-get-remote branch) + (and (magit-branch-p "master") + (magit-get-remote "master")) + (let ((remotes (magit-list-remotes))) + (or (car (member "origin" remotes)) + (car remotes))))) + +(defun magit-branch-merged-p (branch &optional target) + "Return non-nil if BRANCH is merged into its upstream and TARGET. + +TARGET defaults to the current branch. If `HEAD' is detached and +TARGET is nil, then always return nil. As a special case, if +TARGET is t, then return non-nil if BRANCH is merged into any one +of the other local branches. + +If, and only if, BRANCH has an upstream, then only return non-nil +if BRANCH is merged into both TARGET (as described above) as well +as into its upstream." + (and (--if-let (and (magit-branch-p branch) + (magit-get-upstream-branch branch)) + (magit-git-success "merge-base" "--is-ancestor" branch it) + t) + (if (eq target t) + (delete (magit-name-local-branch branch) + (magit-list-containing-branches branch)) + (--when-let (or target (magit-get-current-branch)) + (magit-git-success "merge-base" "--is-ancestor" branch it))))) + +(defun magit-split-branch-name (branch) + (cond ((member branch (magit-list-local-branch-names)) + (cons "." branch)) + ((string-match " " branch) + (pcase-let ((`(,url ,branch) (split-string branch " "))) + (cons url branch))) + ((string-match "/" branch) + (let ((remote (substring branch 0 (match-beginning 0)))) + (if (save-match-data (member remote (magit-list-remotes))) + (cons remote (substring branch (match-end 0))) + (error "Invalid branch name %s" branch)))))) + +(defun magit-get-current-tag (&optional rev with-distance) + "Return the closest tag reachable from REV. + +If optional REV is nil, then default to `HEAD'. +If optional WITH-DISTANCE is non-nil then return (TAG COMMITS), +if it is `dirty' return (TAG COMMIT DIRTY). COMMITS is the number +of commits in `HEAD' but not in TAG and DIRTY is t if there are +uncommitted changes, nil otherwise." + (--when-let (magit-git-str "describe" "--long" "--tags" + (and (eq with-distance 'dirty) "--dirty") rev) + (save-match-data + (string-match + "\\(.+\\)-\\(?:0[0-9]*\\|\\([0-9]+\\)\\)-g[0-9a-z]+\\(-dirty\\)?$" it) + (if with-distance + `(,(match-string 1 it) + ,(string-to-number (or (match-string 2 it) "0")) + ,@(and (match-string 3 it) (list t))) + (match-string 1 it))))) + +(defun magit-get-next-tag (&optional rev with-distance) + "Return the closest tag from which REV is reachable. + +If optional REV is nil, then default to `HEAD'. +If no such tag can be found or if the distance is 0 (in which +case it is the current tag, not the next), return nil instead. +If optional WITH-DISTANCE is non-nil, then return (TAG COMMITS) +where COMMITS is the number of commits in TAG but not in REV." + (--when-let (magit-git-str "describe" "--contains" (or rev "HEAD")) + (save-match-data + (when (string-match "^[^^~]+" it) + (setq it (match-string 0 it)) + (unless (equal it (magit-get-current-tag rev)) + (if with-distance + (list it (car (magit-rev-diff-count it rev))) + it)))))) + +(defvar magit-list-refs-namespaces + '("refs/heads" "refs/remotes" "refs/tags" "refs/pull")) + +(defun magit-list-refs (&optional namespaces format sortby) + "Return list of references. + +When NAMESPACES is non-nil, list refs from these namespaces +rather than those from `magit-list-refs-namespaces'. + +FORMAT is passed to the `--format' flag of `git for-each-ref' +and defaults to \"%(refname)\". If the format is \"%(refname)\" +or \"%(refname:short)\", then drop the symbolic-ref \"HEAD\". + +SORTBY is a key or list of keys to pass to the `--sort' flag of +`git for-each-ref'. When nil, use `magit-list-refs-sortby'" + (unless format + (setq format "%(refname)")) + (let ((refs (magit-git-lines "for-each-ref" + (concat "--format=" format) + (--map (concat "--sort=" it) + (pcase (or sortby magit-list-refs-sortby) + ((and val (pred stringp)) (list val)) + ((and val (pred listp)) val))) + (or namespaces magit-list-refs-namespaces)))) + (if (member format '("%(refname)" "%(refname:short)")) + (--remove (string-match-p "\\(\\`\\|/\\)HEAD\\'" it) refs) + refs))) + +(defun magit-list-branches () + (magit-list-refs (list "refs/heads" "refs/remotes"))) + +(defun magit-list-local-branches () + (magit-list-refs "refs/heads")) + +(defun magit-list-remote-branches (&optional remote) + (magit-list-refs (concat "refs/remotes/" remote))) + +(defun magit-list-related-branches (relation &optional commit arg) + (--remove (string-match-p "\\(\\`(HEAD\\|HEAD -> \\)" it) + (--map (substring it 2) + (magit-git-lines "branch" arg relation commit)))) + +(defun magit-list-containing-branches (&optional commit arg) + (magit-list-related-branches "--contains" commit arg)) + +(defun magit-list-publishing-branches (&optional commit) + (--filter (magit-rev-ancestor-p commit it) + magit-published-branches)) + +(defun magit-list-merged-branches (&optional commit arg) + (magit-list-related-branches "--merged" commit arg)) + +(defun magit-list-unmerged-branches (&optional commit arg) + (magit-list-related-branches "--no-merged" commit arg)) + +(defun magit-list-unmerged-to-upstream-branches () + (--filter (when-let ((upstream (magit-get-upstream-branch it))) + (member it (magit-list-unmerged-branches upstream))) + (magit-list-local-branch-names))) + +(defun magit-list-branches-pointing-at (commit) + (let ((re (format "\\`%s refs/\\(heads\\|remotes\\)/\\(.*\\)\\'" + (magit-rev-verify commit)))) + (--keep (and (string-match re it) + (let ((name (match-string 2 it))) + (and (not (string-suffix-p "HEAD" name)) + name))) + (magit-git-lines "show-ref")))) + +(defun magit-list-refnames (&optional namespaces) + (magit-list-refs namespaces "%(refname:short)")) + +(defun magit-list-branch-names () + (magit-list-refnames (list "refs/heads" "refs/remotes"))) + +(defun magit-list-local-branch-names () + (magit-list-refnames "refs/heads")) + +(defun magit-list-remote-branch-names (&optional remote relative) + (if (and remote relative) + (let ((regexp (format "^refs/remotes/%s/\\(.+\\)" remote))) + (--mapcat (when (string-match regexp it) + (list (match-string 1 it))) + (magit-list-remote-branches remote))) + (magit-list-refnames (concat "refs/remotes/" remote)))) + +(defun magit-format-refs (format &rest args) + (let ((lines (magit-git-lines + "for-each-ref" (concat "--format=" format) + (or args (list "refs/heads" "refs/remotes" "refs/tags"))))) + (if (string-match-p "\f" format) + (--map (split-string it "\f") lines) + lines))) + +(defun magit-list-remotes () + (magit-git-lines "remote")) + +(defun magit-list-tags () + (magit-git-lines "tag")) + +(defun magit-list-stashes (&optional format) + (magit-git-lines "stash" "list" (concat "--format=" (or format "%gd")))) + +(defun magit-list-active-notes-refs () + "Return notes refs according to `core.notesRef' and `notes.displayRef'." + (magit-git-lines "for-each-ref" "--format=%(refname)" + (or (magit-get "core.notesRef") "refs/notes/commits") + (magit-get-all "notes.displayRef"))) + +(defun magit-list-notes-refnames () + (--map (substring it 6) (magit-list-refnames "refs/notes"))) + +(defun magit-remote-list-tags (remote) + (--keep (and (not (string-match-p "\\^{}$" it)) + (substring it 51)) + (magit-git-lines "ls-remote" "--tags" remote))) + +(defun magit-remote-list-branches (remote) + (--keep (and (not (string-match-p "\\^{}$" it)) + (substring it 52)) + (magit-git-lines "ls-remote" "--heads" remote))) + +(defun magit-remote-list-refs (remote) + (--keep (and (not (string-match-p "\\^{}$" it)) + (substring it 41)) + (magit-git-lines "ls-remote" remote))) + +(defun magit-list-module-paths () + (--mapcat (and (string-match "^160000 [0-9a-z]\\{40\\} 0\t\\(.+\\)$" it) + (list (match-string 1 it))) + (magit-git-items "ls-files" "-z" "--stage"))) + +(defun magit-get-submodule-name (path) + "Return the name of the submodule at PATH. +PATH has to be relative to the super-repository." + (cadr (split-string + (car (or (magit-git-items + "config" "-z" + "-f" (expand-file-name ".gitmodules" (magit-toplevel)) + "--get-regexp" "^submodule\\..*\\.path$" + (concat "^" (regexp-quote (directory-file-name path)) "$")) + (error "No such submodule `%s'" path))) + "\n"))) + +(defun magit-list-worktrees () + (let (worktrees worktree) + (dolist (line (let ((magit-git-global-arguments + ;; KLUDGE At least in v2.8.3 this triggers a segfault. + (remove "--no-pager" magit-git-global-arguments))) + (magit-git-lines "worktree" "list" "--porcelain"))) + (cond ((string-prefix-p "worktree" line) + (push (setq worktree (list (substring line 9) nil nil nil)) + worktrees)) + ((string-equal line "bare") + (let* ((default-directory (car worktree)) + (wt (and (not (magit-get-boolean "core.bare")) + (magit-get "core.worktree")))) + (if (and wt (file-exists-p (expand-file-name wt))) + (progn (setf (nth 0 worktree) (expand-file-name wt)) + (setf (nth 2 worktree) (magit-rev-parse "HEAD")) + (setf (nth 3 worktree) (magit-get-current-branch))) + (setf (nth 1 worktree) t)))) + ((string-prefix-p "HEAD" line) + (setf (nth 2 worktree) (substring line 5))) + ((string-prefix-p "branch" line) + (setf (nth 3 worktree) (substring line 18))) + ((string-equal line "detached")))) + (nreverse worktrees))) + +(defun magit-symbolic-ref-p (name) + (magit-git-success "symbolic-ref" "--quiet" name)) + +(defun magit-ref-p (rev) + (or (car (member rev (magit-list-refs))) + (car (member rev (magit-list-refnames))))) + +(defun magit-branch-p (rev) + (or (car (member rev (magit-list-branches))) + (car (member rev (magit-list-branch-names))))) + +(defun magit-local-branch-p (rev) + (or (car (member rev (magit-list-local-branches))) + (car (member rev (magit-list-local-branch-names))))) + +(defun magit-remote-branch-p (rev) + (or (car (member rev (magit-list-remote-branches))) + (car (member rev (magit-list-remote-branch-names))))) + +(defun magit-branch-set-face (branch) + (propertize branch 'face (if (magit-local-branch-p branch) + 'magit-branch-local + 'magit-branch-remote))) + +(defun magit-tag-p (rev) + (car (member rev (magit-list-tags)))) + +(defun magit-remote-p (string) + (car (member string (magit-list-remotes)))) + +(defun magit-rev-diff-count (a b) + "Return the commits in A but not B and vice versa. +Return a list of two integers: (A>B B>A)." + (mapcar 'string-to-number + (split-string (magit-git-string "rev-list" + "--count" "--left-right" + (concat a "..." b)) + "\t"))) + +(defun magit-abbrev-length () + (--if-let (magit-get "core.abbrev") + (string-to-number it) + ;; Guess the length git will be using based on an example + ;; abbreviation. Actually HEAD's abbreviation might be an + ;; outlier, so use the shorter of the abbreviations for two + ;; commits. When a commit does not exist, then fall back + ;; to the default of 7. See #3034. + (min (--if-let (magit-rev-parse "--short" "HEAD") (length it) 7) + (--if-let (magit-rev-parse "--short" "HEAD~") (length it) 7)))) + +(defun magit-abbrev-arg (&optional arg) + (format "--%s=%d" (or arg "abbrev") (magit-abbrev-length))) + +(defun magit-rev-abbrev (rev) + (magit-rev-parse (magit-abbrev-arg "short") rev)) + +(defun magit-commit-children (commit &optional args) + (mapcar #'car + (--filter (member commit (cdr it)) + (--map (split-string it " ") + (magit-git-lines + "log" "--format=%H %P" + (or args (list "--branches" "--tags" "--remotes")) + "--not" commit))))) + +(defun magit-commit-parents (commit) + (--when-let (magit-git-string "rev-list" "-1" "--parents" commit) + (cdr (split-string it)))) + +(defun magit-patch-id (rev) + (with-temp-buffer + (magit-process-file + shell-file-name nil '(t nil) nil shell-command-switch + (let ((exec (shell-quote-argument magit-git-executable))) + (format "%s diff-tree -u %s | %s patch-id" exec rev exec))) + (car (split-string (buffer-string))))) + +(defun magit-rev-format (format &optional rev args) + (let ((str (magit-git-string "show" "--no-patch" + (concat "--format=" format) args + (if rev (concat rev "^{commit}") "HEAD") "--"))) + (unless (string-equal str "") + str))) + +(defun magit-rev-insert-format (format &optional rev args) + (magit-git-insert "show" "--no-patch" + (concat "--format=" format) args + (if rev (concat rev "^{commit}") "HEAD") "--")) + +(defun magit-format-rev-summary (rev) + (--when-let (magit-rev-format "%h %s" rev) + (string-match " " it) + (put-text-property 0 (match-beginning 0) 'face 'magit-hash it) + it)) + +(defvar magit-ref-namespaces + '(("\\`HEAD\\'" . magit-head) + ("\\`refs/tags/\\(.+\\)" . magit-tag) + ("\\`refs/heads/\\(.+\\)" . magit-branch-local) + ("\\`refs/remotes/\\(.+\\)" . magit-branch-remote) + ("\\`refs/bisect/\\(bad\\)" . magit-bisect-bad) + ("\\`refs/bisect/\\(skip.*\\)" . magit-bisect-skip) + ("\\`refs/bisect/\\(good.*\\)" . magit-bisect-good) + ("\\`refs/stash$" . magit-refname-stash) + ("\\`refs/wip/\\(.+\\)" . magit-refname-wip) + ("\\`refs/pullreqs/\\(.+\\)" . magit-refname-pullreq) + ("\\`\\(bad\\):" . magit-bisect-bad) + ("\\`\\(skip\\):" . magit-bisect-skip) + ("\\`\\(good\\):" . magit-bisect-good) + ("\\`\\(.+\\)" . magit-refname)) + "How refs are formatted for display. + +Each entry controls how a certain type of ref is displayed, and +has the form (REGEXP . FACE). REGEXP is a regular expression +used to match full refs. The first entry whose REGEXP matches +the reference is used. + +In log and revision buffers the first regexp submatch becomes the +\"label\" that represents the ref and is propertized with FONT. +In refs buffers the displayed text is controlled by other means +and this option only controls what face is used.") + +(defun magit-format-ref-labels (string) + ;; To support Git <2.2.0, we remove the surrounding parentheses here + ;; rather than specifying that STRING should be generated with Git's + ;; "%D" placeholder. + (setq string (->> string + (replace-regexp-in-string "\\`\\s-*(" "") + (replace-regexp-in-string ")\\s-*\\'" ""))) + (save-match-data + (let ((regexp "\\(, \\|tag: \\|HEAD -> \\)") + names) + (if (and (derived-mode-p 'magit-log-mode) + (member "--simplify-by-decoration" (cadr magit-refresh-args))) + (let ((branches (magit-list-local-branch-names)) + (re (format "^%s/.+" (regexp-opt (magit-list-remotes))))) + (setq names + (--map (cond ((string-equal it "HEAD") it) + ((string-prefix-p "refs/" it) it) + ((member it branches) (concat "refs/heads/" it)) + ((string-match re it) (concat "refs/remotes/" it)) + (t (concat "refs/" it))) + (split-string + (replace-regexp-in-string "tag: " "refs/tags/" string) + regexp t)))) + (setq names (split-string string regexp t))) + (let (state head upstream tags branches remotes other combined) + (dolist (ref names) + (let* ((face (cdr (--first (string-match (car it) ref) + magit-ref-namespaces))) + (name (propertize (or (match-string 1 ref) ref) 'face face))) + (cl-case face + ((magit-bisect-bad magit-bisect-skip magit-bisect-good) + (setq state name)) + (magit-head + (setq head (propertize "@" 'face 'magit-head))) + (magit-tag (push name tags)) + (magit-branch-local (push name branches)) + (magit-branch-remote (push name remotes)) + (t (push name other))))) + (setq remotes + (-keep + (lambda (name) + (if (string-match "\\`\\([^/]*\\)/\\(.*\\)\\'" name) + (let ((r (match-string 1 name)) + (b (match-string 2 name))) + (and (not (equal b "HEAD")) + (if (equal (concat "refs/remotes/" name) + (magit-git-string + "symbolic-ref" + (format "refs/remotes/%s/HEAD" r))) + (propertize name + 'face 'magit-branch-remote-head) + name))) + name)) + remotes)) + (let* ((current (magit-get-current-branch)) + (target (magit-get-upstream-branch current t))) + (dolist (name branches) + (let ((push (car (member (magit-get-push-branch name) remotes)))) + (when push + (setq remotes (delete push remotes)) + (string-match "^[^/]*/" push) + (setq push (substring push 0 (match-end 0)))) + (cond + ((equal name current) + (setq head + (concat push + (propertize name 'face 'magit-branch-current)))) + ((equal name target) + (setq upstream + (concat push + (propertize name 'face '(magit-branch-upstream + magit-branch-local))))) + (t + (push (concat push name) combined))))) + (when (and target (not upstream)) + (if (member target remotes) + (progn + (add-face-text-property 0 (length target) + 'magit-branch-upstream nil target) + (setq upstream target) + (setq remotes (delete target remotes))) + (when-let ((target (car (member target combined)))) + (add-face-text-property 0 (length target) + 'magit-branch-upstream nil target) + (setq upstream target) + (setq combined (delete target combined)))))) + (mapconcat #'identity + (-flatten `(,state + ,head + ,upstream + ,@(nreverse tags) + ,@(nreverse combined) + ,@(nreverse remotes) + ,@other)) + " "))))) + +(defun magit-object-type (object) + (magit-git-string "cat-file" "-t" object)) + +(defmacro magit-with-blob (commit file &rest body) + (declare (indent 2) + (debug (form form body))) + `(with-temp-buffer + (let ((buffer-file-name ,file)) + (save-excursion + (magit-git-insert "cat-file" "-p" + (concat ,commit ":" buffer-file-name))) + (decode-coding-inserted-region + (point-min) (point-max) buffer-file-name t nil nil t) + ,@body))) + +(defmacro magit-with-temp-index (tree arg &rest body) + (declare (indent 2) (debug (form form body))) + (let ((file (cl-gensym "file"))) + `(let ((magit--refresh-cache nil) + (,file (magit-convert-filename-for-git + (make-temp-name (magit-git-dir "index.magit."))))) + (unwind-protect + (magit-with-toplevel + (--when-let ,tree + (or (magit-git-success "read-tree" ,arg it + (concat "--index-output=" ,file)) + (error "Cannot read tree %s" it))) + (if (file-remote-p default-directory) + (let ((magit-tramp-process-environment + (cons (concat "GIT_INDEX_FILE=" ,file) + magit-tramp-process-environment))) + ,@body) + (let ((process-environment + (cons (concat "GIT_INDEX_FILE=" ,file) + process-environment))) + ,@body))) + (ignore-errors + (delete-file (concat (file-remote-p default-directory) ,file))))))) + +(defun magit-commit-tree (message &optional tree &rest parents) + (magit-git-string "commit-tree" "--no-gpg-sign" "-m" message + (--mapcat (list "-p" it) (delq nil parents)) + (or tree + (magit-git-string "write-tree") + (error "Cannot write tree")))) + +(defun magit-commit-worktree (message &optional arg &rest other-parents) + (magit-with-temp-index "HEAD" arg + (and (magit-update-files (magit-unstaged-files)) + (apply #'magit-commit-tree message nil "HEAD" other-parents)))) + +(defun magit-update-files (files) + (magit-git-success "update-index" "--add" "--remove" "--" files)) + +(defun magit-update-ref (ref message rev &optional stashish) + (let ((magit--refresh-cache nil)) + (or (if (not (version< (magit-git-version) "2.6.0")) + (zerop (magit-call-git "update-ref" "--create-reflog" + "-m" message ref rev + (or (magit-rev-verify ref) ""))) + ;; `--create-reflog' didn't exist before v2.6.0 + (let ((oldrev (magit-rev-verify ref)) + (logfile (magit-git-dir (concat "logs/" ref)))) + (unless (file-exists-p logfile) + (when oldrev + (magit-git-success "update-ref" "-d" ref oldrev)) + (make-directory (file-name-directory logfile) t) + (with-temp-file logfile) + (when (and oldrev (not stashish)) + (magit-git-success "update-ref" "-m" "enable reflog" + ref oldrev "")))) + (magit-git-success "update-ref" "-m" message ref rev + (or (magit-rev-verify ref) ""))) + (error "Cannot update %s with %s" ref rev)))) + +(defconst magit-range-re + (concat "\\`\\([^ \t]*[^.]\\)?" ; revA + "\\(\\.\\.\\.?\\)" ; range marker + "\\([^.][^ \t]*\\)?\\'")) ; revB + +(defun magit-split-range (range) + (and (string-match magit-range-re range) + (let ((beg (or (match-string 1 range) "HEAD")) + (end (or (match-string 3 range) "HEAD"))) + (cons (if (string-equal (match-string 2 range) "...") + (magit-git-string "merge-base" beg end) + beg) + end)))) + +(defvar magit-thingatpt--git-revision-chars "-_./[:alnum:]@{}^~!" + "Characters allowable in filenames, excluding space and colon.") + +(put 'git-revision 'end-op + (lambda () + (re-search-forward + (concat "\\=[" magit-thingatpt--git-revision-chars "]*") + nil t))) + +(put 'git-revision 'beginning-op + (lambda () + (if (re-search-backward + (concat "[^" magit-thingatpt--git-revision-chars "]") nil t) + (forward-char) + (goto-char (point-min))))) + +(put 'git-revision 'thing-at-point 'magit-thingatpt--git-revision) + +(defun magit-thingatpt--git-revision () + (--when-let (bounds-of-thing-at-point 'git-revision) + (let ((text (buffer-substring-no-properties (car it) (cdr it)))) + (and (magit-rev-verify-commit text) text)))) + +;;; Completion + +(defvar magit-revision-history nil) + +(defun magit-read-branch (prompt &optional secondary-default) + (magit-completing-read prompt (magit-list-branch-names) + nil t nil 'magit-revision-history + (or (magit-branch-at-point) + secondary-default + (magit-get-current-branch)))) + +(defun magit-read-branch-or-commit (prompt &optional secondary-default) + (or (magit-completing-read prompt (cons "HEAD" (magit-list-refnames)) + nil nil nil 'magit-revision-history + (or (magit-branch-or-commit-at-point) + secondary-default + (magit-get-current-branch))) + (user-error "Nothing selected"))) + +(defun magit-read-range-or-commit (prompt &optional secondary-default) + (magit-read-range + prompt + (or (--when-let (magit-region-values '(commit branch) t) + (deactivate-mark) + (concat (car (last it)) ".." (car it))) + (magit-branch-or-commit-at-point) + secondary-default + (magit-get-current-branch)))) + +(defun magit-read-range (prompt &optional default) + (magit-completing-read-multiple prompt + (magit-list-refnames) + "\\.\\.\\.?" + default 'magit-revision-history)) + +(defun magit-read-remote-branch + (prompt &optional remote default local-branch require-match) + (let ((choice (magit-completing-read + prompt + (-union (and local-branch + (if remote + (concat remote "/" local-branch) + (--map (concat it "/" local-branch) + (magit-list-remotes)))) + (magit-list-remote-branch-names remote t)) + nil require-match nil 'magit-revision-history default))) + (if (or remote (string-match "\\`\\([^/]+\\)/\\(.+\\)" choice)) + choice + (user-error "`%s' doesn't have the form REMOTE/BRANCH" choice)))) + +(defun magit-read-refspec (prompt remote) + (magit-completing-read prompt + (prog2 (message "Determining available refs...") + (magit-remote-list-refs remote) + (message "Determining available refs...done")))) + +(defun magit-read-local-branch (prompt &optional secondary-default) + (magit-completing-read prompt (magit-list-local-branch-names) + nil t nil 'magit-revision-history + (or (magit-local-branch-at-point) + secondary-default + (magit-get-current-branch)))) + +(defun magit-read-local-branch-or-commit (prompt) + (let ((branches (magit-list-local-branch-names)) + (commit (magit-commit-at-point))) + (or (magit-completing-read prompt + (if commit (cons commit branches) branches) + nil nil nil 'magit-revision-history + (or (magit-local-branch-at-point) commit)) + (user-error "Nothing selected")))) + +(defun magit-read-local-branch-or-ref (prompt &optional secondary-default) + (magit-completing-read prompt (nconc (magit-list-local-branch-names) + (magit-list-refs "refs/")) + nil t nil 'magit-revision-history + (or (magit-local-branch-at-point) + secondary-default + (magit-get-current-branch)))) + +(defun magit-read-other-branch + (prompt &optional exclude secondary-default no-require-match) + (let* ((current (magit-get-current-branch)) + (atpoint (magit-branch-at-point)) + (exclude (or exclude current)) + (default (or (and (not (equal atpoint exclude)) atpoint) + (and (not (equal current exclude)) current) + secondary-default + (magit-get-previous-branch)))) + (magit-completing-read prompt (delete exclude (magit-list-branch-names)) + nil (not no-require-match) + nil 'magit-revision-history default))) + +(defun magit-read-other-branch-or-commit + (prompt &optional exclude secondary-default) + (let* ((current (magit-get-current-branch)) + (atpoint (magit-branch-or-commit-at-point)) + (exclude (or exclude current)) + (default (or (and (not (equal atpoint exclude)) atpoint) + (and (not (equal current exclude)) current) + secondary-default + (magit-get-previous-branch)))) + (or (magit-completing-read prompt (delete exclude (magit-list-refnames)) + nil nil nil 'magit-revision-history default) + (user-error "Nothing selected")))) + +(defun magit-read-other-local-branch + (prompt &optional exclude secondary-default no-require-match) + (let* ((current (magit-get-current-branch)) + (atpoint (magit-local-branch-at-point)) + (exclude (or exclude current)) + (default (or (and (not (equal atpoint exclude)) atpoint) + (and (not (equal current exclude)) current) + secondary-default + (magit-get-previous-branch)))) + (magit-completing-read prompt + (delete exclude (magit-list-local-branch-names)) + nil (not no-require-match) + nil 'magit-revision-history default))) + +(defun magit-read-branch-prefer-other (prompt) + (let* ((current (magit-get-current-branch)) + (commit (magit-commit-at-point)) + (atrev (and commit (magit-list-branches-pointing-at commit))) + (atpoint (magit--painted-branch-at-point))) + (magit-completing-read prompt (magit-list-branch-names) + nil t nil 'magit-revision-history + (or (magit-section-value-if 'branch) + atpoint + (and (not (cdr atrev)) (car atrev)) + (--first (not (equal it current)) atrev) + (magit-get-previous-branch) + (car atrev))))) + +(cl-defun magit-read-upstream-branch + (&optional (branch (magit-get-current-branch)) prompt) + (magit-completing-read + (or prompt (format "Change upstream of %s to" branch)) + (-union (--map (concat it "/" branch) + (magit-list-remotes)) + (delete branch (magit-list-branch-names))) + nil nil nil 'magit-revision-history + (or (let ((r (magit-remote-branch-at-point)) + (l (magit-branch-at-point))) + (when (and l (equal l branch)) + (setq l nil)) + (if magit-prefer-remote-upstream (or r l) (or l r))) + (let ((r (magit-branch-p "origin/master")) + (l (and (not (equal branch "master")) + (magit-branch-p "master")))) + (if magit-prefer-remote-upstream (or r l) (or l r))) + (let ((previous (magit-get-previous-branch))) + (and (not (equal previous branch)) previous))))) + +(defun magit-read-starting-point (prompt &optional branch) + (or (magit-completing-read + (concat prompt + (and branch + (if (bound-and-true-p ivy-mode) + ;; Ivy-mode strips faces from prompt. + (format " `%s'" branch) + (concat " " + (propertize branch 'face 'magit-branch-local)))) + " starting at") + (nconc (list "HEAD") + (magit-list-refnames) + (directory-files (magit-git-dir) nil "_HEAD\\'")) + nil nil nil 'magit-revision-history + (magit--default-starting-point)) + (user-error "Nothing selected"))) + +(defun magit--default-starting-point () + (or (let ((r (magit-remote-branch-at-point)) + (l (magit-local-branch-at-point))) + (if magit-prefer-remote-upstream (or r l) (or l r))) + (magit-commit-at-point) + (magit-stash-at-point) + (magit-get-current-branch))) + +(defun magit-read-tag (prompt &optional require-match) + (magit-completing-read prompt (magit-list-tags) nil + require-match nil 'magit-revision-history + (magit-tag-at-point))) + +(defun magit-read-stash (prompt) + (let ((stashes (magit-list-stashes))) + (magit-completing-read prompt stashes nil t nil nil + (magit-stash-at-point) + (car stashes)))) + +(defun magit-read-remote (prompt &optional default use-only) + (let ((remotes (magit-list-remotes))) + (if (and use-only (= (length remotes) 1)) + (car remotes) + (magit-completing-read prompt remotes + nil t nil nil + (or default + (magit-remote-at-point) + (magit-get-remote)))))) + +(defun magit-read-remote-or-url (prompt &optional default) + (magit-completing-read prompt + (nconc (magit-list-remotes) + (list "https://" "git://" "git@")) + nil nil nil nil + (or default + (magit-remote-at-point) + (magit-get-remote)))) + +(defun magit-read-module-path (prompt &optional predicate) + (magit-completing-read prompt (magit-list-module-paths) + predicate t nil nil + (magit-module-at-point predicate))) + +(defun magit-module-confirm (verb &optional predicate) + (let (modules) + (if current-prefix-arg + (progn + (setq modules (magit-list-module-paths)) + (when predicate + (setq modules (-filter predicate modules))) + (unless modules + (if predicate + (user-error "No modules satisfying %s available" predicate) + (user-error "No modules available")))) + (setq modules (magit-region-values 'magit-module-section)) + (when modules + (when predicate + (setq modules (-filter predicate modules))) + (unless modules + (user-error "No modules satisfying %s selected" predicate)))) + (if (> (length modules) 1) + (magit-confirm t nil (format "%s %%i modules" verb) nil modules) + (list (magit-read-module-path (format "%s module" verb) predicate))))) + +;;; Variables in Popups + +(defun magit--format-popup-variable:value (variable width &optional global) + (concat variable + (make-string (max 1 (- width 3 (length variable))) ?\s) + (if-let ((value (magit-get (and global "--global") variable))) + (propertize value 'face 'magit-popup-option-value) + (propertize "unset" 'face 'magit-popup-disabled-argument)))) + +(defun magit--format-popup-variable:values (variable width &optional global) + (concat variable + (make-string (max 1 (- width 3 (length variable))) ?\s) + (if-let ((values (magit-get-all (and global "--global") variable))) + (concat + (propertize (car values) 'face 'magit-popup-option-value) + (mapconcat + (lambda (value) + (concat "\n" (make-string width ?\s) + (propertize value + 'face 'magit-popup-option-value))) + (cdr values) "")) + (propertize "unset" 'face 'magit-popup-disabled-argument)))) + +(defun magit--set-popup-variable + (variable choices &optional default other) + (magit-set (--if-let (magit-git-string "config" "--local" variable) + (cadr (member it choices)) + (car choices)) + variable) + (magit-with-pre-popup-buffer + (magit-refresh)) + (message "%s %s" variable + (magit--format-popup-variable:choices* + variable choices default other))) + +(defun magit--format-popup-variable:choices + (variable choices &optional default other width) + (concat variable + (if width (make-string (- width (length variable)) ?\s) " ") + (magit--format-popup-variable:choices* + variable choices default other))) + +(defun magit--format-popup-variable:choices* + (variable choices &optional default other) + (let ((local (magit-git-string "config" "--local" variable)) + (global (magit-git-string "config" "--global" variable))) + (when other + (setq other (--when-let (magit-get other) + (concat other ":" it)))) + (concat + (propertize "[" 'face 'magit-popup-disabled-argument) + (mapconcat + (lambda (choice) + (propertize choice 'face (if (equal choice local) + 'magit-popup-option-value + 'magit-popup-disabled-argument))) + choices + (propertize "|" 'face 'magit-popup-disabled-argument)) + (when (or global other default) + (concat + (propertize "|" 'face 'magit-popup-disabled-argument) + (cond (global + (propertize (concat "global:" global) + 'face (cond (local + 'magit-popup-disabled-argument) + ((member global choices) + 'magit-popup-option-value) + (t + 'font-lock-warning-face)))) + (other + (propertize other + 'face (if local + 'magit-popup-disabled-argument + 'magit-popup-option-value))) + (default + (propertize (concat "default:" default) + 'face (if local + 'magit-popup-disabled-argument + 'magit-popup-option-value)))))) + (propertize "]" 'face 'magit-popup-disabled-argument)))) + +;;; _ +(provide 'magit-git) +;;; magit-git.el ends here diff --git a/elpa/magit-20181113.1837/magit-gitignore.el b/elpa/magit-20181113.1837/magit-gitignore.el new file mode 100644 index 00000000..1d4e84a9 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-gitignore.el @@ -0,0 +1,98 @@ +;;; magit-gitignore.el --- intentionally untracked files -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements gitignore commands. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +;;; Commands + +;;;###autoload (autoload 'magit-gitignore-popup "magit-gitignore" nil t) +(magit-define-popup magit-gitignore-popup + "Popup console for gitignore commands." + :man-page "gitignore" + :actions '((?l "ignore locally" magit-gitignore-locally) + (?g "ignore globally" magit-gitignore-globally)) + :max-action-columns 1) + +;;;###autoload +(defun magit-gitignore-globally (file-or-pattern) + "Instruct Git to globally ignore FILE-OR-PATTERN." + (interactive (list (magit-gitignore-read-pattern nil))) + (magit--gitignore file-or-pattern nil)) + +;;;###autoload +(defun magit-gitignore-locally (file-or-pattern) + "Instruct Git to locally ignore FILE-OR-PATTERN." + (interactive (list (magit-gitignore-read-pattern t))) + (magit--gitignore file-or-pattern t)) + +(defun magit--gitignore (file-or-pattern local) + (let ((gitignore + (if local + (magit-git-dir (convert-standard-filename "info/exclude")) + (expand-file-name ".gitignore" (magit-toplevel))))) + (make-directory (file-name-directory gitignore) t) + (with-temp-buffer + (when (file-exists-p gitignore) + (insert-file-contents gitignore)) + (goto-char (point-max)) + (unless (bolp) + (insert "\n")) + (insert (replace-regexp-in-string "\\(\\\\*\\)" "\\1\\1" file-or-pattern)) + (insert "\n") + (write-region nil nil gitignore)) + (if local + (magit-refresh) + (magit-run-git "add" ".gitignore")))) + +(defun magit-gitignore-read-pattern (local) + (let* ((default (magit-current-file)) + (choices + (delete-dups + (--mapcat + (cons (concat "/" it) + (when-let ((ext (file-name-extension it))) + (list (concat "/" (file-name-directory "foo") "*." ext) + (concat "*." ext)))) + (magit-untracked-files))))) + (when default + (setq default (concat "/" default)) + (unless (member default choices) + (setq default (concat "*." (file-name-extension default))) + (unless (member default choices) + (setq default nil)))) + (magit-completing-read (concat "File or pattern to ignore" + (and local " locally")) + choices nil nil nil nil default))) + +;;; _ +(provide 'magit-gitignore) +;;; magit-gitignore.el ends here diff --git a/elpa/magit-20181113.1837/magit-imenu.el b/elpa/magit-20181113.1837/magit-imenu.el new file mode 100644 index 00000000..52b7ed6b --- /dev/null +++ b/elpa/magit-20181113.1837/magit-imenu.el @@ -0,0 +1,243 @@ +;;; magit-imenu.el --- Integrate Imenu in magit major modes -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Damien Cassou +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; Emacs' major modes can facilitate navigation in their buffers by +;; supporting Imenu. In such major modes, launching Imenu (M-x imenu) +;; makes Emacs display a list of items (e.g., function definitions in +;; a programming major mode). Selecting an item from this list moves +;; point to this item. + +;; magit-imenu.el adds Imenu support to every major mode in Magit + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) +(require 'git-rebase) + +(defun magit-imenu--index-function (entry-types menu-types) + "Return an alist of imenu entries in current buffer. + +ENTRY-TYPES is a list of section types to be selected through +`imenu'. + +MENU-TYPES is a list of section types containing elements of +ENTRY-TYPES. Elements of MENU-TYPES are are used to categories +elements of ENTRY-TYPES. + +This function is used as a helper for functions set as +`imenu-create-index-function'." + (let ((entries (make-hash-table :test 'equal))) + (goto-char (point-max)) + (while (magit-section--backward-find + (lambda () + (let* ((section (magit-current-section)) + (type (oref section type)) + (parent (oref section parent)) + (parent-type (oref parent type))) + (and (-contains-p entry-types type) + (-contains-p menu-types parent-type))))) + (let* ((section (magit-current-section)) + (name (buffer-substring-no-properties + (line-beginning-position) + (line-end-position))) + (parent (oref section parent)) + (parent-title (buffer-substring-no-properties + (oref parent start) + (1- (oref parent content))))) + (puthash parent-title + (cons (cons name (point)) + (gethash parent-title entries (list))) + entries))) + (mapcar (lambda (menu-title) + (cons menu-title (gethash menu-title entries))) + (hash-table-keys entries)))) + +;;; Log mode + +;;;###autoload +(defun magit-imenu--log-prev-index-position-function () + "Move point to previous line in current buffer. +This function is used as a value for +`imenu-prev-index-position-function'." + (magit-section--backward-find + (lambda () + (-contains-p '(commit stash) + (oref (magit-current-section) type))))) + +;;;###autoload +(defun magit-imenu--log-extract-index-name-function () + "Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line." + (save-match-data + (looking-at "\\([^ ]+\\)[ *|]+\\(.+\\)$") + (format "%s: %s" + (match-string-no-properties 1) + (match-string-no-properties 2)))) + +;;; Diff mode + +;;;###autoload +(defun magit-imenu--diff-prev-index-position-function () + "Move point to previous file line in current buffer. +This function is used as a value for +`imenu-prev-index-position-function'." + (magit-section--backward-find + (lambda () + (let ((section (magit-current-section))) + (and (magit-file-section-p section) + (not (equal (oref (oref section parent) type) + 'diffstat))))))) + +;;;###autoload +(defun magit-imenu--diff-extract-index-name-function () + "Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line." + (buffer-substring-no-properties (line-beginning-position) + (line-end-position))) + +;;; Status mode + +;;;###autoload +(defun magit-imenu--status-create-index-function () + "Return an alist of all imenu entries in current buffer. +This function is used as a value for +`imenu-create-index-function'." + (magit-imenu--index-function + '(file commit stash) + '(unpushed unstaged unpulled untracked staged stashes))) + +;;;; Refs mode + +;;;###autoload +(defun magit-imenu--refs-create-index-function () + "Return an alist of all imenu entries in current buffer. +This function is used as a value for +`imenu-create-index-function'." + (magit-imenu--index-function + '(branch commit tag) + '(local remote tags))) + +;;;; Cherry mode + +;;;###autoload +(defun magit-imenu--cherry-create-index-function () + "Return an alist of all imenu entries in current buffer. +This function is used as a value for +`imenu-create-index-function'." + (magit-imenu--index-function + '(commit) + '(cherries))) + +;;;; Submodule list mode + +;;;###autoload +(defun magit-imenu--submodule-prev-index-position-function () + "Move point to previous line in magit-submodule-list buffer. +This function is used as a value for +`imenu-prev-index-position-function'." + (unless (bobp) + (forward-line -1))) + +;;;###autoload +(defun magit-imenu--submodule-extract-index-name-function () + "Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line." + (elt (tabulated-list-get-entry) 0)) + +;;;; Repolist mode + +;;;###autoload +(defun magit-imenu--repolist-prev-index-position-function () + "Move point to previous line in magit-repolist buffer. +This function is used as a value for +`imenu-prev-index-position-function'." + (unless (bobp) + (forward-line -1))) + +;;;###autoload +(defun magit-imenu--repolist-extract-index-name-function () + "Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line." + (let ((entry (tabulated-list-get-entry))) + (format "%s (%s)" + (elt entry 0) + (elt entry (1- (length entry)))))) + +;;;; Process mode + +;;;###autoload +(defun magit-imenu--process-prev-index-position-function () + "Move point to previous process in magit-process buffer. +This function is used as a value for +`imenu-prev-index-position-function'." + (magit-section--backward-find + (lambda () + (eq (oref (magit-current-section) type) 'process)))) + +;;;###autoload +(defun magit-imenu--process-extract-index-name-function () + "Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line." + (buffer-substring-no-properties (line-beginning-position) + (line-end-position))) + +;;;; Rebase mode + +;;;###autoload +(defun magit-imenu--rebase-prev-index-position-function () + "Move point to previous commit in git-rebase buffer. +This function is used as a value for +`imenu-prev-index-position-function'." + (catch 'found + (while (not (bobp)) + (git-rebase-backward-line) + (when (git-rebase-line-p) + (throw 'found t))))) + +;;;###autoload +(defun magit-imenu--rebase-extract-index-name-function () + "Return imenu name for line at point. +This function is used as a value for +`imenu-extract-index-name-function'. Point should be at the +beginning of the line." + (buffer-substring-no-properties (line-beginning-position) + (line-end-position))) + +;;; _ +(provide 'magit-imenu) +;;; magit-imenu.el ends here diff --git a/elpa/magit-20181113.1837/magit-log.el b/elpa/magit-20181113.1837/magit-log.el new file mode 100644 index 00000000..82cad85a --- /dev/null +++ b/elpa/magit-20181113.1837/magit-log.el @@ -0,0 +1,1754 @@ +;;; magit-log.el --- inspect Git history -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements support for looking at Git logs, including +;; special logs like reflogs and cherry-logs, as well as for selecting +;; a commit from a log. + +;;; Code: + +(require 'magit-core) +(require 'magit-diff) + +(declare-function magit-blob-visit "magit-files" (blob-or-file line)) +(declare-function magit-insert-head-branch-header "magit-status" + (&optional branch)) +(declare-function magit-insert-upstream-branch-header "magit-status" + (&optional branch pull keyword)) +(declare-function magit-read-file-from-rev "magit-files" + (rev prompt &optional default)) +(declare-function magit-show-commit "magit-diff" + (arg1 &optional arg2 arg3 arg4)) +(defvar magit-refs-focus-column-width) +(defvar magit-refs-margin) +(defvar magit-refs-show-commit-count) +(defvar magit-buffer-margin) +(defvar magit-status-margin) +(defvar magit-status-sections-hook) + +(require 'ansi-color) +(require 'crm) +(require 'which-func) + +(eval-when-compile + (require 'subr-x)) + +(defvar bookmark-make-record-function) + +;;; Options +;;;; Log Mode + +(defgroup magit-log nil + "Inspect and manipulate Git history." + :link '(info-link "(magit)Logging") + :group 'magit-modes) + +(defcustom magit-log-mode-hook nil + "Hook run after entering Magit-Log mode." + :group 'magit-log + :type 'hook) + +(defcustom magit-log-arguments '("-n256" "--graph" "--decorate") + "The log arguments used in `magit-log-mode' buffers." + :package-version '(magit . "2.3.0") + :group 'magit-git-arguments + :group 'magit-log + :type '(repeat (string :tag "Argument"))) + +(defcustom magit-log-remove-graph-args '("--follow" "--grep" "-G" "-S" "-L") + "The log arguments that cause the `--graph' argument to be dropped." + :package-version '(magit . "2.3.0") + :group 'magit-log + :type '(repeat (string :tag "Argument")) + :options '("--follow" "--grep" "-G" "-S" "-L")) + +(defcustom magit-log-revision-headers-format "\ +%+b +Author: %aN <%aE> +Committer: %cN <%cE>" + "Additional format string used with the `++header' argument." + :package-version '(magit . "2.3.0") + :group 'magit-log + :type 'string) + +(defcustom magit-log-auto-more nil + "Insert more log entries automatically when moving past the last entry. +Only considered when moving past the last entry with +`magit-goto-*-section' commands." + :group 'magit-log + :type 'boolean) + +(defcustom magit-log-margin '(t age magit-log-margin-width t 18) + "Format of the margin in `magit-log-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the committer date. It can be one + of `age' (to show the age of the commit), `age-abbreviated' (to + abbreviate the time unit to a character), or a string (suitable + for `format-time-string') to show the actual date. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-log + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize 'magit-custom-initialize-reset + :set (apply-partially #'magit-margin-set-variable 'magit-log-mode)) + +(defcustom magit-log-show-refname-after-summary nil + "Whether to show refnames after commit summaries. +This is useful if you use really long branch names." + :package-version '(magit . "2.2.0") + :group 'magit-log + :type 'boolean) + +(defcustom magit-log-highlight-keywords t + "Whether to highlight bracketed keywords in commit summaries." + :package-version '(magit . "2.12.0") + :group 'magit-log + :type 'boolean) + +(defcustom magit-log-header-line-function 'magit-log-header-line-sentence + "Function used to generate text shown in header line of log buffers." + :package-version '(magit . "2.12.0") + :group 'magit-log + :type '(choice (function-item magit-log-header-line-arguments) + (function-item magit-log-header-line-sentence) + function)) + +(defcustom magit-log-trace-definition-function 'which-function + "Function used to determine the function at point. +This is used by the command `magit-log-trace-definition'." + :package-version '(magit . "2.90.0") + :group 'magit-log + :type '(choice (function-item which-function) function)) + +(defface magit-log-graph + '((((class color) (background light)) :foreground "grey30") + (((class color) (background dark)) :foreground "grey80")) + "Face for the graph part of the log output." + :group 'magit-faces) + +(defface magit-log-author + '((((class color) (background light)) :foreground "firebrick") + (((class color) (background dark)) :foreground "tomato")) + "Face for the author part of the log output." + :group 'magit-faces) + +(defface magit-log-date + '((((class color) (background light)) :foreground "grey30") + (((class color) (background dark)) :foreground "grey80")) + "Face for the date part of the log output." + :group 'magit-faces) + +(defface magit-header-line-log-select + '((t :inherit bold)) + "Face for the `header-line' in `magit-log-select-mode'." + :group 'magit-faces) + +;;;; File Log + +(defcustom magit-log-buffer-file-locked t + "Whether `magit-log-buffer-file' uses a dedicated buffer." + :package-version '(magit . "2.7.0") + :group 'magit-commands + :group 'magit-log + :type 'boolean) + +;;;; Select Mode + +(defcustom magit-log-select-arguments '("-n256" "--graph" "--decorate") + "The log arguments used in `magit-log-select-mode' buffers." + :package-version '(magit . "2.3.0") + :group 'magit-log + :type '(repeat (string :tag "Argument"))) + +(defcustom magit-log-select-show-usage 'both + "Whether to show usage information when selecting a commit from a log. +The message can be shown in the `echo-area' or the `header-line', or in +`both' places. If the value isn't one of these symbols, then it should +be nil, in which case no usage information is shown." + :package-version '(magit . "2.1.0") + :group 'magit-log + :type '(choice (const :tag "in echo-area" echo-area) + (const :tag "in header-line" header-line) + (const :tag "in both places" both) + (const :tag "nowhere"))) + +(defcustom magit-log-select-margin + (list (nth 0 magit-log-margin) + (nth 1 magit-log-margin) + 'magit-log-margin-width t + (nth 4 magit-log-margin)) + "Format of the margin in `magit-log-select-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the committer date. It can be one + of `age' (to show the age of the commit), `age-abbreviated' (to + abbreviate the time unit to a character), or a string (suitable + for `format-time-string') to show the actual date. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-log + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize 'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-log-select-mode)) + +;;;; Cherry Mode + +(defcustom magit-cherry-sections-hook + '(magit-insert-cherry-headers + magit-insert-cherry-commits) + "Hook run to insert sections into the cherry buffer." + :package-version '(magit . "2.1.0") + :group 'magit-log + :type 'hook) + +(defcustom magit-cherry-margin + (list (nth 0 magit-log-margin) + (nth 1 magit-log-margin) + 'magit-log-margin-width t + (nth 4 magit-log-margin)) + "Format of the margin in `magit-cherry-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the committer date. It can be one + of `age' (to show the age of the commit), `age-abbreviated' (to + abbreviate the time unit to a character), or a string (suitable + for `format-time-string') to show the actual date. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-log + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize 'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-cherry-mode)) + +;;;; Reflog Mode + +(defcustom magit-reflog-arguments '("-n256") + "The log arguments used in `magit-reflog-mode' buffers." + :package-version '(magit . "2.3.0") + :group 'magit-git-arguments + :type '(repeat (string :tag "Argument"))) + +(defcustom magit-reflog-margin + (list (nth 0 magit-log-margin) + (nth 1 magit-log-margin) + 'magit-log-margin-width nil + (nth 4 magit-log-margin)) + "Format of the margin in `magit-reflog-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the committer date. It can be one + of `age' (to show the age of the commit), `age-abbreviated' (to + abbreviate the time unit to a character), or a string (suitable + for `format-time-string') to show the actual date. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-log + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize 'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-reflog-mode)) + +(defface magit-reflog-commit '((t :foreground "green")) + "Face for commit commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-amend '((t :foreground "magenta")) + "Face for amend commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-merge '((t :foreground "green")) + "Face for merge, checkout and branch commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-checkout '((t :foreground "blue")) + "Face for checkout commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-reset '((t :foreground "red")) + "Face for reset commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-rebase '((t :foreground "magenta")) + "Face for rebase commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-cherry-pick '((t :foreground "green")) + "Face for cherry-pick commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-remote '((t :foreground "cyan")) + "Face for pull and clone commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-other '((t :foreground "cyan")) + "Face for other commands in reflogs." + :group 'magit-faces) + +;;;; Log Sections + +(defcustom magit-log-section-commit-count 10 + "How many recent commits to show in certain log sections. +How many recent commits `magit-insert-recent-commits' and +`magit-insert-unpulled-from-upstream-or-recent' (provided +the upstream isn't ahead of the current branch) show." + :package-version '(magit . "2.1.0") + :group 'magit-status + :type 'number) + +(defcustom magit-log-section-arguments '("-n256" "--decorate") + "The log arguments used in buffers that show other things besides logs." + :package-version '(magit . "2.4.0") + :group 'magit-git-arguments + :group 'magit-log + :group 'magit-status + :type '(repeat (string :tag "Argument"))) + +;;; Commands +;;;; Popups + +(defvar magit-log-popup + '(:variable magit-log-arguments + :man-page "git-log" + :switches ((?g "Show graph" "--graph") + (?c "Show graph in color" "--color") + (?d "Show refnames" "--decorate") + (?S "Show signatures" "--show-signature") + (?u "Show diffs" "--patch") + (?s "Show diffstats" "--stat") + (?h "Show header" "++header" magit-log++header) + (?r "Show in reverse order" "--reverse") + (?D "Simplify by decoration" "--simplify-by-decoration") + (?f "Follow renames when showing single-file log" "--follow")) + :options ((?n "Limit number of commits" "-n") + (?f "Limit to files" "-- " magit-read-files) + (?a "Limit to author" "--author=") + (?o "Order commits by" "++order=" magit-log-select-order) + (?g "Search messages" "--grep=") + (?G "Search changes" "-G") + (?S "Search occurrences" "-S") + (?L "Trace line evolution" "-L" magit-read-file-trace)) + :actions ((?l "Log current" magit-log-current) + (?L "Log local branches" magit-log-branches) + (?r "Reflog current" magit-reflog-current) + (?o "Log other" magit-log-other) + (?b "Log all branches" magit-log-all-branches) + (?O "Reflog other" magit-reflog-other) + (?h "Log HEAD" magit-log-head) + (?a "Log all references" magit-log-all) + (?H "Reflog HEAD" magit-reflog-head)) + :default-action magit-log-current + :max-action-columns 3)) + +(defvar magit-log-mode-refresh-popup + '(:variable magit-log-arguments + :man-page "git-log" + :switches ((?g "Show graph" "--graph") + (?c "Show graph in color" "--color") + (?d "Show refnames" "--decorate") + (?S "Show signatures" "--show-signature") + (?u "Show diffs" "--patch") + (?s "Show diffstats" "--stat") + (?r "Show in reverse order" "--reverse") + (?D "Simplify by decoration" "--simplify-by-decoration") + (?f "Follow renames when showing single-file log" "--follow")) + :options ((?n "Limit number of commits" "-n") + (?f "Limit to files" "-- " magit-read-files) + (?a "Limit to author" "--author=") + (?o "Order commits by" "++order=" magit-log-select-order) + (?g "Search messages" "--grep=") + (?G "Search changes" "-G") + (?S "Search occurrences" "-S") + (?L "Trace line evolution" "-L" magit-read-file-trace)) + :actions ((?g "Refresh" magit-log-refresh) + (?L "Toggle margin" magit-toggle-margin) + (?s "Set defaults" magit-log-set-default-arguments) nil + (?w "Save defaults" magit-log-save-default-arguments)) + :max-action-columns 2)) + +(defvar magit-reflog-mode-refresh-popup + '(:variable magit-reflog-arguments + :man-page "git-reflog" + :options ((?n "Limit number of commits" "-n")))) + +(defvar magit-log-refresh-popup + '(:variable magit-log-arguments + :man-page "git-log" + :switches ((?g "Show graph" "--graph") + (?c "Show graph in color" "--color") + (?d "Show refnames" "--decorate")) + :options ((?n "Limit number of commits" "-n") + (?o "Order commits by" "++order=" magit-log-select-order)) + :actions ("Refresh" + (?g "buffer" magit-log-refresh) + (?s "buffer and set defaults" magit-log-set-default-arguments) + (?w "buffer and save defaults" magit-log-save-default-arguments) + "Margin" + (?L "toggle visibility" magit-toggle-margin) + (?l "cycle style" magit-cycle-margin-style) + (?d "toggle details" magit-toggle-margin-details)) + :max-action-columns 1)) + +(magit-define-popup-keys-deferred 'magit-log-popup) +(magit-define-popup-keys-deferred 'magit-log-mode-refresh-popup) +(magit-define-popup-keys-deferred 'magit-log-refresh-popup) + +(defun magit-log-select-order (&rest _ignored) + "Set one `---order' option in Git log. +This encompasses the options `--author-date-order', +`--date-order', and `--topo-order'." + (magit-read-char-case "Order commits by " t + (?t "[t]opography" "topo") + (?a "[a]uthor date" "author-date") + (?c "[c]ommitter date" "date"))) + +;; This is a dummy procedure used to show help in `magit-log-popup'. +(defun magit-log++header () + "Insert a header after each revision summary in Git log. +Customize `magit-log-revision-headers-format' to change this +header." + nil) + +(defun magit-log-get-buffer-args () + (cond ((and magit-use-sticky-arguments + (derived-mode-p 'magit-log-mode)) + (list (nth 1 magit-refresh-args) + (nth 2 magit-refresh-args))) + ((and (eq magit-use-sticky-arguments t) + (--when-let (magit-mode-get-buffer 'magit-log-mode) + (with-current-buffer it + (list (nth 1 magit-refresh-args) + (nth 2 magit-refresh-args)))))) + (t + (list (default-value 'magit-log-arguments) nil)))) + +(defun magit-log-arguments (&optional refresh) + (cond ((memq magit-current-popup + '(magit-log-popup magit-log-refresh-popup)) + (magit-popup-export-file-args magit-current-popup-args)) + ((and refresh (not (derived-mode-p 'magit-log-mode))) + (list magit-log-section-arguments nil)) + (t + (magit-log-get-buffer-args)))) + +(defun magit-log-popup (arg) + "Popup console for log commands." + (interactive "P") + (let ((magit-log-refresh-popup + (pcase major-mode + (`magit-log-mode magit-log-mode-refresh-popup) + (_ magit-log-refresh-popup))) + (magit-log-arguments + (apply #'magit-popup-import-file-args (magit-log-get-buffer-args)))) + (magit-invoke-popup 'magit-log-popup nil arg))) + +;;;###autoload +(defun magit-log-buffer-file-popup () + "Popup console for log commands. + +This is a variant of `magit-log-popup' which shows the same popup +but which limits the log to the file being visited in the current +buffer." + (interactive) + (if-let ((file (magit-file-relative-name))) + (let ((magit-log-arguments + (magit-popup-import-file-args + (if-let ((buffer (magit-mode-get-buffer 'magit-log-mode))) + (with-current-buffer buffer + (nth 2 magit-refresh-args)) + (default-value 'magit-log-arguments)) + (list file)))) + (magit-invoke-popup 'magit-log-popup nil nil)) + (user-error "Buffer isn't visiting a file"))) + +(defun magit-log-refresh-popup (arg) + "Popup console for changing log arguments in the current buffer." + (interactive "P") + (magit-log-refresh-assert) + (let ((magit-log-refresh-popup + (cond ((derived-mode-p 'magit-log-select-mode) + magit-log-refresh-popup) + ((derived-mode-p 'magit-log-mode) + (let ((def (copy-sequence magit-log-refresh-popup))) + (plist-put def :switches (plist-get magit-log-popup :switches)) + (plist-put def :options (plist-get magit-log-popup :options)) + def)) + (t + magit-log-refresh-popup))) + (magit-log-arguments + (cond ((derived-mode-p 'magit-log-select-mode) + (cadr magit-refresh-args)) + ((derived-mode-p 'magit-log-mode) + (magit-popup-import-file-args (nth 1 magit-refresh-args) + (nth 2 magit-refresh-args))) + (t + magit-log-section-arguments)))) + (magit-invoke-popup 'magit-log-refresh-popup nil arg))) + +(defun magit-read-file-trace (&rest _ignored) + (let ((file (magit-read-file-from-rev "HEAD" "File")) + (trace (magit-read-string "Trace"))) + (concat trace (or (match-string 2 trace) ":") file))) + +;;;; Refresh Commands + +(defun magit-log-refresh (args files) + "Set the local log arguments for the current buffer." + (interactive (magit-log-arguments t)) + (magit-log-refresh-assert) + (cond ((derived-mode-p 'magit-log-select-mode) + (setcar (cdr magit-refresh-args) args)) + ((derived-mode-p 'magit-log-mode) + (setcdr magit-refresh-args (list args files))) + (t + (setq-local magit-log-section-arguments args))) + (magit-refresh)) + +(defun magit-log-set-default-arguments (args files) + "Set the global log arguments for the current buffer." + (interactive (magit-log-arguments t)) + (magit-log-refresh-assert) + (cond ((derived-mode-p 'magit-log-select-mode) + (customize-set-variable 'magit-log-select-arguments args) + (setcar (cdr magit-refresh-args) args)) + ((derived-mode-p 'magit-log-mode) + (customize-set-variable 'magit-log-arguments args) + (setcdr magit-refresh-args (list args files))) + (t + (customize-set-variable 'magit-log-section-arguments args) + (kill-local-variable 'magit-log-section-arguments))) + (magit-refresh)) + +(defun magit-log-save-default-arguments (args files) + "Set and save the global log arguments for the current buffer." + (interactive (magit-log-arguments t)) + (magit-log-refresh-assert) + (cond ((derived-mode-p 'magit-log-select-mode) + (customize-save-variable 'magit-log-select-arguments args) + (setcar (cdr magit-refresh-args) args)) + ((derived-mode-p 'magit-log-mode) + (customize-save-variable 'magit-log-arguments args) + (setcdr magit-refresh-args (list args files))) + (t + (customize-save-variable 'magit-log-section-arguments args) + (kill-local-variable 'magit-log-section-arguments))) + (magit-refresh)) + +(defun magit-log-refresh-assert () + (cond ((derived-mode-p 'magit-reflog-mode) + (user-error "Cannot change log arguments in reflog buffers")) + ((derived-mode-p 'magit-cherry-mode) + (user-error "Cannot change log arguments in cherry buffers")))) + +;;;; Log Commands + +(defvar magit-log-read-revs-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map crm-local-completion-map) + (define-key map "\s" 'self-insert-command) + map)) + +(defun magit-log-read-revs (&optional use-current) + (or (and use-current (--when-let (magit-get-current-branch) (list it))) + (let ((collection `(,@(and (file-exists-p (magit-git-dir "FETCH_HEAD")) + (list "FETCH_HEAD")) + ,@(magit-list-refnames)))) + (split-string + (magit-completing-read-multiple "Log rev,s" collection + "\\(\\.\\.\\.?\\|[, ]\\)" + (or (magit-branch-or-commit-at-point) + (unless use-current + (magit-get-previous-branch))) + 'magit-revision-history + magit-log-read-revs-map) + "[, ]" t)))) + +(defun magit-git-log (revs args files) + (require 'magit) + (magit-mode-setup #'magit-log-mode revs args files) + (magit-log-goto-same-commit)) + +;;;###autoload +(defun magit-log-current (revs &optional args files) + "Show log for the current branch. +When `HEAD' is detached or with a prefix argument show log for +one or more revs read from the minibuffer." + (interactive (cons (magit-log-read-revs t) + (magit-log-arguments))) + (magit-git-log revs args files)) + +;;;###autoload +(defun magit-log-other (revs &optional args files) + "Show log for one or more revs read from the minibuffer. +The user can input any revision or revisions separated by a +space, or even ranges, but only branches and tags, and a +representation of the commit at point, are available as +completion candidates." + (interactive (cons (magit-log-read-revs) + (magit-log-arguments))) + (magit-git-log revs args files)) + +;;;###autoload +(defun magit-log-head (&optional args files) + "Show log for `HEAD'." + (interactive (magit-log-arguments)) + (magit-git-log (list "HEAD") args files)) + +;;;###autoload +(defun magit-log-branches (&optional args files) + "Show log for all local branches and `HEAD'." + (interactive (magit-log-arguments)) + (magit-git-log (if (magit-get-current-branch) + (list "--branches") + (list "HEAD" "--branches")) + args files)) + +;;;###autoload +(defun magit-log-all-branches (&optional args files) + "Show log for all local and remote branches and `HEAD'." + (interactive (magit-log-arguments)) + (magit-git-log (if (magit-get-current-branch) + (list "--branches" "--remotes") + (list "HEAD" "--branches" "--remotes")) + args files)) + +;;;###autoload +(defun magit-log-all (&optional args files) + "Show log for all references and `HEAD'." + (interactive (magit-log-arguments)) + (magit-git-log (if (magit-get-current-branch) + (list "--all") + (list "HEAD" "--all")) + args files)) + +;;;###autoload +(defun magit-log-buffer-file (&optional follow beg end) + "Show log for the blob or file visited in the current buffer. +With a prefix argument or when `--follow' is part of +`magit-log-arguments', then follow renames. When the region is +active, restrict the log to the lines that the region touches." + (interactive + (cons current-prefix-arg + (and (region-active-p) + (magit-file-relative-name) + (save-restriction + (widen) + (list (line-number-at-pos (region-beginning)) + (line-number-at-pos + (let ((end (region-end))) + (if (char-after end) + end + ;; Ensure that we don't get the line number + ;; of a trailing newline. + (1- end))))))))) + (require 'magit) + (if-let ((file (magit-file-relative-name))) + (magit-mode-setup-internal + #'magit-log-mode + (list (list (or magit-buffer-refname + (magit-get-current-branch) + "HEAD")) + (let ((args (car (magit-log-arguments)))) + (when (and follow (not (member "--follow" args))) + (push "--follow" args)) + (when (and (file-regular-p + (expand-file-name file (magit-toplevel))) + beg end) + (setq args (cons (format "-L%s,%s:%s" beg end file) + (cl-delete "-L" args :test + 'string-prefix-p))) + (setq file nil)) + args) + (and file (list file))) + magit-log-buffer-file-locked) + (user-error "Buffer isn't visiting a file")) + (magit-log-goto-same-commit)) + +;;;###autoload +(defun magit-log-trace-definition (file fn rev) + "Show log for the definition at point." + (interactive (list (or (magit-file-relative-name) + (user-error "Buffer isn't visiting a file")) + (funcall magit-log-trace-definition-function) + (or magit-buffer-refname + (magit-get-current-branch) + "HEAD"))) + (require 'magit) + (magit-mode-setup-internal + #'magit-log-mode + (list (list rev) + (cons (format "-L:%s:%s" (regexp-quote fn) file) + (cl-delete "-L" (car (magit-log-arguments)) + :test 'string-prefix-p)) + nil) + magit-log-buffer-file-locked) + (magit-log-goto-same-commit)) + +(defun magit-diff-trace-definition () + "Show log for the definition at point in a diff." + (interactive) + (let (buf pos) + (save-window-excursion + (call-interactively #'magit-diff-visit-file) + (setq buf (current-buffer)) + (setq pos (point))) + (save-excursion + (with-current-buffer buf + (goto-char pos) + (call-interactively #'magit-log-trace-definition))))) + +;;;###autoload +(defun magit-log-merged (commit branch &optional args files) + "Show log for the merge of COMMIT into BRANCH. +More precisely, find merge commit M that brought COMMIT into +BRANCH, and show the log of the range \"M^..M\". This command +requires git-when-merged, which is available from +https://github.com/mhagger/git-when-merged." + (interactive + (append (let ((commit (magit-read-branch-or-commit "Commit"))) + (list commit + (magit-read-other-branch "Merged into" commit))) + (magit-log-arguments))) + (unless (executable-find "git-when-merged") + (user-error "This command requires git-when-merged (%s)" + "https://github.com/mhagger/git-when-merged")) + (magit-git-log + (list (or (magit-git-string "when-merged" "--show-branch" commit branch) + (user-error "Could not find when %s was merged into %s" + commit branch))) + args files)) + +(defun magit-git-reflog (ref args) + (require 'magit) + (magit-mode-setup #'magit-reflog-mode ref args)) + +;;;###autoload +(defun magit-reflog-current (args) + "Display the reflog of the current branch." + (interactive (list magit-reflog-arguments)) + (magit-git-reflog (magit-get-current-branch) args)) + +;;;###autoload +(defun magit-reflog-other (ref args) + "Display the reflog of a branch or another ref." + (interactive (list (magit-read-local-branch-or-ref "Show reflog for") + magit-reflog-arguments)) + (magit-git-reflog ref args)) + +;;;###autoload +(defun magit-reflog-head (args) + "Display the `HEAD' reflog." + (interactive (list magit-reflog-arguments)) + (magit-git-reflog "HEAD" args)) + +;;;; Limit Commands + +(defun magit-log-toggle-commit-limit () + "Toggle the number of commits the current log buffer is limited to. +If the number of commits is currently limited, then remove that +limit. Otherwise set it to 256." + (interactive) + (magit-log-set-commit-limit (lambda (&rest _) nil))) + +(defun magit-log-double-commit-limit () + "Double the number of commits the current log buffer is limited to." + (interactive) + (magit-log-set-commit-limit '*)) + +(defun magit-log-half-commit-limit () + "Half the number of commits the current log buffer is limited to." + (interactive) + (magit-log-set-commit-limit '/)) + +(defun magit-log-set-commit-limit (fn) + (let* ((val (car (magit-log-arguments t))) + (arg (--first (string-match "^-n\\([0-9]+\\)?$" it) val)) + (num (and arg (string-to-number (match-string 1 arg)))) + (num (if num (funcall fn num 2) 256))) + (setq val (delete arg val)) + (setcar (cdr magit-refresh-args) + (if (and num (> num 0)) + (cons (format "-n%i" num) val) + val))) + (magit-refresh)) + +(defun magit-log-get-commit-limit () + (--when-let (--first (string-match "^-n\\([0-9]+\\)?$" it) + (car (magit-log-arguments t))) + (string-to-number (match-string 1 it)))) + +;;;; Other Commands + +(defun magit-log-bury-buffer (&optional arg) + "Bury the current buffer or the revision buffer in the same frame. +Like `magit-mode-bury-buffer' (which see) but with a negative +prefix argument instead bury the revision buffer, provided it +is displayed in the current frame." + (interactive "p") + (if (< arg 0) + (let* ((buf (magit-mode-get-buffer 'magit-revision-mode)) + (win (and buf (get-buffer-window buf (selected-frame))))) + (if win + (with-selected-window win + (with-current-buffer buf + (magit-mode-bury-buffer (> (abs arg) 1)))) + (user-error "No revision buffer in this frame"))) + (magit-mode-bury-buffer (> arg 1)))) + +;;;###autoload +(defun magit-log-move-to-parent (&optional n) + "Move to the Nth parent of the current commit." + (interactive "p") + (when (derived-mode-p 'magit-log-mode) + (when (magit-section-match 'commit) + (let* ((section (magit-current-section)) + (parent-rev (format "%s^%s" (oref section value) (or n 1)))) + (if-let ((parent-hash (magit-rev-parse "--short" parent-rev))) + (if-let ((parent (--first (equal (oref section value) + parent-hash) + (magit-section-siblings section 'next)))) + (magit-section-goto parent) + (user-error + (substitute-command-keys + (concat "Parent " parent-hash " not found. Try typing " + "\\[magit-log-double-commit-limit] first")))) + (user-error "Parent %s does not exist" parent-rev)))))) + +;;; Log Mode + +(defvar magit-log-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-mode-map) + (define-key map "\C-c\C-b" 'magit-go-backward) + (define-key map "\C-c\C-f" 'magit-go-forward) + (define-key map "\C-c\C-n" 'magit-log-move-to-parent) + (define-key map "=" 'magit-log-toggle-commit-limit) + (define-key map "+" 'magit-log-double-commit-limit) + (define-key map "-" 'magit-log-half-commit-limit) + (define-key map "q" 'magit-log-bury-buffer) + map) + "Keymap for `magit-log-mode'.") + +(define-derived-mode magit-log-mode magit-mode "Magit Log" + "Mode for looking at Git log. + +This mode is documented in info node `(magit)Log Buffer'. + +\\\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit at point. + +Type \\[magit-branch-popup] to see available branch commands. +Type \\[magit-merge-popup] to merge the branch or commit at point. +Type \\[magit-cherry-pick-popup] to apply the commit at point. +Type \\[magit-reset] to reset `HEAD' to the commit at point. + +\\{magit-log-mode-map}" + :group 'magit-log + (hack-dir-local-variables-non-file-buffer) + (setq imenu-prev-index-position-function + 'magit-imenu--log-prev-index-position-function) + (setq imenu-extract-index-name-function + 'magit-imenu--log-extract-index-name-function) + (setq-local bookmark-make-record-function + 'magit-bookmark--log-make-record)) + +(defvar magit-log-disable-graph-hack-args + '("-G" "--grep" "--author") + "Arguments which disable the graph speedup hack.") + +(defun magit-log-refresh-buffer (revs args files) + (magit-set-header-line-format + (funcall magit-log-header-line-function revs args files)) + (if (= (length files) 1) + (unless (magit-file-tracked-p (car files)) + (setq args (cons "--full-history" args))) + (setq args (remove "--follow" args))) + (when (--any-p (string-match-p + (concat "^" (regexp-opt magit-log-remove-graph-args)) it) + args) + (setq args (remove "--graph" args))) + (unless (member "--graph" args) + (setq args (remove "--color" args))) + (when-let ((limit (magit-log-get-commit-limit)) + (limit (* 2 limit)) ; increase odds for complete graph + (count (and (= (length revs) 1) + (> limit 1024) ; otherwise it's fast enough + (setq revs (car revs)) + (not (string-match-p "\\.\\." revs)) + (not (member revs '("--all" "--branches"))) + (-none-p (lambda (arg) + (--any-p (string-prefix-p it arg) + magit-log-disable-graph-hack-args)) + args) + (magit-git-string "rev-list" "--count" + "--first-parent" args revs)))) + (setq revs (if (< (string-to-number count) limit) + revs + (format "%s~%s..%s" revs limit revs)))) + (magit-insert-section (logbuf) + (magit-insert-log revs args files))) + +(defun magit-log-header-line-arguments (revs args files) + "Return string describing some of the used arguments." + (mapconcat (lambda (arg) + (if (string-match-p " " arg) + (prin1 arg) + arg)) + `("git" "log" ,@args ,@revs "--" ,@files) + " ")) + +(defun magit-log-header-line-sentence (revs args files) + "Return string containing all arguments." + (concat "Commits in " + (mapconcat #'identity revs " ") + (and (member "--reverse" args) + " in reverse") + (and files (concat " touching " + (mapconcat 'identity files " "))) + (--some (and (string-prefix-p "-L" it) + (concat " " it)) + args))) + +(defun magit-insert-log (revs &optional args files) + "Insert a log section. +Do not add this to a hook variable." + (let ((magit-git-global-arguments + (remove "--literal-pathspecs" magit-git-global-arguments))) + (magit-git-wash (apply-partially #'magit-log-wash-log 'log) + "log" + (format "--format=%s%%h%s%%x00%s%%x00%%aN%%x00%%at%%x00%%s%s" + (if (and (member "--left-right" args) + (not (member "--graph" args))) + "%m " + "") + (if (member "--decorate" args) "%d" "") + (if (member "--show-signature" args) + (progn (setq args (remove "--show-signature" args)) "%G?") + "") + (if (member "++header" args) + (if (member "--graph" (setq args (remove "++header" args))) + (concat "\n" magit-log-revision-headers-format "\n") + (concat "\n" magit-log-revision-headers-format "\n")) + "")) + (progn + (--when-let (--first (string-match "^\\+\\+order=\\(.+\\)$" it) args) + (setq args (cons (format "--%s-order" (match-string 1 it)) + (remove it args)))) + (when (member "--decorate" args) + (setq args (cons "--decorate=full" (remove "--decorate" args)))) + (when (member "--reverse" args) + (setq args (remove "--graph" args))) + args) + "--use-mailmap" "--no-prefix" revs "--" files))) + +(defvar magit-commit-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-show-commit) + (define-key map "a" 'magit-cherry-apply) + map) + "Keymap for `commit' sections.") + +(defvar magit-module-commit-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-show-commit) + map) + "Keymap for `module-commit' sections.") + +(defconst magit-log-heading-re + (concat "^" + "\\(?4:[-_/|\\*o<>. ]*\\)" ; graph + "\\(?1:[0-9a-fA-F]+\\)" ; sha1 + "\\(?3:[^\0\n]+)\\)?\0" ; refs + "\\(?7:[BGUXYREN]\\)?\0" ; gpg + "\\(?5:[^\0\n]*\\)\0" ; author + ;; Note: Date is optional because, prior to Git v2.19.0, + ;; `git rebase -i --root` corrupts the root's author date. + "\\(?6:[^\0\n]*\\)\0" ; date + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-cherry-re + (concat "^" + "\\(?8:[-+]\\) " ; cherry + "\\(?1:[0-9a-fA-F]+\\) " ; sha1 + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-module-re + (concat "^" + "\\(?:\\(?11:[<>]\\) \\)?" ; side + "\\(?1:[0-9a-fA-F]+\\) " ; sha1 + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-bisect-vis-re + (concat "^" + "\\(?4:[-_/|\\*o<>. ]*\\)" ; graph + "\\(?1:[0-9a-fA-F]+\\)" ; sha1 + "\\(?3:[^\0\n]+)\\)?\0" ; refs + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-bisect-log-re + (concat "^# " + "\\(?3:bad:\\|skip:\\|good:\\) " ; "refs" + "\\[\\(?1:[^]\n]+\\)\\] " ; sha1 + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-reflog-re + (concat "^" + "\\(?1:[^\0\n]+\\)\0" ; sha1 + "\\(?5:[^\0\n]*\\)\0" ; author + "\\(?:\\(?:[^@\n]+@{\\(?6:[^}\n]+\\)}\0" ; date + "\\(?10:merge \\|autosave \\|restart \\|[^:\n]+: \\)?" ; refsub + "\\(?2:.*\\)?\\)\\|\0\\)$")) ; msg + +(defconst magit-reflog-subject-re + (concat "\\(?1:[^ ]+\\) ?" ; command + "\\(?2:\\(?: ?-[^ ]+\\)+\\)?" ; option + "\\(?: ?(\\(?3:[^)]+\\))\\)?")) ; type + +(defconst magit-log-stash-re + (concat "^" + "\\(?1:[^\0\n]+\\)\0" ; "sha1" + "\\(?5:[^\0\n]*\\)\0" ; author + "\\(?6:[^\0\n]+\\)\0" ; date + "\\(?2:.*\\)$")) ; msg + +(defvar magit-log-count nil) + +(defvar magit-log-format-message-function 'magit-log-propertize-keywords) + +(defun magit-log-wash-log (style args) + (setq args (-flatten args)) + (when (and (member "--graph" args) + (member "--color" args)) + (let ((ansi-color-apply-face-function + (lambda (beg end face) + (put-text-property beg end 'font-lock-face + (or face 'magit-log-graph))))) + (ansi-color-apply-on-region (point-min) (point-max)))) + (when (eq style 'cherry) + (reverse-region (point-min) (point-max))) + (let ((magit-log-count 0)) + (magit-wash-sequence (apply-partially 'magit-log-wash-rev style + (magit-abbrev-length))) + (if (derived-mode-p 'magit-log-mode) + (when (eq magit-log-count (magit-log-get-commit-limit)) + (magit-insert-section (longer) + (insert-text-button + (substitute-command-keys + (format "Type \\<%s>\\[%s] to show more history" + 'magit-log-mode-map + 'magit-log-double-commit-limit)) + 'action (lambda (_button) + (magit-log-double-commit-limit)) + 'follow-link t + 'mouse-face 'magit-section-highlight))) + (insert ?\n)))) + +(cl-defun magit-log-wash-rev (style abbrev) + (when (derived-mode-p 'magit-log-mode) + (cl-incf magit-log-count)) + (looking-at (pcase style + (`log magit-log-heading-re) + (`cherry magit-log-cherry-re) + (`module magit-log-module-re) + (`reflog magit-log-reflog-re) + (`stash magit-log-stash-re) + (`bisect-vis magit-log-bisect-vis-re) + (`bisect-log magit-log-bisect-log-re))) + (magit-bind-match-strings + (hash msg refs graph author date gpg cherry _ refsub side) nil + (setq msg (substring-no-properties msg)) + (when refs + (setq refs (substring-no-properties refs))) + (let ((align (or (eq style 'cherry) + (not (member "--stat" (cadr magit-refresh-args))))) + (non-graph-re (if (eq style 'bisect-vis) + magit-log-bisect-vis-re + magit-log-heading-re))) + (magit-delete-line) + ;; If the reflog entries have been pruned, the output of `git + ;; reflog show' includes a partial line that refers to the hash + ;; of the youngest expired reflog entry. + (when (and (eq style 'reflog) (not date)) + (cl-return-from magit-log-wash-rev t)) + (magit-insert-section section (commit hash) + (pcase style + (`stash (oset section type 'stash)) + (`module (oset section type 'module-commit)) + (`bisect-log (setq hash (magit-rev-parse "--short" hash)))) + (when cherry + (when (and (derived-mode-p 'magit-refs-mode) + magit-refs-show-commit-count) + (insert (make-string (1- magit-refs-focus-column-width) ?\s))) + (insert (propertize cherry 'face (if (string= cherry "-") + 'magit-cherry-equivalent + 'magit-cherry-unmatched))) + (insert ?\s)) + (when side + (insert (propertize side 'face (if (string= side "<") + 'magit-cherry-equivalent + 'magit-cherry-unmatched))) + (insert ?\s)) + (when align + (insert (propertize hash 'face 'magit-hash) ?\s)) + (when graph + (insert graph)) + (unless align + (insert (propertize hash 'face 'magit-hash) ?\s)) + (when (and refs (not magit-log-show-refname-after-summary)) + (insert (magit-format-ref-labels refs) ?\s)) + (when (eq style 'reflog) + (insert (format "%-2s " (1- magit-log-count))) + (when refsub + (insert (magit-reflog-format-subject + (substring refsub 0 (if (string-match-p ":" refsub) -2 -1)))))) + (when msg + (when gpg + (setq msg (propertize msg 'face + (pcase (aref gpg 0) + (?G 'magit-signature-good) + (?B 'magit-signature-bad) + (?U 'magit-signature-untrusted) + (?X 'magit-signature-expired) + (?Y 'magit-signature-expired-key) + (?R 'magit-signature-revoked) + (?E 'magit-signature-error))))) + (insert (funcall magit-log-format-message-function hash msg))) + (when (and refs magit-log-show-refname-after-summary) + (insert ?\s) + (insert (magit-format-ref-labels refs))) + (insert ?\n) + (when (memq style '(log reflog stash)) + (goto-char (line-beginning-position)) + (when (and refsub + (string-match "\\`\\([^ ]\\) \\+\\(..\\)\\(..\\)" date)) + (setq date (+ (string-to-number (match-string 1 date)) + (* (string-to-number (match-string 2 date)) 60 60) + (* (string-to-number (match-string 3 date)) 60)))) + (save-excursion + (backward-char) + (magit-log-format-margin hash author date))) + (when (and (eq style 'cherry) + (magit-buffer-margin-p)) + (save-excursion + (backward-char) + (apply #'magit-log-format-margin hash + (split-string (magit-rev-format "%aN%x00%ct" hash) "\0")))) + (when (and graph + (not (eobp)) + (not (looking-at non-graph-re))) + (when (looking-at "") + (magit-insert-heading) + (delete-char 1) + (magit-insert-section (commit-header) + (forward-line) + (magit-insert-heading) + (re-search-forward "") + (backward-delete-char 1) + (forward-char) + (insert ?\n)) + (delete-char 1)) + (if (looking-at "^\\(---\\|\n\s\\|\ndiff\\)") + (let ((limit (save-excursion + (and (re-search-forward non-graph-re nil t) + (match-beginning 0))))) + (unless (oref magit-insert-section--current content) + (magit-insert-heading)) + (delete-char (if (looking-at "\n") 1 4)) + (magit-diff-wash-diffs (list "--stat") limit)) + (when align + (setq align (make-string (1+ abbrev) ? ))) + (when (and (not (eobp)) (not (looking-at non-graph-re))) + (when align + (setq align (make-string (1+ abbrev) ? ))) + (while (and (not (eobp)) (not (looking-at non-graph-re))) + (when align + (save-excursion (insert align))) + (magit-make-margin-overlay) + (forward-line)) + ;; When `--format' is used and its value isn't one of the + ;; predefined formats, then `git-log' does not insert a + ;; separator line. + (save-excursion + (forward-line -1) + (looking-at "[-_/|\\*o<>. ]*")) + (setq graph (match-string 0)) + (unless (string-match-p "[/\\]" graph) + (insert graph ?\n)))))))) + t) + +(defun magit-log-propertize-keywords (_rev msg) + (let ((start 0)) + (when (string-match "^\\(squash\\|fixup\\)! " msg start) + (setq start (match-end 0)) + (put-text-property (match-beginning 0) + (match-end 0) + 'face 'magit-keyword-squash msg)) + (while (string-match "\\[[^[]*\\]" msg start) + (setq start (match-end 0)) + (when magit-log-highlight-keywords + (put-text-property (match-beginning 0) + (match-end 0) + 'face 'magit-keyword msg)))) + msg) + +(defun magit-log-maybe-show-more-commits (section) + "When point is at the end of a log buffer, insert more commits. + +Log buffers end with a button \"Type + to show more history\". +When the use of a section movement command puts point on that +button, then automatically show more commits, without the user +having to press \"+\". + +This function is called by `magit-section-movement-hook' and +exists mostly for backward compatibility reasons." + (when (and (eq (oref section type) 'longer) + magit-log-auto-more) + (magit-log-double-commit-limit) + (forward-line -1) + (magit-section-forward))) + +(defvar magit--update-revision-buffer nil) + +(defun magit-log-maybe-update-revision-buffer (&optional _) + "When moving in the log buffer, update the revision buffer. +If there is no revision buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-log-mode) + (magit-log-maybe-update-revision-buffer-1))) + +(defun magit-log-maybe-update-revision-buffer-1 () + (unless magit--update-revision-buffer + (when-let ((commit (magit-section-value-if 'commit)) + (buffer (magit-mode-get-buffer 'magit-revision-mode nil t))) + (setq magit--update-revision-buffer (list commit buffer)) + (run-with-idle-timer + magit-update-other-window-delay nil + (let ((args (magit-show-commit--arguments))) + (lambda () + (pcase-let ((`(,rev ,buf) magit--update-revision-buffer)) + (setq magit--update-revision-buffer nil) + (when (buffer-live-p buf) + (let ((magit-display-buffer-noselect t)) + (apply #'magit-show-commit rev args)))) + (setq magit--update-revision-buffer nil))))))) + +(defvar magit--update-blob-buffer nil) + +(defun magit-log-maybe-update-blob-buffer (&optional _) + "When moving in the log buffer, update the blob buffer. +If there is no blob buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-log-mode) + (magit-log-maybe-update-blob-buffer-1))) + +(defun magit-log-maybe-update-blob-buffer-1 () + (unless magit--update-revision-buffer + (when-let ((commit (magit-section-value-if 'commit)) + (buffer (--first (with-current-buffer it magit-buffer-revision) + (mapcar #'window-buffer (window-list))))) + (setq magit--update-blob-buffer (list commit buffer)) + (run-with-idle-timer + magit-update-other-window-delay nil + (lambda () + (pcase-let ((`(,rev ,buf) magit--update-blob-buffer)) + (setq magit--update-blob-buffer nil) + (when (buffer-live-p buf) + (save-excursion + (with-selected-window (get-buffer-window buf) + (with-current-buffer buf + (magit-blob-visit (list (magit-rev-parse rev) + (magit-file-relative-name + magit-buffer-file-name)) + (line-number-at-pos)))))))))))) + +(defun magit-log-goto-same-commit (&optional default) + (let ((prev magit-previous-section)) + (when-let ((rev (cond ((and prev (magit-section-match 'commit prev)) + (oref prev value)) + ((and prev (magit-section-match 'branch prev)) + (magit-rev-format "%h" (oref prev value))) + (default (magit-rev-format "%h" default)))) + (same (--first (equal (oref it value) rev) + (oref magit-root-section children)))) + (goto-char (oref same start))))) + +;;; Log Margin + +(defvar-local magit-log-margin-show-shortstat nil) + +(defun magit-toggle-log-margin-style () + "Toggle between the regular and the shortstat margin style. +The shortstat style is experimental and rather slow." + (interactive) + (setq magit-log-margin-show-shortstat + (not magit-log-margin-show-shortstat)) + (magit-set-buffer-margin nil t)) + +(defun magit-log-format-margin (rev author date) + (when-let ((option (magit-margin-option))) + (if magit-log-margin-show-shortstat + (magit-log-format-shortstat-margin rev) + (pcase-let ((`(,_ ,style ,width ,details ,details-width) + (or magit-buffer-margin + (symbol-value option)))) + (magit-make-margin-overlay + (concat (and details + (concat (propertize (truncate-string-to-width + (or author "") + details-width + nil ?\s (make-string 1 magit-ellipsis)) + 'face 'magit-log-author) + " ")) + (propertize + (if (stringp style) + (format-time-string + style + (seconds-to-time (string-to-number date))) + (pcase-let* ((abbr (eq style 'age-abbreviated)) + (`(,cnt ,unit) (magit--age date abbr))) + (format (format (if abbr "%%2i%%-%ic" "%%2i %%-%is") + (- width (if details (1+ details-width) 0))) + cnt unit))) + 'face 'magit-log-date))))))) + +(defun magit-log-format-shortstat-margin (rev) + (magit-make-margin-overlay + (if-let ((line (and rev (magit-git-string + "show" "--format=" "--shortstat" rev)))) + (if (string-match "\ +\\([0-9]+\\) files? changed, \ +\\(?:\\([0-9]+\\) insertions?(\\+)\\)?\ +\\(?:\\(?:, \\)?\\([0-9]+\\) deletions?(-)\\)?\\'" line) + (magit-bind-match-strings (files add del) line + (format + "%5s %5s%4s" + (if add + (propertize (format "%s+" add) 'face 'magit-diffstat-added) + "") + (if del + (propertize (format "%s-" del) 'face 'magit-diffstat-removed) + "") + files)) + "") + ""))) + +(defun magit-log-margin-width (style details details-width) + (if magit-log-margin-show-shortstat + 16 + (+ (if details (1+ details-width) 0) + (if (stringp style) + (length (format-time-string style)) + (+ 2 ; two digits + 1 ; trailing space + (if (eq style 'age-abbreviated) + 1 ; single character + (+ 1 ; gap after digits + (apply #'max (--map (max (length (nth 1 it)) + (length (nth 2 it))) + magit--age-spec))))))))) + +;;; Select Mode + +(defvar magit-log-select-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-log-mode-map) + (define-key map "\C-c\C-b" 'undefined) + (define-key map "\C-c\C-f" 'undefined) + (define-key map "." 'magit-log-select-pick) + (define-key map "e" 'magit-log-select-pick) + (define-key map "\C-c\C-c" 'magit-log-select-pick) + (define-key map "q" 'magit-log-select-quit) + (define-key map "\C-c\C-k" 'magit-log-select-quit) + map) + "Keymap for `magit-log-select-mode'.") + +(put 'magit-log-select-pick :advertised-binding [?\C-c ?\C-c]) +(put 'magit-log-select-quit :advertised-binding [?\C-c ?\C-k]) + +(define-derived-mode magit-log-select-mode magit-log-mode "Magit Select" + "Mode for selecting a commit from history. + +This mode is documented in info node `(magit)Select from Log'. + +\\\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit at point. + +\\\ +Type \\[magit-log-select-pick] to select the commit at point. +Type \\[magit-log-select-quit] to abort without selecting a commit." + :group 'magit-log + (hack-dir-local-variables-non-file-buffer)) + +(defun magit-log-select-refresh-buffer (rev args) + (magit-insert-section (logbuf) + (magit-insert-log rev args))) + +(defvar-local magit-log-select-pick-function nil) +(defvar-local magit-log-select-quit-function nil) + +(defun magit-log-select (pick &optional msg quit branch args initial) + (declare (indent defun)) + (magit-mode-setup #'magit-log-select-mode + (or branch (magit-get-current-branch) "HEAD") + (append args magit-log-select-arguments)) + (magit-log-goto-same-commit initial) + (setq magit-log-select-pick-function pick) + (setq magit-log-select-quit-function quit) + (when magit-log-select-show-usage + (let ((pick (propertize (substitute-command-keys + "\\[magit-log-select-pick]") + 'face + 'magit-header-line-key)) + (quit (propertize (substitute-command-keys + "\\[magit-log-select-quit]") + 'face + 'magit-header-line-key))) + (setq msg (format-spec + (if msg + (if (string-suffix-p "," msg) + (concat msg " or %q to abort") + msg) + "Type %p to select commit at point, or %q to abort") + `((?p . ,pick) + (?q . ,quit))))) + (add-face-text-property 0 (length msg) 'magit-header-line-log-select t msg) + (when (memq magit-log-select-show-usage '(both header-line)) + (magit-set-header-line-format msg)) + (when (memq magit-log-select-show-usage '(both echo-area)) + (message "%s" (substring-no-properties msg))))) + +(defun magit-log-select-pick () + "Select the commit at point and act on it. +Call `magit-log-select-pick-function' with the selected +commit as argument." + (interactive) + (let ((fun magit-log-select-pick-function) + (rev (magit-commit-at-point))) + (magit-mode-bury-buffer 'kill) + (funcall fun rev))) + +(defun magit-log-select-quit () + "Abort selecting a commit, don't act on any commit." + (interactive) + (magit-mode-bury-buffer 'kill) + (when magit-log-select-quit-function + (funcall magit-log-select-quit-function))) + +;;; Cherry Mode + +(defvar magit-cherry-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-mode-map) + (define-key map "q" 'magit-log-bury-buffer) + (define-key map "L" 'magit-margin-popup) + map) + "Keymap for `magit-cherry-mode'.") + +(define-derived-mode magit-cherry-mode magit-mode "Magit Cherry" + "Mode for looking at commits not merged upstream. + +\\\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit at point. + +Type \\[magit-cherry-pick-popup] to apply the commit at point. + +\\{magit-cherry-mode-map}" + :group 'magit-log + (hack-dir-local-variables-non-file-buffer) + (setq imenu-create-index-function + 'magit-imenu--cherry-create-index-function) + (setq-local bookmark-make-record-function + 'magit-bookmark--cherry-make-record)) + +;;;###autoload +(defun magit-cherry (head upstream) + "Show commits in a branch that are not merged in the upstream branch." + (interactive + (let ((head (magit-read-branch "Cherry head"))) + (list head (magit-read-other-branch "Cherry upstream" head + (magit-get-upstream-branch head))))) + (require 'magit) + (magit-mode-setup #'magit-cherry-mode upstream head)) + +(defun magit-cherry-refresh-buffer (_upstream _head) + (magit-insert-section (cherry) + (magit-run-section-hook 'magit-cherry-sections-hook))) + +(defun magit-insert-cherry-headers () + "Insert headers appropriate for `magit-cherry-mode' buffers." + (magit-insert-head-branch-header (nth 1 magit-refresh-args)) + (magit-insert-upstream-branch-header (nth 1 magit-refresh-args) + (nth 0 magit-refresh-args) + "Upstream: ") + (insert ?\n)) + +(defun magit-insert-cherry-commits () + "Insert commit sections into a `magit-cherry-mode' buffer." + (magit-insert-section (cherries) + (magit-insert-heading "Cherry commits:") + (magit-git-wash (apply-partially 'magit-log-wash-log 'cherry) + "cherry" "-v" "--abbrev" magit-refresh-args))) + +;;; Reflog Mode + +(defvar magit-reflog-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-log-mode-map) + (define-key map "L" 'magit-margin-popup) + map) + "Keymap for `magit-reflog-mode'.") + +(define-derived-mode magit-reflog-mode magit-log-mode "Magit Reflog" + "Mode for looking at Git reflog. + +This mode is documented in info node `(magit)Reflog'. + +\\\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit at point. + +Type \\[magit-cherry-pick-popup] to apply the commit at point. +Type \\[magit-reset] to reset `HEAD' to the commit at point. + +\\{magit-reflog-mode-map}" + :group 'magit-log + (hack-dir-local-variables-non-file-buffer) + (setq-local bookmark-make-record-function + 'magit-bookmark--reflog-make-record)) + +(defun magit-reflog-refresh-buffer (ref args) + (magit-set-header-line-format (concat "Reflog for " ref)) + (magit-insert-section (reflogbuf) + (magit-git-wash (apply-partially 'magit-log-wash-log 'reflog) + "reflog" "show" "--format=%h%x00%aN%x00%gd%x00%gs" "--date=raw" + args ref "--"))) + +(defvar magit-reflog-labels + '(("commit" . magit-reflog-commit) + ("amend" . magit-reflog-amend) + ("merge" . magit-reflog-merge) + ("checkout" . magit-reflog-checkout) + ("branch" . magit-reflog-checkout) + ("reset" . magit-reflog-reset) + ("rebase" . magit-reflog-rebase) + ("cherry-pick" . magit-reflog-cherry-pick) + ("initial" . magit-reflog-commit) + ("pull" . magit-reflog-remote) + ("clone" . magit-reflog-remote) + ("autosave" . magit-reflog-commit) + ("restart" . magit-reflog-reset))) + +(defun magit-reflog-format-subject (subject) + (let* ((match (string-match magit-reflog-subject-re subject)) + (command (and match (match-string 1 subject))) + (option (and match (match-string 2 subject))) + (type (and match (match-string 3 subject))) + (label (if (string= command "commit") + (or type command) + command)) + (text (if (string= command "commit") + label + (mapconcat #'identity + (delq nil (list command option type)) + " ")))) + (format "%-16s " + (propertize text 'face + (or (cdr (assoc label magit-reflog-labels)) + 'magit-reflog-other))))) + +;;; Log Sections +;;;; Standard Log Sections + +(defvar magit-unpulled-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-diff-dwim) + map) + "Keymap for `unpulled' sections.") + +(magit-define-section-jumper magit-jump-to-unpulled-from-upstream + "Unpulled from @{upstream}" unpulled "..@{upstream}") + +(defun magit-insert-unpulled-from-upstream () + "Insert commits that haven't been pulled from the upstream yet." + (when (magit-git-success "rev-parse" "@{upstream}") + (magit-insert-section (unpulled "..@{upstream}" t) + (magit-insert-heading + (format (propertize "Unpulled from %s:" 'face 'magit-section-heading) + (magit-get-upstream-branch))) + (magit-insert-log "..@{upstream}" magit-log-section-arguments)))) + +(magit-define-section-jumper magit-jump-to-unpulled-from-pushremote + "Unpulled from " unpulled + (concat ".." (magit-get-push-branch))) + +(defun magit-insert-unpulled-from-pushremote () + "Insert commits that haven't been pulled from the push-remote yet." + (--when-let (magit-get-push-branch) + (unless (and (equal (magit-rev-name it) + (magit-rev-name "@{upstream}")) + (or (memq 'magit-insert-unpulled-from-upstream + magit-status-sections-hook) + (memq 'magit-insert-unpulled-from-upstream-or-recent + magit-status-sections-hook))) + (magit-insert-section (unpulled (concat ".." it) t) + (magit-insert-heading + (format (propertize "Unpulled from %s:" 'face 'magit-section-heading) + (propertize it 'face 'magit-branch-remote))) + (magit-insert-log (concat ".." it) magit-log-section-arguments))))) + +(defvar magit-unpushed-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-diff-dwim) + map) + "Keymap for `unpushed' sections.") + +(magit-define-section-jumper magit-jump-to-unpushed-to-upstream + "Unpushed to @{upstream}" unpushed "@{upstream}..") + +(defun magit-insert-unpushed-to-upstream-or-recent () + "Insert section showing unpushed or other recent commits. +If an upstream is configured for the current branch and it is +behind of the current branch, then show the commits that have +not yet been pushed into the upstream branch. If no upstream is +configured or if the upstream is not behind of the current branch, +then show the last `magit-log-section-commit-count' commits." + (let ((upstream (magit-rev-parse "@{upstream}"))) + (if (or (not upstream) + (magit-rev-ancestor-p "HEAD" upstream)) + (magit-insert-recent-commits 'unpushed "@{upstream}..") + (magit-insert-unpushed-to-upstream)))) + +(defun magit-insert-unpushed-to-upstream () + "Insert commits that haven't been pushed to the upstream yet." + (when (magit-git-success "rev-parse" "@{upstream}") + (magit-insert-section (unpushed "@{upstream}..") + (magit-insert-heading + (format (propertize "Unmerged into %s:" 'face 'magit-section-heading) + (magit-get-upstream-branch))) + (magit-insert-log "@{upstream}.." magit-log-section-arguments)))) + +(defun magit-insert-recent-commits (&optional type value) + "Insert section showing recent commits. +Show the last `magit-log-section-commit-count' commits." + (let* ((start (format "HEAD~%s" magit-log-section-commit-count)) + (range (and (magit-rev-verify start) + (concat start "..HEAD")))) + (magit-insert-section ((eval (or type 'recent)) + (or value range) + t) + (magit-insert-heading "Recent commits") + (magit-insert-log range + (cons (format "-n%d" magit-log-section-commit-count) + (--remove (string-prefix-p "-n" it) + magit-log-section-arguments)))))) + +(magit-define-section-jumper magit-jump-to-unpushed-to-pushremote + "Unpushed to " unpushed + (concat (magit-get-push-branch) "..")) + +(defun magit-insert-unpushed-to-pushremote () + "Insert commits that haven't been pushed to the push-remote yet." + (--when-let (magit-get-push-branch) + (unless (and (equal (magit-rev-name it) + (magit-rev-name "@{upstream}")) + (or (memq 'magit-insert-unpushed-to-upstream + magit-status-sections-hook) + (memq 'magit-insert-unpushed-to-upstream-or-recent + magit-status-sections-hook))) + (magit-insert-section (unpushed (concat it "..") t) + (magit-insert-heading + (format (propertize "Unpushed to %s:" 'face 'magit-section-heading) + (propertize it 'face 'magit-branch-remote))) + (magit-insert-log (concat it "..") magit-log-section-arguments))))) + +;;;; Auxiliary Log Sections + +(defun magit-insert-unpulled-cherries () + "Insert section showing unpulled commits. +Like `magit-insert-unpulled-from-upstream' but prefix each commit +which has not been applied yet (i.e. a commit with a patch-id +not shared with any local commit) with \"+\", and all others with +\"-\"." + (when (magit-git-success "rev-parse" "@{upstream}") + (magit-insert-section (unpulled "..@{upstream}") + (magit-insert-heading "Unpulled commits:") + (magit-git-wash (apply-partially 'magit-log-wash-log 'cherry) + "cherry" "-v" (magit-abbrev-arg) + (magit-get-current-branch) "@{upstream}")))) + +(defun magit-insert-unpushed-cherries () + "Insert section showing unpushed commits. +Like `magit-insert-unpushed-to-upstream' but prefix each commit +which has not been applied to upstream yet (i.e. a commit with +a patch-id not shared with any upstream commit) with \"+\", and +all others with \"-\"." + (when (magit-git-success "rev-parse" "@{upstream}") + (magit-insert-section (unpushed "@{upstream}..") + (magit-insert-heading "Unpushed commits:") + (magit-git-wash (apply-partially 'magit-log-wash-log 'cherry) + "cherry" "-v" (magit-abbrev-arg) "@{upstream}")))) + +;;; _ +(provide 'magit-log) +;;; magit-log.el ends here diff --git a/elpa/magit-20181113.1837/magit-margin.el b/elpa/magit-20181113.1837/magit-margin.el new file mode 100644 index 00000000..5aaa4f53 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-margin.el @@ -0,0 +1,242 @@ +;;; magit-margin.el --- margins in Magit buffers -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements support for showing additional information +;; in the margins of Magit buffers. Currently this is only used for +;; commits, for which the committer date or age, and optionally the +;; author name are shown. + +;;; Code: + +(require 'dash) + +(eval-when-compile + (require 'subr-x)) + +(require 'magit-section) +(require 'magit-mode) + +(defgroup magit-margin nil + "Information Magit displays in the margin. + +You can change the STYLE and AUTHOR-WIDTH of all `magit-*-margin' +options to the same values by customizing `magit-log-margin' +*before* `magit' is loaded. If you do that, then the respective +values for the other options will default to what you have set +for that variable. Likewise if you set `magit-log-margin's INIT +to nil, then that is used in the default of all other options. But +setting it to t, i.e. re-enforcing the default for that option, +does not carry to other options." + :link '(info-link "(magit)Log Margin") + :group 'magit-log) + +(defvar-local magit-buffer-margin nil) +(put 'magit-buffer-margin 'permanent-local t) + +(defvar-local magit-set-buffer-margin-refresh nil) + +(defvar magit--age-spec) + +;;; Commands + +(magit-define-popup magit-margin-popup + "Popup console for changing appearance of the margin." + :actions '("Margin" + (?L "Toggle visibility" magit-toggle-margin) + (?l "Cycle style" magit-cycle-margin-style) + (?d "Toggle details" magit-toggle-margin-details) + (lambda () + (and (with-current-buffer magit-pre-popup-buffer + (derived-mode-p 'magit-refs-mode)) + (propertize "Left edge" 'face 'magit-popup-heading))) + (?v "Change verbosity" magit-refs-set-show-commit-count)) + :max-action-columns 1) + +(defun magit-toggle-margin () + "Show or hide the Magit margin." + (interactive) + (unless (magit-margin-option) + (user-error "Magit margin isn't supported in this buffer")) + (setcar magit-buffer-margin (not (magit-buffer-margin-p))) + (magit-set-buffer-margin)) + +(defun magit-cycle-margin-style () + "Cycle style used for the Magit margin." + (interactive) + (unless (magit-margin-option) + (user-error "Magit margin isn't supported in this buffer")) + ;; This is only suitable for commit margins (there are not others). + (setf (cadr magit-buffer-margin) + (pcase (cadr magit-buffer-margin) + (`age 'age-abbreviated) + (`age-abbreviated + (let ((default (cadr (symbol-value (magit-margin-option))))) + (if (stringp default) default "%Y-%m-%d %H:%M "))) + (_ 'age))) + (magit-set-buffer-margin nil t)) + +(defun magit-toggle-margin-details () + "Show or hide details in the Magit margin." + (interactive) + (unless (magit-margin-option) + (user-error "Magit margin isn't supported in this buffer")) + (setf (nth 3 magit-buffer-margin) + (not (nth 3 magit-buffer-margin))) + (magit-set-buffer-margin nil t)) + +;;; Core + +(defun magit-buffer-margin-p () + (car magit-buffer-margin)) + +(defun magit-margin-option () + (pcase major-mode + (`magit-cherry-mode 'magit-cherry-margin) + (`magit-log-mode 'magit-log-margin) + (`magit-log-select-mode 'magit-log-select-margin) + (`magit-reflog-mode 'magit-reflog-margin) + (`magit-refs-mode 'magit-refs-margin) + (`magit-stashes-mode 'magit-stashes-margin) + (`magit-status-mode 'magit-status-margin))) + +(defun magit-set-buffer-margin (&optional reset refresh) + (when-let ((option (magit-margin-option))) + (let* ((default (symbol-value option)) + (default-width (nth 2 default))) + (when (or reset (not magit-buffer-margin)) + (setq magit-buffer-margin (copy-sequence default))) + (pcase-let ((`(,enable ,style ,_width ,details ,details-width) + magit-buffer-margin)) + (when (functionp default-width) + (setf (nth 2 magit-buffer-margin) + (funcall default-width style details details-width))) + (dolist (window (get-buffer-window-list nil nil 0)) + (with-selected-window window + (magit-set-window-margin window) + (if enable + (add-hook 'window-configuration-change-hook + 'magit-set-window-margin nil t) + (remove-hook 'window-configuration-change-hook + 'magit-set-window-margin t)))) + (when (and enable (or refresh magit-set-buffer-margin-refresh)) + (magit-refresh-buffer)))))) + +(defun magit-set-window-margin (&optional window) + (when (or window (setq window (get-buffer-window))) + (with-selected-window window + (set-window-margins + nil (car (window-margins)) + (and (magit-buffer-margin-p) + (nth 2 magit-buffer-margin)))))) + +(defun magit-make-margin-overlay (&optional string previous-line) + (if previous-line + (save-excursion + (forward-line -1) + (magit-make-margin-overlay string)) + ;; Don't put the overlay on the complete line to work around #1880. + (let ((o (make-overlay (1+ (line-beginning-position)) + (line-end-position) + nil t))) + (overlay-put o 'evaporate t) + (overlay-put o 'before-string + (propertize "o" 'display + (list (list 'margin 'right-margin) + (or string " "))))))) + +(defun magit-maybe-make-margin-overlay () + (when (or (magit-section-match + '(unpulled unpushed recent stashes local cherries) + magit-insert-section--current) + (and (eq major-mode 'magit-refs-mode) + (magit-section-match + '(remote commit tags) + magit-insert-section--current))) + (magit-make-margin-overlay nil t))) + +;;; Custom Support + +(defun magit-margin-set-variable (mode symbol value) + (set-default symbol value) + (message "Updating margins in %s buffers..." mode) + (dolist (buffer (buffer-list)) + (with-current-buffer buffer + (when (eq major-mode mode) + (magit-set-buffer-margin t) + (magit-refresh)))) + (message "Updating margins in %s buffers...done" mode)) + +(defconst magit-log-margin--custom-type + '(list (boolean :tag "Show margin initially") + (choice :tag "Show committer" + (string :tag "date using time-format" "%Y-%m-%d %H:%M ") + (const :tag "date's age" age) + (const :tag "date's age (abbreviated)" age-abbreviated)) + (const :tag "Calculate width using magit-log-margin-width" + magit-log-margin-width) + (boolean :tag "Show author name by default") + (integer :tag "Show author name using width"))) + +;;; Time Utilities + +(defvar magit--age-spec + `((?Y "year" "years" ,(round (* 60 60 24 365.2425))) + (?M "month" "months" ,(round (* 60 60 24 30.436875))) + (?w "week" "weeks" ,(* 60 60 24 7)) + (?d "day" "days" ,(* 60 60 24)) + (?h "hour" "hours" ,(* 60 60)) + (?m "minute" "minutes" 60) + (?s "second" "seconds" 1)) + "Time units used when formatting relative commit ages. + +The value is a list of time units, beginning with the longest. +Each element has the form (CHAR UNIT UNITS SECONDS). UNIT is the +time unit, UNITS is the plural of that unit. CHAR is a character +abbreviation. And SECONDS is the number of seconds in one UNIT. + +This is defined as a variable to make it possible to use time +units for a language other than English. It is not defined +as an option, because most other parts of Magit are always in +English.") + +(defun magit--age (date &optional abbreviate) + (cl-labels ((fn (age spec) + (pcase-let ((`(,char ,unit ,units ,weight) (car spec))) + (let ((cnt (round (/ age weight 1.0)))) + (if (or (not (cdr spec)) + (>= (/ age weight) 1)) + (list cnt (cond (abbreviate char) + ((= cnt 1) unit) + (t units))) + (fn age (cdr spec))))))) + (fn (abs (- (float-time) + (if (stringp date) + (string-to-number date) + date))) + magit--age-spec))) + +;;; _ +(provide 'magit-margin) +;;; magit-margin.el ends here diff --git a/elpa/magit-20181113.1837/magit-merge.el b/elpa/magit-20181113.1837/magit-merge.el new file mode 100644 index 00000000..f06b1dc6 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-merge.el @@ -0,0 +1,285 @@ +;;; magit-merge.el --- merge functionality -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements merge commands. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +(declare-function magit-git-push "magit-push" (branch target args)) + +;;; Commands + +;;;###autoload (autoload 'magit-merge-popup "magit" nil t) +(magit-define-popup magit-merge-popup + "Popup console for merge commands." + :man-page "git-merge" + :switches '((?f "Fast-forward only" "--ff-only") + (?n "No fast-forward" "--no-ff")) + :options '((?s "Strategy" "--strategy=")) + :actions '((?m "Merge" magit-merge-plain) + (?p "Preview merge" magit-merge-preview) + (?e "Merge and edit message" magit-merge-editmsg) nil + (?n "Merge but don't commit" magit-merge-nocommit) + (?s "Squash merge" magit-merge-squash) + (?a "Absorb" magit-merge-absorb) + (?i "Merge into" magit-merge-into)) + :sequence-actions '((?m "Commit merge" magit-commit-create) + (?a "Abort merge" magit-merge-abort)) + :sequence-predicate 'magit-merge-in-progress-p + :default-action 'magit-merge + :max-action-columns 2) + +;;;###autoload +(defun magit-merge-plain (rev &optional args nocommit) + "Merge commit REV into the current branch; using default message. + +Unless there are conflicts or a prefix argument is used create a +merge commit using a generic commit message and without letting +the user inspect the result. With a prefix argument pretend the +merge failed to give the user the opportunity to inspect the +merge. + +\(git merge --no-edit|--no-commit [ARGS] REV)" + (interactive (list (magit-read-other-branch-or-commit "Merge") + (magit-merge-arguments) + current-prefix-arg)) + (magit-merge-assert) + (magit-run-git-async "merge" (if nocommit "--no-commit" "--no-edit") args rev)) + +;;;###autoload +(defun magit-merge-editmsg (rev &optional args) + "Merge commit REV into the current branch; and edit message. +Perform the merge and prepare a commit message but let the user +edit it. +\n(git merge --edit --no-ff [ARGS] REV)" + (interactive (list (magit-read-other-branch-or-commit "Merge") + (magit-merge-arguments))) + (magit-merge-assert) + (cl-pushnew "--no-ff" args :test #'equal) + (apply #'magit-run-git-with-editor "merge" "--edit" + (append args (list rev)))) + +;;;###autoload +(defun magit-merge-nocommit (rev &optional args) + "Merge commit REV into the current branch; pretending it failed. +Pretend the merge failed to give the user the opportunity to +inspect the merge and change the commit message. +\n(git merge --no-commit --no-ff [ARGS] REV)" + (interactive (list (magit-read-other-branch-or-commit "Merge") + (magit-merge-arguments))) + (magit-merge-assert) + (cl-pushnew "--no-ff" args :test #'equal) + (magit-run-git-async "merge" "--no-commit" args rev)) + +;;;###autoload +(defun magit-merge-into (branch &optional args) + "Merge the current branch into BRANCH and remove the former. + +Before merging, force push the source branch to its push-remote, +provided the respective remote branch already exists, ensuring +that the respective pull-request (if any) won't get stuck on some +obsolete version of the commits that are being merged. Finally +if `magit-branch-pull-request' was used to create the merged +branch, then also remove the respective remote branch." + (interactive + (list (magit-read-other-local-branch + (format "Merge `%s' into" (magit-get-current-branch)) + nil + (when-let ((upstream (magit-get-upstream-branch))) + (when-let ((upstream (cdr (magit-split-branch-name upstream)))) + (and (magit-branch-p upstream) upstream)))) + (magit-merge-arguments))) + (let ((current (magit-get-current-branch))) + (when (zerop (magit-call-git "checkout" branch)) + (magit--merge-absort current args)))) + +;;;###autoload +(defun magit-merge-absorb (branch &optional args) + "Merge BRANCH into the current branch and remove the former. + +Before merging, force push the source branch to its push-remote, +provided the respective remote branch already exists, ensuring +that the respective pull-request (if any) won't get stuck on some +obsolete version of the commits that are being merged. Finally +if `magit-branch-pull-request' was used to create the merged +branch, then also remove the respective remote branch." + (interactive (list (magit-read-other-local-branch "Absorb branch") + (magit-merge-arguments))) + (magit--merge-absort branch args)) + +(defun magit--merge-absort (branch args) + (when (equal branch "master") + (unless (yes-or-no-p + "Do you really want to merge `master' into another branch? ") + (user-error "Abort"))) + (if-let ((target (magit-get-push-branch branch t))) + (progn + (magit-git-push branch target (list "--force-with-lease")) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (not (zerop (process-exit-status process))) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (magit--merge-absort-1 branch args)))))) + (magit--merge-absort-1 branch args))) + +(defun magit--merge-absort-1 (branch args) + (magit-run-git-async "merge" args "--no-edit" branch) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (magit-branch-maybe-delete-pr-remote branch) + (magit-branch-unset-pushRemote branch) + (magit-run-git "branch" "-D" branch)))))) + +;;;###autoload +(defun magit-merge-squash (rev) + "Squash commit REV into the current branch; don't create a commit. +\n(git merge --squash REV)" + (interactive (list (magit-read-other-branch-or-commit "Squash"))) + (magit-merge-assert) + (magit-run-git-async "merge" "--squash" rev)) + +;;;###autoload +(defun magit-merge-preview (rev) + "Preview result of merging REV into the current branch." + (interactive (list (magit-read-other-branch-or-commit "Preview merge"))) + (magit-mode-setup #'magit-merge-preview-mode rev)) + +(define-derived-mode magit-merge-preview-mode magit-diff-mode "Magit Merge" + "Mode for previewing a merge." + :group 'magit-diff + (hack-dir-local-variables-non-file-buffer)) + +(defun magit-merge-preview-refresh-buffer (rev) + (let* ((branch (magit-get-current-branch)) + (head (or branch (magit-rev-verify "HEAD")))) + (magit-set-header-line-format (format "Preview merge of %s into %s" + rev + (or branch "HEAD"))) + (magit-insert-section (diffbuf) + (magit-git-wash #'magit-diff-wash-diffs + "merge-tree" (magit-git-string "merge-base" head rev) head rev)))) + +;;;###autoload +(defun magit-merge-abort () + "Abort the current merge operation. +\n(git merge --abort)" + (interactive) + (unless (file-exists-p (magit-git-dir "MERGE_HEAD")) + (user-error "No merge in progress")) + (magit-confirm 'abort-merge) + (magit-run-git-async "merge" "--abort")) + +(defun magit-checkout-stage (file arg) + "During a conflict checkout and stage side, or restore conflict." + (interactive + (let ((file (magit-completing-read "Checkout file" + (magit-tracked-files) nil nil nil + 'magit-read-file-hist + (magit-current-file)))) + (cond ((member file (magit-unmerged-files)) + (list file (magit-checkout-read-stage file))) + ((yes-or-no-p (format "Restore conflicts in %s? " file)) + (list file "--merge")) + (t + (user-error "Quit"))))) + (pcase (cons arg (cddr (car (magit-file-status file)))) + ((or `("--ours" ?D ,_) + `("--theirs" ,_ ?D)) + (magit-run-git "rm" "--" file)) + (_ (if (equal arg "--merge") + ;; This fails if the file was deleted on one + ;; side. And we cannot do anything about it. + (magit-run-git "checkout" "--merge" "--" file) + (magit-call-git "checkout" arg "--" file) + (magit-run-git "add" "-u" "--" file))))) + +;;; Utilities + +(defun magit-merge-in-progress-p () + (file-exists-p (magit-git-dir "MERGE_HEAD"))) + +(defun magit--merge-range (&optional head) + (unless head + (setq head (magit-get-shortname + (car (magit-file-lines (magit-git-dir "MERGE_HEAD")))))) + (and head + (concat (magit-git-string "merge-base" "--octopus" "HEAD" head) + ".." head))) + +(defun magit-merge-assert () + (or (not (magit-anything-modified-p t)) + (magit-confirm 'merge-dirty + "Merging with dirty worktree is risky. Continue"))) + +(defun magit-checkout-read-stage (file) + (magit-read-char-case (format "For %s checkout: " file) t + (?o "[o]ur stage" "--ours") + (?t "[t]heir stage" "--theirs") + (?c "[c]onflict" "--merge"))) + +;;; Sections + +(defvar magit-unmerged-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-diff-dwim) + map) + "Keymap for `unmerged' sections.") + +(defun magit-insert-merge-log () + "Insert section for the on-going merge. +Display the heads that are being merged. +If no merge is in progress, do nothing." + (when (magit-merge-in-progress-p) + (let* ((heads (mapcar #'magit-get-shortname + (magit-file-lines (magit-git-dir "MERGE_HEAD")))) + (range (magit--merge-range (car heads)))) + (magit-insert-section (unmerged range) + (magit-insert-heading + (format "Merging %s:" (mapconcat #'identity heads ", "))) + (magit-insert-log + range + (let ((args magit-log-section-arguments)) + (unless (member "--decorate=full" magit-log-section-arguments) + (push "--decorate=full" args)) + args)))))) + +;;; _ +(provide 'magit-merge) +;;; magit-merge.el ends here diff --git a/elpa/magit-20181113.1837/magit-mode.el b/elpa/magit-20181113.1837/magit-mode.el new file mode 100644 index 00000000..2431be75 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-mode.el @@ -0,0 +1,1404 @@ +;;; magit-mode.el --- create and refresh Magit buffers -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements the abstract major-mode `magit-mode' from +;; which almost all other Magit major-modes derive. The code in here +;; is mostly concerned with creating and refreshing Magit buffers. + +;;; Code: + +(require 'cl-lib) +(require 'dash) + +(eval-when-compile + (require 'subr-x)) + +(require 'magit-section) +(require 'magit-git) + +;; For `magit-display-buffer-fullcolumn-most-v1' from `git-commit' +(defvar git-commit-mode) +;; For `magit-xref-insert-buttons' from `magit' +(defvar magit-diff-show-xref-buttons) +(defvar magit-revision-show-xref-buttons) +;; For `magit-refresh' +(defvar magit-post-commit-hook-commands) +(defvar magit-post-stage-hook-commands) +(defvar magit-post-unstage-hook-commands) +;; For `magit-refresh' and `magit-refresh-all' +(declare-function magit-auto-revert-buffers "magit-autorevert" ()) +;; For `magit-refresh-buffer' +(declare-function magit-process-unset-mode-line-error-status "magit-process" ()) +;; For `magit-mode-setup-internal' +(declare-function magit-status-goto-initial-section "magit-status" ()) + +(require 'format-spec) +(require 'help-mode) + +;;; Options + +(defcustom magit-mode-hook + '(magit-load-config-extensions + magit-xref-setup) + "Hook run when entering a mode derived from Magit mode." + :group 'magit-modes + :type 'hook + :options '(magit-load-config-extensions + magit-xref-setup + bug-reference-mode)) + +(defcustom magit-mode-setup-hook + '(magit-maybe-save-repository-buffers + magit-set-buffer-margin) + "Hook run by `magit-mode-setup'. + +This is run right after displaying the buffer and right before +generating or updating its content. `magit-mode-hook' and other, +more specific, `magit-mode-*-hook's on the other hand are run +right before displaying the buffer. Usually one of these hooks +should be used instead of this one." + :package-version '(magit . "2.3.0") + :group 'magit-modes + :type 'hook + :options '(magit-maybe-save-repository-buffers + magit-set-buffer-margin)) + +(defcustom magit-pre-refresh-hook '(magit-maybe-save-repository-buffers) + "Hook run before refreshing in `magit-refresh'. + +This hook, or `magit-post-refresh-hook', should be used +for functions that are not tied to a particular buffer. + +To run a function with a particular buffer current, use +`magit-refresh-buffer-hook' and use `derived-mode-p' +inside your function." + :package-version '(magit . "2.4.0") + :group 'magit-refresh + :type 'hook + :options '(magit-maybe-save-repository-buffers)) + +(defcustom magit-post-refresh-hook nil + "Hook run after refreshing in `magit-refresh'. + +This hook, or `magit-pre-refresh-hook', should be used +for functions that are not tied to a particular buffer. + +To run a function with a particular buffer current, use +`magit-refresh-buffer-hook' and use `derived-mode-p' +inside your function." + :package-version '(magit . "2.4.0") + :group 'magit-refresh + :type 'hook) + +(defcustom magit-display-buffer-function 'magit-display-buffer-traditional + "The function used display a Magit buffer. + +All Magit buffers (buffers whose major-modes derive from +`magit-mode') are displayed using `magit-display-buffer', +which in turn uses the function specified here." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type '(radio (function-item magit-display-buffer-traditional) + (function-item magit-display-buffer-same-window-except-diff-v1) + (function-item magit-display-buffer-fullframe-status-v1) + (function-item magit-display-buffer-fullframe-status-topleft-v1) + (function-item magit-display-buffer-fullcolumn-most-v1) + (function-item display-buffer) + (function :tag "Function"))) + +(defcustom magit-pre-display-buffer-hook '(magit-save-window-configuration) + "Hook run by `magit-display-buffer' before displaying the buffer." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type 'hook + :get 'magit-hook-custom-get + :options '(magit-save-window-configuration)) + +(defcustom magit-post-display-buffer-hook '(magit-maybe-set-dedicated) + "Hook run by `magit-display-buffer' after displaying the buffer." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type 'hook + :get 'magit-hook-custom-get + :options '(magit-maybe-set-dedicated)) + +(defcustom magit-generate-buffer-name-function + 'magit-generate-buffer-name-default-function + "The function used to generate the name for a Magit buffer." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type '(radio (function-item magit-generate-buffer-name-default-function) + (function :tag "Function"))) + +(defcustom magit-buffer-name-format "%x%M%v: %t%x" + "The format string used to name Magit buffers. + +The following %-sequences are supported: + +`%m' The name of the major-mode, but with the `-mode' suffix + removed. + +`%M' Like \"%m\" but abbreviate `magit-status-mode' as `magit'. + +`%v' The value the buffer is locked to, in parentheses, or an + empty string if the buffer is not locked to a value. + +`%V' Like \"%v\", but the string is prefixed with a space, unless + it is an empty string. + +`%t' The top-level directory of the working tree of the + repository, or if `magit-uniquify-buffer-names' is non-nil + an abbreviation of that. + +`%x' If `magit-uniquify-buffer-names' is nil \"*\", otherwise the + empty string. Due to limitations of the `uniquify' package, + buffer names must end with the path. + +`%T' Obsolete, use \"%t%x\" instead. Like \"%t\", but append an + asterisk if and only if `magit-uniquify-buffer-names' is nil. + +The value should always contain \"%m\" or \"%M\", \"%v\" or +\"%V\", and \"%t\" (or the obsolete \"%T\"). + +If `magit-uniquify-buffer-names' is non-nil, then the value must +end with \"%t\" or \"%t%x\" (or the obsolete \"%T\"). See issue +#2841. + +This is used by `magit-generate-buffer-name-default-function'. +If another `magit-generate-buffer-name-function' is used, then +it may not respect this option, or on the contrary it may +support additional %-sequences." + :package-version '(magit . "2.12.0") + :group 'magit-buffers + :type 'string) + +(defcustom magit-uniquify-buffer-names t + "Whether to uniquify the names of Magit buffers." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type 'boolean) + +(defcustom magit-bury-buffer-function 'magit-restore-window-configuration + "The function used to bury or kill the current Magit buffer." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type '(radio (function-item quit-window) + (function-item magit-mode-quit-window) + (function-item magit-restore-window-configuration) + (function :tag "Function"))) + +(defcustom magit-use-sticky-arguments t + "How to reuse arguments from existing diff and log buffers. + +nil Always use the default value of the variable + `magit-log-arguments' for log commands. Likewise, + always use the default value of the variable + `magit-diff-arguments' for diff command calls. + +current If the mode of the current buffer is derived from + `magit-log-mode' or `magit-diff-mode', reuse the + arguments from that buffer instead of those given by + the variable `magit-log-arguments' or + `magit-diff-arguments', respectively. + +t Like `current', but if the mode of the current buffer + is not derived from `magit-log-mode' or + `magit-diff-mode', use the arguments from the current + repository's active (i.e. non-locked) `magit-log-mode' + or `magit-diff-mode' buffer, respectively, if it + exists. + + Note that commands that generate a + `magit-revision-mode' or `magit-stash-mode' buffer will + also collect their diff arguments from the active + `magit-diff-mode' buffer. + +In general, there is a separation between the \"sticky\" +arguments for log and diff buffers, but there is one special +case: if the current buffer is a log buffer, +`magit-show-commit' (considered a diff command) uses the file +filter from the log buffer." + :package-version '(magit . "2.11.0") + :group 'magit-buffers + :type '(choice (const :tag "disabled" nil) + (const :tag "sticky for current" current) + (const :tag "sticky" t))) + +(defcustom magit-region-highlight-hook + '(magit-section-update-region magit-diff-update-hunk-region) + "Functions used to highlight the region. + +Each function is run with the current section as only argument +until one of them returns non-nil. If all functions return nil, +then fall back to regular region highlighting." + :package-version '(magit . "2.1.0") + :group 'magit-refresh + :type 'hook + :options '(magit-section-update-region magit-diff-update-hunk-region)) + +(defcustom magit-create-buffer-hook nil + "Normal hook run after creating a new `magit-mode' buffer." + :package-version '(magit . "2.90.0") + :group 'magit-refresh + :type 'hook) + +(defcustom magit-refresh-buffer-hook nil + "Normal hook for `magit-refresh-buffer' to run after refreshing." + :package-version '(magit . "2.1.0") + :group 'magit-refresh + :type 'hook) + +(defcustom magit-refresh-status-buffer t + "Whether the status buffer is refreshed after running git. + +When this is non-nil, then the status buffer is automatically +refreshed after running git for side-effects, in addition to the +current Magit buffer, which is always refreshed automatically. + +Only set this to nil after exhausting all other options to +improve performance." + :package-version '(magit . "2.4.0") + :group 'magit-refresh + :group 'magit-status + :type 'boolean) + +(defcustom magit-refresh-verbose nil + "Whether to revert Magit buffers verbosely." + :package-version '(magit . "2.1.0") + :group 'magit-refresh + :type 'boolean) + +(defcustom magit-save-repository-buffers t + "Whether to save file-visiting buffers when appropriate. + +If non-nil, then all modified file-visiting buffers belonging +to the current repository may be saved before running Magit +commands and before creating or refreshing Magit buffers. +If `dontask', then this is done without user intervention, for +any other non-nil value the user has to confirm each save. + +The default is t to avoid surprises, but `dontask' is the +recommended value." + :group 'magit-essentials + :group 'magit-buffers + :type '(choice (const :tag "Never" nil) + (const :tag "Ask" t) + (const :tag "Save without asking" dontask))) + +(defcustom magit-keep-region-overlay nil + "Whether to keep the region overlay when there is a valid selection. + +By default Magit removes the regular region overlay if, and only +if, that region constitutes a valid selection as understood by +Magit commands. Otherwise it does not remove that overlay, and +the region looks like it would in other buffers. + +There are two types of such valid selections: hunk-internal +regions and regions that select two or more sibling sections. +In such cases Magit removes the region overlay and instead +highlights a slightly larger range. All text (for hunk-internal +regions) or the headings of all sections (for sibling selections) +that are inside that range (not just inside the region) are acted +on by commands such as the staging command. This buffer range +begins at the beginning of the line on which the region begins +and ends at the end of the line on which the region ends. + +Because Magit acts on this larger range and not the region, it is +actually quite important to visualize that larger range. If we +don't do that, then one might think that these commands act on +the region instead. If you want to *also* visualize the region, +then set this option to t. But please note that when the region +does *not* constitute a valid selection, then the region is +*always* visualized as usual, and that it is usually under such +circumstances that you want to use a non-magit command to act on +the region. + +Besides keeping the region overlay, setting this option to t also +causes all face properties, except for `:foreground', to be +ignored for the faces used to highlight headings of selected +sections. This avoids the worst conflicts that result from +displaying the region and the selection overlays at the same +time. We are not interested in dealing with other conflicts. +In fact we *already* provide a way to avoid all of these +conflicts: *not* changing the value of this option. + +It should be clear by now that we consider it a mistake to set +this to display the region when the Magit selection is also +visualized, but since it has been requested a few times and +because it doesn't cost much to offer this option we do so. +However that might change. If the existence of this option +starts complicating other things, then it will be removed." + :package-version '(magit . "2.3.0") + :group 'magit-miscellaneous + :type 'boolean) + +;;; Magit Mode + +(defvar magit-mode-map + (let ((map (make-keymap))) + (suppress-keymap map t) + (cond ((featurep 'jkl) + (define-key map [return] 'magit-visit-thing) + (define-key map [C-return] 'magit-dired-jump) + (define-key map [tab] 'magit-section-toggle) + (define-key map [C-tab] 'magit-section-cycle) + (define-key map [M-tab] 'magit-section-cycle-diffs) + (define-key map [S-tab] 'magit-section-cycle-global) + (define-key map (kbd "M-o") 'magit-section-up) + (define-key map (kbd "i") 'magit-section-backward) + (define-key map (kbd "k") 'magit-section-forward) + (define-key map (kbd "M-i") 'magit-section-backward-sibling) + (define-key map (kbd "M-k") 'magit-section-forward-sibling) + (define-key map (kbd "p") 'magit-push-popup) + (define-key map (kbd ",") 'magit-delete-thing) + (define-key map (kbd ";") 'magit-file-untrack) + (define-key map (kbd "C-c C-i") 'magit-gitignore-popup)) + (t + (define-key map [C-return] 'magit-visit-thing) + (define-key map (kbd "C-m") 'magit-visit-thing) + (define-key map (kbd "C-M-i") 'magit-dired-jump) + (define-key map (kbd "C-i") 'magit-section-toggle) + (define-key map [C-tab] 'magit-section-cycle) + (define-key map [M-tab] 'magit-section-cycle-diffs) + ;; [backtab] is the most portable binding for Shift+Tab. + (define-key map [backtab] 'magit-section-cycle-global) + (define-key map (kbd "^") 'magit-section-up) + (define-key map (kbd "p") 'magit-section-backward) + (define-key map (kbd "n") 'magit-section-forward) + (define-key map (kbd "M-p") 'magit-section-backward-sibling) + (define-key map (kbd "M-n") 'magit-section-forward-sibling) + (define-key map (kbd "P") 'magit-push-popup) + (define-key map (kbd "k") 'magit-delete-thing) + (define-key map (kbd "K") 'magit-file-untrack) + (define-key map (kbd "i") 'magit-gitignore-popup) + (define-key map (kbd "I") 'magit-gitignore-popup))) + (define-key map (kbd "SPC") 'magit-diff-show-or-scroll-up) + (define-key map (kbd "DEL") 'magit-diff-show-or-scroll-down) + (define-key map "+" 'magit-diff-more-context) + (define-key map "-" 'magit-diff-less-context) + (define-key map "0" 'magit-diff-default-context) + (define-key map "1" 'magit-section-show-level-1) + (define-key map "2" 'magit-section-show-level-2) + (define-key map "3" 'magit-section-show-level-3) + (define-key map "4" 'magit-section-show-level-4) + (define-key map (kbd "M-1") 'magit-section-show-level-1-all) + (define-key map (kbd "M-2") 'magit-section-show-level-2-all) + (define-key map (kbd "M-3") 'magit-section-show-level-3-all) + (define-key map (kbd "M-4") 'magit-section-show-level-4-all) + (define-key map "$" 'magit-process-buffer) + (define-key map "%" 'magit-worktree-popup) + (define-key map "a" 'magit-cherry-apply) + (define-key map "A" 'magit-cherry-pick-popup) + (define-key map "b" 'magit-branch-popup) + (define-key map "B" 'magit-bisect-popup) + (define-key map "c" 'magit-commit-popup) + (define-key map "d" 'magit-diff-popup) + (define-key map "D" 'magit-diff-refresh-popup) + (define-key map "e" 'magit-ediff-dwim) + (define-key map "E" 'magit-ediff-popup) + (define-key map "f" 'magit-fetch-popup) + (define-key map "F" 'magit-pull-popup) + (define-key map "g" 'magit-refresh) + (define-key map "G" 'magit-refresh-all) + (define-key map "h" 'magit-dispatch-popup) + (define-key map "?" 'magit-dispatch-popup) + (define-key map "l" 'magit-log-popup) + (define-key map "L" 'magit-log-refresh-popup) + (define-key map "m" 'magit-merge-popup) + (define-key map "M" 'magit-remote-popup) + (define-key map "o" 'magit-submodule-popup) + (define-key map "O" 'magit-subtree-popup) + (define-key map "q" 'magit-mode-bury-buffer) + (define-key map "r" 'magit-rebase-popup) + (define-key map "R" 'magit-file-rename) + (define-key map "t" 'magit-tag-popup) + (define-key map "T" 'magit-notes-popup) + (define-key map "s" 'magit-stage-file) + (define-key map "S" 'magit-stage-modified) + (define-key map "u" 'magit-unstage-file) + (define-key map "U" 'magit-unstage-all) + (define-key map "v" 'magit-revert-no-commit) + (define-key map "V" 'magit-revert-popup) + (define-key map "w" 'magit-am-popup) + (define-key map "W" 'magit-patch-popup) + (define-key map "x" 'magit-reset-quickly) + (define-key map "X" 'magit-reset-popup) + (define-key map "y" 'magit-show-refs-popup) + (define-key map "Y" 'magit-cherry) + (define-key map "z" 'magit-stash-popup) + (define-key map "Z" 'magit-stash-popup) + (define-key map ":" 'magit-git-command) + (define-key map "!" 'magit-run-popup) + (define-key map (kbd "C-c C-c") 'magit-dispatch-popup) + (define-key map (kbd "C-c C-e") 'magit-edit-thing) + (define-key map (kbd "C-c C-w") 'magit-browse-thing) + (define-key map (kbd "C-x a") 'magit-add-change-log-entry) + (define-key map (kbd "C-x 4 a") 'magit-add-change-log-entry-other-window) + (define-key map (kbd "C-w") 'magit-copy-section-value) + (define-key map (kbd "M-w") 'magit-copy-buffer-revision) + (define-key map [remap previous-line] 'magit-previous-line) + (define-key map [remap next-line] 'magit-next-line) + (define-key map [remap evil-previous-line] 'evil-previous-visual-line) + (define-key map [remap evil-next-line] 'evil-next-visual-line) + map) + "Parent keymap for all keymaps of modes derived from `magit-mode'.") + +(defun magit-delete-thing () + "This is a placeholder command. +Where applicable, section-specific keymaps bind another command +which deletes the thing at point." + (interactive) + (user-error "There is no thing at point that could be deleted")) + +(defun magit-visit-thing () + "This is a placeholder command. +Where applicable, section-specific keymaps bind another command +which visits the thing at point." + (interactive) + (if (eq magit-current-popup 'magit-dispatch-popup) + (progn (setq magit-current-popup nil) + (call-interactively (key-binding (this-command-keys)))) + (user-error "There is no thing at point that could be visited"))) + +(defun magit-edit-thing () + "This is a placeholder command. +Where applicable, section-specific keymaps bind another command +which lets you edit the thing at point, likely in another buffer." + (interactive) + (if (eq magit-current-popup 'magit-dispatch-popup) + (progn (setq magit-current-popup nil) + (call-interactively (key-binding (this-command-keys)))) + (user-error "There is no thing at point that could be edited"))) + +(defun magit-browse-thing () + "This is a placeholder command. +Where applicable, section-specific keymaps bind another command +which visits the thing at point using `browse-url'." + (interactive) + (user-error "There is no thing at point that could be browsed")) + +(easy-menu-define magit-mode-menu magit-mode-map + "Magit menu" + '("Magit" + ["Refresh" magit-refresh t] + ["Refresh all" magit-refresh-all t] + "---" + ["Stage" magit-stage t] + ["Stage modified" magit-stage-modified t] + ["Unstage" magit-unstage t] + ["Reset index" magit-reset-index t] + ["Commit" magit-commit-popup t] + ["Add log entry" magit-commit-add-log t] + ["Tag" magit-tag-create t] + "---" + ["Diff working tree" magit-diff-working-tree t] + ["Diff" magit-diff t] + ("Log" + ["Log" magit-log-other t] + ["Reflog" magit-reflog-other t] + ["Extended..." magit-log-popup t]) + "---" + ["Cherry pick" magit-cherry-pick t] + ["Revert commit" magit-revert-popup t] + "---" + ["Ignore globally" magit-gitignore-globally t] + ["Ignore locally" magit-gitignore-locally t] + ["Discard" magit-discard t] + ["Reset head and index" magit-reset-mixed t] + ["Stash" magit-stash-both t] + ["Snapshot" magit-snapshot-both t] + "---" + ["Branch..." magit-checkout t] + ["Merge" magit-merge t] + ["Ediff resolve" magit-ediff-resolve t] + ["Rebase..." magit-rebase-popup t] + "---" + ["Push" magit-push t] + ["Pull" magit-pull-branch t] + ["Remote update" magit-fetch-all t] + ("Submodule" + ["Submodule update" magit-submodule-update t] + ["Submodule update and init" magit-submodule-setup t] + ["Submodule init" magit-submodule-init t] + ["Submodule sync" magit-submodule-sync t]) + "---" + ("Extensions") + "---" + ["Display Git output" magit-process-buffer t] + ["Quit Magit" magit-mode-bury-buffer t])) + +(defun magit-load-config-extensions () + "Load Magit extensions that are defined at the Git config layer." + (dolist (ext (magit-get-all "magit.extension")) + (let ((sym (intern (format "magit-%s-mode" ext)))) + (when (fboundp sym) + (funcall sym 1))))) + +(define-derived-mode magit-mode special-mode "Magit" + "Parent major mode from which Magit major modes inherit. + +Magit is documented in info node `(magit)'." + :group 'magit-modes + (buffer-disable-undo) + (setq truncate-lines t) + (setq buffer-read-only t) + (setq-local line-move-visual t) ; see #1771 + (setq show-trailing-whitespace nil) + (setq list-buffers-directory (abbreviate-file-name default-directory)) + (hack-dir-local-variables-non-file-buffer) + (make-local-variable 'text-property-default-nonsticky) + (push (cons 'keymap t) text-property-default-nonsticky) + (add-hook 'post-command-hook #'magit-section-update-highlight t t) + (add-hook 'deactivate-mark-hook #'magit-section-update-highlight t t) + (setq-local redisplay-highlight-region-function 'magit-highlight-region) + (setq-local redisplay-unhighlight-region-function 'magit-unhighlight-region) + (setq mode-line-process (magit-repository-local-get 'mode-line-process)) + (when (bound-and-true-p global-linum-mode) + (linum-mode -1)) + (when (and (fboundp 'nlinum-mode) + (bound-and-true-p global-nlinum-mode)) + (nlinum-mode -1)) + (when (and (fboundp 'display-line-numbers-mode) + (bound-and-true-p global-display-line-numbers-mode)) + (display-line-numbers-mode -1)) + (add-hook 'kill-buffer-hook 'magit-preserve-section-visibility-cache)) + +(defvar-local magit-region-overlays nil) + +(defun magit-delete-region-overlays () + (mapc #'delete-overlay magit-region-overlays) + (setq magit-region-overlays nil)) + +(defun magit-highlight-region (start end window rol) + (magit-delete-region-overlays) + (if (and (run-hook-with-args-until-success 'magit-region-highlight-hook + (magit-current-section)) + (not magit-keep-region-overlay) + (not (= (line-number-at-pos start) + (line-number-at-pos end))) + ;; (not (eq (car-safe last-command-event) 'mouse-movement)) + ) + (funcall (default-value 'redisplay-unhighlight-region-function) rol) + (funcall (default-value 'redisplay-highlight-region-function) + start end window rol))) + +(defun magit-unhighlight-region (rol) + (setq magit-section-highlighted-section nil) + (magit-delete-region-overlays) + (funcall (default-value 'redisplay-unhighlight-region-function) rol)) + +(defvar-local magit-refresh-args nil + "The arguments used to refresh the current buffer.") +(put 'magit-refresh-args 'permanent-local t) + +(defvar-local magit-previous-section nil) +(put 'magit-previous-section 'permanent-local t) + +(defun magit-mode-setup (mode &rest args) + "Setup up a MODE buffer using ARGS to generate its content." + (magit-mode-setup-internal mode args)) + +(defun magit-mode-setup-internal (mode args &optional locked) + "Setup up a MODE buffer using ARGS to generate its content. +When optional LOCKED is non-nil, then create a buffer that is +locked to its value, which is derived from MODE and ARGS." + (let* ((value (and locked (magit-buffer-lock-value mode args))) + (buffer (magit-mode-get-buffer mode nil nil value)) + (section (and buffer (magit-current-section))) + (created (not buffer))) + (unless buffer + (setq buffer (magit-with-toplevel + (magit-generate-new-buffer mode value)))) + (with-current-buffer buffer + (setq magit-previous-section section) + (setq magit-refresh-args args) + (funcall mode) + (when created + (magit-status-goto-initial-section) + (run-hooks 'magit-create-buffer-hook))) + (magit-display-buffer buffer) + (with-current-buffer buffer + (run-hooks 'magit-mode-setup-hook) + (magit-refresh-buffer)))) + +(defvar magit-display-buffer-noselect nil + "If non-nil, then `magit-display-buffer' doesn't call `select-window'.") + +(defun magit-display-buffer (buffer) + "Display BUFFER in some window and maybe select it. + +Display the buffer using `magit-display-buffer-function' and +then, unless `magit-display-buffer-noselect' is non-nil, select +the window which was used to display the buffer. + +Also run the hooks `magit-pre-display-buffer-hook' +and `magit-post-display-buffer-hook'." + (with-current-buffer buffer + (run-hooks 'magit-pre-display-buffer-hook)) + (let ((window (funcall magit-display-buffer-function buffer))) + (unless magit-display-buffer-noselect + (let* ((old-frame (selected-frame)) + (new-frame (window-frame window))) + (select-window window) + (unless (eq old-frame new-frame) + (select-frame-set-input-focus new-frame))))) + (with-current-buffer buffer + (run-hooks 'magit-post-display-buffer-hook))) + +(defun magit-display-buffer-traditional (buffer) + "Display BUFFER the way this has traditionally been done." + (display-buffer + buffer (if (and (derived-mode-p 'magit-mode) + (not (memq (with-current-buffer buffer major-mode) + '(magit-process-mode + magit-revision-mode + magit-diff-mode + magit-stash-mode + magit-status-mode)))) + '(display-buffer-same-window) + nil))) ; display in another window + +(defun magit-display-buffer-same-window-except-diff-v1 (buffer) + "Display BUFFER in the selected window except for some modes. +If a buffer's `major-mode' derives from `magit-diff-mode' or +`magit-process-mode', display it in another window. Display all +other buffers in the selected window." + (display-buffer + buffer (if (with-current-buffer buffer + (derived-mode-p 'magit-diff-mode 'magit-process-mode)) + nil ; display in another window + '(display-buffer-same-window)))) + +(defun magit--display-buffer-fullframe (buffer alist) + (when-let ((window (or (display-buffer-reuse-window buffer alist) + (display-buffer-same-window buffer alist) + (display-buffer-pop-up-window buffer alist) + (display-buffer-use-some-window buffer alist)))) + (delete-other-windows window) + window)) + +(defun magit-display-buffer-fullframe-status-v1 (buffer) + "Display BUFFER, filling entire frame if BUFFER is a status buffer. +Otherwise, behave like `magit-display-buffer-traditional'." + (if (eq (with-current-buffer buffer major-mode) + 'magit-status-mode) + (display-buffer buffer '(magit--display-buffer-fullframe)) + (magit-display-buffer-traditional buffer))) + +(defun magit--display-buffer-topleft (buffer alist) + (or (display-buffer-reuse-window buffer alist) + (when-let ((window2 (display-buffer-pop-up-window buffer alist))) + (let ((window1 (get-buffer-window)) + (buffer1 (current-buffer)) + (buffer2 (window-buffer window2)) + (w2-quit-restore (window-parameter window2 'quit-restore))) + (set-window-buffer window1 buffer2) + (set-window-buffer window2 buffer1) + (select-window window2) + ;; Swap some window state that `magit-mode-quit-window' and + ;; `quit-restore-window' inspect. + (set-window-prev-buffers window2 (cdr (window-prev-buffers window1))) + (set-window-prev-buffers window1 nil) + (set-window-parameter window2 'magit-dedicated + (window-parameter window1 'magit-dedicated)) + (set-window-parameter window1 'magit-dedicated t) + (set-window-parameter window1 'quit-restore + (list 'window 'window + (nth 2 w2-quit-restore) + (nth 3 w2-quit-restore))) + (set-window-parameter window2 'quit-restore nil) + window1)))) + +(defun magit-display-buffer-fullframe-status-topleft-v1 (buffer) + "Display BUFFER, filling entire frame if BUFFER is a status buffer. +When BUFFER derives from `magit-diff-mode' or +`magit-process-mode', try to display BUFFER to the top or left of +the current buffer rather than to the bottom or right, as +`magit-display-buffer-fullframe-status-v1' would. Whether the +split is made vertically or horizontally is determined by +`split-window-preferred-function'." + (display-buffer + buffer + (cond ((eq (with-current-buffer buffer major-mode) + 'magit-status-mode) + '(magit--display-buffer-fullframe)) + ((with-current-buffer buffer + (derived-mode-p 'magit-diff-mode 'magit-process-mode)) + '(magit--display-buffer-topleft)) + (t + '(display-buffer-same-window))))) + +(defun magit--display-buffer-fullcolumn (buffer alist) + (when-let ((window (or (display-buffer-reuse-window buffer alist) + (display-buffer-same-window buffer alist) + (display-buffer-below-selected buffer alist)))) + (delete-other-windows-vertically window) + window)) + +(defun magit-display-buffer-fullcolumn-most-v1 (buffer) + "Display BUFFER using the full column except in some cases. +For most cases where BUFFER's `major-mode' derives from +`magit-mode', display it in the selected window and grow that +window to the full height of the frame, deleting other windows in +that column as necessary. However, display BUFFER in another +window if 1) BUFFER's mode derives from `magit-process-mode', or +2) BUFFER's mode derives from `magit-diff-mode', provided that +the mode of the current buffer derives from `magit-log-mode' or +`magit-cherry-mode'." + (display-buffer + buffer + (cond ((and (or git-commit-mode + (derived-mode-p 'magit-log-mode 'magit-cherry-mode)) + (with-current-buffer buffer + (derived-mode-p 'magit-diff-mode))) + nil) + ((with-current-buffer buffer + (derived-mode-p 'magit-process-mode)) + nil) + (t + '(magit--display-buffer-fullcolumn))))) + +(defun magit-maybe-set-dedicated () + "Mark the selected window as dedicated if appropriate. + +If a new window was created to display the buffer, then remember +that fact. That information is used by `magit-mode-quit-window', +to determine whether the window should be deleted when its last +Magit buffer is buried." + (let ((window (get-buffer-window (current-buffer)))) + (when (and (window-live-p window) + (not (window-prev-buffers window))) + (set-window-parameter window 'magit-dedicated t)))) + +(defvar-local magit--default-directory nil + "Value of `default-directory' when buffer is generated. +This exists to prevent a let-bound `default-directory' from +tricking `magit-mode-get-buffer' or `magit-mode-get-buffers' into +thinking a buffer belongs to a repo that it doesn't.") +(put 'magit--default-directory 'permanent-local t) + +(defun magit-mode-get-buffers () + (let ((topdir (magit-toplevel))) + (--filter (with-current-buffer it + (and (derived-mode-p 'magit-mode) + (equal magit--default-directory topdir))) + (buffer-list)))) + +(defvar-local magit-buffer-locked-p nil) +(put 'magit-buffer-locked-p 'permanent-local t) + +(defun magit-mode-get-buffer (mode &optional create frame value) + (when create + (error "`magit-mode-get-buffer's CREATE argument is obsolete")) + (if-let ((topdir (magit-toplevel))) + (--first (with-current-buffer it + (and (eq major-mode mode) + (equal magit--default-directory topdir) + (if value + (and magit-buffer-locked-p + (equal (magit-buffer-lock-value) value)) + (not magit-buffer-locked-p)))) + (if frame + (mapcar #'window-buffer + (window-list (unless (eq frame t) frame))) + (buffer-list))) + (magit--not-inside-repository-error))) + +(defun magit-generate-new-buffer (mode &optional value) + (let* ((name (funcall magit-generate-buffer-name-function mode value)) + (buffer (generate-new-buffer name))) + (with-current-buffer buffer + (setq magit--default-directory default-directory) + (setq magit-buffer-locked-p (and value t)) + (magit-restore-section-visibility-cache mode)) + (when magit-uniquify-buffer-names + (add-to-list 'uniquify-list-buffers-directory-modes mode) + (with-current-buffer buffer + (setq list-buffers-directory (abbreviate-file-name default-directory))) + (let ((uniquify-buffer-name-style + (if (memq uniquify-buffer-name-style '(nil forward)) + 'post-forward-angle-brackets + uniquify-buffer-name-style))) + (uniquify-rationalize-file-buffer-names + name (file-name-directory (directory-file-name default-directory)) + buffer))) + buffer)) + +(defun magit-generate-buffer-name-default-function (mode &optional value) + "Generate buffer name for a MODE buffer in the current repository. +The returned name is based on `magit-buffer-name-format' and +takes `magit-uniquify-buffer-names' and VALUE, if non-nil, into +account." + (let ((m (substring (symbol-name mode) 0 -5)) + (v (and value (format "%s" (if (listp value) value (list value))))) + (n (if magit-uniquify-buffer-names + (file-name-nondirectory + (directory-file-name default-directory)) + (abbreviate-file-name default-directory)))) + (format-spec + magit-buffer-name-format + `((?m . ,m) + (?M . ,(if (eq mode 'magit-status-mode) "magit" m)) + (?v . ,(or v "")) + (?V . ,(if v (concat " " v) "")) + (?t . ,n) + (?x . ,(if magit-uniquify-buffer-names "" "*")) + (?T . ,(if magit-uniquify-buffer-names n (concat n "*"))))))) + +(defun magit-toggle-buffer-lock () + "Lock the current buffer to its value or unlock it. + +Locking a buffer to its value prevents it from being reused to +display another value. The name of a locked buffer contains its +value, which allows telling it apart from other locked buffers +and the unlocked buffer. + +Not all Magit buffers can be locked to their values, for example +it wouldn't make sense to lock a status buffer. + +There can only be a single unlocked buffer using a certain +major-mode per repository. So when a buffer is being unlocked +and another unlocked buffer already exists for that mode and +repository, then the former buffer is instead deleted and the +latter is displayed in its place." + (interactive) + (if magit-buffer-locked-p + (if-let ((unlocked (magit-mode-get-buffer major-mode))) + (let ((locked (current-buffer))) + (switch-to-buffer unlocked nil t) + (kill-buffer locked)) + (setq magit-buffer-locked-p nil) + (rename-buffer (funcall magit-generate-buffer-name-function + major-mode))) + (if-let ((value (magit-buffer-lock-value))) + (if-let ((locked (magit-mode-get-buffer major-mode nil nil value))) + (let ((unlocked (current-buffer))) + (switch-to-buffer locked nil t) + (kill-buffer unlocked)) + (setq magit-buffer-locked-p t) + (rename-buffer (funcall magit-generate-buffer-name-function + major-mode value))) + (user-error "Buffer has no value it could be locked to")))) + +(defvar magit-buffer-lock-functions '((forge-topic-mode . car)) + "Provide buffer-locking support for third-party modes. +An alist of symbols to functions. + +The symbol must be the major-mode the locked buffer will have. + +The function must take a single argument, a list of refresh +arguments (the value of `magit-refresh-args') and return a +value that identifies the buffer (i.e., its 'lock value'). +If the third-party mode is invoked as + + (magit-mode-setup-internal #\\='my-mode \\='(1 2 3) t) + +the function will be invoked as + + (funcall lock-func \\='(1 2 3)) + +if the cons (my-mode . lock-func) is in this list. + +This variable is intended for third-party extensions; +`magit-buffer-lock-value' implements all built-in behavior. + +See also `magit-toggle-buffer-lock'.") + +(cl-defun magit-buffer-lock-value + (&optional (mode major-mode) + (args magit-refresh-args)) + "Find an appropriate buffer lock value for MODE under ARGS. +See also `magit-buffer-lock-functions'." + (cl-case mode + (magit-cherry-mode + (pcase-let ((`(,upstream ,head) args)) + (concat head ".." upstream))) + (magit-diff-mode + (pcase-let ((`(,rev-or-range ,const ,_args ,files) args)) + (nconc (cons (or rev-or-range + (if (member "--cached" const) + (progn (setq const (delete "--cached" const)) + 'staged) + 'unstaged)) + const) + (and files (cons "--" files))))) + (magit-log-mode + (pcase-let ((`(,revs ,_args ,files) args)) + (if (and revs files) + (append revs (cons "--" files)) + (append revs files)))) + (magit-refs-mode + (pcase-let ((`(,ref ,args) args)) + (cons (or ref "HEAD") args))) + (magit-revision-mode + (pcase-let ((`(,rev ,_const ,_args ,files) args)) + (if files (cons rev files) (list rev)))) + ((magit-reflog-mode ; (ref ~args) + magit-stash-mode ; (stash _const _args _files) + magit-stashes-mode) ; (ref) + (car args)) + (t + (--when-let (cdr (assq mode magit-buffer-lock-functions)) + (funcall it args))))) + +(defun magit-mode-bury-buffer (&optional kill-buffer) + "Bury the current buffer. +With a prefix argument, kill the buffer instead. +This is done using `magit-bury-buffer-function'." + (interactive "P") + (funcall magit-bury-buffer-function kill-buffer)) + +(defun magit-mode-quit-window (kill-buffer) + "Quit the selected window and bury its buffer. + +This behaves similar to `quit-window', but when the window +was originally created to display a Magit buffer and the +current buffer is the last remaining Magit buffer that was +ever displayed in the selected window, then delete that +window." + (if (or (one-window-p) + (--first (let ((buffer (car it))) + (and (not (eq buffer (current-buffer))) + (buffer-live-p buffer) + (or (not (window-parameter nil 'magit-dedicated)) + (with-current-buffer buffer + (derived-mode-p 'magit-mode + 'magit-process-mode))))) + (window-prev-buffers))) + (quit-window kill-buffer) + (let ((window (selected-window))) + (quit-window kill-buffer) + (when (window-live-p window) + (delete-window window))))) + +;;; Refresh Magit Buffers + +(defvar inhibit-magit-refresh nil) + +(defun magit-refresh () + "Refresh some buffers belonging to the current repository. + +Refresh the current buffer if its major mode derives from +`magit-mode', and refresh the corresponding status buffer. + +Run hooks `magit-pre-refresh-hook' and `magit-post-refresh-hook'." + (interactive) + (unless inhibit-magit-refresh + (unwind-protect + (let ((start (current-time)) + (magit--refresh-cache (or magit--refresh-cache + (list (cons 0 0))))) + (when magit-refresh-verbose + (message "Refreshing magit...")) + (magit-run-hook-with-benchmark 'magit-pre-refresh-hook) + (when (derived-mode-p 'magit-mode) + (magit-refresh-buffer)) + (--when-let (and magit-refresh-status-buffer + (not (derived-mode-p 'magit-status-mode)) + (magit-mode-get-buffer 'magit-status-mode)) + (with-current-buffer it + (magit-refresh-buffer))) + (magit-auto-revert-buffers) + (cond + ((and (not this-command) + (memq last-command magit-post-commit-hook-commands)) + (magit-run-hook-with-benchmark 'magit-post-commit-hook)) + ((memq this-command magit-post-stage-hook-commands) + (magit-run-hook-with-benchmark 'magit-post-stage-hook)) + ((memq this-command magit-post-unstage-hook-commands) + (magit-run-hook-with-benchmark 'magit-post-unstage-hook))) + (magit-run-hook-with-benchmark 'magit-post-refresh-hook) + (when magit-refresh-verbose + (message "Refreshing magit...done (%.3fs, cached %s/%s)" + (float-time (time-subtract (current-time) start)) + (caar magit--refresh-cache) + (+ (caar magit--refresh-cache) + (cdar magit--refresh-cache))))) + (run-hooks 'magit-unwind-refresh-hook)))) + +(defun magit-refresh-all () + "Refresh all buffers belonging to the current repository. + +Refresh all Magit buffers belonging to the current repository, +and revert buffers that visit files located inside the current +repository. + +Run hooks `magit-pre-refresh-hook' and `magit-post-refresh-hook'." + (interactive) + (magit-run-hook-with-benchmark 'magit-pre-refresh-hook) + (dolist (buffer (magit-mode-get-buffers)) + (with-current-buffer buffer (magit-refresh-buffer))) + (magit-auto-revert-buffers) + (magit-run-hook-with-benchmark 'magit-post-refresh-hook)) + +(defvar-local magit-refresh-start-time nil) + +(defun magit-refresh-buffer () + "Refresh the current Magit buffer." + (setq magit-refresh-start-time (current-time)) + (let ((refresh (intern (format "%s-refresh-buffer" + (substring (symbol-name major-mode) 0 -5)))) + (magit--refresh-cache (or magit--refresh-cache (list (cons 0 0))))) + (when (functionp refresh) + (when magit-refresh-verbose + (message "Refreshing buffer `%s'..." (buffer-name))) + (let* ((buffer (current-buffer)) + (windows + (--mapcat (with-selected-window it + (with-current-buffer buffer + (when-let ((section (magit-current-section))) + (list + (nconc (list it section) + (magit-refresh-get-relative-position)))))) + (or (get-buffer-window-list buffer nil t) + (list (selected-window)))))) + (deactivate-mark) + (setq magit-section-highlight-overlays nil) + (setq magit-section-highlighted-section nil) + (setq magit-section-highlighted-sections nil) + (setq magit-section-unhighlight-sections nil) + (magit-process-unset-mode-line-error-status) + (let ((inhibit-read-only t)) + (erase-buffer) + (save-excursion + (apply refresh magit-refresh-args))) + (dolist (window windows) + (with-selected-window (car window) + (with-current-buffer buffer + (apply #'magit-section-goto-successor (cdr window))))) + (run-hooks 'magit-refresh-buffer-hook) + (magit-section-update-highlight) + (set-buffer-modified-p nil)) + (when magit-refresh-verbose + (message "Refreshing buffer `%s'...done (%.3fs)" (buffer-name) + (float-time (time-subtract (current-time) + magit-refresh-start-time))))))) + +(defun magit-refresh-get-relative-position () + (when-let ((section (magit-current-section))) + (let ((start (oref section start))) + (list (count-lines start (point)) + (- (point) (line-beginning-position)) + (and (magit-hunk-section-p section) + (region-active-p) + (progn (goto-char (line-beginning-position)) + (when (looking-at "^[-+]") (forward-line)) + (while (looking-at "^[ @]") (forward-line)) + (let ((beg (point))) + (cond ((looking-at "^[-+]") + (forward-line) + (while (looking-at "^[-+]") (forward-line)) + (while (looking-at "^ ") (forward-line)) + (forward-line -1) + (regexp-quote (buffer-substring-no-properties + beg (line-end-position)))) + (t t))))))))) + +;;; Save File-Visiting Buffers + +(defvar disable-magit-save-buffers nil) + +(defun magit-pre-command-hook () + (setq disable-magit-save-buffers nil)) +(add-hook 'pre-command-hook #'magit-pre-command-hook) + +(defvar magit-after-save-refresh-buffers nil) + +(defun magit-after-save-refresh-buffers () + (dolist (buffer magit-after-save-refresh-buffers) + (when (buffer-live-p buffer) + (with-current-buffer buffer + (magit-refresh-buffer)))) + (setq magit-after-save-refresh-buffers nil) + (remove-hook 'post-command-hook 'magit-after-save-refresh-buffers)) + +(defun magit-after-save-refresh-status () + "Refresh the status buffer of the current repository. + +This function is intended to be added to `after-save-hook'. + +If the status buffer does not exist or the file being visited in +the current buffer isn't inside the working tree of a repository, +then do nothing. + +Note that refreshing a Magit buffer is done by re-creating its +contents from scratch, which can be slow in large repositories. +If you are not satisfied with Magit's performance, then you +should obviously not add this function to that hook." + (when (and (not disable-magit-save-buffers) + (magit-inside-worktree-p t)) + (--when-let (ignore-errors (magit-mode-get-buffer 'magit-status-mode)) + (add-to-list 'magit-after-save-refresh-buffers it) + (add-hook 'post-command-hook 'magit-after-save-refresh-buffers)))) + +(defun magit-maybe-save-repository-buffers () + "Maybe save file-visiting buffers belonging to the current repository. +Do so if `magit-save-repository-buffers' is non-nil. You should +not remove this from any hooks, instead set that variable to nil +if you so desire." + (when (and magit-save-repository-buffers + (not disable-magit-save-buffers)) + (setq disable-magit-save-buffers t) + (let ((msg (current-message))) + (magit-save-repository-buffers + (eq magit-save-repository-buffers 'dontask)) + (when (and msg + (current-message) + (not (equal msg (current-message)))) + (message "%s" msg))))) + +(add-hook 'magit-pre-refresh-hook #'magit-maybe-save-repository-buffers) +(add-hook 'magit-pre-call-git-hook #'magit-maybe-save-repository-buffers) +(add-hook 'magit-pre-start-git-hook #'magit-maybe-save-repository-buffers) + +(defvar-local magit-inhibit-refresh-save nil) + +(defun magit-save-repository-buffers (&optional arg) + "Save file-visiting buffers belonging to the current repository. +After any buffer where `buffer-save-without-query' is non-nil +is saved without asking, the user is asked about each modified +buffer which visits a file in the current repository. Optional +argument (the prefix) non-nil means save all with no questions." + (interactive "P") + (when-let ((topdir (magit-rev-parse-safe "--show-toplevel"))) + (let ((remote (file-remote-p topdir)) + (save-some-buffers-action-alist + `((?Y (lambda (buffer) + (with-current-buffer buffer + (setq buffer-save-without-query t) + (save-buffer))) + "to save the current buffer and remember choice") + (?N (lambda (buffer) + (with-current-buffer buffer + (setq magit-inhibit-refresh-save t))) + "to skip the current buffer and remember choice") + ,@save-some-buffers-action-alist))) + (save-some-buffers + arg (lambda () + (and (not magit-inhibit-refresh-save) + buffer-file-name + (file-exists-p (file-name-directory buffer-file-name)) + ;; Avoid needlessly connecting to unrelated remotes. + (equal (file-remote-p buffer-file-name) + remote) + (string-prefix-p topdir (file-truename buffer-file-name)) + (equal (magit-rev-parse-safe "--show-toplevel") + topdir))))))) + +;;; Restore Window Configuration + +(defvar magit-inhibit-save-previous-winconf nil) + +(defvar-local magit-previous-window-configuration nil) +(put 'magit-previous-window-configuration 'permanent-local t) + +(defun magit-save-window-configuration () + "Save the current window configuration. + +Later, when the buffer is buried, it may be restored by +`magit-restore-window-configuration'." + (if magit-inhibit-save-previous-winconf + (when (eq magit-inhibit-save-previous-winconf 'unset) + (setq magit-previous-window-configuration nil)) + (unless (get-buffer-window (current-buffer) (selected-frame)) + (setq magit-previous-window-configuration + (current-window-configuration))))) + +(defun magit-restore-window-configuration (&optional kill-buffer) + "Bury or kill the current buffer and restore previous window configuration." + (let ((winconf magit-previous-window-configuration) + (buffer (current-buffer)) + (frame (selected-frame))) + (quit-window kill-buffer (selected-window)) + (when (and winconf (equal frame (window-configuration-frame winconf))) + (set-window-configuration winconf) + (when (buffer-live-p buffer) + (with-current-buffer buffer + (setq magit-previous-window-configuration nil)))))) + +;;; Buffer History + +(defun magit-go-backward () + "Move backward in current buffer's history." + (interactive) + (if help-xref-stack + (help-xref-go-back (current-buffer)) + (user-error "No previous entry in buffer's history"))) + +(defun magit-go-forward () + "Move forward in current buffer's history." + (interactive) + (if help-xref-forward-stack + (help-xref-go-forward (current-buffer)) + (user-error "No next entry in buffer's history"))) + +(defun magit-insert-xref-buttons (&optional _) + "Insert xref buttons." + (when (or help-xref-stack help-xref-forward-stack) + (when help-xref-stack + (magit-xref-insert-button help-back-label 'magit-xref-backward)) + (when help-xref-forward-stack + (when help-xref-stack + (insert " ")) + (magit-xref-insert-button help-forward-label 'magit-xref-forward)))) + +(defun magit-xref-insert-button (label type) + (magit-insert-section (button label) + (insert-text-button label 'type type + 'help-args (list (current-buffer))))) + +(define-button-type 'magit-xref-backward + :supertype 'help-back + 'mouse-face 'magit-section-highlight + 'help-echo (purecopy "mouse-2, RET: go back to previous history entry")) + +(define-button-type 'magit-xref-forward + :supertype 'help-forward + 'mouse-face 'magit-section-highlight + 'help-echo (purecopy "mouse-2, RET: go back to next history entry")) + +(defun magit-xref-setup () + "Insert backward/forward buttons if the major-mode supports it. +Currently `magit-log-mode', `magit-reflog-mode', +`magit-diff-mode', and `magit-revision-mode' support it" + (when (memq major-mode '(magit-log-mode + magit-reflog-mode + magit-diff-mode + magit-revision-mode)) + (when help-xref-stack-item + (push (cons (point) help-xref-stack-item) help-xref-stack) + (setq help-xref-forward-stack nil)) + (when (called-interactively-p 'interactive) + (--when-let (nthcdr 10 help-xref-stack) + (setcdr it nil))) + (setq help-xref-stack-item + `(magit-xref-restore ,default-directory ,@magit-refresh-args)))) + +(defun magit-xref-restore (&rest args) + (magit-xref-setup) + (setq default-directory (car args)) + (setq magit-refresh-args (cdr args)) + (magit-refresh-buffer)) + +;;; Repository-Local Cache + +(defvar magit-repository-local-cache nil + "Alist mapping `magit-toplevel' paths to alists of key/value pairs.") + +(defun magit-repository-local-repository () + "Return the key for the current repository." + (or (bound-and-true-p magit--default-directory) + (magit-toplevel))) + +(defun magit-repository-local-set (key value &optional repository) + "Set the repository-local VALUE for KEY. + +Unless specified, REPOSITORY is the current buffer's repository. + +If REPOSITORY is nil (meaning there is no current repository), +then the value is not cached, and we return nil." + (let* ((repokey (or repository (magit-repository-local-repository))) + (cache (assoc repokey magit-repository-local-cache))) + ;; Don't cache values for a nil REPOSITORY, as the 'set' and 'get' + ;; calls for some KEY may happen in unrelated contexts. + (when repokey + (if cache + (let ((keyvalue (assoc key (cdr cache)))) + (if keyvalue + ;; Update pre-existing value for key. + (setcdr keyvalue value) + ;; No such key in repository-local cache. + (push (cons key value) (cdr cache)))) + ;; No cache for this repository. + (push (cons repokey (list (cons key value))) + magit-repository-local-cache))))) + +(defun magit-repository-local-exists-p (key &optional repository) + "Non-nil when a repository-local value exists for KEY. + +Returns a (KEY . value) cons cell. + +The KEY is matched using `equal'. + +Unless specified, REPOSITORY is the current buffer's repository." + (let* ((repokey (or repository (magit-repository-local-repository))) + (cache (assoc repokey magit-repository-local-cache))) + (and cache + (assoc key (cdr cache))))) + +(defun magit-repository-local-get (key &optional default repository) + "Return the repository-local value for KEY. + +Return DEFAULT if no value for KEY exists. + +The KEY is matched using `equal'. + +Unless specified, REPOSITORY is the current buffer's repository." + (let ((keyvalue (magit-repository-local-exists-p key repository))) + (if keyvalue + (cdr keyvalue) + default))) + +(defun magit-repository-local-delete (key &optional repository) + "Delete the repository-local value for KEY. + +Unless specified, REPOSITORY is the current buffer's repository." + (let* ((repokey (or repository (magit-repository-local-repository))) + (cache (assoc repokey magit-repository-local-cache))) + (when cache + ;; There is no `assoc-delete-all'. + (setf (cdr cache) + (cl-delete key (cdr cache) :key #'car :test #'equal))))) + +(defun magit-zap-caches () + "Zap caches for the current repository. +Remove the repository's entry from `magit-repository-local-cache' +and set `magit-section-visibility-cache' to nil in all of the +repository's Magit buffers." + (interactive) + (magit-with-toplevel + (setq magit-repository-local-cache + (cl-delete default-directory + magit-repository-local-cache + :key #'car :test #'equal))) + (dolist (buffer (magit-mode-get-buffers)) + (with-current-buffer buffer + (setq magit-section-visibility-cache nil)))) + +;;; Utilities + +(defun magit-run-hook-with-benchmark (hook) + (when hook + (if magit-refresh-verbose + (let ((start (current-time))) + (message "Running %s..." hook) + (run-hooks hook) + (message "Running %s...done (%.3fs)" hook + (float-time (time-subtract (current-time) start)))) + (run-hooks hook)))) + +;;; _ +(provide 'magit-mode) +;;; magit-mode.el ends here diff --git a/elpa/magit-20181113.1837/magit-notes.el b/elpa/magit-20181113.1837/magit-notes.el new file mode 100644 index 00000000..e4806a23 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-notes.el @@ -0,0 +1,202 @@ +;;; magit-notes.el --- notes support -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements support for `git-notes'. + +;;; Code: + +(require 'magit) + +;;; Popup + +;;;###autoload (autoload 'magit-notes-popup "magit" nil t) +(magit-define-popup magit-notes-popup + "Popup console for notes commands." + :man-page "git-notes" + :variables '("Configure local settings" + (?c "core.notesRef" + magit-set-core.notesRef + magit-format-core.notesRef) + (?d "notes.displayRef" + magit-set-notes.displayRef + magit-format-notes.displayRef) + "Configure global settings" + (?C "core.notesRef" + magit-set-global-core.notesRef + magit-format-global-core.notesRef) + (?D "notes.displayRef" + magit-set-global-notes.displayRef + magit-format-global-notes.displayRef)) + :switches '("Switch for prune" + (?n "Dry run" "--dry-run")) + :options '("Option for edit and remove" + (?r "Manipulate ref" "--ref=" magit-notes-popup-read-ref) + "Option for merge" + (?s "Merge strategy" "--strategy=")) + :actions '((?T "Edit" magit-notes-edit) + (?r "Remove" magit-notes-remove) + (?m "Merge" magit-notes-merge) + (?p "Prune" magit-notes-prune)) + :sequence-actions '((?c "Commit merge" magit-notes-merge-commit) + (?a "Abort merge" magit-notes-merge-abort)) + :sequence-predicate 'magit-notes-merging-p + :default-action 'magit-notes-edit) + +(defun magit-notes-merging-p () + (let ((dir (magit-git-dir "NOTES_MERGE_WORKTREE"))) + (and (file-directory-p dir) + (directory-files dir nil "^[^.]")))) + +(defun magit-format-core.notesRef () + (magit--format-popup-variable:value "core.notesRef" 22)) + +(defun magit-format-notes.displayRef () + (magit--format-popup-variable:values "notes.displayRef" 22)) + +(defun magit-format-global-core.notesRef () + (magit--format-popup-variable:value "core.notesRef" 22 t)) + +(defun magit-format-global-notes.displayRef () + (magit--format-popup-variable:values "notes.displayRef" 22 t)) + +;;; Commands + +(defun magit-notes-edit (commit &optional ref) + "Edit the note attached to COMMIT. +REF is the notes ref used to store the notes. + +Interactively or when optional REF is nil use the value of Git +variable `core.notesRef' or \"refs/notes/commits\" if that is +undefined." + (interactive (magit-notes-read-args "Edit notes")) + (magit-run-git-with-editor "notes" (and ref (concat "--ref=" ref)) + "edit" commit)) + +(defun magit-notes-remove (commit &optional ref) + "Remove the note attached to COMMIT. +REF is the notes ref from which the note is removed. + +Interactively or when optional REF is nil use the value of Git +variable `core.notesRef' or \"refs/notes/commits\" if that is +undefined." + (interactive (magit-notes-read-args "Remove notes")) + (magit-run-git-with-editor "notes" (and ref (concat "--ref=" ref)) + "remove" commit)) + +(defun magit-notes-merge (ref) + "Merge the notes ref REF into the current notes ref. + +The current notes ref is the value of Git variable +`core.notesRef' or \"refs/notes/commits\" if that is undefined. + +When there are conflicts, then they have to be resolved in the +temporary worktree \".git/NOTES_MERGE_WORKTREE\". When +done use `magit-notes-merge-commit' to finish. To abort +use `magit-notes-merge-abort'." + (interactive (list (magit-read-string-ns "Merge reference"))) + (magit-run-git-with-editor "notes" "merge" ref)) + +(defun magit-notes-merge-commit () + "Commit the current notes ref merge. +Also see `magit-notes-merge'." + (interactive) + (magit-run-git-with-editor "notes" "merge" "--commit")) + +(defun magit-notes-merge-abort () + "Abort the current notes ref merge. +Also see `magit-notes-merge'." + (interactive) + (magit-run-git-with-editor "notes" "merge" "--abort")) + +(defun magit-notes-prune (&optional dry-run) + "Remove notes about unreachable commits." + (interactive (list (and (member "--dry-run" (magit-notes-arguments)) t))) + (when dry-run + (magit-process-buffer)) + (magit-run-git-with-editor "notes" "prune" (and dry-run "--dry-run"))) + +(defun magit-set-core.notesRef (ref) + "Set the local value of `core.notesRef' to REF." + (interactive (list (magit-notes-read-ref "Set local core.notesRef"))) + (magit-set ref "core.notesRef") + (magit-with-pre-popup-buffer + (magit-refresh))) + +(defun magit-set-global-core.notesRef (ref) + "Set the global value of `core.notesRef' to REF." + (interactive (list (magit-notes-read-ref "Set global core.notesRef"))) + (magit-set ref "--global" "core.notesRef") + (magit-with-pre-popup-buffer + (magit-refresh))) + +(defun magit-set-notes.displayRef (refs) + "Set the local values of `notes.displayRef' to REFS." + (interactive (list (magit-notes-read-refs "Set local notes.displayRef"))) + (magit-set-all refs "notes.displayRef") + (magit-with-pre-popup-buffer + (magit-refresh))) + +(defun magit-set-global-notes.displayRef (refs) + "Set the global values of `notes.displayRef' to REFS." + (interactive (list (magit-notes-read-refs "Set global notes.displayRef"))) + (magit-set-all refs "--global" "notes.displayRef") + (magit-with-pre-popup-buffer + (magit-refresh))) + +(defun magit-notes-read-ref (prompt) + (--when-let (magit-completing-read + prompt (magit-list-notes-refnames) nil nil + (--when-let (magit-get "core.notesRef") + (if (string-prefix-p "refs/notes/" it) + (substring it 11) + it))) + (if (string-prefix-p "refs/" it) + it + (concat "refs/notes/" it)))) + +(defun magit-notes-read-refs (prompt) + (mapcar (lambda (ref) + (if (string-prefix-p "refs/" ref) + ref + (concat "refs/notes/" ref))) + (completing-read-multiple + (concat prompt ": ") + (magit-list-notes-refnames) nil nil + (mapconcat (lambda (ref) + (if (string-prefix-p "refs/notes/" ref) + (substring ref 11) + ref)) + (magit-get-all "notes.displayRef") + ",")))) + +(defun magit-notes-read-args (prompt) + (list (magit-read-branch-or-commit prompt (magit-stash-at-point)) + (--when-let (--first (string-match "^--ref=\\(.+\\)" it) + (magit-notes-arguments)) + (match-string 1 it)))) + +;;; _ +(provide 'magit-notes) +;;; magit-notes.el ends here diff --git a/elpa/magit-20181113.1837/magit-obsolete.el b/elpa/magit-20181113.1837/magit-obsolete.el new file mode 100644 index 00000000..67a3d1ce --- /dev/null +++ b/elpa/magit-20181113.1837/magit-obsolete.el @@ -0,0 +1,55 @@ +;;; magit-obsolete.el --- obsolete definitions -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library defines aliases for obsolete variables and functions. + +;;; Code: + +(require 'magit) + +;;; Obsolete since v2.90.0 + +(define-obsolete-function-alias 'magit-reset-head 'magit-reset-mixed "Magit 2.90.0") +(define-obsolete-function-alias 'magit-gitignore 'magit-gitignore-globally "Magit 2.90.0") +(define-obsolete-function-alias 'magit-branch 'magit-branch-create "Magit 2.90.0") +(define-obsolete-function-alias 'magit-tag 'magit-tag-create "Magit 2.90.0") +(define-obsolete-function-alias 'magit-fetch 'magit-fetch-other "Magit 2.90.0") +(define-obsolete-function-alias 'magit-pull 'magit-pull-branch "Magit 2.90.0") +(define-obsolete-function-alias 'magit-rebase 'magit-rebase-branch "Magit 2.90.0") +(define-obsolete-function-alias 'magit-blame 'magit-blame-addition "Magit 2.90.0") +(define-obsolete-function-alias 'magit-revert 'magit-revert-and-commit "Magit 2.90.0") +(define-obsolete-function-alias 'magit-reset 'magit-reset-quickly "Magit 2.90.0") +(define-obsolete-function-alias 'magit-merge 'magit-merge-plain "Magit 2.90.0") +(define-obsolete-function-alias 'magit-stash 'magit-stash-both "Magit 2.90.0") +(define-obsolete-function-alias 'magit-snapshot 'magit-snapshot-both "Magit 2.90.0") +(define-obsolete-function-alias 'magit-push 'magit-push-other "Magit 2.90.0") +(define-obsolete-function-alias 'magit-commit 'magit-commit-create "Magit 2.90.0") +(define-obsolete-function-alias 'magit-log 'magit-log-other "Magit 2.90.0") +(define-obsolete-function-alias 'magit-reflog 'magit-reflog-other "Magit 2.90.0") +(define-obsolete-function-alias 'magit-diff 'magit-diff-range "Magit 2.90.0") + +;;; _ +(provide 'magit-obsolete) +;;; magit-obsolete.el ends here diff --git a/elpa/magit-20181113.1837/magit-patch.el b/elpa/magit-20181113.1837/magit-patch.el new file mode 100644 index 00000000..e42b44a6 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-patch.el @@ -0,0 +1,188 @@ +;;; magit-patch.el --- creating and applying patches -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements patch commands. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +;;; Options + +(defcustom magit-patch-save-arguments '(exclude "--stat") + "Arguments used by `magit-patch-save-arguments' (which see)" + :package-version '(magit . "2.12.0") + :group 'magit-diff + :type '(choice (const :tag "use buffer arguments" buffer) + (cons :tag "use buffer arguments except" + (const :format "" exclude) + (repeat :format "%v%i\n" + (string :tag "Argument"))) + (repeat :tag "use constant arguments" + (string :tag "Argument")))) + +;;; Commands + +;;;###autoload (autoload 'magit-patch-popup "magit-patch" nil t) +(magit-define-popup magit-patch-popup + "Popup console for patch commands." + :man-page "git-format-patch" + :switches '("Switches for formatting patches" + (?l "Add cover letter" "--cover-letter")) + :options '("Options for formatting patches" + (?f "From" "--from=") + (?t "To" "--to=") + (?c "CC" "--cc=") + (?r "In reply to" "--in-reply-to=") + (?P "Subject Prefix" "--subject-prefix=") + (?v "Reroll count" "--reroll-count=") + (?s "Thread style" "--thread=") + (?U "Context lines" "-U") + (?M "Detect renames" "-M") + (?C "Detect copies" "-C") + (?A "Diff algorithm" "--diff-algorithm=" + magit-diff-select-algorithm) + (?o "Output directory" "--output-directory=") + (?F "Limit to files" "-- " magit-read-files)) + :actions '((?p "Format patches" magit-format-patch) + (?r "Request pull" magit-request-pull)) + :default-action 'magit-format-patch) + +;;;###autoload +(defun magit-format-patch (range args files) + "Create patches for the commits in RANGE. +When a single commit is given for RANGE, create a patch for the +changes introduced by that commit (unlike 'git format-patch' +which creates patches for all commits that are reachable from +`HEAD' but not from the specified commit)." + (interactive + (cons (if-let ((revs (magit-region-values 'commit t))) + (concat (car (last revs)) "^.." (car revs)) + (let ((range (magit-read-range-or-commit + "Format range or commit"))) + (if (string-match-p "\\.\\." range) + range + (format "%s~..%s" range range)))) + (magit-popup-export-file-args (magit-patch-arguments)))) + (magit-run-git "format-patch" range args "--" files) + (when (member "--cover-letter" args) + (find-file + (expand-file-name + "0000-cover-letter.patch" + (let ((topdir (magit-toplevel))) + (or (--some (and (string-match "--output-directory=\\(.+\\)" it) + (expand-file-name (match-string 1 it) topdir)) + args) + topdir)))))) + +;;;###autoload +(defun magit-request-pull (url start end) + "Request upstream to pull from you public repository. + +URL is the url of your publically accessible repository. +START is a commit that already is in the upstream repository. +END is the last commit, usually a branch name, which upstream +is asked to pull. START has to be reachable from that commit." + (interactive + (list (magit-get "remote" (magit-read-remote "Remote") "url") + (magit-read-branch-or-commit "Start" (magit-get-upstream-branch)) + (magit-read-branch-or-commit "End"))) + (let ((dir default-directory)) + ;; mu4e changes default-directory + (compose-mail) + (setq default-directory dir)) + (message-goto-body) + (magit-git-insert "request-pull" start url end) + (set-buffer-modified-p nil)) + +;;;###autoload (autoload 'magit-patch-apply-popup "magit-patch" nil t) +(magit-define-popup magit-patch-apply-popup + "Popup console for applying a patch file." + :man-page "git-apply" + :switches '((?i "Also apply to index" "--index") + (?c "Only apply to index" "--cached") + (?3 "Fall back on 3way merge" "--3way")) + :actions '((?a "Apply patch" magit-patch-apply)) + :default-action 'magit-patch-apply) + +;;;###autoload +(defun magit-patch-apply (file &rest args) + "Apply the patch file FILE." + (interactive (list (expand-file-name + (read-file-name "Apply patch: " + default-directory nil nil + (--when-let (magit-file-at-point) + (file-relative-name it)))) + (magit-patch-apply-arguments))) + (magit-run-git "apply" args "--" (magit-convert-filename-for-git file))) + +;;;###autoload +(defun magit-patch-save (file &optional arg) + "Write current diff into patch FILE. + +What arguments are used to create the patch depends on the value +of `magit-patch-save-arguments' and whether a prefix argument is +used. + +If the value is the symbol `buffer', then use the same arguments +as the buffer. With a prefix argument use no arguments. + +If the value is a list beginning with the symbol `exclude', then +use the same arguments as the buffer except for those matched by +entries in the cdr of the list. The comparison is done using +`string-prefix-p'. With a prefix argument use the same arguments +as the buffer. + +If the value is a list of strings (including the empty list), +then use those arguments. With a prefix argument use the same +arguments as the buffer. + +Of course the arguments that are required to actually show the +same differences as those shown in the buffer are always used." + (interactive (list (read-file-name "Write patch file: " default-directory) + current-prefix-arg)) + (unless (derived-mode-p 'magit-diff-mode) + (user-error "Only diff buffers can be saved as patches")) + (pcase-let ((`(,rev ,const ,args ,files) magit-refresh-args)) + (when (derived-mode-p 'magit-revision-mode) + (setq rev (format "%s~..%s" rev rev))) + (cond ((eq magit-patch-save-arguments 'buffer) + (when arg + (setq args nil))) + ((eq (car-safe magit-patch-save-arguments) 'exclude) + (unless arg + (setq args (-difference args (cdr magit-patch-save-arguments))))) + ((not arg) + (setq args magit-patch-save-arguments))) + (with-temp-file file + (magit-git-insert "diff" rev "-p" const args "--" files))) + (magit-refresh)) + +;;; _ +(provide 'magit-patch) +;;; magit-patch.el ends here diff --git a/elpa/magit-20181113.1837/magit-pkg.el b/elpa/magit-20181113.1837/magit-pkg.el new file mode 100644 index 00000000..34a4b60c --- /dev/null +++ b/elpa/magit-20181113.1837/magit-pkg.el @@ -0,0 +1,11 @@ +(define-package "magit" "20181113.1837" "A Git porcelain inside Emacs." + '((emacs "25.1") + (async "20180527") + (dash "20180910") + (ghub "20181107") + (git-commit "20181104") + (magit-popup "20181003") + (with-editor "20181103"))) +;; Local Variables: +;; no-byte-compile: t +;; End: diff --git a/elpa/magit-20181113.1837/magit-process.el b/elpa/magit-20181113.1837/magit-process.el new file mode 100644 index 00000000..6378ffc1 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-process.el @@ -0,0 +1,1122 @@ +;;; magit-process.el --- process functionality -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements the tools used to run Git for side-effects. + +;; Note that the functions used to run Git and then consume its +;; output, are defined in `magit-git.el'. There's a bit of overlap +;; though. + +;;; Code: + +(require 'ansi-color) +(require 'cl-lib) +(require 'dash) + +(eval-when-compile + (require 'subr-x)) + +(require 'with-editor) +(require 'magit-utils) +(require 'magit-section) +(require 'magit-git) +(require 'magit-mode) + +(declare-function auth-source-search "auth-source" + (&rest spec &key max require create delete &allow-other-keys)) + +;;; Options + +(defcustom magit-process-connection-type (not (eq system-type 'cygwin)) + "Connection type used for the Git process. + +If nil, use pipes: this is usually more efficient, and works on Cygwin. +If t, use ptys: this enables Magit to prompt for passphrases when needed." + :group 'magit-process + :type '(choice (const :tag "pipe" nil) + (const :tag "pty" t))) + +(defcustom magit-need-cygwin-noglob + (and (eq system-type 'windows-nt) + (with-temp-buffer + (let ((process-environment + (append magit-git-environment process-environment))) + (condition-case e + (process-file magit-git-executable + nil (current-buffer) nil + "-c" "alias.echo=!echo" "echo" "x{0}") + (file-error + (lwarn 'magit-process :warning + "Could not run Git: %S" e)))) + (equal "x0\n" (buffer-string)))) + "Whether to use a workaround for Cygwin's globbing behavior. + +If non-nil, add environment variables to `process-environment' to +prevent the git.exe distributed by Cygwin and MSYS2 from +attempting to perform glob expansion when called from a native +Windows build of Emacs. See #2246." + :package-version '(magit . "2.3.0") + :group 'magit-process + :type '(choice (const :tag "Yes" t) + (const :tag "No" nil))) + +(defcustom magit-process-popup-time -1 + "Popup the process buffer if a command takes longer than this many seconds." + :group 'magit-process + :type '(choice (const :tag "Never" -1) + (const :tag "Immediately" 0) + (integer :tag "After this many seconds"))) + +(defcustom magit-process-log-max 32 + "Maximum number of sections to keep in a process log buffer. +When adding a new section would go beyond the limit set here, +then the older half of the sections are remove. Sections that +belong to processes that are still running are never removed. +When this is nil, no sections are ever removed." + :package-version '(magit . "2.1.0") + :group 'magit-process + :type '(choice (const :tag "Never remove old sections" nil) integer)) + +(defcustom magit-process-error-tooltip-max-lines 20 + "The number of lines for `magit-process-error-lines' to return. + +These are displayed in a tooltip for `mode-line-process' errors. + +If `magit-process-error-tooltip-max-lines' is nil, the tooltip +displays the text of `magit-process-error-summary' instead." + :package-version '(magit . "2.12.0") + :group 'magit-process + :type '(choice (const :tag "Use summary line" nil) + integer)) + +(defcustom magit-credential-cache-daemon-socket + (--some (pcase-let ((`(,prog . ,args) (split-string it))) + (if (and prog + (string-match-p + "\\`\\(?:\\(?:/.*/\\)?git-credential-\\)?cache\\'" prog)) + (or (cl-loop for (opt val) on args + if (string= opt "--socket") + return val) + (expand-file-name "~/.git-credential-cache/socket")))) + ;; Note: `magit-process-file' is not yet defined when + ;; evaluating this form, so we use `process-lines'. + (ignore-errors + (let ((process-environment + (append magit-git-environment process-environment))) + (process-lines magit-git-executable + "config" "--get-all" "credential.helper")))) + "If non-nil, start a credential cache daemon using this socket. + +When using Git's cache credential helper in the normal way, Emacs +sends a SIGHUP to the credential daemon after the git subprocess +has exited, causing the daemon to also quit. This can be avoided +by starting the `git-credential-cache--daemon' process directly +from Emacs. + +The function `magit-maybe-start-credential-cache-daemon' takes +care of starting the daemon if necessary, using the value of this +option as the socket. If this option is nil, then it does not +start any daemon. Likewise if another daemon is already running, +then it starts no new daemon. This function has to be a member +of the hook variable `magit-credential-hook' for this to work. +If an error occurs while starting the daemon, most likely because +the necessary executable is missing, then the function removes +itself from the hook, to avoid further futile attempts." + :package-version '(magit . "2.3.0") + :group 'magit-process + :type '(choice (file :tag "Socket") + (const :tag "Don't start a cache daemon" nil))) + +(defcustom magit-process-yes-or-no-prompt-regexp + " [\[(]\\([Yy]\\(?:es\\)?\\)[/|]\\([Nn]o?\\)[\])] ?[?:] ?$" + "Regexp matching Yes-or-No prompts of Git and its subprocesses." + :package-version '(magit . "2.1.0") + :group 'magit-process + :type 'regexp) + +(defcustom magit-process-password-prompt-regexps + '("^\\(Enter \\)?[Pp]assphrase\\( for \\(RSA \\)?key '.*'\\)?: ?$" + ;; Match-group 99 is used to identify the "user@host" part. + "^\\(Enter \\)?[Pp]assword\\( for '\\(https?://\\)?\\(?99:.*\\)'\\)?: ?$" + "^.*'s password: ?$" + "^Yubikey for .*: ?$" + "^Enter PIN for .*: ?$") + "List of regexps matching password prompts of Git and its subprocesses. +Also see `magit-process-find-password-functions'." + :package-version '(magit . "2.8.0") + :group 'magit-process + :type '(repeat (regexp))) + +(defcustom magit-process-find-password-functions nil + "List of functions to try in sequence to get a password. + +These functions may be called when git asks for a password, which +is detected using `magit-process-password-prompt-regexps'. They +are called if and only if matching the prompt resulted in the +value of the 99th submatch to be non-nil. Therefore users can +control for which prompts these functions should be called by +putting the host name in the 99th submatch, or not. + +If the functions are called, then they are called in the order +given, with the host name as only argument, until one of them +returns non-nil. If they are not called or none of them returns +non-nil, then the password is read from the user instead." + :package-version '(magit . "2.3.0") + :group 'magit-process + :type 'hook + :options '(magit-process-password-auth-source)) + +(defcustom magit-process-username-prompt-regexps + '("^Username for '.*': ?$") + "List of regexps matching username prompts of Git and its subprocesses." + :package-version '(magit . "2.1.0") + :group 'magit-process + :type '(repeat (regexp))) + +(defcustom magit-process-ensure-unix-line-ending t + "Whether Magit should ensure a unix coding system when talking to Git." + :package-version '(magit . "2.6.0") + :group 'magit-process + :type 'boolean) + +(defcustom magit-process-display-mode-line-error t + "Whether Magit should retain and highlight process errors in the mode line." + :package-version '(magit . "2.12.0") + :group 'magit-process + :type 'boolean) + +(defface magit-process-ok + '((t :inherit magit-section-heading :foreground "green")) + "Face for zero exit-status." + :group 'magit-faces) + +(defface magit-process-ng + '((t :inherit magit-section-heading :foreground "red")) + "Face for non-zero exit-status." + :group 'magit-faces) + +(defface magit-mode-line-process + '((t :inherit mode-line-emphasis)) + "Face for `mode-line-process' status when Git is running for side-effects." + :group 'magit-faces) + +(defface magit-mode-line-process-error + '((t :inherit error)) + "Face for `mode-line-process' error status. + +Used when `magit-process-display-mode-line-error' is non-nil." + :group 'magit-faces) + +;;; Process Mode + +(defvar magit-process-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-mode-map) + map) + "Keymap for `magit-process-mode'.") + +(define-derived-mode magit-process-mode magit-mode "Magit Process" + "Mode for looking at Git process output." + :group 'magit-process + (hack-dir-local-variables-non-file-buffer) + (setq imenu-prev-index-position-function + 'magit-imenu--process-prev-index-position-function) + (setq imenu-extract-index-name-function + 'magit-imenu--process-extract-index-name-function)) + +(defun magit-process-buffer (&optional nodisplay) + "Display the current repository's process buffer. + +If that buffer doesn't exist yet, then create it. +Non-interactively return the buffer and unless +optional NODISPLAY is non-nil also display it." + (interactive) + (let ((topdir (magit-toplevel))) + (unless topdir + (magit--with-safe-default-directory nil + (setq topdir default-directory) + (let (prev) + (while (not (equal topdir prev)) + (setq prev topdir) + (setq topdir (file-name-directory (directory-file-name topdir))))))) + (let ((buffer (or (--first (with-current-buffer it + (and (eq major-mode 'magit-process-mode) + (equal default-directory topdir))) + (buffer-list)) + (let ((default-directory topdir)) + (magit-generate-new-buffer 'magit-process-mode))))) + (with-current-buffer buffer + (if magit-root-section + (when magit-process-log-max + (magit-process-truncate-log)) + (magit-process-mode) + (let ((inhibit-read-only t) + (magit-insert-section--parent nil) + (magit-insert-section--oldroot nil)) + (make-local-variable 'text-property-default-nonsticky) + (magit-insert-section (processbuf) + (insert "\n"))))) + (unless nodisplay + (magit-display-buffer buffer)) + buffer))) + +(defun magit-process-kill () + "Kill the process at point." + (interactive) + (when-let ((process (magit-section-value-if 'process))) + (unless (eq (process-status process) 'run) + (user-error "Process isn't running")) + (magit-confirm 'kill-process) + (kill-process process))) + +;;; Synchronous Processes + +(defvar magit-process-raise-error nil) + +(defun magit-git (&rest args) + "Call Git synchronously in a separate process, for side-effects. + +Option `magit-git-executable' specifies the Git executable. +The arguments ARGS specify arguments to Git, they are flattened +before use. + +Process output goes into a new section in the buffer returned by +`magit-process-buffer'. If Git exits with a non-zero status, +then raise an error." + (let ((magit-process-raise-error t)) + (magit-call-git args))) + +(defun magit-run-git (&rest args) + "Call Git synchronously in a separate process, and refresh. + +Option `magit-git-executable' specifies the Git executable and +option `magit-git-global-arguments' specifies constant arguments. +The arguments ARGS specify arguments to Git, they are flattened +before use. + +After Git returns, the current buffer (if it is a Magit buffer) +as well as the current repository's status buffer are refreshed. + +Process output goes into a new section in the buffer returned by +`magit-process-buffer'." + (let ((magit--refresh-cache (list (cons 0 0)))) + (magit-call-git args) + (when (member (car args) '("init" "clone")) + ;; Creating a new repository invalidates the cache. + (setq magit--refresh-cache nil)) + (magit-refresh))) + +(defvar magit-pre-call-git-hook nil) + +(defun magit-call-git (&rest args) + "Call Git synchronously in a separate process. + +Option `magit-git-executable' specifies the Git executable and +option `magit-git-global-arguments' specifies constant arguments. +The arguments ARGS specify arguments to Git, they are flattened +before use. + +Process output goes into a new section in the buffer returned by +`magit-process-buffer'." + (run-hooks 'magit-pre-call-git-hook) + (let ((default-process-coding-system (magit--process-coding-system))) + (apply #'magit-call-process magit-git-executable + (magit-process-git-arguments args)))) + +(defun magit-call-process (program &rest args) + "Call PROGRAM synchronously in a separate process. +Process output goes into a new section in the buffer returned by +`magit-process-buffer'." + (pcase-let ((`(,process-buf . ,section) + (magit-process-setup program args))) + (magit-process-finish + (let ((inhibit-read-only t)) + (apply #'magit-process-file program nil process-buf nil args)) + process-buf (current-buffer) default-directory section))) + +(defun magit-process-file (process &optional infile buffer display &rest args) + "Process files synchronously in a separate process. +Identical to `process-file' but temporarily enable Cygwin's +\"noglob\" option during the call and ensure unix eol +conversion." + (let ((process-environment (magit-process-environment)) + (default-process-coding-system (magit--process-coding-system))) + (apply #'process-file process infile buffer display args))) + +(defun magit-process-environment () + ;; The various w32 hacks are only applicable when running on the + ;; local machine. As of Emacs 25.1, a local binding of + ;; process-environment different from the top-level value affects + ;; the environment used in + ;; tramp-sh-handle-{start-file-process,process-file}. + (let ((local (not (file-remote-p default-directory)))) + (append magit-git-environment + (and local + (cdr (assoc magit-git-executable magit-git-w32-path-hack))) + (and local magit-need-cygwin-noglob + (mapcar (lambda (var) + (concat var "=" (--if-let (getenv var) + (concat it " noglob") + "noglob"))) + '("CYGWIN" "MSYS"))) + process-environment))) + +(defvar magit-this-process nil) + +(defun magit-run-git-with-input (&rest args) + "Call Git in a separate process. +ARGS is flattened and then used as arguments to Git. + +The current buffer's content is used as the process' standard +input. + +Option `magit-git-executable' specifies the Git executable and +option `magit-git-global-arguments' specifies constant arguments. +The remaining arguments ARGS specify arguments to Git, they are +flattened before use." + (when (eq system-type 'windows-nt) + ;; On w32, git expects UTF-8 encoded input, ignore any user + ;; configuration telling us otherwise (see #3250). + (encode-coding-region (point-min) (point-max) 'utf-8-unix)) + (if (file-remote-p default-directory) + ;; We lack `process-file-region', so fall back to asynch + + ;; waiting in remote case. + (progn + (magit-start-git (current-buffer) args) + (while (and magit-this-process + (eq (process-status magit-this-process) 'run)) + (sleep-for 0.005))) + (run-hooks 'magit-pre-call-git-hook) + (pcase-let* ((process-environment (magit-process-environment)) + (default-process-coding-system (magit--process-coding-system)) + (flat-args (magit-process-git-arguments args)) + (`(,process-buf . ,section) + (magit-process-setup magit-git-executable flat-args)) + (inhibit-read-only t)) + (magit-process-finish + (apply #'call-process-region (point-min) (point-max) + magit-git-executable nil process-buf nil flat-args) + process-buf nil default-directory section)))) + +(defun magit-run-git-with-logfile (file &rest args) + "Call Git in a separate process and log its output to FILE. +This function might have a short halflive." + (apply #'magit-process-file magit-git-executable nil `(:file ,file) nil + (magit-process-git-arguments args)) + (magit-refresh)) + +;;; Asynchronous Processes + +(defun magit-run-git-async (&rest args) + "Start Git, prepare for refresh, and return the process object. +ARGS is flattened and then used as arguments to Git. + +Display the command line arguments in the echo area. + +After Git returns some buffers are refreshed: the buffer that was +current when this function was called (if it is a Magit buffer +and still alive), as well as the respective Magit status buffer. + +See `magit-start-process' for more information." + (message "Running %s %s" magit-git-executable + (let ((m (mapconcat #'identity (-flatten args) " "))) + (remove-list-of-text-properties 0 (length m) '(face) m) + m)) + (magit-start-git nil args)) + +(defun magit-run-git-with-editor (&rest args) + "Export GIT_EDITOR and start Git. +Also prepare for refresh and return the process object. +ARGS is flattened and then used as arguments to Git. + +Display the command line arguments in the echo area. + +After Git returns some buffers are refreshed: the buffer that was +current when this function was called (if it is a Magit buffer +and still alive), as well as the respective Magit status buffer. + +See `magit-start-process' and `with-editor' for more information." + (magit--record-separated-gitdir) + (magit-with-editor (magit-run-git-async args))) + +(defun magit-run-git-sequencer (&rest args) + "Export GIT_EDITOR and start Git. +Also prepare for refresh and return the process object. +ARGS is flattened and then used as arguments to Git. + +Display the command line arguments in the echo area. + +After Git returns some buffers are refreshed: the buffer that was +current when this function was called (if it is a Magit buffer +and still alive), as well as the respective Magit status buffer. +If the sequence stops at a commit, make the section representing +that commit the current section by moving `point' there. + +See `magit-start-process' and `with-editor' for more information." + (apply #'magit-run-git-with-editor args) + (set-process-sentinel magit-this-process #'magit-sequencer-process-sentinel) + magit-this-process) + +(defvar magit-pre-start-git-hook nil) + +(defun magit-start-git (input &rest args) + "Start Git, prepare for refresh, and return the process object. + +If INPUT is non-nil, it has to be a buffer or the name of an +existing buffer. The buffer content becomes the processes +standard input. + +Option `magit-git-executable' specifies the Git executable and +option `magit-git-global-arguments' specifies constant arguments. +The remaining arguments ARGS specify arguments to Git, they are +flattened before use. + +After Git returns some buffers are refreshed: the buffer that was +current when this function was called (if it is a Magit buffer +and still alive), as well as the respective Magit status buffer. + +See `magit-start-process' for more information." + (run-hooks 'magit-pre-start-git-hook) + (let ((default-process-coding-system (magit--process-coding-system))) + (apply #'magit-start-process magit-git-executable input + (magit-process-git-arguments args)))) + +(defun magit-start-process (program &optional input &rest args) + "Start PROGRAM, prepare for refresh, and return the process object. + +If optional argument INPUT is non-nil, it has to be a buffer or +the name of an existing buffer. The buffer content becomes the +processes standard input. + +The process is started using `start-file-process' and then setup +to use the sentinel `magit-process-sentinel' and the filter +`magit-process-filter'. Information required by these functions +is stored in the process object. When this function returns the +process has not started to run yet so it is possible to override +the sentinel and filter. + +After the process returns, `magit-process-sentinel' refreshes the +buffer that was current when `magit-start-process' was called (if +it is a Magit buffer and still alive), as well as the respective +Magit status buffer." + (pcase-let* + ((`(,process-buf . ,section) + (magit-process-setup program args)) + (process + (let ((process-connection-type + ;; Don't use a pty, because it would set icrnl + ;; which would modify the input (issue #20). + (and (not input) magit-process-connection-type)) + (process-environment (magit-process-environment)) + (default-process-coding-system (magit--process-coding-system))) + (apply #'start-file-process + (file-name-nondirectory program) + process-buf program args)))) + (with-editor-set-process-filter process #'magit-process-filter) + (set-process-sentinel process #'magit-process-sentinel) + (set-process-buffer process process-buf) + (when (eq system-type 'windows-nt) + ;; On w32, git expects UTF-8 encoded input, ignore any user + ;; configuration telling us otherwise. + (set-process-coding-system process 'utf-8-unix)) + (process-put process 'section section) + (process-put process 'command-buf (current-buffer)) + (process-put process 'default-dir default-directory) + (when inhibit-magit-refresh + (process-put process 'inhibit-refresh t)) + (oset section process process) + (with-current-buffer process-buf + (set-marker (process-mark process) (point))) + (when input + (with-current-buffer input + (process-send-region process (point-min) (point-max)) + (process-send-eof process))) + (setq magit-this-process process) + (oset section value process) + (magit-process-display-buffer process) + process)) + +(defun magit-parse-git-async (&rest args) + (setq args (magit-process-git-arguments args)) + (let ((command-buf (current-buffer)) + (process-buf (generate-new-buffer " *temp*")) + (toplevel (magit-toplevel))) + (with-current-buffer process-buf + (setq default-directory toplevel) + (let ((process + (let ((process-connection-type nil) + (process-environment (magit-process-environment)) + (default-process-coding-system + (magit--process-coding-system))) + (apply #'start-file-process "git" process-buf + magit-git-executable args)))) + (process-put process 'command-buf command-buf) + (process-put process 'parsed (point)) + (setq magit-this-process process) + process)))) + +;;; Process Internals + +(defun magit-process-setup (program args) + (magit-process-set-mode-line program args) + (let ((pwd default-directory) + (buf (magit-process-buffer t))) + (cons buf (with-current-buffer buf + (prog1 (magit-process-insert-section pwd program args nil nil) + (backward-char 1)))))) + +(defun magit-process-insert-section (pwd program args &optional errcode errlog) + (let ((inhibit-read-only t) + (magit-insert-section--parent magit-root-section) + (magit-insert-section--oldroot nil)) + (goto-char (1- (point-max))) + (magit-insert-section (process) + (insert (if errcode + (format "%3s " (propertize (number-to-string errcode) + 'face 'magit-process-ng)) + "run ")) + (unless (equal (expand-file-name pwd) + (expand-file-name default-directory)) + (insert (file-relative-name pwd default-directory) ?\s)) + (cond + ((and args (equal program magit-git-executable)) + (setq args (-split-at (length magit-git-global-arguments) args)) + (insert (propertize (file-name-nondirectory program) + 'face 'magit-section-heading) " ") + (insert (propertize (char-to-string magit-ellipsis) + 'face 'magit-section-heading + 'help-echo (mapconcat #'identity (car args) " "))) + (insert " ") + (insert (propertize (mapconcat #'shell-quote-argument (cadr args) " ") + 'face 'magit-section-heading))) + ((and args (equal program shell-file-name)) + (insert (propertize (cadr args) 'face 'magit-section-heading))) + (t + (insert (propertize (file-name-nondirectory program) + 'face 'magit-section-heading) " ") + (insert (propertize (mapconcat #'shell-quote-argument args " ") + 'face 'magit-section-heading)))) + (magit-insert-heading) + (when errlog + (insert-file-contents errlog) + (goto-char (1- (point-max)))) + (insert "\n")))) + +(defun magit-process-truncate-log () + (let* ((head nil) + (tail (oref magit-root-section children)) + (count (length tail))) + (when (> (1+ count) magit-process-log-max) + (while (and (cdr tail) + (> count (/ magit-process-log-max 2))) + (let* ((inhibit-read-only t) + (section (car tail)) + (process (oref section process))) + (cond ((not process)) + ((memq (process-status process) '(exit signal)) + (delete-region (oref section start) + (1+ (oref section end))) + (cl-decf count)) + (t + (push section head)))) + (pop tail)) + (oset magit-root-section children + (nconc (reverse head) tail))))) + +(defun magit-process-sentinel (process event) + "Default sentinel used by `magit-start-process'." + (when (memq (process-status process) '(exit signal)) + (setq event (substring event 0 -1)) + (when (string-match "^finished" event) + (message (concat (capitalize (process-name process)) " finished"))) + (magit-process-finish process) + (when (eq process magit-this-process) + (setq magit-this-process nil)) + (unless (process-get process 'inhibit-refresh) + (let ((command-buf (process-get process 'command-buf))) + (if (buffer-live-p command-buf) + (with-current-buffer command-buf + (magit-refresh)) + (with-temp-buffer + (setq default-directory (process-get process 'default-dir)) + (magit-refresh))))))) + +(defun magit-sequencer-process-sentinel (process event) + "Special sentinel used by `magit-run-git-sequencer'." + (when (memq (process-status process) '(exit signal)) + (magit-process-sentinel process event) + (when-let ((process-buf (process-buffer process))) + (when (buffer-live-p process-buf) + (when-let ((status-buf (with-current-buffer process-buf + (magit-mode-get-buffer 'magit-status-mode)))) + (with-current-buffer status-buf + (--when-let + (magit-get-section + `((commit . ,(magit-rev-parse "HEAD")) + (,(pcase (car (cadr (-split-at + (1+ (length magit-git-global-arguments)) + (process-command process)))) + ((or "rebase" "am") 'rebase-sequence) + ((or "cherry-pick" "revert") 'sequence))) + (status))) + (goto-char (oref it start)) + (magit-section-update-highlight)))))))) + +(defun magit-process-filter (proc string) + "Default filter used by `magit-start-process'." + (with-current-buffer (process-buffer proc) + (let ((inhibit-read-only t)) + (magit-process-yes-or-no-prompt proc string) + (magit-process-username-prompt proc string) + (magit-process-password-prompt proc string) + (goto-char (process-mark proc)) + (setq string (propertize string 'magit-section + (process-get proc 'section))) + ;; Find last ^M in string. If one was found, ignore + ;; everything before it and delete the current line. + (let ((ret-pos (length string))) + (while (and (>= (cl-decf ret-pos) 0) + (/= ?\r (aref string ret-pos)))) + (if (< ret-pos 0) + (insert string) + (delete-region (line-beginning-position) (point)) + (insert (substring string (1+ ret-pos))))) + (set-marker (process-mark proc) (point))))) + +(defmacro magit-process-kill-on-abort (proc &rest body) + (declare (indent 1) (debug (form body))) + (let ((map (cl-gensym))) + `(let ((,map (make-sparse-keymap))) + (set-keymap-parent ,map minibuffer-local-map) + (define-key ,map "\C-g" + (lambda () + (interactive) + (ignore-errors (kill-process ,proc)) + (abort-recursive-edit))) + (let ((minibuffer-local-map ,map)) + ,@body)))) + +(defun magit-process-yes-or-no-prompt (process string) + "Forward Yes-or-No prompts to the user." + (when-let ((beg (string-match magit-process-yes-or-no-prompt-regexp string))) + (let ((max-mini-window-height 30)) + (process-send-string + process + (downcase + (concat + (match-string + (if (save-match-data + (magit-process-kill-on-abort process + (yes-or-no-p (substring string 0 beg)))) 1 2) + string) + "\n")))))) + +(defun magit-process-password-auth-source (key) + "Use `auth-source-search' to get a password. +If found, return the password. Otherwise, return nil. + +To use this function add it to the appropriate hook + (add-hook 'magit-process-find-password-functions + 'magit-process-password-auth-source) + +KEY typically derives from a prompt such as: + Password for 'https://tarsius@bitbucket.org' +in which case it would be the string + tarsius@bitbucket.org +which matches the ~/.authinfo.gpg entry + machine bitbucket.org login tarsius password 12345 +or iff that is undefined, for backward compatibility + machine tarsius@bitbucket.org password 12345" + (require 'auth-source) + (and (string-match "\\`\\([^@]+\\)@\\([^@]+\\)\\'" key) + (let* ((user (match-string 1 key)) + (host (match-string 2 key)) + (secret + (plist-get + (car (or (auth-source-search :max 1 :host host :user user) + (auth-source-search :max 1 :host key))) + :secret))) + (if (functionp secret) + (funcall secret) + secret)))) + +(defun magit-process-password-prompt (process string) + "Find a password based on prompt STRING and send it to git. +Use `magit-process-password-prompt-regexps' to find a known +prompt. If and only if one is found, then call functions in +`magit-process-find-password-functions' until one of them returns +the password. If all function return nil, then read the password +from the user." + (when-let ((prompt (magit-process-match-prompt + magit-process-password-prompt-regexps string))) + (process-send-string + process (magit-process-kill-on-abort process + (concat (or (when-let ((key (match-string 99 string))) + (run-hook-with-args-until-success + 'magit-process-find-password-functions key)) + (read-passwd prompt)) + "\n"))))) + +(defun magit-process-username-prompt (process string) + "Forward username prompts to the user." + (--when-let (magit-process-match-prompt + magit-process-username-prompt-regexps string) + (process-send-string + process (magit-process-kill-on-abort process + (concat (read-string it nil nil (user-login-name)) "\n"))))) + +(defun magit-process-match-prompt (prompts string) + "Match STRING against PROMPTS and set match data. +Return the matched string suffixed with \": \", if needed." + (when (--any-p (string-match it string) prompts) + (let ((prompt (match-string 0 string))) + (cond ((string-suffix-p ": " prompt) prompt) + ((string-suffix-p ":" prompt) (concat prompt " ")) + (t (concat prompt ": ")))))) + +(defun magit--process-coding-system () + (let ((fro (or magit-git-output-coding-system + (car default-process-coding-system))) + (to (cdr default-process-coding-system))) + (if magit-process-ensure-unix-line-ending + (cons (coding-system-change-eol-conversion fro 'unix) + (coding-system-change-eol-conversion to 'unix)) + (cons fro to)))) + +(defvar magit-credential-hook nil + "Hook run before Git needs credentials.") + +(defvar magit-credential-cache-daemon-process nil) + +(defun magit-maybe-start-credential-cache-daemon () + "Maybe start a `git-credential-cache--daemon' process. + +If such a process is already running or if the value of option +`magit-credential-cache-daemon-socket' is nil, then do nothing. +Otherwise start the process passing the value of that options +as argument." + (unless (or (not magit-credential-cache-daemon-socket) + (process-live-p magit-credential-cache-daemon-process) + (memq magit-credential-cache-daemon-process + (list-system-processes))) + (setq magit-credential-cache-daemon-process + (or (--first (let* ((attr (process-attributes it)) + (comm (cdr (assq 'comm attr))) + (user (cdr (assq 'user attr)))) + (and (string= comm "git-credential-cache--daemon") + (string= user user-login-name))) + (list-system-processes)) + (condition-case nil + (start-process "git-credential-cache--daemon" + " *git-credential-cache--daemon*" + magit-git-executable + "credential-cache--daemon" + magit-credential-cache-daemon-socket) + ;; Some Git implementations (e.g. Windows) won't have + ;; this program; if we fail the first time, stop trying. + ((debug error) + (remove-hook 'magit-credential-hook + #'magit-maybe-start-credential-cache-daemon))))))) + +(add-hook 'magit-credential-hook #'magit-maybe-start-credential-cache-daemon) + +(defun tramp-sh-handle-start-file-process--magit-tramp-process-environment + (fn name buffer program &rest args) + (if magit-tramp-process-environment + (apply fn name buffer + (car magit-tramp-process-environment) + (append (cdr magit-tramp-process-environment) + (cons program args))) + (apply fn name buffer program args))) + +(advice-add 'tramp-sh-handle-start-file-process :around + 'tramp-sh-handle-start-file-process--magit-tramp-process-environment) + +(defun tramp-sh-handle-process-file--magit-tramp-process-environment + (fn program &optional infile destination display &rest args) + (if magit-tramp-process-environment + (apply fn "env" infile destination display + (append magit-tramp-process-environment + (cons program args))) + (apply fn program infile destination display args))) + +(advice-add 'tramp-sh-handle-process-file :around + 'tramp-sh-handle-process-file--magit-tramp-process-environment) + +(defvar magit-mode-line-process-map + (let ((map (make-sparse-keymap))) + (define-key map (kbd " ") + 'magit-process-buffer) + map) + "Keymap for `mode-line-process'.") + +(defun magit-process-set-mode-line (program args) + "Display the git command (sans arguments) in the mode line." + (when (equal program magit-git-executable) + (setq args (nthcdr (length magit-git-global-arguments) args))) + (let ((str (concat " " (propertize + (concat (file-name-nondirectory program) + (and args (concat " " (car args)))) + 'mouse-face 'highlight + 'keymap magit-mode-line-process-map + 'help-echo "mouse-1: Show process buffer" + 'face 'magit-mode-line-process)))) + (magit-repository-local-set 'mode-line-process str) + (dolist (buf (magit-mode-get-buffers)) + (with-current-buffer buf + (setq mode-line-process str))) + (force-mode-line-update t))) + +(defun magit-process-set-mode-line-error-status (&optional error str) + "Apply an error face to the string set by `magit-process-set-mode-line'. + +If ERROR is supplied, include it in the `mode-line-process' tooltip. + +If STR is supplied, it replaces the `mode-line-process' text." + (setq str (or str (magit-repository-local-get 'mode-line-process))) + (when str + (setq error (format "%smouse-1: Show process buffer" + (if (stringp error) + (concat error "\n\n") + ""))) + (setq str (concat " " (propertize + (substring-no-properties str 1) + 'mouse-face 'highlight + 'keymap magit-mode-line-process-map + 'help-echo error + 'face 'magit-mode-line-process-error))) + (magit-repository-local-set 'mode-line-process str) + (dolist (buf (magit-mode-get-buffers)) + (with-current-buffer buf + (setq mode-line-process str))) + (force-mode-line-update t) + ;; We remove any error status from the mode line when a magit + ;; buffer is refreshed (see `magit-refresh-buffer'), but we must + ;; ensure that we ignore any refreshes during the remainder of the + ;; current command -- otherwise a newly-set error status would be + ;; removed before it was seen. We set a flag which prevents the + ;; status from being removed prior to the next command, so that + ;; the error status is guaranteed to remain visible until then. + (let ((repokey (magit-repository-local-repository))) + ;; The following closure captures the repokey value, and is + ;; added to `pre-command-hook'. + (cl-labels ((enable-magit-process-unset-mode-line + () ;; Remove ourself from the hook variable, so + ;; that we only run once. + (remove-hook 'pre-command-hook + #'enable-magit-process-unset-mode-line) + ;; Clear the inhibit flag for the repository in + ;; which we set it. + (magit-repository-local-set + 'inhibit-magit-process-unset-mode-line nil repokey))) + ;; Set the inhibit flag until the next command is invoked. + (magit-repository-local-set + 'inhibit-magit-process-unset-mode-line t repokey) + (add-hook 'pre-command-hook + #'enable-magit-process-unset-mode-line))))) + +(defun magit-process-unset-mode-line-error-status () + "Remove any current error status from the mode line." + (let ((status (or mode-line-process + (magit-repository-local-get 'mode-line-process)))) + (when (and status + (eq (get-text-property 1 'face status) + 'magit-mode-line-process-error)) + (magit-process-unset-mode-line)))) + +(defun magit-process-unset-mode-line () + "Remove the git command from the mode line." + (unless (magit-repository-local-get 'inhibit-magit-process-unset-mode-line) + (magit-repository-local-set 'mode-line-process nil) + (dolist (buf (magit-mode-get-buffers)) + (with-current-buffer buf (setq mode-line-process nil))) + (force-mode-line-update t))) + +(defvar magit-process-error-message-regexps + (list "^\\*ERROR\\*: Canceled by user$" + "^\\(?:error\\|fatal\\|git\\): \\(.*\\)$" + "^\\(Cannot rebase:.*\\)$")) + +(define-error 'magit-git-error "Git error") + +(defun magit-process-error-summary (process-buf section) + "A one-line error summary from the given SECTION." + (or (and (buffer-live-p process-buf) + (with-current-buffer process-buf + (and (oref section content) + (save-excursion + (goto-char (oref section end)) + (run-hook-wrapped + 'magit-process-error-message-regexps + (lambda (re) + (save-excursion + (and (re-search-backward + re (oref section start) t) + (or (match-string-no-properties 1) + (and (not magit-process-raise-error) + 'suppressed)))))))))) + "Git failed")) + +(defun magit-process-error-tooltip (process-buf section) + "Returns the text from SECTION of the PROCESS-BUF buffer. + +Limited by `magit-process-error-tooltip-max-lines'." + (and (integerp magit-process-error-tooltip-max-lines) + (> magit-process-error-tooltip-max-lines 0) + (buffer-live-p process-buf) + (with-current-buffer process-buf + (save-excursion + (goto-char (or (oref section content) + (oref section start))) + (buffer-substring-no-properties + (point) + (save-excursion + (forward-line magit-process-error-tooltip-max-lines) + (goto-char + (if (> (point) (oref section end)) + (oref section end) + (point))) + ;; Remove any trailing whitespace. + (when (re-search-backward "[^[:space:]\n]" + (oref section start) t) + (forward-char 1)) + (point))))))) + +(defvar-local magit-this-error nil) + +(defvar magit-process-finish-apply-ansi-colors nil) + +(defun magit-process-finish (arg &optional process-buf command-buf + default-dir section) + (unless (integerp arg) + (setq process-buf (process-buffer arg)) + (setq command-buf (process-get arg 'command-buf)) + (setq default-dir (process-get arg 'default-dir)) + (setq section (process-get arg 'section)) + (setq arg (process-exit-status arg))) + (when (fboundp 'dired-uncache) + (dired-uncache default-dir)) + (when (buffer-live-p process-buf) + (with-current-buffer process-buf + (let ((inhibit-read-only t) + (marker (oref section start))) + (goto-char marker) + (save-excursion + (delete-char 3) + (set-marker-insertion-type marker nil) + (insert (propertize (format "%3s" arg) + 'magit-section section + 'face (if (= arg 0) + 'magit-process-ok + 'magit-process-ng))) + (set-marker-insertion-type marker t)) + (when magit-process-finish-apply-ansi-colors + (ansi-color-apply-on-region (oref section content) + (oref section end))) + (if (= (oref section end) + (+ (line-end-position) 2)) + (save-excursion + (goto-char (1+ (line-end-position))) + (delete-char -1) + (oset section content nil)) + (let ((buf (magit-process-buffer t))) + (when (and (= arg 0) + (not (--any-p (eq (window-buffer it) buf) + (window-list)))) + (magit-section-hide section))))))) + (if (= arg 0) + ;; Unset the `mode-line-process' value upon success. + (magit-process-unset-mode-line) + ;; Otherwise process the error. + (let ((msg (magit-process-error-summary process-buf section))) + ;; Change `mode-line-process' to an error face upon failure. + (if magit-process-display-mode-line-error + (magit-process-set-mode-line-error-status + (or (magit-process-error-tooltip process-buf section) + msg)) + (magit-process-unset-mode-line)) + ;; Either signal the error, or else display the error summary in + ;; the status buffer and with a message in the echo area. + (cond + (magit-process-raise-error + (signal 'magit-git-error (list (format "%s (in %s)" msg default-dir)))) + ((not (eq msg 'suppressed)) + (when (buffer-live-p process-buf) + (with-current-buffer process-buf + (when-let ((status-buf (magit-mode-get-buffer 'magit-status-mode))) + (with-current-buffer status-buf + (setq magit-this-error msg))))) + (message "%s ... [%s buffer %s for details]" msg + (if-let ((key (and (buffer-live-p command-buf) + (with-current-buffer command-buf + (car (where-is-internal + 'magit-process-buffer)))))) + (format "Hit %s to see" (key-description key)) + "See") + (buffer-name process-buf)))))) + arg) + +(defun magit-process-display-buffer (process) + (when (process-live-p process) + (let ((buf (process-buffer process))) + (cond ((not (buffer-live-p buf))) + ((= magit-process-popup-time 0) + (if (minibufferp) + (switch-to-buffer-other-window buf) + (pop-to-buffer buf))) + ((> magit-process-popup-time 0) + (run-with-timer magit-process-popup-time nil + (lambda (p) + (when (eq (process-status p) 'run) + (let ((buf (process-buffer p))) + (when (buffer-live-p buf) + (if (minibufferp) + (switch-to-buffer-other-window buf) + (pop-to-buffer buf)))))) + process)))))) + +(defun magit--log-action (summary line list) + (let (heading lines) + (if (cdr list) + (progn (setq heading (funcall summary list)) + (setq lines (mapcar line list))) + (setq heading (funcall line (car list)))) + (with-current-buffer (magit-process-buffer t) + (goto-char (1- (point-max))) + (let ((inhibit-read-only t)) + (magit-insert-section (message) + (magit-insert-heading (concat " * " heading)) + (when lines + (dolist (line lines) + (insert line "\n")) + (insert "\n")))) + (let ((inhibit-message t)) + (when heading + (setq lines (cons heading lines))) + (message (mapconcat #'identity lines "\n")))))) + +;;; _ +(provide 'magit-process) +;;; magit-process.el ends here diff --git a/elpa/magit-20181113.1837/magit-pull.el b/elpa/magit-20181113.1837/magit-pull.el new file mode 100644 index 00000000..67abe436 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-pull.el @@ -0,0 +1,151 @@ +;;; magit-pull.el --- update local objects and refs -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements pull commands. + +;;; Code: + +(require 'magit) + +;;; Commands + +;;;###autoload (autoload 'magit-pull-popup "magit-pull" nil t) +(magit-define-popup magit-pull-popup + "Popup console for pull commands." + :man-page "git-pull" + :variables '("Configure" + (?r "branch.%s.rebase" + magit-cycle-branch*rebase + magit-pull-format-branch*rebase) + (?C "variables..." magit-branch-config-popup)) + :actions '((lambda () + (--if-let (magit-get-current-branch) + (concat + (propertize "Pull into " 'face 'magit-popup-heading) + (propertize it 'face 'magit-branch-local) + (propertize " from" 'face 'magit-popup-heading)) + (propertize "Pull from" 'face 'magit-popup-heading))) + (?p magit-get-push-branch magit-pull-from-pushremote) + (?u magit-get-upstream-branch magit-pull-from-upstream) + (?e "elsewhere" magit-pull-branch)) + :default-action 'magit-pull + :max-action-columns 1) + +;;;###autoload (autoload 'magit-pull-and-fetch-popup "magit-pull" nil t) +(magit-define-popup magit-pull-and-fetch-popup + "Popup console for pull and fetch commands. + +This popup is intended as a replacement for the separate popups +`magit-pull-popup' and `magit-fetch-popup'. To use it, add this +to your init file: + + (with-eval-after-load \\='magit-remote + (define-key magit-mode-map \"f\" \\='magit-pull-and-fetch-popup) + (define-key magit-mode-map \"F\" nil)) + +The combined popup does not offer all commands and arguments +available from the individual popups. Instead of the argument +`--prune' and the command `magit-fetch-all' it uses two commands +`magit-fetch-prune' and `magit-fetch-no-prune'. And the commands +`magit-fetch-from-pushremote' and `magit-fetch-from-upstream' are +missing. To add them use something like: + + (with-eval-after-load \\='magit-remote + (magit-define-popup-action \\='magit-pull-and-fetch-popup ?U + \\='magit-get-upstream-branch + \\='magit-fetch-from-upstream-remote ?F) + (magit-define-popup-action \\='magit-pull-and-fetch-popup ?P + \\='magit-get-push-branch + \\='magit-fetch-from-push-remote ?F))" + :man-page "git-pull" + :variables '("Configure" + (?r "branch.%s.rebase" + magit-cycle-branch*rebase + magit-pull-format-branch*rebase) + (?C "variables..." magit-branch-config-popup)) + :actions '((lambda () + (--if-let (magit-get-current-branch) + (concat + (propertize "Pull into " 'face 'magit-popup-heading) + (propertize it 'face 'magit-branch-local) + (propertize " from" 'face 'magit-popup-heading)) + (propertize "Pull from" 'face 'magit-popup-heading))) + (?p magit-get-push-branch magit-pull-from-pushremote) + (?u magit-get-upstream-branch magit-pull-from-upstream) + (?e "elsewhere" magit-pull-branch) + "Fetch from" + (?f "remotes" magit-fetch-all-no-prune) + (?F "remotes and prune" magit-fetch-all-prune) + "Fetch" + (?o "another branch" magit-fetch-branch) + (?s "explicit refspec" magit-fetch-refspec) + (?m "submodules" magit-fetch-modules)) + :default-action 'magit-fetch + :max-action-columns 1) + +(defun magit-pull-format-branch*rebase () + (magit--format-popup-variable:choices + (format "branch.%s.rebase" (or (magit-get-current-branch) "")) + '("true" "false") + "false" "pull.rebase")) + +(defun magit-git-pull (source args) + (run-hooks 'magit-credential-hook) + (pcase-let ((`(,remote . ,branch) + (magit-split-branch-name source))) + (magit-run-git-with-editor "pull" args remote branch))) + +;;;###autoload +(defun magit-pull-from-pushremote (args) + "Pull from the push-remote of the current branch." + (interactive (list (magit-pull-arguments))) + (--if-let (magit-get-push-branch) + (magit-git-pull it args) + (--if-let (magit-get-current-branch) + (user-error "No push-remote is configured for %s" it) + (user-error "No branch is checked out")))) + +;;;###autoload +(defun magit-pull-from-upstream (args) + "Pull from the upstream of the current branch." + (interactive (list (magit-pull-arguments))) + (--if-let (magit-get-upstream-branch) + (progn (run-hooks 'magit-credential-hook) + (magit-run-git-with-editor + "pull" args (car (magit-split-branch-name it)))) + (--if-let (magit-get-current-branch) + (user-error "No upstream is configured for %s" it) + (user-error "No branch is checked out")))) + +;;;###autoload +(defun magit-pull-branch (source args) + "Pull from a branch read in the minibuffer." + (interactive (list (magit-read-remote-branch "Pull" nil nil nil t) + (magit-pull-arguments))) + (magit-git-pull source args)) + +;;; _ +(provide 'magit-pull) +;;; magit-pull.el ends here diff --git a/elpa/magit-20181113.1837/magit-push.el b/elpa/magit-20181113.1837/magit-push.el new file mode 100644 index 00000000..f6e04282 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-push.el @@ -0,0 +1,345 @@ +;;; magit-push.el --- update remote objects and refs -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements push commands. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +;;; Options + +(defcustom magit-push-current-set-remote-if-missing t + "Whether to configure missing remotes before pushing. + +When nil, then the command `magit-push-current-to-pushremote' and +`magit-push-current-to-upstream' do not appear in the push popup +if the push-remote resp. upstream is not configured. If the user +invokes one of these commands anyway, then it raises an error. + +When non-nil, then these commands always appear in the push +popup. But if the required configuration is missing, then they +do appear in a way that indicates that this is the case. If the +user invokes one of them, then it asks for the necessary +configuration, stores the configuration, and then uses it to push +a first time. + +This option also affects whether the argument `--set-upstream' is +available in the popup. If the value is t, then that argument is +redundant. But note that changing the value of this option does +not take affect immediately, the argument will only be added or +removed after restarting Emacs." + :package-version '(magit . "2.6.0") + :group 'magit-commands + :type '(choice (const :tag "don't set" nil) + (const :tag "set branch..pushRemote" t) + (const :tag "set remote.pushDefault" default))) + +;;; Commands + +;;;###autoload (autoload 'magit-push-popup "magit-push" nil t) +(magit-define-popup magit-push-popup + "Popup console for push commands." + :man-page "git-push" + :switches `((?f "Force with lease" "--force-with-lease") + (?F "Force" "--force") + (?h "Disable hooks" "--no-verify") + (?d "Dry run" "--dry-run") + ,@(and (not magit-push-current-set-remote-if-missing) + '((?u "Set upstream" "--set-upstream")))) + :actions '("Configure" + (?C "variables..." magit-branch-config-popup) + (lambda () + (--when-let (magit-get-current-branch) + (concat (propertize "Push " 'face 'magit-popup-heading) + (propertize it 'face 'magit-branch-local) + (propertize " to" 'face 'magit-popup-heading)))) + (?p magit--push-current-to-pushremote-desc + magit-push-current-to-pushremote) + (?u magit--push-current-to-upstream-desc + magit-push-current-to-upstream) + (?e "elsewhere\n" magit-push-current) + "Push" + (?o "another branch" magit-push-other) + (?T "a tag" magit-push-tag) + (?r "explicit refspecs" magit-push-refspecs) + (?t "all tags" magit-push-tags) + (?m "matching branches" magit-push-matching)) + :max-action-columns 2) + +(defun magit-git-push (branch target args) + (run-hooks 'magit-credential-hook) + (pcase-let ((`(,remote . ,target) + (magit-split-branch-name target))) + (magit-run-git-async "push" "-v" args remote + (format "%s:refs/heads/%s" branch target)))) + +;;;###autoload +(defun magit-push-current-to-pushremote (args &optional push-remote) + "Push the current branch to `branch..pushRemote'. +If that variable is unset, then push to `remote.pushDefault'. + +When `magit-push-current-set-remote-if-missing' is non-nil and +the push-remote is not configured, then read the push-remote from +the user, set it, and then push to it. With a prefix argument +the push-remote can be changed before pushed to it." + (interactive + (list (magit-push-arguments) + (and (magit--push-current-set-pushremote-p current-prefix-arg) + (magit-read-remote + (if (eq magit-push-current-set-remote-if-missing 'default) + "Set `remote.pushDefault' and push there" + (format "Set `branch.%s.pushRemote' and push there" + (magit-get-current-branch))))))) + (--if-let (magit-get-current-branch) + (progn (when push-remote + (setf (magit-get + (if (eq magit-push-current-set-remote-if-missing 'default) + "remote.pushDefault" + (format "branch.%s.pushRemote" it))) + push-remote)) + (if-let ((remote (magit-get-push-remote it))) + (if (member remote (magit-list-remotes)) + (magit-git-push it (concat remote "/" it) args) + (user-error "Remote `%s' doesn't exist" remote)) + (user-error "No push-remote is configured for %s" it))) + (user-error "No branch is checked out"))) + +(defun magit--push-current-set-pushremote-p (&optional change) + (and (or change + (and magit-push-current-set-remote-if-missing + (not (magit-get-push-remote)))) + (magit-get-current-branch))) + +(defun magit--push-current-to-pushremote-desc () + (--if-let (magit-get-push-branch) + (concat (magit-branch-set-face it) "\n") + (and (magit--push-current-set-pushremote-p) + (concat + (propertize (if (eq magit-push-current-set-remote-if-missing 'default) + "pushDefault" + "pushRemote") + 'face 'bold) + ", after setting that\n")))) + +;;;###autoload +(defun magit-push-current-to-upstream (args &optional upstream) + "Push the current branch to its upstream branch. + +When `magit-push-current-set-remote-if-missing' is non-nil and +the upstream is not configured, then read the upstream from the +user, set it, and then push to it. With a prefix argument the +upstream can be changed before pushed to it." + (interactive + (list (magit-push-arguments) + (and (magit--push-current-set-upstream-p current-prefix-arg) + (magit-read-upstream-branch)))) + (--if-let (magit-get-current-branch) + (progn + (when upstream + (magit-set-upstream-branch it upstream)) + (if-let ((target (magit-get-upstream-branch it))) + (magit-git-push it target args) + (user-error "No upstream is configured for %s" it))) + (user-error "No branch is checked out"))) + +(defun magit--push-current-set-upstream-p (&optional change) + (and (or change + (and magit-push-current-set-remote-if-missing + (not (magit-get-upstream-branch)))) + (magit-get-current-branch))) + +(defun magit--push-current-to-upstream-desc () + (--if-let (magit-get-upstream-branch) + (concat (magit-branch-set-face it) "\n") + (and (magit--push-current-set-upstream-p) + (concat (propertize "@{upstream}" 'face 'bold) + ", after setting that\n")))) + +;;;###autoload +(defun magit-push-current (target args) + "Push the current branch to a branch read in the minibuffer." + (interactive + (--if-let (magit-get-current-branch) + (list (magit-read-remote-branch (format "Push %s to" it) + nil nil it 'confirm) + (magit-push-arguments)) + (user-error "No branch is checked out"))) + (magit-git-push (magit-get-current-branch) target args)) + +;;;###autoload +(defun magit-push-other (source target args) + "Push an arbitrary branch or commit somewhere. +Both the source and the target are read in the minibuffer." + (interactive + (let ((source (magit-read-local-branch-or-commit "Push"))) + (list source + (magit-read-remote-branch + (format "Push %s to" source) nil + (if (magit-local-branch-p source) + (or (magit-get-push-branch source) + (magit-get-upstream-branch source)) + (and (magit-rev-ancestor-p source "HEAD") + (or (magit-get-push-branch) + (magit-get-upstream-branch)))) + source 'confirm) + (magit-push-arguments)))) + (magit-git-push source target args)) + +(defvar magit-push-refspecs-history nil) + +;;;###autoload +(defun magit-push-refspecs (remote refspecs args) + "Push one or multiple REFSPECS to a REMOTE. +Both the REMOTE and the REFSPECS are read in the minibuffer. To +use multiple REFSPECS, separate them with commas. Completion is +only available for the part before the colon, or when no colon +is used." + (interactive + (list (magit-read-remote "Push to remote") + (split-string (magit-completing-read-multiple + "Push refspec,s" + (cons "HEAD" (magit-list-local-branch-names)) + nil nil 'magit-push-refspecs-history) + crm-default-separator t) + (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args remote refspecs)) + +;;;###autoload +(defun magit-push-matching (remote &optional args) + "Push all matching branches to another repository. +If multiple remotes exist, then read one from the user. +If just one exists, use that without requiring confirmation." + (interactive (list (magit-read-remote "Push matching branches to" nil t) + (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args remote ":")) + +;;;###autoload +(defun magit-push-tags (remote &optional args) + "Push all tags to another repository. +If only one remote exists, then push to that. Otherwise prompt +for a remote, offering the remote configured for the current +branch as default." + (interactive (list (magit-read-remote "Push tags to remote" nil t) + (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" remote "--tags" args)) + +;;;###autoload +(defun magit-push-tag (tag remote &optional args) + "Push a tag to another repository." + (interactive + (let ((tag (magit-read-tag "Push tag"))) + (list tag (magit-read-remote (format "Push %s to remote" tag) nil t) + (magit-push-arguments)))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" remote tag args)) + +;;;###autoload +(defun magit-push-implicitly (args) + "Push somewhere without using an explicit refspec. + +This command simply runs \"git push -v [ARGS]\". ARGS are the +arguments specified in the popup buffer. No explicit refspec +arguments are used. Instead the behavior depends on at least +these Git variables: `push.default', `remote.pushDefault', +`branch..pushRemote', `branch..remote', +`branch..merge', and `remote..push'. + +To add this command to the push popup add this to your init file: + + (with-eval-after-load \\='magit-remote + (magit-define-popup-action \\='magit-push-popup ?P + \\='magit-push-implicitly--desc + \\='magit-push-implicitly ?p t)) + +The function `magit-push-implicitly--desc' attempts to predict +what this command will do. The value it returns is displayed in +the popup buffer." + (interactive (list (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args)) + +(defun magit-push-implicitly--desc () + (let ((default (magit-get "push.default"))) + (unless (equal default "nothing") + (or (when-let ((remote (or (magit-get-remote) + (magit-remote-p "origin"))) + (refspec (magit-get "remote" remote "push"))) + (format "%s using %s" + (propertize remote 'face 'magit-branch-remote) + (propertize refspec 'face 'bold))) + (--when-let (and (not (magit-get-push-branch)) + (magit-get-upstream-branch)) + (format "%s aka %s\n" + (magit-branch-set-face it) + (propertize "@{upstream}" 'face 'bold))) + (--when-let (magit-get-push-branch) + (format "%s aka %s\n" + (magit-branch-set-face it) + (propertize "pushRemote" 'face 'bold))) + (--when-let (magit-get-@{push}-branch) + (format "%s aka %s\n" + (magit-branch-set-face it) + (propertize "@{push}" 'face 'bold))) + (format "using %s (%s is %s)\n" + (propertize "git push" 'face 'bold) + (propertize "push.default" 'face 'bold) + (propertize default 'face 'bold)))))) + +;;;###autoload +(defun magit-push-to-remote (remote args) + "Push to REMOTE without using an explicit refspec. +The REMOTE is read in the minibuffer. + +This command simply runs \"git push -v [ARGS] REMOTE\". ARGS +are the arguments specified in the popup buffer. No refspec +arguments are used. Instead the behavior depends on at least +these Git variables: `push.default', `remote.pushDefault', +`branch..pushRemote', `branch..remote', +`branch..merge', and `remote..push'. + +To add this command to the push popup add this to your init file: + + (with-eval-after-load \\='magit-remote + (magit-define-popup-action \\='magit-push-popup ?r + \\='magit-push-to-remote--desc + \\='magit-push-to-remote ?p t))" + (interactive (list (magit-read-remote "Push to remote") + (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args remote)) + +(defun magit-push-to-remote--desc () + (format "using %s\n" (propertize "git push " 'face 'bold))) + +;;; _ +(provide 'magit-push) +;;; magit-push.el ends here diff --git a/elpa/magit-20181113.1837/magit-refs.el b/elpa/magit-20181113.1837/magit-refs.el new file mode 100644 index 00000000..a0bddd3f --- /dev/null +++ b/elpa/magit-20181113.1837/magit-refs.el @@ -0,0 +1,752 @@ +;;; magit-refs.el --- listing references -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements support for listing references in a buffer. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +(defvar bookmark-make-record-function) + +;;; Options + +(defgroup magit-refs nil + "Inspect and manipulate Git branches and tags." + :link '(info-link "(magit)References Buffer") + :group 'magit-modes) + +(defcustom magit-refs-mode-hook nil + "Hook run after entering Magit-Refs mode." + :package-version '(magit . "2.1.0") + :group 'magit-refs + :type 'hook) + +(defcustom magit-refs-sections-hook + '(magit-insert-error-header + magit-insert-branch-description + magit-insert-local-branches + magit-insert-remote-branches + magit-insert-tags) + "Hook run to insert sections into a references buffer." + :package-version '(magit . "2.1.0") + :group 'magit-refs + :type 'hook) + +(defcustom magit-refs-show-commit-count nil + "Whether to show commit counts in Magit-Refs mode buffers. + +all Show counts for branches and tags. +branch Show counts for branches only. +nil Never show counts. + +To change the value in an existing buffer use the command +`magit-refs-show-commit-count'" + :package-version '(magit . "2.1.0") + :group 'magit-refs + :safe (lambda (val) (memq val '(all branch nil))) + :type '(choice (const all :tag "For branches and tags") + (const branch :tag "For branches only") + (const nil :tag "Never"))) +(put 'magit-refs-show-commit-count 'safe-local-variable 'symbolp) +(put 'magit-refs-show-commit-count 'permanent-local t) + +(defcustom magit-refs-pad-commit-counts nil + "Whether to pad all counts on all sides in `magit-refs-mode' buffers. + +If this is nil, then some commit counts are displayed right next +to one of the branches that appear next to the count, without any +space in between. This might look bad if the branch name faces +look too similar to `magit-dimmed'. + +If this is non-nil, then spaces are placed on both sides of all +commit counts." + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type 'boolean) + +(defvar magit-refs-show-push-remote nil + "Whether to show the push-remotes of local branches. +Also show the commits that the local branch is ahead and behind +the push-target. Unfortunately there is a bug in Git that makes +this useless (the commits ahead and behind the upstream are +shown), so this isn't enabled yet.") + +(defcustom magit-refs-show-remote-prefix nil + "Whether to show the remote prefix in lists of remote branches. + +This is redundant because the name of the remote is already shown +in the heading preceeding the list of its branches." + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type 'boolean) + +(defcustom magit-refs-margin + (list nil + (nth 1 magit-log-margin) + 'magit-log-margin-width nil + (nth 4 magit-log-margin)) + "Format of the margin in `magit-refs-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the committer date. It can be one + of `age' (to show the age of the commit), `age-abbreviated' (to + abbreviate the time unit to a character), or a string (suitable + for `format-time-string') to show the actual date. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-refs + :group 'magit-margin + :safe (lambda (val) (memq val '(all branch nil))) + :type magit-log-margin--custom-type + :initialize 'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-refs-mode)) + +(defcustom magit-refs-margin-for-tags nil + "Whether to show information about tags in the margin. + +This is disabled by default because it is slow if there are many +tags." + :package-version '(magit . "2.9.0") + :group 'magit-refs + :group 'magit-margin + :type 'boolean) + +(defcustom magit-refs-primary-column-width (cons 16 32) + "Width of the focus column in `magit-refs-mode' buffers. + +The primary column is the column that contains the name of the +branch that the current row is about. + +If this is an integer, then the column is that many columns wide. +Otherwise it has to be a cons-cell of two integers. The first +specifies the minimal width, the second the maximal width. In that +case the actual width is determined using the length of the names +of the shown local branches. (Remote branches and tags are not +taken into account when calculating to optimal width.)" + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type '(choice (integer :tag "Constant wide") + (cons :tag "Wide constrains" + (integer :tag "Minimum") + (integer :tag "Maximum")))) + +(defcustom magit-refs-focus-column-width 5 + "Width of the focus column in `magit-refs-mode' buffers. + +The focus column is the first column, which marks one +branch (usually the current branch) as the focused branch using +\"*\" or \"@\". For each other reference, this column optionally +shows how many commits it is ahead of the focused branch and \"<\", or +if it isn't ahead then the commits it is behind and \">\", or if it +isn't behind either, then a \"=\". + +This column may also display only \"*\" or \"@\" for the focused +branch, in which case this option is ignored. Use \"L v\" to +change the verbosity of this column." + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type 'integer) + +(defcustom magit-refs-filter-alist nil + "Alist controlling which refs are omitted from `magit-refs-mode' buffers. + +All keys are tried in order until one matches. Then its value +is used and subsequent elements are ignored. If the value is +non-nil, then the reference is displayed, otherwise it is not. +If no element matches, then the reference is displayed. + +A key can either be a regular expression that the refname has +to match, or a function that takes the refname as only argument +and returns a boolean. Contrary to how they are displayed in +the buffer, for comparison each tag begins with \"tags/\" and +each remote branch with \"/\"." + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type '(alist :key-type (choice :tag "Key" regexp function) + :value-type (boolean :tag "Value" + :on "show (non-nil)" + :off "omit (nil)"))) + +(defcustom magit-visit-ref-behavior nil + "Control how `magit-visit-ref' behaves in `magit-refs-mode' buffers. + +By default `magit-visit-ref' behaves like `magit-show-commit', +in all buffers, including `magit-refs-mode' buffers. When the +type of the section at point is `commit' then \"RET\" is bound to +`magit-show-commit', and when the type is either `branch' or +`tag' then it is bound to `magit-visit-ref'. + +\"RET\" is one of Magit's most essential keys and at least by +default it should behave consistently across all of Magit, +especially because users quickly learn that it does something +very harmless; it shows more information about the thing at point +in another buffer. + +However \"RET\" used to behave differently in `magit-refs-mode' +buffers, doing surprising things, some of which cannot really be +described as \"visit this thing\". If you have grown accustomed +to such inconsistent, but to you useful, behavior, then you can +restore that by adding one or more of the below symbols to the +value of this option. But keep in mind that by doing so you +don't only introduce inconsistencies, you also lose some +functionality and might have to resort to `M-x magit-show-commit' +to get it back. + +`magit-visit-ref' looks for these symbols in the order in which +they are described here. If the presence of a symbol applies to +the current situation, then the symbols that follow do not affect +the outcome. + +`focus-on-ref' + + With a prefix argument update the buffer to show commit counts + and lists of cherry commits relative to the reference at point + instead of relative to the current buffer or `HEAD'. + + Instead of adding this symbol, consider pressing \"C-u y o RET\". + +`create-branch' + + If point is on a remote branch, then create a new local branch + with the same name, use the remote branch as its upstream, and + then check out the local branch. + + Instead of adding this symbol, consider pressing \"b c RET RET\", + like you would do in other buffers. + +`checkout-any' + + Check out the reference at point. If that reference is a tag + or a remote branch, then this results in a detached `HEAD'. + + Instead of adding this symbol, consider pressing \"b b RET\", + like you would do in other buffers. + +`checkout-branch' + + Check out the local branch at point. + + Instead of adding this symbol, consider pressing \"b b RET\", + like you would do in other buffers." + :package-version '(magit . "2.9.0") + :group 'magit-refs + :group 'magit-commands + :options '(focus-on-ref create-branch checkout-any checkout-branch) + :type '(list :convert-widget custom-hook-convert-widget)) + +;;; Mode + +(defvar magit-refs-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-mode-map) + (define-key map "\C-y" 'magit-refs-set-show-commit-count) + (define-key map "L" 'magit-margin-popup) + map) + "Keymap for `magit-refs-mode'.") + +(define-derived-mode magit-refs-mode magit-mode "Magit Refs" + "Mode which lists and compares references. + +This mode is documented in info node `(magit)References Buffer'. + +\\\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-section-toggle] to expand or hide the section at point. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit or branch at point. + +Type \\[magit-branch-popup] to see available branch commands. +Type \\[magit-merge-popup] to merge the branch or commit at point. +Type \\[magit-cherry-pick-popup] to apply the commit at point. +Type \\[magit-reset] to reset `HEAD' to the commit at point. + +\\{magit-refs-mode-map}" + :group 'magit-refs + (hack-dir-local-variables-non-file-buffer) + (setq imenu-create-index-function + #'magit-imenu--refs-create-index-function) + (setq-local bookmark-make-record-function + #'magit-bookmark--refs-make-record)) + +(defun magit-refs-refresh-buffer (ref &optional args) + (setq magit-set-buffer-margin-refresh (not (magit-buffer-margin-p))) + (unless ref + (setq ref "HEAD")) + (unless (magit-rev-verify ref) + (setq magit-refs-show-commit-count nil)) + (magit-set-header-line-format + (format "%s %s" ref (mapconcat #'identity args " "))) + (magit-insert-section (branchbuf) + (magit-run-section-hook 'magit-refs-sections-hook)) + (add-hook 'kill-buffer-hook 'magit-preserve-section-visibility-cache)) + +;;; Commands + +(defcustom magit-show-refs-arguments nil + "The arguments used in `magit-refs-mode' buffers." + :group 'magit-git-arguments + :group 'magit-refs + :type '(repeat (string :tag "Argument"))) + +(defvar magit-show-refs-popup + (list + :variable 'magit-show-refs-arguments + :man-page "git-branch" + :switches '((?m "Merged to HEAD" "--merged") + (?M "Merged to master" "--merged=master") + (?n "Not merged to HEAD" "--no-merged") + (?N "Not merged to master" "--no-merged=master")) + :options '((?c "Contains" "--contains=" magit-read-branch-or-commit) + (?m "Merged" "--merged=" magit-read-branch-or-commit) + (?n "Not merged" "--no-merged=" magit-read-branch-or-commit) + (?s "Sort" "--sort=" magit-read-ref-sort)) + :actions '((?y "Show refs, comparing them with HEAD" + magit-show-refs-head) + (?c "Show refs, comparing them with current branch" + magit-show-refs-current) + (?o "Show refs, comparing them with other branch" + magit-show-refs)) + :default-action 'magit-show-refs-head + :max-action-columns 1 + :use-prefix (lambda () + (if (derived-mode-p 'magit-refs-mode) + (if current-prefix-arg 'popup 'default) + 'popup)))) + +(magit-define-popup-keys-deferred 'magit-show-refs-popup) + +(defun magit-read-ref-sort (prompt initial-input) + (magit-completing-read prompt + '("-committerdate" "-authordate" + "committerdate" "authordate") + nil nil initial-input)) + +(defun magit-show-refs-get-buffer-args () + (cond ((and magit-use-sticky-arguments + (derived-mode-p 'magit-refs-mode)) + (cadr magit-refresh-args)) + ((and (eq magit-use-sticky-arguments t) + (--when-let (magit-mode-get-buffer 'magit-refs-mode) + (with-current-buffer it + (cadr magit-refresh-args))))) + (t + (default-value 'magit-show-refs-arguments)))) + +(defun magit-show-refs-arguments () + (if (eq magit-current-popup 'magit-show-refs-popup) + magit-current-popup-args + (magit-show-refs-get-buffer-args))) + +;;;###autoload +(defun magit-show-refs-popup (&optional arg) + "Popup console for `magit-show-refs'." + (interactive "P") + (let ((magit-show-refs-arguments (magit-show-refs-get-buffer-args))) + (magit-invoke-popup 'magit-show-refs-popup nil arg))) + +;;;###autoload +(defun magit-show-refs-head (&optional args) + "List and compare references in a dedicated buffer. +Refs are compared with `HEAD'." + (interactive (list (magit-show-refs-arguments))) + (magit-show-refs nil args)) + +;;;###autoload +(defun magit-show-refs-current (&optional args) + "List and compare references in a dedicated buffer. +Refs are compared with the current branch or `HEAD' if +it is detached." + (interactive (list (magit-show-refs-arguments))) + (magit-show-refs (magit-get-current-branch) args)) + +;;;###autoload +(defun magit-show-refs (&optional ref args) + "List and compare references in a dedicated buffer. +Refs are compared with a branch read from the user." + (interactive (list (magit-read-other-branch "Compare with") + (magit-show-refs-arguments))) + (magit-mode-setup #'magit-refs-mode ref args)) + +(defun magit-refs-set-show-commit-count () + "Change for which refs the commit count is shown." + (interactive) + (setq-local magit-refs-show-commit-count + (magit-read-char-case "Show commit counts for " nil + (?a "[a]ll refs" 'all) + (?b "[b]ranches only" t) + (?n "[n]othing" nil))) + (magit-refresh)) + +(defun magit-visit-ref () + "Visit the reference or revision at point in another buffer. +If there is no revision at point or with a prefix argument prompt +for a revision. + +This command behaves just like `magit-show-commit', except if +point is on a reference in a `magit-refs-mode' buffer (a buffer +listing branches and tags), in which case the behavior may be +different, but only if you have customized the option +`magit-visit-ref-behavior' (which see)." + (interactive) + (if (and (derived-mode-p 'magit-refs-mode) + (magit-section-match '(branch tag))) + (let ((ref (oref (magit-current-section) value))) + (cond (current-prefix-arg + (cond ((memq 'focus-on-ref magit-visit-ref-behavior) + (magit-show-refs ref)) + (magit-visit-ref-behavior + ;; Don't prompt for commit to visit. + (let ((current-prefix-arg nil)) + (call-interactively #'magit-show-commit))))) + ((and (memq 'create-branch magit-visit-ref-behavior) + (magit-section-match [branch remote])) + (let ((branch (cdr (magit-split-branch-name ref)))) + (if (magit-branch-p branch) + (if (magit-rev-eq branch ref) + (magit-call-git "checkout" branch) + (setq branch (propertize branch 'face 'magit-branch-local)) + (setq ref (propertize ref 'face 'magit-branch-remote)) + (pcase (prog1 (read-char-choice (format (propertize "\ +Branch %s already exists. + [c]heckout %s as-is + [r]reset %s to %s and checkout %s + [a]bort " 'face 'minibuffer-prompt) branch branch branch ref branch) + '(?c ?r ?a)) + (message "")) ; otherwise prompt sticks + (?c (magit-call-git "checkout" branch)) + (?r (magit-call-git "checkout" "-B" branch ref)) + (?a (user-error "Abort")))) + (magit-call-git "checkout" "-b" branch ref)) + (setcar magit-refresh-args branch) + (magit-refresh))) + ((or (memq 'checkout-any magit-visit-ref-behavior) + (and (memq 'checkout-branch magit-visit-ref-behavior) + (magit-section-match [branch local]))) + (magit-call-git "checkout" ref) + (setcar magit-refresh-args ref) + (magit-refresh)) + (t + (call-interactively #'magit-show-commit)))) + (call-interactively #'magit-show-commit))) + +;;; Sections + +(defvar magit-remote-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-delete-thing] 'magit-remote-remove) + (define-key map "R" 'magit-remote-rename) + map) + "Keymap for `remote' sections.") + +(defvar magit-branch-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-visit-ref) + (define-key map [remap magit-delete-thing] 'magit-branch-delete) + (define-key map "R" 'magit-branch-rename) + map) + "Keymap for `branch' sections.") + +(defvar magit-tag-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-visit-ref) + (define-key map [remap magit-delete-thing] 'magit-tag-delete) + map) + "Keymap for `tag' sections.") + +(defun magit-insert-branch-description () + "Insert header containing the description of the current branch. +Insert a header line with the name and description of the +current branch. The description is taken from the Git variable +`branch..description'; if that is undefined then no header +line is inserted at all." + (when-let ((branch (magit-get-current-branch)) + (desc (magit-get "branch" branch "description")) + (desc (split-string desc "\n"))) + (when (equal (car (last desc)) "") + (setq desc (butlast desc))) + (magit-insert-section (branchdesc branch t) + (magit-insert-heading branch ": " (car desc)) + (when (cdr desc) + (insert (mapconcat 'identity (cdr desc) "\n")) + (insert "\n\n"))))) + +(defun magit-insert-tags () + "Insert sections showing all tags." + (when-let ((tags (magit-git-lines "tag" "--list" "-n" + (cadr magit-refresh-args)))) + (let ((_head (magit-rev-parse "HEAD"))) + (magit-insert-section (tags) + (magit-insert-heading "Tags:") + (dolist (tag tags) + (string-match "^\\([^ \t]+\\)[ \t]+\\([^ \t\n].*\\)?" tag) + (let ((tag (match-string 1 tag)) + (msg (match-string 2 tag))) + (when (magit-refs--insert-refname-p tag) + (magit-insert-section section (tag tag t) + (magit-insert-heading + (magit-refs--format-focus-column tag 'tag) + (propertize tag 'face 'magit-tag) + (make-string (max 1 (- magit-refs-primary-column-width + (length tag))) + ?\s) + (and msg (magit-log-propertize-keywords nil msg))) + (when (and magit-refs-margin-for-tags (magit-buffer-margin-p)) + (magit-refs--format-margin tag)) + (magit-refs--insert-cherry-commits tag section))))) + (insert ?\n) + (magit-make-margin-overlay nil t))))) + +(defun magit-insert-remote-branches () + "Insert sections showing all remote-tracking branches." + (dolist (remote (magit-list-remotes)) + (magit-insert-section (remote remote) + (magit-insert-heading + (let ((pull (magit-get "remote" remote "url")) + (push (magit-get "remote" remote "pushurl"))) + (format (propertize "Remote %s (%s):" 'face 'magit-section-heading) + (propertize remote 'face 'magit-branch-remote) + (concat pull (and pull push ", ") push)))) + (let (head) + (dolist (line (magit-git-lines "for-each-ref" "--format=\ +%(symref:short)%00%(refname:short)%00%(refname)%00%(subject)" + (concat "refs/remotes/" remote) + (cadr magit-refresh-args))) + (pcase-let ((`(,head-branch ,branch ,ref ,msg) + (-replace "" nil (split-string line "\0")))) + (if head-branch + (progn (cl-assert (equal branch (concat remote "/HEAD"))) + (setq head head-branch)) + (when (magit-refs--insert-refname-p branch) + (magit-insert-section section (branch branch t) + (let ((headp (equal branch head)) + (abbrev (if magit-refs-show-remote-prefix + branch + (substring branch (1+ (length remote)))))) + (magit-insert-heading + (magit-refs--format-focus-column branch) + (magit-refs--propertize-branch + abbrev ref (and headp 'magit-branch-remote-head)) + (make-string (max 1 (- magit-refs-primary-column-width + (length abbrev))) + ?\s) + (and msg (magit-log-propertize-keywords nil msg)))) + (when (magit-buffer-margin-p) + (magit-refs--format-margin branch)) + (magit-refs--insert-cherry-commits branch section))))))) + (insert ?\n) + (magit-make-margin-overlay nil t)))) + +(defun magit-insert-local-branches () + "Insert sections showing all local branches." + (magit-insert-section (local nil) + (magit-insert-heading "Branches:") + (dolist (line (magit-refs--format-local-branches)) + (pcase-let ((`(,branch . ,strings) line)) + (magit-insert-section section + ((eval (if branch 'branch 'commit)) + (or branch (magit-rev-parse "HEAD")) + t) + (apply #'magit-insert-heading strings) + (when (magit-buffer-margin-p) + (magit-refs--format-margin branch)) + (magit-refs--insert-cherry-commits branch section)))) + (insert ?\n) + (magit-make-margin-overlay nil t))) + +(defun magit-refs--format-local-branches () + (let ((lines (-keep 'magit-refs--format-local-branch + (magit-git-lines + "for-each-ref" + (concat "--format=\ +%(HEAD)%00%(refname:short)%00%(refname)%00\ +%(upstream:short)%00%(upstream)%00%(upstream:track)%00" + (if magit-refs-show-push-remote "\ +%(push:remotename)%00%(push)%00%(push:track)%00%(subject)" + "%00%00%00%(subject)")) + "refs/heads" + (cadr magit-refresh-args))))) + (unless (magit-get-current-branch) + (push (magit-refs--format-local-branch + (concat "*\0\0\0\0\0\0\0\0" (magit-rev-format "%s"))) + lines)) + (setq-local magit-refs-primary-column-width + (let ((def (default-value 'magit-refs-primary-column-width))) + (if (atom def) + def + (pcase-let ((`(,min . ,max) def)) + (min max (apply #'max min (mapcar #'car lines))))))) + (mapcar (pcase-lambda (`(,_ ,branch ,focus ,branch-desc ,u:ahead ,p:ahead + ,u:behind ,upstream ,p:behind ,push ,msg)) + (list branch focus branch-desc u:ahead p:ahead + (make-string (max 1 (- magit-refs-primary-column-width + (length (concat branch-desc + u:ahead + p:ahead + u:behind)))) + ?\s) + u:behind upstream p:behind push + msg)) + lines))) + +(defun magit-refs--format-local-branch (line) + (pcase-let ((`(,head ,branch ,ref ,upstream ,u:ref ,u:track + ,push ,p:ref ,p:track ,msg) + (-replace "" nil (split-string line "\0")))) + (when (or (not branch) + (magit-refs--insert-refname-p branch)) + (let* ((headp (equal head "*")) + (pushp (and push + magit-refs-show-push-remote + (magit-rev-verify p:ref) + (not (equal p:ref u:ref)))) + (branch-desc + (if branch + (magit-refs--propertize-branch + branch ref (and headp 'magit-branch-current)) + (propertize "(detached)" 'face 'font-lock-warning-face))) + (u:ahead (and u:track + (string-match "ahead \\([0-9]+\\)" u:track) + (propertize + (concat (and magit-refs-pad-commit-counts " ") + (match-string 1 u:track) + ">") + 'face 'magit-dimmed))) + (u:behind (and u:track + (string-match "behind \\([0-9]+\\)" u:track) + (propertize + (concat "<" + (match-string 1 u:track) + (and magit-refs-pad-commit-counts " ")) + 'face 'magit-dimmed))) + (p:ahead (and pushp p:track + (string-match "ahead \\([0-9]+\\)" p:track) + (propertize + (concat (match-string 1 p:track) + ">" + (and magit-refs-pad-commit-counts " ")) + 'face 'magit-branch-remote))) + (p:behind (and pushp p:track + (string-match "behind \\([0-9]+\\)" p:track) + (propertize + (concat "<" + (match-string 1 p:track) + (and magit-refs-pad-commit-counts " ")) + 'face 'magit-dimmed)))) + (list (1+ (length (concat branch-desc u:ahead p:ahead u:behind))) + branch + (magit-refs--format-focus-column branch headp) + branch-desc u:ahead p:ahead u:behind + (and upstream + (concat (if (equal u:track "[gone]") + (propertize upstream 'face 'error) + (magit-refs--propertize-branch upstream u:ref)) + " ")) + (and pushp + (concat p:behind + (propertize push 'face 'magit-branch-remote) + " ")) + (and msg (magit-log-propertize-keywords nil msg))))))) + +(defun magit-refs--format-focus-column (ref &optional type) + (let ((focus (car magit-refresh-args)) + (width (if magit-refs-show-commit-count + magit-refs-focus-column-width + 1))) + (format + (format "%%%ss " width) + (cond ((or (equal ref focus) + (and (eq type t) + (eq focus nil))) + (propertize (concat (if focus "@" "*") + (make-string (1- width) ?\s)) + 'face 'magit-section-heading)) + ((if (eq type 'tag) + (eq magit-refs-show-commit-count 'all) + magit-refs-show-commit-count) + (pcase-let ((`(,behind ,ahead) + (magit-rev-diff-count + (or (car magit-refresh-args) "HEAD") + ref))) + (propertize + (cond ((> ahead 0) (concat "<" (number-to-string ahead))) + ((> behind 0) (concat (number-to-string behind) ">")) + (t "=")) + 'face 'magit-dimmed))) + (t ""))))) + +(defun magit-refs--propertize-branch (branch ref &optional head-face) + (let ((face (cdr (cl-find-if (pcase-lambda (`(,re . ,_)) + (string-match-p re ref)) + magit-ref-namespaces)))) + (propertize branch 'face (if head-face (list face head-face) face)))) + +(defun magit-refs--insert-refname-p (refname) + (--if-let (-first (pcase-lambda (`(,key . ,_)) + (if (functionp key) + (funcall key refname) + (string-match-p key refname))) + magit-refs-filter-alist) + (cdr it) + t)) + +(defun magit-refs--insert-cherry-commits (ref section) + (if (oref section hidden) + (oset section washer + (apply-partially #'magit-refs--insert-cherry-commits-1 ref section)) + (magit-refs--insert-cherry-commits-1 ref section))) + +(defun magit-refs--insert-cherry-commits-1 (ref _section) + (let ((start (point)) + (magit-insert-section--current nil)) + (magit-git-wash (apply-partially 'magit-log-wash-log 'cherry) + "cherry" "-v" (magit-abbrev-arg) + (or (car magit-refresh-args) "HEAD") + ref magit-refresh-args) + (unless (= (point) start) + (magit-make-margin-overlay nil t)))) + +(defun magit-refs--format-margin (commit) + (save-excursion + (goto-char (line-beginning-position 0)) + (let ((line (magit-rev-format "%ct%cN" commit))) + (magit-log-format-margin commit + (substring line 10) + (substring line 0 10))))) + +;;; _ +(provide 'magit-refs) +;;; magit-refs.el ends here diff --git a/elpa/magit-20181113.1837/magit-remote.el b/elpa/magit-20181113.1837/magit-remote.el new file mode 100644 index 00000000..5f80452a --- /dev/null +++ b/elpa/magit-20181113.1837/magit-remote.el @@ -0,0 +1,376 @@ +;;; magit-remote.el --- transfer Git commits -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements remote commands. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-remote-add-set-remote.pushDefault 'ask-if-unset + "Whether to set the value of `remote.pushDefault' after adding a remote. + +If `ask', then always ask. If `ask-if-unset', then ask, but only +if the variable isn't set already. If nil, then don't ever set. +If the value is a string, then set without asking, provided that +the name of the added remote is equal to that string and the +variable isn't already set." + :package-version '(magit . "2.4.0") + :group 'magit-commands + :type '(choice (const :tag "ask if unset" ask-if-unset) + (const :tag "always ask" ask) + (string :tag "set if named") + (const :tag "don't set"))) + +(defcustom magit-remote-popup-show-variables t + "Whether the `magit-remote-popup' shows Git variables. +When set to nil, no variables are displayed directly in this +popup, instead the sub-popup `magit-remote-config-popup' has +to be used to view and change remote related variables." + :package-version '(magit . "2.12.0") + :group 'magit-commands + :type 'boolean) + +;;; Commands + +(defvar magit-remote-config-variables) + +;;;###autoload (autoload 'magit-remote-popup "magit-remote" nil t) +(magit-define-popup magit-remote-popup + "Popup console for remote commands." + :man-page "git-remote" + :default-arguments '("-f") + :variables (lambda () + (and magit-remote-popup-show-variables + magit-remote-config-variables)) + :switches '("Switches for add" + (?f "Fetch after add" "-f")) + :actions '((?a "Add" magit-remote-add) + (?C "Configure..." magit-remote-config-popup) + (?r "Rename" magit-remote-rename) + (?p "Prune stale branches" magit-remote-prune) + (?k "Remove" magit-remote-remove) + (?P "Prune stale refspecs" magit-remote-prune-refspecs)) + :max-action-columns 2) + +(defun magit-read-url (prompt &optional initial-input) + (let ((url (magit-read-string-ns prompt initial-input))) + (if (string-prefix-p "~" url) + (expand-file-name url) + url))) + +;;;###autoload +(defun magit-remote-add (remote url &optional args) + "Add a remote named REMOTE and fetch it." + (interactive (list (magit-read-string-ns "Remote name") + (magit-read-url "Remote url") + (magit-remote-arguments))) + (if (pcase (list magit-remote-add-set-remote.pushDefault + (magit-get "remote.pushDefault")) + (`(,(pred stringp) ,_) t) + ((or `(ask ,_) `(ask-if-unset nil)) + (y-or-n-p (format "Set `remote.pushDefault' to \"%s\"? " remote)))) + (progn (magit-call-git "remote" "add" args remote url) + (setf (magit-get "remote.pushDefault") remote) + (magit-refresh)) + (magit-run-git-async "remote" "add" args remote url))) + +;;;###autoload +(defun magit-remote-rename (old new) + "Rename the remote named OLD to NEW." + (interactive + (let ((remote (magit-read-remote "Rename remote"))) + (list remote (magit-read-string-ns (format "Rename %s to" remote))))) + (unless (string= old new) + (magit-call-git "remote" "rename" old new) + (magit-remote--cleanup-push-variables old new) + (magit-refresh))) + +;;;###autoload +(defun magit-remote-remove (remote) + "Delete the remote named REMOTE." + (interactive (list (magit-read-remote "Delete remote"))) + (magit-call-git "remote" "rm" remote) + (magit-remote--cleanup-push-variables remote) + (magit-refresh)) + +(defun magit-remote--cleanup-push-variables (remote &optional new-name) + (magit-with-toplevel + (when (equal (magit-get "remote.pushDefault") remote) + (magit-set new-name "remote.pushDefault")) + (dolist (var (magit-git-lines "config" "--name-only" + "--get-regexp" "^branch\.[^.]*\.pushRemote" + (format "^%s$" remote))) + (magit-call-git "config" (and (not new-name) "--unset") var new-name)))) + +(defconst magit--refspec-re "\\`\\(\\+\\)?\\([^:]+\\):\\(.*\\)\\'") + +;;;###autoload +(defun magit-remote-prune (remote) + "Remove stale remote-tracking branches for REMOTE." + (interactive (list (magit-read-remote "Prune stale branches of remote"))) + (magit-run-git-async "remote" "prune" remote)) + +;;;###autoload +(defun magit-remote-prune-refspecs (remote) + "Remove stale refspecs for REMOTE. + +A refspec is stale if there no longer exists at least one branch +on the remote that would be fetched due to that refspec. A stale +refspec is problematic because its existence causes Git to refuse +to fetch according to the remaining non-stale refspecs. + +If only stale refspecs remain, then offer to either delete the +remote or to replace the stale refspecs with the default refspec. + +Also remove the remote-tracking branches that were created due to +the now stale refspecs. Other stale branches are not removed." + (interactive (list (magit-read-remote "Prune refspecs of remote"))) + (let* ((tracking-refs (magit-list-remote-branches remote)) + (remote-refs (magit-remote-list-refs remote)) + (variable (format "remote.%s.fetch" remote)) + (refspecs (magit-get-all variable)) + stale) + (dolist (refspec refspecs) + (when (string-match magit--refspec-re refspec) + (let ((theirs (match-string 2 refspec)) + (ours (match-string 3 refspec))) + (unless (if (string-match "\\*" theirs) + (let ((re (replace-match ".*" t t theirs))) + (--some (string-match-p re it) remote-refs)) + (member theirs remote-refs)) + (push (cons refspec + (if (string-match "\\*" ours) + (let ((re (replace-match ".*" t t ours))) + (--filter (string-match-p re it) tracking-refs)) + (list (car (member ours tracking-refs))))) + stale))))) + (if (not stale) + (message "No stale refspecs for remote %S" remote) + (if (= (length stale) + (length refspecs)) + (magit-read-char-case + (format "All of %s's refspecs are stale. " remote) nil + (?s "replace with [d]efault refspec" + (magit-set-all + (list (format "+refs/heads/*:refs/remotes/%s/*" remote)) + variable)) + (?r "[r]emove remote" + (magit-call-git "remote" "rm" remote)) + (?a "or [a]abort" + (user-error "Abort"))) + (if (if (= (length stale) 1) + (pcase-let ((`(,refspec . ,refs) (car stale))) + (magit-confirm 'prune-stale-refspecs + (format "Prune stale refspec %s and branch %%s" refspec) + (format "Prune stale refspec %s and %%i branches" refspec) + nil refs)) + (magit-confirm 'prune-stale-refspecs nil + (format "Prune %%i stale refspecs and %i branches" + (length (cl-mapcan (lambda (s) (copy-sequence (cdr s))) + stale))) + nil + (mapcar (pcase-lambda (`(,refspec . ,refs)) + (concat refspec "\n" + (mapconcat (lambda (b) (concat " " b)) + refs "\n"))) + stale))) + (pcase-dolist (`(,refspec . ,refs) stale) + (magit-call-git "config" "--unset" variable + (regexp-quote refspec)) + (magit--log-action + (lambda (refs) + (format "Deleting %i branches" (length refs))) + (lambda (ref) + (format "Deleting branch %s (was %s)" ref + (magit-rev-parse "--short" ref))) + refs) + (dolist (ref refs) + (magit-call-git "update-ref" "-d" ref))) + (user-error "Abort"))) + (magit-refresh)))) + +;;;###autoload +(defun magit-remote-set-head (remote &optional branch) + "Set the local representation of REMOTE's default branch. +Query REMOTE and set the symbolic-ref refs/remotes//HEAD +accordingly. With a prefix argument query for the branch to be +used, which allows you to select an incorrect value if you fancy +doing that." + (interactive + (let ((remote (magit-read-remote "Set HEAD for remote"))) + (list remote + (and current-prefix-arg + (magit-read-remote-branch (format "Set %s/HEAD to" remote) + remote nil nil t))))) + (magit-run-git "remote" "set-head" remote (or branch "--auto"))) + +;;;###autoload +(defun magit-remote-unset-head (remote) + "Unset the local representation of REMOTE's default branch. +Delete the symbolic-ref \"refs/remotes//HEAD\"." + (interactive (list (magit-read-remote "Unset HEAD for remote"))) + (magit-run-git "remote" "set-head" remote "--delete")) + +;;; Configure + +(defvar magit-remote-config--remote nil) + +;;;###autoload +(defun magit-remote-config-popup (remote) + "Popup console for setting remote variables." + (interactive + (list (if (or current-prefix-arg + (and (eq magit-current-popup 'magit-remote-popup) + magit-remote-popup-show-variables)) + (magit-read-remote "Configure remote") + (magit-remote-config--remote-1)))) + (let ((magit-remote-config--remote remote)) + (magit-invoke-popup 'magit-remote-config-popup nil nil))) + +(defvar magit-remote-config-variables + '((lambda () + (concat + (propertize "Configure " 'face 'magit-popup-heading) + (propertize (magit-remote-config--remote) 'face 'magit-branch-remote))) + (?u "remote.%s.url" + magit-set-remote*url + magit-format-remote*url) + (?U "remote.%s.fetch" + magit-set-remote*fetch + magit-format-remote*fetch) + (?s "remote.%s.pushurl" + magit-set-remote*pushurl + magit-format-remote*pushurl) + (?S "remote.%s.push" + magit-set-remote*push + magit-format-remote*push) + (?O "remote.%s.tagOpt" + magit-cycle-remote*tagOpt + magit-format-remote*tagOpt))) + +(defvar magit-remote-config-popup + `(:man-page "git-remote" + :variables ,magit-remote-config-variables + :setup-function magit-remote-config-popup-setup)) + +(defun magit-remote-config-popup-setup (val def) + (magit-popup-default-setup val def) + (setq-local magit-remote-config--remote magit-remote-config--remote)) + +(defun magit-remote-config--remote (&optional prompt) + (if prompt + (or (and (not current-prefix-arg) + (or magit-remote-config--remote + (magit-remote-config--remote-1))) + (magit-read-remote prompt)) + (or magit-remote-config--remote + (magit-remote-config--remote-1) + ""))) + +(defun magit-remote-config--remote-1 () + (let ((remote (magit-get-upstream-remote))) + (if (or (not remote) + (equal remote ".")) + (and (magit-remote-p "origin") "origin") + remote))) + +(defun magit-set-remote*url (remote urls) + "Set the variable `url' for the remote named REMOTE to URLS." + (interactive (magit-remote-config--read-args "url" "Urls: ")) + (magit-remote-config--set-url remote "url" urls)) + +(defun magit-set-remote*fetch (remote values) + "Set the variable `fetch' for the remote named REMOTE to VALUES." + (interactive (magit-remote-config--read-args "fetch" "Fetch specs: ")) + (magit-set-all values "remote" remote "fetch") + (magit-refresh)) + +(defun magit-set-remote*pushurl (remote urls) + "Set the variable `pushurl' for the remote named REMOTE to URLS." + (interactive (magit-remote-config--read-args "pushurl" "Urls: ")) + (magit-remote-config--set-url remote "pushurl" urls "--push")) + +(defun magit-set-remote*push (remote values) + "Set the variable `push' for the remote named REMOTE to VALUES." + (interactive (magit-remote-config--read-args "push" "Push specs: ")) + (magit-set-all values "remote" remote "push") + (magit-refresh)) + +(defun magit-cycle-remote*tagOpt (remote) + (interactive (list (magit-remote-config--remote))) + (magit--set-popup-variable (format "remote.%s.tagOpt" remote) + '("--no-tags" "--tags") nil)) + +(defun magit-format-remote*url () + (magit-remote-config--format-variable "url")) + +(defun magit-format-remote*fetch () + (magit-remote-config--format-variable "fetch")) + +(defun magit-format-remote*pushurl () + (magit-remote-config--format-variable "pushurl")) + +(defun magit-format-remote*push () + (magit-remote-config--format-variable "push")) + +(defun magit-format-remote*tagOpt () + (let ((remote (magit-remote-config--remote))) + (magit--format-popup-variable:choices + (format "remote.%s.tagOpts" remote) + '("--no-tags" "--tags") nil nil + (+ (length remote) 16)))) + +(defun magit-remote-config--read-args (var prompt) + (let* ((remote (magit-remote-config--remote (format "Set `%s' of remote" var))) + (value (magit-get-all "remote" remote var))) + (list remote + (mapcar (lambda (url) + (if (string-prefix-p "~" url) + (expand-file-name url) + url)) + (completing-read-multiple + prompt nil nil nil + (and value (mapconcat #'identity value ","))))))) + +(defun magit-remote-config--set-url (remote var values &optional arg) + (let ((old (magit-get-all "remote" remote var))) + (dolist (v (-difference values old)) + (magit-call-git "remote" "set-url" arg "--add" remote v)) + (dolist (v (-difference old values)) + (magit-call-git "remote" "set-url" arg "--delete" remote + (concat "^" (regexp-quote v) "$")))) + (magit-refresh)) + +(defun magit-remote-config--format-variable (variable) + (magit--format-popup-variable:values + (format "remote.%s.%s" (magit-remote-config--remote) variable) + 25)) + +;;; _ +(provide 'magit-remote) +;;; magit-remote.el ends here diff --git a/elpa/magit-20181113.1837/magit-repos.el b/elpa/magit-20181113.1837/magit-repos.el new file mode 100644 index 00000000..8db44d86 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-repos.el @@ -0,0 +1,314 @@ +;;; magit-repos.el --- listing repositories -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements support for listing repositories. This +;; includes getting a Lisp list of known repositories as well as a +;; mode for listing repositories in a buffer. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit-core) + +(declare-function magit-status-internal "magit-status" (directory)) + +(defvar x-stretch-cursor) + +;;; Options + +(defcustom magit-repository-directories + '(("~/.emacs.d/" . 0) ; this should always be a repository + ("~/.emacs.d/lib/" . 1)) ; useful for `borg' users + "List of directories that are or contain Git repositories. + +Each element has the form (DIRECTORY . DEPTH). DIRECTORY has +to be a directory or a directory file-name, a string. DEPTH, +an integer, specifies the maximum depth to look for Git +repositories. If it is 0, then only add DIRECTORY itself." + :package-version '(magit . "2.90.0") + :group 'magit-essentials + :type '(repeat (cons directory (integer :tag "Depth")))) + +(defgroup magit-repolist nil + "List repositories in a buffer." + :link '(info-link "(magit)Repository List") + :group 'magit-modes) + +(defcustom magit-repolist-mode-hook '(hl-line-mode) + "Hook run after entering Magit-Repolist mode." + :package-version '(magit . "2.9.0") + :group 'magit-repolist + :type 'hook + :get 'magit-hook-custom-get + :options '(hl-line-mode)) + +(defcustom magit-repolist-columns + '(("Name" 25 magit-repolist-column-ident nil) + ("Version" 25 magit-repolist-column-version nil) + ("BU" 3 magit-repolist-column-unpushed-to-upstream + ((:right-align t) + (:help-echo "Local changes not in upstream"))) + ("Path" 99 magit-repolist-column-path nil)) + "List of columns displayed by `magit-list-repositories'. + +Each element has the form (HEADER WIDTH FORMAT PROPS). + +HEADER is the string displayed in the header. WIDTH is the width +of the column. FORMAT is a function that is called with one +argument, the repository identification (usually its basename), +and with `default-directory' bound to the toplevel of its working +tree. It has to return a string to be inserted or nil. PROPS is +an alist that supports the keys `:right-align' and `:pad-right'. +Some entries also use `:help-echo', but `tabulated-list' does not +actually support that yet." + :package-version '(magit . "2.12.0") + :group 'magit-repolist + :type `(repeat (list :tag "Column" + (string :tag "Header Label") + (integer :tag "Column Width") + (function :tag "Inserter Function") + (repeat :tag "Properties" + (list (choice :tag "Property" + (const :right-align) + (const :pad-right) + (symbol)) + (sexp :tag "Value")))))) + + +;;; List Repositories +;;;; Command +;;;###autoload +(defun magit-list-repositories () + "Display a list of repositories. + +Use the options `magit-repository-directories' to control which +repositories are displayed." + (interactive) + (if magit-repository-directories + (with-current-buffer (get-buffer-create "*Magit Repositories*") + (magit-repolist-mode) + (magit-repolist-refresh) + (tabulated-list-print) + (switch-to-buffer (current-buffer))) + (message "You need to customize `magit-repository-directories' %s" + "before you can list repositories"))) + +;;;; Mode + +(defvar magit-repolist-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map tabulated-list-mode-map) + (define-key map (if (featurep 'jkl) [return] (kbd "C-m")) + 'magit-repolist-status) + map) + "Local keymap for Magit-Repolist mode buffers.") + +(defun magit-repolist-status (&optional _button) + "Show the status for the repository at point." + (interactive) + (--if-let (tabulated-list-get-id) + (magit-status-internal (expand-file-name it)) + (user-error "There is no repository at point"))) + +(define-derived-mode magit-repolist-mode tabulated-list-mode "Repos" + "Major mode for browsing a list of Git repositories." + (setq x-stretch-cursor nil) + (setq tabulated-list-padding 0) + (setq tabulated-list-sort-key (cons "Path" nil)) + (setq tabulated-list-format + (vconcat (mapcar (pcase-lambda (`(,title ,width ,_fn ,props)) + (nconc (list title width t) + (-flatten props))) + magit-repolist-columns))) + (tabulated-list-init-header) + (add-hook 'tabulated-list-revert-hook 'magit-repolist-refresh nil t) + (setq imenu-prev-index-position-function + 'magit-imenu--repolist-prev-index-position-function) + (setq imenu-extract-index-name-function + 'magit-imenu--repolist-extract-index-name-function)) + +(defun magit-repolist-refresh () + (setq tabulated-list-entries + (mapcar (pcase-lambda (`(,id . ,path)) + (let ((default-directory path)) + (list path + (vconcat (--map (or (funcall (nth 2 it) id) "") + magit-repolist-columns))))) + (magit-list-repos-uniquify + (--map (cons (file-name-nondirectory (directory-file-name it)) + it) + (magit-list-repos)))))) + +;;;; Columns + +(defun magit-repolist-column-ident (id) + "Insert the identification of the repository. +Usually this is just its basename." + id) + +(defun magit-repolist-column-path (_id) + "Insert the absolute path of the repository." + (abbreviate-file-name default-directory)) + +(defun magit-repolist-column-version (_id) + "Insert a description of the repository's `HEAD' revision." + (let ((v (or (magit-git-string "describe" "--tags" "--dirty") + ;; If there are no tags, use the date in MELPA format. + (magit-git-string "show" "--no-patch" "--format=%cd-g%h" + "--date=format:%Y%m%d.%H%M")))) + (save-match-data + (when (string-match "-dirty\\'" v) + (put-text-property (1+ (match-beginning 0)) (length v) 'face 'error v)) + (if (and v (string-match "\\`[0-9]" v)) + (concat " " v) + v)))) + +(defun magit-repolist-column-branch (_id) + "Insert the current branch." + (magit-get-current-branch)) + +(defun magit-repolist-column-upstream (_id) + "Insert the upstream branch of the current branch." + (magit-get-upstream-branch)) + +(defun magit-repolist-column-dirty (_id) + "Insert a letter if there are uncommitted changes. + +Show N if there is at least one untracked file. +Show U if there is at least one unstaged file. +Show S if there is at least one staged file. +Only one letter is shown, the first that applies." + (cond ((magit-untracked-files) "N") + ((magit-unstaged-files) "U") + ((magit-staged-files) "S"))) + +(defun magit-repolist-column-unpulled-from-upstream (_id) + "Insert number of upstream commits not in the current branch." + (--when-let (magit-get-upstream-branch nil t) + (let ((n (cadr (magit-rev-diff-count "HEAD" it)))) + (propertize (number-to-string n) 'face (if (> n 0) 'bold 'shadow))))) + +(defun magit-repolist-column-unpulled-from-pushremote (_id) + "Insert number of commits in the push branch but not the current branch." + (--when-let (magit-get-push-branch nil t) + (let ((n (cadr (magit-rev-diff-count "HEAD" it)))) + (propertize (number-to-string n) 'face (if (> n 0) 'bold 'shadow))))) + +(defun magit-repolist-column-unpushed-to-upstream (_id) + "Insert number of commits in the current branch but not its upstream." + (--when-let (magit-get-upstream-branch nil t) + (let ((n (car (magit-rev-diff-count "HEAD" it)))) + (propertize (number-to-string n) 'face (if (> n 0) 'bold 'shadow))))) + +(defun magit-repolist-column-unpushed-to-pushremote (_id) + "Insert number of commits in the current branch but not its push branch." + (--when-let (magit-get-push-branch nil t) + (let ((n (car (magit-rev-diff-count "HEAD" it)))) + (propertize (number-to-string n) 'face (if (> n 0) 'bold 'shadow))))) + +(defun magit-repolist-column-branches (_id) + "Insert number of branches." + (let ((n (length (magit-list-local-branches)))) + (propertize (number-to-string n) 'face (if (> n 1) 'bold 'shadow)))) + +(defun magit-repolist-column-stashes (_id) + "Insert number of stashes." + (let ((n (length (magit-list-stashes)))) + (propertize (number-to-string n) 'face (if (> n 0) 'bold 'shadow)))) + +;;; Read Repository + +(defun magit-read-repository (&optional read-directory-name) + "Read a Git repository in the minibuffer, with completion. + +The completion choices are the basenames of top-levels of +repositories found in the directories specified by option +`magit-repository-directories'. In case of name conflicts +the basenames are prefixed with the name of the respective +parent directories. The returned value is the actual path +to the selected repository. + +With prefix argument simply read a directory name using +`read-directory-name'." + (if-let ((repos (and (not read-directory-name) + magit-repository-directories + (magit-list-repos-uniquify + (--map (cons (file-name-nondirectory + (directory-file-name it)) + it) + (magit-list-repos)))))) + (let ((reply (magit-completing-read "Git repository" repos))) + (file-name-as-directory + (or (cdr (assoc reply repos)) + (if (file-directory-p reply) + (expand-file-name reply) + (user-error "Not a repository or a directory: %s" reply))))) + (file-name-as-directory + (read-directory-name "Git repository: " + (or (magit-toplevel) default-directory))))) + +(defun magit-list-repos () + (cl-mapcan (pcase-lambda (`(,dir . ,depth)) + (magit-list-repos-1 dir depth)) + magit-repository-directories)) + +(defun magit-list-repos-1 (directory depth) + (cond ((file-readable-p (expand-file-name ".git" directory)) + (list directory)) + ((and (> depth 0) (magit-file-accessible-directory-p directory)) + (--mapcat (and (file-directory-p it) + (magit-list-repos-1 it (1- depth))) + (directory-files directory t + directory-files-no-dot-files-regexp t))))) + +(defun magit-list-repos-uniquify (alist) + (let (result (dict (make-hash-table :test 'equal))) + (dolist (a (delete-dups alist)) + (puthash (car a) (cons (cdr a) (gethash (car a) dict)) dict)) + (maphash + (lambda (key value) + (if (= (length value) 1) + (push (cons key (car value)) result) + (setq result + (append result + (magit-list-repos-uniquify + (--map (cons (concat + key "\\" + (file-name-nondirectory + (directory-file-name + (substring it 0 (- (1+ (length key))))))) + it) + value)))))) + dict) + result)) + +;;; _ +(provide 'magit-repos) +;;; magit-repos.el ends here diff --git a/elpa/magit-20181113.1837/magit-reset.el b/elpa/magit-20181113.1837/magit-reset.el new file mode 100644 index 00000000..c4876499 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-reset.el @@ -0,0 +1,126 @@ +;;; magit-reset.el --- reset fuctionality -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements reset commands. + +;;; Code: + +(require 'magit) + +;;;###autoload (autoload 'magit-reset-popup "magit" nil t) +(magit-define-popup magit-reset-popup + "Popup console for reset commands." + :man-page "git-reset" + :actions '((?m "reset mixed (HEAD and index)" magit-reset-mixed) + (?s "reset soft (HEAD only)" magit-reset-soft) + (?h "reset hard (HEAD, index, and files)" magit-reset-hard) + (?i "reset index (only)" magit-reset-index) + (?w "reset worktree (only)" magit-reset-worktree) + nil + (?f "reset a file" magit-file-checkout)) + :max-action-columns 1) + +;;;###autoload +(defun magit-reset-mixed (commit) + "Reset the `HEAD' and index to COMMIT, but not the working tree. +\n(git reset --mixed COMMIT)" + (interactive (list (magit-reset-read-branch-or-commit "Reset %s to"))) + (magit-reset-internal "--mixed" commit)) + +;;;###autoload +(defun magit-reset-soft (commit) + "Reset the `HEAD' to COMMIT, but not the index and working tree. +\n(git reset --soft REVISION)" + (interactive (list (magit-reset-read-branch-or-commit "Soft reset %s to"))) + (magit-reset-internal "--soft" commit)) + +;;;###autoload +(defun magit-reset-hard (commit) + "Reset the `HEAD', index, and working tree to COMMIT. +\n(git reset --hard REVISION)" + (interactive (list (magit-reset-read-branch-or-commit + (concat (propertize "Hard" 'face 'bold) + " reset %s to")))) + (magit-reset-internal "--hard" commit)) + +;;;###autoload +(defun magit-reset-index (commit) + "Reset the index to COMMIT. +Keep the `HEAD' and working tree as-is, so if COMMIT refers to the +head this effectively unstages all changes. +\n(git reset COMMIT .)" + (interactive (list (magit-read-branch-or-commit "Reset index to"))) + (magit-reset-internal nil commit ".")) + +;;;###autoload +(defun magit-reset-worktree (commit) + "Reset the worktree to COMMIT. +Keep the `HEAD' and index as-is." + (interactive (list (magit-read-branch-or-commit "Reset worktree to"))) + (magit-with-temp-index commit nil + (magit-wip-commit-before-change nil " before reset") + (magit-run-git "checkout-index" "--all" "--force") + (magit-wip-commit-after-apply nil " after reset"))) + +;;;###autoload +(defun magit-reset-quickly (commit &optional hard) + "Reset the `HEAD' and index to COMMIT, and possibly the working tree. +With a prefix argument reset the working tree otherwise don't. +\n(git reset --mixed|--hard COMMIT)" + (interactive (list (magit-reset-read-branch-or-commit + (if current-prefix-arg + (concat (propertize "Hard" 'face 'bold) + " reset %s to") + "Reset %s to")) + current-prefix-arg)) + (magit-reset-internal (if hard "--hard" "--mixed") commit)) + +(defun magit-reset-read-branch-or-commit (prompt) + "Prompt for and return a ref to reset HEAD to. + +PROMPT is a format string, where either the current branch name +or \"detached head\" will be substituted for %s." + (magit-read-branch-or-commit + (format prompt (or (magit-get-current-branch) "detached head")))) + +(defun magit-reset-internal (arg commit &optional path) + (when (and (not (member arg '("--hard" nil))) + (equal (magit-rev-parse commit) + (magit-rev-parse "HEAD~"))) + (with-temp-buffer + (magit-git-insert "show" "-s" "--format=%B" "HEAD") + (when git-commit-major-mode + (funcall git-commit-major-mode)) + (git-commit-setup-font-lock) + (git-commit-save-message))) + (let ((cmd (if (and (equal commit "HEAD") (not arg)) "unstage" "reset"))) + (magit-wip-commit-before-change nil (concat " before " cmd)) + (magit-run-git "reset" arg commit "--" path) + (when (equal cmd "unstage") + (magit-wip-commit-after-apply nil " after unstage")))) + +;;; _ +(provide 'magit-reset) +;;; magit-reset.el ends here diff --git a/elpa/magit-20181113.1837/magit-section.el b/elpa/magit-20181113.1837/magit-section.el new file mode 100644 index 00000000..b7c4c8d4 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-section.el @@ -0,0 +1,1457 @@ +;;; magit-section.el --- section functionality -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements "sections" as used in all Magit buffers. +;; If you have used Magit before, then you probably know what that +;; means, otherwise think "read-only Org-Mode for Git", kinda. + +;;; Code: + +(require 'cl-lib) +(require 'dash) +(require 'eieio) + +(eval-when-compile + (require 'subr-x)) + +(require 'magit-utils) + +(declare-function magit-maybe-make-margin-overlay "magit-margin" ()) +(declare-function magit-repository-local-get "magit-mode" + (key &optional default repository)) +(declare-function magit-repository-local-set "magit-mode" + (key value &optional repository)) +(defvar magit-keep-region-overlay) + +;;; Options + +(defgroup magit-section nil + "Expandable sections." + :link '(info-link "(magit)Sections") + :group 'magit) + +(defcustom magit-section-show-child-count t + "Whether to append the number of children to section headings. +This only applies to sections for which doing so makes sense." + :package-version '(magit . "2.1.0") + :group 'magit-section + :type 'boolean) + +(defcustom magit-section-movement-hook + '(magit-hunk-set-window-start + magit-log-maybe-update-revision-buffer + magit-log-maybe-show-more-commits) + "Hook run by `magit-section-goto'. +That function in turn is used by all section movement commands." + :package-version '(magit . "2.3.0") + :group 'magit-section + :type 'hook + :options '(magit-hunk-set-window-start + magit-status-maybe-update-revision-buffer + magit-status-maybe-update-blob-buffer + magit-log-maybe-update-revision-buffer + magit-log-maybe-update-blob-buffer + magit-log-maybe-show-more-commits)) + +(defcustom magit-section-highlight-hook + '(magit-diff-highlight + magit-section-highlight + magit-section-highlight-selection) + "Functions used to highlight the current section. +Each function is run with the current section as only argument +until one of them returns non-nil." + :package-version '(magit . "2.1.0") + :group 'magit-section + :type 'hook + :options '(magit-diff-highlight + magit-section-highlight + magit-section-highlight-selection)) + +(defcustom magit-section-unhighlight-hook + '(magit-diff-unhighlight) + "Functions used to unhighlight the previously current section. +Each function is run with the current section as only argument +until one of them returns non-nil. Most sections are properly +unhighlighted without requiring a specialized unhighlighter, +diff-related sections being the only exception." + :package-version '(magit . "2.1.0") + :group 'magit-section + :type 'hook + :options '(magit-diff-unhighlight)) + +(defcustom magit-section-set-visibility-hook + '(magit-diff-expansion-threshold + magit-section-cached-visibility) + "Hook used to set the initial visibility of a section. +Stop at the first function that returns non-nil. The returned +value should be `show', `hide' or nil. If no function returns +non-nil, determine the visibility as usual, i.e. use the +hardcoded section specific default (see `magit-insert-section')." + :package-version '(magit . "2.4.0") + :group 'magit-section + :type 'hook + :options '(magit-diff-expansion-threshold + magit-section-cached-visibility)) + +(defcustom magit-section-cache-visibility t + "Whether to cache visibility of sections. + +Sections always retain their visibility state when they are being +recreated during a refresh. But if a section disappears and then +later reappears again, then this option controls whether this is +the case. + +If t, then cache the visibility of all sections. If a list of +section types, then only do so for matching sections. If nil, +then don't do so for any sections." + :package-version '(magit . "2.12.0") + :group 'magit-section + :type '(choice (const :tag "Don't cache visibility" nil) + (const :tag "Cache visibility of all sections" t) + (repeat :tag "Cache visibility for section types" symbol))) + +(defcustom magit-section-initial-visibility-alist + '((stashes . hide)) + "Alist controlling the initial visibility of sections. + +Each element maps a section type or lineage to the initial +visibility state for such sections. The state has to be one of +`show' or `hide', or a function that returns one of these symbols. +A function is called with the section as the only argument. + +Use the command `magit-describe-section' to determine a section's +lineage or type. The vector in the output is the section lineage +and the type is the first element of that vector. Wildcards can +be used, see `magit-section-match'. + +Currently this option is only used to override hardcoded defaults, +but in the future it will also be used set the defaults. + +An entry whose key is `magit-status-initial-section' specifies +the visibility of the section `magit-status-goto-initial-section' +jumps to. This does not only override defaults, but also other +entries of this alist." + :package-version '(magit . "2.12.0") + :group 'magit-section + :type '(alist :key-type (sexp :tag "Section type/lineage") + :value-type (choice (const hide) + (const show) + function))) + +(defface magit-section-highlight + '((((class color) (background light)) :background "grey95") + (((class color) (background dark)) :background "grey20")) + "Face for highlighting the current section." + :group 'magit-faces) + +(defface magit-section-heading + '((((class color) (background light)) :foreground "DarkGoldenrod4" :weight bold) + (((class color) (background dark)) :foreground "LightGoldenrod2" :weight bold)) + "Face for section headings." + :group 'magit-faces) + +(defface magit-section-secondary-heading '((t :weight bold)) + "Face for section headings of some secondary headings." + :group 'magit-faces) + +(defface magit-section-heading-selection + '((((class color) (background light)) :foreground "salmon4") + (((class color) (background dark)) :foreground "LightSalmon3")) + "Face for selected section headings." + :group 'magit-faces) + +;;; Classes + +(defvar magit--current-section-hook nil + "Internal variable used for `magit-explain-section'.") + +(defvar magit--section-type-alist + '( + (file . magit-file-section) + (hunk . magit-hunk-section) + (module . magit-module-section) + )) + +(defclass magit-section () + ((type :initform nil :initarg :type) + (value :initform nil :initarg :value) + (start :initform nil :initarg :start) + (content :initform nil) + (end :initform nil) + (hidden :initform nil) + (washer :initform nil) + (process :initform nil) + (heading-highlight-face :initform nil) + (inserter :initform (symbol-value 'magit--current-section-hook)) + (parent :initform nil :initarg :parent) + (children :initform nil))) + +(defclass magit-file-section (magit-section) + ((source :initform nil) + (header :initform nil))) + +(defclass magit-hunk-section (magit-section) + ((refined :initform nil))) + +(defclass magit-module-section (magit-file-section) + ()) + +;;; Core + +(defvar-local magit-root-section nil + "The root section in the current buffer. +All other sections are descendants of this section. The value +of this variable is set by `magit-insert-section' and you should +never modify it.") +(put 'magit-root-section 'permanent-local t) + +(defun magit-current-section () + "Return the section at point." + (or (get-text-property (point) 'magit-section) magit-root-section)) + +(defun magit-section-ident (section) + "Return an unique identifier for SECTION. +The return value has the form ((TYPE . VALUE)...)." + (with-slots (type value parent) section + (cons (cons type + (cond ((not (memq type '(unpulled unpushed))) value) + ((string-match-p "@{upstream}" value) value) + ;; Unfortunately Git chokes on "@{push}" when + ;; the value of `push.default' does not allow a + ;; 1:1 mapping. Arbitrary commands may consult + ;; the section value so we cannot use "@{push}". + ;; But `unpushed' and `unpulled' sections should + ;; keep their identity when switching branches + ;; so we have to use another value here. + ((string-match-p "\\`\\.\\." value) "..@{push}") + (t "@{push}.."))) + (and parent + (magit-section-ident parent))))) + +(defun magit-get-section (ident &optional root) + "Return the section identified by IDENT. +IDENT has to be a list as returned by `magit-section-ident'." + (setq ident (reverse ident)) + (let ((section (or root magit-root-section))) + (when (eq (car (pop ident)) + (oref section type)) + (while (and ident + (setq section + (--first + (and (eq (caar ident) (oref it type)) + (equal (cdar ident) (oref it value))) + (oref section children)))) + (pop ident)) + section))) + +(defun magit-section-lineage (section) + "Return the lineage of SECTION. +The return value has the form (TYPE...)." + (cons (oref section type) + (when-let ((parent (oref section parent))) + (magit-section-lineage parent)))) + +(defvar magit-insert-section--current nil "For internal use only.") +(defvar magit-insert-section--parent nil "For internal use only.") +(defvar magit-insert-section--oldroot nil "For internal use only.") + +;;; Commands +;;;; Movement + +(defun magit-section-forward () + "Move to the beginning of the next visible section." + (interactive) + (if (eobp) + (user-error "No next section") + (let ((section (magit-current-section))) + (if (oref section parent) + (let ((next (and (not (oref section hidden)) + (not (= (oref section end) + (1+ (point)))) + (car (oref section children))))) + (while (and section (not next)) + (unless (setq next (car (magit-section-siblings section 'next))) + (setq section (oref section parent)))) + (if next + (magit-section-goto next) + (user-error "No next section"))) + (magit-section-goto 1))))) + +(defun magit-section-backward () + "Move to the beginning of the current or the previous visible section. +When point is at the beginning of a section then move to the +beginning of the previous visible section. Otherwise move to +the beginning of the current section." + (interactive) + (if (bobp) + (user-error "No previous section") + (let ((section (magit-current-section)) children) + (cond + ((and (= (point) + (1- (oref section end))) + (setq children (oref section children))) + (magit-section-goto (car (last children)))) + ((and (oref section parent) + (not (= (point) + (oref section start)))) + (magit-section-goto section)) + (t + (let ((prev (car (magit-section-siblings section 'prev)))) + (if prev + (while (and (not (oref prev hidden)) + (setq children (oref prev children))) + (setq prev (car (last children)))) + (setq prev (oref section parent))) + (cond (prev + (magit-section-goto prev)) + ((oref section parent) + (user-error "No previous section")) + ;; Eob special cases. + ((not (get-text-property (1- (point)) 'invisible)) + (magit-section-goto -1)) + (t + (goto-char (previous-single-property-change + (1- (point)) 'invisible)) + (forward-line -1) + (magit-section-goto (magit-current-section)))))))))) + +(defun magit-section-up () + "Move to the beginning of the parent section." + (interactive) + (--if-let (oref (magit-current-section) parent) + (magit-section-goto it) + (user-error "No parent section"))) + +(defun magit-section-forward-sibling () + "Move to the beginning of the next sibling section. +If there is no next sibling section, then move to the parent." + (interactive) + (let ((current (magit-current-section))) + (if (oref current parent) + (--if-let (car (magit-section-siblings current 'next)) + (magit-section-goto it) + (magit-section-forward)) + (magit-section-goto 1)))) + +(defun magit-section-backward-sibling () + "Move to the beginning of the previous sibling section. +If there is no previous sibling section, then move to the parent." + (interactive) + (let ((current (magit-current-section))) + (if (oref current parent) + (--if-let (car (magit-section-siblings current 'prev)) + (magit-section-goto it) + (magit-section-backward)) + (magit-section-goto -1)))) + +(defun magit-section-goto (arg) + (if (integerp arg) + (progn (forward-line arg) + (setq arg (magit-current-section))) + (goto-char (oref arg start))) + (run-hook-with-args 'magit-section-movement-hook arg)) + +(defun magit-section-set-window-start (section) + "Ensure the beginning of SECTION is visible." + (unless (pos-visible-in-window-p (oref section end)) + (set-window-start (selected-window) (oref section start)))) + +(defun magit-hunk-set-window-start (section) + "When SECTION is a `hunk', ensure that its beginning is visible. +It the SECTION has a different type, then do nothing." + (when (magit-hunk-section-p section) + (magit-section-set-window-start section))) + +(defmacro magit-define-section-jumper (name heading type &optional value) + "Define an interactive function to go some section. +Together TYPE and VALUE identify the section. +HEADING is the displayed heading of the section." + (declare (indent defun)) + `(defun ,name (&optional expand) ,(format "\ +Jump to the section \"%s\". +With a prefix argument also expand it." heading) + (interactive "P") + (--if-let (magit-get-section + (cons (cons ',type ,value) + (magit-section-ident magit-root-section))) + (progn (goto-char (oref it start)) + (when expand + (with-local-quit (magit-section-show it)) + (recenter 0))) + (message ,(format "Section \"%s\" wasn't found" heading))))) + +;;;; Visibility + +(defun magit-section-show (section) + "Show the body of the current section." + (interactive (list (magit-current-section))) + (oset section hidden nil) + (when-let ((washer (oref section washer))) + (oset section washer nil) + (let ((inhibit-read-only t) + (magit-insert-section--parent section) + (content (oref section content))) + (save-excursion + (if (and content (< content (oref section end))) + (funcall washer section) ; already partially washed (hunk) + (goto-char (oref section end)) + (oset section content (point-marker)) + (funcall washer) + (oset section end (point-marker))))) + (magit-section-update-highlight)) + (when-let ((beg (oref section content))) + (remove-overlays beg (oref section end) 'invisible t)) + (magit-section-maybe-cache-visibility section) + (dolist (child (oref section children)) + (if (oref child hidden) + (magit-section-hide child) + (magit-section-show child)))) + +(defun magit-section-hide (section) + "Hide the body of the current section." + (interactive (list (magit-current-section))) + (if (eq section magit-root-section) + (user-error "Cannot hide root section") + (oset section hidden t) + (when-let ((beg (oref section content))) + (let ((end (oref section end))) + (remove-overlays beg end 'invisible t) + (let ((o (make-overlay beg end))) + (overlay-put o 'evaporate t) + (overlay-put o 'invisible t)))) + (magit-section-maybe-cache-visibility section))) + +(defun magit-section-toggle (section) + "Toggle visibility of the body of the current section." + (interactive (list (magit-current-section))) + (if (eq section magit-root-section) + (user-error "Cannot hide root section") + (goto-char (oref section start)) + (if (oref section hidden) + (magit-section-show section) + (magit-section-hide section)))) + +(defun magit-section-toggle-children (section) + "Toggle visibility of bodies of children of the current section." + (interactive (list (magit-current-section))) + (goto-char (oref section start)) + (let* ((children (oref section children)) + (show (--any-p (oref it hidden) children))) + (dolist (c children) + (oset c hidden show))) + (magit-section-show section)) + +(defun magit-section-show-children (section &optional depth) + "Recursively show the bodies of children of the current section. +With a prefix argument show children that deep and hide deeper +children." + (interactive (list (magit-current-section))) + (magit-section-show-children-1 section depth) + (magit-section-show section)) + +(defun magit-section-show-children-1 (section &optional depth) + (dolist (child (oref section children)) + (oset child hidden nil) + (if depth + (if (> depth 0) + (magit-section-show-children-1 child (1- depth)) + (magit-section-hide child)) + (magit-section-show-children-1 child)))) + +(defun magit-section-hide-children (section) + "Recursively hide the bodies of children of the current section." + (interactive (list (magit-current-section))) + (mapc 'magit-section-hide (oref section children))) + +(defun magit-section-show-headings (section) + "Recursively show headings of children of the current section. +Only show the headings, previously shown text-only bodies are +hidden." + (interactive (list (magit-current-section))) + (magit-section-show-headings-1 section) + (magit-section-show section)) + +(defun magit-section-show-headings-1 (section) + (dolist (child (oref section children)) + (oset child hidden nil) + (when (or (oref child children) + (not (oref child content))) + (magit-section-show-headings-1 child)))) + +(defun magit-section-cycle (section) + "Cycle visibility of current section and its children." + (interactive (list (magit-current-section))) + (goto-char (oref section start)) + (if (oref section hidden) + (progn (magit-section-show section) + (magit-section-hide-children section)) + (let ((children (oref section children))) + (cond ((and (--any-p (oref it hidden) children) + (--any-p (oref it children) children)) + (magit-section-show-headings section)) + ((-any-p 'magit-section-hidden-body children) + (magit-section-show-children section)) + (t + (magit-section-hide section)))))) + +(defun magit-section-cycle-global () + "Cycle visibility of all sections in the current buffer." + (interactive) + (let ((children (oref magit-root-section children))) + (cond ((and (--any-p (oref it hidden) children) + (--any-p (oref it children) children)) + (magit-section-show-headings magit-root-section)) + ((-any-p 'magit-section-hidden-body children) + (magit-section-show-children magit-root-section)) + (t + (mapc 'magit-section-hide children))))) + +(defun magit-section-cycle-diffs () + "Cycle visibility of diff-related sections in the current buffer." + (interactive) + (when-let ((sections + (cond ((derived-mode-p 'magit-status-mode) + (--mapcat + (when it + (when (oref it hidden) + (magit-section-show it)) + (oref it children)) + (list (magit-get-section '((staged) (status))) + (magit-get-section '((unstaged) (status)))))) + ((derived-mode-p 'magit-diff-mode) + (-filter #'magit-file-section-p + (oref magit-root-section children)))))) + (if (--any-p (oref it hidden) sections) + (dolist (s sections) + (magit-section-show s) + (magit-section-hide-children s)) + (let ((children (--mapcat (oref it children) sections))) + (cond ((and (--any-p (oref it hidden) children) + (--any-p (oref it children) children)) + (mapc 'magit-section-show-headings sections)) + ((-any-p 'magit-section-hidden-body children) + (mapc 'magit-section-show-children sections)) + (t + (mapc 'magit-section-hide sections))))))) + +(defun magit-section-hidden-body (section &optional pred) + (--if-let (oref section children) + (funcall (or pred '-any-p) 'magit-section-hidden-body it) + (and (oref section content) + (oref section hidden)))) + +(defun magit-section-invisible-p (section) + "Return t if the SECTION's body is invisible. +When the body of an ancestor of SECTION is collapsed then +SECTION's body (and heading) obviously cannot be visible." + (or (oref section hidden) + (--when-let (oref section parent) + (magit-section-invisible-p it)))) + +(defun magit-section-show-level (level) + "Show surrounding sections up to LEVEL. +If LEVEL is negative, show up to the absolute value. +Sections at higher levels are hidden." + (if (< level 0) + (let ((s (magit-current-section))) + (setq level (- level)) + (while (> (1- (length (magit-section-ident s))) level) + (setq s (oref s parent)) + (goto-char (oref s start))) + (magit-section-show-children magit-root-section (1- level))) + (cl-do* ((s (magit-current-section) + (oref s parent)) + (i (1- (length (magit-section-ident s))) + (cl-decf i))) + ((cond ((< i level) (magit-section-show-children s (- level i 1)) t) + ((= i level) (magit-section-hide s) t)) + (magit-section-goto s))))) + +(defun magit-section-show-level-1 () + "Show surrounding sections on first level." + (interactive) + (magit-section-show-level 1)) + +(defun magit-section-show-level-1-all () + "Show all sections on first level." + (interactive) + (magit-section-show-level -1)) + +(defun magit-section-show-level-2 () + "Show surrounding sections up to second level." + (interactive) + (magit-section-show-level 2)) + +(defun magit-section-show-level-2-all () + "Show all sections up to second level." + (interactive) + (magit-section-show-level -2)) + +(defun magit-section-show-level-3 () + "Show surrounding sections up to third level." + (interactive) + (magit-section-show-level 3)) + +(defun magit-section-show-level-3-all () + "Show all sections up to third level." + (interactive) + (magit-section-show-level -3)) + +(defun magit-section-show-level-4 () + "Show surrounding sections up to fourth level." + (interactive) + (magit-section-show-level 4)) + +(defun magit-section-show-level-4-all () + "Show all sections up to fourth level." + (interactive) + (magit-section-show-level -4)) + +;;;; Auxiliary + +(defun magit-describe-section-briefly (section &optional message ident) + "Show information about the section at point. +With a prefix argument show the section identity instead of the +section lineage. This command is intended for debugging purposes." + (interactive (list (magit-current-section) t)) + (let ((str (format "#<%s %S %S %s-%s>" + (eieio-object-class section) + (let ((val (oref section value))) + (cond ((stringp val) + (substring-no-properties val)) + ((and (eieio-object-p val) + (fboundp 'cl-prin1-to-string)) + (cl-prin1-to-string val)) + (t + val))) + (if ident + (magit-section-ident section) + (apply #'vector (magit-section-lineage section))) + (when-let ((m (oref section start))) + (marker-position m)) + (when-let ((m (oref section end))) + (marker-position m))))) + (if message (message "%s" str) str))) + +(cl-defmethod cl-print-object ((section magit-section) stream) + "Print `magit-describe-section' result of SECTION." + ;; Used by debug and edebug as of Emacs 26. + (princ (magit-describe-section-briefly section) stream)) + +(defun magit-describe-section (section &optional interactive-p) + "Show information about the section at point." + (interactive (list (magit-current-section) t)) + (let ((inserter-section section)) + (while (and inserter-section (not (oref inserter-section inserter))) + (setq inserter-section (oref inserter-section parent))) + (when (and inserter-section (oref inserter-section inserter)) + (setq section inserter-section))) + (pcase (oref section inserter) + (`((,hook ,fun) . ,src-src) + (help-setup-xref `(magit-describe-section ,section) interactive-p) + (with-help-window (help-buffer) + (with-current-buffer standard-output + (insert (format-message + "%s\n is inserted by `%s'\n from `%s'" + (magit-describe-section-briefly section) + (make-text-button (symbol-name fun) nil + :type 'help-function + 'help-args (list fun)) + (make-text-button (symbol-name hook) nil + :type 'help-variable + 'help-args (list hook)))) + (pcase-dolist (`(,hook ,fun) src-src) + (insert (format-message + ",\n called by `%s'\n from `%s'" + (make-text-button (symbol-name fun) nil + :type 'help-function + 'help-args (list fun)) + (make-text-button (symbol-name hook) nil + :type 'help-variable + 'help-args (list hook))))) + (insert ".\n\n") + (insert + (format-message + "`%s' is " + (make-text-button (symbol-name fun) nil + :type 'help-function 'help-args (list fun)))) + (describe-function-1 fun)))) + (_ (message "%s, inserter unknown" + (magit-describe-section-briefly section))))) + +;;; Match + +(cl-defun magit-section-match + (condition &optional (section (magit-current-section))) + "Return t if SECTION matches CONDITION. + +SECTION defaults to the section at point. If SECTION is not +specified and there also is no section at point, then return +nil. + +CONDITION can take the following forms: + (CONDITION...) matches if any of the CONDITIONs matches. + [CLASS...] matches if the section's class is the same + as the first CLASS or a subclass of that; + the section's parent class matches the + second CLASS; and so on. + [* CLASS...] matches sections that match [CLASS...] and + also recursively all their child sections. + CLASS matches if the section's class is the same + as CLASS or a subclass of that; regardless + of the classes of the parent sections. + +Each CLASS should be a class symbol, identifying a class that +derives from `magit-section'. For backward compatibility CLASS +can also be a \"type symbol\". A section matches such a symbol +if the value of its `type' slot is `eq'. If a type symbol has +an entry in `magit--section-type-alist', then a section also +matches that type if its class is a subclass of the class that +corresponds to the type as per that alist. + +Note that it is not necessary to specify the complete section +lineage as printed by `magit-describe-section-briefly', unless +of course you want to be that precise." + (and section (magit-section-match-1 condition section))) + +(defun magit-section-match-1 (condition section) + (cl-assert condition) + (and section + (if (listp condition) + (--first (magit-section-match-1 it section) condition) + (magit-section-match-2 (if (symbolp condition) + (list condition) + (cl-coerce condition 'list)) + section)))) + +(defun magit-section-match-2 (condition section) + (if (eq (car condition) '*) + (or (magit-section-match-2 (cdr condition) section) + (when-let ((parent (oref section parent))) + (magit-section-match-2 condition parent))) + (and (let ((c (car condition))) + (if (class-p c) + (cl-typep section c) + (if-let ((class (cdr (assq c magit--section-type-alist)))) + (cl-typep section class) + (eq (oref section type) c)))) + (or (not (setq condition (cdr condition))) + (when-let ((parent (oref section parent))) + (magit-section-match-2 condition parent)))))) + +(defun magit-section-value-if (condition &optional section) + "If the section at point matches CONDITION, then return its value. + +If optional SECTION is non-nil then test whether that matches +instead. If there is no section at point and SECTION is nil, +then return nil. If the section does not match, then return +nil. + +See `magit-section-match' for the forms CONDITION can take." + (when-let ((section (or section (magit-current-section)))) + (and (magit-section-match condition section) + (oref section value)))) + +(defmacro magit-section-when (condition &rest body) + "If the section at point matches CONDITION, evaluate BODY. + +If the section matches, then evaluate BODY forms sequentially +with `it' bound to the section and return the value of the last +form. If there are no BODY forms, then return the value of the +section. If the section does not match or if there is no section +at point, then return nil. + +See `magit-section-match' for the forms CONDITION can take." + (declare (obsolete + "instead use `magit-section-match' or `magit-section-value-if'." + "Magit 2.90.0") + (indent 1) + (debug (sexp body))) + `(--when-let (magit-current-section) + ;; Quoting CONDITION here often leads to double-quotes, which + ;; isn't an issue because `magit-section-match-1' implicitly + ;; deals with that. We shouldn't force users of this function + ;; to not quote CONDITION because that would needlessly break + ;; backward compatibility. + (when (magit-section-match ',condition it) + ,@(or body '((oref it value)))))) + +(defmacro magit-section-case (&rest clauses) + "Choose among clauses on the type of the section at point. + +Each clause looks like (CONDITION BODY...). The type of the +section is compared against each CONDITION; the BODY forms of the +first match are evaluated sequentially and the value of the last +form is returned. Inside BODY the symbol `it' is bound to the +section at point. If no clause succeeds or if there is no +section at point, return nil. + +See `magit-section-match' for the forms CONDITION can take. +Additionally a CONDITION of t is allowed in the final clause, and +matches if no other CONDITION match, even if there is no section +at point." + (declare (indent 0) + (debug (&rest (sexp body)))) + `(let* ((it (magit-current-section))) + (cond ,@(mapcar (lambda (clause) + `(,(or (eq (car clause) t) + `(and it + (magit-section-match-1 ',(car clause) it))) + ,@(cdr clause))) + clauses)))) + +(defun magit-section-match-assoc (section alist) + "Return the value associated with SECTION's type or lineage in ALIST." + (-some (pcase-lambda (`(,key . ,val)) + (and (magit-section-match-1 key section) val)) + alist)) + +;;; Create + +(defvar magit-insert-section-hook nil + "Hook run after `magit-insert-section's BODY. +Avoid using this hook and only ever do so if you know +what you are doing and are sure there is no other way.") + +(defmacro magit-insert-section (&rest args) + "Insert a section at point. + +TYPE is the section type, a symbol. Many commands that act on +the current section behave differently depending on that type. +Also if a variable `magit-TYPE-section-map' exists, then use +that as the text-property `keymap' of all text belonging to the +section (but this may be overwritten in subsections). TYPE can +also have the form `(eval FORM)' in which case FORM is evaluated +at runtime. + +Optional VALUE is the value of the section, usually a string +that is required when acting on the section. + +When optional HIDE is non-nil collapse the section body by +default, i.e. when first creating the section, but not when +refreshing the buffer. Else expand it by default. This can be +overwritten using `magit-section-set-visibility-hook'. When a +section is recreated during a refresh, then the visibility of +predecessor is inherited and HIDE is ignored (but the hook is +still honored). + +BODY is any number of forms that actually insert the section's +heading and body. Optional NAME, if specified, has to be a +symbol, which is then bound to the struct of the section being +inserted. + +Before BODY is evaluated the `start' of the section object is set +to the value of `point' and after BODY was evaluated its `end' is +set to the new value of `point'; BODY is responsible for moving +`point' forward. + +If it turns out inside BODY that the section is empty, then +`magit-cancel-section' can be used to abort and remove all traces +of the partially inserted section. This can happen when creating +a section by washing Git's output and Git didn't actually output +anything this time around. + +\(fn [NAME] (TYPE &optional VALUE HIDE) &rest BODY)" + (declare (indent defun) + (debug ([&optional symbolp] + (&or [("eval" symbolp) &optional form form] + [symbolp &optional form form]) + body))) + (let ((tp (cl-gensym "type")) + (s* (and (symbolp (car args)) + (pop args))) + (s (cl-gensym "section"))) + `(let* ((,tp ,(let ((type (nth 0 (car args)))) + (if (eq (car-safe type) 'eval) + (cadr type) + `',type))) + (,s (funcall (if (class-p ,tp) + ,tp + (or (cdr (assq ,tp magit--section-type-alist)) + 'magit-section)) + :type + (if (class-p ,tp) + (or (car (rassq ,tp magit--section-type-alist)) + (error "BUG: No entry for %s in %s" ,tp + 'magit--section-type-alist)) + ,tp) + :value ,(nth 1 (car args)) + :start (point-marker) + :parent magit-insert-section--parent))) + (oset ,s hidden + (if-let ((value (run-hook-with-args-until-success + 'magit-section-set-visibility-hook ,s))) + (eq value 'hide) + (if-let ((incarnation (and magit-insert-section--oldroot + (magit-get-section + (magit-section-ident ,s) + magit-insert-section--oldroot)))) + (oref incarnation hidden) + (if-let ((value (magit-section-match-assoc + ,s magit-section-initial-visibility-alist))) + (progn + (when (functionp value) + (setq value (funcall value ,s))) + (eq value 'hide)) + ,(nth 2 (car args)))))) + (let ((magit-insert-section--current ,s) + (magit-insert-section--parent ,s) + (magit-insert-section--oldroot + (or magit-insert-section--oldroot + (unless magit-insert-section--parent + (prog1 magit-root-section + (setq magit-root-section ,s)))))) + (catch 'cancel-section + ,@(if s* + `((let ((,s* ,s)) + ,@(cdr args))) + (cdr args)) + ;; `magit-insert-section-hook' should *not* be run with + ;; `magit-run-section-hook' because it's a hook that runs + ;; on section insertion, not a section inserting hook. + (run-hooks 'magit-insert-section-hook) + (magit-insert-child-count ,s) + (set-marker-insertion-type (oref ,s start) t) + (let* ((end (oset ,s end (point-marker))) + (magit-map (intern (format "magit-%s-section-map" + (oref ,s type)))) + (forge-map (intern (format "forge-%s-section-map" + (oref ,s type)))) + (map (or (and (boundp magit-map) (symbol-value magit-map)) + (and (boundp forge-map) (symbol-value forge-map))))) + (save-excursion + (goto-char (oref ,s start)) + (while (< (point) end) + (let ((next (or (next-single-property-change + (point) 'magit-section) + end))) + (unless (get-text-property (point) 'magit-section) + (put-text-property (point) next 'magit-section ,s) + (when map + (put-text-property (point) next 'keymap map))) + (goto-char next))))) + (if (eq ,s magit-root-section) + (let ((magit-section-cache-visibility nil)) + (magit-section-show ,s)) + (oset (oref ,s parent) children + (nconc (oref (oref ,s parent) children) + (list ,s))))) + ,s)))) + +(defun magit-cancel-section () + (when magit-insert-section--current + (if (not (oref magit-insert-section--current parent)) + (insert "(empty)\n") + (delete-region (oref magit-insert-section--current start) + (point)) + (setq magit-insert-section--current nil) + (throw 'cancel-section nil)))) + +(defun magit-insert-heading (&rest args) + "Insert the heading for the section currently being inserted. + +This function should only be used inside `magit-insert-section'. + +When called without any arguments, then just set the `content' +slot of the object representing the section being inserted to +a marker at `point'. The section should only contain a single +line when this function is used like this. + +When called with arguments ARGS, which have to be strings, or +nil, then insert those strings at point. The section should not +contain any text before this happens and afterwards it should +again only contain a single line. If the `face' property is set +anywhere inside any of these strings, then insert all of them +unchanged. Otherwise use the `magit-section-heading' face for +all inserted text. + +The `content' property of the section struct is the end of the +heading (which lasts from `start' to `content') and the beginning +of the the body (which lasts from `content' to `end'). If the +value of `content' is nil, then the section has no heading and +its body cannot be collapsed. If a section does have a heading, +then its height must be exactly one line, including a trailing +newline character. This isn't enforced, you are responsible for +getting it right. The only exception is that this function does +insert a newline character if necessary." + (declare (indent defun)) + (when args + (let ((heading (apply #'concat args))) + (insert (if (text-property-not-all 0 (length heading) 'face nil heading) + heading + (propertize heading 'face 'magit-section-heading))))) + (unless (bolp) + (insert ?\n)) + (magit-maybe-make-margin-overlay) + (oset magit-insert-section--current content (point-marker))) + +(defun magit-insert-headers (hook) + (let* ((header-sections nil) + (magit-insert-section-hook + (cons (lambda () + (push magit-insert-section--current + header-sections)) + (if (listp magit-insert-section-hook) + magit-insert-section-hook + (list magit-insert-section-hook))))) + (magit-run-section-hook hook) + (when header-sections + (insert "\n") + ;; Make the first header into the parent of the rest. + (when (cdr header-sections) + (cl-callf nreverse header-sections) + (let* ((1st-header (pop header-sections)) + (header-parent (oref 1st-header parent))) + (oset header-parent children (list 1st-header)) + (oset 1st-header children header-sections) + (oset 1st-header content (oref (car header-sections) start)) + (oset 1st-header end (oref (car (last header-sections)) end)) + (dolist (sub-header header-sections) + (oset sub-header parent 1st-header))))))) + +(defun magit-insert-child-count (section) + "Modify SECTION's heading to contain number of child sections. + +If `magit-section-show-child-count' is non-nil and the SECTION +has children and its heading ends with \":\", then replace that +with \" (N)\", where N is the number of child sections. + +This function is called by `magit-insert-section' after that has +evaluated its BODY. Admittedly that's a bit of a hack." + ;; This has to be fast, not pretty! + (let (content count) + (when (and magit-section-show-child-count + (setq count (length (oref section children))) + (> count 0) + (setq content (oref section content)) + (eq (char-before (1- content)) ?:)) + (save-excursion + (goto-char (- content 2)) + (insert (format " (%s)" count)) + (delete-char 1))))) + +;;; Update + +(defvar-local magit-section-highlight-overlays nil) +(defvar-local magit-section-highlighted-section nil) +(defvar-local magit-section-highlighted-sections nil) +(defvar-local magit-section-unhighlight-sections nil) + +(defun magit-section-update-region (_) + "When the region is a valid section-selection, highlight them all." + ;; At least that's what it does conceptually. In actuality it just + ;; returns a list of those sections, and it doesn't even matter if + ;; this is a member of `magit-region-highlight-hook'. It probably + ;; should be removed, but I want to make sure before removing it. + (magit-region-sections)) + +(defun magit-section-update-highlight () + (let ((section (magit-current-section))) + (unless (eq section magit-section-highlighted-section) + (let ((inhibit-read-only t) + (deactivate-mark nil) + (selection (magit-region-sections))) + (mapc #'delete-overlay magit-section-highlight-overlays) + (setq magit-section-highlight-overlays nil) + (setq magit-section-unhighlight-sections + magit-section-highlighted-sections) + (setq magit-section-highlighted-sections nil) + (unless (eq section magit-root-section) + (run-hook-with-args-until-success + 'magit-section-highlight-hook section selection)) + (dolist (s magit-section-unhighlight-sections) + (run-hook-with-args-until-success + 'magit-section-unhighlight-hook s selection)) + (restore-buffer-modified-p nil) + (unless (eq magit-section-highlighted-section section) + (setq magit-section-highlighted-section + (and (not (oref section hidden)) + section)))) + (when (version< emacs-version "25.1") + (setq deactivate-mark nil))))) + +(defun magit-section-highlight (section selection) + "Highlight SECTION and if non-nil all sections in SELECTION. +This function works for any section but produces undesirable +effects for diff related sections, which by default are +highlighted using `magit-diff-highlight'. Return t." + (when-let ((face (oref section heading-highlight-face))) + (dolist (section (or selection (list section))) + (magit-section-make-overlay + (oref section start) + (or (oref section content) + (oref section end)) + face))) + (cond (selection + (magit-section-make-overlay (oref (car selection) start) + (oref (car (last selection)) end) + 'magit-section-highlight) + (magit-section-highlight-selection nil selection)) + (t + (magit-section-make-overlay (oref section start) + (oref section end) + 'magit-section-highlight))) + t) + +(defun magit-section-highlight-selection (_ selection) + "Highlight the section-selection region. +If SELECTION is non-nil, then it is a list of sections selected by +the region. The headings of these sections are then highlighted. + +This is a fallback for people who don't want to highlight the +current section and therefore removed `magit-section-highlight' +from `magit-section-highlight-hook'. + +This function is necessary to ensure that a representation of +such a region is visible. If neither of these functions were +part of the hook variable, then such a region would be +invisible." + (when (and selection + (not (and (eq this-command 'mouse-drag-region)))) + (dolist (section selection) + (magit-section-make-overlay (oref section start) + (or (oref section content) + (oref section end)) + 'magit-section-heading-selection)) + t)) + +(defun magit-section-make-overlay (start end face) + ;; Yes, this doesn't belong here. But the alternative of + ;; spreading this hack across the code base is even worse. + (when (and magit-keep-region-overlay + (memq face '(magit-section-heading-selection + magit-diff-file-heading-selection + magit-diff-hunk-heading-selection))) + (setq face (list :foreground (face-foreground face)))) + (let ((ov (make-overlay start end nil t))) + (overlay-put ov 'face face) + (overlay-put ov 'evaporate t) + (push ov magit-section-highlight-overlays) + ov)) + +(defun magit-section-goto-successor (section line char arg) + (let ((ident (magit-section-ident section))) + (--if-let (magit-get-section ident) + (let ((start (oref it start))) + (goto-char start) + (unless (eq it magit-root-section) + (ignore-errors + (forward-line line) + (forward-char char)) + (unless (eq (magit-current-section) it) + (goto-char start)))) + (or (and (magit-hunk-section-p section) + (when-let ((parent (magit-get-section + (magit-section-ident + (oref section parent))))) + (let* ((children (oref parent children)) + (siblings (magit-section-siblings section 'prev)) + (previous (nth (length siblings) children))) + (if (not arg) + (--when-let (or previous (car (last children))) + (magit-section-goto it) + t) + (when previous + (magit-section-goto previous)) + (if (and (stringp arg) + (re-search-forward arg (oref parent end) t)) + (goto-char (match-beginning 0)) + (goto-char (oref (car (last children)) end)) + (forward-line -1) + (while (looking-at "^ ") (forward-line -1)) + (while (looking-at "^[-+]") (forward-line -1)) + (forward-line)))))) + (goto-char (--if-let (magit-section-goto-successor-1 section) + (if (eq (oref it type) 'button) + (point-min) + (oref it start)) + (point-min))))))) + +(defun magit-section-goto-successor-1 (section) + (or (--when-let (pcase (oref section type) + (`staged 'unstaged) + (`unstaged 'staged) + (`unpushed 'unpulled) + (`unpulled 'unpushed)) + (magit-get-section `((,it) (status)))) + (--when-let (car (magit-section-siblings section 'next)) + (magit-get-section (magit-section-ident it))) + (--when-let (car (magit-section-siblings section 'prev)) + (magit-get-section (magit-section-ident it))) + (--when-let (oref section parent) + (or (magit-get-section (magit-section-ident it)) + (magit-section-goto-successor-1 it))))) + +;;; Visibility + +(defvar-local magit-section-visibility-cache nil) +(put 'magit-section-visibility-cache 'permanent-local t) + +(defun magit-section-cached-visibility (section) + "Set SECTION's visibility to the cached value." + (cdr (assoc (magit-section-ident section) + magit-section-visibility-cache))) + +(cl-defun magit-section-cache-visibility + (&optional (section magit-insert-section--current)) + ;; Emacs 25's `alist-get' lacks TESTFN. + (let* ((id (magit-section-ident section)) + (elt (assoc id magit-section-visibility-cache)) + (val (if (oref section hidden) 'hide 'show))) + (if elt + (setcdr elt val) + (push (cons id val) magit-section-visibility-cache)))) + +(cl-defun magit-section-maybe-cache-visibility + (&optional (section magit-insert-section--current)) + (when (or (eq magit-section-cache-visibility t) + (memq (oref section type) + magit-section-cache-visibility)) + (magit-section-cache-visibility section))) + +(defun magit-preserve-section-visibility-cache () + (when (derived-mode-p 'magit-status-mode 'magit-refs-mode) + (magit-repository-local-set + (cons major-mode 'magit-section-visibility-cache) + magit-section-visibility-cache))) + +(defun magit-restore-section-visibility-cache (mode) + (setq magit-section-visibility-cache + (magit-repository-local-get + (cons mode 'magit-section-visibility-cache)))) + +;;; Utilities + +(cl-defun magit-section-selected-p (section &optional (selection nil sselection)) + (and (not (eq section magit-root-section)) + (or (eq section (magit-current-section)) + (memq section (if sselection + selection + (setq selection (magit-region-sections)))) + (--when-let (oref section parent) + (magit-section-selected-p it selection))))) + +(defun magit-section-parent-value (section) + (when-let ((parent (oref section parent))) + (oref parent value))) + +(defun magit-section-siblings (section &optional direction) + "Return a list of the sibling sections of SECTION. + +If optional DIRECTION is `prev', then return siblings that come +before SECTION. If it is `next', then return siblings that come +after SECTION. For all other values, return all siblings +excluding SECTION itself." + (when-let ((parent (oref section parent))) + (let ((siblings (oref parent children))) + (pcase direction + (`prev (cdr (member section (reverse siblings)))) + (`next (cdr (member section siblings))) + (_ (remq section siblings)))))) + +(defun magit-region-values (&optional condition multiple) + "Return a list of the values of the selected sections. + +Return the values that themselves would be returned by +`magit-region-sections' (which see)." + (--map (oref it value) + (magit-region-sections condition multiple))) + +(defun magit-region-sections (&optional condition multiple) + "Return a list of the selected sections. + +When the region is active and constitutes a valid section +selection, then return a list of all selected sections. This is +the case when the region begins in the heading of a section and +ends in the heading of the same section or in that of a sibling +section. If optional MULTIPLE is non-nil, then the region cannot +begin and end in the same section. + +When the selection is not valid, then return nil. In this case, +most commands that can act on the selected sections will instead +act on the section at point. + +When the region looks like it would in any other buffer then +the selection is invalid. When the selection is valid then the +region uses the `magit-section-highlight' face. This does not +apply to diffs where things get a bit more complicated, but even +here if the region looks like it usually does, then that's not +a valid selection as far as this function is concerned. + +If optional CONDITION is non-nil, then the selection not only +has to be valid; all selected sections additionally have to match +CONDITION, or nil is returned. See `magit-section-match' for the +forms CONDITION can take." + (when (region-active-p) + (let* ((rbeg (region-beginning)) + (rend (region-end)) + (sbeg (get-text-property rbeg 'magit-section)) + (send (get-text-property rend 'magit-section))) + (when (and send + (not (eq send magit-root-section)) + (not (and multiple (eq send sbeg)))) + (let ((siblings (cons sbeg (magit-section-siblings sbeg 'next))) + sections) + (when (and (memq send siblings) + (magit-section-position-in-heading-p sbeg rbeg) + (magit-section-position-in-heading-p send rend)) + (while siblings + (push (car siblings) sections) + (when (eq (pop siblings) send) + (setq siblings nil))) + (setq sections (nreverse sections)) + (when (or (not condition) + (--all-p (magit-section-match condition it) sections)) + sections))))))) + +(defun magit-section-position-in-heading-p (&optional section pos) + "Return t if POSITION is inside the heading of SECTION. +POSITION defaults to point and SECTION defaults to the +current section." + (unless section + (setq section (magit-current-section))) + (unless pos + (setq pos (point))) + (and section + (>= pos (oref section start)) + (< pos (or (oref section content) + (oref section end))) + t)) + +(defun magit-section-internal-region-p (&optional section) + "Return t if the region is active and inside SECTION's body. +If optional SECTION is nil, use the current section." + (and (region-active-p) + (or section (setq section (magit-current-section))) + (let ((beg (get-text-property (region-beginning) 'magit-section))) + (and (eq beg (get-text-property (region-end) 'magit-section)) + (eq beg section))) + (not (or (magit-section-position-in-heading-p section (region-beginning)) + (magit-section-position-in-heading-p section (region-end)))) + t)) + +(defun magit-section--backward-protected () + "Move to the beginning of the current or the previous visible section. +Same as `magit-section-backward' but for non-interactive use. +Suppress `magit-section-movement-hook', and return a boolean to +indicate whether a section was found, instead of raising an error +if not." + (condition-case nil + (let ((magit-section-movement-hook nil)) + (magit-section-backward) + t) + (user-error nil))) + +(defun magit-section--backward-find (predicate) + "Move to the first previous section satisfying PREDICATE. +PREDICATE does not take any parameter and should not move +point." + (let (found) + (while (and (setq found (magit-section--backward-protected)) + (not (funcall predicate)))) + found)) + +(defun magit-wash-sequence (function) + "Repeatedly call FUNCTION until it returns nil or eob is reached. +FUNCTION has to move point forward or return nil." + (while (and (not (eobp)) (funcall function)))) + +(defun magit-add-section-hook (hook function &optional at append local) + "Add to the value of section hook HOOK the function FUNCTION. + +Add FUNCTION at the beginning of the hook list unless optional +APPEND is non-nil, in which case FUNCTION is added at the end. +If FUNCTION already is a member, then move it to the new location. + +If optional AT is non-nil and a member of the hook list, then +add FUNCTION next to that instead. Add before or after AT, or +replace AT with FUNCTION depending on APPEND. If APPEND is the +symbol `replace', then replace AT with FUNCTION. For any other +non-nil value place FUNCTION right after AT. If nil, then place +FUNCTION right before AT. If FUNCTION already is a member of the +list but AT is not, then leave FUNCTION where ever it already is. + +If optional LOCAL is non-nil, then modify the hook's buffer-local +value rather than its global value. This makes the hook local by +copying the default value. That copy is then modified. + +HOOK should be a symbol. If HOOK is void, it is first set to nil. +HOOK's value must not be a single hook function. FUNCTION should +be a function that takes no arguments and inserts one or multiple +sections at point, moving point forward. FUNCTION may choose not +to insert its section(s), when doing so would not make sense. It +should not be abused for other side-effects. To remove FUNCTION +again use `remove-hook'." + (unless (boundp hook) + (error "Cannot add function to undefined hook variable %s" hook)) + (or (default-boundp hook) (set-default hook nil)) + (let ((value (if local + (if (local-variable-p hook) + (symbol-value hook) + (unless (local-variable-if-set-p hook) + (make-local-variable hook)) + (copy-sequence (default-value hook))) + (default-value hook)))) + (if at + (when (setq at (member at value)) + (setq value (delq function value)) + (cond ((eq append 'replace) + (setcar at function)) + (append + (push function (cdr at))) + (t + (push (car at) (cdr at)) + (setcar at function)))) + (setq value (delq function value))) + (unless (member function value) + (setq value (if append + (append value (list function)) + (cons function value)))) + (when (eq append 'replace) + (setq value (delq at value))) + (if local + (set hook value) + (set-default hook value)))) + +(defun magit-run-section-hook (hook &rest args) + "Run HOOK with ARGS, warning about invalid entries." + (let ((entries (symbol-value hook))) + (unless (listp entries) + (setq entries (list entries))) + (--when-let (-remove #'functionp entries) + (message "`%s' contains entries that are no longer valid. +%s\nUsing standard value instead. Please re-configure hook variable." + hook + (mapconcat (lambda (sym) (format " `%s'" sym)) it "\n")) + (sit-for 5) + (setq entries (eval (car (get hook 'standard-value))))) + (dolist (entry entries) + (let ((magit--current-section-hook (cons (list hook entry) + magit--current-section-hook))) + (apply entry args))))) + +;;; _ +(provide 'magit-section) +;;; magit-section.el ends here diff --git a/elpa/magit-20181113.1837/magit-sequence.el b/elpa/magit-20181113.1837/magit-sequence.el new file mode 100644 index 00000000..0eb1ec6b --- /dev/null +++ b/elpa/magit-20181113.1837/magit-sequence.el @@ -0,0 +1,915 @@ +;;; magit-sequence.el --- history manipulation in Magit -*- lexical-binding: t -*- + +;; Copyright (C) 2011-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; Support for Git commands that replay commits and help the user make +;; changes along the way. Supports `cherry-pick', `revert', `rebase', +;; `rebase--interactive' and `am'. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +;;; Options +;;;; Faces + +(defface magit-sequence-pick + '((t :inherit default)) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-stop + '((((class color) (background light)) :foreground "DarkOliveGreen4") + (((class color) (background dark)) :foreground "DarkSeaGreen2")) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-part + '((((class color) (background light)) :foreground "Goldenrod4") + (((class color) (background dark)) :foreground "LightGoldenrod2")) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-head + '((((class color) (background light)) :foreground "SkyBlue4") + (((class color) (background dark)) :foreground "LightSkyBlue1")) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-drop + '((((class color) (background light)) :foreground "IndianRed") + (((class color) (background dark)) :foreground "IndianRed")) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-done + '((t :inherit magit-hash)) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-onto + '((t :inherit magit-sequence-done)) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-exec + '((t :inherit magit-hash)) + "Face used in sequence sections." + :group 'magit-faces) + +;;; Common + +;;;###autoload +(defun magit-sequencer-continue () + "Resume the current cherry-pick or revert sequence." + (interactive) + (if (magit-sequencer-in-progress-p) + (if (magit-anything-unstaged-p t) + (user-error "Cannot continue due to unstaged changes") + (magit-run-git-sequencer + (if (magit-revert-in-progress-p) "revert" "cherry-pick") "--continue")) + (user-error "No cherry-pick or revert in progress"))) + +;;;###autoload +(defun magit-sequencer-skip () + "Skip the stopped at commit during a cherry-pick or revert sequence." + (interactive) + (if (magit-sequencer-in-progress-p) + (progn (magit-call-git "reset" "--hard") + (magit-sequencer-continue)) + (user-error "No cherry-pick or revert in progress"))) + +;;;###autoload +(defun magit-sequencer-abort () + "Abort the current cherry-pick or revert sequence. +This discards all changes made since the sequence started." + (interactive) + (if (magit-sequencer-in-progress-p) + (magit-run-git-sequencer + (if (magit-revert-in-progress-p) "revert" "cherry-pick") "--abort") + (user-error "No cherry-pick or revert in progress"))) + +(defun magit-sequencer-in-progress-p () + (or (magit-cherry-pick-in-progress-p) + (magit-revert-in-progress-p))) + +;;; Cherry-Pick + +(defvar magit-perl-executable "perl" + "The Perl executable.") + +;;;###autoload (autoload 'magit-cherry-pick-popup "magit-sequence" nil t) +(magit-define-popup magit-cherry-pick-popup + "Popup console for cherry-pick commands." + :man-page "git-cherry-pick" + :switches '((?s "Add Signed-off-by lines" "--signoff") + (?e "Edit commit messages" "--edit") + (?x "Reference cherry in commit message" "-x") + (?F "Attempt fast-forward" "--ff")) + :options '((?s "Strategy" "--strategy=") + (?m "Replay merge relative to parent" "--mainline=")) + :actions '("Apply here" + (?A "Pick" magit-cherry-copy) + (?a "Apply" magit-cherry-apply) + (?h "Harvest" magit-cherry-harvest) + "Apply elsewhere" + (?d "Donate" magit-cherry-donate) + (?n "Spinout" magit-cherry-spinout) + (?s "Spinoff" magit-cherry-spinoff)) + :sequence-actions '((?A "Continue" magit-sequencer-continue) + (?s "Skip" magit-sequencer-skip) + (?a "Abort" magit-sequencer-abort)) + :sequence-predicate 'magit-sequencer-in-progress-p + :default-arguments '("--ff")) + +(defun magit-cherry-pick-read-args (prompt) + (list (or (nreverse (magit-region-values 'commit)) + (magit-read-other-branch-or-commit prompt)) + (magit-cherry-pick-arguments))) + +(defun magit--cherry-move-read-args (verb away fn) + (declare (indent defun)) + (let ((commits (or (nreverse (magit-region-values 'commit)) + (list (funcall (if away + 'magit-read-branch-or-commit + 'magit-read-other-branch-or-commit) + (format "%s cherry" (capitalize verb)))))) + (current (magit-get-current-branch))) + (unless current + (user-error "Cannot %s cherries while HEAD is detached" verb)) + (let ((reachable (magit-rev-ancestor-p (car commits) current)) + (msg "Cannot %s cherries that %s reachable from HEAD")) + (pcase (list away reachable) + (`(nil t) (user-error msg verb "are")) + (`(t nil) (user-error msg verb "are not")))) + `(,commits + ,@(funcall fn commits) + ,(magit-cherry-pick-arguments)))) + +(defun magit--cherry-spinoff-read-args (verb) + (magit--cherry-move-read-args verb t + (lambda (commits) + (butlast (magit-branch-read-args + (format "Create branch from %s cherries" commits)))))) + +;;;###autoload +(defun magit-cherry-copy (commits &optional args) + "Copy COMMITS from another branch onto the current branch. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then pick all of them, +without prompting." + (interactive (magit-cherry-pick-read-args "Cherry-pick")) + (magit--cherry-pick commits args)) + +;;;###autoload +(defun magit-cherry-apply (commits &optional args) + "Apply the changes in COMMITS but do not commit them. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then apply all of them, +without prompting." + (interactive (magit-cherry-pick-read-args "Apply changes from commit")) + (magit--cherry-pick commits (cons "--no-commit" (remove "--ff" args)))) + +;;;###autoload +(defun magit-cherry-harvest (commits branch &optional args) + "Move COMMITS from another BRANCH onto the current branch. +Remove the COMMITS from BRANCH and stay on the current branch. +If a conflict occurs, then you have to fix that and finish the +process manually." + (interactive + (magit--cherry-move-read-args "harvest" nil + (lambda (commits) + (list (let ((branches (magit-list-containing-branches (car commits)))) + (pcase (length branches) + (0 nil) + (1 (car branches)) + (_ (magit-completing-read + (format "Remove %s cherries from branch" (length commits)) + branches nil t)))))))) + (magit--cherry-move commits branch (magit-get-current-branch) args nil t)) + +;;;###autoload +(defun magit-cherry-donate (commits branch &optional args) + "Move COMMITS from the current branch onto another existing BRANCH. +Remove COMMITS from the current branch and stay on that branch. +If a conflict occurs, then you have to fix that and finish the +process manually." + (interactive + (magit--cherry-move-read-args "donate" t + (lambda (commits) + (list (magit-read-other-branch (format "Move %s cherries to branch" + (length commits))))))) + (magit--cherry-move commits (magit-get-current-branch) branch args)) + +;;;###autoload +(defun magit-cherry-spinout (commits branch start-point &optional args) + "Move COMMITS from the current branch onto a new BRANCH. +Remove COMMITS from the current branch and stay on that branch. +If a conflict occurs, then you have to fix that and finish the +process manually." + (interactive (magit--cherry-spinoff-read-args "spinout")) + (magit--cherry-move commits (magit-get-current-branch) branch args + start-point)) + +;;;###autoload +(defun magit-cherry-spinoff (commits branch start-point &optional args) + "Move COMMITS from the current branch onto a new BRANCH. +Remove COMMITS from the current branch and checkout BRANCH. +If a conflict occurs, then you have to fix that and finish +the process manually." + (interactive (magit--cherry-spinoff-read-args "spinoff")) + (magit--cherry-move commits (magit-get-current-branch) branch args + start-point t)) + +(defun magit--cherry-move (commits src dst args + &optional start-point checkout-dst) + (let ((current (magit-get-current-branch))) + (unless (magit-branch-p dst) + (let ((magit-process-raise-error t)) + (magit-call-git "branch" dst start-point)) + (--when-let (magit-get-indirect-upstream-branch start-point) + (magit-call-git "branch" "--set-upstream-to" it dst))) + (unless (equal dst current) + (let ((magit-process-raise-error t)) + (magit-call-git "checkout" dst))) + (if (not src) ; harvest only + (magit--cherry-pick commits args) + (let ((tip (car (last commits))) + (keep (concat (car commits) "^"))) + (magit--cherry-pick commits args) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (cond + ((magit-rev-equal tip src) + (magit-call-git "update-ref" + "-m" (format "reset: moving to %s" keep) + (magit-ref-fullname src) + keep tip) + (if (not checkout-dst) + (magit-run-git "checkout" src) + (magit-refresh))) + (t + (magit-git "checkout" src) + (let ((process-environment process-environment)) + (push (format "%s=%s -i -ne '/^pick (%s)/ or print'" + "GIT_SEQUENCE_EDITOR" + magit-perl-executable + (mapconcat #'magit-rev-abbrev commits "|")) + process-environment) + (magit-run-git-sequencer "rebase" "-i" keep)) + (when checkout-dst + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (magit-run-git "checkout" dst)))))))))))))))) + +(defun magit--cherry-pick (commits args &optional revert) + (let ((command (if revert "revert" "cherry-pick"))) + (when (stringp commits) + (setq commits (if (string-match-p "\\.\\." commits) + (split-string commits "\\.\\.") + (list commits)))) + (magit-run-git-sequencer + (if revert "revert" "cherry-pick") + (pcase-let ((`(,merge ,non-merge) + (-separate 'magit-merge-commit-p commits))) + (cond + ((not merge) + (--remove (string-prefix-p "--mainline=" it) args)) + (non-merge + (user-error "Cannot %s merge and non-merge commits at once" + command)) + ((--first (string-prefix-p "--mainline=" it) args) + args) + (t + (cons (format "--mainline=%s" + (read-number "Replay merges relative to parent: ")) + args)))) + commits))) + +(defun magit-cherry-pick-in-progress-p () + ;; .git/sequencer/todo does not exist when there is only one commit left. + (file-exists-p (magit-git-dir "CHERRY_PICK_HEAD"))) + +;;; Revert + +;;;###autoload (autoload 'magit-revert-popup "magit-sequence" nil t) +(magit-define-popup magit-revert-popup + "Popup console for revert commands." + :man-page "git-revert" + :switches '((?s "Add Signed-off-by lines" "--signoff") + (?e "Edit commit message" "--edit") + (?E "Don't edit commit message" "--no-edit")) + :options '((?s "Strategy" "--strategy=") + (?S "Sign using gpg" "--gpg-sign=" magit-read-gpg-secret-key) + (?m "Replay merge relative to parent" "--mainline=")) + :actions '((?V "Revert commit(s)" magit-revert-and-commit) + (?v "Revert changes" magit-revert-no-commit)) + :sequence-actions '((?V "Continue" magit-sequencer-continue) + (?s "Skip" magit-sequencer-skip) + (?a "Abort" magit-sequencer-abort)) + :sequence-predicate 'magit-sequencer-in-progress-p + :default-arguments '("--edit")) + +(defun magit-revert-read-args (prompt) + (list (or (magit-region-values 'commit) + (magit-read-branch-or-commit prompt)) + (magit-revert-arguments))) + +;;;###autoload +(defun magit-revert-and-commit (commit &optional args) + "Revert COMMIT by creating a new commit. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then revert all of them, +without prompting." + (interactive (magit-revert-read-args "Revert commit")) + (magit--cherry-pick commit args t)) + +;;;###autoload +(defun magit-revert-no-commit (commit &optional args) + "Revert COMMIT by applying it in reverse to the worktree. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then revert all of them, +without prompting." + (interactive (magit-revert-read-args "Revert changes")) + (magit--cherry-pick commit (cons "--no-commit" args) t)) + +(defun magit-revert-in-progress-p () + ;; .git/sequencer/todo does not exist when there is only one commit left. + (file-exists-p (magit-git-dir "REVERT_HEAD"))) + +;;; Patch + +;;;###autoload (autoload 'magit-am-popup "magit-sequence" nil t) +(magit-define-popup magit-am-popup + "Popup console for mailbox commands." + :man-page "git-am" + :switches '((?3 "Fall back on 3way merge" "--3way") + (?s "Add Signed-off-by lines" "--signoff") + (?c "Remove text before scissors line" "--scissors") + (?k "Inhibit removal of email cruft" "--keep") + (?b "Limit removal of email cruft" "--keep-non-patch") + (?d "Use author date as committer date" + "--committer-date-is-author-date") + (?D "Use committer date as author date" "--ignore-date")) + :options '((?p "Remove leading slashes from paths" "-p" + magit-read-number-string)) + :actions '((?m "Apply maildir" magit-am-apply-maildir) + (?w "Apply patches" magit-am-apply-patches) + (?a "Apply plain patch" magit-patch-apply-popup)) + :default-arguments '("--3way") + :default-actions 'magit-am-apply-patches + :max-action-columns 1 + :sequence-actions '((?w "Continue" magit-am-continue) + (?s "Skip" magit-am-skip) + (?a "Abort" magit-am-abort)) + :sequence-predicate 'magit-am-in-progress-p) + +;;;###autoload +(defun magit-am-apply-patches (&optional files args) + "Apply the patches FILES." + (interactive (list (or (magit-region-values 'file) + (list (let ((default (magit-file-at-point))) + (read-file-name + (if default + (format "Apply patch (%s): " default) + "Apply patch: ") + nil default)))) + (magit-am-arguments))) + (magit-run-git-sequencer "am" args "--" + (--map (magit-convert-filename-for-git + (expand-file-name it)) + files))) + +;;;###autoload +(defun magit-am-apply-maildir (&optional maildir args) + "Apply the patches from MAILDIR." + (interactive (list (read-file-name "Apply mbox or Maildir: ") + (magit-am-arguments))) + (magit-run-git-sequencer "am" args (magit-convert-filename-for-git + (expand-file-name maildir)))) + +;;;###autoload +(defun magit-am-continue () + "Resume the current patch applying sequence." + (interactive) + (if (magit-am-in-progress-p) + (if (magit-anything-unstaged-p t) + (error "Cannot continue due to unstaged changes") + (magit-run-git-sequencer "am" "--continue")) + (user-error "Not applying any patches"))) + +;;;###autoload +(defun magit-am-skip () + "Skip the stopped at patch during a patch applying sequence." + (interactive) + (if (magit-am-in-progress-p) + (magit-run-git-sequencer "am" "--skip") + (user-error "Not applying any patches"))) + +;;;###autoload +(defun magit-am-abort () + "Abort the current patch applying sequence. +This discards all changes made since the sequence started." + (interactive) + (if (magit-am-in-progress-p) + (magit-run-git "am" "--abort") + (user-error "Not applying any patches"))) + +(defun magit-am-in-progress-p () + (file-exists-p (magit-git-dir "rebase-apply/applying"))) + +;;; Rebase + +;;;###autoload (autoload 'magit-rebase-popup "magit-sequence" nil t) +(magit-define-popup magit-rebase-popup + "Key menu for rebasing." + :man-page "git-rebase" + :switches '((?k "Keep empty commits" "--keep-empty") + (?p "Preserve merges" "--preserve-merges") + (?c "Lie about committer date" "--committer-date-is-author-date") + (?a "Autosquash" "--autosquash") + (?A "Autostash" "--autostash") + (?i "Interactive" "--interactive") + (?h "Disable hooks" "--no-verify")) + :actions '((lambda () + (concat (propertize "Rebase " 'face 'magit-popup-heading) + (propertize (or (magit-get-current-branch) "HEAD") + 'face 'magit-branch-local) + (propertize " onto" 'face 'magit-popup-heading))) + (?p (lambda () + (--when-let (magit-get-push-branch) (concat it "\n"))) + magit-rebase-onto-pushremote) + (?u (lambda () + (--when-let (magit-get-upstream-branch) (concat it "\n"))) + magit-rebase-onto-upstream) + (?e "elsewhere" magit-rebase-branch) + "Rebase" + (?i "interactively" magit-rebase-interactive) + (?m "to modify a commit" magit-rebase-edit-commit) + (?s "a subset" magit-rebase-subset) + (?w "to reword a commit" magit-rebase-reword-commit) nil + (?k "to remove a commit" magit-rebase-remove-commit) nil + (?f "to autosquash" magit-rebase-autosquash)) + :sequence-actions '((?r "Continue" magit-rebase-continue) + (?s "Skip" magit-rebase-skip) + (?e "Edit" magit-rebase-edit) + (?a "Abort" magit-rebase-abort)) + :sequence-predicate 'magit-rebase-in-progress-p + :max-action-columns 2) + +(defun magit-git-rebase (target args) + (magit-run-git-sequencer "rebase" target args)) + +;;;###autoload +(defun magit-rebase-onto-pushremote (args) + "Rebase the current branch onto `branch..pushRemote'. +If that variable is unset, then rebase onto `remote.pushDefault'." + (interactive (list (magit-rebase-arguments))) + (--if-let (magit-get-current-branch) + (if-let ((remote (magit-get-push-remote it))) + (if (member remote (magit-list-remotes)) + (magit-git-rebase (concat remote "/" it) args) + (user-error "Remote `%s' doesn't exist" remote)) + (user-error "No push-remote is configured for %s" it)) + (user-error "No branch is checked out"))) + +;;;###autoload +(defun magit-rebase-onto-upstream (args) + "Rebase the current branch onto its upstream branch." + (interactive (list (magit-rebase-arguments))) + (--if-let (magit-get-current-branch) + (if-let ((target (magit-get-upstream-branch it))) + (magit-git-rebase target args) + (user-error "No upstream is configured for %s" it)) + (user-error "No branch is checked out"))) + +;;;###autoload +(defun magit-rebase-branch (target args) + "Rebase the current branch onto a branch read in the minibuffer. +All commits that are reachable from `HEAD' but not from the +selected branch TARGET are being rebased." + (interactive (list (magit-read-other-branch-or-commit "Rebase onto") + (magit-rebase-arguments))) + (message "Rebasing...") + (magit-git-rebase target args) + (message "Rebasing...done")) + +;;;###autoload +(defun magit-rebase-subset (newbase start args) + "Rebase a subset of the current branch's history onto a new base. +Rebase commits from START to `HEAD' onto NEWBASE. +START has to be selected from a list of recent commits." + (interactive (list (magit-read-other-branch-or-commit + "Rebase subset onto" nil + (magit-get-upstream-branch)) + nil + (magit-rebase-arguments))) + (if start + (progn (message "Rebasing...") + (magit-run-git-sequencer "rebase" "--onto" newbase start args) + (message "Rebasing...done")) + (magit-log-select + `(lambda (commit) + (magit-rebase-subset ,newbase (concat commit "^") (list ,@args))) + (concat "Type %p on a commit to rebase it " + "and commits above it onto " newbase ",")))) + +(defun magit-rebase-interactive-1 + (commit args message &optional editor delay-edit-confirm noassert confirm) + (declare (indent 2)) + (when commit + (if (eq commit :merge-base) + (setq commit (--if-let (magit-get-upstream-branch) + (magit-git-string "merge-base" it "HEAD") + nil)) + (unless (magit-rev-ancestor-p commit "HEAD") + (user-error "%s isn't an ancestor of HEAD" commit)) + (if (magit-commit-parents commit) + (setq commit (concat commit "^")) + (setq args (cons "--root" args))))) + (when (and commit (not noassert)) + (setq commit (magit-rebase-interactive-assert commit delay-edit-confirm))) + (if (and commit (not confirm)) + (let ((process-environment process-environment)) + (when editor + (push (concat "GIT_SEQUENCE_EDITOR=" editor) process-environment)) + (magit-run-git-sequencer "rebase" "-i" args + (unless (member "--root" args) commit))) + (magit-log-select + `(lambda (commit) + (magit-rebase-interactive-1 commit (list ,@args) + ,message ,editor ,delay-edit-confirm ,noassert)) + message))) + +(defvar magit--rebase-published-symbol nil) +(defvar magit--rebase-public-edit-confirmed nil) + +(defun magit-rebase-interactive-assert (since &optional delay-edit-confirm) + (let* ((commit (if (string-suffix-p "^" since) + ;; If SINCE is "REV^", then the user selected + ;; "REV", which is the first commit that will + ;; be replaced. (from^..to] <=> [from..to]. + (substring since 0 -1) + ;; The "--root" argument is being used. + since)) + (branches (magit-list-publishing-branches commit))) + (setq magit--rebase-public-edit-confirmed + (delete (magit-toplevel) magit--rebase-public-edit-confirmed)) + (when (and branches + (or (not delay-edit-confirm) + ;; The user might have stopped at a published commit + ;; merely to add new commits *after* it. Try not to + ;; ask users whether they really want to edit public + ;; commits, when they don't actually intend to do so. + (not (--all-p (magit-rev-equal it commit) branches)))) + (let ((m1 "Some of these commits have already been published to ") + (m2 ".\nDo you really want to modify them")) + (magit-confirm (or magit--rebase-published-symbol 'rebase-published) + (concat m1 "%s" m2) + (concat m1 "%i public branches" m2) + nil branches)) + (push (magit-toplevel) magit--rebase-public-edit-confirmed))) + (if (magit-git-lines "rev-list" "--merges" (concat since "..HEAD")) + (magit-read-char-case "Proceed despite merge in rebase range? " nil + (?c "[c]ontinue" since) + (?s "[s]elect other" nil) + (?a "[a]bort" (user-error "Quit"))) + since)) + +;;;###autoload +(defun magit-rebase-interactive (commit args) + "Start an interactive rebase sequence." + (interactive (list (magit-commit-at-point) + (magit-rebase-arguments))) + (magit-rebase-interactive-1 commit args + "Type %p on a commit to rebase it and all commits above it," + nil t)) + +;;;###autoload +(defun magit-rebase-autosquash (args) + "Combine squash and fixup commits with their intended targets." + (interactive (list (magit-rebase-arguments))) + (magit-rebase-interactive-1 :merge-base (cons "--autosquash" args) + "Type %p on a commit to squash into it and then rebase as necessary," + "true" nil t)) + +;;;###autoload +(defun magit-rebase-edit-commit (commit args) + "Edit a single older commit using rebase." + (interactive (list (magit-commit-at-point) + (magit-rebase-arguments))) + (magit-rebase-interactive-1 commit args + "Type %p on a commit to edit it," + (concat magit-perl-executable + " -i -p -e '++$x if not $x and s/^pick/edit/'") + t)) + +;;;###autoload +(defun magit-rebase-reword-commit (commit args) + "Reword a single older commit using rebase." + (interactive (list (magit-commit-at-point) + (magit-rebase-arguments))) + (magit-rebase-interactive-1 commit args + "Type %p on a commit to reword its message," + (concat magit-perl-executable + " -i -p -e '++$x if not $x and s/^pick/reword/'"))) + +;;;###autoload +(defun magit-rebase-remove-commit (commit args) + "Remove a single older commit using rebase." + (interactive (list (magit-commit-at-point) + (magit-rebase-arguments))) + (magit-rebase-interactive-1 commit args + "Type %p on a commit to remove it," + (concat magit-perl-executable + " -i -p -e '++$x if not $x and s/^pick/# pick/'") + nil nil t)) + +;;;###autoload +(defun magit-rebase-continue (&optional noedit) + "Restart the current rebasing operation. +In some cases this pops up a commit message buffer for you do +edit. With a prefix argument the old message is reused as-is." + (interactive "P") + (if (magit-rebase-in-progress-p) + (if (magit-anything-unstaged-p t) + (user-error "Cannot continue rebase with unstaged changes") + (when (and (magit-anything-staged-p) + (file-exists-p (magit-git-dir "rebase-merge")) + (not (member (magit-toplevel) + magit--rebase-public-edit-confirmed))) + (magit-commit-amend-assert)) + (if noedit + (let ((process-environment process-environment)) + (push "GIT_EDITOR=true" process-environment) + (magit-run-git-async (magit--rebase-resume-command) "--continue") + (set-process-sentinel magit-this-process + #'magit-sequencer-process-sentinel) + magit-this-process) + (magit-run-git-sequencer (magit--rebase-resume-command) "--continue"))) + (user-error "No rebase in progress"))) + +;;;###autoload +(defun magit-rebase-skip () + "Skip the current commit and restart the current rebase operation." + (interactive) + (unless (magit-rebase-in-progress-p) + (user-error "No rebase in progress")) + (magit-run-git-sequencer (magit--rebase-resume-command) "--skip")) + +;;;###autoload +(defun magit-rebase-edit () + "Edit the todo list of the current rebase operation." + (interactive) + (unless (magit-rebase-in-progress-p) + (user-error "No rebase in progress")) + (magit-run-git-sequencer "rebase" "--edit-todo")) + +;;;###autoload +(defun magit-rebase-abort () + "Abort the current rebase operation, restoring the original branch." + (interactive) + (unless (magit-rebase-in-progress-p) + (user-error "No rebase in progress")) + (magit-confirm 'abort-rebase "Abort this rebase") + (magit-run-git (magit--rebase-resume-command) "--abort")) + +(defun magit-rebase-in-progress-p () + "Return t if a rebase is in progress." + (or (file-exists-p (magit-git-dir "rebase-merge")) + (file-exists-p (magit-git-dir "rebase-apply/onto")))) + +(defun magit--rebase-resume-command () + (if (file-exists-p (magit-git-dir "rebase-recursive")) "rbr" "rebase")) + +;;; Sections + +(defun magit-insert-sequencer-sequence () + "Insert section for the on-going cherry-pick or revert sequence. +If no such sequence is in progress, do nothing." + (let ((picking (magit-cherry-pick-in-progress-p))) + (when (or picking (magit-revert-in-progress-p)) + (magit-insert-section (sequence) + (magit-insert-heading (if picking "Cherry Picking" "Reverting")) + (when-let ((lines + (cdr (magit-file-lines (magit-git-dir "sequencer/todo"))))) + (dolist (line (nreverse lines)) + (when (string-match + "^\\(pick\\|revert\\) \\([^ ]+\\) \\(.*\\)$" line) + (magit-bind-match-strings (cmd hash msg) line + (magit-insert-section (commit hash) + (insert (propertize cmd 'face 'magit-sequence-pick) + " " (propertize hash 'face 'magit-hash) + " " msg "\n")))))) + (magit-sequence-insert-sequence + (magit-file-line (magit-git-dir (if picking + "CHERRY_PICK_HEAD" + "REVERT_HEAD"))) + (magit-file-line (magit-git-dir "sequencer/head"))) + (insert "\n"))))) + +(defun magit-insert-am-sequence () + "Insert section for the on-going patch applying sequence. +If no such sequence is in progress, do nothing." + (when (magit-am-in-progress-p) + (magit-insert-section (rebase-sequence) + (magit-insert-heading "Applying patches") + (let ((patches (nreverse (magit-rebase-patches))) + patch commit) + (while patches + (setq patch (pop patches)) + (setq commit (magit-rev-verify-commit + (cadr (split-string (magit-file-line patch))))) + (cond ((and commit patches) + (magit-sequence-insert-commit + "pick" commit 'magit-sequence-pick)) + (patches + (magit-sequence-insert-am-patch + "pick" patch 'magit-sequence-pick)) + (commit + (magit-sequence-insert-sequence commit "ORIG_HEAD")) + (t + (magit-sequence-insert-am-patch + "stop" patch 'magit-sequence-stop) + (magit-sequence-insert-sequence nil "ORIG_HEAD"))))) + (insert ?\n)))) + +(defun magit-sequence-insert-am-patch (type patch face) + (magit-insert-section (file patch) + (let ((title + (with-temp-buffer + (insert-file-contents patch nil nil 4096) + (unless (re-search-forward "^Subject: " nil t) + (goto-char (point-min))) + (buffer-substring (point) (line-end-position))))) + (insert (propertize type 'face face) + ?\s (propertize (file-name-nondirectory patch) 'face 'magit-hash) + ?\s title + ?\n)))) + +(defun magit-insert-rebase-sequence () + "Insert section for the on-going rebase sequence. +If no such sequence is in progress, do nothing." + (when (magit-rebase-in-progress-p) + (let* ((interactive (file-directory-p (magit-git-dir "rebase-merge"))) + (dir (if interactive "rebase-merge/" "rebase-apply/")) + (name (-> (concat dir "head-name") magit-git-dir magit-file-line)) + (onto (-> (concat dir "onto") magit-git-dir magit-file-line)) + (onto (or (magit-rev-name onto name) + (magit-rev-name onto "refs/heads/*") onto)) + (name (or (magit-rev-name name "refs/heads/*") name))) + (magit-insert-section (rebase-sequence) + (magit-insert-heading (format "Rebasing %s onto %s" name onto)) + (if interactive + (magit-rebase-insert-merge-sequence onto) + (magit-rebase-insert-apply-sequence onto)) + (insert ?\n))))) + +(defun magit-rebase-insert-merge-sequence (onto) + (let (exec) + (dolist (line (nreverse + (magit-file-lines + (magit-git-dir "rebase-merge/git-rebase-todo")))) + (cond ((string-prefix-p "exec" line) + (setq exec (substring line 5))) + ((string-match (format "^\\([^%c ]+\\) \\([^ ]+\\) .*$" + (string-to-char + (or (magit-get "core.commentChar") "#"))) + line) + (magit-bind-match-strings (action hash) line + (unless (equal action "exec") + (magit-sequence-insert-commit + action hash 'magit-sequence-pick exec))) + (setq exec nil))))) + (magit-sequence-insert-sequence + (magit-file-line (magit-git-dir "rebase-merge/stopped-sha")) + onto + (--when-let (magit-file-lines (magit-git-dir "rebase-merge/done")) + (cadr (split-string (car (last it))))))) + +(defun magit-rebase-insert-apply-sequence (onto) + (let ((rewritten + (--map (car (split-string it)) + (magit-file-lines (magit-git-dir "rebase-apply/rewritten")))) + (stop (magit-file-line (magit-git-dir "rebase-apply/original-commit")))) + (dolist (patch (nreverse (cdr (magit-rebase-patches)))) + (let ((hash (cadr (split-string (magit-file-line patch))))) + (unless (or (member hash rewritten) + (equal hash stop)) + (magit-sequence-insert-commit "pick" hash 'magit-sequence-pick))))) + (magit-sequence-insert-sequence + (magit-file-line (magit-git-dir "rebase-apply/original-commit")) + onto)) + +(defun magit-rebase-patches () + (directory-files (magit-git-dir "rebase-apply") t "^[0-9]\\{4\\}$")) + +(defun magit-sequence-insert-sequence (stop onto &optional orig) + (let ((head (magit-rev-parse "HEAD")) done) + (setq onto (if onto (magit-rev-parse onto) head)) + (setq done (magit-git-lines "log" "--format=%H" (concat onto "..HEAD"))) + (when (and stop (not (member stop done))) + (let ((id (magit-patch-id stop))) + (--if-let (--first (equal (magit-patch-id it) id) done) + (setq stop it) + (cond + ((--first (magit-rev-equal it stop) done) + ;; The commit's testament has been executed. + (magit-sequence-insert-commit "void" stop 'magit-sequence-drop)) + ;; The faith of the commit is still undecided... + ((magit-anything-unmerged-p) + ;; ...and time travel isn't for the faint of heart. + (magit-sequence-insert-commit "join" stop 'magit-sequence-part)) + ((magit-anything-modified-p t) + ;; ...and the dust hasn't settled yet... + (magit-sequence-insert-commit + (let* ((magit--refresh-cache nil) + (staged (magit-commit-tree "oO" nil "HEAD")) + (unstaged (magit-commit-worktree "oO" "--reset"))) + (cond + ;; ...but we could end up at the same tree just by committing. + ((or (magit-rev-equal staged stop) + (magit-rev-equal unstaged stop)) "goal") + ;; ...but the changes are still there, untainted. + ((or (equal (magit-patch-id staged) id) + (equal (magit-patch-id unstaged) id)) "same") + ;; ...and some changes are gone and/or others were added. + (t "work"))) + stop 'magit-sequence-part)) + ;; The commit is definitely gone... + ((--first (magit-rev-equal it stop) done) + ;; ...but all of its changes are still in effect. + (magit-sequence-insert-commit "poof" stop 'magit-sequence-drop)) + (t + ;; ...and some changes are gone and/or other changes were added. + (magit-sequence-insert-commit "gone" stop 'magit-sequence-drop))) + (setq stop nil)))) + (dolist (rev done) + (apply 'magit-sequence-insert-commit + (cond ((equal rev stop) + ;; ...but its reincarnation lives on. + ;; Or it didn't die in the first place. + (list (if (and (equal rev head) + (equal (magit-patch-id rev) + (magit-patch-id orig))) + "stop" ; We haven't done anything yet. + "like") ; There are new commits. + rev (if (equal rev head) + 'magit-sequence-head + 'magit-sequence-stop))) + ((equal rev head) + (list "done" rev 'magit-sequence-head)) + (t + (list "done" rev 'magit-sequence-done))))) + (magit-sequence-insert-commit "onto" onto + (if (equal onto head) + 'magit-sequence-head + 'magit-sequence-onto)))) + +(defun magit-sequence-insert-commit (type hash face &optional exec) + (magit-insert-section (commit hash) + (magit-insert-heading + (propertize type 'face face) "\s" + (magit-format-rev-summary hash) "\n") + (when exec + (insert (propertize "exec" 'face 'magit-sequence-onto) "\s" exec "\n")))) + +;;; _ +(provide 'magit-sequence) +;;; magit-sequence.el ends here diff --git a/elpa/magit-20181113.1837/magit-stash.el b/elpa/magit-20181113.1837/magit-stash.el new file mode 100644 index 00000000..9012c9aa --- /dev/null +++ b/elpa/magit-20181113.1837/magit-stash.el @@ -0,0 +1,496 @@ +;;; magit-stash.el --- stash support for Magit -*- lexical-binding: t -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; Support for Git stashes. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +(defvar bookmark-make-record-function) + +;;; Options + +(defgroup magit-stash nil + "List stashes and show stash diffs." + :group 'magit-modes) + +;;;; Diff options + +(defcustom magit-stash-sections-hook + '(magit-insert-stash-notes + magit-insert-stash-worktree + magit-insert-stash-index + magit-insert-stash-untracked) + "Hook run to insert sections into stash diff buffers." + :package-version '(magit . "2.1.0") + :group 'magit-stash + :type 'hook) + +;;;; Log options + +(defcustom magit-stashes-margin + (list (nth 0 magit-log-margin) + (nth 1 magit-log-margin) + 'magit-log-margin-width nil + (nth 4 magit-log-margin)) + "Format of the margin in `magit-stashes-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the committer date. It can be one + of `age' (to show the age of the commit), `age-abbreviated' (to + abbreviate the time unit to a character), or a string (suitable + for `format-time-string') to show the actual date. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-stash + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize 'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-stashes-mode)) + +;;; Commands + +;;;###autoload (autoload 'magit-stash-popup "magit-stash" nil t) +(magit-define-popup magit-stash-popup + "Popup console for stash commands." + :man-page "git-stash" + :switches '((?u "Also save untracked files" "--include-untracked") + (?a "Also save untracked and ignored files" "--all")) + :actions '((?z "Save" magit-stash-both) + (?Z "Snapshot" magit-snapshot-both) + (?p "Pop" magit-stash-pop) + (?i "Save index" magit-stash-index) + (?I "Snapshot index" magit-snapshot-index) + (?a "Apply" magit-stash-apply) + (?w "Save worktree" magit-stash-worktree) + (?W "Snapshot worktree" magit-snapshot-worktree) + (?l "List" magit-stash-list) + (?x "Save keeping index" magit-stash-keep-index) + (?r "Snapshot to wipref" magit-wip-commit) + (?v "Show" magit-stash-show) + (?b "Branch" magit-stash-branch) + (?k "Drop" magit-stash-drop) nil + (?B "Branch here" magit-stash-branch-here) nil nil + (?f "Format patch" magit-stash-format-patch)) + :default-action 'magit-stash + :max-action-columns 3) + +;;;###autoload +(defun magit-stash-both (message &optional include-untracked) + "Create a stash of the index and working tree. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive (magit-stash-read-args)) + (magit-stash-save message t t include-untracked t)) + +;;;###autoload +(defun magit-stash-index (message) + "Create a stash of the index only. +Unstaged and untracked changes are not stashed. The stashed +changes are applied in reverse to both the index and the +worktree. This command can fail when the worktree is not clean. +Applying the resulting stash has the inverse effect." + (interactive (list (magit-stash-read-message))) + (magit-stash-save message t nil nil t 'worktree)) + +;;;###autoload +(defun magit-stash-worktree (message &optional include-untracked) + "Create a stash of unstaged changes in the working tree. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive (magit-stash-read-args)) + (magit-stash-save message nil t include-untracked t 'index)) + +;;;###autoload +(defun magit-stash-keep-index (message &optional include-untracked) + "Create a stash of the index and working tree, keeping index intact. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive (magit-stash-read-args)) + (magit-stash-save message t t include-untracked t 'index)) + +(defun magit-stash-read-args () + (list (magit-stash-read-message) + (magit-stash-read-untracked))) + +(defun magit-stash-read-untracked () + (let ((prefix (prefix-numeric-value current-prefix-arg)) + (args (magit-stash-arguments))) + (cond ((or (= prefix 16) (member "--all" args)) 'all) + ((or (= prefix 4) (member "--include-untracked" args)) t)))) + +(defun magit-stash-read-message () + (let* ((default (format "On %s: " + (or (magit-get-current-branch) "(no branch)"))) + (input (magit-read-string "Stash message" default))) + (if (equal input default) + (concat default (magit-rev-format "%h %s")) + input))) + +;;;###autoload +(defun magit-snapshot-both (&optional include-untracked) + "Create a snapshot of the index and working tree. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive (magit-snapshot-read-args)) + (magit-snapshot-save t t include-untracked t)) + +;;;###autoload +(defun magit-snapshot-index () + "Create a snapshot of the index only. +Unstaged and untracked changes are not stashed." + (interactive) + (magit-snapshot-save t nil nil t)) + +;;;###autoload +(defun magit-snapshot-worktree (&optional include-untracked) + "Create a snapshot of unstaged changes in the working tree. +Untracked files are included according to popup arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive (magit-snapshot-read-args)) + (magit-snapshot-save nil t include-untracked t)) + +(defun magit-snapshot-read-args () + (list (magit-stash-read-untracked))) + +(defun magit-snapshot-save (index worktree untracked &optional refresh) + (magit-stash-save (concat "WIP on " (magit-stash-summary)) + index worktree untracked refresh t)) + +;;;###autoload +(defun magit-stash-apply (stash) + "Apply a stash to the working tree. +Try to preserve the stash index. If that fails because there +are staged changes, apply without preserving the stash index." + (interactive (list (magit-read-stash "Apply stash"))) + (if (= (magit-call-git "stash" "apply" "--index" stash) 0) + (magit-refresh) + (magit-run-git "stash" "apply" stash))) + +(defun magit-stash-pop (stash) + "Apply a stash to the working tree and remove it from stash list. +Try to preserve the stash index. If that fails because there +are staged changes, apply without preserving the stash index +and forgo removing the stash." + (interactive (list (magit-read-stash "Pop stash"))) + (if (= (magit-call-git "stash" "apply" "--index" stash) 0) + (magit-stash-drop stash) + (magit-run-git "stash" "apply" stash))) + +;;;###autoload +(defun magit-stash-drop (stash) + "Remove a stash from the stash list. +When the region is active offer to drop all contained stashes." + (interactive (list (--if-let (magit-region-values 'stash) + (magit-confirm t nil "Drop %i stashes" nil it) + (magit-read-stash "Drop stash")))) + (dolist (stash (if (listp stash) + (nreverse (prog1 stash (setq stash (car stash)))) + (list stash))) + (message "Deleted refs/%s (was %s)" stash + (magit-rev-parse "--short" stash)) + (magit-call-git "rev-parse" stash) + (magit-call-git "reflog" "delete" "--updateref" "--rewrite" stash)) + (when-let ((ref (and (string-match "\\(.+\\)@{[0-9]+}$" stash) + (match-string 1 stash)))) + (unless (string-match "^refs/" ref) + (setq ref (concat "refs/" ref))) + (unless (magit-rev-verify (concat ref "@{0}")) + (magit-run-git "update-ref" "-d" ref))) + (magit-refresh)) + +;;;###autoload +(defun magit-stash-clear (ref) + "Remove all stashes saved in REF's reflog by deleting REF." + (interactive (let ((ref (or (magit-section-value-if 'stashes) "refs/stash"))) + (magit-confirm t (format "Drop all stashes in %s" ref)) + (list ref))) + (magit-run-git "update-ref" "-d" ref)) + +;;;###autoload +(defun magit-stash-branch (stash branch) + "Create and checkout a new BRANCH from STASH." + (interactive (list (magit-read-stash "Branch stash") + (magit-read-string-ns "Branch name"))) + (magit-run-git "stash" "branch" branch stash)) + +;;;###autoload +(defun magit-stash-branch-here (stash branch) + "Create and checkout a new BRANCH and apply STASH. +The branch is created using `magit-branch', using the current +branch or `HEAD' as the string-point." + (interactive (list (magit-read-stash "Branch stash") + (magit-read-string-ns "Branch name"))) + (let ((inhibit-magit-refresh t)) + (magit-branch-create branch (or (magit-get-current-branch) "HEAD"))) + (magit-stash-apply stash)) + +;;;###autoload +(defun magit-stash-format-patch (stash) + "Create a patch from STASH" + (interactive (list (magit-read-stash "Create patch from stash"))) + (with-temp-file (magit-rev-format "0001-%f.patch" stash) + (magit-git-insert "stash" "show" "-p" stash)) + (magit-refresh)) + +;;; Plumbing + +(defun magit-stash-save (message index worktree untracked + &optional refresh keep noerror ref) + (if (or (and index (magit-staged-files t)) + (and worktree (magit-unstaged-files t)) + (and untracked (magit-untracked-files (eq untracked 'all)))) + (magit-with-toplevel + (magit-stash-store message (or ref "refs/stash") + (magit-stash-create message index worktree untracked)) + (if (eq keep 'worktree) + (with-temp-buffer + (magit-git-insert "diff" "--cached") + (magit-run-git-with-input + "apply" "--reverse" "--cached" "--ignore-space-change" "-") + (magit-run-git-with-input + "apply" "--reverse" "--ignore-space-change" "-")) + (unless (eq keep t) + (if (eq keep 'index) + (magit-call-git "checkout" "--" ".") + (magit-call-git "reset" "--hard" "HEAD")) + (when untracked + (magit-call-git "clean" "--force" "-d" + (and (eq untracked 'all) "-x"))))) + (when refresh + (magit-refresh))) + (unless noerror + (user-error "No %s changes to save" (cond ((not index) "unstaged") + ((not worktree) "staged") + (t "local")))))) + +(defun magit-stash-store (message ref commit) + (magit-update-ref ref message commit t)) + +(defun magit-stash-create (message index worktree untracked) + (unless (magit-rev-parse "--verify" "HEAD") + (error "You do not have the initial commit yet")) + (let ((magit-git-global-arguments (nconc (list "-c" "commit.gpgsign=false") + magit-git-global-arguments)) + (default-directory (magit-toplevel)) + (summary (magit-stash-summary)) + (head "HEAD")) + (when (and worktree (not index)) + (setq head (or (magit-commit-tree "pre-stash index" nil "HEAD") + (error "Cannot save the current index state")))) + (or (setq index (magit-commit-tree (concat "index on " summary) nil head)) + (error "Cannot save the current index state")) + (and untracked + (setq untracked (magit-untracked-files (eq untracked 'all))) + (setq untracked (magit-with-temp-index nil nil + (or (and (magit-update-files untracked) + (magit-commit-tree + (concat "untracked files on " summary))) + (error "Cannot save the untracked files"))))) + (magit-with-temp-index index "-m" + (when worktree + (or (magit-update-files (magit-git-items "diff" "-z" "--name-only" head)) + (error "Cannot save the current worktree state"))) + (or (magit-commit-tree message nil head index untracked) + (error "Cannot save the current worktree state"))))) + +(defun magit-stash-summary () + (concat (or (magit-get-current-branch) "(no branch)") + ": " (magit-rev-format "%h %s"))) + +;;; Sections + +(defvar magit-stashes-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-delete-thing] 'magit-stash-clear) + map) + "Keymap for `stashes' section.") + +(defvar magit-stash-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-stash-show) + (define-key map [remap magit-delete-thing] 'magit-stash-drop) + (define-key map "a" 'magit-stash-apply) + (define-key map "A" 'magit-stash-pop) + map) + "Keymap for `stash' sections.") + +(magit-define-section-jumper magit-jump-to-stashes + "Stashes" stashes "refs/stash") + +(cl-defun magit-insert-stashes (&optional (ref "refs/stash") + (heading "Stashes:")) + "Insert `stashes' section showing reflog for \"refs/stash\". +If optional REF is non-nil, show reflog for that instead. +If optional HEADING is non-nil, use that as section heading +instead of \"Stashes:\"." + (let ((verified (magit-rev-verify ref)) + (autostash + (and (magit-rebase-in-progress-p) + (magit-file-line + (magit-git-dir + (-> (if (file-directory-p (magit-git-dir "rebase-merge")) + "rebase-merge/autostash" + "rebase-apply/autostash"))))))) + (when (or autostash verified) + (magit-insert-section (stashes ref) + (magit-insert-heading heading) + (when autostash + (pcase-let ((`(,author ,date ,msg) + (split-string + (car (magit-git-lines + "show" "-q" "--format=%aN%x00%at%x00%s" + autostash)) + "\0"))) + (magit-insert-section (stash autostash) + (insert (propertize "AUTOSTASH" 'face 'magit-hash)) + (insert " " msg "\n") + (save-excursion + (backward-char) + (magit-log-format-margin autostash author date))))) + (if verified + (magit-git-wash (apply-partially 'magit-log-wash-log 'stash) + "reflog" "--format=%gd%x00%aN%x00%at%x00%gs" ref) + (insert ?\n) + (save-excursion + (backward-char) + (magit-make-margin-overlay))))))) + +;;; List Stashes + +;;;###autoload +(defun magit-stash-list () + "List all stashes in a buffer." + (interactive) + (magit-mode-setup #'magit-stashes-mode "refs/stash")) + +(define-derived-mode magit-stashes-mode magit-reflog-mode "Magit Stashes" + "Mode for looking at lists of stashes." + :group 'magit-log + (hack-dir-local-variables-non-file-buffer) + (setq-local bookmark-make-record-function + #'magit-bookmark--stashes-make-record)) + +(cl-defun magit-stashes-refresh-buffer (ref) + (magit-insert-section (stashesbuf) + (magit-insert-heading (if (equal ref "refs/stash") + "Stashes:" + (format "Stashes [%s]:" ref))) + (magit-git-wash (apply-partially 'magit-log-wash-log 'stash) + "reflog" "--format=%gd%x00%aN%x00%at%x00%gs" ref))) + +;;; Show Stash + +;;;###autoload +(defun magit-stash-show (stash &optional args files) + "Show all diffs of a stash in a buffer." + (interactive (cons (or (and (not current-prefix-arg) + (magit-stash-at-point)) + (magit-read-stash "Show stash")) + (pcase-let ((`(,args ,files) (magit-diff-arguments))) + (list (delete "--stat" args) files)))) + (magit-mode-setup #'magit-stash-mode stash nil args files)) + +(define-derived-mode magit-stash-mode magit-diff-mode "Magit Stash" + "Mode for looking at individual stashes." + :group 'magit-diff + (hack-dir-local-variables-non-file-buffer) + (setq-local bookmark-make-record-function + #'magit-bookmark--stash-make-record)) + +(defun magit-stash-refresh-buffer (stash _const _args _files) + (magit-set-header-line-format + (concat (propertize (capitalize stash) 'face 'magit-section-heading) + " " + (magit-rev-format "%s" stash))) + (setq magit-buffer-revision-hash (magit-rev-parse stash)) + (magit-insert-section (stash) + (magit-run-section-hook 'magit-stash-sections-hook))) + +(defun magit-stash-insert-section (commit range message &optional files) + (magit-insert-section (commit commit) + (magit-insert-heading message) + (magit-git-wash #'magit-diff-wash-diffs + "diff" range "-p" "--no-prefix" + (nth 2 magit-refresh-args) + "--" (or files (nth 3 magit-refresh-args))))) + +(defun magit-insert-stash-notes () + "Insert section showing notes for a stash. +This shows the notes for stash@{N} but not for the other commits +that make up the stash." + (magit-insert-section section (note) + (magit-insert-heading "Notes") + (magit-git-insert "notes" "show" (car magit-refresh-args)) + (if (= (point) + (oref section content)) + (magit-cancel-section) + (insert "\n")))) + +(defun magit-insert-stash-index () + "Insert section showing staged changes of the stash." + (let ((stash (car magit-refresh-args))) + (magit-stash-insert-section (format "%s^2" stash) + (format "%s^..%s^2" stash stash) + "Staged"))) + +(defun magit-insert-stash-worktree () + "Insert section showing unstaged changes of the stash." + (let ((stash (car magit-refresh-args))) + (magit-stash-insert-section stash + (format "%s^2..%s" stash stash) + "Unstaged"))) + +(defun magit-insert-stash-untracked () + "Insert section showing the untracked files commit of the stash." + (let ((stash (car magit-refresh-args)) + (rev (concat (car magit-refresh-args) "^3"))) + (when (magit-rev-verify rev) + (magit-stash-insert-section (format "%s^3" stash) + (format "%s^..%s^3" stash stash) + "Untracked files" + (magit-git-items "ls-tree" "-z" "--name-only" + "-r" "--full-tree" rev))))) + +;;; _ +(provide 'magit-stash) +;;; magit-stash.el ends here diff --git a/elpa/magit-20181113.1837/magit-status.el b/elpa/magit-20181113.1837/magit-status.el new file mode 100644 index 00000000..73a31672 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-status.el @@ -0,0 +1,634 @@ +;;; magit-status.el --- the grand overview -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements the status buffer. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +(defvar bookmark-make-record-function) + +;;; Options + +(defgroup magit-status nil + "Inspect and manipulate Git repositories." + :link '(info-link "(magit)Status Buffer") + :group 'magit-modes) + +(defcustom magit-status-mode-hook nil + "Hook run after entering Magit-Status mode." + :group 'magit-status + :type 'hook) + +(defcustom magit-status-headers-hook + '(magit-insert-error-header + magit-insert-diff-filter-header + magit-insert-head-branch-header + magit-insert-upstream-branch-header + magit-insert-push-branch-header + magit-insert-tags-header) + "Hook run to insert headers into the status buffer. + +This hook is run by `magit-insert-status-headers', which in turn +has to be a member of `magit-status-sections-hook' to be used at +all." + :package-version '(magit . "2.1.0") + :group 'magit-status + :type 'hook + :options '(magit-insert-error-header + magit-insert-diff-filter-header + magit-insert-repo-header + magit-insert-remote-header + magit-insert-head-branch-header + magit-insert-upstream-branch-header + magit-insert-push-branch-header + magit-insert-tags-header)) + +(defcustom magit-status-sections-hook + '(magit-insert-status-headers + magit-insert-merge-log + magit-insert-rebase-sequence + magit-insert-am-sequence + magit-insert-sequencer-sequence + magit-insert-bisect-output + magit-insert-bisect-rest + magit-insert-bisect-log + magit-insert-untracked-files + magit-insert-unstaged-changes + magit-insert-staged-changes + magit-insert-stashes + magit-insert-unpushed-to-pushremote + magit-insert-unpushed-to-upstream-or-recent + magit-insert-unpulled-from-pushremote + magit-insert-unpulled-from-upstream) + "Hook run to insert sections into a status buffer." + :package-version '(magit . "2.12.0") + :group 'magit-status + :type 'hook) + +(defcustom magit-status-initial-section '(1) + "The section point is placed on when a status buffer is created. + +When such a buffer is merely being refreshed or being shown again +after it was merely burried, then this option has no effect. + +If this is nil, then point remains on the very first section as +usual. Otherwise it has to be a list of integers and section +identity lists. The members of that list are tried in order +until a matching section is found. + +An integer means to jump to the nth section, 1 for example +jumps over the headings. To get a section's \"identity list\" +use \\[universal-argument] \\[magit-describe-section-briefly]. + +If, for example, you want to jump to the commits that haven't +been pulled from the upstream, or else the second section, then +use: (((unpulled . \"..@{upstream}\") (status)) 1). + +See option `magit-section-initial-visibility-alist' for how to +control the initial visibility of the jumped to section." + :package-version '(magit . "2.90.0") + :group 'magit-status + :type '(choice (const :tag "as usual" nil) + (repeat (choice (number :tag "nth top-level section") + (sexp :tag "section identity"))))) + +(defcustom magit-status-show-hashes-in-headers nil + "Whether headers in the status buffer show hashes. +The functions which respect this option are +`magit-insert-head-branch-header', +`magit-insert-upstream-branch-header', and +`magit-insert-push-branch-header'." + :package-version '(magit . "2.4.0") + :group 'magit-status + :type 'boolean) + +(defcustom magit-status-margin + (list nil + (nth 1 magit-log-margin) + 'magit-log-margin-width nil + (nth 4 magit-log-margin)) + "Format of the margin in `magit-status-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the committer date. It can be one + of `age' (to show the age of the commit), `age-abbreviated' (to + abbreviate the time unit to a character), or a string (suitable + for `format-time-string') to show the actual date. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-status + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize 'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-status-mode)) + +;;; Commands + +;;;###autoload +(defun magit-init (directory) + "Initialize a Git repository, then show its status. + +If the directory is below an existing repository, then the user +has to confirm that a new one should be created inside. If the +directory is the root of the existing repository, then the user +has to confirm that it should be reinitialized. + +Non-interactively DIRECTORY is (re-)initialized unconditionally." + (interactive + (let ((directory (file-name-as-directory + (expand-file-name + (read-directory-name "Create repository in: "))))) + (when-let ((toplevel (magit-toplevel directory))) + (setq toplevel (expand-file-name toplevel)) + (unless (y-or-n-p (if (file-equal-p toplevel directory) + (format "Reinitialize existing repository %s? " + directory) + (format "%s is a repository. Create another in %s? " + toplevel directory))) + (user-error "Abort"))) + (list directory))) + ;; `git init' does not understand the meaning of "~"! + (magit-call-git "init" (magit-convert-filename-for-git + (expand-file-name directory))) + (magit-status-internal directory)) + +;;;###autoload +(defun magit-status (&optional directory cache) + "Show the status of the current Git repository in a buffer. +With a prefix argument prompt for a repository to be shown. +With two prefix arguments prompt for an arbitrary directory. +If that directory isn't the root of an existing repository, +then offer to initialize it as a new repository." + (interactive + (let ((magit--refresh-cache (list (cons 0 0)))) + (list (and (or current-prefix-arg (not (magit-toplevel))) + (magit-read-repository + (>= (prefix-numeric-value current-prefix-arg) 16))) + magit--refresh-cache))) + (let ((magit--refresh-cache (or cache (list (cons 0 0))))) + (if directory + (let ((toplevel (magit-toplevel directory))) + (setq directory (file-name-as-directory + (expand-file-name directory))) + (if (and toplevel (file-equal-p directory toplevel)) + (magit-status-internal directory) + (when (y-or-n-p + (if toplevel + (format "%s is a repository. Create another in %s? " + toplevel directory) + (format "Create repository in %s? " directory))) + ;; Creating a new repository will invalidate cached + ;; values. + (setq magit--refresh-cache nil) + (magit-init directory)))) + (magit-status-internal default-directory)))) + +(put 'magit-status 'interactive-only 'magit-status-internal) + +(defalias 'magit 'magit-status + "An alias for `magit-status' for better discoverability. + +Instead of invoking this alias for `magit-status' using +\"M-x magit RET\", you should bind a key to `magit-status' +and read the info node `(magit)Getting Started', which +also contains other useful hints.") + +;;;###autoload +(defun magit-status-internal (directory) + (magit--tramp-asserts directory) + (let ((default-directory directory)) + (magit-mode-setup #'magit-status-mode))) + +(defvar magit--remotes-using-recent-git nil) + +(defun magit--tramp-asserts (directory) + (when-let ((remote (file-remote-p directory))) + (unless (member remote magit--remotes-using-recent-git) + (if-let ((version (let ((default-directory directory)) + (magit-git-version)))) + (if (version<= magit--minimal-git version) + (push version magit--remotes-using-recent-git) + (display-warning 'magit (format "\ +Magit requires Git >= %s, but on %s the version is %s. + +If multiple Git versions are installed on the host, then the +problem might be that TRAMP uses the wrong executable. + +First check the value of `magit-git-executable'. Its value is +used when running git locally as well as when running it on a +remote host. The default value is \"git\", except on Windows +where an absolute path is used for performance reasons. + +If the value already is just \"git\" but TRAMP never-the-less +doesn't use the correct executable, then consult the info node +`(tramp)Remote programs'.\n" magit--minimal-git remote version) :error)) + (display-warning 'magit (format "\ +Magit cannot find Git on %s. + +First check the value of `magit-git-executable'. Its value is +used when running git locally as well as when running it on a +remote host. The default value is \"git\", except on Windows +where an absolute path is used for performance reasons. + +If the value already is just \"git\" but TRAMP never-the-less +doesn't find the executable, then consult the info node +`(tramp)Remote programs'.\n" remote) :error))))) + +;;; Mode + +(defvar magit-status-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-mode-map) + (define-key map "jz" 'magit-jump-to-stashes) + (define-key map "jt" 'magit-jump-to-tracked) + (define-key map "jn" 'magit-jump-to-untracked) + (define-key map "ju" 'magit-jump-to-unstaged) + (define-key map "js" 'magit-jump-to-staged) + (define-key map "jfu" 'magit-jump-to-unpulled-from-upstream) + (define-key map "jfp" 'magit-jump-to-unpulled-from-pushremote) + (define-key map "jpu" 'magit-jump-to-unpushed-to-upstream) + (define-key map "jpp" 'magit-jump-to-unpushed-to-pushremote) + (define-key map [remap dired-jump] 'magit-dired-jump) + map) + "Keymap for `magit-status-mode'.") + +(define-derived-mode magit-status-mode magit-mode "Magit" + "Mode for looking at Git status. + +This mode is documented in info node `(magit)Status Buffer'. + +\\\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-section-toggle] to expand or hide the section at point. +Type \\[magit-visit-thing] to visit the change or commit at point. + +Type \\[magit-dispatch-popup] to see available prefix popups. + +Staging and applying changes is documented in info node +`(magit)Staging and Unstaging' and info node `(magit)Applying'. + +\\Type \ +\\[magit-apply] to apply the change at point, \ +\\[magit-stage] to stage, +\\[magit-unstage] to unstage, \ +\\[magit-discard] to discard, or \ +\\[magit-reverse] to reverse it. + +\\\ +Type \\[magit-commit-popup] to create a commit. + +\\{magit-status-mode-map}" + :group 'magit-status + (hack-dir-local-variables-non-file-buffer) + (setq imenu-create-index-function + 'magit-imenu--status-create-index-function) + (setq-local bookmark-make-record-function + #'magit-bookmark--status-make-record)) + +(defun magit-status-refresh-buffer () + (magit-git-exit-code "update-index" "--refresh") + (magit-insert-section (status) + (magit-run-section-hook 'magit-status-sections-hook))) + +(defun magit-status-goto-initial-section () + "In a `magit-status-mode' buffer, jump `magit-status-initial-section'. +Actually doing so is deferred until `magit-refresh-buffer-hook' +runs `magit-status-goto-initial-section-1'. That function then +removes itself from the hook, so that this only happens when the +status buffer is first created." + (when (and magit-status-initial-section + (derived-mode-p 'magit-status-mode)) + (add-hook 'magit-refresh-buffer-hook + 'magit-status-goto-initial-section-1 nil t))) + +(defun magit-status-goto-initial-section-1 () + "In a `magit-status-mode' buffer, jump `magit-status-initial-section'. +This function removes itself from `magit-refresh-buffer-hook'." + (when-let ((section + (--some (if (integerp it) + (nth (1- it) + (magit-section-siblings (magit-current-section) + 'next)) + (magit-get-section it)) + magit-status-initial-section))) + (goto-char (oref section start)) + (when-let ((vis (cdr (assq 'magit-status-initial-section + magit-section-initial-visibility-alist)))) + (if (eq vis 'hide) + (magit-section-hide section) + (magit-section-show section)))) + (remove-hook 'magit-refresh-buffer-hook + 'magit-status-goto-initial-section-1 t)) + +(defun magit-status-maybe-update-revision-buffer (&optional _) + "When moving in the status buffer, update the revision buffer. +If there is no revision buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-status-mode) + (magit-log-maybe-update-revision-buffer-1))) + +(defun magit-status-maybe-update-blob-buffer (&optional _) + "When moving in the status buffer, update the blob buffer. +If there is no blob buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-status-mode) + (magit-log-maybe-update-blob-buffer-1))) + +;;; Sections +;;;; Special Headers + +(defun magit-insert-status-headers () + "Insert header sections appropriate for `magit-status-mode' buffers. +The sections are inserted by running the functions on the hook +`magit-status-headers-hook'." + (if (magit-rev-verify "HEAD") + (magit-insert-headers 'magit-status-headers-hook) + (insert "In the beginning there was darkness\n\n"))) + +(defvar magit-error-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-process-buffer) + map) + "Keymap for `error' sections.") + +(defun magit-insert-error-header () + "Insert the message about the Git error that just occured. + +This function is only aware of the last error that occur when Git +was run for side-effects. If, for example, an error occurs while +generating a diff, then that error won't be inserted. Refreshing +the status buffer causes this section to disappear again." + (when magit-this-error + (magit-insert-section (error 'git) + (insert (propertize (format "%-10s" "GitError! ") + 'face 'magit-section-heading)) + (insert (propertize magit-this-error 'face 'font-lock-warning-face)) + (when-let ((key (car (where-is-internal 'magit-process-buffer)))) + (insert (format " [Type `%s' for details]" (key-description key)))) + (insert ?\n)) + (setq magit-this-error nil))) + +(defun magit-insert-diff-filter-header () + "Insert a header line showing the effective diff filters." + (let ((ignore-modules (magit-ignore-submodules-p))) + (when (or ignore-modules + magit-diff-section-file-args) + (insert (propertize (format "%-10s" "Filter! ") + 'face 'magit-section-heading)) + (when ignore-modules + (insert ignore-modules) + (when magit-diff-section-file-args + (insert " -- "))) + (when magit-diff-section-file-args + (insert (mapconcat #'identity magit-diff-section-file-args " "))) + (insert ?\n)))) + +;;;; Reference Headers + +(cl-defun magit-insert-head-branch-header + (&optional (branch (magit-get-current-branch))) + "Insert a header line about BRANCH. +When BRANCH is nil, use the current branch or, if none, the +detached `HEAD'." + (let ((output (magit-rev-format "%h %s" (or branch "HEAD")))) + (string-match "^\\([^ ]+\\) \\(.*\\)" output) + (magit-bind-match-strings (commit summary) output + (if branch + (magit-insert-section (branch branch) + (insert (format "%-10s" "Head: ")) + (when magit-status-show-hashes-in-headers + (insert (propertize commit 'face 'magit-hash) ?\s)) + (insert (propertize branch 'face 'magit-branch-local)) + (insert ?\s) + (insert (funcall magit-log-format-message-function branch summary)) + (insert ?\n)) + (magit-insert-section (commit commit) + (insert (format "%-10s" "Head: ")) + (insert (propertize commit 'face 'magit-hash)) + (insert ?\s summary ?\n)))))) + +(cl-defun magit-insert-upstream-branch-header + (&optional (branch (magit-get-current-branch)) + (pull (magit-get-upstream-branch branch)) + keyword) + "Insert a header line about branch usually pulled into current branch." + (when pull + (magit-insert-section (branch pull) + (let ((rebase (magit-get "branch" branch "rebase"))) + (pcase rebase + ("true") + ("false" (setq rebase nil)) + (_ (setq rebase (magit-get-boolean "pull.rebase")))) + (insert (format "%-10s" (or keyword (if rebase "Rebase: " "Merge: "))))) + (--when-let (and magit-status-show-hashes-in-headers + (not (string-match-p " " pull)) + (magit-rev-format "%h" pull)) + (insert (propertize it 'face 'magit-hash) " ")) + (if (string-match-p " " pull) + (pcase-let ((`(,url ,branch) (split-string pull " "))) + (insert branch " from " url " ")) + (insert pull " ") + (--if-let (and (magit-rev-verify pull) + (magit-rev-format "%s" pull)) + (insert (funcall magit-log-format-message-function pull it)) + (insert (propertize "is missing" 'face 'font-lock-warning-face)))) + (insert ?\n)))) + +(cl-defun magit-insert-push-branch-header + (&optional (branch (magit-get-current-branch)) + (push (magit-get-push-branch branch))) + "Insert a header line about the branch the current branch is pushed to." + (when push + (magit-insert-section (branch push) + (insert (format "%-10s" "Push: ")) + (--when-let (and magit-status-show-hashes-in-headers + (magit-rev-format "%h" push)) + (insert (propertize it 'face 'magit-hash) ?\s)) + (insert (propertize push 'face 'magit-branch-remote) ?\s) + (--if-let (and (magit-rev-verify push) + (magit-rev-format "%s" push)) + (insert (funcall magit-log-format-message-function push it)) + (insert (propertize "is missing" 'face 'font-lock-warning-face))) + (insert ?\n)))) + +(defun magit-insert-tags-header () + "Insert a header line about the current and/or next tag." + (let* ((this-tag (magit-get-current-tag nil t)) + (next-tag (magit-get-next-tag nil t)) + (this-cnt (cadr this-tag)) + (next-cnt (cadr next-tag)) + (this-tag (car this-tag)) + (next-tag (car next-tag)) + (both-tags (and this-tag next-tag t))) + (when (or this-tag next-tag) + (magit-insert-section (tag (or this-tag next-tag)) + (insert (format "%-10s" (if both-tags "Tags: " "Tag: "))) + (cl-flet ((insert-count + (tag count face) + (insert (concat (propertize tag 'face 'magit-tag) + (and (> count 0) + (format " (%s)" + (propertize (format "%s" count) + 'face face))))))) + (when this-tag (insert-count this-tag this-cnt 'magit-branch-local)) + (when both-tags (insert ", ")) + (when next-tag (insert-count next-tag next-cnt 'magit-tag))) + (insert ?\n))))) + +;;;; Auxiliary Headers + +(defun magit-insert-user-header () + "Insert a header line about the current user." + (let ((name (magit-get "user.name")) + (email (magit-get "user.email"))) + (when (and name email) + (magit-insert-section (user name) + (insert (format "%-10s" "User: ")) + (insert (propertize name 'face 'magit-log-author)) + (insert " <" email ">\n"))))) + +(defun magit-insert-repo-header () + "Insert a header line showing the path to the repository top-level." + (let ((topdir (magit-toplevel))) + (magit-insert-section (repo topdir) + (insert (format "%-10s%s\n" "Repo: " (abbreviate-file-name topdir)))))) + +(defun magit-insert-remote-header () + "Insert a header line about the remote of the current branch. + +If no remote is configured for the current branch, then fall back +showing the \"origin\" remote, or if that does not exist the first +remote in alphabetic order." + (when-let ((name (magit-get-some-remote)) + ;; Under certain configurations it's possible for url + ;; to be nil, when name is not, see #2858. + (url (magit-get "remote" name "url"))) + (magit-insert-section (remote name) + (insert (format "%-10s" "Remote: ")) + (insert (propertize name 'face 'magit-branch-remote) ?\s) + (insert url ?\n)))) + +;;;; File Sections + +(defvar magit-untracked-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-delete-thing] 'magit-discard) + (define-key map "s" 'magit-stage) + map) + "Keymap for the `untracked' section.") + +(magit-define-section-jumper magit-jump-to-untracked "Untracked files" untracked) + +(defun magit-insert-untracked-files () + "Maybe insert a list or tree of untracked files. + +Do so depending on the value of `status.showUntrackedFiles'. +Note that even if the value is `all', Magit still initially +only shows directories. But the directory sections can then +be expanded using \"TAB\". + +If the first element of `magit-diff-section-arguments' is a +directory, then limit the list to files below that. The value +value of that variable can be set using \"D = f DIRECTORY RET g\"." + (let* ((show (or (magit-get "status.showUntrackedFiles") "normal")) + (base (car magit-diff-section-file-args)) + (base (and base (file-directory-p base) base))) + (unless (equal show "no") + (if (equal show "all") + (when-let ((files (magit-untracked-files nil base))) + (magit-insert-section (untracked) + (magit-insert-heading "Untracked files:") + (magit-insert-files files base) + (insert ?\n))) + (when-let ((files + (--mapcat (and (eq (aref it 0) ??) + (list (substring it 3))) + (magit-git-items "status" "-z" "--porcelain" + (magit-ignore-submodules-p) + "--" base)))) + (magit-insert-section (untracked) + (magit-insert-heading "Untracked files:") + (dolist (file files) + (magit-insert-section (file file) + (insert (propertize file 'face 'magit-filename) ?\n))) + (insert ?\n))))))) + +(magit-define-section-jumper magit-jump-to-tracked "Tracked files" tracked) + +(defun magit-insert-tracked-files () + "Insert a tree of tracked files. + +If the first element of `magit-diff-section-arguments' is a +directory, then limit the list to files below that. The value +value of that variable can be set using \"D = f DIRECTORY RET g\"." + (when-let ((files (magit-list-files))) + (let* ((base (car magit-diff-section-file-args)) + (base (and base (file-directory-p base) base))) + (magit-insert-section (tracked nil t) + (magit-insert-heading "Tracked files:") + (magit-insert-files files base) + (insert ?\n))))) + +(defun magit-insert-ignored-files () + "Insert a tree of ignored files. + +If the first element of `magit-diff-section-arguments' is a +directory, then limit the list to files below that. The value +of that variable can be set using \"D = f DIRECTORY RET g\"." + (when-let ((files (magit-ignored-files))) + (let* ((base (car magit-diff-section-file-args)) + (base (and base (file-directory-p base) base))) + (magit-insert-section (tracked nil t) + (magit-insert-heading "Ignored files:") + (magit-insert-files files base) + (insert ?\n))))) + +(defun magit-insert-files (files directory) + (while (and files (string-prefix-p (or directory "") (car files))) + (let ((dir (file-name-directory (car files)))) + (if (equal dir directory) + (let ((file (pop files))) + (magit-insert-section (file file) + (insert (propertize file 'face 'magit-filename) ?\n))) + (magit-insert-section (file dir t) + (insert (propertize dir 'file 'magit-filename) ?\n) + (magit-insert-heading) + (setq files (magit-insert-files files dir)))))) + files) + +;;; _ +(provide 'magit-status) +;;; magit-status.el ends here diff --git a/elpa/magit-20181113.1837/magit-submodule.el b/elpa/magit-20181113.1837/magit-submodule.el new file mode 100644 index 00000000..d05b7e8d --- /dev/null +++ b/elpa/magit-20181113.1837/magit-submodule.el @@ -0,0 +1,636 @@ +;;; magit-submodule.el --- submodule support for Magit -*- lexical-binding: t -*- + +;; Copyright (C) 2011-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit) + +(defvar x-stretch-cursor) +(defvar bookmark-make-record-function) + +;;; Options + +(defcustom magit-module-sections-hook + '(magit-insert-modules-overview + magit-insert-modules-unpulled-from-upstream + magit-insert-modules-unpulled-from-pushremote + magit-insert-modules-unpushed-to-upstream + magit-insert-modules-unpushed-to-pushremote) + "Hook run by `magit-insert-modules'. + +That function isn't part of `magit-status-sections-hook's default +value, so you have to add it yourself for this hook to have any +effect." + :package-version '(magit . "2.11.0") + :group 'magit-status + :type 'hook) + +(defcustom magit-module-sections-nested t + "Whether `magit-insert-modules' wraps inserted sections. + +If this is non-nil, then only a single top-level section +is inserted. If it is nil, then all sections listed in +`magit-module-sections-hook' become top-level sections." + :package-version '(magit . "2.11.0") + :group 'magit-status + :type 'boolean) + +(defcustom magit-submodule-list-mode-hook '(hl-line-mode) + "Hook run after entering Magit-Submodule-List mode." + :package-version '(magit . "2.9.0") + :group 'magit-repolist + :type 'hook + :get 'magit-hook-custom-get + :options '(hl-line-mode)) + +(defcustom magit-submodule-list-columns + '(("Path" 25 magit-modulelist-column-path nil) + ("Version" 25 magit-repolist-column-version nil) + ("Branch" 20 magit-repolist-column-branch nil) + ("BU" 3 magit-repolist-column-unpushed-to-upstream ((:right-align t))) + ("BP" 3 magit-repolist-column-unpushed-to-pushremote ((:right-align t))) + ("B" 3 magit-repolist-column-branches ((:right-align t))) + ("S" 3 magit-repolist-column-stashes ((:right-align t)))) + "List of columns displayed by `magit-list-submodules'. + +Each element has the form (HEADER WIDTH FORMAT PROPS). + +HEADER is the string displayed in the header. WIDTH is the width +of the column. FORMAT is a function that is called with one +argument, the repository identification (usually its basename), +and with `default-directory' bound to the toplevel of its working +tree. It has to return a string to be inserted or nil. PROPS is +an alist that supports the keys `:right-align' and `:pad-right'." + :package-version '(magit . "2.8.0") + :group 'magit-repolist-mode + :type `(repeat (list :tag "Column" + (string :tag "Header Label") + (integer :tag "Column Width") + (function :tag "Inserter Function") + (repeat :tag "Properties" + (list (choice :tag "Property" + (const :right-align) + (const :pad-right) + (symbol)) + (sexp :tag "Value")))))) + +(defcustom magit-submodule-remove-trash-gitdirs nil + "Whether `magit-submodule-remove' offers to trash module gitdirs. + +If this is nil, then that command does not offer to do so unless +a prefix argument is used. When this is t, then it does offer to +do so even without a prefix argument. + +In both cases the action still has to be confirmed unless that is +disabled using the option `magit-no-confirm'. Doing the latter +and also setting this variable to t will lead to tears." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type 'boolean) + +;;; Popup + +;;;###autoload (autoload 'magit-submodule-popup "magit-submodule" nil t) +(magit-define-popup magit-submodule-popup + "Popup console for submodule commands." + :man-page "git-submodule" + :switches '((?f "Force" "--force") + (?r "Recursive" "--recursive") + (?N "Do not fetch" "--no-fetch") + (?C "Checkout tip" "--checkout") + (?R "Rebase onto tip" "--rebase") + (?M "Merge tip" "--merge") + (?U "Use upstream tip" "--remote")) + :actions + '((?a "Add git submodule add [--force]" + magit-submodule-add) + (?r "Register git submodule init" + magit-submodule-register) + (?p "Populate git submodule update --init" + magit-submodule-populate) + (?u "Update git submodule update [--force] [--no-fetch] + [--remote] [--recursive] [--checkout|--rebase|--merge]" + magit-submodule-update) + (?s "Synchronize git submodule sync [--recursive]" + magit-submodule-synchronize) + (?d "Unpopulate git submodule deinit [--force]" + magit-submodule-unpopulate) + (?k "Remove" magit-submodule-remove) + nil + (?l "List all modules" magit-list-submodules) + (?f "Fetch all modules" magit-fetch-modules)) + :max-action-columns 1) + +(defun magit-submodule-filtered-arguments (&rest filters) + (--filter (and (member it filters) it) + (magit-submodule-arguments))) + +;;;###autoload +(defun magit-submodule-add (url &optional path name args) + "Add the repository at URL as a module. + +Optional PATH is the path to the module relative to the root of +the superproject. If it is nil, then the path is determined +based on the URL. Optional NAME is the name of the module. If +it is nil, then PATH also becomes the name." + (interactive + (magit-with-toplevel + (let* ((url (magit-read-string-ns "Add submodule (remote url)")) + (path (let ((read-file-name-function + (if (or (eq read-file-name-function 'ido-read-file-name) + (advice-function-member-p + 'ido-read-file-name + read-file-name-function)) + ;; The Ido variant doesn't work properly here. + #'read-file-name-default + read-file-name-function))) + (directory-file-name + (file-relative-name + (read-directory-name + "Add submodules at path: " nil nil nil + (and (string-match "\\([^./]+\\)\\(\\.git\\)?$" url) + (match-string 1 url)))))))) + (list url + (directory-file-name path) + (magit-submodule-read-name-for-path path) + (magit-submodule-filtered-arguments "--force"))))) + (magit-with-toplevel + (magit-submodule--maybe-reuse-gitdir name path) + (magit-run-git-async "submodule" "add" + (and name (list "--name" name)) + args "--" url path) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (unless (version< (magit-git-version) "2.12.0") + (magit-call-git "submodule" "absorbgitdirs" path)) + (magit-refresh))))))) + +;;;###autoload +(defun magit-submodule-read-name-for-path (path &optional prefer-short) + (let* ((path (directory-file-name (file-relative-name path))) + (name (file-name-nondirectory path))) + (push (if prefer-short path name) minibuffer-history) + (magit-read-string-ns + "Submodule name" nil (cons 'minibuffer-history 2) + (or (--keep (pcase-let ((`(,var ,val) (split-string it "="))) + (and (equal val path) + (cadr (split-string var "\\.")))) + (magit-git-lines "config" "--list" "-f" ".gitmodules")) + (if prefer-short name path))))) + +;;;###autoload +(defun magit-submodule-register (modules) + "Register MODULES. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + ;; This command and the underlying "git submodule init" do NOT + ;; "initialize" modules. They merely "register" modules in the + ;; super-projects $GIT_DIR/config file, the purpose of which is to + ;; allow users to change such values before actually initializing + ;; the modules. + (interactive + (list (magit-module-confirm "Register" 'magit-module-no-worktree-p))) + (magit-with-toplevel + (magit-run-git-async "submodule" "init" "--" modules))) + +;;;###autoload +(defun magit-submodule-populate (modules) + "Create MODULES working directories, checking out the recorded commits. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + ;; This is the command that actually "initializes" modules. + ;; A module is initialized when it has a working directory, + ;; a gitlink, and a .gitmodules entry. + (interactive + (list (magit-module-confirm "Populate" 'magit-module-no-worktree-p))) + (magit-with-toplevel + (magit-run-git-async "submodule" "update" "--init" "--" modules))) + +;;;###autoload +(defun magit-submodule-update (modules args) + "Update MODULES by checking out the recorded commits. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + ;; Unlike `git-submodule's `update' command ours can only update + ;; "initialized" modules by checking out other commits but not + ;; "initialize" modules by creating the working directories. + ;; To do the latter we provide the "setup" command. + (interactive + (list (magit-module-confirm "Update" 'magit-module-worktree-p) + (magit-submodule-filtered-arguments + "--force" "--remote" "--recursive" "--checkout" "--rebase" "--merge" + "--no-fetch"))) + (magit-with-toplevel + (magit-run-git-async "submodule" "update" args "--" modules))) + +;;;###autoload +(defun magit-submodule-synchronize (modules args) + "Synchronize url configuration of MODULES. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + (interactive + (list (magit-module-confirm "Synchronize" 'magit-module-worktree-p) + (magit-submodule-filtered-arguments "--recursive"))) + (magit-with-toplevel + (magit-run-git-async "submodule" "sync" args "--" modules))) + +;;;###autoload +(defun magit-submodule-unpopulate (modules args) + "Remove working directories of MODULES. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + ;; Even though a package is "uninitialized" (it has no worktree) + ;; the super-projects $GIT_DIR/config may never-the-less set the + ;; module's url. This may happen if you `deinit' and then `init' + ;; to register (NOT initialize). Because the purpose of `deinit' + ;; is to remove the working directory AND to remove the url, this + ;; command does not limit itself to modules that have no working + ;; directory. + (interactive + (list (magit-module-confirm "Unpopulate") + (magit-submodule-filtered-arguments "--force"))) + (magit-with-toplevel + (magit-run-git-async "submodule" "deinit" args "--" modules))) + +;;;###autoload +(defun magit-submodule-remove (modules args trash-gitdirs) + "Unregister MODULES and remove their working directories. + +For safety reasons, do not remove the gitdirs and if a module has +uncomitted changes, then do not remove it at all. If a module's +gitdir is located inside the working directory, then move it into +the gitdir of the superproject first. + +With the \"--force\" argument offer to remove dirty working +directories and with a prefix argument offer to delete gitdirs. +Both actions are very dangerous and have to be confirmed. There +are additional safety precautions in place, so you might be able +to recover from making a mistake here, but don't count on it." + (interactive + (list (if-let ((modules (magit-region-values 'magit-module-section t))) + (magit-confirm 'remove-modules nil "Remove %i modules" nil modules) + (list (magit-read-module-path "Remove module"))) + (magit-submodule-filtered-arguments "--force") + current-prefix-arg)) + (when (version< (magit-git-version) "2.12.0") + (error "This command requires Git v2.12.0")) + (when magit-submodule-remove-trash-gitdirs + (setq trash-gitdirs t)) + (magit-with-toplevel + (when-let + ((modified + (-filter (lambda (module) + (let ((default-directory (file-name-as-directory + (expand-file-name module)))) + (and (cddr (directory-files default-directory)) + (magit-anything-modified-p)))) + modules))) + (if (member "--force" args) + (if (magit-confirm 'remove-dirty-modules + "Remove dirty module %s" + "Remove %i dirty modules" + t modified) + (dolist (module modified) + (let ((default-directory (file-name-as-directory + (expand-file-name module)))) + (magit-git "stash" "push" + "-m" "backup before removal of this module"))) + (setq modules (cl-set-difference modules modified))) + (if (cdr modified) + (message "Omitting %s modules with uncommitted changes: %s" + (length modified) + (mapconcat #'identity modified ", ")) + (message "Omitting module %s, it has uncommitted changes" + (car modified))) + (setq modules (cl-set-difference modules modified)))) + (when modules + (let ((alist + (and trash-gitdirs + (--map (split-string it "\0") + (magit-git-lines "submodule" "foreach" "-q" + "printf \"$sm_path\\0$name\n\""))))) + (magit-git "submodule" "absorbgitdirs" "--" modules) + (magit-git "submodule" "deinit" args "--" modules) + (magit-git "rm" args "--" modules) + (when (and trash-gitdirs + (magit-confirm 'trash-module-gitdirs + "Trash gitdir of module %s" + "Trash gitdirs of %i modules" + t modules)) + (dolist (module modules) + (if-let ((name (cadr (assoc module alist)))) + ;; Disregard if `magit-delete-by-moving-to-trash' + ;; is nil. Not doing so would be too dangerous. + (delete-directory (magit-git-dir + (convert-standard-filename + (concat "modules/" name))) + t t) + (error "BUG: Weird module name and/or path for %s" module))))) + (magit-refresh)))) + +;;; Sections + +;;;###autoload +(defun magit-insert-modules () + "Insert submodule sections. +Hook `magit-module-sections-hook' controls which module sections +are inserted, and option `magit-module-sections-nested' controls +whether they are wrapped in an additional section." + (when-let ((modules (magit-list-module-paths))) + (if magit-module-sections-nested + (magit-insert-section section (modules nil t) + (magit-insert-heading + (format "%s (%s)" + (propertize "Modules" 'face 'magit-section-heading) + (length modules))) + (if (oref section hidden) + (oset section washer 'magit--insert-modules) + (magit--insert-modules))) + (magit--insert-modules)))) + +(defun magit--insert-modules (&optional _section) + (magit-run-section-hook 'magit-module-sections-hook)) + +;;;###autoload +(defun magit-insert-modules-overview () + "Insert sections for all modules. +For each section insert the path and the output of `git describe --tags', +or, failing that, the abbreviated HEAD commit hash." + (when-let ((modules (magit-list-module-paths))) + (magit-insert-section section (modules nil t) + (magit-insert-heading + (format "%s (%s)" + (propertize "Modules overview" 'face 'magit-section-heading) + (length modules))) + (if (oref section hidden) + (oset section washer 'magit--insert-modules-overview) + (magit--insert-modules-overview))))) + +(defvar magit-modules-overview-align-numbers t) + +(defun magit--insert-modules-overview (&optional _section) + (magit-with-toplevel + (let* ((modules (magit-list-module-paths)) + (path-format (format "%%-%is " + (min (apply 'max (mapcar 'length modules)) + (/ (window-width) 2)))) + (branch-format (format "%%-%is " (min 25 (/ (window-width) 3))))) + (dolist (module modules) + (let ((default-directory + (expand-file-name (file-name-as-directory module)))) + (magit-insert-section (magit-module-section module t) + (insert (propertize (format path-format module) + 'face 'magit-diff-file-heading)) + (if (not (file-exists-p ".git")) + (insert "(unpopulated)") + (insert (format branch-format + (--if-let (magit-get-current-branch) + (propertize it 'face 'magit-branch-local) + (propertize "(detached)" 'face 'warning)))) + (--if-let (magit-git-string "describe" "--tags") + (progn (when (and magit-modules-overview-align-numbers + (string-match-p "\\`[0-9]" it)) + (insert ?\s)) + (insert (propertize it 'face 'magit-tag))) + (--when-let (magit-rev-format "%h") + (insert (propertize it 'face 'magit-hash))))) + (insert ?\n)))))) + (insert ?\n)) + +(defvar magit-modules-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-list-submodules) + map) + "Keymap for `modules' sections.") + +(defvar magit-module-section-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-file-section-map) + (unless (featurep 'jkl) + (define-key map "\C-j" 'magit-submodule-visit)) + (define-key map [C-return] 'magit-submodule-visit) + (define-key map [remap magit-visit-thing] 'magit-submodule-visit) + (define-key map [remap magit-delete-thing] 'magit-submodule-unpopulate) + (define-key map "K" 'magit-file-untrack) + (define-key map "R" 'magit-file-rename) + map) + "Keymap for `module' sections.") + +(defun magit-submodule-visit (module &optional other-window) + "Visit MODULE by calling `magit-status' on it. +Offer to initialize MODULE if it's not checked out yet. +With a prefix argument, visit in another window." + (interactive (list (or (magit-section-value-if 'module) + (magit-read-module-path "Visit module")) + current-prefix-arg)) + (magit-with-toplevel + (let ((path (expand-file-name module))) + (cond + ((file-exists-p (expand-file-name ".git" module)) + (magit-diff-visit-directory path other-window)) + ((y-or-n-p (format "Initialize submodule '%s' first?" module)) + (magit-run-git-async "submodule" "update" "--init" "--" module) + (set-process-sentinel + magit-this-process + (lambda (process event) + (let ((magit-process-raise-error t)) + (magit-process-sentinel process event)) + (when (and (eq (process-status process) 'exit) + (= (process-exit-status process) 0)) + (magit-diff-visit-directory path other-window))))) + ((file-exists-p path) + (dired-jump other-window (concat path "/."))))))) + +;;;###autoload +(defun magit-insert-modules-unpulled-from-upstream () + "Insert sections for modules that haven't been pulled from the upstream. +These sections can be expanded to show the respective commits." + (magit--insert-modules-logs "Modules unpulled from @{upstream}" + 'modules-unpulled-from-upstream + "HEAD..@{upstream}")) + +;;;###autoload +(defun magit-insert-modules-unpulled-from-pushremote () + "Insert sections for modules that haven't been pulled from the push-remote. +These sections can be expanded to show the respective commits." + (magit--insert-modules-logs "Modules unpulled from @{push}" + 'modules-unpulled-from-pushremote + "HEAD..@{push}")) + +;;;###autoload +(defun magit-insert-modules-unpushed-to-upstream () + "Insert sections for modules that haven't been pushed to the upstream. +These sections can be expanded to show the respective commits." + (magit--insert-modules-logs "Modules unmerged into @{upstream}" + 'modules-unpushed-to-upstream + "@{upstream}..HEAD")) + +;;;###autoload +(defun magit-insert-modules-unpushed-to-pushremote () + "Insert sections for modules that haven't been pushed to the push-remote. +These sections can be expanded to show the respective commits." + (magit--insert-modules-logs "Modules unpushed to @{push}" + 'modules-unpushed-to-pushremote + "@{push}..HEAD")) + +(defun magit--insert-modules-logs (heading type range) + "For internal use, don't add to a hook." + (unless (magit-ignore-submodules-p) + (when-let ((modules (magit-list-module-paths))) + (magit-insert-section section ((eval type) nil t) + (string-match "\\`\\(.+\\) \\([^ ]+\\)\\'" heading) + (magit-insert-heading + (propertize (match-string 1 heading) 'face 'magit-section-heading) " " + (propertize (match-string 2 heading) 'face 'magit-branch-remote) ":") + (magit-with-toplevel + (dolist (module modules) + (when (magit-module-worktree-p module) + (let ((default-directory + (expand-file-name (file-name-as-directory module)))) + (when (magit-file-accessible-directory-p default-directory) + (magit-insert-section sec (magit-module-section module t) + (magit-insert-heading + (propertize module 'face 'magit-diff-file-heading) ":") + (magit-git-wash + (apply-partially 'magit-log-wash-log 'module) + "-c" "push.default=current" "log" "--oneline" range) + (when (> (point) + (oref sec content)) + (delete-char -1)))))))) + (if (> (point) + (oref section content)) + (insert ?\n) + (magit-cancel-section)))))) + +;;; List + +;;;###autoload +(defun magit-list-submodules () + "Display a list of the current repository's submodules." + (interactive) + (magit-display-buffer + (or (magit-mode-get-buffer 'magit-submodule-list-mode) + (magit-with-toplevel + (magit-generate-new-buffer 'magit-submodule-list-mode)))) + (magit-submodule-list-mode) + (magit-submodule-list-refresh) + (tabulated-list-print)) + +(defvar magit-submodule-list-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-repolist-mode-map) + map) + "Local keymap for Magit-Submodule-List mode buffers.") + +(define-derived-mode magit-submodule-list-mode tabulated-list-mode "Modules" + "Major mode for browsing a list of Git submodules." + :group 'magit-repolist-mode + (setq x-stretch-cursor nil) + (setq tabulated-list-padding 0) + (setq tabulated-list-sort-key (cons "Path" nil)) + (setq tabulated-list-format + (vconcat (mapcar (pcase-lambda (`(,title ,width ,_fn ,props)) + (nconc (list title width t) + (-flatten props))) + magit-submodule-list-columns))) + (tabulated-list-init-header) + (add-hook 'tabulated-list-revert-hook 'magit-submodule-list-refresh nil t) + (setq imenu-prev-index-position-function + #'magit-imenu--submodule-prev-index-position-function) + (setq imenu-extract-index-name-function + #'magit-imenu--submodule-extract-index-name-function) + (setq-local bookmark-make-record-function + #'magit-bookmark--submodules-make-record)) + +(defun magit-submodule-list-refresh () + (setq tabulated-list-entries + (-keep (lambda (module) + (let ((default-directory + (expand-file-name (file-name-as-directory module)))) + (and (file-exists-p ".git") + (list module + (vconcat + (--map (or (funcall (nth 2 it) module) "") + magit-submodule-list-columns)))))) + (magit-list-module-paths)))) + +(defun magit-modulelist-column-path (path) + "Insert the relative path of the submodule." + path) + +;;; Utilities + +(defun magit-submodule--maybe-reuse-gitdir (name path) + (let ((gitdir + (magit-git-dir (convert-standard-filename (concat "modules/" name))))) + (when (and (file-exists-p gitdir) + (not (file-exists-p path))) + (pcase (read-char-choice + (concat + gitdir " already exists.\n" + "Type [u] to use the existing gitdir and create the working tree\n" + " [r] to rename the existing gitdir and clone again\n" + " [t] to trash the existing gitdir and clone again\n" + " [C-g] to abort ") + '(?u ?r ?t)) + (?u (magit-submodule--restore-worktree (expand-file-name path) gitdir)) + (?r (rename-file gitdir (concat gitdir "-" + (format-time-string "%F-%T")))) + (?t (delete-directory gitdir t t)))))) + +(defun magit-submodule--restore-worktree (worktree gitdir) + (make-directory worktree t) + (with-temp-file (expand-file-name ".git" worktree) + (insert "gitdir: " (file-relative-name gitdir worktree) "\n")) + (let ((default-directory worktree)) + (magit-call-git "reset" "--hard" "HEAD"))) + +;;; _ +(provide 'magit-submodule) +;;; magit-submodule.el ends here diff --git a/elpa/magit-20181113.1837/magit-subtree.el b/elpa/magit-20181113.1837/magit-subtree.el new file mode 100644 index 00000000..4e5d32b0 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-subtree.el @@ -0,0 +1,147 @@ +;;; magit-subtree.el --- subtree support for Magit -*- lexical-binding: t -*- + +;; Copyright (C) 2011-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Code: + +(require 'magit) + +;;; Popup + +;;;###autoload (autoload 'magit-subtree-popup "magit-subtree" nil t) +(magit-define-popup magit-subtree-popup + "Popup console for subtree commands." + :man-page "git-subtree" + :switches '("Switches for add, merge, push, and pull" + (?s "Squash" "--squash") + "Switches for split" + (?i "Ignore joins" "--ignore-joins") + (?j "Rejoin" "--rejoin")) + :options '("Options" + (?p "Prefix" "--prefix=" magit-subtree-read-prefix) + "Options for add, merge, and pull" + (?m "Message" "--message=") + "Options for split" + (?a "Annotate" "--annotate=") + (?b "Branch" "--branch=") + (?o "Onto" "--onto=" magit-read-branch-or-commit)) + :actions '((?a "Add" magit-subtree-add) + (?m "Merge" magit-subtree-merge) + (?p "Push" magit-subtree-push) + (?c "Add commit" magit-subtree-add-commit) + (?f "Pull" magit-subtree-pull) + (?s "Split" magit-subtree-split)) + :max-action-columns 3) + +(defun magit-subtree-read-prefix (prompt &optional default) + (let* ((insert-default-directory nil) + (topdir (magit-toplevel)) + (prefix (read-directory-name (concat prompt ": ") topdir default))) + (if (file-name-absolute-p prefix) + ;; At least `ido-mode's variant is not compatible. + (if (string-prefix-p topdir prefix) + (file-relative-name prefix topdir) + (user-error "%s isn't inside the repository at %s" prefix topdir)) + prefix))) + +;;; Commands + +(defun magit-subtree-prefix (prompt) + (--if-let (--first (string-prefix-p "--prefix=" it) + (magit-subtree-arguments)) + (substring it 9) + (magit-subtree-read-prefix prompt))) + +(defun magit-subtree-args () + (-filter (lambda (arg) + (if (eq this-command 'magit-subtree-split) + (or (equal arg "--ignore-joins") + (equal arg "--rejoin") + (string-prefix-p "--annotate=" arg) + (string-prefix-p "--branch=" arg) + (string-prefix-p "--onto=" arg)) + (or (equal arg "--squash") + (and (string-prefix-p "--message=" arg) + (not (eq this-command 'magit-subtree-push)))))) + (magit-subtree-arguments))) + +(defun magit-git-subtree (subcmd prefix &rest args) + (magit-run-git-async "subtree" subcmd (concat "--prefix=" prefix) args)) + +;;;###autoload +(defun magit-subtree-add (prefix repository ref args) + "Add REF from REPOSITORY as a new subtree at PREFIX." + (interactive + (cons (magit-subtree-prefix "Add subtree") + (let ((remote (magit-read-remote-or-url "From repository"))) + (list remote + (magit-read-refspec "Ref" remote) + (magit-subtree-args))))) + (magit-git-subtree "add" prefix args repository ref)) + +;;;###autoload +(defun magit-subtree-add-commit (prefix commit args) + "Add COMMIT as a new subtree at PREFIX." + (interactive (list (magit-subtree-prefix "Add subtree") + (magit-read-string-ns "Commit") + (magit-subtree-args))) + (magit-git-subtree "add" prefix args commit)) + +;;;###autoload +(defun magit-subtree-merge (prefix commit args) + "Merge COMMIT into the PREFIX subtree." + (interactive (list (magit-subtree-prefix "Merge into subtree") + (magit-read-string-ns "Commit") + (magit-subtree-args))) + (magit-git-subtree "merge" prefix args commit)) + +;;;###autoload +(defun magit-subtree-pull (prefix repository ref args) + "Pull REF from REPOSITORY into the PREFIX subtree." + (interactive + (cons (magit-subtree-prefix "Pull into subtree") + (let ((remote (magit-read-remote-or-url "From repository"))) + (list remote + (magit-read-refspec "Ref" remote) + (magit-subtree-args))))) + (magit-git-subtree "pull" prefix args repository ref)) + +;;;###autoload +(defun magit-subtree-push (prefix repository ref args) + "Extract the history of the subtree PREFIX and push it to REF on REPOSITORY." + (interactive (list (magit-subtree-prefix "Push subtree") + (magit-read-remote-or-url "To repository") + (magit-read-string-ns "To reference") + (magit-subtree-args))) + (magit-git-subtree "push" prefix args repository ref)) + +;;;###autoload +(defun magit-subtree-split (prefix commit args) + "Extract the history of the subtree PREFIX." + (interactive (list (magit-subtree-prefix "Split subtree") + (magit-read-string-ns "Commit") + (magit-subtree-args))) + (magit-git-subtree "split" prefix args commit)) + +;;; _ +(provide 'magit-subtree) +;;; magit-subtree.el ends here diff --git a/elpa/magit-20181113.1837/magit-tag.el b/elpa/magit-20181113.1837/magit-tag.el new file mode 100644 index 00000000..ca5f6aba --- /dev/null +++ b/elpa/magit-20181113.1837/magit-tag.el @@ -0,0 +1,133 @@ +;;; magit-tag.el --- tag functionality -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements tag commands. + +;;; Code: + +(require 'magit) + +;;;###autoload (autoload 'magit-tag-popup "magit" nil t) +(magit-define-popup magit-tag-popup + "Popup console for tag commands." + :man-page "git-tag" + :switches '((?a "Annotate" "--annotate") + (?f "Force" "--force") + (?s "Sign" "--sign")) + :options '((?f "Sign" "--local-user=" magit-read-gpg-secret-key)) + :actions '((?t "Create" magit-tag-create) + (?k "Delete" magit-tag-delete) + (?p "Prune" magit-tag-prune)) + :default-action 'magit-tag-create) + +;;;###autoload +(defun magit-tag-create (name rev &optional args) + "Create a new tag with the given NAME at REV. +With a prefix argument annotate the tag. +\n(git tag [--annotate] NAME REV)" + (interactive (list (magit-read-tag "Tag name") + (magit-read-branch-or-commit "Place tag on") + (let ((args (magit-tag-arguments))) + (when current-prefix-arg + (cl-pushnew "--annotate" args)) + args))) + (magit-run-git-with-editor "tag" args name rev)) + +;;;###autoload +(defun magit-tag-delete (tags) + "Delete one or more tags. +If the region marks multiple tags (and nothing else), then offer +to delete those, otherwise prompt for a single tag to be deleted, +defaulting to the tag at point. +\n(git tag -d TAGS)" + (interactive (list (--if-let (magit-region-values 'tag) + (magit-confirm t nil "Delete %i tags" nil it) + (magit-read-tag "Delete tag" t)))) + (magit-run-git "tag" "-d" tags)) + +;;;###autoload +(defun magit-tag-prune (tags remote-tags remote) + "Offer to delete tags missing locally from REMOTE, and vice versa." + (interactive + (let* ((remote (magit-read-remote "Prune tags using remote")) + (tags (magit-list-tags)) + (rtags (prog2 (message "Determining remote tags...") + (magit-remote-list-tags remote) + (message "Determining remote tags...done"))) + (ltags (-difference tags rtags)) + (rtags (-difference rtags tags))) + (unless (or ltags rtags) + (message "Same tags exist locally and remotely")) + (unless (magit-confirm t + "Delete %s locally" + "Delete %i tags locally" + 'noabort ltags) + (setq ltags nil)) + (unless (magit-confirm t + "Delete %s from remote" + "Delete %i tags from remote" + 'noabort rtags) + (setq rtags nil)) + (list ltags rtags remote))) + (when tags + (magit-call-git "tag" "-d" tags)) + (when remote-tags + (magit-run-git-async "push" remote (--map (concat ":" it) remote-tags)))) + +;;;###autoload +(defun magit-tag-release (tag) + "Create an opinionated release tag. + +Assume version tags that match \"\\\\`v?[0-9]\\\\(\\\\.[0-9]\\\\)*\\\\'\". +Prompt for the name of the new tag using the highest existing tag +as initial input and call \"git tag --annotate --sign -m MSG\" TAG, +regardless of whether these arguments are enabled in the popup. +Given a TAG \"v1.2.3\" and a repository \"/path/to/foo-bar\", the +MESSAGE would be \"Foo-Bar 1.2.3\". + +Because it is so opinionated, this command is not available from +the tag popup by default." + (interactive + (list (read-string "Create tag: " + (car (nreverse + (cl-sort (magit-list-tags) #'version< + :key (lambda (tag) + (if (string-prefix-p "v" tag) + (substring tag 1) + tag)))))))) + (magit-run-git + "tag" "--annotate" "--sign" + "-m" (format "%s %s" + (capitalize (file-name-nondirectory + (directory-file-name (magit-toplevel)))) + (if (string-prefix-p "v" tag) + (substring tag 1) + tag)) + tag) + (magit-show-refs)) + +;;; _ +(provide 'magit-tag) +;;; magit-tag.el ends here diff --git a/elpa/magit-20181113.1837/magit-utils.el b/elpa/magit-20181113.1837/magit-utils.el new file mode 100644 index 00000000..fc819514 --- /dev/null +++ b/elpa/magit-20181113.1837/magit-utils.el @@ -0,0 +1,1099 @@ +;;; magit-utils.el --- various utilities -*- lexical-binding: t; coding: utf-8 -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Contains code from GNU Emacs https://www.gnu.org/software/emacs, +;; released under the GNU General Public License version 3 or later. + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library defines several utility functions used by several +;; other libraries which cannot depend on one another (because +;; circular dependencies are not good). Luckily most (all) of these +;; functions have very little (nothing) to do with Git, so we not only +;; have to do this, it even makes sense. + +;; Unfortunately there are also some options which are used by several +;; libraries which cannot depend on one another, they are defined here +;; too. + +;;; Code: + +(require 'cl-lib) +(require 'dash) + +(eval-when-compile + (require 'subr-x)) + +(require 'crm) + +(eval-when-compile (require 'ido)) +(declare-function ido-completing-read+ "ido-completing-read+" + (prompt collection &optional predicate + require-match initial-input + hist def inherit-input-method)) +(declare-function Info-get-token "info" (pos start all &optional errorstring)) + +(eval-when-compile (require 'vc-git)) +(declare-function vc-git--run-command-string "vc-git" (file &rest args)) + +(defvar magit-wip-before-change-mode) + +(require 'magit-popup) + +;;; Options + +(defcustom magit-completing-read-function 'magit-builtin-completing-read + "Function to be called when requesting input from the user. + +If you have enabled `ivy-mode' or `helm-mode', then you don't +have to customize this option; `magit-builtin-completing-read' +will work just fine. However, if you use Ido completion, then +you do have to use `magit-ido-completion-read', because Ido is +less well behaved than the former, more modern alternatives. + +If you would like to use Ivy or Helm completion with Magit but +not enable the respective modes globally, then customize this +option to use `ivy-completing-read' or +`helm--completing-read-default'. If you choose to use +`ivy-completing-read', note that the items may always be shown in +alphabetical order, depending on your version of Ivy." + :group 'magit-essentials + :type '(radio (function-item magit-builtin-completing-read) + (function-item magit-ido-completing-read) + (function-item ivy-completing-read) + (function-item helm--completing-read-default) + (function :tag "Other function"))) + +(defcustom magit-dwim-selection + '((magit-stash-apply nil t) + (magit-stash-branch nil t) + (magit-stash-branch-here nil t) + (magit-stash-format-patch nil t) + (magit-stash-drop nil ask) + (magit-stash-pop nil ask) + (forge-browse-commit nil t) + (forge-browse-branch nil t) + (forge-browse-remote nil t) + (forge-browse-issue nil t) + (forge-browse-pullreq nil t) + (forge-edit-topic-title nil t) + (forge-edit-topic-labels nil t) + (forge-edit-topic-assignees nil t) + (forge-visit-issue nil t) + (forge-visit-pullreq nil t)) + "When not to offer alternatives and ask for confirmation. + +Many commands by default ask the user to select from a list of +possible candidates. They do so even when there is a thing at +point that they can act on, which is then offered as the default. + +This option can be used to tell certain commands to use the thing +at point instead of asking the user to select a candidate to act +on, with or without confirmation. + +The value has the form ((COMMAND nil|PROMPT DEFAULT)...). + +- COMMAND is the command that should not prompt for a choice. + To have an effect, the command has to use the function + `magit-completing-read' or a utility function which in turn uses + that function. + +- If the command uses `magit-completing-read' multiple times, then + PROMPT can be used to only affect one of these uses. PROMPT, if + non-nil, is a regular expression that is used to match against + the PROMPT argument passed to `magit-completing-read'. + +- DEFAULT specifies how to use the default. If it is t, then + the DEFAULT argument passed to `magit-completing-read' is used + without confirmation. If it is `ask', then the user is given + a chance to abort. DEFAULT can also be nil, in which case the + entry has no effect." + :package-version '(magit . "2.12.0") + :group 'magit-commands + :type '(repeat + (list (symbol :tag "Command") ; It might not be fboundp yet. + (choice (const :tag "for all prompts" nil) + (regexp :tag "for prompts matching regexp")) + (choice (const :tag "offer other choices" nil) + (const :tag "require confirmation" ask) + (const :tag "use default without confirmation" t))))) + +(defconst magit--confirm-actions + '((const reverse) (const discard) + (const rename) (const resurrect) + (const untrack) (const trash) + (const delete) (const abort-rebase) + (const abort-merge) (const merge-dirty) + (const drop-stashes) (const reset-bisect) + (const kill-process) (const delete-unmerged-branch) + (const delete-pr-branch) (const remove-modules) + (const stage-all-changes) (const unstage-all-changes) + (const safe-with-wip))) + +(defcustom magit-no-confirm nil + "A list of symbols for actions Magit should not confirm, or t. + +Many potentially dangerous commands by default ask the user for +confirmation. Each of the below symbols stands for an action +which, when invoked unintentionally or without being fully aware +of the consequences, could lead to tears. In many cases there +are several commands that perform variations of a certain action, +so we don't use the command names but more generic symbols. + +Applying changes: + + `discard' Discarding one or more changes (i.e. hunks or the + complete diff for a file) loses that change, obviously. + + `reverse' Reverting one or more changes can usually be undone + by reverting the reversion. + + `stage-all-changes', `unstage-all-changes' When there are both + staged and unstaged changes, then un-/staging everything would + destroy that distinction. Of course that also applies when + un-/staging a single change, but then less is lost and one does + that so often that having to confirm every time would be + unacceptable. + +Files: + + `delete' When a file that isn't yet tracked by Git is deleted + then it is completely lost, not just the last changes. Very + dangerous. + + `trash' Instead of deleting a file it can also be move to the + system trash. Obviously much less dangerous than deleting it. + + Also see option `magit-delete-by-moving-to-trash'. + + `resurrect' A deleted file can easily be resurrected by + \"deleting\" the deletion, which is done using the same command + that was used to delete the same file in the first place. + + `untrack' Untracking a file can be undone by tracking it again. + + `rename' Renaming a file can easily be undone. + +Sequences: + + `reset-bisect' Aborting (known to Git as \"resetting\") a + bisect operation loses all information collected so far. + + `abort-rebase' Aborting a rebase throws away all already + modified commits, but it's possible to restore those from the + reflog. + + `abort-merge' Aborting a merge throws away all conflict + resolutions which has already been carried out by the user. + + `merge-dirty' Merging with a dirty worktree can make it hard to + go back to the state before the merge was initiated. + +References: + + `delete-unmerged-branch' Once a branch has been deleted it can + only be restored using low-level recovery tools provided by + Git. And even then the reflog is gone. The user always has + to confirm the deletion of a branch by accepting the default + choice (or selecting another branch), but when a branch has + not been merged yet, also make sure the user is aware of that. + + `delete-pr-branch' When deleting a branch that was created from + a pull request and if no other branches still exist on that + remote, then `magit-branch-delete' offers to delete the remote + as well. This should be safe because it only happens if no + other refs exist in the remotes namespace, and you can recreate + the remote if necessary. + + `drop-stashes' Dropping a stash is dangerous because Git stores + stashes in the reflog. Once a stash is removed, there is no + going back without using low-level recovery tools provided by + Git. When a single stash is dropped, then the user always has + to confirm by accepting the default (or selecting another). + This action only concerns the deletion of multiple stashes at + once. + +Edit published history: + + Without adding these symbols here, you will be warned before + editing commits that have already been pushed to one of the + branches listed in `magit-published-branches'. + + `amend-published' Affects most commands that amend to \"HEAD\". + + `rebase-published' Affects commands that perform interactive + rebases. This includes commands from the commit popup that + modify a commit other than \"HEAD\", namely the various fixup + and squash variants. + + `edit-published' Affects the commands `magit-edit-line-commit' + and `magit-diff-edit-hunk-commit'. These two commands make + it quite easy to accidentally edit a published commit, so you + should think twice before configuring them not to ask for + confirmation. + + To disable confirmation completely, add all three symbols here + or set `magit-published-branches' to nil. + +Removing modules: + + `remove-modules' When you remove the working directory of a + module that does not contain uncommitted changes, then that is + safer than doing so when there are uncommitted changes and/or + when you also remove the gitdir. Still, you don't want to do + that by accident. + + `remove-dirty-modules' When you remove the working directory of + a module that contains uncommitted changes, then those changes + are gone for good. It is better to go to the module, inspect + these changes and only if appropriate discard them manually. + + `trash-module-gitdirs' When you remove the gitdir of a module, + then all unpushed changes are gone for good. It is very easy + to forget that you have some unfinished work on an unpublished + feature branch or even in a stash. + + Actually there are some safety precautions in place, that might + help you out if you make an unwise choice here, but don't count + on it. In case of emergency, stay calm and check the stash and + the `trash-directory' for traces of lost work. + +Various: + + `kill-process' There seldom is a reason to kill a process. + +Global settings: + + Instead of adding all of the above symbols to the value of this + option you can also set it to the atom `t', which has the same + effect as adding all of the above symbols. Doing that most + certainly is a bad idea, especially because other symbols might + be added in the future. So even if you don't want to be asked + for confirmation for any of these actions, you are still better + of adding all of the respective symbols individually. + + When `magit-wip-before-change-mode' is enabled then these actions + can fairly easily be undone: `discard', `reverse', + `stage-all-changes', and `unstage-all-changes'. If and only if + this mode is enabled, then `safe-with-wip' has the same effect + as adding all of these symbols individually." + :package-version '(magit . "2.1.0") + :group 'magit-essentials + :group 'magit-commands + :type `(choice (const :tag "Always require confirmation" nil) + (const :tag "Never require confirmation" t) + (set :tag "Require confirmation except for" + ;; `remove-dirty-modules' and + ;; `trash-module-gitdirs' intentionally + ;; omitted. + ,@magit--confirm-actions))) + +(defcustom magit-slow-confirm '(drop-stashes) + "Whether to ask user \"y or n\" or \"yes or no\" questions. + +When this is nil, then `y-or-n-p' is used when the user has to +confirm a potentially destructive action. When this is t, then +`yes-or-no-p' is used instead. If this is a list of symbols +identifying actions, then `yes-or-no-p' is used for those, +`y-or-no-p' for all others. The list of actions is the same as +for `magit-no-confirm' (which see)." + :package-version '(magit . "2.9.0") + :group 'magit-miscellaneous + :type `(choice (const :tag "Always ask \"yes or no\" questions" t) + (const :tag "Always ask \"y or n\" questions" nil) + (set :tag "Ask \"yes or no\" questions only for" + ,@magit--confirm-actions))) + +(defcustom magit-no-message nil + "A list of messages Magit should not display. + +Magit displays most echo area messages using `message', but a few +are displayed using `magit-message' instead, which takes the same +arguments as the former, FORMAT-STRING and ARGS. `magit-message' +forgoes printing a message if any member of this list is a prefix +of the respective FORMAT-STRING. + +If Magit prints a message which causes you grief, then please +first investigate whether there is another option which can be +used to suppress it. If that is not the case, then ask the Magit +maintainers to start using `magit-message' instead of `message' +in that case. We are not proactively replacing all uses of +`message' with `magit-message', just in case someone *might* find +some of these messages useless. + +Messages which can currently be suppressed using this option are: +* \"Turning on magit-auto-revert-mode...\"" + :package-version '(magit . "2.8.0") + :group 'magit-miscellaneous + :type '(repeat string)) + +(defcustom magit-ellipsis ?… + "Character used to abbreviate text. + +Currently this is used to abbreviate author names in the margin +and in process buffers to elide `magit-git-global-arguments'." + :package-version '(magit . "2.1.0") + :group 'magit-miscellaneous + :type 'character) + +(defcustom magit-update-other-window-delay 0.2 + "Delay before automatically updating the other window. + +When moving around in certain buffers, then certain other +buffers, which are being displayed in another window, may +optionally be updated to display information about the +section at point. + +When holding down a key to move by more than just one section, +then that would update that buffer for each section on the way. +To prevent that, updating the revision buffer is delayed, and +this option controls for how long. For optimal experience you +might have to adjust this delay and/or the keyboard repeat rate +and delay of your graphical environment or operating system." + :package-version '(magit . "2.3.0") + :group 'magit-miscellaneous + :type 'number) + +(defcustom magit-view-git-manual-method 'info + "How links to Git documentation are followed from Magit's Info manuals. + +`info' Follow the link to the node in the `gitman' Info manual + as usual. Unfortunately that manual is not installed by + default on some platforms, and when it is then the nodes + look worse than the actual manpages. + +`man' View the respective man-page using the `man' package. + +`woman' View the respective man-page using the `woman' package." + :package-version '(magit . "2.9.0") + :group 'magit-miscellaneous + :type '(choice (const :tag "view info manual" info) + (const :tag "view manpage using `man'" man) + (const :tag "view manpage using `woman'" woman))) + +;;; User Input + +(defvar helm-completion-in-region-default-sort-fn) +(defvar ivy-sort-functions-alist) + +(defvar magit-completing-read--silent-default nil) + +(defun magit-completing-read (prompt collection &optional + predicate require-match initial-input + hist def fallback) + "Read a choice in the minibuffer, or use the default choice. + +This is the function that Magit commands use when they need the +user to select a single thing to act on. The arguments have the +same meaning as for `completing-read', except for FALLBACK, which +is unique to this function and is described below. + +Instead of asking the user to choose from a list of possible +candidates, this function may instead just return the default +specified by DEF, with or without requiring user confirmation. +Whether that is the case depends on PROMPT, `this-command' and +`magit-dwim-selection'. See the documentation of the latter for +more information. + +If it does use the default without the user even having to +confirm that, then `magit-completing-read--silent-default' is set +to t, otherwise nil. + +If it does read a value in the minibuffer, then this function +acts similarly to `completing-read', except for the following: + +- If REQUIRE-MATCH is nil and the user exits without a choice, + then nil is returned instead of an empty string. + +- If REQUIRE-MATCH is non-nil and the users exits without a + choice, an user-error is raised. + +- FALLBACK specifies a secondary default that is only used if + the primary default DEF is nil. The secondary default is not + subject to `magit-dwim-selection' — if DEF is nil but FALLBACK + is not, then this function always asks the user to choose a + candidate, just as if both defaults were nil. + +- \": \" is appended to PROMPT. + +- PROMPT is modified to end with \" (default DEF|FALLBACK): \" + provided that DEF or FALLBACK is non-nil, that neither + `ivy-mode' nor `helm-mode' is enabled, and that + `magit-completing-read-function' is set to its default value of + `magit-builtin-completing-read'." + (setq magit-completing-read--silent-default nil) + (if-let ((dwim (and def + (nth 2 (-first (pcase-lambda (`(,cmd ,re ,_)) + (and (eq this-command cmd) + (or (not re) + (string-match-p re prompt)))) + magit-dwim-selection))))) + (if (eq dwim 'ask) + (if (y-or-n-p (format "%s %s? " prompt def)) + def + (user-error "Abort")) + (setq magit-completing-read--silent-default t) + def) + (unless def + (setq def fallback)) + (let ((command this-command) + (reply (funcall magit-completing-read-function + (concat prompt ": ") + (if (and def (not (member def collection))) + (cons def collection) + collection) + predicate + require-match initial-input hist def))) + (setq this-command command) + (if (string= reply "") + (if require-match + (user-error "Nothing selected") + nil) + reply)))) + +(defun magit--completion-table (collection) + (lambda (string pred action) + (if (eq action 'metadata) + '(metadata (display-sort-function . identity)) + (complete-with-action action collection string pred)))) + +(defun magit-builtin-completing-read + (prompt choices &optional predicate require-match initial-input hist def) + "Magit wrapper for standard `completing-read' function." + (unless (or (bound-and-true-p helm-mode) + (bound-and-true-p ivy-mode)) + (setq prompt (magit-prompt-with-default prompt def)) + (setq choices (magit--completion-table choices))) + (cl-letf (((symbol-function 'completion-pcm--all-completions) + #'magit-completion-pcm--all-completions)) + (let ((ivy-sort-functions-alist nil)) + (completing-read prompt choices + predicate require-match + initial-input hist def)))) + +(defun magit-completing-read-multiple + (prompt choices &optional sep default hist keymap) + "Read multiple items from CHOICES, separated by SEP. + +Set up the `crm' variables needed to read multiple values with +`read-from-minibuffer'. + +SEP is a regexp matching characters that can separate choices. +When SEP is nil, it defaults to `crm-default-separator'. +DEFAULT, HIST, and KEYMAP are passed to `read-from-minibuffer'. +When KEYMAP is nil, it defaults to `crm-local-completion-map'. + +Unlike `completing-read-multiple', the return value is not split +into a list." + (let* ((crm-separator (or sep crm-default-separator)) + (crm-completion-table (magit--completion-table choices)) + (choose-completion-string-functions + '(crm--choose-completion-string)) + (minibuffer-completion-table #'crm--collection-fn) + (minibuffer-completion-confirm t) + (helm-completion-in-region-default-sort-fn nil) + (input + (cl-letf (((symbol-function 'completion-pcm--all-completions) + #'magit-completion-pcm--all-completions)) + (read-from-minibuffer + (concat prompt (and default (format " (%s)" default)) ": ") + nil (or keymap crm-local-completion-map) + nil hist default)))) + (when (string-equal input "") + (or (setq input default) + (user-error "Nothing selected"))) + input)) + +(defun magit-completing-read-multiple* + (prompt table &optional predicate require-match initial-input + hist def inherit-input-method) + "Read multiple strings in the minibuffer, with completion. +Like `completing-read-multiple' but don't mess with order of +TABLE. Also bind `helm-completion-in-region-default-sort-fn' +to nil." + (unwind-protect + (cl-letf (((symbol-function 'completion-pcm--all-completions) + #'magit-completion-pcm--all-completions)) + (add-hook 'choose-completion-string-functions + 'crm--choose-completion-string) + (let* ((minibuffer-completion-table #'crm--collection-fn) + (minibuffer-completion-predicate predicate) + ;; see completing_read in src/minibuf.c + (minibuffer-completion-confirm + (unless (eq require-match t) require-match)) + (crm-completion-table (magit--completion-table table)) + (map (if require-match + crm-local-must-match-map + crm-local-completion-map)) + (helm-completion-in-region-default-sort-fn nil) + ;; If the user enters empty input, `read-from-minibuffer' + ;; returns the empty string, not DEF. + (input (read-from-minibuffer + prompt initial-input map + nil hist def inherit-input-method))) + (and def (string-equal input "") (setq input def)) + ;; Remove empty strings in the list of read strings. + (split-string input crm-separator t))) + (remove-hook 'choose-completion-string-functions + 'crm--choose-completion-string))) + +(defun magit-ido-completing-read + (prompt choices &optional predicate require-match initial-input hist def) + "Ido-based `completing-read' almost-replacement. + +Unfortunately `ido-completing-read' is not suitable as a +drop-in replacement for `completing-read', instead we use +`ido-completing-read+' from the third-party package by the +same name." + (if (require 'ido-completing-read+ nil t) + (ido-completing-read+ prompt choices predicate require-match + initial-input hist def) + (display-warning 'magit "ido-completing-read+ is not installed + +To use Ido completion with Magit you need to install the +third-party `ido-completing-read+' packages. Falling +back to built-in `completing-read' for now." :error) + (magit-builtin-completing-read prompt choices predicate require-match + initial-input hist def))) + +(defun magit-prompt-with-default (prompt def) + (if (and def (> (length prompt) 2) + (string-equal ": " (substring prompt -2))) + (format "%s (default %s): " (substring prompt 0 -2) def) + prompt)) + +(defvar magit-minibuffer-local-ns-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map minibuffer-local-map) + (define-key map "\s" 'magit-whitespace-disallowed) + (define-key map "\t" 'magit-whitespace-disallowed) + map)) + +(defun magit-whitespace-disallowed () + "Beep to tell the user that whitespace is not allowed." + (interactive) + (ding) + (message "Whitespace isn't allowed here") + (setq defining-kbd-macro nil) + (force-mode-line-update)) + +(defun magit-read-string (prompt &optional initial-input history default-value + inherit-input-method no-whitespace) + "Read a string from the minibuffer, prompting with string PROMPT. + +This is similar to `read-string', but +* empty input is only allowed if DEFAULT-VALUE is non-nil in + which case that is returned, +* whitespace is not allowed and leading and trailing whitespace is + removed automatically if NO-WHITESPACE is non-nil, +* \": \" is appended to PROMPT, and +* an invalid DEFAULT-VALUE is silently ignored." + (when default-value + (when (consp default-value) + (setq default-value (car default-value))) + (unless (stringp default-value) + (setq default-value nil))) + (let* ((minibuffer-completion-table nil) + (val (read-from-minibuffer + (magit-prompt-with-default (concat prompt ": ") default-value) + initial-input (and no-whitespace magit-minibuffer-local-ns-map) + nil history default-value inherit-input-method)) + (trim (lambda (regexp string) + (save-match-data + (if (string-match regexp string) + (replace-match "" t t string) + string))))) + (when (and (string= val "") default-value) + (setq val default-value)) + (when no-whitespace + (setq val (funcall trim "\\`\\(?:[ \t\n\r]+\\)" + (funcall trim "\\(?:[ \t\n\r]+\\)\\'" val)))) + (cond ((string= val "") + (user-error "Need non-empty input")) + ((and no-whitespace (string-match-p "[\s\t\n]" val)) + (user-error "Input contains whitespace")) + (t val)))) + +(defun magit-read-string-ns (prompt &optional initial-input history + default-value inherit-input-method) + "Call `magit-read-string' with non-nil NO-WHITESPACE." + (magit-read-string prompt initial-input history default-value + inherit-input-method t)) + +(defmacro magit-read-char-case (prompt verbose &rest clauses) + (declare (indent 2) + (debug (form form &rest (characterp form body)))) + `(pcase (read-char-choice + (concat ,prompt + ,(concat (mapconcat 'cadr clauses ", ") + (and verbose ", or [C-g] to abort") " ")) + ',(mapcar 'car clauses)) + ,@(--map `(,(car it) ,@(cddr it)) clauses))) + +(defun magit-y-or-n-p (prompt &optional action) + "Ask user a \"y or n\" or a \"yes or no\" question using PROMPT. +Which kind of question is used depends on whether +ACTION is a member of option `magit-slow-confirm'." + (if (or (eq magit-slow-confirm t) + (and action (member action magit-slow-confirm))) + (yes-or-no-p prompt) + (y-or-n-p prompt))) + +(defvar magit--no-confirm-alist + '((safe-with-wip magit-wip-before-change-mode + discard reverse stage-all-changes unstage-all-changes))) + +(cl-defun magit-confirm (action &optional prompt prompt-n noabort + (items nil sitems)) + (declare (indent defun)) + (setq prompt-n (format (concat (or prompt-n prompt) "? ") (length items))) + (setq prompt (format (concat (or prompt (magit-confirm-make-prompt action)) + "? ") + (car items))) + (or (cond ((and (not (eq action t)) + (or (eq magit-no-confirm t) + (memq action magit-no-confirm) + (cl-member-if (pcase-lambda (`(,key ,var . ,sub)) + (and (memq key magit-no-confirm) + (memq action sub) + (or (not var) + (and (boundp var) + (symbol-value var))))) + magit--no-confirm-alist))) + (or (not sitems) items)) + ((not sitems) + (magit-y-or-n-p prompt action)) + ((= (length items) 1) + (and (magit-y-or-n-p prompt action) items)) + ((> (length items) 1) + (and (magit-y-or-n-p (concat (mapconcat #'identity items "\n") + "\n\n" prompt-n) + action) + items))) + (if noabort nil (user-error "Abort")))) + +(defun magit-confirm-files (action files &optional prompt) + (when files + (unless prompt + (setq prompt (magit-confirm-make-prompt action))) + (magit-confirm action + (concat prompt " %s") + (concat prompt " %i files") + nil files))) + +(defun magit-confirm-make-prompt (action) + (let ((prompt (symbol-name action))) + (replace-regexp-in-string + "-" " " (concat (upcase (substring prompt 0 1)) (substring prompt 1))))) + +(defun magit-read-number-string (prompt &optional default) + "Like `read-number' but return value is a string. +DEFAULT may be a number or a numeric string." + (number-to-string + (read-number prompt (if (stringp default) + (string-to-number default) + default)))) + +;;; Debug Utilities + +;;;###autoload +(defun magit-emacs-Q-command () + "Show a shell command that runs an uncustomized Emacs with only Magit loaded. +See info node `(magit)Debugging Tools' for more information." + (interactive) + (let ((cmd (mapconcat + #'shell-quote-argument + `(,(concat invocation-directory invocation-name) + "-Q" "--eval" "(setq debug-on-error t)" + ,@(cl-mapcan + (lambda (dir) (list "-L" dir)) + (delete-dups + (cl-mapcan + (lambda (lib) + (let ((path (locate-library lib))) + (cond + (path + (list (file-name-directory path))) + ((not (member lib '("lv" "transient"))) + (error "Cannot find mandatory dependency %s" lib))))) + '(;; Like `LOAD_PATH' in `default.mk'. + "dash" + "ghub" + "graphql" + "lv" + "magit-popup" + "transient" + "treepy" + "with-editor" + ;; Obviously `magit' itself is needed too. + "magit" + ;; While this is part of the Magit repository, + ;; it is distributed as a separate package. + "git-commit" + ;; Even though `async' is a dependency of the + ;; `magit' package, it is not required here. + )))) + ;; Avoid Emacs bug#16406 by using full path. + "-l" ,(file-name-sans-extension (locate-library "magit"))) + " "))) + (message "Uncustomized Magit command saved to kill-ring, %s" + "please run it in a terminal.") + (kill-new cmd))) + +;;; Text Utilities + +(defmacro magit-bind-match-strings (varlist string &rest body) + "Bind variables to submatches according to VARLIST then evaluate BODY. +Bind the symbols in VARLIST to submatches of the current match +data, starting with 1 and incrementing by 1 for each symbol. If +the last match was against a string, then that has to be provided +as STRING." + (declare (indent 2) (debug (listp form body))) + (let ((s (cl-gensym "string")) + (i 0)) + `(let ((,s ,string)) + (let ,(save-match-data + (--map (list it (list 'match-string (cl-incf i) s)) varlist)) + ,@body)))) + +(defun magit-delete-line () + "Delete the rest of the current line." + (delete-region (point) (1+ (line-end-position)))) + +(defun magit-delete-match (&optional num) + "Delete text matched by last search. +If optional NUM is specified, only delete that subexpression." + (delete-region (match-beginning (or num 0)) + (match-end (or num 0)))) + +(defun magit-file-line (file) + "Return the first line of FILE as a string." + (when (file-regular-p file) + (with-temp-buffer + (insert-file-contents file) + (buffer-substring-no-properties (point-min) + (line-end-position))))) + +(defun magit-file-lines (file &optional keep-empty-lines) + "Return a list of strings containing one element per line in FILE. +Unless optional argument KEEP-EMPTY-LINES is t, trim all empty lines." + (when (file-regular-p file) + (with-temp-buffer + (insert-file-contents file) + (split-string (buffer-string) "\n" (not keep-empty-lines))))) + +(defun magit-set-header-line-format (string) + "Set the header-line using STRING. +Propertize STRING with the `magit-header-line' face if no face is +present, and pad the left and right sides of STRING equally such +that it will align with the text area." + (let* ((header-line + (concat (propertize " " + 'display + '(space :align-to 0)) + string + (propertize + " " + 'display + `(space :width (+ left-fringe + left-margin + ,@(and (eq (car (window-current-scroll-bars)) + 'left) + '(scroll-bar))))))) + (len (length header-line))) + (setq header-line-format + (if (text-property-not-all 0 len 'face nil header-line) + (let ((face (get-text-property 0 'face string))) + (when (and (atom face) + (magit-face-property-all face string)) + (add-face-text-property 0 1 face nil header-line) + (add-face-text-property (1- len) len face nil header-line)) + header-line) + (propertize header-line + 'face + 'magit-header-line))))) + +(defun magit-face-property-all (face string) + "Return non-nil if FACE is present in all of STRING." + (cl-loop for pos = 0 then (next-single-property-change pos 'face string) + unless pos + return t + for current = (get-text-property pos 'face string) + unless (if (consp current) + (memq face current) + (eq face current)) + return nil)) + +(defun magit--format-spec (format specification) + "Like `format-spec' but preserve text properties in SPECIFICATION." + (with-temp-buffer + (insert format) + (goto-char (point-min)) + (while (search-forward "%" nil t) + (cond + ;; Quoted percent sign. + ((eq (char-after) ?%) + (delete-char 1)) + ;; Valid format spec. + ((looking-at "\\([-0-9.]*\\)\\([a-zA-Z]\\)") + (let* ((num (match-string 1)) + (spec (string-to-char (match-string 2))) + (val (assq spec specification))) + (unless val + (error "Invalid format character: `%%%c'" spec)) + (setq val (cdr val)) + ;; Pad result to desired length. + (let ((text (format (concat "%" num "s") val))) + ;; Insert first, to preserve text properties. + (if (next-property-change 0 (concat " " text)) + ;; If the inserted text has properties, then preserve those. + (insert text) + ;; Otherwise preserve FORMAT's properties, like `format-spec'. + (insert-and-inherit text)) + ;; Delete the specifier body. + (delete-region (+ (match-beginning 0) (length text)) + (+ (match-end 0) (length text))) + ;; Delete the percent sign. + (delete-region (1- (match-beginning 0)) (match-beginning 0))))) + ;; Signal an error on bogus format strings. + (t + (error "Invalid format string")))) + (buffer-string))) + +;;; Missing from Emacs + +(defun magit-kill-this-buffer () + "Kill the current buffer." + (interactive) + (kill-buffer (current-buffer))) + +;;; Kludges for Emacs Bugs + +(defun magit-file-accessible-directory-p (filename) + "Like `file-accessible-directory-p' but work around an Apple bug. +See http://debbugs.gnu.org/cgi/bugreport.cgi?bug=21573#17 +and https://github.com/magit/magit/issues/2295." + (and (file-directory-p filename) + (file-accessible-directory-p filename))) + +(when (version<= "25.1" emacs-version) + (with-eval-after-load 'vc-git + (defun vc-git-conflicted-files (directory) + "Return the list of files with conflicts in DIRECTORY." + (let* ((status + (vc-git--run-command-string directory "diff-files" + "--name-status")) + (lines (when status (split-string status "\n" 'omit-nulls))) + files) + (dolist (line lines files) + (when (string-match "\\([ MADRCU?!]\\)[ \t]+\\(.+\\)" line) + (let ((state (match-string 1 line)) + (file (match-string 2 line))) + (when (equal state "U") + (push (expand-file-name file directory) files))))))))) + +(when (< emacs-major-version 27) + (defun vc-git--call@bug21559 (fn buffer command &rest args) + "Backport https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559." + (let ((process-environment process-environment)) + (when revert-buffer-in-progress-p + (push "GIT_OPTIONAL_LOCKS=0" process-environment)) + (apply fn buffer command args))) + (advice-add 'vc-git--call :around 'vc-git--call@bug21559) + + (defun vc-git-command@bug21559 + (fn buffer okstatus file-or-list &rest flags) + "Backport https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559." + (let ((process-environment process-environment)) + (when revert-buffer-in-progress-p + (push "GIT_OPTIONAL_LOCKS=0" process-environment)) + (apply fn buffer okstatus file-or-list flags))) + (advice-add 'vc-git-command :around 'vc-git-command@bug21559) + + (defun auto-revert-handler@bug21559 (fn) + "Backport https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559." + (let ((revert-buffer-in-progress-p t)) + (funcall fn))) + (advice-add 'auto-revert-handler :around 'auto-revert-handler@bug21559) + ) + +;; `completion-pcm--all-completions' reverses the completion list. To +;; preserve the order of our pre-sorted completions, we'll temporarily +;; override it with the function below. bug#24676 +(defun magit-completion-pcm--all-completions (prefix pattern table pred) + (if (completion-pcm--pattern-trivial-p pattern) + (all-completions (concat prefix (car pattern)) table pred) + (let* ((regex (completion-pcm--pattern->regex pattern)) + (case-fold-search completion-ignore-case) + (completion-regexp-list (cons regex completion-regexp-list)) + (compl (all-completions + (concat prefix + (if (stringp (car pattern)) (car pattern) "")) + table pred))) + (if (not (functionp table)) + compl + (let ((poss ())) + (dolist (c compl) + (when (string-match-p regex c) (push c poss))) + ;; This `nreverse' call is the only code change made to the + ;; `completion-pcm--all-completions' that shipped with Emacs 25.1. + (nreverse poss)))))) + +;;; Kludges for Incompatible Modes + +(defvar whitespace-mode) + +(defun whitespace-dont-turn-on-in-magit-mode (fn) + "Prevent `whitespace-mode' from being turned on in Magit buffers. + +Because `whitespace-mode' uses font-lock and Magit does not, they +are not compatible. Therefore you cannot turn on that minor-mode +in Magit buffers. If you try to enable it anyway, then this +advice prevents that. + +If the reason the attempt is made is that `global-whitespace-mode' +is enabled, then that is done silently. However if you call the local +minor-mode interactively, then that results in an error. + +See `magit-diff-paint-whitespace' for an alternative." + (if (not (derived-mode-p 'magit-mode)) + (funcall fn) + (setq whitespace-mode nil) + (when (eq this-command 'whitespace-mode) + (user-error + "Whitespace mode NOT enabled because it is not compatible with Magit")))) + +(advice-add 'whitespace-turn-on :around + 'whitespace-dont-turn-on-in-magit-mode) + +;;; Kludges for Custom + +(defun magit-custom-initialize-reset (symbol exp) + "Initialize SYMBOL based on EXP. +Set the symbol, using `set-default' (unlike +`custom-initialize-reset' which uses the `:set' function if any.) +The value is either the symbol's current value + (as obtained using the `:get' function), if any, +or the value in the symbol's `saved-value' property if any, +or (last of all) the value of EXP." + (set-default-toplevel-value + symbol + (condition-case nil + (let ((def (default-toplevel-value symbol)) + (getter (get symbol 'custom-get))) + (if getter (funcall getter symbol) def)) + (error + (eval (let ((sv (get symbol 'saved-value))) + (if sv (car sv) exp))))))) + +(defun magit-hook-custom-get (symbol) + (if (symbol-file symbol 'defvar) + (default-toplevel-value symbol) + ;; + ;; Called by `custom-initialize-reset' on behalf of `symbol's + ;; `defcustom', which is being evaluated for the first time to + ;; set the initial value, but there's already a default value, + ;; which most likely was established by one or more `add-hook' + ;; calls. + ;; + ;; We combine the `standard-value' and the current value, while + ;; preserving the order established by `:options', and return + ;; the result of that to be used as the "initial" default value. + ;; + (let ((standard (eval (car (get symbol 'standard-value)))) + (current (default-toplevel-value symbol)) + (value nil)) + (dolist (fn (get symbol 'custom-options)) + (when (or (memq fn standard) + (memq fn current)) + (push fn value))) + (dolist (fn current) + (unless (memq fn value) + (push fn value))) + (nreverse value)))) + +;;; Kludges for Info Manuals + +;;;###autoload +(defun Info-follow-nearest-node--magit-gitman (fn &optional fork) + (if magit-view-git-manual-method + (let ((node (Info-get-token + (point) "\\*note[ \n\t]+" + "\\*note[ \n\t]+\\([^:]*\\):\\(:\\|[ \n\t]*(\\)?"))) + (if (and node (string-match "^(gitman)\\(.+\\)" node)) + (pcase magit-view-git-manual-method + (`man (require 'man) + (man (match-string 1 node))) + (`woman (require 'woman) + (woman (match-string 1 node))) + (_ + (user-error "Invalid value for `magit-view-git-documentation'"))) + (funcall fn fork))) + (funcall fn fork))) + +;;;###autoload +(advice-add 'Info-follow-nearest-node :around + 'Info-follow-nearest-node--magit-gitman) + +;;;###autoload +(defun org-man-export--magit-gitman (fn link description format) + (if (and (eq format 'texinfo) + (string-match-p "\\`git" link)) + (replace-regexp-in-string "%s" link " +@ifinfo +@ref{%s,,,gitman,}. +@end ifinfo +@ifhtml +@html +the %s(1) manpage. +@end html +@end ifhtml +@iftex +the %s(1) manpage. +@end iftex +") + (funcall fn link description format))) + +;;;###autoload +(advice-add 'org-man-export :around + 'org-man-export--magit-gitman) + +;;; Miscellaneous + +(defun magit-message (format-string &rest args) + "Display a message at the bottom of the screen, or not. +Like `message', except that if the users configured option +`magit-no-message' to prevent the message corresponding to +FORMAT-STRING to be displayed, then don't." + (unless (--first (string-prefix-p it format-string) magit-no-message) + (apply #'message format-string args))) + +(defun magit-msg (format-string &rest args) + "Display a message at the bottom of the screen, but don't log it. +Like `message', except that `message-log-max' is bound to nil." + (let ((message-log-max nil)) + (apply #'message format-string args))) + +;;; _ +(provide 'magit-utils) +;;; magit-utils.el ends here diff --git a/elpa/magit-20181113.1837/magit-wip.el b/elpa/magit-20181113.1837/magit-wip.el new file mode 100644 index 00000000..10c085be --- /dev/null +++ b/elpa/magit-20181113.1837/magit-wip.el @@ -0,0 +1,432 @@ +;;; magit-wip.el --- commit snapshots to work-in-progress refs -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library defines tree global modes which automatically commit +;; snapshots to branch-specific work-in-progress refs before and after +;; making changes, and two commands which can be used to do so on +;; demand. + +;;; Code: + +(eval-when-compile + (require 'subr-x)) + +(require 'magit-core) +(require 'magit-log) + +;;; Options + +(defgroup magit-wip nil + "Automatically commit to work-in-progress refs." + :link '(info-link "(magit)Wip Modes") + :group 'magit-modes + :group 'magit-essentials) + +(defgroup magit-wip-legacy nil + "It is better to not use these modes individually." + :link '(info-link "(magit)Legacy Wip Modes") + :group 'magit-wip) + +(defcustom magit-wip-mode-lighter " Wip" + "Lighter for Magit-Wip mode." + :package-version '(magit . "2.90.0") + :group 'magit-wip + :type 'string) + +(defcustom magit-wip-after-save-local-mode-lighter "" + "Lighter for Magit-Wip-After-Save-Local mode." + :package-version '(magit . "2.1.0") + :group 'magit-wip-legacy + :type 'string) + +(defcustom magit-wip-after-apply-mode-lighter "" + "Lighter for Magit-Wip-After-Apply mode." + :package-version '(magit . "2.1.0") + :group 'magit-wip-legacy + :type 'string) + +(defcustom magit-wip-before-change-mode-lighter "" + "Lighter for Magit-Wip-Before-Change mode." + :package-version '(magit . "2.1.0") + :group 'magit-wip-legacy + :type 'string) + +(defcustom magit-wip-initial-backup-mode-lighter "" + "Lighter for Magit-Wip-Initial Backup mode." + :package-version '(magit . "2.1.0") + :group 'magit-wip-legacy + :type 'string) + +(defcustom magit-wip-merge-branch nil + "Whether to merge the current branch into its wip ref. + +If non-nil and the current branch has new commits, then it is +merged into the wip ref before creating a new wip commit. This +makes it easier to inspect wip history and the wip commits are +never garbage collected. + +If nil and the current branch has new commits, then the wip ref +is reset to the tip of the branch before creating a new wip +commit. With this setting wip commits are eventually garbage +collected. This is currently the default." + :package-version '(magit . "2.90.0") + :group 'magit-wip + :type 'boolean) + +(defcustom magit-wip-namespace "refs/wip/" + "Namespace used for work-in-progress refs. +The wip refs are named \"index/\" +and \"wtree/\". When snapshots +are created while the `HEAD' is detached then \"HEAD\" +is used as `branch-ref'." + :package-version '(magit . "2.1.0") + :group 'magit-wip + :type 'string) + +;;; Modes + +(define-minor-mode magit-wip-mode + "Save uncommitted changes to work-in-progress refs. + +Whenever appropriate (i.e. when dataloss would be a possibility +otherwise) this mode causes uncommitted changes to be committed +to dedicated work-in-progress refs. + +For historic reasons this mode is implemented on top of four +other `magit-wip-*' modes, which can also be used individually, +if you want finer control over when the wip refs are updated; +but that is discouraged." + :package-version '(magit . "2.90.0") + :lighter magit-wip-mode-lighter + :global t + (let ((arg (if magit-wip-mode 1 -1))) + (magit-wip-after-save-mode arg) + (magit-wip-after-apply-mode arg) + (magit-wip-before-change-mode arg) + (magit-wip-initial-backup-mode arg))) + +(define-minor-mode magit-wip-after-save-local-mode + "After saving, also commit to a worktree work-in-progress ref. + +After saving the current file-visiting buffer this mode also +commits the changes to the worktree work-in-progress ref for +the current branch. + +This mode should be enabled globally by turning on the globalized +variant `magit-wip-after-save-mode'." + :package-version '(magit . "2.1.0") + :lighter magit-wip-after-save-local-mode-lighter + (if magit-wip-after-save-local-mode + (if (and buffer-file-name (magit-inside-worktree-p t)) + (add-hook 'after-save-hook 'magit-wip-commit-buffer-file t t) + (setq magit-wip-after-save-local-mode nil) + (user-error "Need a worktree and a file")) + (remove-hook 'after-save-hook 'magit-wip-commit-buffer-file t))) + +(defun magit-wip-after-save-local-mode-turn-on () + (and buffer-file-name + (magit-inside-worktree-p t) + (magit-file-tracked-p buffer-file-name) + (magit-wip-after-save-local-mode))) + +;;;###autoload +(define-globalized-minor-mode magit-wip-after-save-mode + magit-wip-after-save-local-mode magit-wip-after-save-local-mode-turn-on + :package-version '(magit . "2.1.0") + :group 'magit-wip) + +(defun magit-wip-commit-buffer-file (&optional msg) + "Commit visited file to a worktree work-in-progress ref. + +Also see `magit-wip-after-save-mode' which calls this function +automatically whenever a buffer visiting a tracked file is saved." + (interactive) + (--when-let (magit-wip-get-ref) + (magit-with-toplevel + (let ((file (file-relative-name buffer-file-name))) + (magit-wip-commit-worktree + it (list file) + (format (cond (msg) + ((called-interactively-p 'any) + "wip-save %s after save") + (t + "autosave %s after save")) + file)))))) + +;;;###autoload +(define-minor-mode magit-wip-after-apply-mode + "Commit to work-in-progress refs. + +After applying a change using any \"apply variant\" +command (apply, stage, unstage, discard, and reverse) commit the +affected files to the current wip refs. For each branch there +may be two wip refs; one contains snapshots of the files as found +in the worktree and the other contains snapshots of the entries +in the index." + :package-version '(magit . "2.1.0") + :group 'magit-wip + :lighter magit-wip-after-apply-mode-lighter + :global t) + +(defun magit-wip-commit-after-apply (&optional files msg) + (when magit-wip-after-apply-mode + (magit-wip-commit files msg))) + +;;;###autoload +(define-minor-mode magit-wip-before-change-mode + "Commit to work-in-progress refs before certain destructive changes. + +Before invoking a revert command or an \"apply variant\" +command (apply, stage, unstage, discard, and reverse) commit the +affected tracked files to the current wip refs. For each branch +there may be two wip refs; one contains snapshots of the files +as found in the worktree and the other contains snapshots of the +entries in the index. + +Only changes to files which could potentially be affected by the +command which is about to be called are committed." + :package-version '(magit . "2.1.0") + :group 'magit-wip + :lighter magit-wip-before-change-mode-lighter + :global t) + +(defun magit-wip-commit-before-change (&optional files msg) + (when magit-wip-before-change-mode + (magit-with-toplevel + (magit-wip-commit files msg)))) + +(define-minor-mode magit-wip-initial-backup-mode + "Before saving a buffer for the first time, commit to a wip ref." + :package-version '(magit . "2.90.0") + :group 'magit-wip + :lighter magit-wip-initial-backup-mode-lighter + :global t + (if magit-wip-initial-backup-mode + (add-hook 'before-save-hook 'magit-wip-commit-initial-backup) + (remove-hook 'before-save-hook 'magit-wip-commit-initial-backup))) + +(defvar-local magit-wip-buffer-backed-up nil) +(put 'magit-wip-buffer-backed-up 'permanent-local t) + +;;;###autoload +(defun magit-wip-commit-initial-backup () + "Before saving, commit current file to a worktree wip ref. + +The user has to add this function to `before-save-hook'. + +Commit the current state of the visited file before saving the +current buffer to that file. This backs up the same version of +the file as `backup-buffer' would, but stores the backup in the +worktree wip ref, which is also used by the various Magit Wip +modes, instead of in a backup file as `backup-buffer' would. + +This function ignores the variables that affect `backup-buffer' +and can be used along-side that function, which is recommended +because this function only backs up files that are tracked in +a Git repository." + (when (and (not magit-wip-buffer-backed-up) + buffer-file-name + (magit-inside-worktree-p t) + (magit-file-tracked-p buffer-file-name)) + (let ((magit-save-repository-buffers nil)) + (magit-wip-commit-buffer-file "autosave %s before save")) + (setq magit-wip-buffer-backed-up t))) + +;;; Core + +(defun magit-wip-commit (&optional files msg) + "Commit all tracked files to the work-in-progress refs. + +Interactively, commit all changes to all tracked files using +a generic commit message. With a prefix-argument the commit +message is read in the minibuffer. + +Non-interactively, only commit changes to FILES using MSG as +commit message." + (interactive (list nil (if current-prefix-arg + (magit-read-string "Wip commit message") + "wip-save tracked files"))) + (--when-let (magit-wip-get-ref) + (magit-wip-commit-index it files msg) + (magit-wip-commit-worktree it files msg))) + +(defun magit-wip-commit-index (ref files msg) + (let* ((wipref (magit--wip-index-ref ref)) + (parent (magit-wip-get-parent ref wipref)) + (tree (magit-git-string "write-tree"))) + (magit-wip-update-wipref ref wipref tree parent files msg "index"))) + +(defun magit-wip-commit-worktree (ref files msg) + (let* ((wipref (magit--wip-wtree-ref ref)) + (parent (magit-wip-get-parent ref wipref)) + (tree (magit-with-temp-index parent "--reset" + (if files + (magit-call-git "add" "--" files) + (magit-with-toplevel + (magit-call-git "add" "-u" "."))) + (magit-git-string "write-tree")))) + (magit-wip-update-wipref ref wipref tree parent files msg "worktree"))) + +(defun magit-wip-update-wipref (ref wipref tree parent files msg start-msg) + (cond + ((and (not (equal parent wipref)) + (or (not magit-wip-merge-branch) + (not (magit-rev-verify wipref)))) + (setq start-msg (concat "start autosaving " start-msg)) + (magit-update-ref wipref start-msg + (magit-git-string "commit-tree" "--no-gpg-sign" + "-p" parent "-m" start-msg + (concat parent "^{tree}"))) + (setq parent wipref)) + ((and magit-wip-merge-branch + (or (not (magit-rev-ancestor-p ref wipref)) + (not (magit-rev-ancestor-p + (concat (magit-git-string "log" "--format=%H" + "-1" "--merges" wipref) + "^2") + ref)))) + (setq start-msg (format "merge %s into %s" ref start-msg)) + (magit-update-ref wipref start-msg + (magit-git-string "commit-tree" "--no-gpg-sign" + "-p" wipref "-p" ref + "-m" start-msg + (concat ref "^{tree}"))) + (setq parent wipref))) + (when (magit-git-failure "diff-tree" "--quiet" parent tree "--" files) + (unless (and msg (not (= (aref msg 0) ?\s))) + (let ((len (length files))) + (setq msg (concat + (cond ((= len 0) "autosave tracked files") + ((> len 1) (format "autosave %s files" len)) + (t (concat "autosave " + (file-relative-name (car files) + (magit-toplevel))))) + msg)))) + (magit-update-ref wipref msg + (magit-git-string "commit-tree" "--no-gpg-sign" + "-p" parent "-m" msg tree)))) + +(defun magit-wip-get-ref () + (let ((ref (or (magit-git-string "symbolic-ref" "HEAD") "HEAD"))) + (and (magit-rev-verify ref) + ref))) + +(defun magit-wip-get-parent (ref wipref) + (if (and (magit-rev-verify wipref) + (equal (magit-git-string "merge-base" wipref ref) + (magit-rev-verify ref))) + wipref + ref)) + +(defun magit--wip-index-ref (&optional ref) + (magit--wip-ref "index/" ref)) + +(defun magit--wip-wtree-ref (&optional ref) + (magit--wip-ref "wtree/" ref)) + +(defun magit--wip-ref (namespace &optional ref) + (concat magit-wip-namespace namespace + (or (and ref (string-prefix-p "refs/" ref) ref) + (when-let ((branch (or ref (magit-get-current-branch)))) + (concat "refs/heads/" branch)) + "HEAD"))) + +(defun magit-wip-maybe-add-commit-hook () + (when (and magit-wip-merge-branch + (magit-wip-any-enabled-p)) + (add-hook 'git-commit-post-finish-hook 'magit-wip-commit nil t))) + +(defun magit-wip-any-enabled-p () + (or magit-wip-mode + magit-wip-after-save-local-mode + magit-wip-after-save-mode + magit-wip-after-apply-mode + magit-wip-before-change-mode + magit-wip-initial-backup-mode)) + +;;; Log + +(defun magit-wip-log-index (args files) + "Show log for the index wip ref of the current branch." + (interactive (magit-log-arguments)) + (magit-git-log (list (magit--wip-index-ref)) args files)) + +(defun magit-wip-log-worktree (args files) + "Show log for the worktree wip ref of the current branch." + (interactive (magit-log-arguments)) + (magit-git-log (list (magit--wip-wtree-ref)) args files)) + +(defun magit-wip-log-current (branch args files count) + "Show log for the current branch and its wip refs. +With a negative prefix argument only show the worktree wip ref. +The absolute numeric value of the prefix argument controls how +many \"branches\" of each wip ref are shown." + (interactive + (nconc (list (or (magit-get-current-branch) "HEAD")) + (magit-log-arguments) + (list (prefix-numeric-value current-prefix-arg)))) + (magit-wip-log branch args files count)) + +(defun magit-wip-log (branch args files count) + "Show log for a branch and its wip refs. +With a negative prefix argument only show the worktree wip ref. +The absolute numeric value of the prefix argument controls how +many \"branches\" of each wip ref are shown." + (interactive + (nconc (list (magit-completing-read + "Log branch and its wip refs" + (-snoc (magit-list-local-branch-names) "HEAD") + nil t nil 'magit-revision-history + (or (magit-branch-at-point) + (magit-get-current-branch) + "HEAD"))) + (magit-log-arguments) + (list (prefix-numeric-value current-prefix-arg)))) + (magit-git-log (nconc (list branch) + (magit-wip-log-get-tips + (magit--wip-wtree-ref branch) + (abs count)) + (and (>= count 0) + (magit-wip-log-get-tips + (magit--wip-index-ref branch) + (abs count)))) + args files)) + +(defun magit-wip-log-get-tips (wipref count) + (when-let ((reflog (magit-git-lines "reflog" wipref))) + (let (tips) + (while (and reflog (> count 1)) + (setq reflog (cl-member "^[^ ]+ [^:]+: restart autosaving" + reflog :test #'string-match-p)) + (when (and (cadr reflog) + (string-match "^[^ ]+ \\([^:]+\\)" (cadr reflog))) + (push (match-string 1 (cadr reflog)) tips)) + (setq reflog (cddr reflog)) + (cl-decf count)) + (cons wipref (nreverse tips))))) + +;;; _ +(provide 'magit-wip) +;;; magit-wip.el ends here diff --git a/elpa/magit-20181113.1837/magit-worktree.el b/elpa/magit-20181113.1837/magit-worktree.el new file mode 100644 index 00000000..08941e5a --- /dev/null +++ b/elpa/magit-20181113.1837/magit-worktree.el @@ -0,0 +1,175 @@ +;;; magit-worktree.el --- worktree support -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This library implements support for `git-worktree'. + +;;; Code: + +(require 'magit) + +;;; Commands + +;;;###autoload (autoload 'magit-worktree-popup "magit-worktree" nil t) +(magit-define-popup magit-worktree-popup + "Popup console for worktree commands." + :man-page "git-worktree" + :actions `((?b "Create new worktree" magit-worktree-checkout) + (?c "Create new branch and worktree" magit-worktree-branch) + ,@(and (not (require (quote forge) nil t)) + '((?p "Create new worktree from pull-request" + magit-worktree-checkout-pull-request))) + (?k "Delete worktree" magit-worktree-delete) + (?g "Show status for worktree" magit-worktree-status)) + :max-action-columns 1) + +;;;###autoload +(defun magit-worktree-checkout (path branch) + "Checkout BRANCH in a new worktree at PATH." + (interactive + (let ((branch (magit-read-local-branch-or-commit "Checkout"))) + (list (read-directory-name (format "Checkout %s in new worktree: " branch)) + branch))) + (magit-run-git "worktree" "add" (expand-file-name path) branch) + (magit-diff-visit-directory path)) + +(defun magit-worktree-checkout-pull-request (path pr) + "Create, configure and checkout a new worktree from a pull-request. +This is like `magit-checkout-pull-request', except that it +also creates a new worktree. Please see the manual for more +information." + (interactive + (let ((pr (magit-read-pull-request "Checkout pull request"))) + (let-alist pr + (let ((path (let ((branch (magit--pullreq-branch pr t))) + (read-directory-name + (format "Checkout #%s as `%s' in new worktree: " + .number branch) + (file-name-directory + (directory-file-name default-directory)) + nil nil + (if (string-match-p "\\`pr-[0-9]+\\'" branch) + (number-to-string .number) + (format "%s-%s" .number .head.ref)))))) + (when (equal path "") + (user-error "The empty string isn't a valid path")) + (list path pr))))) + (when (and (file-exists-p path) + (not (and (file-directory-p path) + (= (length (directory-files "/tmp/testing/")) 2)))) + (user-error "%s already exists and isn't empty" path)) + (magit-worktree-checkout path + (let ((inhibit-magit-refresh t)) + (magit-branch-pull-request pr)))) + +;;;###autoload +(defun magit-worktree-branch (path branch start-point &optional force) + "Create a new BRANCH and check it out in a new worktree at PATH." + (interactive + `(,(read-directory-name "Create worktree: ") + ,@(butlast (magit-branch-read-args "Create and checkout branch")) + ,current-prefix-arg)) + (magit-run-git "worktree" "add" (if force "-B" "-b") + branch (expand-file-name path) start-point) + (magit-diff-visit-directory path)) + +(defun magit-worktree-delete (worktree) + "Delete a worktree, defaulting to the worktree at point. +The primary worktree cannot be deleted." + (interactive + (list (magit-completing-read "Delete worktree" + (cdr (magit-list-worktrees)) + nil t nil nil + (magit-section-value-if 'worktree)))) + (if (file-directory-p (expand-file-name ".git" worktree)) + (user-error "Deleting %s would delete the shared .git directory" worktree) + (let ((primary (file-name-as-directory (caar (magit-list-worktrees))))) + (magit-confirm-files (if magit-delete-by-moving-to-trash 'trash 'delete) + (list "worktree")) + (when (file-exists-p worktree) + (let ((delete-by-moving-to-trash magit-delete-by-moving-to-trash)) + (delete-directory worktree t magit-delete-by-moving-to-trash))) + (if (file-exists-p default-directory) + (magit-run-git "worktree" "prune") + (let ((default-directory primary)) + (magit-run-git "worktree" "prune")) + (when (derived-mode-p 'magit-status-mode) + (kill-buffer) + (magit-status-internal primary)))))) + +(defun magit-worktree-status (worktree) + "Show the status for the worktree at point. +If there is no worktree at point, then read one in the +minibuffer. If the worktree at point is the one whose +status is already being displayed in the current buffer, +then show it in Dired instead." + (interactive + (list (or (magit-section-value-if 'worktree) + (magit-completing-read + "Show status for worktree" + (cl-delete (directory-file-name (magit-toplevel)) + (magit-list-worktrees) + :test #'equal :key #'car))))) + (magit-diff-visit-directory worktree)) + +;;; Sections + +(defvar magit-worktree-section-map + (let ((map (make-sparse-keymap))) + (define-key map [remap magit-visit-thing] 'magit-worktree-status) + (define-key map [remap magit-delete-thing] 'magit-worktree-delete) + map) + "Keymap for `worktree' sections.") + +(defun magit-insert-worktrees () + "Insert sections for all worktrees. +If there is only one worktree, then insert nothing." + (let ((worktrees (magit-list-worktrees))) + (when (> (length worktrees) 1) + (magit-insert-section (worktrees) + (magit-insert-heading "Worktrees:") + (let* ((cols + (mapcar (pcase-lambda (`(,path ,barep ,commit ,branch)) + (cons (cond + (branch (propertize branch + 'face 'magit-branch-local)) + (commit (propertize (magit-rev-abbrev commit) + 'face 'magit-hash)) + (barep "(bare)")) + path)) + worktrees)) + (align (1+ (-max (--map (string-width (car it)) cols))))) + (pcase-dolist (`(,head . ,path) cols) + (magit-insert-section (worktree path) + (insert head) + (indent-to align) + (insert (let ((r (file-relative-name path)) + (a (abbreviate-file-name path))) + (if (< (string-width r) (string-width a)) r a))) + (insert ?\n)))) + (insert ?\n))))) + +;;; _ +(provide 'magit-worktree) +;;; magit-worktree.el ends here diff --git a/elpa/magit-20181113.1837/magit.el b/elpa/magit-20181113.1837/magit.el new file mode 100644 index 00000000..5bd9146f --- /dev/null +++ b/elpa/magit-20181113.1837/magit.el @@ -0,0 +1,630 @@ +;;; magit.el --- A Git porcelain inside Emacs -*- lexical-binding: t; coding: utf-8 -*- + +;; Copyright (C) 2008-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; Author: Marius Vollmer +;; Maintainer: Jonas Bernoulli +;; Kyle Meyer +;; Noam Postavsky +;; Former-Maintainers: +;; Nicolas Dudebout +;; Peter J. Weisberg +;; Phil Jackson +;; Rémi Vanicat +;; Yann Hodique + +;; Keywords: git tools vc +;; Homepage: https://github.com/magit/magit + +;; Magit requires at least GNU Emacs 25.1 and Git 2.0.0. + +;; Magit 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. +;; +;; Magit 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 Magit. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; Magit is an interface to the version control system Git, +;; implemented as an Emacs package. Magit aspires to be a complete +;; Git porcelain. While we cannot (yet) claim, that Magit wraps and +;; improves upon each and every Git command, it is complete enough to +;; allow even experienced Git users to perform almost all of their +;; daily version control tasks directly from within Emacs. While many +;; fine Git clients exist, only Magit and Git itself deserve to be +;; called porcelains. + +;;; Code: + +(require 'cl-lib) +(require 'dash) + +(eval-when-compile + (require 'subr-x)) + +(require 'with-editor) +(require 'git-commit) +(require 'magit-core) +(require 'magit-diff) +(require 'magit-apply) +(require 'magit-log) +(require 'magit-repos) + +(require 'format-spec) +(require 'package nil t) ; used in `magit-version' + +(defconst magit--minimal-git "2.0.0") +(defconst magit--minimal-emacs "25.1") + +;;; Faces + +(defface magit-header-line + '((t :inherit magit-section-heading)) + "Face for the `header-line' in some Magit modes. +Note that some modes, such as `magit-log-select-mode', have their +own faces for the `header-line', or for parts of the +`header-line'." + :group 'magit-faces) + +(defface magit-header-line-key + '((t :inherit magit-popup-key)) + "Face for keys in the `header-line'." + :group 'magit-faces) + +(defface magit-dimmed + '((((class color) (background light)) :foreground "grey50") + (((class color) (background dark)) :foreground "grey50")) + "Face for text that shouldn't stand out." + :group 'magit-faces) + +(defface magit-hash + '((((class color) (background light)) :foreground "grey60") + (((class color) (background dark)) :foreground "grey40")) + "Face for the sha1 part of the log output." + :group 'magit-faces) + +(defface magit-tag + '((((class color) (background light)) :foreground "Goldenrod4") + (((class color) (background dark)) :foreground "LightGoldenrod2")) + "Face for tag labels shown in log buffer." + :group 'magit-faces) + +(defface magit-branch-remote + '((((class color) (background light)) :foreground "DarkOliveGreen4") + (((class color) (background dark)) :foreground "DarkSeaGreen2")) + "Face for remote branch head labels shown in log buffer." + :group 'magit-faces) + +(defface magit-branch-remote-head + '((((class color) (background light)) :inherit magit-branch-remote :box t) + (((class color) (background dark)) :inherit magit-branch-remote :box t)) + "Face for current branch." + :group 'magit-faces) + +(defface magit-branch-local + '((((class color) (background light)) :foreground "SkyBlue4") + (((class color) (background dark)) :foreground "LightSkyBlue1")) + "Face for local branches." + :group 'magit-faces) + +(defface magit-branch-current + '((((class color) (background light)) :inherit magit-branch-local :box t) + (((class color) (background dark)) :inherit magit-branch-local :box t)) + "Face for current branch." + :group 'magit-faces) + +(defface magit-branch-upstream + '((t :slant italic)) + "Face for upstream branch. +This face is only used in logs and it gets combined + with `magit-branch-local', `magit-branch-remote' +and/or `magit-branch-remote-head'." + :group 'magit-faces) + +(defface magit-head + '((((class color) (background light)) :inherit magit-branch-local) + (((class color) (background dark)) :inherit magit-branch-local)) + "Face for the symbolic ref `HEAD'." + :group 'magit-faces) + +(defface magit-refname + '((((class color) (background light)) :foreground "grey30") + (((class color) (background dark)) :foreground "grey80")) + "Face for refnames without a dedicated face." + :group 'magit-faces) + +(defface magit-refname-stash + '((t :inherit magit-refname)) + "Face for stash refnames." + :group 'magit-faces) + +(defface magit-refname-wip + '((t :inherit magit-refname)) + "Face for wip refnames." + :group 'magit-faces) + +(defface magit-refname-pullreq + '((t :inherit magit-refname)) + "Face for pullreq refnames." + :group 'magit-faces) + +(defface magit-keyword + '((t :inherit font-lock-string-face)) + "Face for parts of commit messages inside brackets." + :group 'magit-faces) + +(defface magit-keyword-squash + '((t :inherit font-lock-warning-face)) + "Face for squash! and fixup! keywords in commit messages." + :group 'magit-faces) + +(defface magit-signature-good + '((t :foreground "green")) + "Face for good signatures." + :group 'magit-faces) + +(defface magit-signature-bad + '((t :foreground "red" :weight bold)) + "Face for bad signatures." + :group 'magit-faces) + +(defface magit-signature-untrusted + '((t :foreground "cyan")) + "Face for good untrusted signatures." + :group 'magit-faces) + +(defface magit-signature-expired + '((t :foreground "orange")) + "Face for signatures that have expired." + :group 'magit-faces) + +(defface magit-signature-expired-key + '((t :inherit magit-signature-expired)) + "Face for signatures made by an expired key." + :group 'magit-faces) + +(defface magit-signature-revoked + '((t :foreground "violet red")) + "Face for signatures made by a revoked key." + :group 'magit-faces) + +(defface magit-signature-error + '((t :foreground "firebrick3")) + "Face for signatures that cannot be checked (e.g. missing key)." + :group 'magit-faces) + +(defface magit-cherry-unmatched + '((t :foreground "cyan")) + "Face for unmatched cherry commits." + :group 'magit-faces) + +(defface magit-cherry-equivalent + '((t :foreground "magenta")) + "Face for equivalent cherry commits." + :group 'magit-faces) + +(defface magit-filename + '((t :weight normal)) + "Face for filenames." + :group 'magit-faces) + +;;; Dispatch Popup + +;;;###autoload (autoload 'magit-dispatch-popup "magit" nil t) +(magit-define-popup magit-dispatch-popup + "Popup console for dispatching other popups." + :actions '("Popup and dwim commands" + (?A "Cherry-picking" magit-cherry-pick-popup) + (?b "Branching" magit-branch-popup) + (?B "Bisecting" magit-bisect-popup) + (?c "Committing" magit-commit-popup) + (?d "Diffing" magit-diff-popup) + (?D "Change diffs" magit-diff-refresh-popup) + (?e "Ediff dwimming" magit-ediff-dwim) + (?E "Ediffing" magit-ediff-popup) + (?f "Fetching" magit-fetch-popup) + (?F "Pulling" magit-pull-popup) + (?l "Logging" magit-log-popup) + (?L "Change logs" magit-log-refresh-popup) + (?m "Merging" magit-merge-popup) + (?M "Remoting" magit-remote-popup) + (?o "Submodules" magit-submodule-popup) + (?O "Subtrees" magit-subtree-popup) + (?P "Pushing" magit-push-popup) + (?r "Rebasing" magit-rebase-popup) + (?t "Tagging" magit-tag-popup) + (?T "Notes" magit-notes-popup) + (?V "Reverting" magit-revert-popup) + (?w "Apply patches" magit-am-popup) + (?W "Format patches" magit-patch-popup) + (?X "Resetting" magit-reset-popup) + (?y "Show Refs" magit-show-refs-popup) + (?z "Stashing" magit-stash-popup) + (?! "Running" magit-run-popup) + (?% "Worktree" magit-worktree-popup) + (lambda () + (and (with-current-buffer magit-pre-popup-buffer + (derived-mode-p 'magit-mode)) + (propertize "Applying changes" 'face 'magit-popup-heading))) + (?a "Apply" magit-apply) + (?s "Stage" magit-stage) + (?u "Unstage" magit-unstage) + (?v "Reverse" magit-reverse) + (?S "Stage all" magit-stage-modified) + (?U "Unstage all" magit-unstage-all) + (?k "Discard" magit-discard) + (lambda () + (and (with-current-buffer magit-pre-popup-buffer + (derived-mode-p 'magit-mode)) + (propertize "Essential commands" 'face 'magit-popup-heading))) + (?g " refresh current buffer" magit-refresh) + ;; These bindings only work because of :setup-function. + (?\t " toggle section at point" magit-section-toggle) + (?\r " visit thing at point" magit-visit-thing) + ;; This binding has no effect and only appears to do + ;; so because it is identical to the global binding. + ("C-h m" "show all key bindings" describe-mode)) + :setup-function 'magit-dispatch-popup-setup + :max-action-columns (lambda (heading) + (pcase heading + ("Popup and dwim commands" 4) + ("Applying changes" 3) + ("Essential commands" 1)))) + +(defvar magit-dispatch-popup-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map magit-popup-mode-map) + (cond ((featurep 'jkl) + (define-key map [tab] 'magit-invoke-popup-action) + (define-key map [return] 'magit-invoke-popup-action)) + (t + (define-key map (kbd "C-i") 'magit-invoke-popup-action) + (define-key map (kbd "C-m") 'magit-invoke-popup-action))) + map) + "Keymap used by `magit-dispatch-popup'.") + +(defun magit-dispatch-popup-setup (val def) + (magit-popup-default-setup val def) + (use-local-map magit-dispatch-popup-map) + ;; This is necessary for users (i.e. me) who have broken the + ;; connection between C-i (aka TAB) and tab, and C-m (aka RET) + ;; and return. + (magit-popup-put + :actions (nconc (magit-popup-get :actions) + (list (make-magit-popup-event :key 'tab + :fun 'magit-section-toggle) + (make-magit-popup-event :key 'return + :fun 'magit-visit-thing))))) + +;;; Git Popup + +(defcustom magit-shell-command-verbose-prompt t + "Whether to show the working directory when reading a command. +This affects `magit-git-command', `magit-git-command-topdir', +`magit-shell-command', and `magit-shell-command-topdir'." + :package-version '(magit . "2.11.0") + :group 'magit-commands + :type 'boolean) + +(defvar magit-git-command-history nil) + +;;;###autoload (autoload 'magit-run-popup "magit" nil t) +(magit-define-popup magit-run-popup + "Popup console for running raw Git commands." + :actions '((?! "Git Subcommand (in topdir)" magit-git-command-topdir) + (?k "Gitk" magit-run-gitk) + (?p "Git Subcommand (in pwd)" magit-git-command) + (?a "Gitk --all" magit-run-gitk-all) + (?s "Shell command (in topdir)" magit-shell-command-topdir) + (?b "Gitk --branches" magit-run-gitk-branches) + (?S "Shell command (in pwd)" magit-shell-command) + (?g "Git Gui" magit-run-git-gui)) + :default-action 'magit-git-command + :max-action-columns 2) + +;;;###autoload +(defun magit-git-command (command) + "Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. \"git \" is +used as initial input, but can be deleted to run another command. + +With a prefix argument COMMAND is run in the top-level directory +of the current working tree, otherwise in `default-directory'." + (interactive (list (magit-read-shell-command nil "git "))) + (magit--shell-command command)) + +;;;###autoload +(defun magit-git-command-topdir (command) + "Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. \"git \" is +used as initial input, but can be deleted to run another command. + +COMMAND is run in the top-level directory of the current +working tree." + (interactive (list (magit-read-shell-command t "git "))) + (magit--shell-command command (magit-toplevel))) + +;;;###autoload +(defun magit-shell-command (command) + "Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. With a +prefix argument COMMAND is run in the top-level directory of +the current working tree, otherwise in `default-directory'." + (interactive (list (magit-read-shell-command))) + (magit--shell-command command)) + +;;;###autoload +(defun magit-shell-command-topdir (command) + "Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. COMMAND +is run in the top-level directory of the current working tree." + (interactive (list (magit-read-shell-command t))) + (magit--shell-command command (magit-toplevel))) + +(defun magit--shell-command (command &optional directory) + (let ((default-directory (or directory default-directory)) + (process-environment process-environment)) + (push "GIT_PAGER=cat" process-environment) + (magit-start-process shell-file-name nil + shell-command-switch command)) + (magit-process-buffer)) + +(defun magit-read-shell-command (&optional toplevel initial-input) + (let ((dir (abbreviate-file-name + (if (or toplevel current-prefix-arg) + (or (magit-toplevel) + (magit--not-inside-repository-error)) + default-directory)))) + (read-shell-command (if magit-shell-command-verbose-prompt + (format "Async shell command in %s: " dir) + "Async shell command: ") + initial-input 'magit-git-command-history))) + +;;; Font-Lock Keywords + +(defconst magit-font-lock-keywords + (eval-when-compile + `((,(concat "(\\(magit-define-section-jumper\\)\\_>" + "[ \t'\(]*" + "\\(\\(?:\\sw\\|\\s_\\)+\\)?") + (1 'font-lock-keyword-face) + (2 'font-lock-function-name-face nil t)) + (,(concat "(" (regexp-opt '("magit-insert-section" + "magit-section-case" + "magit-bind-match-strings" + "magit-with-temp-index" + "magit-with-blob" + "magit-with-toplevel") t) + "\\_>") + . 1)))) + +(font-lock-add-keywords 'emacs-lisp-mode magit-font-lock-keywords) + +;;; Version + +(defvar magit-version 'undefined + "The version of Magit that you're using. +Use the function by the same name instead of this variable.") + +;;;###autoload +(defun magit-version (&optional print-dest) + "Return the version of Magit currently in use. +If optional argument PRINT-DEST is non-nil, output +stream (interactively, the echo area, or the current buffer with +a prefix argument), also print the used versions of Magit, Git, +and Emacs to it." + (interactive (list (if current-prefix-arg (current-buffer) t))) + (let ((magit-git-global-arguments nil) + (toplib (or load-file-name buffer-file-name)) + debug) + (unless (and toplib + (equal (file-name-nondirectory toplib) "magit.el")) + (setq toplib (locate-library "magit.el"))) + (setq toplib (and toplib (file-chase-links toplib))) + (push toplib debug) + (when toplib + (let* ((topdir (file-name-directory toplib)) + (gitdir (expand-file-name + ".git" (file-name-directory + (directory-file-name topdir)))) + (static (locate-library "magit-version.el" nil (list topdir))) + (static (and static (file-chase-links static)))) + (or (progn + (push 'repo debug) + (when (and (file-exists-p gitdir) + ;; It is a repo, but is it the Magit repo? + (file-exists-p + (expand-file-name "../lisp/magit.el" gitdir))) + (push t debug) + ;; Inside the repo the version file should only exist + ;; while running make. + (when (and static (not noninteractive)) + (ignore-errors (delete-file static))) + (setq magit-version + (let ((default-directory topdir)) + (magit-git-string "describe" "--tags" "--dirty"))))) + (progn + (push 'static debug) + (when (and static (file-exists-p static)) + (push t debug) + (load-file static) + magit-version)) + (when (featurep 'package) + (push 'elpa debug) + (ignore-errors + (--when-let (assq 'magit package-alist) + (push t debug) + (setq magit-version + (and (fboundp 'package-desc-version) + (package-version-join + (package-desc-version (cadr it)))))))) + (progn + (push 'dirname debug) + (let ((dirname (file-name-nondirectory + (directory-file-name topdir)))) + (when (string-match "\\`magit-\\([0-9]\\{8\\}\\.[0-9]*\\)" + dirname) + (setq magit-version (match-string 1 dirname)))))))) + (if (stringp magit-version) + (when print-dest + (princ (format "Magit %s, Git %s, Emacs %s, %s" + (or magit-version "(unknown)") + (or (let ((magit-git-debug + (lambda (err) + (display-warning '(magit git) + err :error)))) + (magit-git-version t)) + "(unknown)") + emacs-version + system-type) + print-dest)) + (setq debug (reverse debug)) + (setq magit-version 'error) + (when magit-version + (push magit-version debug)) + (unless (equal (getenv "TRAVIS") "true") + ;; The repository is a sparse clone. + (message "Cannot determine Magit's version %S" debug))) + magit-version)) + +;;; Debugging Tools + +(defun magit-debug-git-executable () + "Display a buffer with information about `magit-git-executable'. +See info node `(magit)Debugging Tools' for more information." + (interactive) + (with-current-buffer (get-buffer-create "*magit-git-debug*") + (pop-to-buffer (current-buffer)) + (erase-buffer) + (insert (concat + (format "magit-git-executable: %S" magit-git-executable) + (and (not (file-name-absolute-p magit-git-executable)) + (format " [%S]" (executable-find magit-git-executable))) + (format " (%s)\n" + (let* ((errmsg nil) + (magit-git-debug (lambda (err) (setq errmsg err)))) + (or (magit-git-version t) errmsg))))) + (insert (format "exec-path: %S\n" exec-path)) + (--when-let (cl-set-difference + (-filter #'file-exists-p (remq nil (parse-colon-path + (getenv "PATH")))) + (-filter #'file-exists-p (remq nil exec-path)) + :test #'file-equal-p) + (insert (format " entries in PATH, but not in exec-path: %S\n" it))) + (dolist (execdir exec-path) + (insert (format " %s (%s)\n" execdir (car (file-attributes execdir)))) + (when (file-directory-p execdir) + (dolist (exec (directory-files + execdir t (concat + "\\`git" (regexp-opt exec-suffixes) "\\'"))) + (insert (format " %s (%s)\n" exec + (let* ((magit-git-executable exec) + (errmsg nil) + (magit-git-debug (lambda (err) (setq errmsg err)))) + (or (magit-git-version t) errmsg))))))))) + +;;; Startup Asserts + +(defun magit-startup-asserts () + (when-let ((val (getenv "GIT_DIR"))) + (setenv "GIT_DIR") + (message "Magit unset $GIT_DIR (was %S). See \ +https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike" val)) + (when-let ((val (getenv "GIT_WORK_TREE"))) + (setenv "GIT_WORK_TREE") + (message "Magit unset $GIT_WORK_TREE (was %S). See \ +https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike" val)) + (let ((version (magit-git-version))) + (when (and version + (version< version magit--minimal-git) + (not (equal (getenv "TRAVIS") "true"))) + (display-warning 'magit (format "\ +Magit requires Git >= %s, you are using %s. + +If this comes as a surprise to you, because you do actually have +a newer version installed, then that probably means that the +older version happens to appear earlier on the `$PATH'. If you +always start Emacs from a shell, then that can be fixed in the +shell's init file. If you start Emacs by clicking on an icon, +or using some sort of application launcher, then you probably +have to adjust the environment as seen by graphical interface. +For X11 something like ~/.xinitrc should work. + +If you use Tramp to work inside remote Git repositories, then you +have to make sure a suitable Git is used on the remote machines +too.\n" magit--minimal-git version) :error))) + (when (version< emacs-version magit--minimal-emacs) + (display-warning 'magit (format "\ +Magit requires Emacs >= %s, you are using %s. + +If this comes as a surprise to you, because you do actually have +a newer version installed, then that probably means that the +older version happens to appear earlier on the `$PATH'. If you +always start Emacs from a shell, then that can be fixed in the +shell's init file. If you start Emacs by clicking on an icon, +or using some sort of application launcher, then you probably +have to adjust the environment as seen by graphical interface. +For X11 something like ~/.xinitrc should work.\n" + magit--minimal-emacs emacs-version) + :error))) + +;;; Loading Libraries + +(provide 'magit) + +(cl-eval-when (load eval) + (require 'magit-status) + (require 'magit-refs) + (require 'magit-files) + (require 'magit-collab) + (require 'magit-reset) + (require 'magit-branch) + (require 'magit-merge) + (require 'magit-tag) + (require 'magit-worktree) + (require 'magit-notes) + (require 'magit-sequence) + (require 'magit-commit) + (require 'magit-remote) + (require 'magit-clone) + (require 'magit-fetch) + (require 'magit-pull) + (require 'magit-push) + (require 'magit-bisect) + (require 'magit-stash) + (require 'magit-blame) + (require 'magit-obsolete) + (require 'magit-submodule) + (unless (load "magit-autoloads" t t) + (require 'magit-subtree) + (require 'magit-ediff) + (require 'magit-extras) + (require 'git-rebase) + (require 'magit-imenu) + (require 'magit-bookmark))) + +(eval-after-load 'bookmark + '(require 'magit-bookmark)) + +(if after-init-time + (progn (magit-startup-asserts) + (magit-version)) + (add-hook 'after-init-hook #'magit-startup-asserts t) + (add-hook 'after-init-hook #'magit-version t)) + +;;; magit.el ends here diff --git a/elpa/magit-20181113.1837/magit.info b/elpa/magit-20181113.1837/magit.info new file mode 100644 index 00000000..64e27c03 --- /dev/null +++ b/elpa/magit-20181113.1837/magit.info @@ -0,0 +1,187 @@ +This is magit.info, produced by makeinfo version 6.5 from magit.texi. + + Copyright (C) 2015-2018 Jonas Bernoulli + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document 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. + +INFO-DIR-SECTION Emacs +START-INFO-DIR-ENTRY +* Magit: (magit). Using Git from Emacs with Magit. +END-INFO-DIR-ENTRY + + +Indirect: +magit.info-1: 754 +magit.info-2: 307175 + +Tag Table: +(Indirect) +Node: Top754 +Node: Introduction6307 +Node: Installation11030 +Node: Installing from Melpa11360 +Node: Installing from the Git Repository12433 +Node: Post-Installation Tasks14979 +Node: Getting Started16264 +Node: Interface Concepts21611 +Node: Modes and Buffers21942 +Node: Switching Buffers23691 +Node: Naming Buffers28234 +Node: Quitting Windows31541 +Node: Automatic Refreshing of Magit Buffers33173 +Node: Automatic Saving of File-Visiting Buffers35941 +Node: Automatic Reverting of File-Visiting Buffers37126 +Node: Risk of Reverting Automatically42122 +Node: Sections44505 +Node: Section Movement45446 +Node: Section Visibility49543 +Node: Section Hooks54402 +Node: Section Types and Values56809 +Node: Section Options58112 +Node: Popup Buffers and Prefix Commands58584 +Node: Completion Confirmation and the Selection60965 +Node: Action Confirmation61402 +Node: Completion and Confirmation68748 +Node: The Selection71934 +Node: The hunk-internal region74833 +Node: Support for Completion Frameworks75922 +Node: Additional Completion Options80738 +Node: Running Git81337 +Node: Viewing Git Output81610 +Node: Git Process Status82743 +Node: Running Git Manually83708 +Node: Git Executable86110 +Node: Global Git Arguments88392 +Node: Inspecting89198 +Node: Status Buffer90345 +Node: Status Sections93109 +Node: Status Header Sections97912 +Node: Status Module Sections100542 +Node: Status Options103047 +Node: Repository List104801 +Node: Logging106959 +Node: Refreshing Logs109412 +Node: Log Buffer110797 +Node: Log Margin114592 +Node: Select from Log117232 +Node: Reflog119336 +Node: Cherries120868 +Node: Diffing122595 +Node: Refreshing Diffs125548 +Node: Diff Buffer129039 +Node: Diff Options133623 +Node: Revision Buffer137899 +Node: Ediffing140833 +Node: References Buffer144429 +Node: References Sections154193 +Node: Bisecting155054 +Node: Visiting Blobs156792 +Node: Blaming157302 +Node: Manipulating163113 +Node: Repository Setup163429 +Node: Staging and Unstaging164469 +Node: Staging from File-Visiting Buffers168550 +Node: Applying169718 +Node: Committing171611 +Node: Initiating a Commit172194 +Node: Editing Commit Messages175522 +Node: Branching185918 +Node: The Two Remotes186148 +Node: The Branch Popup188765 +Node: The Branch Config Popup205825 +Node: Auxiliary Branch Commands211766 +Node: Merging212871 +Node: Resolving Conflicts216802 +Node: Rebasing221803 +Node: Editing Rebase Sequences225967 +Node: Information About In-Progress Rebase228997 +Ref: Information About In-Progress Rebase-Footnote-1237746 +Node: Cherry Picking238342 +Node: Reverting242594 +Node: Resetting243968 +Node: Stashing245622 +Node: Transferring250145 +Node: Remotes250383 +Node: The Remote Popup250539 +Node: The Remote Config Popup254007 +Node: Fetching255663 +Node: Pulling257025 +Node: Pushing257868 +Node: Creating and Sending Patches262609 +Node: Applying Patches263446 +Node: Miscellaneous265032 +Node: Tagging265348 +Node: Notes266696 +Node: Submodules269007 +Node: Listing Submodules269221 +Node: Submodule Popup271145 +Node: Subtree273598 +Node: Worktree274838 +Node: Common Commands276048 +Node: Wip Modes277795 +Node: Wip Graph282728 +Node: Legacy Wip Modes285042 +Node: Minor Mode for Buffers Visiting Files287937 +Node: Minor Mode for Buffers Visiting Blobs293353 +Node: Customizing294166 +Node: Per-Repository Configuration295834 +Node: Essential Settings297483 +Node: Safety297807 +Node: Performance299572 +Node: Microsoft Windows Performance307175 +Node: MacOS Performance308366 +Ref: MacOS Performance-Footnote-1309602 +Ref: MacOS Performance-Footnote-2309684 +Ref: MacOS Performance-Footnote-3309744 +Node: Plumbing309910 +Node: Calling Git310733 +Node: Getting a Value from Git312258 +Node: Calling Git for Effect315344 +Node: Section Plumbing321864 +Node: Creating Sections322092 +Node: Section Selection325992 +Node: Matching Sections327791 +Node: Refreshing Buffers333764 +Node: Conventions336906 +Node: Theming Faces337098 +Node: FAQ345213 +Node: FAQ - How to ...?345655 +Node: How to show git's output?346015 +Node: How to install the gitman info manual?346769 +Node: How to show diffs for gpg-encrypted files?347739 +Node: How does branching and pushing work?348335 +Node: Can Magit be used as ediff-version-control-package?348698 +Node: FAQ - Issues and Errors350687 +Node: Magit is slow351619 +Node: I changed several thousand files at once and now Magit is unusable351833 +Node: I am having problems committing352562 +Node: I am using MS Windows and cannot push with Magit353043 +Node: I am using OS X and SOMETHING works in shell but not in Magit353660 +Node: Diffs contain control sequences354466 +Node: Expanding a file to show the diff causes it to disappear355579 +Node: Point is wrong in the COMMIT_EDITMSG buffer356130 +Node: The mode-line information isn't always up-to-date357176 +Node: A branch and tag sharing the same name breaks SOMETHING358258 +Node: My Git hooks work on the command-line but not inside Magit359146 +Node: git-commit-mode isn't used when committing from the command-line359983 +Node: Point ends up inside invisible text when jumping to a file-visiting buffer362250 +Node: Debugging Tools363048 +Node: Keystroke Index364935 +Node: Command Index396948 +Node: Function Index431821 +Node: Variable Index447202 + +End Tag Table + + +Local Variables: +coding: utf-8 +End: diff --git a/elpa/magit-20181113.1837/magit.info-1 b/elpa/magit-20181113.1837/magit.info-1 new file mode 100644 index 00000000..bda4ef17 --- /dev/null +++ b/elpa/magit-20181113.1837/magit.info-1 @@ -0,0 +1,7962 @@ +This is magit.info, produced by makeinfo version 6.5 from magit.texi. + + Copyright (C) 2015-2018 Jonas Bernoulli + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document 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. + +INFO-DIR-SECTION Emacs +START-INFO-DIR-ENTRY +* Magit: (magit). Using Git from Emacs with Magit. +END-INFO-DIR-ENTRY + + +File: magit.info, Node: Top, Next: Introduction, Up: (dir) + +Magit User Manual +***************** + +Magit is an interface to the version control system Git, implemented as +an Emacs package. Magit aspires to be a complete Git porcelain. While +we cannot (yet) claim that Magit wraps and improves upon each and every +Git command, it is complete enough to allow even experienced Git users +to perform almost all of their daily version control tasks directly from +within Emacs. While many fine Git clients exist, only Magit and Git +itself deserve to be called porcelains. + +This manual is for Magit version 2.90.0 (v2.90.0-4-g13b32ae1c+1). + + Copyright (C) 2015-2018 Jonas Bernoulli + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document 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. + +* Menu: + +* Introduction:: +* Installation:: +* Getting Started:: +* Interface Concepts:: +* Inspecting:: +* Manipulating:: +* Transferring:: +* Miscellaneous:: +* Customizing:: +* Plumbing:: +* FAQ:: +* Debugging Tools:: +* Keystroke Index:: +* Command Index:: +* Function Index:: +* Variable Index:: + +— The Detailed Node Listing — + +Installation + +* Installing from Melpa:: +* Installing from the Git Repository:: +* Post-Installation Tasks:: + +Interface Concepts + +* Modes and Buffers:: +* Sections:: +* Popup Buffers and Prefix Commands:: +* Completion, Confirmation and the Selection: Completion Confirmation and the Selection. +* Running Git:: + +Modes and Buffers + +* Switching Buffers:: +* Naming Buffers:: +* Quitting Windows:: +* Automatic Refreshing of Magit Buffers:: +* Automatic Saving of File-Visiting Buffers:: +* Automatic Reverting of File-Visiting Buffers:: + + +Sections + +* Section Movement:: +* Section Visibility:: +* Section Hooks:: +* Section Types and Values:: +* Section Options:: + + +Completion, Confirmation and the Selection + +* Action Confirmation:: +* Completion and Confirmation:: +* The Selection:: +* The hunk-internal region:: +* Support for Completion Frameworks:: +* Additional Completion Options:: + + +Running Git + +* Viewing Git Output:: +* Git Process Status:: +* Running Git Manually:: +* Git Executable:: +* Global Git Arguments:: + + +Inspecting + +* Status Buffer:: +* Repository List:: +* Logging:: +* Diffing:: +* Ediffing:: +* References Buffer:: +* Bisecting:: +* Visiting Blobs:: +* Blaming:: + +Status Buffer + +* Status Sections:: +* Status Header Sections:: +* Status Module Sections:: +* Status Options:: + + +Logging + +* Refreshing Logs:: +* Log Buffer:: +* Log Margin:: +* Select from Log:: +* Reflog:: +* Cherries:: + + +Diffing + +* Refreshing Diffs:: +* Diff Buffer:: +* Diff Options:: +* Revision Buffer:: + + +References Buffer + +* References Sections:: + + +Manipulating + +* Repository Setup:: +* Staging and Unstaging:: +* Applying:: +* Committing:: +* Branching:: +* Merging:: +* Resolving Conflicts:: +* Rebasing:: +* Cherry Picking:: +* Resetting:: +* Stashing:: + +Staging and Unstaging + +* Staging from File-Visiting Buffers:: + + +Committing + +* Initiating a Commit:: +* Editing Commit Messages:: + + +Branching + +* The Two Remotes:: +* The Branch Popup:: +* The Branch Config Popup:: +* Auxiliary Branch Commands:: + + +Rebasing + +* Editing Rebase Sequences:: +* Information About In-Progress Rebase:: + + +Cherry Picking + +* Reverting:: + + +Transferring + +* Remotes:: +* Fetching:: +* Pulling:: +* Pushing:: +* Creating and Sending Patches:: +* Applying Patches:: + +Remotes + +* The Remote Popup:: +* The Remote Config Popup:: + + +Miscellaneous + +* Tagging:: +* Notes:: +* Submodules:: +* Subtree:: +* Worktree:: +* Common Commands:: +* Wip Modes:: +* Minor Mode for Buffers Visiting Files:: +* Minor Mode for Buffers Visiting Blobs:: + +Submodules + +* Listing Submodules:: +* Submodule Popup:: + + +Wip Modes + +* Wip Graph:: +* Legacy Wip Modes:: + + +Customizing + +* Per-Repository Configuration:: +* Essential Settings:: + +Essential Settings + +* Safety:: +* Performance:: + + +Plumbing + +* Calling Git:: +* Section Plumbing:: +* Refreshing Buffers:: +* Conventions:: + +Calling Git + +* Getting a Value from Git:: +* Calling Git for Effect:: + + +Section Plumbing + +* Creating Sections:: +* Section Selection:: +* Matching Sections:: + + +Conventions + +* Theming Faces:: + + +FAQ + +* FAQ - How to ...?:: +* FAQ - Issues and Errors:: + +FAQ - How to ...? + +* How to show git's output?:: +* How to install the gitman info manual?:: +* How to show diffs for gpg-encrypted files?:: +* How does branching and pushing work?:: +* Can Magit be used as ediff-version-control-package?:: + + +FAQ - Issues and Errors + +* Magit is slow:: +* I changed several thousand files at once and now Magit is unusable:: +* I am having problems committing:: +* I am using MS Windows and cannot push with Magit:: +* I am using OS X and SOMETHING works in shell, but not in Magit: I am using OS X and SOMETHING works in shell but not in Magit. +* Diffs contain control sequences:: +* Expanding a file to show the diff causes it to disappear:: +* Point is wrong in the COMMIT_EDITMSG buffer:: +* The mode-line information isn't always up-to-date:: +* A branch and tag sharing the same name breaks SOMETHING:: +* My Git hooks work on the command-line but not inside Magit:: +* git-commit-mode isn't used when committing from the command-line:: +* Point ends up inside invisible text when jumping to a file-visiting buffer:: + + + + +File: magit.info, Node: Introduction, Next: Installation, Prev: Top, Up: Top + +1 Introduction +************** + +Magit is an interface to the version control system Git, implemented as +an Emacs package. Magit aspires to be a complete Git porcelain. While +we cannot (yet) claim that Magit wraps and improves upon each and every +Git command, it is complete enough to allow even experienced Git users +to perform almost all of their daily version control tasks directly from +within Emacs. While many fine Git clients exist, only Magit and Git +itself deserve to be called porcelains. + + Staging and otherwise applying changes is one of the most important +features in a Git porcelain and here Magit outshines anything else, +including Git itself. Git’s own staging interface (‘git add --patch’) +is so cumbersome that many users only use it in exceptional cases. In +Magit staging a hunk or even just part of a hunk is as trivial as +staging all changes made to a file. + + The most visible part of Magit’s interface is the status buffer, +which displays information about the current repository. Its content is +created by running several Git commands and making their output +actionable. Among other things, it displays information about the +current branch, lists unpulled and unpushed changes and contains +sections displaying the staged and unstaged changes. That might sound +noisy, but, since sections are collapsible, it’s not. + + To stage or unstage a change one places the cursor on the change and +then types ‘s’ or ‘u’. The change can be a file or a hunk, or when the +region is active (i.e. when there is a selection) several files or +hunks, or even just part of a hunk. The change or changes that these +commands - and many others - would act on are highlighted. + + Magit also implements several other "apply variants" in addition to +staging and unstaging. One can discard or reverse a change, or apply it +to the working tree. Git’s own porcelain only supports this for staging +and unstaging and you would have to do something like ‘git diff ... | +??? | git apply ...’ to discard, revert, or apply a single hunk on the +command line. In fact that’s exactly what Magit does internally (which +is what lead to the term "apply variants"). + + Magit isn’t just for Git experts, but it does assume some prior +experience with Git as well as Emacs. That being said, many users have +reported that using Magit was what finally taught them what Git is +capable of and how to use it to its fullest. Other users wished they +had switched to Emacs sooner so that they would have gotten their hands +on Magit earlier. + + While one has to know the basic features of Emacs to be able to make +full use of Magit, acquiring just enough Emacs skills doesn’t take long +and is worth it, even for users who prefer other editors. Vim users are +advised to give Evil (https://bitbucket.org/lyro/evil/wiki/Home), the +"Extensible VI Layer for Emacs", and Spacemacs +(https://github.com/syl20bnr/spacemacs), an "Emacs starter-kit focused +on Evil" a try. + + Magit provides a consistent and efficient Git porcelain. After a +short learning period, you will be able to perform most of your daily +version control tasks faster than you would on the command line. You +will likely also start using features that seemed too daunting in the +past. + + Magit fully embraces Git. It exposes many advanced features using a +simple but flexible interface instead of only wrapping the trivial ones +like many GUI clients do. Of course Magit supports logging, cloning, +pushing, and other commands that usually don’t fail in spectacular ways; +but it also supports tasks that often cannot be completed in a single +step. Magit fully supports tasks such as merging, rebasing, +cherry-picking, reverting, and blaming by not only providing a command +to initiate these tasks but also by displaying context sensitive +information along the way and providing commands that are useful for +resolving conflicts and resuming the sequence after doing so. + + Magit wraps and in many cases improves upon at least the following +Git porcelain commands: ‘add’, ‘am’, ‘bisect’, ‘blame’, ‘branch’, +‘checkout’, ‘cherry’, ‘cherry-pick’, ‘clean’, ‘clone’, ‘commit’, +‘config’, ‘describe’, ‘diff’, ‘fetch’, ‘format-patch’, ‘init’, ‘log’, +‘merge’, ‘merge-tree’, ‘mv’, ‘notes’, ‘pull’, ‘rebase’, ‘reflog’, +‘remote’, ‘request-pull’, ‘reset’, ‘revert’, ‘rm’, ‘show’, ‘stash’, +‘submodule’, ‘subtree’, ‘tag’, and ‘worktree.’ Many more Magit porcelain +commands are implemented on top of Git plumbing commands. + + +File: magit.info, Node: Installation, Next: Getting Started, Prev: Introduction, Up: Top + +2 Installation +************** + +Magit can be installed using Emacs’ package manager or manually from its +development repository. + +* Menu: + +* Installing from Melpa:: +* Installing from the Git Repository:: +* Post-Installation Tasks:: + + +File: magit.info, Node: Installing from Melpa, Next: Installing from the Git Repository, Up: Installation + +2.1 Installing from Melpa +========================= + +Magit is available from Melpa and Melpa-Stable. If you haven’t used +Emacs’ package manager before, then it is high time you familiarize +yourself with it by reading the documentation in the Emacs manual, see +*note (emacs)Packages::. Then add one of the archives to +‘package-archives’: + + • To use Melpa: + + (require 'package) + (add-to-list 'package-archives + '("melpa" . "http://melpa.org/packages/") t) + + • To use Melpa-Stable: + + (require 'package) + (add-to-list 'package-archives + '("melpa-stable" . "http://stable.melpa.org/packages/") t) + + Once you have added your preferred archive, you need to update the +local package list using: + + M-x package-refresh-contents RET + + Once you have done that, you can install Magit and its dependencies +using: + + M-x package-install RET magit RET + + Now see *note Post-Installation Tasks::. + + +File: magit.info, Node: Installing from the Git Repository, Next: Post-Installation Tasks, Prev: Installing from Melpa, Up: Installation + +2.2 Installing from the Git Repository +====================================== + +Magit depends on the ‘dash’, ‘ghub’, ‘graphql’, ‘magit-popup’, ‘treepy’ +and ‘with-editor’ libraries which are available from Melpa and +Melpa-Stable. Install them using ‘M-x package-install RET +RET’. Of course you may also install them manually from their +repository. + + Then clone the Magit repository: + + $ git clone https://github.com/magit/magit.git ~/.emacs.d/site-lisp/magit + $ cd ~/.emacs.d/site-lisp/magit + + Then compile the libraries and generate the info manuals: + + $ make + + If you haven’t installed ‘dash’, ‘ghub’, ‘graphql’, ‘magit-popup’, +‘treepy’ and ‘with-editor’ from Melpa or at +‘/path/to/magit/../’, then you have to tell ‘make’ where to +find them. To do so create the file ‘/path/to/magit/config.mk’ with the +following content before running ‘make’: + + LOAD_PATH = -L /path/to/magit/lisp + LOAD_PATH += -L /path/to/dash + LOAD_PATH += -L /path/to/ghub + LOAD_PATH += -L /path/to/graphql + LOAD_PATH += -L /path/to/magit-popup + LOAD_PATH += -L /path/to/treepy + LOAD_PATH += -L /path/to/with-editor + + Finally add this to your init file: + + (add-to-list 'load-path "~/.emacs.d/site-lisp/magit/lisp") + (require 'magit) + + (with-eval-after-load 'info + (info-initialize) + (add-to-list 'Info-directory-list + "~/.emacs.d/site-lisp/magit/Documentation/")) + + Note that you have to add the ‘lisp’ subdirectory to the ‘load-path’, +not the top-level of the repository, and that elements of ‘load-path’ +should not end with a slash, while those of ‘Info-directory-list’ +should. + + Instead of requiring the feature ‘magit’, you could load just the +autoload definitions, by loading the file ‘magit-autoloads.el’. + + (load "/path/to/magit/lisp/magit-autoloads") + + Instead of running Magit directly from the repository by adding that +to the ‘load-path’, you might want to instead install it in some other +directory using ‘sudo make install’ and setting ‘load-path’ accordingly. + + To update Magit use: + + $ git pull + $ make + + At times it might be necessary to run ‘make clean all’ instead. + + To view all available targets use ‘make help’. + + Now see *note Post-Installation Tasks::. + + +File: magit.info, Node: Post-Installation Tasks, Prev: Installing from the Git Repository, Up: Installation + +2.3 Post-Installation Tasks +=========================== + +After installing Magit you should verify that you are indeed using the +Magit, Git, and Emacs releases you think you are using. It’s best to +restart Emacs before doing so, to make sure you are not using an +outdated value for ‘load-path’. + + M-x magit-version RET + + should display something like + + Magit 2.8.0, Git 2.10.2, Emacs 25.1.1, gnu/linux + + Then you might also want to read about options that many users likely +want to customize. See *note Essential Settings::. + + To be able to follow cross references to Git manpages found in this +manual, you might also have to manually install the ‘gitman’ info +manual, or advice ‘Info-follow-nearest-node’ to instead open the actual +manpage. See *note How to install the gitman info manual?::. + + If you are completely new to Magit then see *note Getting Started::. + + If you run into problems, then please see the *note FAQ::. Also see +the *note Debugging Tools::. + + And last but not least please consider making a donation, to ensure +that I can keep working on Magit. See . +for various donation options. + + +File: magit.info, Node: Getting Started, Next: Interface Concepts, Prev: Installation, Up: Top + +3 Getting Started +***************** + +This short tutorial describes the most essential features that many +Magitians use on a daily basis. It only scratches the surface but +should be enough to get you started. + + IMPORTANT: It is safest if you clone some repository just for this +tutorial. Alternatively you can use an existing local repository, but +if you do that, then you should commit all uncommitted changes before +proceeding. + + To display information about the current Git repository, type ‘M-x +magit-status RET’. You will be using this command a lot, and should +therefore give it a global key binding. This is what we recommend: + + (global-set-key (kbd "C-x g") 'magit-status) + + Most Magit commands are commonly invoked from the status buffer. It +can be considered the primary interface for interacting with Git using +Magit. Many other Magit buffers may exist at a given time, but they are +often created from this buffer. + + Depending on what state your repository is in, this buffer may +contain sections titled "Staged changes", "Unstaged changes", "Unmerged +into origin/master", "Unpushed to origin/master", and many others. + + Since we are starting from a safe state, which you can easily return +to (by doing a ‘git reset --hard PRE-MAGIT-STATE’), there currently are +not staged or unstaged changes. Edit some files and save the changes. +Then go back to the status buffer, while at the same time refreshing it, +by typing ‘C-x g’. (When the status buffer, or any Magit buffer for +that matter, is the current buffer, then you can also use just ‘g’ to +refresh it). + + Move between sections using ‘p’ and ‘n’. Note that the bodies of +some sections are hidden. Type ‘TAB’ to expand or collapse the section +at point. You can also use ‘C-tab’ to cycle the visibility of the +current section and its children. Move to a file section inside the +section named "Unstaged changes" and type ‘s’ to stage the changes you +have made to that file. That file now appears under "Staged changes". + + Magit can stage and unstage individual hunks, not just complete +files. Move to the file you have just staged, expand it using ‘TAB’, +move to one of the hunks using ‘n’, and unstage just that by typing ‘u’. +Note how the staging (‘s’) and unstaging (‘u’) commands operate on the +change at point. Many other commands behave the same way. + + You can also un-/stage just part of a hunk. Inside the body of a +hunk section (move there using ‘C-n’), set the mark using ‘C-SPC’ and +move down until some added and/or removed lines fall inside the region +but not all of them. Again type ‘s’ to stage. + + It is also possible to un-/stage multiple files at once. Move to a +file section, type ‘C-SPC’, move to the next file using ‘n’, and then +‘s’ to stage both files. Note that both the mark and point have to be +on the headings of sibling sections for this to work. If the region +looks like it does in other buffers, then it doesn’t select Magit +sections that can be acted on as a unit. + + And then of course you want to commit your changes. Type ‘c’. This +shows the committing popup buffer featuring various commit variants and +arguments that can be passed to ‘git commit’. Do not worry about those +for now. We want to create a "normal" commit, which is done by typing +‘c’ again. + + Now two new buffers appear. One is for writing the commit message, +the other shows a diff with the changes that you are about to committed. +Write a message and then type ‘C-c C-c’ to actually create the commit. + + You probably don’t want to push the commit you just created because +you just committed some random changes, but if that is not the case you +could push it by typing ‘P’ to bring up the push popup and then ‘p’ to +push to a branch with the same name as the local branch onto the remote +configured as the push-remote. (If the push-remote is not configured +yet, then you would first be prompted for the remote to push to.) + + So far we have mentioned the commit, push, and log popups. These are +probably among the popups you will be using the most, but many others +exist. To show a popup that lists all other popups (as well as the +various apply commands and some other fundamental commands), type ‘h’. +Try a few. + + The key bindings in that popup correspond to the bindings in Magit +buffers, including but not limited to the status buffer. So you could +type ‘h d’ to bring up the diff popup, but once you remember that "d" +stands for "diff", you would usually do so by just typing ‘d’. But the +"popup of popups" is useful even once you have memorized all the +bindings, as it can provide easy access to Magit commands from non-Magit +buffers. You should create a global key binding for this command too: + + (global-set-key (kbd "C-x M-g") 'magit-dispatch-popup) + + In the same vein, you might also want to enable +‘global-magit-file-mode’ to get some more Magit key bindings in regular +file-visiting buffers (see *note Minor Mode for Buffers Visiting +Files::). + + It is not necessary that you do so now, but if you stick with Magit, +then it is highly recommended that you read the next section too. + + +File: magit.info, Node: Interface Concepts, Next: Inspecting, Prev: Getting Started, Up: Top + +4 Interface Concepts +******************** + +* Menu: + +* Modes and Buffers:: +* Sections:: +* Popup Buffers and Prefix Commands:: +* Completion, Confirmation and the Selection: Completion Confirmation and the Selection. +* Running Git:: + + +File: magit.info, Node: Modes and Buffers, Next: Sections, Up: Interface Concepts + +4.1 Modes and Buffers +===================== + +Magit provides several major-modes. For each of these modes there +usually exists only one buffer per repository. Separate modes and thus +buffers exist for commits, diffs, logs, and some other things. + + Besides these special purpose buffers, there also exists an overview +buffer, called the *status buffer*. It’s usually from this buffer that +the user invokes Git commands, or creates or visits other buffers. + + In this manual we often speak about "Magit buffers". By that we mean +buffers whose major-modes derive from ‘magit-mode’. + +‘M-x magit-toggle-buffer-lock’ (‘magit-toggle-buffer-lock’) + + This command locks the current buffer to its value or if the buffer + is already locked, then it unlocks it. + + Locking a buffer to its value prevents it from being reused to + display another value. The name of a locked buffer contains its + value, which allows telling it apart from other locked buffers and + the unlocked buffer. + + Not all Magit buffers can be locked to their values; for example, + it wouldn’t make sense to lock a status buffer. + + There can only be a single unlocked buffer using a certain + major-mode per repository. So when a buffer is being unlocked and + another unlocked buffer already exists for that mode and + repository, then the former buffer is instead deleted and the + latter is displayed in its place. + +* Menu: + +* Switching Buffers:: +* Naming Buffers:: +* Quitting Windows:: +* Automatic Refreshing of Magit Buffers:: +* Automatic Saving of File-Visiting Buffers:: +* Automatic Reverting of File-Visiting Buffers:: + + +File: magit.info, Node: Switching Buffers, Next: Naming Buffers, Up: Modes and Buffers + +4.1.1 Switching Buffers +----------------------- + + -- Function: magit-display-buffer buffer + + This function is a wrapper around ‘display-buffer’ and is used to + display any Magit buffer. It displays BUFFER in some window and, + unlike ‘display-buffer’, also selects that window, provided + ‘magit-display-buffer-noselect’ is ‘nil’. It also runs the hooks + mentioned below. + + -- Variable: magit-display-buffer-noselect + + When this is non-nil, then ‘magit-display-buffer’ only displays the + buffer but forgoes also selecting the window. This variable should + not be set globally, it is only intended to be let-bound, by code + that automatically updates "the other window". This is used for + example when the revision buffer is updated when you move inside + the log buffer. + + -- User Option: magit-display-buffer-function + + The function specified here is called by ‘magit-display-buffer’ + with one argument, a buffer, to actually display that buffer. This + function should call ‘display-buffer’ with that buffer as first and + a list of display actions as second argument. + + Magit provides several functions, listed below, that are suitable + values for this option. If you want to use different rules, then a + good way of doing that is to start with a copy of one of these + functions and then adjust it to your needs. + + Instead of using a wrapper around ‘display-buffer’, that function + itself can be used here, in which case the display actions have to + be specified by adding them to ‘display-buffer-alist’ instead. + + To learn about display actions, see *note (elisp)Choosing a Window + for Display::. + + -- Function: magit-display-buffer-traditional buffer + + This function is the current default value of the option + ‘magit-display-buffer-function’. Before that option and this + function were added, the behavior was hard-coded in many places all + over the code base but now all the rules are contained in this one + function (except for the "noselect" special case mentioned above). + + -- Function: magit-display-buffer-same-window-except-diff-v1 + + This function displays most buffers in the currently selected + window. If a buffer’s mode derives from ‘magit-diff-mode’ or + ‘magit-process-mode’, it is displayed in another window. + + -- Function: magit-display-buffer-fullframe-status-v1 + + This function fills the entire frame when displaying a status + buffer. Otherwise, it behaves like + ‘magit-display-buffer-traditional’. + + -- Function: magit-display-buffer-fullframe-status-topleft-v1 + + This function fills the entire frame when displaying a status + buffer. It behaves like ‘magit-display-buffer-fullframe-status-v1’ + except that it displays buffers that derive from ‘magit-diff-mode’ + or ‘magit-process-mode’ to the top or left of the current buffer + rather than to the bottom or right. As a result, Magit buffers + tend to pop up on the same side as they would if + ‘magit-display-buffer-traditional’ were in use. + + -- Function: magit-display-buffer-fullcolumn-most-v1 + + This function displays most buffers so that they fill the entire + height of the frame. However, the buffer is displayed in another + window if (1) the buffer’s mode derives from ‘magit-process-mode’, + or (2) the buffer’s mode derives from ‘magit-diff-mode’, provided + that the mode of the current buffer derives from ‘magit-log-mode’ + or ‘magit-cherry-mode’. + + -- User Option: magit-pre-display-buffer-hook + + This hook is run by ‘magit-display-buffer’ before displaying the + buffer. + + -- Function: magit-save-window-configuration + + This function saves the current window configuration. Later when + the buffer is buried, it may be restored by + ‘magit-restore-window-configuration’. + + -- User Option: magit-post-display-buffer-hook + + This hook is run by ‘magit-display-buffer’ after displaying the + buffer. + + -- Function: magit-maybe-set-dedicated + + This function remembers if a new window had to be created to + display the buffer, or whether an existing window was reused. This + information is later used by ‘magit-mode-quit-window’, to determine + whether the window should be deleted when its last Magit buffer is + buried. + + +File: magit.info, Node: Naming Buffers, Next: Quitting Windows, Prev: Switching Buffers, Up: Modes and Buffers + +4.1.2 Naming Buffers +-------------------- + + -- User Option: magit-generate-buffer-name-function + + The function used to generate the names of Magit buffers. + + Such a function should take the options + ‘magit-uniquify-buffer-names’ as well as ‘magit-buffer-name-format’ + into account. If it doesn’t, then should be clearly stated in the + doc-string. And if it supports %-sequences beyond those mentioned + in the doc-string of the option ‘magit-buffer-name-format’, then + its own doc-string should describe the additions. + + -- Function: magit-generate-buffer-name-default-function mode + + This function returns a buffer name suitable for a buffer whose + major-mode is MODE and which shows information about the repository + in which ‘default-directory’ is located. + + This function uses ‘magit-buffer-name-format’ and supporting all of + the %-sequences mentioned the documentation of that option. It + also respects the option ‘magit-uniquify-buffer-names’. + + -- User Option: magit-buffer-name-format + + The format string used to name Magit buffers. + + At least the following %-sequences are supported: + + • ‘%m’ + + The name of the major-mode, but with the ‘-mode’ suffix + removed. + + • ‘%M’ + + Like ‘%m’ but abbreviate ‘magit-status-mode’ as ‘magit’. + + • ‘%v’ + + The value the buffer is locked to, in parentheses, or an empty + string if the buffer is not locked to a value. + + • ‘%V’ + + Like ‘%v’, but the string is prefixed with a space, unless it + is an empty string. + + • ‘%t’ + + The top-level directory of the working tree of the repository, + or if ‘magit-uniquify-buffer-names’ is non-nil an abbreviation + of that. + + • ‘%x’ + + If ‘magit-uniquify-buffer-names’ is nil "*", otherwise the + empty string. Due to limitations of the ‘uniquify’ package, + buffer names must end with the path. + + • ‘%T’ + + Obsolete, use "%t%x" instead. Like ‘%t’, but append an + asterisk if and only if ‘magit-uniquify-buffer-names’ is nil. + + The value should always contain ‘%m’ or ‘%M’, ‘%v’ or ‘%V’, and + ‘%t’ (or the obsolete ‘%T’). If ‘magit-uniquify-buffer-names’ is + non-nil, then the value must end with ‘%t’ or ‘%t%x’ (or the + obsolete ‘%T’). See issue #2841. + + -- User Option: magit-uniquify-buffer-names + + This option controls whether the names of Magit buffers are + uniquified. If the names are not being uniquified, then they + contain the full path of the top-level of the working tree of the + corresponding repository. If they are being uniquified, then they + end with the basename of the top-level, or if that would conflict + with the name used for other buffers, then the names of all these + buffers are adjusted until they no longer conflict. + + This is done using the ‘uniquify’ package; customize its options to + control how buffer names are uniquified. + + +File: magit.info, Node: Quitting Windows, Next: Automatic Refreshing of Magit Buffers, Prev: Naming Buffers, Up: Modes and Buffers + +4.1.3 Quitting Windows +---------------------- + +‘q’ (‘magit-mode-bury-buffer’) + + This command buries the current Magit buffer. With a prefix + argument, it instead kills the buffer. + + -- User Option: magit-bury-buffer-function + + The function used to actually bury or kill the current buffer. + + ‘magit-mode-bury-buffer’ calls this function with one argument. If + the argument is non-nil, then the function has to kill the current + buffer. Otherwise it has to bury it alive. The default value + currently is ‘magit-restore-window-configuration’. + + -- Function: magit-restore-window-configuration kill-buffer + + Bury or kill the current buffer using ‘quit-window’, which is + called with KILL-BUFFER as first and the selected window as second + argument. + + Then restore the window configuration that existed right before the + current buffer was displayed in the selected frame. Unfortunately + that also means that point gets adjusted in all the buffers, which + are being displayed in the selected frame. + + -- Function: magit-mode-quit-window kill-buffer + + Bury or kill the current buffer using ‘quit-window’, which is + called with KILL-BUFFER as first and the selected window as second + argument. + + Then, if the window was originally created to display a Magit + buffer and the buried buffer was the last remaining Magit buffer + that was ever displayed in the window, then that is deleted. + + +File: magit.info, Node: Automatic Refreshing of Magit Buffers, Next: Automatic Saving of File-Visiting Buffers, Prev: Quitting Windows, Up: Modes and Buffers + +4.1.4 Automatic Refreshing of Magit Buffers +------------------------------------------- + +After running a command which may change the state of the current +repository, the current Magit buffer and the corresponding status buffer +are refreshed. The status buffer may optionally be automatically +refreshed whenever a buffer is saved to a file inside the respective +repository. + + Automatically refreshing Magit buffers ensures that the displayed +information is up-to-date most of the time but can lead to a noticeable +delay in big repositories. Other Magit buffers are not refreshed to +keep the delay to a minimum and also because doing so can sometimes be +undesirable. + + Buffers can also be refreshed explicitly, which is useful in buffers +that weren’t current during the last refresh and after changes were made +to the repository outside of Magit. + +‘g’ (‘magit-refresh’) + + This command refreshes the current buffer if its major mode derives + from ‘magit-mode’ as well as the corresponding status buffer. + + If the option ‘magit-revert-buffers’ calls for it, then it also + reverts all unmodified buffers that visit files being tracked in + the current repository. + +‘G’ (‘magit-refresh-all’) + + This command refreshes all Magit buffers belonging to the current + repository and also reverts all unmodified buffers that visit files + being tracked in the current repository. + + The file-visiting buffers are always reverted, even if + ‘magit-revert-buffers’ is nil. + + -- User Option: magit-refresh-buffer-hook + + This hook is run in each Magit buffer that was refreshed during the + current refresh - normally the current buffer and the status + buffer. + + -- User Option: magit-refresh-status-buffer + + When this option is non-nil, then the status buffer is + automatically refreshed after running git for side-effects, in + addition to the current Magit buffer, which is always refreshed + automatically. + + Only set this to nil after exhausting all other options to improve + performance. + + -- Function: magit-after-save-refresh-status + + This function is intended to be added to ‘after-save-hook’. After + doing that the corresponding status buffer is refreshed whenever a + buffer is saved to a file inside a repository. + + Note that refreshing a Magit buffer is done by re-creating its + contents from scratch, which can be slow in large repositories. If + you are not satisfied with Magit’s performance, then you should + obviously not add this function to that hook. + + +File: magit.info, Node: Automatic Saving of File-Visiting Buffers, Next: Automatic Reverting of File-Visiting Buffers, Prev: Automatic Refreshing of Magit Buffers, Up: Modes and Buffers + +4.1.5 Automatic Saving of File-Visiting Buffers +----------------------------------------------- + +File-visiting buffers are by default saved at certain points in time. +This doesn’t guarantee that Magit buffers are always up-to-date, but, +provided one only edits files by editing them in Emacs and uses only +Magit to interact with Git, one can be fairly confident. When in doubt +or after outside changes, type ‘g’ (‘magit-refresh’) to save and refresh +explicitly. + + -- User Option: magit-save-repository-buffers + + This option controls whether file-visiting buffers are saved before + certain events. + + If this is non-nil then all modified file-visiting buffers + belonging to the current repository may be saved before running + commands, before creating new Magit buffers, and before explicitly + refreshing such buffers. If this is ‘dontask’ then this is done + without user intervention. If it is ‘t’ then the user has to + confirm each save. + + +File: magit.info, Node: Automatic Reverting of File-Visiting Buffers, Prev: Automatic Saving of File-Visiting Buffers, Up: Modes and Buffers + +4.1.6 Automatic Reverting of File-Visiting Buffers +-------------------------------------------------- + +By default Magit automatically reverts buffers that are visiting files +that are being tracked in a Git repository, after they have changed on +disk. When using Magit one often changes files on disk by running git, +i.e. "outside Emacs", making this a rather important feature. + + For example, if you discard a change in the status buffer, then that +is done by running ‘git apply --reverse ...’, and Emacs considers the +file to have "changed on disk". If Magit did not automatically revert +the buffer, then you would have to type ‘M-x revert-buffer RET RET’ in +the visiting buffer before you could continue making changes. + + -- User Option: magit-auto-revert-mode + + When this mode is enabled, then buffers that visit tracked files, + are automatically reverted after the visited files changed on disk. + + -- User Option: global-auto-revert-mode + + When this mode is enabled, then any file-visiting buffer is + automatically reverted after the visited file changed on disk. + + If you like buffers that visit tracked files to be automatically + reverted, then you might also like any buffer to be reverted, not + just those visiting tracked files. If that is the case, then + enable this mode _instead of_ ‘magit-auto-revert-mode’. + + -- User Option: magit-auto-revert-immediately + + This option controls whether Magit reverts buffers immediately. + + If this is non-nil and either ‘global-auto-revert-mode’ or + ‘magit-auto-revert-mode’ is enabled, then Magit immediately reverts + buffers by explicitly calling ‘auto-revert-buffers’ after running + git for side-effects. + + If ‘auto-revert-use-notify’ is non-nil (and file notifications are + actually supported), then ‘magit-auto-revert-immediately’ does not + have to be non-nil, because the reverts happen immediately anyway. + + If ‘magit-auto-revert-immediately’ and ‘auto-revert-use-notify’ are + both ‘nil’, then reverts happen after ‘auto-revert-interval’ + seconds of user inactivity. That is not desirable. + + -- User Option: auto-revert-use-notify + + This option controls whether file notification functions should be + used. Note that this variable unfortunately defaults to ‘t’ even + on systems on which file notifications cannot be used. + + -- User Option: magit-auto-revert-tracked-only + + This option controls whether ‘magit-auto-revert-mode’ only reverts + tracked files or all files that are located inside Git + repositories, including untracked files and files located inside + Git’s control directory. + + -- Command: auto-revert-mode + + The global mode ‘magit-auto-revert-mode’ works by turning on this + local mode in the appropriate buffers (but + ‘global-auto-revert-mode’ is implemented differently). You can + also turn it on or off manually, which might be necessary if Magit + does not notice that a previously untracked file now is being + tracked or vice-versa. + + -- User Option: auto-revert-stop-on-user-input + + This option controls whether the arrival of user input suspends the + automatic reverts for ‘auto-revert-interval’ seconds. + + -- User Option: auto-revert-interval + + This option controls for how many seconds Emacs waits before + resuming suspended reverts. + + -- User Option: auto-revert-buffer-list-filter + + This option specifies an additional filter used by + ‘auto-revert-buffers’ to determine whether a buffer should be + reverted or not. + + This option is provided by ‘magit’, which also redefines + ‘auto-revert-buffers’ to respect it. Magit users who do not turn + on the local mode ‘auto-revert-mode’ themselves, are best served by + setting the value to ‘magit-auto-revert-repository-buffers-p’. + + However the default is nil, to not disturb users who do use the + local mode directly. If you experience delays when running Magit + commands, then you should consider using one of the predicates + provided by Magit - especially if you also use Tramp. + + Users who do turn on ‘auto-revert-mode’ in buffers in which Magit + doesn’t do that for them, should likely not use any filter. Users + who turn on ‘global-auto-revert-mode’, do not have to worry about + this option, because it is disregarded if the global mode is + enabled. + + -- User Option: auto-revert-verbose + + This option controls whether Emacs reports when a buffer has been + reverted. + + The options with the ‘auto-revert-’ prefix are located in the Custom +group named ‘auto-revert’. The other, magit-specific, options are +located in the ‘magit’ group. + +* Menu: + +* Risk of Reverting Automatically:: + + +File: magit.info, Node: Risk of Reverting Automatically, Up: Automatic Reverting of File-Visiting Buffers + +Risk of Reverting Automatically +............................... + +For the vast majority users automatically reverting file-visiting +buffers after they have changed on disk is harmless. + + If a buffer is modified (i.e. it contains changes that haven’t been +saved yet), then Emacs would refuse to automatically revert it. If you +save a previously modified buffer, then that results in what is seen by +Git as an uncommitted change. Git would then refuse to carry out any +commands that would cause these changes to be lost. In other words, if +there is anything that could be lost, then either Git or Emacs would +refuse to discard the changes. + + However if you do use file-visiting buffers as a sort of ad hoc +"staging area", then the automatic reverts could potentially cause data +loss. So far I have only heard from one user who uses such a workflow. + + An example: You visit some file in a buffer, edit it, and save the +changes. Then, outside of Emacs (or at least not using Magit or by +saving the buffer) you change the file on disk again. At this point the +buffer is the only place where the intermediate version still exists. +You have saved the changes to disk, but that has since been overwritten. +Meanwhile Emacs considers the buffer to be unmodified (because you have +not made any changes to it since you last saved it to the visited file) +and therefore would not object to it being automatically reverted. At +this point an Auto-Revert mode would kick in. It would check whether +the buffer is modified and since that is not the case it would revert +it. The intermediate version would be lost. (Actually you could still +get it back using the ‘undo’ command.) + + If your workflow depends on Emacs preserving the intermediate version +in the buffer, then you have to disable all Auto-Revert modes. But +please consider that such a workflow would be dangerous even without +using an Auto-Revert mode, and should therefore be avoided. If Emacs +crashed or if you quit Emacs by mistake, then you would also lose the +buffer content. There would be no autosave file still containing the +intermediate version (because that was deleted when you saved the +buffer) and you would not be asked whether you want to save the buffer +(because it isn’t modified). + + +File: magit.info, Node: Sections, Next: Popup Buffers and Prefix Commands, Prev: Modes and Buffers, Up: Interface Concepts + +4.2 Sections +============ + +Magit buffers are organized into nested sections, which can be collapsed +and expanded, similar to how sections are handled in Org mode. Each +section also has a type, and some sections also have a value. For each +section type there can also be a local keymap, shared by all sections of +that type. + + Taking advantage of the section value and type, many commands operate +on the current section, or when the region is active and selects +sections of the same type, all of the selected sections. Commands that +only make sense for a particular section type (as opposed to just +behaving differently depending on the type) are usually bound in section +type keymaps. + +* Menu: + +* Section Movement:: +* Section Visibility:: +* Section Hooks:: +* Section Types and Values:: +* Section Options:: + + +File: magit.info, Node: Section Movement, Next: Section Visibility, Up: Sections + +4.2.1 Section Movement +---------------------- + +To move within a section use the usual keys (‘C-p’, ‘C-n’, ‘C-b’, ‘C-f’ +etc), whose global bindings are not shadowed. To move to another +section use the following commands. + +‘p’ (‘magit-section-backward’) + + When not at the beginning of a section, then move to the beginning + of the current section. At the beginning of a section, instead + move to the beginning of the previous visible section. + +‘n’ (‘magit-section-forward’) + + Move to the beginning of the next visible section. + +‘M-p’ (‘magit-section-backward-siblings’) + + Move to the beginning of the previous sibling section. If there is + no previous sibling section, then move to the parent section + instead. + +‘M-n’ (‘magit-section-forward-siblings’) + + Move to the beginning of the next sibling section. If there is no + next sibling section, then move to the parent section instead. + +‘^’ (‘magit-section-up’) + + Move to the beginning of the parent of the current section. + + The above commands all call the hook ‘magit-section-movement-hook’. +Any of the functions listed below can be used as members of this hook. + + -- Variable: magit-section-movement-hook + + This hook is run by all of the above movement commands, after + arriving at the destination. + + -- Function: magit-hunk-set-window-start + + This hook function ensures that the beginning of the current + section is visible, provided it is a ‘hunk’ section. Otherwise, it + does nothing. This function is a member of the hook’s default + value. + + -- Function: magit-section-set-window-start + + This hook function ensures that the beginning of the current + section is visible, regardless of the section’s type. If you add + this to ‘magit-section-movement-hook’, then you must remove the + hunk-only variant in turn. + + -- Function: magit-log-maybe-show-more-commits + + This hook function only has an effect in log buffers, and ‘point’ + is on the "show more" section. If that is the case, then it + doubles the number of commits that are being shown. This function + is a member of the hook’s default value. + + -- Function: magit-log-maybe-update-revision-buffer + + When moving inside a log buffer, then this function updates the + revision buffer, provided it is already being displayed in another + window of the same frame. This function is a member of the hook’s + default value. + + -- Function: magit-log-maybe-update-blob-buffer + + When moving inside a log buffer and another window of the same + frame displays a blob buffer, then this function instead displays + the blob buffer for the commit at point in that window. + + -- Function: magit-status-maybe-update-revision-buffer + + When moving inside a status buffer, then this function updates the + revision buffer, provided it is already being displayed in another + window of the same frame. + + -- Function: magit-status-maybe-update-blob-buffer + + When moving inside a status buffer and another window of the same + frame displays a blob buffer, then this function instead displays + the blob buffer for the commit at point in that window. + + -- User Option: magit-update-other-window-delay + + Delay before automatically updating the other window. + + When moving around in certain buffers, then certain other buffers, + which are being displayed in another window, may optionally be + updated to display information about the section at point. + + When holding down a key to move by more than just one section, then + that would update that buffer for each section on the way. To + prevent that, updating the revision buffer is delayed, and this + option controls for how long. For optimal experience you might + have to adjust this delay and/or the keyboard repeat rate and delay + of your graphical environment or operating system. + + +File: magit.info, Node: Section Visibility, Next: Section Hooks, Prev: Section Movement, Up: Sections + +4.2.2 Section Visibility +------------------------ + +Magit provides many commands for changing the visibility of sections, +but all you need to get started are the next two. + +‘TAB’ (‘magit-section-toggle’) + + Toggle the visibility of the body of the current section. + +‘C-’ (‘magit-section-cycle’) + + Cycle the visibility of current section and its children. + +‘M-’ (‘magit-section-cycle-diffs’) + + Cycle the visibility of diff-related sections in the current + buffer. + +‘S-’ (‘magit-section-cycle-global’) + + Cycle the visibility of all sections in the current buffer. + +‘1’ (‘magit-section-show-level-1’) +‘2’ (‘magit-section-show-level-2’) +‘3’ (‘magit-section-show-level-3’) +‘4’ (‘magit-section-show-level-4’) + + Show sections surrounding the current section up to level N. + +‘M-1’ (‘magit-section-show-level-1-all’) +‘M-2’ (‘magit-section-show-level-2-all’) +‘M-3’ (‘magit-section-show-level-3-all’) +‘M-4’ (‘magit-section-show-level-4-all’) + + Show all sections up to level N. + + Some functions, which are used to implement the above commands, are +also exposed as commands themselves. By default no keys are bound to +these commands, as they are generally perceived to be much less useful. +But your mileage may vary. + + -- Command: magit-section-show + + Show the body of the current section. + + -- Command: magit-section-hide + + Hide the body of the current section. + + -- Command: magit-section-show-headings + + Recursively show headings of children of the current section. Only + show the headings. Previously shown text-only bodies are hidden. + + -- Command: magit-section-show-children + + Recursively show the bodies of children of the current section. + With a prefix argument show children down to the level of the + current section, and hide deeper children. + + -- Command: magit-section-hide-children + + Recursively hide the bodies of children of the current section. + + -- Command: magit-section-toggle-children + + Toggle visibility of bodies of children of the current section. + + When a buffer is first created then some sections are shown expanded +while others are not. This is hard coded. When a buffer is refreshed +then the previous visibility is preserved. The initial visibility of +certain sections can also be overwritten using the hook +‘magit-section-set-visibility-hook’. + + -- User Option: magit-section-initial-visibility-alist + + This options can be used to override the initial visibility of + sections. In the future it will also be used to define the + defaults, but currently a section’s default is still hardcoded. + + The value is an alist. Each element maps a section type or lineage + to the initial visibility state for such sections. The state has + to be one of ‘show’ or ‘hide’, or a function that returns one of + these symbols. A function is called with the section as the only + argument. + + Use the command ‘magit-describe-section-briefly’ to determine a + section’s lineage or type. The vector in the output is the section + lineage and the type is the first element of that vector. + Wildcards can be used, see ‘magit-section-match’. + + -- User Option: magit-section-cache-visibility + + This option controls for which sections the previous visibility + state should be restored if a section disappears and later appears + again. The value is a boolean or a list of section types. If t, + then the visibility of all sections is cached. Otherwise this is + only done for sections whose type matches one of the listed types. + + This requires that the function ‘magit-section-cached-visibility’ + is a member of ‘magit-section-set-visibility-hook’. + + -- Variable: magit-section-set-visibility-hook + + This hook is run when first creating a buffer and also when + refreshing an existing buffer, and is used to determine the + visibility of the section currently being inserted. + + Each function is called with one argument, the section being + inserted. It should return ‘hide’ or ‘show’, or to leave the + visibility undefined ‘nil’. If no function decides on the + visibility and the buffer is being refreshed, then the visibility + is preserved; or if the buffer is being created, then the hard + coded default is used. + + Usually this should only be used to set the initial visibility but + not during refreshes. If ‘magit-insert-section--oldroot’ is + non-nil, then the buffer is being refreshed and these functions + should immediately return ‘nil’. + + +File: magit.info, Node: Section Hooks, Next: Section Types and Values, Prev: Section Visibility, Up: Sections + +4.2.3 Section Hooks +------------------- + +Which sections are inserted into certain buffers is controlled with +hooks. This includes the status and the refs buffers. For other +buffers, e.g. log and diff buffers, this is not possible. The command +‘magit-describe-section’ can be used to see which hook (if any) was +responsible for inserting the section at point. + + For buffers whose sections can be customized by the user, a hook +variable called ‘magit-TYPE-sections-hook’ exists. This hook should be +changed using ‘magit-add-section-hook’. Avoid using ‘add-hooks’ or the +Custom interface. + + The various available section hook variables are described later in +this manual along with the appropriate "section inserter functions". + + -- Function: magit-add-section-hook hook function &optional at append + local + + Add the function FUNCTION to the value of section hook HOOK. + + Add FUNCTION at the beginning of the hook list unless optional + APPEND is non-nil, in which case FUNCTION is added at the end. If + FUNCTION already is a member then move it to the new location. + + If optional AT is non-nil and a member of the hook list, then add + FUNCTION next to that instead. Add before or after AT, or replace + AT with FUNCTION depending on APPEND. If APPEND is the symbol + ‘replace’, then replace AT with FUNCTION. For any other non-nil + value place FUNCTION right after AT. If nil, then place FUNCTION + right before AT. If FUNCTION already is a member of the list but + AT is not, then leave FUNCTION where ever it already is. + + If optional LOCAL is non-nil, then modify the hook’s buffer-local + value rather than its global value. This makes the hook local by + copying the default value. That copy is then modified. + + HOOK should be a symbol. If HOOK is void, it is first set to nil. + HOOK’s value must not be a single hook function. FUNCTION should + be a function that takes no arguments and inserts one or multiple + sections at point, moving point forward. FUNCTION may choose not + to insert its section(s), when doing so would not make sense. It + should not be abused for other side-effects. + + To remove a function from a section hook, use ‘remove-hook’. + + +File: magit.info, Node: Section Types and Values, Next: Section Options, Prev: Section Hooks, Up: Sections + +4.2.4 Section Types and Values +------------------------------ + +Each section has a type, for example ‘hunk’, ‘file’, and ‘commit’. +Instances of certain section types also have a value. The value of a +section of type ‘file’, for example, is a file name. + + Users usually do not have to worry about a section’s type and value, +but knowing them can be handy at times. + +‘M-x magit-describe-section-briefly’ (‘magit-describe-section-briefly’) + + Show information about the section at point in the echo area, as + "#". + + Many commands behave differently depending on the type of the section +at point and/or somehow consume the value of that section. But that is +only one of the reasons why the same key may do something different, +depending on what section is current. + + Additionally for each section type a keymap *might* be defined, named +‘magit-TYPE-section-map’. That keymap is used as text property keymap +of all text belonging to any section of the respective type. If such a +map does not exist for a certain type, then you can define it yourself, +and it will automatically be used. + + +File: magit.info, Node: Section Options, Prev: Section Types and Values, Up: Sections + +4.2.5 Section Options +--------------------- + +This section describes options that have an effect on more than just a +certain type of sections. As you can see there are not many of those. + + -- User Option: magit-section-show-child-count + + Whether to append the number of children to section headings. This + only affects sections that could benefit from this information. + + +File: magit.info, Node: Popup Buffers and Prefix Commands, Next: Completion Confirmation and the Selection, Prev: Sections, Up: Interface Concepts + +4.3 Popup Buffers and Prefix Commands +===================================== + +Many Magit commands are implemented using *popup buffers*. First the +user invokes a *popup* or *prefix* command, which causes a popup buffer +with the available *infix* arguments and *suffix* commands to be +displayed. The user then optionally toggles/sets some arguments and +finally invokes one of the suffix commands. + + This is implemented in the library ‘magit-popup’. Earlier releases +used the library ‘magit-key-mode’. A future release will switch to a +yet-to-be-written successor, which will likely be named ‘transient’. + + Because ‘magit-popup’ can also be used by other packages without +having to depend on all of Magit, it is documented in its own manual. +See *note (magit-popup)Top::. + +‘C-c C-c’ (‘magit-dispatch-popup’) + + This popup command shows a buffer featuring all other Magit popup + commands as well as some other commands that are not popup commands + themselves. + + This command is also, or especially, useful outside Magit buffers, so +you should setup a global binding: + + (global-set-key (kbd "C-x M-g") 'magit-dispatch-popup) + + Most popups set their initial arguments according to the +corresponding ‘magit-*-arguments’ variable. Two popups, the log and +diff popups (see *note Logging:: and *note Diffing::), may behave a bit +differently, depending on the value of ‘magit-use-sticky-arguments’. + + -- User Option: magit-use-sticky-arguments + + This option controls how diff and log commands reuse arguments from + existing buffers. + + When ‘t’ (the default value), the log or diff popup reuses the + arguments from the current repository’s log or diff buffer, + respectively. When no log or diff buffer exists for the current + repository, these popups use the default value of + ‘magit-log-arguments’ or ‘magit-diff-arguments’. + + When ‘current’, log and diff popups will only reuse the arguments + if the current buffer is derived from ‘magit-log-mode’ or + ‘magit-diff-mode’, respectively. + + When ‘nil’, the default value of ‘magit-log-arguments’ or + ‘magit-diff-arguments’ is always used. + + +File: magit.info, Node: Completion Confirmation and the Selection, Next: Running Git, Prev: Popup Buffers and Prefix Commands, Up: Interface Concepts + +4.4 Completion, Confirmation and the Selection +============================================== + +* Menu: + +* Action Confirmation:: +* Completion and Confirmation:: +* The Selection:: +* The hunk-internal region:: +* Support for Completion Frameworks:: +* Additional Completion Options:: + + +File: magit.info, Node: Action Confirmation, Next: Completion and Confirmation, Up: Completion Confirmation and the Selection + +4.4.1 Action Confirmation +------------------------- + +By default many actions that could potentially lead to data loss have to +be confirmed. This includes many very common actions, so this can +quickly become annoying. Many of these actions can be undone and if you +have thought about how to undo certain mistakes, then it should be safe +to disable confirmation for the respective actions. + + The option ‘magit-no-confirm’ can be used to tell Magit to perform +certain actions without the user having to confirm them. Note that +while this option can only be used to disable confirmation for a +specific set of actions, the next section explains another way of +telling Magit to ask fewer questions. + + -- User Option: magit-no-confirm + + The value of this option is a list of symbols, representing actions + that do not have to be confirmed by the user before being carried + out. + + By default many potentially dangerous commands ask the user for + confirmation. Each of the below symbols stands for an action + which, when invoked unintentionally or without being fully aware of + the consequences, could lead to tears. In many cases there are + several commands that perform variations of a certain action, so we + don’t use the command names but more generic symbols. + + • Applying changes: + + • ‘discard’ Discarding one or more changes (i.e. hunks or + the complete diff for a file) loses that change, + obviously. + + • ‘reverse’ Reverting one or more changes can usually be + undone by reverting the reversion. + + • ‘stage-all-changes’, ‘unstage-all-changes’ When there are + both staged and unstaged changes, then un-/staging + everything would destroy that distinction. Of course + that also applies when un-/staging a single change, but + then less is lost and one does that so often that having + to confirm every time would be unacceptable. + + • Files: + + • ‘delete’ When a file that isn’t yet tracked by Git is + deleted, then it is completely lost, not just the last + changes. Very dangerous. + + • ‘trash’ Instead of deleting a file it can also be move to + the system trash. Obviously much less dangerous than + deleting it. + + Also see option ‘magit-delete-by-moving-to-trash’. + + • ‘resurrect’ A deleted file can easily be resurrected by + "deleting" the deletion, which is done using the same + command that was used to delete the same file in the + first place. + + • ‘untrack’ Untracking a file can be undone by tracking it + again. + + • ‘rename’ Renaming a file can easily be undone. + + • Sequences: + + • ‘reset-bisect’ Aborting (known to Git as "resetting") a + bisect operation loses all information collected so far. + + • ‘abort-rebase’ Aborting a rebase throws away all already + modified commits, but it’s possible to restore those from + the reflog. + + • ‘abort-merge’ Aborting a merge throws away all conflict + resolutions which have already been carried out by the + user. + + • ‘merge-dirty’ Merging with a dirty worktree can make it + hard to go back to the state before the merge was + initiated. + + • References: + + • ‘delete-unmerged-branch’ Once a branch has been deleted, + it can only be restored using low-level recovery tools + provided by Git. And even then the reflog is gone. The + user always has to confirm the deletion of a branch by + accepting the default choice (or selecting another + branch), but when a branch has not been merged yet, also + make sure the user is aware of that. + + • ‘delete-pr-branch’ When deleting a branch that was + created from a pull request and if no other branches + still exist on that remote, then ‘magit-branch-delete’ + offers to delete the remote as well. This should be safe + because it only happens if no other refs exist in the + remotes namespace, and you can recreate the remote if + necessary. + + • ‘drop-stashes’ Dropping a stash is dangerous because Git + stores stashes in the reflog. Once a stash is removed, + there is no going back without using low-level recovery + tools provided by Git. When a single stash is dropped, + then the user always has to confirm by accepting the + default (or selecting another). This action only + concerns the deletion of multiple stashes at once. + + • Edit published history: + + Without adding these symbols here, you will be warned before + editing commits that have already been pushed to one of the + branches listed in ‘magit-published-branches’. + + • ‘amend-published’ Affects most commands that amend to + "HEAD". + + • ‘rebase-published’ Affects commands that perform + interactive rebases. This includes commands from the + commit popup that modify a commit other than "HEAD", + namely the various fixup and squash variants. + + • ‘edit-published’ Affects the commands + ‘magit-edit-line-commit’ and + ‘magit-diff-edit-hunk-commit’. These two commands make + it quite easy to accidentally edit a published commit, so + you should think twice before configuring them not to ask + for confirmation. + + To disable confirmation completely, add all three symbols here + or set ‘magit-published-branches’ to ‘nil’. + + • Various: + + • ‘kill-process’ There seldom is a reason to kill a + process. + + • Global settings: + + Instead of adding all of the above symbols to the value of + this option, you can also set it to the atom ‘t’, which has + the same effect as adding all of the above symbols. Doing + that most certainly is a bad idea, especially because other + symbols might be added in the future. So even if you don’t + want to be asked for confirmation for any of these actions, + you are still better of adding all of the respective symbols + individually. + + When ‘magit-wip-before-change-mode’ is enabled, then the + following actions can be undone fairly easily: ‘discard’, + ‘reverse’, ‘stage-all-changes’, and ‘unstage-all-changes’. If + and only if this mode is enabled, then ‘safe-with-wip’ has the + same effect as adding all of these symbols individually. + + +File: magit.info, Node: Completion and Confirmation, Next: The Selection, Prev: Action Confirmation, Up: Completion Confirmation and the Selection + +4.4.2 Completion and Confirmation +--------------------------------- + +Many Magit commands ask the user to select from a list of possible +things to act on, while offering the most likely choice as the default. +For many of these commands the default is the thing at point, provided +that it actually is a valid thing to act on. For many commands that act +on a branch, the current branch serves as the default if there is no +branch at point. + + These commands combine asking for confirmation and asking for a +target to act on into a single action. The user can confirm the default +target using ‘RET’ or abort using ‘C-g’. This is similar to a +‘y-or-n-p’ prompt, but the keys to confirm or abort differ. + + At the same time the user is also given the opportunity to select +another target, which is useful because for some commands and/or in some +situations you might want to select the action before selecting the +target by moving to it. + + However you might find that for some commands you always want to use +the default target, if any, or even that you want the command to act on +the default without requiring any confirmation at all. The option +‘magit-dwim-selection’ can be used to configure certain commands to that +effect. + + Note that when the region is active then many commands act on the +things that are selected using a mechanism based on the region, in many +cases after asking for confirmation. This region-based mechanism is +called the "selection" and is described in detail in the next section. +When a selection exists that is valid for the invoked command, then that +command never offers to act on something else, and whether it asks for +confirmation is not controlled by this option. + + Also note that Magit asks for confirmation of certain actions that +are not coupled with completion (or the selection). Such dialogs are +also not affected by this option and are described in the previous +section. + + -- User Option: magit-dwim-selection + + This option can be used to tell certain commands to use the thing at +point instead of asking the user to select a candidate to act on, with +or without confirmation. + + The value has the form ‘((COMMAND nil|PROMPT DEFAULT)...)’. + + • COMMAND is the command that should not prompt for a choice. To + have an effect, the command has to use the function + ‘magit-completing-read’ or a utility function which in turn uses + that function. + + • If the command uses ‘magit-completing-read’ multiple times, then + PROMPT can be used to only affect one of these uses. PROMPT, if + non-nil, is a regular expression that is used to match against the + PROMPT argument passed to ‘magit-completing-read’. + + • DEFAULT specifies how to use the default. If it is ‘t’, then the + DEFAULT argument passed to ‘magit-completing-read’ is used without + confirmation. If it is ‘ask’, then the user is given a chance to + abort. DEFAULT can also be ‘nil’, in which case the entry has no + effect. + + +File: magit.info, Node: The Selection, Next: The hunk-internal region, Prev: Completion and Confirmation, Up: Completion Confirmation and the Selection + +4.4.3 The Selection +------------------- + +If the region is active, then many Magit commands act on the things that +are selected using a mechanism based on the region instead of one single +thing. When the region is not active, then these commands act on the +thing at point or read a single thing to act on. This is described in +the previous section — this section only covers how multiple things are +selected, how that is visualized, and how certain commands behave when +that is the case. + + Magit’s mechanism for selecting multiple things, or rather sections +that represent these things, is based on the Emacs region, but the area +that Magit considers to be selected is typically larger than the region +and additional restrictions apply. + + Magit makes a distinction between a region that qualifies as forming +a valid Magit selection and a region that does not. If the region does +not qualify, then it is displayed as it is in other Emacs buffers. If +the region does qualify as a Magit selection, then the selection is +always visualized, while the region itself is only visualized if it +begins and ends on the same line. + + For a region to qualify as a Magit selection, it must begin in the +heading of one section and end in the heading of a sibling section. +Note that if the end of the region is at the very beginning of section +heading (i.e. at the very beginning of a line) then that section is +considered to be *inside* the selection. + + This is not consistent with how the region is normally treated in +Emacs — if the region ends at the beginning of a line, then that line is +outside the region. Due to how Magit visualizes the selection, it +should be obvious that this difference exists. + + Not every command acts on every valid selection. Some commands do +not even consider the location of point, others may act on the section +at point but not support acting on the selection, and even commands that +do support the selection of course only do so if it selects things that +they can act on. + + This is the main reason why the selection must include the section at +point. Even if a selection exists, the invoked command may disregard +it, in which case it may act on the current section only. It is much +safer to only act on the current section but not the other selected +sections than it is to act on the current section *instead* of the +selected sections. The latter would be much more surprising and if the +current section always is part of the selection, then that cannot +happen. + + -- Variable: magit-keep-region-overlay + + This variable controls whether the region is visualized as usual + even when a valid Magit selection or a hunk-internal region exists. + See the doc-string for more information. + + +File: magit.info, Node: The hunk-internal region, Next: Support for Completion Frameworks, Prev: The Selection, Up: Completion Confirmation and the Selection + +4.4.4 The hunk-internal region +------------------------------ + +Somewhat related to the Magit selection described in the previous +section is the hunk-internal region. + + Like the selection, the hunk-internal region is based on the Emacs +region but causes that region to not be visualized as it would in other +Emacs buffers, and includes the line on which the region ends even if it +ends at the very beginning of that line. + + Unlike the selection, which is based on a region that must begin in +the heading of one section and ends in the section of a sibling section, +the hunk-internal region must begin inside the *body* of a hunk section +and end in the body of the *same* section. + + The hunk-internal region is honored by "apply" commands, which can, +among other targets, act on a hunk. If the hunk-internal region is +active, then such commands act only on the marked part of the hunk +instead of on the complete hunk. + + +File: magit.info, Node: Support for Completion Frameworks, Next: Additional Completion Options, Prev: The hunk-internal region, Up: Completion Confirmation and the Selection + +4.4.5 Support for Completion Frameworks +--------------------------------------- + +The built-in option ‘completing-read-function’ specifies the low-level +function used by ‘completing-read’ to ask a user to select from a list +of choices. Its default value is ‘completing-read-default’. +Alternative completion frameworks typically activate themselves by +substituting their own implementation. + + Mostly for historic reasons Magit provides a similar option named +‘magit-completing-read-function’, which only controls the low-level +function used by ‘magit-completing-read’. This option also makes it +possible to use a different completing mechanism for Magit than for the +rest of Emacs, but doing that is not recommend. + + You most likely don’t have to customize the magit-specific option to +use an alternative completion framework. For example, if you enable +‘ivy-mode’, then Magit will respect that, and if you enable ‘helm-mode’, +then you are done too. + + However if you want to use Ido, then ‘ido-mode’ won’t do the trick. +You will also have to install the ‘ido-completing-read+’ package and use +‘magit-ido-completing-read’ as ‘magit-completing-read-function’. + + -- User Option: magit-completing-read-function + + The value of this variable is the low-level function used to + perform completion by code that uses ‘magit-completing-read’ (as + opposed to the built-in ‘completing-read’). + + The default value, ‘magit-builtin-completing-read’, is suitable for + the standard completion mechanism, ‘ivy-mode’, and ‘helm-mode’ at + least. + + The built-in ‘completing-read’ and ‘completing-read-default’ are + *not* suitable to be used here. ‘magit-builtin-completing-read’ + performs some additional work, and any function used in its place + has to do the same. + + -- Function: magit-builtin-completing-read prompt choices &optional + predicate require-match initial-input hist def + + This function performs completion using the built-in + ‘completion-read’ and does some additional magit-specific work. + + -- Function: magit-ido-completing-read prompt choices &optional + predicate require-match initial-input hist def + + This function performs completion using ‘ido-completing-read+’ from + the package by the same name (which you have to explicitly install) + and does some additional magit-specific work. + + We have to use ‘ido-completing-read+’ instead of the + ‘ido-completing-read’ that comes with Ido itself, because the + latter, while intended as a drop-in replacement, cannot serve that + purpose because it violates too many of the implicit conventions. + + -- Function: magit-completing-read prompt choices &optional predicate + require-match initial-input hist def fallback + + This is the function that Magit commands use when they need the + user to select a single thing to act on. The arguments have the + same meaning as for ‘completing-read’, except for FALLBACK, which + is unique to this function and is described below. + + Instead of asking the user to choose from a list of possible + candidates, this function may just return the default specified by + DEF, with or without requiring user confirmation. Whether that is + the case depends on PROMPT, ‘this-command’ and + ‘magit-dwim-selection’. See the documentation of the latter for + more information. + + If it does read a value in the minibuffer, then this function acts + similar to ‘completing-read’, except for the following: + + • If REQUIRE-MATCH is ‘nil’ and the user exits without a choice, + then ‘nil’ is returned instead of an empty string. + + • If REQUIRE-MATCH is non-nil and the users exits without a + choice, an user-error is raised. + + • FALLBACK specifies a secondary default that is only used if + the primary default DEF is ‘nil’. The secondary default is + not subject to ‘magit-dwim-selection’ — if DEF is ‘nil’ but + FALLBACK is not, then this function always asks the user to + choose a candidate, just as if both defaults were ‘nil’. + + • ": " is appended to PROMPT. + + • PROMPT is modified to end with \" (default DEF|FALLBACK): \" + provided that DEF or FALLBACK is non-nil, that neither + ‘ivy-mode’ nor ‘helm-mode’ is enabled, and that + ‘magit-completing-read-function’ is set to its default value + of ‘magit-builtin-completing-read’. + + +File: magit.info, Node: Additional Completion Options, Prev: Support for Completion Frameworks, Up: Completion Confirmation and the Selection + +4.4.6 Additional Completion Options +----------------------------------- + + -- User Option: magit-list-refs-sortby + + For many commands that read a ref or refs from the user, the value + of this option can be used to control the order of the refs. Valid + values include any key accepted by the ‘--sort’ flag of ‘git + for-each-ref’. By default, refs are sorted alphabetically by their + full name (e.g., "refs/heads/master"). + + +File: magit.info, Node: Running Git, Prev: Completion Confirmation and the Selection, Up: Interface Concepts + +4.5 Running Git +=============== + +* Menu: + +* Viewing Git Output:: +* Git Process Status:: +* Running Git Manually:: +* Git Executable:: +* Global Git Arguments:: + + +File: magit.info, Node: Viewing Git Output, Next: Git Process Status, Up: Running Git + +4.5.1 Viewing Git Output +------------------------ + +Magit runs Git either for side-effects (e.g. when pushing) or to get +some value (e.g. the name of the current branch). + + When Git is run for side-effects, the process output is logged in a +per-repository log buffer, which can be consulted using the +‘magit-process’ command when things don’t go as expected. + + The output/errors for up to ‘magit-process-log-max’ Git commands are +retained. + +‘$’ (‘magit-process’) + + This commands displays the process buffer for the current + repository. + + Inside that buffer, the usual key bindings for navigating and showing +sections are available. There is one additional command. + +‘k’ (‘magit-process-kill’) + + This command kills the process represented by the section at point. + + -- User Option: magit-git-debug + + When this is non-nil then the output of all calls to git are logged + in the process buffer. This is useful when debugging, otherwise it + just negatively affects performance. + + +File: magit.info, Node: Git Process Status, Next: Running Git Manually, Prev: Viewing Git Output, Up: Running Git + +4.5.2 Git Process Status +------------------------ + +When a Git process is running for side-effects, Magit displays an +indicator in the mode line, using the ‘magit-mode-line-process’ face. + + If the Git process exits successfully, the process indicator is +removed from the mode line immediately. + + In the case of a Git error, the process indicator is not removed, but +is instead highlighted with the ‘magit-mode-line-process-error’ face, +and the error details from the process buffer are provided as a tooltip +for mouse users. This error indicator persists in the mode line until +the next magit buffer refresh. + + If you do not wish process errors to be indicated in the mode line, +customize the ‘magit-process-display-mode-line-error’ user option. + + Process errors are additionally indicated at the top of the status +buffer. + + +File: magit.info, Node: Running Git Manually, Next: Git Executable, Prev: Git Process Status, Up: Running Git + +4.5.3 Running Git Manually +-------------------------- + +While Magit provides many Emacs commands to interact with Git, it does +not cover everything. In those cases your existing Git knowledge will +come in handy. Magit provides some commands for running arbitrary Git +commands by typing them into the minibuffer, instead of having to switch +to a shell. + +‘!’ (‘magit-run-popup’) + + Shows the popup buffer featuring the below suffix commands. + +‘! !’ (‘magit-git-command-topdir’) + + This command reads a command from the user and executes it in the + top-level directory of the current working tree. + + The string "git " is used as initial input when prompting the user + for the command. It can be removed to run another command. + +‘! p’ (‘magit-git-command’) + + This command reads a command from the user and executes it in + ‘default-directory’. With a prefix argument the command is + executed in the top-level directory of the current working tree + instead. + + The string "git " is used as initial input when prompting the user + for the command. It can be removed to run another command. + +‘! s’ (‘magit-shell-command-topdir’) + + This command reads a command from the user and executes it in the + top-level directory of the current working tree. + +‘! S’ (‘magit-shell-command’) + + This command reads a command from the user and executes it in + ‘default-directory’. With a prefix argument the command is + executed in the top-level directory of the current working tree + instead. + + -- User Option: magit-shell-command-verbose-prompt + + Whether the prompt, used by the the above commands when reading a + shell command, shows the directory in which it will be run. + + These suffix commands start external gui tools. + +‘! k’ (‘magit-run-gitk’) + + This command runs ‘gitk’ in the current repository. + +‘! a’ (‘magit-run-gitk-all’) + + This command runs ‘gitk --all’ in the current repository. + +‘! b’ (‘magit-run-gitk-branches’) + + This command runs ‘gitk --branches’ in the current repository. + +‘! g’ (‘magit-run-git-gui’) + + This command runs ‘git gui’ in the current repository. + + +File: magit.info, Node: Git Executable, Next: Global Git Arguments, Prev: Running Git Manually, Up: Running Git + +4.5.4 Git Executable +-------------------- + +Except on MS Windows, Magit defaults to running Git without specifying +the path to the git executable. Instead the first executable found by +Emacs on ‘exec-path’ is used (whose value in turn is set based on the +value of the environment variable ‘$PATH’ when Emacs was started). + + This has the advantage that it continues to work even when using +Tramp to connect to a remote machine on which the executable is found in +a different place. The downside is that if you have multiple versions +of Git installed, then you might end up using another version than the +one you think you are using. + +‘M-x magit-version’ (‘magit-version’) + + This command shows the currently used versions of Magit, Git, and + Emacs in the echo area. Non-interactively this just returns the + Magit version. + + When the ‘system-type’ is ‘windows-nt’, then ‘magit-git-executable’ +is set to an absolute path when Magit is first loaded. This is +necessary because Git on that platform comes with several wrapper +scripts for the actual git binary, which are also placed on ‘$PATH’, and +using one of these wrappers instead of the binary would degrade +performance horribly. + + If Magit doesn’t find the correct executable then you *can* work +around that by setting ‘magit-git-executable’ to an absolute path. But +note that doing so is a kludge. It is better to make sure the order in +the environment variable ‘$PATH’ is correct, and that Emacs is started +with that environment in effect. The command +‘magit-debug-git-executable’ can be useful to find out where Emacs is +searching for git. If you have to connect from Windows to a non-Windows +machine, then you must change the value to "git". + + -- User Option: magit-git-executable + + The git executable used by Magit, either the full path to the + executable or the string "git" to let Emacs find the executable + itself, using the standard mechanism for doing such things. + +‘M-x magit-debug-git-executable’ (‘magit-debug-git-executable’) + + Display a buffer with information about ‘magit-git-executable’. + + +File: magit.info, Node: Global Git Arguments, Prev: Git Executable, Up: Running Git + +4.5.5 Global Git Arguments +-------------------------- + + -- User Option: magit-git-global-arguments + + The arguments set here are used every time the git executable is + run as a subprocess. They are placed right after the executable + itself and before the git command - as in ‘git HERE... COMMAND + REST’. For valid arguments see *note (gitman)git::. + + Be careful what you add here, especially if you are using Tramp to + connect to servers with ancient Git versions. Never remove + anything that is part of the default value, unless you really know + what you are doing. And think very hard before adding something; + it will be used every time Magit runs Git for any purpose. + + +File: magit.info, Node: Inspecting, Next: Manipulating, Prev: Interface Concepts, Up: Top + +5 Inspecting +************ + +The functionality provided by Magit can be roughly divided into three +groups: inspecting existing data, manipulating existing data or adding +new data, and transferring data. Of course that is a rather crude +distinction that often falls short, but it’s more useful than no +distinction at all. This section is concerned with inspecting data, the +next two with manipulating and transferring it. Then follows a section +about miscellaneous functionality, which cannot easily be fit into this +distinction. + + Of course other distinctions make sense too, e.g. Git’s distinction +between porcelain and plumbing commands, which for the most part is +equivalent to Emacs’ distinction between interactive commands and +non-interactive functions. All of the sections mentioned before are +mainly concerned with the porcelain – Magit’s plumbing layer is +described later. + +* Menu: + +* Status Buffer:: +* Repository List:: +* Logging:: +* Diffing:: +* Ediffing:: +* References Buffer:: +* Bisecting:: +* Visiting Blobs:: +* Blaming:: + + +File: magit.info, Node: Status Buffer, Next: Repository List, Up: Inspecting + +5.1 Status Buffer +================= + +While other Magit buffers contain e.g. one particular diff or one +particular log, the status buffer contains the diffs for staged and +unstaged changes, logs for unpushed and unpulled commits, lists of +stashes and untracked files, and information related to the current +branch. + + During certain incomplete operations – for example when a merge +resulted in a conflict – additional information is displayed that helps +proceeding with or aborting the operation. + + The command ‘magit-status’ displays the status buffer belonging to +the current repository in another window. This command is used so often +that it should be bound globally. We recommend using ‘C-x g’: + + (global-set-key (kbd "C-x g") 'magit-status) + +‘C-x g’ (‘magit-status’) + + Show the status of the current Git repository in a buffer. With a + prefix argument prompt for a repository to be shown. With two + prefix arguments prompt for an arbitrary directory. If that + directory isn’t the root of an existing repository, then offer to + initialize it as a new repository. + + -- User Option: magit-repository-directories + + List of directories that are Git repositories or contain Git + repositories. + + Each element has the form ‘(DIRECTORY . DEPTH)’. DIRECTORY has to + be a directory or a directory file-name, a string. DEPTH, an + integer, specifies the maximum depth to look for Git repositories. + If it is 0, then only add DIRECTORY itself. + + -- User Option: magit-repository-directories-depth + + The maximum depth to look for Git repositories. This option is + obsolete and only used for elements of the option + ‘magit-repository-directories’ (which see) that don’t specify the + depth directly. + + -- Command: ido-enter-magit-status + + From an Ido prompt used to open a file, instead drop into + ‘magit-status’. This is similar to ‘ido-magic-delete-char’, which, + despite its name, usually causes a Dired buffer to be created. + + To make this command available, use something like: + + (add-hook 'ido-setup-hook + (lambda () + (define-key ido-completion-map + (kbd \"C-x g\") 'ido-enter-magit-status))) + + Starting with Emacs 25.1 the Ido keymaps are defined just once + instead of every time Ido is invoked, so now you can modify it like + pretty much every other keymap: + + (define-key ido-common-completion-map + (kbd \"C-x g\") 'ido-enter-magit-status) + +* Menu: + +* Status Sections:: +* Status Header Sections:: +* Status Module Sections:: +* Status Options:: + + +File: magit.info, Node: Status Sections, Next: Status Header Sections, Up: Status Buffer + +5.1.1 Status Sections +--------------------- + +The contents of status buffers is controlled using the hook +‘magit-status-sections-hook’. See *note Section Hooks:: to learn about +such hooks and how to customize them. + + -- User Option: magit-status-sections-hook + + Hook run to insert sections into a status buffer. + + The first function on that hook by default is +‘magit-insert-status-headers’; it is described in the next section. By +default the following functions are also members of that hook: + + -- Function: magit-insert-merge-log + + Insert section for the on-going merge. Display the heads that are + being merged. If no merge is in progress, do nothing. + + -- Function: magit-insert-rebase-sequence + + Insert section for the on-going rebase sequence. If no such + sequence is in progress, do nothing. + + -- Function: magit-insert-am-sequence + + Insert section for the on-going patch applying sequence. If no + such sequence is in progress, do nothing. + + -- Function: magit-insert-sequencer-sequence + + Insert section for the on-going cherry-pick or revert sequence. If + no such sequence is in progress, do nothing. + + -- Function: magit-insert-bisect-output + + While bisecting, insert section with output from ‘git bisect’. + + -- Function: magit-insert-bisect-rest + + While bisecting, insert section visualizing the bisect state. + + -- Function: magit-insert-bisect-log + + While bisecting, insert section logging bisect progress. + + -- Function: magit-insert-untracked-files + + Maybe insert a list or tree of untracked files. + + Do so depending on the value of ‘status.showUntrackedFiles’. Note + that even if the value is ‘all’, Magit still initially only shows + directories. But the directory sections can then be expanded using + ‘TAB’. + + -- Function: magit-insert-unstaged-changes + + Insert section showing unstaged changes. + + -- Function: magit-insert-staged-changes + + Insert section showing staged changes. + + -- Function: magit-insert-stashes &optional ref heading + + Insert the ‘stashes’ section showing reflog for "refs/stash". If + optional REF is non-nil show reflog for that instead. If optional + HEADING is non-nil use that as section heading instead of + "Stashes:". + + -- Function: magit-insert-unpulled-from-upstream + + Insert section showing commits that haven’t been pulled from the + upstream branch yet. + + -- Function: magit-insert-unpulled-from-pushremote + + Insert section showing commits that haven’t been pulled from the + push-remote branch yet. + + -- Function: magit-insert-unpushed-to-upstream + + Insert section showing commits that haven’t been pushed to the + upstream yet. + + -- Function: magit-insert-unpushed-to-pushremote + + Insert section showing commits that haven’t been pushed to the + push-remote yet. + + The following functions can also be added to the above hook: + + -- Function: magit-insert-tracked-files + + Insert a tree of tracked files. + + -- Function: magit-insert-ignored-files + + Insert a tree of ignored files. + + If the first element of ‘magit-diff-section-arguments’ is a + directory, then limit the list to files below that. The value of + that variable can be set using ‘D = f RET g’. + + -- Function: magit-insert-unpulled-or-recent-commits + + Insert section showing unpulled or recent commits. If an upstream + is configured for the current branch and it is ahead of the current + branch, then show the missing commits. Otherwise, show the last + ‘magit-log-section-commit-count’ commits. + + -- Function: magit-insert-recent-commits + + Insert section showing the last ‘magit-log-section-commit-count’ + commits. + + -- User Option: magit-log-section-commit-count + + How many recent commits ‘magit-insert-recent-commits’ and + ‘magit-insert-unpulled-or-recent-commits’ (provided there are no + unpulled commits) show. + + -- Function: magit-insert-unpulled-cherries + + Insert section showing unpulled commits. Like + ‘magit-insert-unpulled-commits’ but prefix each commit that has not + been applied yet (i.e. a commit with a patch-id not shared with + any local commit) with "+", and all others with "-". + + -- Function: magit-insert-unpushed-cherries + + Insert section showing unpushed commits. Like + ‘magit-insert-unpushed-commits’ but prefix each commit which has + not been applied to upstream yet (i.e. a commit with a patch-id + not shared with any upstream commit) with "+" and all others with + "-". + + See *note References Buffer:: for some more section inserters, which +could be used here. + + +File: magit.info, Node: Status Header Sections, Next: Status Module Sections, Prev: Status Sections, Up: Status Buffer + +5.1.2 Status Header Sections +---------------------------- + +The contents of status buffers is controlled using the hook +‘magit-status-sections-hook’ (see *note Status Sections::). + + By default ‘magit-insert-status-headers’ is the first member of that +hook variable. + + -- Function: magit-insert-status-headers + + Insert headers sections appropriate for ‘magit-status-mode’ + buffers. The sections are inserted by running the functions on the + hook ‘magit-status-headers-hook’. + + -- User Option: magit-status-headers-hook + + Hook run to insert headers sections into the status buffer. + + This hook is run by ‘magit-insert-status-headers’, which in turn + has to be a member of ‘magit-status-sections-hook’ to be used at + all. + + By default the following functions are members of the above hook: + + -- Function: magit-insert-error-header + + Insert a header line showing the message about the Git error that + just occurred. + + This function is only aware of the last error that occur when Git + was run for side-effects. If, for example, an error occurs while + generating a diff, then that error won’t be inserted. Refreshing + the status buffer causes this section to disappear again. + + -- Function: magit-insert-diff-filter-header + + Insert a header line showing the effective diff filters. + + -- Function: magit-insert-head-branch-header + + Insert a header line about the current branch or detached ‘HEAD’. + + -- Function: magit-insert-upstream-branch-header + + Insert a header line about the branch that is usually pulled into + the current branch. + + -- Function: magit-insert-push-branch-header + + Insert a header line about the branch that the current branch is + usually pushed to. + + -- Function: magit-insert-tags-header + + Insert a header line about the current and/or next tag, along with + the number of commits between the tag and ‘HEAD’. + + The following functions can also be added to the above hook: + + -- Function: magit-insert-repo-header + + Insert a header line showing the path to the repository top-level. + + -- Function: magit-insert-remote-header + + Insert a header line about the remote of the current branch. + + If no remote is configured for the current branch, then fall back + showing the "origin" remote, or if that does not exist the first + remote in alphabetic order. + + -- Function: magit-insert-user-header + + Insert a header line about the current user. + + +File: magit.info, Node: Status Module Sections, Next: Status Options, Prev: Status Header Sections, Up: Status Buffer + +5.1.3 Status Module Sections +---------------------------- + +The contents of status buffers is controlled using the hook +‘magit-status-sections-hook’ (see *note Status Sections::). + + By default ‘magit-insert-modules’ is _not_ a member of that hook +variable. + + -- Function: magit-insert-modules + + Insert submodule sections. + + Hook ‘magit-module-sections-hook’ controls which module sections + are inserted, and option ‘magit-module-sections-nested’ controls + whether they are wrapped in an additional section. + + -- User Option: magit-module-sections-hook + + Hook run by ‘magit-insert-modules’. + + -- User Option: magit-module-sections-nested + + This option controls whether ‘magit-insert-modules’ wraps inserted + sections in an additional section. + + If this is non-nil, then only a single top-level section is + inserted. If it is nil, then all sections listed in + ‘magit-module-sections-hook’ become top-level sections. + + -- Function: magit-insert-modules-overview + + Insert sections for all submodules. For each section insert the + path, the branch, and the output of ‘git describe --tags’, or, + failing that, the abbreviated HEAD commit hash. + + Press ‘RET’ on such a submodule section to show its own status + buffer. Press ‘RET’ on the "Modules" section to display a list of + submodules in a separate buffer. This shows additional information + not displayed in the super-repository’s status buffer. + + -- Function: magit-insert-modules-unpulled-from-upstream + + Insert sections for modules that haven’t been pulled from the + upstream yet. These sections can be expanded to show the + respective commits. + + -- Function: magit-insert-modules-unpulled-from-pushremote + + Insert sections for modules that haven’t been pulled from the + push-remote yet. These sections can be expanded to show the + respective commits. + + -- Function: magit-insert-modules-unpushed-to-upstream + + Insert sections for modules that haven’t been pushed to the + upstream yet. These sections can be expanded to show the + respective commits. + + -- Function: magit-insert-modules-unpushed-to-pushremote + + Insert sections for modules that haven’t been pushed to the + push-remote yet. These sections can be expanded to show the + respective commits. + + +File: magit.info, Node: Status Options, Prev: Status Module Sections, Up: Status Buffer + +5.1.4 Status Options +-------------------- + + -- User Option: magit-status-refresh-hook + + Hook run after a status buffer has been refreshed. + + -- User Option: magit-status-margin + + This option specifies whether the margin is initially shown in + Magit-Status mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + + • STYLE controls how to format the committer date. It can be + one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. + + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + + • AUTHOR controls whether the name of the author is also shown + by default. + + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + -- User Option: magit-log-section-args + + Additional Git arguments used when creating log sections. Only + ‘--graph’, ‘--decorate’, and ‘--show-signature’ are supported. + This option is only a temporary kludge and will be removed. + + Note that due to an issue in Git the use of ‘--graph’ is very slow + with long histories, so you probably don’t want to add this here. + + Also see the proceeding section for more options concerning status +buffers. + + +File: magit.info, Node: Repository List, Next: Logging, Prev: Status Buffer, Up: Inspecting + +5.2 Repository List +=================== + + -- Command: magit-list-repositories + + This command displays a list of repositories in a separate buffer. + + The options ‘magit-repository-directories’ and + ‘magit-repository-directories-depth’ control which repositories are + displayed. + + -- User Option: magit-repolist-columns + + This option controls what columns are displayed by the command + ‘magit-list-repositories’ and how they are displayed. + + Each element has the form ‘(HEADER WIDTH FORMAT PROPS)’. + + HEADER is the string displayed in the header. WIDTH is the width + of the column. FORMAT is a function that is called with one + argument, the repository identification (usually its basename), and + with ‘default-directory’ bound to the toplevel of its working tree. + It has to return a string to be inserted or nil. PROPS is an alist + that supports the keys ‘:right-align’ and ‘:pad-right’. + + The following functions can be added to the above option: + + -- Function: magit-repolist-column-ident + + This function inserts the identification of the repository. + Usually this is just its basename. + + -- Function: magit-repolist-column-path + + This function inserts the absolute path of the repository. + + -- Function: magit-repolist-column-version + + This function inserts a description of the repository’s ‘HEAD’ + revision. + + -- Function: magit-repolist-column-unpulled-from-upstream + + This function inserts the number of upstream commits not in the + current branch. + + -- Function: magit-repolist-column-unpulled-from-pushremote + + This function inserts the number of commits in the push branch but + not the current branch. + + -- Function: magit-repolist-column-unpushed-to-upstream + + This function inserts the number of commits in the current branch + but not its upstream. + + -- Function: magit-repolist-column-unpushed-to-pushremote + + This function inserts the number of commits in the current branch + but not its push branch. + + +File: magit.info, Node: Logging, Next: Diffing, Prev: Repository List, Up: Inspecting + +5.3 Logging +=========== + +The status buffer contains logs for the unpushed and unpulled commits, +but that obviously isn’t enough. The prefix command ‘magit-log-popup’, +on ‘l’, features several suffix commands, which show a specific log in a +separate log buffer. + + Like other popups, the log popup also features several arguments that +can be changed before invoking one of the suffix commands. However, in +the case of the log popup, these arguments may be taken from those +currently in use in the current repository’s log buffer, depending on +the value of ‘magit-use-sticky-arguments’ (see *note Popup Buffers and +Prefix Commands::). + + For information about the various arguments, see *note +(gitman)git-log::. + + The switch ‘++order=VALUE’ is converted to one of +‘--author-date-order’, ‘--date-order’, or ‘--topo-order’ before being +passed to ‘git log’. + + The log popup also features several reflog commands. See *note +Reflog::. + +‘l’ (‘magit-log-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘l l’ (‘magit-log-current’) + + Show log for the current branch. When ‘HEAD’ is detached or with a + prefix argument, show log for one or more revs read from the + minibuffer. + +‘l o’ (‘magit-log-other’) + + Show log for one or more revs read from the minibuffer. The user + can input any revision or revisions separated by a space, or even + ranges, but only branches, tags, and a representation of the commit + at point are available as completion candidates. + +‘l h’ (‘magit-log-head’) + + Show log for ‘HEAD’. + +‘l L’ (‘magit-log-branches’) + + Show log for all local branches and ‘HEAD’. + +‘l b’ (‘magit-log-all-branches’) + + Show log for all local and remote branches and ‘HEAD’. + +‘l a’ (‘magit-log-all’) + + Show log for all references and ‘HEAD’. + + Two additional commands that show the log for the file or blob that +is being visited in the current buffer exists, see *note Minor Mode for +Buffers Visiting Files::. The command ‘magit-cherry’ also shows a log, +see *note Cherries::. + +* Menu: + +* Refreshing Logs:: +* Log Buffer:: +* Log Margin:: +* Select from Log:: +* Reflog:: +* Cherries:: + + +File: magit.info, Node: Refreshing Logs, Next: Log Buffer, Up: Logging + +5.3.1 Refreshing Logs +--------------------- + +The prefix command ‘magit-log-refresh-popup’, on ‘L’, can be used to +change the log arguments used in the current buffer, without changing +which log is shown. This works in dedicated log buffers, but also in +the status buffer. + +‘L’ (‘magit-log-refresh-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘L g’ (‘magit-log-refresh’) + + This suffix command sets the local log arguments for the current + buffer. + +‘L s’ (‘magit-log-set-default-arguments’) + + This suffix command sets the default log arguments for buffers of + the same type as that of the current buffer. Other existing + buffers of the same type are not affected because their local + values have already been initialized. + +‘L w’ (‘magit-log-save-default-arguments’) + + This suffix command sets the default log arguments for buffers of + the same type as that of the current buffer, and saves the value + for future sessions. Other existing buffers of the same type are + not affected because their local values have already been + initialized. + +‘L t’ (‘magit-toggle-margin’) + + Show or hide the margin. + + +File: magit.info, Node: Log Buffer, Next: Log Margin, Prev: Refreshing Logs, Up: Logging + +5.3.2 Log Buffer +---------------- + +‘L’ (‘magit-log-refresh-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. See *note + Refreshing Logs::. + +‘q’ (‘magit-log-bury-buffer’) + + Bury the current buffer or the revision buffer in the same frame. + Like ‘magit-mode-bury-buffer’ (which see) but with a negative + prefix argument instead bury the revision buffer, provided it is + displayed in the current frame. + +‘C-c C-b’ (‘magit-go-backward’) + + Move backward in current buffer’s history. + +‘C-c C-f’ (‘magit-go-forward’) + + Move forward in current buffer’s history. + +‘C-c C-n’ (‘magit-log-move-to-parent’) + + Move to a parent of the current commit. By default, this is the + first parent, but a numeric prefix can be used to specify another + parent. + +‘SPC’ (‘magit-diff-show-or-scroll-up’) + + Update the commit or diff buffer for the thing at point. + + Either show the commit or stash at point in the appropriate buffer, + or if that buffer is already being displayed in the current frame + and contains information about that commit or stash, then instead + scroll the buffer up. If there is no commit or stash at point, + then prompt for a commit. + +‘DEL’ (‘magit-diff-show-or-scroll-down’) + + Update the commit or diff buffer for the thing at point. + + Either show the commit or stash at point in the appropriate buffer, + or if that buffer is already being displayed in the current frame + and contains information about that commit or stash, then instead + scroll the buffer down. If there is no commit or stash at point, + then prompt for a commit. + +‘=’ (‘magit-log-toggle-commit-limit’) + + Toggle the number of commits the current log buffer is limited to. + If the number of commits is currently limited, then remove that + limit. Otherwise set it to 256. + +‘+’ (‘magit-log-double-commit-limit’) + + Double the number of commits the current log buffer is limited to. + +‘-’ (‘magit-log-half-commit-limit’) + + Half the number of commits the current log buffer is limited to. + + -- User Option: magit-log-auto-more + + Insert more log entries automatically when moving past the last + entry. Only considered when moving past the last entry with + ‘magit-goto-*-section’ commands. + + -- User Option: magit-log-show-refname-after-summary + + Whether to show the refnames after the commit summaries. This is + useful if you use really long branch names. + + Magit displays references in logs a bit differently from how Git does +it. + + Local branches are blue and remote branches are green. Of course +that depends on the used theme, as do the colors used for other types of +references. The current branch has a box around it, as do remote +branches that are their respective remote’s ‘HEAD’ branch. + + If a local branch and its push-target point at the same commit, then +their names are combined to preserve space and to make that relationship +visible. For example: + + origin/feature + [green][blue-] + + instead of + + feature origin/feature + [blue-] [green-------] + + Also note that while the popup features the ‘--show-signature’ +argument, that won’t actually be used when enabled, because Magit +defaults to use just one line per commit. Instead the commit colorized +to indicate the validity of the signed commit object, using the faces +named ‘magit-signature-*’ (which see). + + For a description of ‘magit-log-margin’ see *note Log Margin::. + + +File: magit.info, Node: Log Margin, Next: Select from Log, Prev: Log Buffer, Up: Logging + +5.3.3 Log Margin +---------------- + +In buffers which show one or more logs, it is possible to show +additional information about each commit in the margin. The options +used to configure the margin are named ‘magit-INFIX-margin’, where INFIX +is the same as in the respective major-mode ‘magit-INFIX-mode’. In +regular log buffers that would be ‘magit-log-margin’. + + -- User Option: magit-log-margin + + This option specifies whether the margin is initially shown in + Magit-Log mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + + • STYLE controls how to format the committer date. It can be + one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. + + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + + • AUTHOR controls whether the name of the author is also shown + by default. + + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + You can change the STYLE and AUTHOR-WIDTH of all ‘magit-INFIX-margin’ +options to the same values by customizing ‘magit-log-margin’ *before* +‘magit’ is loaded. If you do that, then the respective values for the +other options will default to what you have set for that variable. +Likewise if you set INIT in ‘magit-log-margin’ to ‘nil’, then that is +used in the default of all other options. But setting it to ‘t’, i.e. +re-enforcing the default for that option, does not carry to other +options. + +‘L’ (‘magit-margin-popup’) + + This prefix command features the following commands for changing + the appearance of the margin. + + In some buffers that support the margin, "L" is bound to +‘magit-log-refresh-popup’, but that popup features the same commands, +and then some other unrelated commands. + +‘L L’ (‘magit-toggle-margin’) + + This command shows or hides the margin. + +‘L l’ (‘magit-cycle-margin-style’) + + This command cycles the style used for the margin. + +‘L d’ (‘magit-toggle-margin-details’) + + This command shows or hides details in the margin. + + +File: magit.info, Node: Select from Log, Next: Reflog, Prev: Log Margin, Up: Logging + +5.3.4 Select from Log +--------------------- + +When the user has to select a recent commit that is reachable from +‘HEAD’, using regular completion would be inconvenient (because most +humans cannot remember hashes or "HEAD~5", at least not without double +checking). Instead a log buffer is used to select the commit, which has +the advantage that commits are presented in order and with the commit +message. + + Such selection logs are used when selecting the beginning of a rebase +and when selecting the commit to be squashed into. + + In addition to the key bindings available in all log buffers, the +following additional key bindings are available in selection log +buffers: + +‘C-c C-c’ (‘magit-log-select-pick’) + + Select the commit at point and act on it. Call + ‘magit-log-select-pick-function’ with the selected commit as + argument. + +‘C-c C-k’ (‘magit-log-select-quit’) + + Abort selecting a commit, don’t act on any commit. + + -- User Option: magit-log-select-margin + + This option specifies whether the margin is initially shown in + Magit-Log-Select mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + + • STYLE controls how to format the committer date. It can be + one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. + + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + + • AUTHOR controls whether the name of the author is also shown + by default. + + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + +File: magit.info, Node: Reflog, Next: Cherries, Prev: Select from Log, Up: Logging + +5.3.5 Reflog +------------ + +Also see *note (gitman)git-reflog::. + + These reflog commands are available from the log popup. See *note +Logging::. + +‘l r’ (‘magit-reflog-current’) + + Display the reflog of the current branch. + +‘l O’ (‘magit-reflog-other’) + + Display the reflog of a branch or another ref. + +‘l H’ (‘magit-reflog-head’) + + Display the ‘HEAD’ reflog. + + -- User Option: magit-reflog-margin + + This option specifies whether the margin is initially shown in + Magit-Reflog mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + + • STYLE controls how to format the committer date. It can be + one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. + + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + + • AUTHOR controls whether the name of the author is also shown + by default. + + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + +File: magit.info, Node: Cherries, Prev: Reflog, Up: Logging + +5.3.6 Cherries +-------------- + +Cherries are commits that haven’t been applied upstream (yet), and are +usually visualized using a log. Each commit is prefixed with ‘-’ if it +has an equivalent in the upstream and ‘+’ if it does not, i.e. if it is +a cherry. + + The command ‘magit-cherry’ shows cherries for a single branch, but +the references buffer (see *note References Buffer::) can show cherries +for multiple "upstreams" at once. + + Also see *note (gitman)git-reflog::. + +‘Y’ (‘magit-cherry’) + + Show commits that are in a certain branch but that have not been + merged in the upstream branch. + + -- User Option: magit-cherry-margin + + This option specifies whether the margin is initially shown in + Magit-Cherry mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + + • STYLE controls how to format the committer date. It can be + one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. + + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + + • AUTHOR controls whether the name of the author is also shown + by default. + + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + +File: magit.info, Node: Diffing, Next: Ediffing, Prev: Logging, Up: Inspecting + +5.4 Diffing +=========== + +The status buffer contains diffs for the staged and unstaged commits, +but that obviously isn’t enough. The prefix command ‘magit-diff-popup’, +on ‘d’, features several suffix commands, which show a specific diff in +a separate diff buffer. + + Like other popups, the diff popup also features several arguments +that can be changed before invoking one of the suffix commands. +However, in the case of the diff popup, these arguments may be taken +from those currently in use in the current repository’s log buffer, +depending on the value of ‘magit-use-sticky-arguments’ (see *note Popup +Buffers and Prefix Commands::). + + Also see *note (gitman)git-diff::. + +‘d’ (‘magit-diff-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘d d’ (‘magit-diff-dwim’) + + Show changes for the thing at point. + +‘d r’ (‘magit-diff-range’) + + Show differences between two commits. + + RANGE should be a range (A..B or A...B) but can also be a single + commit. If one side of the range is omitted, then it defaults to + ‘HEAD’. If just a commit is given, then changes in the working + tree relative to that commit are shown. + + If the region is active, use the revisions on the first and last + line of the region. With a prefix argument, instead of diffing the + revisions, choose a revision to view changes along, starting at the + common ancestor of both revisions (i.e., use a "..." range). + +‘d w’ (‘magit-diff-working-tree’) + + Show changes between the current working tree and the ‘HEAD’ + commit. With a prefix argument show changes between the working + tree and a commit read from the minibuffer. + +‘d s’ (‘magit-diff-staged’) + + Show changes between the index and the ‘HEAD’ commit. With a + prefix argument show changes between the index and a commit read + from the minibuffer. + +‘d u’ (‘magit-diff-unstaged’) + + Show changes between the working tree and the index. + +‘d p’ (‘magit-diff-paths’) + + Show changes between any two files on disk. + + All of the above suffix commands update the repository’s diff buffer. +The diff popup also features two commands which show differences in +another buffer: + +‘d c’ (‘magit-show-commit’) + + Show the commit at point. If there is no commit at point or with a + prefix argument, prompt for a commit. + +‘d t’ (‘magit-stash-show’) + + Show all diffs of a stash in a buffer. + + Two additional commands that show the diff for the file or blob that +is being visited in the current buffer exists, see *note Minor Mode for +Buffers Visiting Files::. + +* Menu: + +* Refreshing Diffs:: +* Diff Buffer:: +* Diff Options:: +* Revision Buffer:: + + +File: magit.info, Node: Refreshing Diffs, Next: Diff Buffer, Up: Diffing + +5.4.1 Refreshing Diffs +---------------------- + +The prefix command ‘magit-diff-refresh-popup’, on ‘D’, can be used to +change the diff arguments used in the current buffer, without changing +which diff is shown. This works in dedicated diff buffers, but also in +the status buffer. + +‘D’ (‘magit-diff-refresh-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘D g’ (‘magit-diff-refresh’) + + This suffix command sets the local diff arguments for the current + buffer. + +‘D s’ (‘magit-diff-set-default-arguments’) + + This suffix command sets the default diff arguments for buffers of + the same type as that of the current buffer. Other existing + buffers of the same type are not affected because their local + values have already been initialized. + +‘D w’ (‘magit-diff-save-default-arguments’) + + This suffix command sets the default diff arguments for buffers of + the same type as that of the current buffer, and saves the value + for future sessions. Other existing buffers of the same type are + not affected because their local values have already been + initialized. + +‘D t’ (‘magit-diff-toggle-refine-hunk’) + + This command toggles hunk refinement on or off. + +‘D r’ (‘magit-diff-switch-range-type’) + + This command converts the diff range type from "revA..revB" to + "revB...revA", or vice versa. + +‘D f’ (‘magit-diff-flip-revs’) + + This command swaps revisions in the diff range from "revA..revB" to + "revB..revA", or vice versa. + +‘D F’ (‘magit-diff-toggle-file-filter’) + + This command toggles the file restriction of the diffs in the + current buffer, allowing you to quickly switch between viewing all + the changes in the commit and the restricted subset. As a special + case, when this command is called from a log buffer, it toggles the + file restriction in the repository’s revision buffer, which is + useful when you display a revision from a log buffer that is + restricted to a file or files. + + In addition to the above popup, which allows changing any of the +supported arguments, there also exist some commands which change a +particular argument. + +‘-’ (‘magit-diff-less-context’) + + This command decreases the context for diff hunks by COUNT lines. + +‘+’ (‘magit-diff-more-context’) + + This command increases the context for diff hunks by COUNT lines. + +‘0’ (‘magit-diff-default-context’) + + This command resets the context for diff hunks to the default + height. + + The following commands quickly change what diff is being displayed +without having to using one of the diff popups. + +‘C-c C-d’ (‘magit-diff-while-committing’) + + While committing, this command shows the changes that are about to + be committed. While amending, invoking the command again toggles + between showing just the new changes or all the changes that will + be committed. + + This binding is available in the diff buffer as well as the commit + message buffer. + +‘C-c C-b’ (‘magit-go-backward’) + + This command moves backward in current buffer’s history. + +‘C-c C-f’ (‘magit-go-forward’) + + This command moves forward in current buffer’s history. + + +File: magit.info, Node: Diff Buffer, Next: Diff Options, Prev: Refreshing Diffs, Up: Diffing + +5.4.2 Diff Buffer +----------------- + +These commands are available in diff buffers. + +‘RET’ (‘magit-diff-visit-file’) + + From a diff, visit the corresponding file at the appropriate + position. + + If the diff shows changes in the worktree, the index, or ‘HEAD’, + then visit the actual file. Otherwise, when the diff is about an + older commit or a range, then visit the appropriate blob. + + If point is on a removed line, then visit the blob for the first + parent of the commit which removed that line, i.e. the last commit + where that line still existed. Otherwise visit the blob for the + commit whose changes are being shown. + + Interactively, when the file or blob to be displayed is already + being displayed in another window of the same frame, then just + select that window and adjust point. Otherwise, or with a prefix + argument, display the buffer in another window. The meaning of the + prefix argument can be inverted or further modified using the + option ‘magit-display-file-buffer-function’. + + Non-interactively the optional OTHER-WINDOW argument is taken + literally. DISPLAY-FN can be used to specify the display function + explicitly, in which case OTHER-WINDOW is ignored. + + The optional FORCE-WORKTREE means to force visiting the worktree + version of the file. To do this interactively use the command + ‘magit-diff-visit-file-worktree’ instead. + + -- User Option: magit-diff-visit-previous-blob + + This option controls whether ‘magit-diff-visit-file’ may visit the + previous blob. When this is ‘t’ and point is on a removed line in + a diff for a committed change, then ‘magit-diff-visit-file’ visits + the blob from the last revision which still had that line. + + Currently this is only supported for committed changes, for staged + and unstaged changes ‘magit-diff-visit-file’ always visits the file + in the working tree. + +‘C-’ (‘magit-diff-visit-file-worktree’) + + From a diff, visit the corresponding file at the appropriate + position. + + When the file is already being displayed in another window of the + same frame, then just select that window and adjust point. With a + prefix argument also display in another window. + + The actual file in the worktree is visited. The positions in the + hunk headers get less useful the "older" the changes are, and as a + result, jumping to the appropriate position gets less reliable. + + Also see ‘magit-diff-visit-file’, which visits the respective blob, + unless the diff shows changes in the worktree, the index, or + ‘HEAD’. + + -- Command: magit-diff-visit-file-other-window + + From a diff, visit the corresponding file at the appropriate + position in another window. + +‘C-c C-t’ (‘magit-diff-trace-definition’) + + From a diff, show log for the definition at point. + + -- User Option: magit-log-trace-definition-function + + The function used by ‘magit-log-trace-definition’ to determine the + function at point. For major-modes that have special needs, you + could set that using the mode’s hook. + +‘C-c C-e’ (‘magit-diff-edit-hunk-commit’) + + From a hunk, edit the respective commit and visit the file. + + First visit the file being modified by the hunk at the correct + location using ‘magit-diff-visit-file’. This actually visits a + blob. When point is on a diff header, not within an individual + hunk, then this visits the blob the first hunk is about. + + Then invoke ‘magit-edit-line-commit’, which uses an interactive + rebase to make the commit editable, or if that is not possible + because the commit is not reachable from ‘HEAD’ by checking out + that commit directly. This also causes the actual worktree file to + be visited. + + Neither the blob nor the file buffer are killed when finishing the + rebase. If that is undesirable, then it might be better to use + ‘magit-rebase-edit-command’ instead of this command. + +‘j’ (‘magit-jump-to-diffstat-or-diff’) + + Jump to the diffstat or diff. When point is on a file inside the + diffstat section, then jump to the respective diff section. + Otherwise, jump to the diffstat section or a child thereof. + +‘SPC’ (‘scroll-up’) + + Scroll text upward. + +‘DEL’ (‘scroll-down’) + + Scroll text downward. + + +File: magit.info, Node: Diff Options, Next: Revision Buffer, Prev: Diff Buffer, Up: Diffing + +5.4.3 Diff Options +------------------ + + -- User Option: magit-diff-refine-hunk + + Whether to show word-granularity differences within diff hunks. + + • ‘nil’ never show fine differences. + + • ‘t’ show fine differences for the current diff hunk only. + + • ‘all’ show fine differences for all displayed diff hunks. + + -- User Option: magit-diff-adjust-tab-width + + Whether to adjust the width of tabs in diffs. + + Determining the correct width can be expensive if it requires + opening large and/or many files, so the widths are cached in the + variable ‘magit-diff--tab-width-cache’. Set that to nil to + invalidate the cache. + + • ‘nil’ Never adjust tab width. Use ‘tab-width’s value from the + Magit buffer itself instead. + + • ‘t’ If the corresponding file-visiting buffer exits, then use + ‘tab-width’’s value from that buffer. Doing this is cheap, so + this value is used even if a corresponding cache entry exists. + + • ‘always’ If there is no such buffer, then temporarily visit + the file to determine the value. + + • NUMBER Like ‘always’, but don’t visit files larger than NUMBER + bytes. + + -- User Option: magit-diff-paint-whitespace + + Specify where to highlight whitespace errors. + + See ‘magit-diff-highlight-trailing’, + ‘magit-diff-highlight-indentation’. The symbol ‘t’ means in all + diffs, ‘status’ means only in the status buffer, and nil means + nowhere. + + -- User Option: magit-diff-highlight-trailing + + Whether to highlight whitespace at the end of a line in diffs. + Used only when ‘magit-diff-paint-whitespace’ is non-nil. + + -- User Option: magit-diff-highlight-indentation + + Highlight the "wrong" indentation style. Used only when + ‘magit-diff-paint-whitespace’ is non-nil. + + The value is a list of cons cells. The car is a regular + expression, and the cdr is the value that applies to repositories + whose directory matches the regular expression. If more than one + element matches, then the *last* element in the list applies. The + default value should therefore come first in the list. + + If the value is ‘tabs’, highlight indentation with tabs. If the + value is an integer, highlight indentation with at least that many + spaces. Otherwise, highlight neither. + + -- User Option: magit-diff-hide-trailing-cr-characters + + Whether to hide ^M characters at the end of a line in diffs. + + -- User Option: magit-diff-highlight-hunk-region-functions + + This option specifies the functions used to highlight the + hunk-internal region. + + ‘magit-diff-highlight-hunk-region-dim-outside’ overlays the outside + of the hunk internal selection with a face that causes the added + and removed lines to have the same background color as context + lines. This function should not be removed from the value of this + option. + + ‘magit-diff-highlight-hunk-region-using-overlays’ and + ‘magit-diff-highlight-hunk-region-using-underline’ emphasize the + region by placing delimiting horizontal lines before and after it. + Both of these functions have glitches which cannot be fixed due to + limitations of Emacs’ display engine. For more information see + ff. + + Instead of, or in addition to, using delimiting horizontal lines, + to emphasize the boundaries, you may which to emphasize the text + itself, using ‘magit-diff-highlight-hunk-region-using-face’. + + In terminal frames it’s not possible to draw lines as the overlay + and underline variants normally do, so there they fall back to + calling the face function instead. + + -- User Option: magit-diff-unmarked-lines-keep-foreground + + This option controls whether added and removed lines outside the + hunk-internal region only lose their distinct background color or + also the foreground color. Whether the outside of the region is + dimmed at all depends on + ‘magit-diff-highlight-hunk-region-functions’. + + +File: magit.info, Node: Revision Buffer, Prev: Diff Options, Up: Diffing + +5.4.4 Revision Buffer +--------------------- + + -- User Option: magit-revision-insert-related-refs + + Whether to show related branches in revision buffers. + + • ‘nil’ Don’t show any related branches. + + • ‘t’ Show related local branches. + + • ‘all’ Show related local and remote branches. + + • ‘mixed’ Show all containing branches and local merged + branches. + + -- User Option: magit-revision-show-gravatars + + Whether to show gravatar images in revision buffers. + + If ‘nil’, then don’t insert any gravatar images. If ‘t’, then + insert both images. If ‘author’ or ‘committer’, then insert only + the respective image. + + If you have customized the option ‘magit-revision-header-format’ + and want to insert the images then you might also have to specify + where to do so. In that case the value has to be a cons-cell of + two regular expressions. The car specifies where to insert the + author’s image. The top half of the image is inserted right after + the matched text, the bottom half on the next line in the same + column. The cdr specifies where to insert the committer’s image, + accordingly. Either the car or the cdr may be nil." + + -- User Option: magit-revision-use-hash-sections + + Whether to turn hashes inside the commit message into sections. + + If non-nil, then hashes inside the commit message are turned into + ‘commit’ sections. There is a trade off to be made between + performance and reliability: + + • ‘slow’ calls git for every word to be absolutely sure. + + • ‘quick’ skips words less than seven characters long. + + • ‘quicker’ additionally skips words that don’t contain a + number. + + • ‘quickest’ uses all words that are at least seven characters + long and which contain at least one number as well as at least + one letter. + + If nil, then no hashes are turned into sections, but you can still + visit the commit at point using "RET". + + The diffs shown in the revision buffer may be automatically +restricted to a subset of the changed files. If the revision buffer is +displayed from a log buffer, the revision buffer will share the same +file restriction as that log buffer (also see the command +‘magit-diff-toggle-file-filter’). Note, however, that the log’s file +restriction will be ignored when ‘magit-log-arguments’ includes +‘--follow’. In this case, the ‘-u’ argument of the log popup can be +used to show the file-restricted diffs inline. + + If the revision buffer is not displayed from a log buffer, the file +restriction is determined by the file restriction in the repository’s +diff buffer, if it exists, and the value of the option +‘magit-use-sticky-arguments’. + + +File: magit.info, Node: Ediffing, Next: References Buffer, Prev: Diffing, Up: Inspecting + +5.5 Ediffing +============ + +This section describes how to enter Ediff from Magit buffers. For +information on how to use Ediff itself, see *note (ediff)Top::. + +‘e’ (‘magit-ediff-dwim’) + + Compare, stage, or resolve using Ediff. + + This command tries to guess what file, and what commit or range the + user wants to compare, stage, or resolve using Ediff. It might + only be able to guess either the file, or range/commit, in which + case the user is asked about the other. It might not always guess + right, in which case the appropriate ‘magit-ediff-*’ command has to + be used explicitly. If it cannot read the user’s mind at all, then + it asks the user for a command to run. + +‘E’ (‘magit-ediff-popup’) + + This prefix command shows the following suffix commands in a popup + buffer. + +‘E r’ (‘magit-ediff-compare’) + + Compare two revisions of a file using Ediff. + + If the region is active, use the revisions on the first and last + line of the region. With a prefix argument, instead of diffing the + revisions, choose a revision to view changes along, starting at the + common ancestor of both revisions (i.e., use a "..." range). + +‘E m’ (‘magit-ediff-resolve’) + + Resolve outstanding conflicts in a file using Ediff, defaulting to + the file at point. + + Provided that the value of ‘merge.conflictstyle’ is ‘diff3’, you + can view the file’s merge-base revision using ‘/’ in the Ediff + control buffer. + + In the rare event that you want to manually resolve all conflicts, + including those already resolved by Git, use + ‘ediff-merge-revisions-with-ancestor’. + +‘E s’ (‘magit-ediff-stage’) + + Stage and unstage changes to a file using Ediff, defaulting to the + file at point. + +‘E u’ (‘magit-ediff-show-unstaged’) + + Show unstaged changes to a file using Ediff. + +‘E i’ (‘magit-ediff-show-staged’) + + Show staged changes to a file using Ediff. + +‘E w’ (‘magit-ediff-show-working-tree’) + + Show changes in a file between ‘HEAD’ and working tree using Ediff. + +‘E c’ (‘magit-ediff-show-commit’) + + Show changes to a file introduced by a commit using Ediff. + +‘E z’ (‘magit-ediff-show-stash’) + + Show changes to a file introduced by a stash using Ediff. + + -- User Option: magit-ediff-dwim-show-on-hunks + + This option controls what command ‘magit-ediff-dwim’ calls when + point is on uncommitted hunks. When nil, always run + ‘magit-ediff-stage’. Otherwise, use ‘magit-ediff-show-staged’ and + ‘magit-ediff-show-unstaged’ to show staged and unstaged changes, + respectively. + + -- User Option: magit-ediff-show-stash-with-index + + This option controls whether ‘magit-ediff-show-stash’ includes a + buffer containing the file’s state in the index at the time the + stash was created. This makes it possible to tell which changes in + the stash were staged. + + -- User Option: magit-ediff-quit-hook + + This hook is run after quitting an Ediff session that was created + using a Magit command. The hook functions are run inside the Ediff + control buffer, and should not change the current buffer. + + This is similar to ‘ediff-quit-hook’ but takes the needs of Magit + into account. The regular ‘ediff-quit-hook’ is ignored by Ediff + sessions that were created using a Magit command. + + +File: magit.info, Node: References Buffer, Next: Bisecting, Prev: Ediffing, Up: Inspecting + +5.6 References Buffer +===================== + +‘y’ (‘magit-show-refs-popup’) + + List and compare references in a dedicated buffer. By default all + refs are compared with ‘HEAD’, but with a prefix argument this + command instead acts as a prefix command and shows the following + suffix commands along with the appropriate infix arguments in a + popup buffer. + +‘y y’ (‘magit-show-refs-head’) + + List and compare references in a dedicated buffer. Refs are + compared with ‘HEAD’. + +‘y c’ (‘magit-show-refs-current’) + + List and compare references in a dedicated buffer. Refs are + compared with the current branch or ‘HEAD’ if it is detached. + +‘y o’ (‘magit-show-refs’) + + List and compare references in a dedicated buffer. Refs are + compared with a branch read from the user. + + -- User Option: magit-refs-show-commit-count + + Whether to show commit counts in Magit-Refs mode buffers. + + • ‘all’ Show counts for branches and tags. + + • ‘branch’ Show counts for branches only. + + • ‘nil’ Never show counts. + + The default is ‘nil’ because anything else can be very expensive. + + -- User Option: magit-refs-pad-commit-counts + + Whether to pad all commit counts on all sides in Magit-Refs mode + buffers. + + If this is nil, then some commit counts are displayed right next to + one of the branches that appear next to the count, without any + space in between. This might look bad if the branch name faces + look too similar to ‘magit-dimmed’. + + If this is non-nil, then spaces are placed on both sides of all + commit counts. + + -- User Option: magit-refs-show-remote-prefix + + Whether to show the remote prefix in lists of remote branches. + + Showing the prefix is redundant because the name of the remote is + already shown in the heading preceding the list of its branches. + + -- User Option: magit-refs-primary-column-width + + Width of the primary column in ‘magit-refs-mode’ buffers. The + primary column is the column that contains the name of the branch + that the current row is about. + + If this is an integer, then the column is that many columns wide. + Otherwise it has to be a cons-cell of two integers. The first + specifies the minimal width, the second the maximal width. In that + case the actual width is determined using the length of the names + of the shown local branches. (Remote branches and tags are not + taken into account when calculating to optimal width.) + + -- User Option: magit-refs-focus-column-width + + Width of the focus column in ‘magit-refs-mode’ buffers. + + The focus column is the first column, which marks one branch + (usually the current branch) as the focused branch using ‘*’ or + ‘@’. For each other reference, this column optionally shows how + many commits it is ahead of the focused branch and ‘<’, or if it + isn’t ahead then the commits it is behind and ‘>’, or if it isn’t + behind either, then a ‘=’. + + This column may also display only ‘*’ or ‘@’ for the focused + branch, in which case this option is ignored. Use ‘L v’ to change + the verbosity of this column. + + -- User Option: magit-refs-margin + + This option specifies whether the margin is initially shown in + Magit-Refs mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + + • STYLE controls how to format the committer date. It can be + one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. + + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + + • AUTHOR controls whether the name of the author is also shown + by default. + + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + -- User Option: magit-refs-margin-for-tags + + This option specifies whether to show information about tags in the + margin. This is disabled by default because it is slow if there + are many tags. + + The following variables control how individual refs are displayed. +If you change one of these variables (especially the "%c" part), then +you should also change the others to keep things aligned. The following +%-sequences are supported: + + • ‘%a’ Number of commits this ref has over the one we compare to. + + • ‘%b’ Number of commits the ref we compare to has over this one. + + • ‘%c’ Number of commits this ref has over the one we compare to. + For the ref which all other refs are compared this is instead "@", + if it is the current branch, or "#" otherwise. + + • ‘%C’ For the ref which all other refs are compared this is "@", if + it is the current branch, or "#" otherwise. For all other refs " + ". + + • ‘%h’ Hash of this ref’s tip. + + • ‘%m’ Commit summary of the tip of this ref. + + • ‘%n’ Name of this ref. + + • ‘%u’ Upstream of this local branch. + + • ‘%U’ Upstream of this local branch and additional local vs. + upstream information. + + -- User Option: magit-refs-filter-alist + + This alist controls which tags and branches are omitted from being + displayed in ‘magit-refs-mode’ buffers. If it is ‘nil’, then all + refs are displayed (subject to ‘magit-refs-sections-hook’). + + All keys are tried in order until one matches. Then its value is + used and subsequent elements are ignored. If the value is non-nil, + then the reference is displayed, otherwise it is not. If no + element matches, then the reference is displayed. + + A key can either be a regular expression that the refname has to + match, or a function that takes the refname as only argument and + returns a boolean. Contrary to how they are displayed in the + buffer, for comparison each tag begins with "tags/" and each remote + branch with "/". + +‘RET’ (‘magit-visit-ref’) + + This command visits the reference or revision at point in another + buffer. If there is no revision at point or with a prefix argument + then it prompts for a revision. + + This command behaves just like ‘magit-show-commit’ as described + above, except if point is on a reference in a ‘magit-refs-mode’ + buffer, in which case the behavior may be different, but only if + you have customized the option ‘magit-visit-ref-behavior’. + + -- User Option: magit-visit-ref-behavior + + This option controls how ‘magit-visit-ref’ behaves in + ‘magit-refs-mode’ buffers. + + By default ‘magit-visit-ref’ behaves like ‘magit-show-commit’, in + all buffers, including ‘magit-refs-mode’ buffers. When the type of + the section at point is ‘commit’ then "RET" is bound to + ‘magit-show-commit’, and when the type is either ‘branch’ or ‘tag’ + then it is bound to ‘magit-visit-ref’. + + "RET" is one of Magit’s most essential keys and at least by default + it should behave consistently across all of Magit, especially + because users quickly learn that it does something very harmless; + it shows more information about the thing at point in another + buffer. + + However "RET" used to behave differently in ‘magit-refs-mode’ + buffers, doing surprising things, some of which cannot really be + described as "visit this thing". If you’ve grown accustomed this + behavior, you can restore it by adding one or more of the below + symbols to the value of this option. But keep in mind that by + doing so you don’t only introduce inconsistencies, you also lose + some functionality and might have to resort to ‘M-x + magit-show-commit’ to get it back. + + ‘magit-visit-ref’ looks for these symbols in the order in which + they are described here. If the presence of a symbol applies to + the current situation, then the symbols that follow do not affect + the outcome. + + • ‘focus-on-ref’ + + With a prefix argument update the buffer to show commit counts + and lists of cherry commits relative to the reference at point + instead of relative to the current buffer or ‘HEAD’. + + Instead of adding this symbol, consider pressing "C-u y o + RET". + + • ‘create-branch’ + + If point is on a remote branch, then create a new local branch + with the same name, use the remote branch as its upstream, and + then check out the local branch. + + Instead of adding this symbol, consider pressing "b c RET + RET", like you would do in other buffers. + + • ‘checkout-any’ + + Check out the reference at point. If that reference is a tag + or a remote branch, then this results in a detached ‘HEAD’. + + Instead of adding this symbol, consider pressing "b b RET", + like you would do in other buffers. + + • ‘checkout-branch’ + + Check out the local branch at point. + + Instead of adding this symbol, consider pressing "b b RET", + like you would do in other buffers. + +* Menu: + +* References Sections:: + + +File: magit.info, Node: References Sections, Up: References Buffer + +5.6.1 References Sections +------------------------- + +The contents of references buffers is controlled using the hook +‘magit-refs-sections-hook’. See *note Section Hooks:: to learn about +such hooks and how to customize them. All of the below functions are +members of the default value. Note that it makes much less sense to +customize this hook than it does for the respective hook used for the +status buffer. + + -- User Option: magit-refs-sections-hook + + Hook run to insert sections into a references buffer. + + -- Function: magit-insert-local-branches + + Insert sections showing all local branches. + + -- Function: magit-insert-remote-branches + + Insert sections showing all remote-tracking branches. + + -- Function: magit-insert-tags + + Insert sections showing all tags. + + +File: magit.info, Node: Bisecting, Next: Visiting Blobs, Prev: References Buffer, Up: Inspecting + +5.7 Bisecting +============= + +Also see *note (gitman)git-bisect::. + +‘B’ (‘magit-bisect-popup’) + + This prefix command shows the following suffix commands in a popup + buffer. + + When bisecting is not in progress, then the popup buffer features the +following commands. + +‘B B’ (‘magit-bisect-start’) + + Start a bisect session. + + Bisecting a bug means to find the commit that introduced it. This + command starts such a bisect session by asking for a known good and + a bad commit. + +‘B s’ (‘magit-bisect-run’) + + Bisect automatically by running commands after each step. + + When bisecting is in progress, then the popup buffer features these +commands instead. + +‘B b’ (‘magit-bisect-bad’) + + Mark the current commit as bad. Use this after you have asserted + that the commit does contain the bug in question. + +‘B g’ (‘magit-bisect-good’) + + Mark the current commit as good. Use this after you have asserted + that the commit does not contain the bug in question. + +‘B k’ (‘magit-bisect-skip’) + + Skip the current commit. Use this if for some reason the current + commit is not a good one to test. This command lets Git choose a + different one. + +‘B r’ (‘magit-bisect-reset’) + + After bisecting, cleanup bisection state and return to original + ‘HEAD’. + + By default the status buffer shows information about the ongoing +bisect session. + + -- User Option: magit-bisect-show-graph + + This option controls whether a graph is displayed for the log of + commits that still have to be bisected. + + +File: magit.info, Node: Visiting Blobs, Next: Blaming, Prev: Bisecting, Up: Inspecting + +5.8 Visiting Blobs +================== + +‘M-x magit-find-file’ (‘magit-find-file’) + + View FILE from REV. Switch to a buffer visiting blob REV:FILE, + creating one if none already exists. + +‘M-x magit-find-file-other-window’ (‘magit-find-file-other-window’) + + View FILE from REV, in another window. Like ‘magit-find-file’, but + create a new window or reuse an existing one. + + +File: magit.info, Node: Blaming, Prev: Visiting Blobs, Up: Inspecting + +5.9 Blaming +=========== + +Also see *note (gitman)git-blame::. + + To start blaming you can use ‘M-x’ in a file-visiting buffer to +invoke one of the following commands. You can also invoke these +commands using the blame popup, which is available on ‘b’ in +file-visiting buffers that already contain blame information and, also +on ‘b’, in all blob-visiting buffers. You can also enter the blame +popup from the file popup, which is available on ‘C-c M-g’, provided +‘magit-file-mode’ is enabled, see *note Minor Mode for Buffers Visiting +Files::. + + -- Command: magit-blame-addition + + This command augments each line or chunk of lines in the current + file- or blob-visiting buffer with information about what commits + last touched these lines. + + If the buffer visits a revision of that file, then history up to + that revision is considered. Otherwise, the file’s full history is + considered, including uncommitted changes. + + If Magit-Blame mode is already turned on in the current buffer then + blaming is done recursively, by visiting REVISION:FILE (using + ‘magit-find-file’), where REVISION is a parent of the revision that + added the current line or chunk of lines. + + -- Command: magit-blame-echo + + This command is like ‘magit-blame-addition’ except that it doesn’t + turn on ‘read-only-mode’ and that it initially uses the + visualization style specified by option ‘magit-blame-echo-style’. + + -- Command: magit-blame-removal + + This command augments each line or chunk of lines in the current + blob-visiting buffer with information about the revision that + removes it. It cannot be used in file-visiting buffers. + + Like ‘magit-blame-addition’, this command can be used recursively. + + -- Command: magit-blame-reverse + + This command augments each line or chunk of lines in the current + file- or blob-visiting buffer with information about the last + revision in which a line still existed. + + Like ‘magit-blame-addition’, this command can be used recursively. + + The following key bindings are available when Magit-Blame mode is +enabled and Read-Only mode is not enabled. These commands are also +available in other buffers; here only the behavior is described that is +relevant in file-visiting buffers that are being blamed. + +‘RET’ (‘magit-show-commit’) + + This command shows the commit that last touched the line at point. + +‘SPC’ (‘magit-diff-show-or-scroll-up’) + + This command updates the commit buffer. + + This either shows the commit that last touched the line at point in + the appropriate buffer, or if that buffer is already being + displayed in the current frame and if that buffer contains + information about that commit, then the buffer is scrolled up + instead. + +‘DEL’ (‘magit-diff-show-or-scroll-down’) + + This command updates the commit buffer. + + This either shows the commit that last touched the line at point in + the appropriate buffer, or if that buffer is already being + displayed in the current frame and if that buffer contains + information about that commit, then the buffer is scrolled down + instead. + + The following key bindings are available when Magit-Blame mode is +enabled and Read-Only mode is not enabled. + +‘b’ (‘magit-blame-popup’) + + This prefix command shows the above suffix command along with the + appropriate infix arguments in a popup buffer. + +‘n’ (‘magit-blame-next-chunk’) + + This command moves to the next chunk. + +‘N’ (‘magit-blame-next-chunk-same-commit’) + + This command moves to the next chunk from the same commit. + +‘p’ (‘magit-blame-previous-chunk’) + + This command moves to the previous chunk. + +‘P’ (‘magit-blame-previous-chunk-same-commit’) + + This command moves to the previous chunk from the same commit. + +‘q’ (‘magit-blame-quit’) + + This command turns off Magit-Blame mode. If the buffer was created + during a recursive blame, then it also kills the buffer. + +‘M-w’ (‘magit-blame-copy-hash’) + + This command saves the hash of the current chunk’s commit to the + kill ring. + + When the region is active, the command saves the region’s content + instead of the hash, like ‘kill-ring-save’ would. + +‘c’ (‘magit-blame-cycle-style’) + + This command changes how blame information is visualized in the + current buffer by cycling through the styles specified using the + option ‘magit-blame-styles’. + + Blaming is also controlled using the following options. + + -- User Option: magit-blame-styles + + This option defines a list of styles used to visualize blame + information. For now see its doc-string to learn more. + + -- User Option: magit-blame-echo-style + + This option specifies the blame visualization style used by the + command ‘magit-blame-echo’. This must be a symbol that is used as + the identifier for one of the styles defined in + ‘magit-blame-styles’. + + -- User Option: magit-blame-time-format + + This option specifies the format string used to display times when + showing blame information. + + -- User Option: magit-blame-read-only + + This option controls whether blaming a buffer also makes + temporarily read-only. + + -- User Option: magit-blame-disable-modes + + This option lists incompatible minor-modes that should be disabled + temporarily when a buffer contains blame information. They are + enabled again when the buffer no longer shows blame information. + + -- User Option: magit-blame-goto-chunk-hook + + This hook is run when moving between chunks. + + +File: magit.info, Node: Manipulating, Next: Transferring, Prev: Inspecting, Up: Top + +6 Manipulating +************** + +* Menu: + +* Repository Setup:: +* Staging and Unstaging:: +* Applying:: +* Committing:: +* Branching:: +* Merging:: +* Resolving Conflicts:: +* Rebasing:: +* Cherry Picking:: +* Resetting:: +* Stashing:: + + +File: magit.info, Node: Repository Setup, Next: Staging and Unstaging, Up: Manipulating + +6.1 Repository Setup +==================== + +‘M-x magit-init’ (‘magit-init’) + + This command initializes a repository and then shows the status + buffer for the new repository. + + If the directory is below an existing repository, then the user has + to confirm that a new one should be created inside. If the + directory is the root of the existing repository, then the user has + to confirm that it should be reinitialized. + +‘M-x magit-clone’ (‘magit-clone’) + + This command clones a repository and then shows the status buffer + for the new repository. + + The user is queried for a remote url and a local directory. + + -- User Option: magit-clone-set-remote.pushDefault + + Whether to set the value of ‘remote.pushDefault’ after cloning. + + If ‘t’, then set without asking. If ‘nil’, then don’t set. If + ‘ask’, then ask the user every time she clones a repository. + + +File: magit.info, Node: Staging and Unstaging, Next: Applying, Prev: Repository Setup, Up: Manipulating + +6.2 Staging and Unstaging +========================= + +Like Git, Magit can of course stage and unstage complete files. Unlike +Git, it also allows users to gracefully un-/stage individual hunks and +even just part of a hunk. To stage individual hunks and parts of hunks +using Git directly, one has to use the very modal and rather clumsy +interface of a ‘git add --interactive’ session. + + With Magit, on the other hand, one can un-/stage individual hunks by +just moving point into the respective section inside a diff displayed in +the status buffer or a separate diff buffer and typing ‘s’ or ‘u’. To +operate on just parts of a hunk, mark the changes that should be +un-/staged using the region and then press the same key that would be +used to un-/stage. To stage multiple files or hunks at once use a +region that starts inside the heading of such a section and ends inside +the heading of a sibling section of the same type. + + Besides staging and unstaging, Magit also provides several other +"apply variants" that can also operate on a file, multiple files at +once, a hunk, multiple hunks at once, and on parts of a hunk. These +apply variants are described in the next section. + + You can also use Ediff to stage and unstage. See *note Ediffing::. + +‘s’ (‘magit-stage’) + + Add the change at point to the staging area. + + With a prefix argument and an untracked file (or files) at point, + stage the file but not its content. This makes it possible to + stage only a subset of the new file’s changes. + +‘S’ (‘magit-stage-modified’) + + Stage all changes to files modified in the worktree. Stage all new + content of tracked files and remove tracked files that no longer + exist in the working tree from the index also. With a prefix + argument also stage previously untracked (but not ignored) files. + +‘u’ (‘magit-unstage’) + + Remove the change at point from the staging area. + + Only staged changes can be unstaged. But by default this command + performs an action that is somewhat similar to unstaging, when it + is called on a committed change: it reverses the change in the + index but not in the working tree. + +‘U’ (‘magit-unstage-all’) + + Remove all changes from the staging area. + + -- User Option: magit-unstage-committed + + This option controls whether ‘magit-unstage’ "unstages" committed + changes by reversing them in the index but not the working tree. + The alternative is to raise an error. + +‘M-x magit-reverse-in-index’ (‘magit-reverse-in-index’) + + This command reverses the committed change at point in the index + but not the working tree. By default no key is bound directly to + this command, but it is indirectly called when ‘u’ + (‘magit-unstage’) is pressed on a committed change. + + This allows extracting a change from ‘HEAD’, while leaving it in + the working tree, so that it can later be committed using a + separate commit. A typical workflow would be: + + • Optionally make sure that there are no uncommitted changes. + + • Visit the ‘HEAD’ commit and navigate to the change that should + not have been included in that commit. + + • Type ‘u’ (‘magit-unstage’) to reverse it in the index. This + assumes that ‘magit-unstage-committed-changes’ is non-nil. + + • Type ‘c e’ to extend ‘HEAD’ with the staged changes, including + those that were already staged before. + + • Optionally stage the remaining changes using ‘s’ or ‘S’ and + then type ‘c c’ to create a new commit. + +‘M-x magit-reset-index’ (‘magit-reset-index’) + + Reset the index to some commit. The commit is read from the user + and defaults to the commit at point. If there is no commit at + point, then it defaults to ‘HEAD’. + +* Menu: + +* Staging from File-Visiting Buffers:: + + +File: magit.info, Node: Staging from File-Visiting Buffers, Up: Staging and Unstaging + +6.2.1 Staging from File-Visiting Buffers +---------------------------------------- + +Fine-grained un-/staging has to be done from the status or a diff +buffer, but it’s also possible to un-/stage all changes made to the file +visited in the current buffer right from inside that buffer. + +‘M-x magit-stage-file’ (‘magit-stage-file’) + + When invoked inside a file-visiting buffer, then stage all changes + to that file. In a Magit buffer, stage the file at point if any. + Otherwise prompt for a file to be staged. With a prefix argument + always prompt the user for a file, even in a file-visiting buffer + or when there is a file section at point. + +‘M-x magit-unstage-file’ (‘magit-unstage-file’) + + When invoked inside a file-visiting buffer, then unstage all + changes to that file. In a Magit buffer, unstage the file at point + if any. Otherwise prompt for a file to be unstaged. With a prefix + argument always prompt the user for a file, even in a file-visiting + buffer or when there is a file section at point. + + +File: magit.info, Node: Applying, Next: Committing, Prev: Staging and Unstaging, Up: Manipulating + +6.3 Applying +============ + +Magit provides several "apply variants": stage, unstage, discard, +reverse, and "regular apply". At least when operating on a hunk they +are all implemented using ‘git apply’, which is why they are called +"apply variants". + + • Stage. Apply a change from the working tree to the index. The + change also remains in the working tree. + + • Unstage. Remove a change from the index. The change remains in + the working tree. + + • Discard. On a staged change, remove it from the working tree and + the index. On an unstaged change, remove it from the working tree + only. + + • Reverse. Reverse a change in the working tree. Both committed and + staged changes can be reversed. Unstaged changes cannot be + reversed. Discard them instead. + + • Apply. Apply a change to the working tree. Both committed and + staged changes can be applied. Unstaged changes cannot be applied + - as they already have been applied. + + The previous section described the staging and unstaging commands. +What follows are the commands which implement the remaining apply +variants. + +‘a’ (‘magit-apply’) + + Apply the change at point to the working tree. + + With a prefix argument fallback to a 3-way merge. Doing so causes + the change to be applied to the index as well. + +‘k’ (‘magit-discard’) + + Remove the change at point from the working tree. + +‘v’ (‘magit-reverse’) + + Reverse the change at point in the working tree. + + With a prefix argument fallback to a 3-way merge. Doing so causes + the change to be applied to the index as well. + + With a prefix argument all apply variants attempt a 3-way merge when +appropriate (i.e. when ‘git apply’ is used internally). + + +File: magit.info, Node: Committing, Next: Branching, Prev: Applying, Up: Manipulating + +6.4 Committing +============== + +When the user initiates a commit, Magit calls ‘git commit’ without any +arguments, so Git has to get it from the user. It creates the file +‘.git/COMMIT_EDITMSG’ and then opens that file in an editor. Magit +arranges for that editor to be the Emacsclient. Once the user finishes +the editing session, the Emacsclient exits and Git creates the commit +using the file’s content as message. + +* Menu: + +* Initiating a Commit:: +* Editing Commit Messages:: + + +File: magit.info, Node: Initiating a Commit, Next: Editing Commit Messages, Up: Committing + +6.4.1 Initiating a Commit +------------------------- + +Also see *note (gitman)git-commit::. + +‘c’ (‘magit-commit-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘c c’ (‘magit-commit-create’) + + Create a new commit on ‘HEAD’. With a prefix argument amend to the + commit at ‘HEAD’ instead. + +‘c a’ (‘magit-commit-amend’) + + Amend the last commit. + +‘c e’ (‘magit-commit-extend’) + + Amend the last commit, without editing the message. With a prefix + argument keep the committer date, otherwise change it. The option + ‘magit-commit-extend-override-date’ can be used to inverse the + meaning of the prefix argument. + + Non-interactively respect the optional OVERRIDE-DATE argument and + ignore the option. + +‘c w’ (‘magit-commit-reword’) + + Reword the last commit, ignoring staged changes. With a prefix + argument keep the committer date, otherwise change it. The option + ‘magit-commit-reword-override-date’ can be used to inverse the + meaning of the prefix argument. + + Non-interactively respect the optional OVERRIDE-DATE argument and + ignore the option. + +‘c f’ (‘magit-commit-fixup’) + + Create a fixup commit. + + With a prefix argument the target commit has to be confirmed. + Otherwise the commit at point may be used without confirmation + depending on the value of option ‘magit-commit-squash-confirm’. + +‘c F’ (‘magit-commit-instant-fixup’) + + Create a fixup commit and instantly rebase. + +‘c s’ (‘magit-commit-squash’) + + Create a squash commit, without editing the squash message. + + With a prefix argument the target commit has to be confirmed. + Otherwise the commit at point may be used without confirmation + depending on the value of option ‘magit-commit-squash-confirm’. + +‘c S’ (‘magit-commit-instant-squash’) + + Create a squash commit and instantly rebase. + +‘c A’ (‘magit-commit-augment’) + + Create a squash commit, editing the squash message. + + With a prefix argument the target commit has to be confirmed. + Otherwise the commit at point may be used without confirmation + depending on the value of option ‘magit-commit-squash-confirm’. + + -- User Option: magit-commit-ask-to-stage + + Whether to ask to stage all unstaged changes when committing and + nothing is staged. + + -- User Option: magit-commit-extend-override-date + + Whether using ‘magit-commit-extend’ changes the committer date. + + -- User Option: magit-commit-reword-override-date + + Whether using ‘magit-commit-reword’ changes the committer date. + + -- User Option: magit-commit-squash-confirm + + Whether the commit targeted by squash and fixup has to be + confirmed. When non-nil then the commit at point (if any) is used + as default choice. Otherwise it has to be confirmed. This option + only affects ‘magit-commit-squash’ and ‘magit-commit-fixup’. The + "instant" variants always require confirmation because making an + error while using those is harder to recover from. + + +File: magit.info, Node: Editing Commit Messages, Prev: Initiating a Commit, Up: Committing + +6.4.2 Editing Commit Messages +----------------------------- + +After initiating a commit as described in the previous section, two new +buffers appear. One shows the changes that are about to committed, +while the other is used to write the message. All regular editing +commands are available in the commit message buffer. This section only +describes the additional commands. + + Commit messages are edited in an edit session - in the background Git +is waiting for the editor, in our case the Emacsclient, to save the +commit message in a file (in most cases ‘.git/COMMIT_EDITMSG’) and then +return. If the Emacsclient returns with a non-zero exit status then Git +does not create the commit. So the most important commands are those +for finishing and aborting the commit. + +‘C-c C-c’ (‘with-editor-finish’) + + Finish the current editing session by returning with exit code 0. + Git then creates the commit using the message it finds in the file. + +‘C-c C-k’ (‘with-editor-cancel’) + + Cancel the current editing session by returning with exit code 1. + Git then cancels the commit, but leaves the file untouched. + + In addition to being used by Git, these messages may also be stored +in a ring that persists until Emacs is closed. By default the message +is stored at the beginning and the end of an edit session (regardless of +whether the session is finished successfully or was canceled). It is +sometimes useful to bring back messages from that ring. + +‘C-c M-s’ (‘git-commit-save-message’) + + Save the current buffer content to the commit message ring. + +‘M-p’ (‘git-commit-prev-message’) + + Cycle backward through the commit message ring, after saving the + current message to the ring. With a numeric prefix ARG, go back + ARG comments. + +‘M-n’ (‘git-commit-next-message’) + + Cycle forward through the commit message ring, after saving the + current message to the ring. With a numeric prefix ARG, go back + ARG comments. + + By default the diff for the changes that are about to be committed +are automatically shown when invoking the commit. When amending to an +existing commit it may be useful to show either the changes that are +about to be added to that commit or to show those changes together with +those that are already committed. + +‘C-c C-d’ (‘magit-diff-while-committing’) + + While committing, show the changes that are about to be committed. + While amending, invoking the command again toggles between showing + just the new changes or all the changes that will be committed. + +‘C-c C-w’ (‘magit-pop-revision-stack’) + + This command inserts a representation of a revision into the + current buffer. It can be used inside buffers used to write commit + messages but also in other buffers such as buffers used to edit + emails or ChangeLog files. + + By default this command pops the revision which was last added to + the ‘magit-revision-stack’ and inserts it into the current buffer + according to ‘magit-pop-revision-stack-format’. Revisions can be + put on the stack using ‘magit-copy-section-value’ and + ‘magit-copy-buffer-revision’. + + If the stack is empty or with a prefix argument it instead reads a + revision in the minibuffer. By using the minibuffer history this + allows selecting an item which was popped earlier or to insert an + arbitrary reference or revision without first pushing it onto the + stack. + + When reading the revision from the minibuffer, then it might not be + possible to guess the correct repository. When this command is + called inside a repository (e.g. while composing a commit + message), then that repository is used. Otherwise (e.g. while + composing an email) then the repository recorded for the top + element of the stack is used (even though we insert another + revision). If not called inside a repository and with an empty + stack, or with two prefix arguments, then read the repository in + the minibuffer too. + + -- User Option: magit-pop-revision-stack-format + + This option controls how the command ‘magit-pop-revision-stack’ + inserts a revision into the current buffer. + + The entries on the stack have the format ‘(HASH TOPLEVEL)’ and this + option has the format ‘(POINT-FORMAT EOB-FORMAT INDEX-REGEXP)’, all + of which may be nil or a string (though either one of EOB-FORMAT or + POINT-FORMAT should be a string, and if INDEX-REGEXP is non-nil, + then the two formats should be too). + + First INDEX-REGEXP is used to find the previously inserted entry, + by searching backward from point. The first submatch must match + the index number. That number is incremented by one, and becomes + the index number of the entry to be inserted. If you don’t want to + number the inserted revisions, then use nil for INDEX-REGEXP. + + If INDEX-REGEXP is non-nil then both POINT-FORMAT and EOB-FORMAT + should contain \"%N\", which is replaced with the number that was + determined in the previous step. + + Both formats, if non-nil and after removing %N, are then expanded + using ‘git show –format=FORMAT ...’ inside TOPLEVEL. + + The expansion of POINT-FORMAT is inserted at point, and the + expansion of EOB-FORMAT is inserted at the end of the buffer (if + the buffer ends with a comment, then it is inserted right before + that). + + Some projects use pseudo headers in commit messages. Magit colorizes +such headers and provides some commands to insert such headers. + + -- User Option: git-commit-known-pseudo-headers + + A list of Git pseudo headers to be highlighted. + +‘C-c C-a’ (‘git-commit-ack’) + + Insert a header acknowledging that you have looked at the commit. + +‘C-c C-r’ (‘git-commit-review’) + + Insert a header acknowledging that you have reviewed the commit. + +‘C-c C-s’ (‘git-commit-signoff’) + + Insert a header to sign off the commit. + +‘C-c C-t’ (‘git-commit-test’) + + Insert a header acknowledging that you have tested the commit. + +‘C-c C-o’ (‘git-commit-cc’) + + Insert a header mentioning someone who might be interested. + +‘C-c C-p’ (‘git-commit-reported’) + + Insert a header mentioning the person who reported the issue being + fixed by the commit. + +‘C-c C-i’ (‘git-commit-suggested’) + + Insert a header mentioning the person who suggested the change. + + ‘git-commit-mode’ is a minor mode that is only used to establish the +above key bindings. This allows using an arbitrary major mode when +editing the commit message. It’s even possible to use a different major +mode in different repositories, which is useful when different projects +impose different commit message conventions. + + -- User Option: git-commit-major-mode + + The value of this option is the major mode used to edit Git commit + messages. + + Because ‘git-commit-mode’ is a minor mode, we don’t use its mode hook +to setup the buffer, except for the key bindings. All other setup +happens in the function ‘git-commit-setup’, which among other things +runs the hook ‘git-commit-setup-hook’. The following functions are +suitable for that hook. + + -- User Option: git-commit-setup-hook + + Hook run at the end of ‘git-commit-setup’. + + -- Function: magit-revert-buffers &optional force + + Revert unmodified file-visiting buffers of the current repository. + + If either ‘magit-revert-buffers’ is non-nil and + ‘inhibit-magit-revert’ is nil, or if optional FORCE is non-nil, + then revert all unmodified buffers that visit files being tracked + in the current repository. + + -- Function: git-commit-save-message + + Save the current buffer content to the commit message ring. + + -- Function: git-commit-setup-changelog-support + + After this function is called, ChangeLog entries are treated as + paragraphs. + + -- Function: git-commit-turn-on-auto-fill + + Turn on ‘auto-fill-mode’ and set ‘fill-column’ to the value of + ‘git-commit-fill-column’. + + -- Function: git-commit-turn-on-flyspell + + Turn on Flyspell mode. Also prevent comments from being checked + and finally check current non-comment text. + + -- Function: git-commit-propertize-diff + + Propertize the diff shown inside the commit message buffer. Git + inserts such diffs into the commit message template when the + ‘--verbose’ argument is used. Magit’s commit popup by default does + not offer that argument because the diff that is shown in a + separate buffer is more useful. But some users disagree, which is + why this function exists. + + -- Function: with-editor-usage-message + + Show usage information in the echo area. + + Magit also helps with writing *good* commit messages by complaining +when certain rules are violated. + + -- User Option: git-commit-summary-max-length + + The intended maximal length of the summary line of commit messages. + Characters beyond this column are colorized to indicate that this + preference has been violated. + + -- User Option: git-commit-fill-column + + Column beyond which automatic line-wrapping should happen in commit + message buffers. + + -- User Option: git-commit-finish-query-functions + + List of functions called to query before performing commit. + + The commit message buffer is current while the functions are + called. If any of them returns nil, then the commit is not + performed and the buffer is not killed. The user should then fix + the issue and try again. + + The functions are called with one argument. If it is non-nil then + that indicates that the user used a prefix argument to force + finishing the session despite issues. Functions should usually + honor this wish and return non-nil. + + -- Function: git-commit-check-style-conventions + + Check for violations of certain basic style conventions. For each + violation ask the user if she wants to proceed anyway. This makes + sure the summary line isn’t too long and that the second line is + empty. + + To show no diff while committing remove ‘magit-commit-diff’ from +‘server-switch-hook’. + + +File: magit.info, Node: Branching, Next: Merging, Prev: Committing, Up: Manipulating + +6.5 Branching +============= + +* Menu: + +* The Two Remotes:: +* The Branch Popup:: +* The Branch Config Popup:: +* Auxiliary Branch Commands:: + + +File: magit.info, Node: The Two Remotes, Next: The Branch Popup, Up: Branching + +6.5.1 The Two Remotes +--------------------- + +The upstream branch of some local branch is the branch into which the +commits on that local branch should eventually be merged, usually +something like ‘origin/master’. For the ‘master’ branch itself the +upstream branch and the branch it is being pushed to, are usually the +same remote branch. But for a feature branch the upstream branch and +the branch it is being pushed to should differ. + + The commits on feature branches too should _eventually_ end up in a +remote branch such as ‘origin/master’ or ‘origin/maint’. Such a branch +should therefore be used as the upstream. But feature branches +shouldn’t be pushed directly to such branches. Instead a feature branch +‘my-feature’ is usually pushed to ‘my-fork/my-feature’ or if you are a +contributor ‘origin/my-feature’. After the new feature has been +reviewed, the maintainer merges the feature into ‘master’. And finally +‘master’ (not ‘my-feature’ itself) is pushed to ‘origin/master’. + + But new features seldom are perfect on the first try, and so feature +branches usually have to be reviewed, improved, and re-pushed several +times. Pushing should therefore be easy to do, and for that reason many +Git users have concluded that it is best to use the remote branch to +which the local feature branch is being pushed as its upstream. + + But luckily Git has long ago gained support for a push-remote which +can be configured separately from the upstream branch, using the +variables ‘branch..pushRemote’ and ‘remote.pushDefault’. So we no +longer have to choose which of the two remotes should be used as "the +remote". + + Each of the fetching, pulling, and pushing popups features three +commands that act on the current branch and some other branch. Of +these, ‘p’ is bound to a command which acts on the push-remote, ‘u’ is +bound to a command which acts on the upstream, and ‘e’ is bound to a +command which acts on any other branch. The status buffer shows +unpushed and unpulled commits for both the push-remote and the upstream. + + It’s fairly simple to configure these two remotes. The values of all +the variables that are related to fetching, pulling, and pushing (as +well as some other branch-related variables) can be inspected and +changed using the popup ‘magit-branch-config-popup’, which is a +sub-popup of many popups that deal with branches. It is also possible +to set the push-remote or upstream while pushing (see *note Pushing::). + + +File: magit.info, Node: The Branch Popup, Next: The Branch Config Popup, Prev: The Two Remotes, Up: Branching + +6.5.2 The Branch Popup +---------------------- + +The popup ‘magit-branch-popup’ is used to create and checkout branches, +and to make changes to existing branches. It is not used to fetch, +pull, merge, rebase, or push branches, i.e. this popup deals with +branches themselves, not with the commits reachable from them. Those +features are available from separate popups. + +‘b’ (‘magit-branch-popup’) + + This prefix command shows the following suffix commands in a popup + buffer. + + By default it also displays the values of some branch-related Git + variables and allows changing their values, just like the + specialized ‘magit-branch-config-popup’ does. + + -- User Option: magit-branch-popup-show-variables + + Whether the ‘magit-branch-popup’ shows Git variables. This + defaults to t to avoid changing key bindings. When set to nil, no + variables are displayed directly in this popup, and the sub-popup + ‘magit-branch-config-popup’ has to be used instead to view and + change branch related variables. + +‘b C’ (‘magit-branch-config-popup’) + + This command shows branch related variables in a separate popup. + By default this asks the user for which branch the variables should + be shown. When ‘magit-branch-popup-show-variables’ is ‘nil’, then + it shows the variables for the current branch, unless a prefix + argument is used. + +‘b b’ (‘magit-checkout’) + + Checkout a revision read in the minibuffer and defaulting to the + branch or arbitrary revision at point. If the revision is a local + branch then that becomes the current branch. If it is something + else then ‘HEAD’ becomes detached. Checkout fails if the working + tree or the staging area contain changes. + +‘b n’ (‘magit-branch-create’) + + Create a new branch. The user is asked for a branch or arbitrary + revision to use as the starting point of the new branch. When a + branch name is provided, then that becomes the upstream branch of + the new branch. The name of the new branch is also read in the + minibuffer. + + Also see option ‘magit-branch-prefer-remote-upstream’. + +‘b c’ (‘magit-branch-and-checkout’) + + This command creates a new branch like ‘magit-branch’, but then + also checks it out. + + Also see option ‘magit-branch-prefer-remote-upstream’. + +‘b l’ (‘magit-branch-checkout’) + + This command checks out an existing or new local branch. It reads + a branch name from the user offering all local branches and a + subset of remote branches as candidates. Remote branches for which + a local branch by the same name exists are omitted from the list of + candidates. The user can also enter a completely new branch name. + + • If the user selects an existing local branch, then that is + checked out. + + • If the user selects a remote branch, then it creates and + checks out a new local branch with the same name, and + configures the selected remote branch as the push target. + + • If the user enters a new branch name, then it creates and + checks that out, after also reading the starting-point from + the user. + + In the latter two cases the upstream is also set. Whether it is + set to the chosen starting point or something else depends on the + value of ‘magit-branch-adjust-remote-upstream-alist’. + +‘b s’ (‘magit-branch-spinoff’) + + This command creates and checks out a new branch starting at and + tracking the current branch. That branch in turn is reset to the + last commit it shares with its upstream. If the current branch has + no upstream or no unpushed commits, then the new branch is created + anyway and the previously current branch is not touched. + + This is useful to create a feature branch after work has already + began on the old branch (likely but not necessarily "master"). + + If the current branch is a member of the value of option + ‘magit-branch-prefer-remote-upstream’ (which see), then the current + branch will be used as the starting point as usual, but the + upstream of the starting-point may be used as the upstream of the + new branch, instead of the starting-point itself. + + If optional FROM is non-nil, then the source branch is reset to + ‘FROM~’, instead of to the last commit it shares with its upstream. + Interactively, FROM is only ever non-nil, if the region selects + some commits, and among those commits, FROM is the commit that is + the fewest commits ahead of the source branch. + + The commit at the other end of the selection actually does not + matter, all commits between FROM and ‘HEAD’ are moved to the new + branch. If FROM is not reachable from ‘HEAD’ or is reachable from + the source branch’s upstream, then an error is raised. + +‘b Y’ (‘magit-branch-pull-request’) + + This command creates and configures a new branch from a Github + pull-request, creating and configuring a new remote if necessary. + + The name of the local branch is the same as the name of the remote + branch that you are being asked to merge, unless the contributor + could not be bother to properly name the branch before opening the + pull-request. The most likely such case is when you are being + asked to merge something like "fork/master" into "origin/master". + In such cases the local branch will be named "pr-N", where ‘N’ is + the pull-request number. + + These variables are always set by this command: + + • ‘branch..pullRequest’ is set to the pull-request number. + + • ‘branch..pullRequestRemote’ is set to the remote on + which the pull-request branch is located. + + • ‘branch..pushRemote’ is set to the same remote as + ‘branch..pullRequestRemote’ if that is possible, + otherwise it is set to the upstream remote. + + • ‘branch..description’ is set to the pull-request title. + + • ‘branch..rebase’ is set to ‘true’ because there should + be no merge commits among the commits in a pull-request. + + This command also configures the upstream and the push-remote of + the local branch that it creates. + + The branch against which the pull-request was opened, is always + used as the upstream. This makes it easy to see what commits you + are being asked to merge in the section titled something like + "Unmerged into origin/master". + + Like for other commands that create a branch it depends on the + option ‘magit-branch-prefer-remote-upstream’ whether the remote + branch itself or the respective local branch is used as the + upstream, so this section may also be titled e.g. "Unmerged into + master". + + When necessary and possible, then the remote pull-request branch is + configured to be used as the push-target. This makes it easy to + see what further changes the contributor has made since you last + reviewed their changes in the section titled something like + "Unpulled from origin/new-feature" or "Unpulled from + fork/new-feature". + + • If the pull-request branch is located in the upstream + repository, then you probably have set ‘remote.pushDefault’ to + that repository. However some users like to set that variable + to their personal fork, even if they have push access to the + upstream, so ‘branch..pushRemote’ is set anyway. + + • If the pull-request branch is located inside a fork, then you + are usually able to push to that branch, because Github by + default allows the recipient of a pull-request to push to the + remote pull-request branch even if it is located in a fork. + The contributor has to explicitly disable this. + + • If you are not allowed to push to the pull-request branch + on the fork, then a branch by the same name located in + the upstream repository is configured as the push-target. + + • A — sadly rather common — special case is when the + contributor didn’t bother to use a dedicated branch for + the pull-request. + + The most likely such case is when you are being asked to + merge something like "fork/master" into "origin/master". + The special push permission mentioned above is never + granted for the branch that is the repository’s default + branch, and that would almost certainly be the case in + this scenario. + + To enable you to easily push somewhere anyway, the local + branch is named "pr-N" (where ‘N’ is the pull-request + number) and the upstream repository is used as the + push-remote. + + • Finally, if you are allowed to push to the pull-request + branch and the contributor had the foresight to use a + dedicated branch, then the fork is configured as the + push-remote. + + The push-remote is configured using + ‘branch..pushRemote’, even if the used value is + identical to that of ‘remote.pushDefault’, just in case you + change the value of the latter later on. Additionally the + variable ‘branch..pullRequestRemote’ is set to the + remote on which the pull-request branch is located. + + When you later delete the local pull-request branch, then you are + offered to also delete the corresponding remote, provided it is not + the upstream remote and that the tracking branch that corresponds + to the deleted branch is the only remaining tracked branch. If you + don’t confirm, then only the tracking branch itself is deleted in + addition to the local branch. + + Do not delete the tracking branch instead of the local branch. The + cleanup mentioned in the previous paragraph is not performed if you + do that. + +‘b y’ (‘magit-checkout-pull-request’) + + This command creates and configures a new branch from a pull + request, the same way ‘magit-branch-pull-request’ does. + Additionally it checks out the new branch. + +‘b x’ (‘magit-branch-reset’) + + This command resets a branch, defaulting to the branch at point, to + the tip of another branch or any other commit. + + When the branch being reset is the current branch, then a hard + reset is performed. If there are any uncommitted changes, then the + user has to confirm the reset because those changes would be lost. + + This is useful when you have started work on a feature branch but + realize it’s all crap and want to start over. + + When resetting to another branch and a prefix argument is used, + then the target branch is set as the upstream of the branch that is + being reset. + +‘b k’ (‘magit-branch-delete’) + + Delete one or multiple branches. If the region marks multiple + branches, then offer to delete those. Otherwise, prompt for a + single branch to be deleted, defaulting to the branch at point. + +‘b r’ (‘magit-branch-rename’) + + Rename a branch. The branch and the new name are read in the + minibuffer. With prefix argument the branch is renamed even if + that name conflicts with an existing branch. + + -- User Option: magit-branch-read-upstream-first + + When creating a branch, whether to read the upstream branch before + the name of the branch that is to be created. The default is + ‘nil’, and I recommend you leave it at that. + + -- User Option: magit-branch-prefer-remote-upstream + + This option specifies whether remote upstreams are favored over + local upstreams when creating new branches. + + When a new branch is created, then the branch, commit, or stash at + point is suggested as the starting point of the new branch, or if + there is no such revision at point the current branch. In either + case the user may choose another starting point. + + If the chosen starting point is a branch, then it may also be set + as the upstream of the new branch, depending on the value of the + Git variable ‘branch.autoSetupMerge’. By default this is done for + remote branches, but not for local branches. + + You might prefer to always use some remote branch as upstream. If + the chosen starting point is (1) a local branch, (2) whose name + matches a member of the value of this option, (3) the upstream of + that local branch is a remote branch with the same name, and (4) + that remote branch can be fast-forwarded to the local branch, then + the chosen branch is used as starting point, but its own upstream + is used as the upstream of the new branch. + + Members of this option’s value are treated as branch names that + have to match exactly unless they contain a character that makes + them invalid as a branch name. Recommended characters to use to + trigger interpretation as a regexp are "*" and "^". Some other + characters which you might expect to be invalid, actually are not, + e.g. ".+$" are all perfectly valid. More precisely, if ‘git + check-ref-format –branch STRING’ exits with a non-zero status, then + treat STRING as a regexp. + + Assuming the chosen branch matches these conditions you would end + up with with e.g.: + + feature --upstream--> origin/master + + instead of + + feature --upstream--> master --upstream--> origin/master + + Which you prefer is a matter of personal preference. If you do + prefer the former, then you should add branches such as ‘master’, + ‘next’, and ‘maint’ to the value of this options. + + -- User Option: magit-branch-adjust-remote-upstream-alist + + The value of this option is an alist of branches to be used as the + upstream when branching a remote branch. + + When creating a local branch from an ephemeral branch located on a + remote, e.g. a feature or hotfix branch, then that remote branch + should usually not be used as the upstream branch, since the + push-remote already allows accessing it and having both the + upstream and the push-remote reference the same related branch + would be wasteful. Instead a branch like "maint" or "master" + should be used as the upstream. + + This option allows specifying the branch that should be used as the + upstream when branching certain remote branches. The value is an + alist of the form ‘((UPSTREAM . RULE)...)’. The first matching + element is used, the following elements are ignored. + + UPSTREAM is the branch to be used as the upstream for branches + specified by RULE. It can be a local or a remote branch. + + RULE can either be a regular expression, matching branches whose + upstream should be the one specified by UPSTREAM. Or it can be a + list of the only branches that should *not* use UPSTREAM; all other + branches will. Matching is done after stripping the remote part of + the name of the branch that is being branched from. + + If you use a finite set of non-ephemeral branches across all your + repositories, then you might use something like: + + (("origin/master" "master" "next" "maint")) + + Or if the names of all your ephemeral branches contain a slash, at + least in some repositories, then a good value could be: + + (("origin/master" . "/")) + + Of course you can also fine-tune: + + (("origin/maint" . "\\`hotfix/") + ("origin/master" . "\\`feature/")) + + -- Command: magit-branch-orphan + + This command creates and checks out a new orphan branch with + contents from a given revision. + + -- Command: magit-branch-or-checkout + + This command is a hybrid between ‘magit-checkout’ and + ‘magit-branch-and-checkout’ and is intended as a replacement for + the former in ‘magit-branch-popup’. + + It first asks the user for an existing branch or revision. If the + user input actually can be resolved as a branch or revision, then + it checks that out, just like ‘magit-checkout’ would. + + Otherwise it creates and checks out a new branch using the input as + its name. Before doing so it reads the starting-point for the new + branch. This is similar to what ‘magit-branch-and-checkout’ does. + + To use this command instead of ‘magit-checkout’ add this to your + init file: + + (magit-remove-popup-key 'magit-branch-popup :action ?b) + (magit-define-popup-action 'magit-branch-popup + ?b "Checkout" 'magit-branch-or-checkout + 'magit-branch t) + + +File: magit.info, Node: The Branch Config Popup, Next: Auxiliary Branch Commands, Prev: The Branch Popup, Up: Branching + +6.5.3 The Branch Config Popup +----------------------------- + + -- Command: magit-branch-config-popup + + This prefix command shows the following branch-related Git + variables in a popup buffer. The values can be changed from that + buffer. + + This popup is a sub-popup of several popups that deal with + branches, including ‘magit-branch-popup’, ‘magit-pull-popup’, + ‘magit-fetch-popup’, ‘magit-pull-and-fetch-popup’, and + ‘magit-push-popup’. In all of these popups "C" is bound to this + popup. + + The following variables are used to configure a specific branch. The +values are being displayed for the current branch (if any). To change +the value for another branch invoke ‘magit-branch-config-popup’ with a +prefix argument. + + -- Variable: branch.NAME.merge + + Together with ‘branch.NAME.remote’ this variable defines the + upstream branch of the local branch named NAME. The value of this + variable is the full reference of the upstream _branch_. + + -- Variable: branch.NAME.remote + + Together with ‘branch.NAME.merge’ this variable defines the + upstream branch of the local branch named NAME. The value of this + variable is the name of the upstream _remote_. + + -- Variable: branch.NAME.rebase + + This variable controls whether pulling into the branch named NAME + is done by rebasing or by merging the fetched branch. + + • When ‘true’ then pulling is done by rebasing. + + • When ‘false’ then pulling is done by merging. + + • When undefined then the value of ‘pull.rebase’ is used. The + default of that variable is ‘false’. + + -- Variable: branch.NAME.pushRemote + + This variable specifies the remote that the branch named NAME is + usually pushed to. The value has to be the name of an existing + remote. + + It is not possible to specify the name of _branch_ to push the + local branch to. The name of the remote branch is always the same + as the name of the local branch. + + If this variable is undefined but ‘remote.pushDefault’ is defined, + then the value of the latter is used. By default + ‘remote.pushDefault’ is undefined. + + -- Variable: branch.NAME.description + + This variable can be used to describe the branch named NAME. That + description is used e.g. when turning the branch into a series of + patches. + + The following variables specify defaults which are used if the above +branch-specific variables are not set. + + -- Variable: pull.rebase + + This variable specifies whether pulling is done by rebasing or by + merging. It can be overwritten using ‘branch.NAME.rebase’. + + • When ‘true’ then pulling is done by rebasing. + + • When ‘false’ (the default) then pulling is done by merging. + + Since it is never a good idea to merge the upstream branch into a + feature or hotfix branch and most branches are such branches, you + should consider setting this to ‘true’, and ‘branch.master.rebase’ + to ‘false’. + + -- Variable: remote.pushDefault + + This variable specifies what remote the local branches are usually + pushed to. This can be overwritten per branch using + ‘branch.NAME.pushRemote’. + + The following variables are used during the creation of a branch and +control whether the various branch-specific variables are automatically +set at this time. + + -- Variable: branch.autoSetupMerge + + This variable specifies under what circumstances creating a branch + NAME should result in the variables ‘branch.NAME.merge’ and + ‘branch.NAME.remote’ being set according to the starting point used + to create the branch. If the starting point isn’t a branch, then + these variables are never set. + + • When ‘always’ then the variables are set regardless of whether + the starting point is a local or a remote branch. + + • When ‘true’ (the default) then the variables are set when the + starting point is a remote branch, but not when it is a local + branch. + + • When ‘false’ then the variables are never set. + + -- Variable: branch.autoSetupRebase + + This variable specifies whether creating a branch NAME should + result in the variable ‘branch.NAME.rebase’ being set to ‘true’. + + • When ‘always’ then the variable is set regardless of whether + the starting point is a local or a remote branch. + + • When ‘local’ then the variable are set when the starting point + is a local branch, but not when it is a remote branch. + + • When ‘remote’ then the variable are set when the starting + point is a remote branch, but not when it is a local branch. + + • When ‘never’ (the default) then the variable is never set. + + Note that the respective commands always change the repository-local +values. If you want to change the global value, which is used when the +local value is undefined, then you have to do so on the command line, +e.g.: + + git config --global remote.autoSetupMerge always + + For more information about these variables you should also see + + *note (gitman)git-config::. Also see *note (gitman)git-branch::. , +*note (gitman)git-checkout::. and *note Pushing::. + + -- User Option: magit-prefer-remote-upstream + + This option controls whether commands that read a branch from the + user and then set it as the upstream branch, offer a local or a + remote branch as default completion candidate, when they have the + choice. + + This affects all commands that use ‘magit-read-upstream-branch’ or + ‘magit-read-starting-point’, which includes all commands that + change the upstream and many which create new branches. + + +File: magit.info, Node: Auxiliary Branch Commands, Prev: The Branch Config Popup, Up: Branching + +6.5.4 Auxiliary Branch Commands +------------------------------- + +These commands are not available from the branch popup by default. + + -- Command: magit-branch-shelve + + This command shelves a branch. This is done by deleting the + branch, and creating a new reference "refs/shelved/BRANCH-NAME" + pointing at the same commit as the branch pointed at. If the + deleted branch had a reflog, then that is preserved as the reflog + of the new reference. + + This is useful if you want to move a branch out of sight, but are + not ready to completely discard it yet. + + -- Command: magit-branch-unshelve + + This command unshelves a branch that was previously shelved using + ‘magit-branch-shelve’. This is done by deleting the reference + "refs/shelved/BRANCH-NAME" and creating a branch "BRANCH-NAME" + pointing at the same commit as the deleted reference pointed at. + If the deleted reference had a reflog, then that is restored as the + reflog of the branch. + + +File: magit.info, Node: Merging, Next: Resolving Conflicts, Prev: Branching, Up: Manipulating + +6.6 Merging +=========== + +Also see *note (gitman)git-merge::. For information on how to resolve +merge conflicts see the next section. + +‘m’ (‘magit-merge-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + + When no merge is in progress, then the popup buffer features the +following commands. + +‘m m’ (‘magit-merge-plain’) + + This command merges another branch or an arbitrary revision into + the current branch. The branch or revision to be merged is read in + the minibuffer and defaults to the branch at point. + + Unless there are conflicts or a prefix argument is used, then the + resulting merge commit uses a generic commit message, and the user + does not get a chance to inspect or change it before the commit is + created. With a prefix argument this does not actually create the + merge commit, which makes it possible to inspect how conflicts were + resolved and to adjust the commit message. + +‘m e’ (‘magit-merge-editmsg’) + + This command merges another branch or an arbitrary revision into + the current branch and opens a commit message buffer, so that the + user can make adjustments. The commit is not actually created + until the user finishes with ‘C-c C-c’. + +‘m n’ (‘magit-merge-nocommit’) + + This command merges another branch or an arbitrary revision into + the current branch, but does not actually create the merge commit. + The user can then further adjust the merge, even when automatic + conflict resolution succeeded and/or adjust the commit message. + +‘m a’ (‘magit-merge-absorb’) + + This command merges another local branch into the current branch + and then removes the former. + + Before the source branch is merged, it is first force pushed to its + push-remote, provided the respective remote branch already exists. + This ensures that the respective pull-request (if any) won’t get + stuck on some obsolete version of the commits that are being + merged. Finally, if ‘magit-branch-pull-request’ was used to create + the merged branch, then the respective remote branch is also + removed. + +‘m i’ (‘magit-merge-into’) + + This command merges the current branch into another local branch + and then removes the former. The latter becomes the new current + branch. + + Before the source branch is merged, it is first force pushed to its + push-remote, provided the respective remote branch already exists. + This ensures that the respective pull-request (if any) won’t get + stuck on some obsolete version of the commits that are being + merged. Finally, if ‘magit-branch-pull-request’ was used to create + the merged branch, then the respective remote branch is also + removed. + +‘m s’ (‘magit-merge-squash’) + + This command squashes the changes introduced by another branch or + an arbitrary revision into the current branch. This only applies + the changes made by the squashed commits. No information is + preserved that would allow creating an actual merge commit. + Instead of this command you should probably use a command from the + apply popup. + +‘m p’ (‘magit-merge-preview’) + + This command shows a preview of merging another branch or an + arbitrary revision into the current branch. + + When a merge is in progress, then the popup buffer features these +commands instead. + +‘m m’ (‘magit-merge’) + + After the user resolved conflicts, this command proceeds with the + merge. If some conflicts weren’t resolved, then this command + fails. + +‘m a’ (‘magit-merge-abort’) + + This command aborts the current merge operation. + + +File: magit.info, Node: Resolving Conflicts, Next: Rebasing, Prev: Merging, Up: Manipulating + +6.7 Resolving Conflicts +======================= + +When merging branches (or otherwise combining or changing history) +conflicts can occur. If you edited two completely different parts of +the same file in two branches and then merge one of these branches into +the other, then Git can resolve that on its own, but if you edit the +same area of a file, then a human is required to decide how the two +versions, or "sides of the conflict", are to be combined into one. + + Here we can only provide a brief introduction to the subject and +point you toward some tools that can help. If you are new to this, then +please also consult Git’s own documentation as well as other resources. + + If a file has conflicts and Git cannot resolve them by itself, then +it puts both versions into the affected file along with special markers +whose purpose is to denote the boundaries of the unresolved part of the +file and between the different versions. These boundary lines begin +with the strings consisting of six times the same character, one of ‘<’, +‘|’, ‘=’ and ‘>’ and are followed by information about the source of the +respective versions, e.g.: + + <<<<<<< HEAD + Take the blue pill. + ======= + Take the red pill. + >>>>>>> feature + + In this case you have chosen to take the red pill on one branch and +on another you picked the blue pill. Now that you are merging these two +diverging branches, Git cannot possibly know which pill you want to +take. + + To resolve that conflict you have to create a version of the affected +area of the file by keeping only one of the sides, possibly by editing +it in order to bring in the changes from the other side, remove the +other versions as well as the markers, and then stage the result. A +possible resolution might be: + + Take both pills. + + Often it is useful to see not only the two sides of the conflict but +also the "original" version from before the same area of the file was +modified twice on different branches. Instruct Git to insert that +version as well by running this command once: + + git config --global merge.conflictStyle diff3 + + The above conflict might then have looked like this: + + <<<<<<< HEAD + Take the blue pill. + ||||||| merged common ancestors + Take either the blue or the red pill, but not both. + ======= + Take the red pill. + >>>>>>> feature + + If that were the case, then the above conflict resolution would not +have been correct, which demonstrates why seeing the original version +alongside the conflicting versions can be useful. + + You can perform the conflict resolution completely by hand, but Emacs +also provides some packages that help in the process: Smerge, Ediff +(*note (ediff)Top::), and Emerge (*note (emacs)Emerge::). Magit does +not provide its own tools for conflict resolution, but it does make +using Smerge and Ediff more convenient. (Ediff supersedes Emerge, so +you probably don’t want to use the latter anyway.) + + In the Magit status buffer, files with unresolved conflicts are +listed in the "Unstaged changes" and/or "Staged changes" sections. They +are prefixed with the word "unmerged", which in this context essentially +is a synonym for "unresolved". + + Pressing ‘RET’ while point is on such a file section shows a buffer +visiting that file, turns on ‘smerge-mode’ in that buffer, and places +point inside the first area with conflicts. You should then resolve +that conflict using regular edit commands and/or Smerge commands. + + Unfortunately Smerge does not have a manual, but you can get a list +of commands and binding ‘C-c ^ C-h’ and press ‘RET’ while point is on a +command name to read its documentation. + + Normally you would edit one version and then tell Smerge to keep only +that version. Use ‘C-c ^ m’ (‘smerge-keep-mine’) to keep the ‘HEAD’ +version or ‘C-c ^ o’ (‘smerge-keep-other’) to keep the version that +follows "|||||||". Then use ‘C-c ^ n’ to move to the next conflicting +area in the same file. Once you are done resolving conflicts, return to +the Magit status buffer. The file should now be shown as "modified", no +longer as "unmerged", because Smerge automatically stages the file when +you save the buffer after resolving the last conflict. + + Alternatively you could use Ediff, which uses separate buffers for +the different versions of the file. To resolve conflicts in a file +using Ediff press ‘e’ while point is on such a file in the status +buffer. + + Ediff can be used for other purposes as well. For more information +on how to enter Ediff from Magit, see *note Ediffing::. Explaining how +to use Ediff is beyond the scope of this manual, instead see *note +(ediff)Top::. + + If you are unsure whether you should Smerge or Ediff, then use the +former. It is much easier to understand and use, and except for truly +complex conflicts, the latter is usually overkill. + + +File: magit.info, Node: Rebasing, Next: Cherry Picking, Prev: Resolving Conflicts, Up: Manipulating + +6.8 Rebasing +============ + +Also see *note (gitman)git-rebase::. For information on how to resolve +conflicts that occur during rebases see the preceding section. + +‘r’ (‘magit-rebase-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + + When no rebase is in progress, then the popup buffer features the +following commands. + + Using one of these commands _starts_ a rebase sequence. Git might +then stop somewhere along the way, either because you told it to do so, +or because applying a commit failed due to a conflict. When that +happens, then the status buffer shows information about the rebase +sequence which is in progress in a section similar to a log section. +See *note Information About In-Progress Rebase::. + +‘r p’ (‘magit-rebase-onto-pushremote’) + + Rebase the current branch onto ‘branch..pushRemote’. If that + variable is unset, then rebase onto ‘remote.pushDefault’. + +‘r u’ (‘magit-rebase-onto-upstream’) + + Rebase the current branch onto its upstream branch. + +‘r e’ (‘magit-rebase-branch’) + + Rebase the current branch onto a branch read in the minibuffer. + All commits that are reachable from head but not from the selected + branch TARGET are being rebased." + +‘r s’ (‘magit-rebase-subset’) + + Start a non-interactive rebase sequence with commits from START to + ‘HEAD’ onto NEWBASE. START has to be selected from a list of + recent commits. + + By default Magit uses the ‘--autostash’ argument, which causes +uncommitted changes to be stored in a stash before the rebase begins. +These changes are restored after the rebase completes and if possible +the stash is removed. If the stash does not apply cleanly, then the +stash is not removed. In case something goes wrong when resolving the +conflicts, this allows you to start over. + + Even though one of the actions is dedicated to interactive rebases, +the popup also features the infix argument ‘--interactive’. This can be +used to turn one of the other, non-interactive rebase variants into an +interactive rebase. + + For example if you want to clean up a feature branch and at the same +time rebase it onto ‘master’, then you could use ‘r-iu’. But we +recommend that you instead do that in two steps. First use ‘ri’ to +cleanup the feature branch, and then in a second step ‘ru’ to rebase it +onto ‘master’. That way if things turn out to be more complicated than +you thought and/or you make a mistake and have to start over, then you +only have to redo half the work. + + Explicitly enabling ‘--interactive’ won’t have an effect on the +following commands as they always use that argument anyway, even if it +is not enabled in the popup. + +‘r i’ (‘magit-rebase-interactive’) + + Start an interactive rebase sequence. + +‘r f’ (‘magit-rebase-autosquash’) + + Combine squash and fixup commits with their intended targets. + +‘r m’ (‘magit-rebase-edit-commit’) + + Edit a single older commit using rebase. + +‘r w’ (‘magit-rebase-reword-commit’) + + Reword a single older commit using rebase. + +‘r k’ (‘magit-rebase-remove-commit’) + + Remove a single older commit using rebase. + + When a rebase is in progress, then the popup buffer features these +commands instead. + +‘r r’ (‘magit-rebase-continue’) + + Restart the current rebasing operation. + + In some cases this pops up a commit message buffer for you do edit. + With a prefix argument the old message is reused as-is. + +‘r s’ (‘magit-rebase-skip’) + + Skip the current commit and restart the current rebase operation. + +‘r e’ (‘magit-rebase-edit’) + + Edit the todo list of the current rebase operation. + +‘r a’ (‘magit-rebase-abort’) + + Abort the current rebase operation, restoring the original branch. + +* Menu: + +* Editing Rebase Sequences:: +* Information About In-Progress Rebase:: + + +File: magit.info, Node: Editing Rebase Sequences, Next: Information About In-Progress Rebase, Up: Rebasing + +6.8.1 Editing Rebase Sequences +------------------------------ + +‘C-c C-c’ (‘with-editor-finish’) + + Finish the current editing session by returning with exit code 0. + Git then uses the rebase instructions it finds in the file. + +‘C-c C-k’ (‘with-editor-cancel’) + + Cancel the current editing session by returning with exit code 1. + Git then forgoes starting the rebase sequence. + +‘RET’ (‘git-rebase-show-commit’) + + Show the commit on the current line in another buffer and select + that buffer. + +‘SPC’ (‘git-rebase-show-or-scroll-up’) + + Show the commit on the current line in another buffer without + selecting that buffer. If the revision buffer is already visible + in another window of the current frame, then instead scroll that + window up. + +‘DEL’ (‘git-rebase-show-or-scroll-down’) + + Show the commit on the current line in another buffer without + selecting that buffer. If the revision buffer is already visible + in another window of the current frame, then instead scroll that + window down. + +‘p’ (‘git-rebase-backward-line’) + + Move to previous line. + +‘n’ (‘forward-line’) + + Move to next line. + +‘M-p’ (‘git-rebase-move-line-up’) + + Move the current commit (or command) up. + +‘M-n’ (‘git-rebase-move-line-down’) + + Move the current commit (or command) down. + +‘r’ (‘git-rebase-reword’) + + Edit message of commit on current line. + +‘e’ (‘git-rebase-edit’) + + Stop at the commit on the current line. + +‘s’ (‘git-rebase-squash’) + + Meld commit on current line into previous commit, and edit message. + +‘f’ (‘git-rebase-fixup’) + + Meld commit on current line into previous commit, discarding the + current commit’s message. + +‘k’ (‘git-rebase-kill-line’) + + Kill the current action line. + +‘c’ (‘git-rebase-pick’) + + Use commit on current line. + +‘x’ (‘git-rebase-exec’) + + Insert a shell command to be run after the proceeding commit. + + If there already is such a command on the current line, then edit + that instead. With a prefix argument insert a new command even + when there already is one on the current line. With empty input + remove the command on the current line, if any. + +‘y’ (‘git-rebase-insert’) + + Read an arbitrary commit and insert it below current line. + +‘C-x u’ (‘git-rebase-undo’) + + Undo some previous changes. Like ‘undo’ but works in read-only + buffers. + + -- User Option: git-rebase-auto-advance + + Whether to move to next line after changing a line. + + -- User Option: git-rebase-show-instructions + + Whether to show usage instructions inside the rebase buffer. + + -- User Option: git-rebase-confirm-cancel + + Whether confirmation is required to cancel. + + +File: magit.info, Node: Information About In-Progress Rebase, Prev: Editing Rebase Sequences, Up: Rebasing + +6.8.2 Information About In-Progress Rebase +------------------------------------------ + +While a rebase sequence is in progress, the status buffer features a +section that lists the commits that have already been applied as well as +the commits that still have to be applied. + + The commits are split in two halves. When rebase stops at a commit, +either because the user has to deal with a conflict or because s/he +explicitly requested that rebase stops at that commit, then point is +placed on the commit that separates the two groups, i.e. on ‘HEAD’. +The commits above it have not been applied yet, while the ‘HEAD’ and the +commits below it have already been applied. In between these two groups +of applied and yet-to-be applied commits, there sometimes is a commit +which has been dropped. + + Each commit is prefixed with a word and these words are additionally +shown in different colors to indicate the status of the commits. + + The following colors are used: + + • Yellow commits have not been applied yet. + + • Gray commits have already been applied. + + • The blue commit is the ‘HEAD’ commit. + + • The green commit is the commit the rebase sequence stopped at. If + this is the same commit as ‘HEAD’ (e.g. because you haven’t done + anything yet after rebase stopped at the commit, then this commit + is shown in blue, not green). There can only be a green *and* a + blue commit at the same time, if you create one or more new commits + after rebase stops at a commit. + + • Red commits have been dropped. They are shown for reference only, + e.g. to make it easier to diff. + + Of course these colors are subject to the color-theme in use. + + The following words are used: + + • Commits prefixed with ‘pick’, ‘reword’, ‘edit’, ‘squash’, and + ‘fixup’ have not been applied yet. These words have the same + meaning here as they do in the buffer used to edit the rebase + sequence. See *note Editing Rebase Sequences::. + + • Commits prefixed with ‘done’ and ‘onto’ have already been applied. + It is possible for such a commit to be the ‘HEAD’, in which case it + is blue. Otherwise it is grey. + + • The commit prefixed with ‘onto’ is the commit on top of which + all the other commits are being re-applied. This commit + itself did not have to be re-applied, it is the commit rebase + did rewind to before starting to re-apply other commits. + + • Commits prefixed with ‘done’ have already been re-applied. + This includes commits that have been re-applied but also new + commits that you have created during the rebase. + + • All other commits, those not prefixed with any of the above words, + are in some way related to the commit at which rebase stopped. + + To determine whether a commit is related to the stopped-at commit + their hashes, trees and patch-ids (1) are being compared. The + commit message is not used for this purpose. + + Generally speaking commits that are related to the stopped-at + commit can have any of the used colors, though not all color/word + combinations are possible. + + Words used for stopped-at commits are: + + • When a commit is prefixed with ‘void’, then that indicates + that Magit knows for sure that all the changes in that commit + have been applied using several new commits. This commit is + no longer reachable from ‘HEAD’, and it also isn’t one of the + commits that will be applied when resuming the session. + + • When a commit is prefixed with ‘join’, then that indicates + that the rebase sequence stopped at that commit due to a + conflict - you now have to join (merge) the changes with what + has already been applied. In a sense this is the commit + rebase stopped at, but while its effect is already in the + index and in the worktree (with conflict markers), the commit + itself has not actually been applied yet (it isn’t the + ‘HEAD’). So it is shown in yellow, like the other commits + that still have to be applied. + + • When a commit is prefixed with ‘stop’ or a _blue_ or _green_ + ‘same’, then that indicates that rebase stopped at this + commit, that it is still applied or has been applied again, + and that at least its patch-id is unchanged. + + • When a commit is prefixed with ‘stop’, then that + indicates that rebase stopped at that commit because you + requested that earlier, and its patch-id is unchanged. + It might even still be the exact same commit. + + • When a commit is prefixed with a _blue_ or _green_ + ‘same’, then that indicates that while its tree or hash + changed, its patch-id did not. If it is blue, then it is + the ‘HEAD’ commit (as always for blue). When it is + green, then it no longer is ‘HEAD’ because other commit + have been created since (but before continuing the + rebase). + + • When a commit is prefixed with ‘goal’, a _yellow_ ‘same,’ or + ‘work’, then that indicates that rebase applied that commit + but that you then reset ‘HEAD’ to an earlier commit (likely to + split it up into multiple commits), and that there are some + uncommitted changes remaining which likely (but not + necessarily) originate from that commit. + + • When a commit is prefixed with ‘goal’, then that + indicates that it is still possible to create a new + commit with the exact same tree (the "goal") without + manually editing any files, by committing the index, or + by staging all changes and then committing that. This is + the case when the original tree still exists in the index + or worktree in untainted form. + + • When a commit is prefixed with a yellow ‘same’, then that + indicates that it is no longer possible to create a + commit with the exact same tree, but that it is still + possible to create a commit with the same patch-id. This + would be the case if you created a new commit with other + changes, but the changes from the original commit still + exist in the index or working tree in untainted form. + + • When a commit is prefixed with ‘work’, then that + indicates that you reset ‘HEAD’ to an earlier commit, and + that there are some staged and/or unstaged changes + (likely, but not necessarily) originating from that + commit. However it is no longer possible to create a new + commit with the same tree or at least the same patch-id + because you have already made other changes. + + • When a commit is prefixed with ‘poof’ or ‘gone’, then that + indicates that rebase applied that commit but that you then + reset ‘HEAD’ to an earlier commit (likely to split it up into + multiple commits), and that there are no uncommitted changes. + + • When a commit is prefixed with ‘poof’, then that + indicates that it is no longer reachable from ‘HEAD’, but + that it has been replaced with one or more commits, which + together have the exact same effect. + + • When a commit is prefixed with ‘gone’, then that + indicates that it is no longer reachable from ‘HEAD’ and + that we also cannot determine whether its changes are + still in effect in one or more new commits. They might + be, but if so, then there must also be other changes + which makes it impossible to know for sure. + + Do not worry if you do not fully understand the above. That’s okay, +you will acquire a good enough understanding through practice. + + For other sequence operations such as cherry-picking, a similar +section is displayed, but they lack some of the features described +above, due to limitations in the git commands used to implement them. +Most importantly these sequences only support "picking" a commit but not +other actions such as "rewording", and they do not keep track of the +commits which have already been applied. + + ---------- Footnotes ---------- + + (1) The patch-id is a hash of the _changes_ introduced by a commit. +It differs from the hash of the commit itself, which is a hash of the +result of applying that change (i.e. the resulting trees and blobs) as +well as author and committer information, the commit message, and the +hashes of the parents of the commit. The patch-id hash on the other +hand is created only from the added and removed lines, even line numbers +and whitespace changes are ignored when calculating this hash. The +patch-ids of two commits can be used to answer the question "Do these +commits make the same change?". + + +File: magit.info, Node: Cherry Picking, Next: Resetting, Prev: Rebasing, Up: Manipulating + +6.9 Cherry Picking +================== + +Also see *note (gitman)git-cherry-pick::. + +‘A’ (‘magit-cherry-pick-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + + When no cherry-pick or revert is in progress, then the popup buffer +features the following commands. + +‘A A’ (‘magit-cherry-copy’) + + This command copies COMMITS from another branch onto the current + branch. If the region selects multiple commits, then those are + copied, without prompting. Otherwise the user is prompted for a + commit or range, defaulting to the commit at point. + +‘A a’ (‘magit-cherry-apply’) + + This command applies the changes in COMMITS from another branch + onto the current branch. If the region selects multiple commits, + then those are used, without prompting. Otherwise the user is + prompted for a commit or range, defaulting to the commit at point. + + This command also has a top-level binding, which can be invoked + without using the popup by typing ‘a’ at the top-level. + + The following commands not only apply some commits to some branch, +but also remove them from some other branch. The removal is performed +using either ‘git-update-ref’ or if necessary ‘git-rebase’. Both +applying commits as well as removing them using ‘git-rebase’ can lead to +conflicts. If that happens, then these commands abort and you not only +have to resolve the conflicts but also finish the process the same way +you would have to if these commands didn’t exist at all. + +‘A h’ (‘magit-cherry-harvest’) + + This command moves the selected COMMITS that must be located on + another BRANCH onto the current branch instead, removing them from + the former. When this command succeeds, then the same branch is + current as before. + + Applying the commits on the current branch or removing them from + the other branch can lead to conflicts. When that happens, then + this command stops and you have to resolve the conflicts and then + finish the process manually. + +‘A d’ (‘magit-cherry-donate’) + + This command moves the selected COMMITS from the current branch + onto another existing BRANCH, removing them from the former. When + this command succeeds, then the same branch is current as before. + + Applying the commits on the other branch or removing them from the + current branch can lead to conflicts. When that happens, then this + command stops and you have to resolve the conflicts and then finish + the process manually. + +‘A n’ (‘magit-cherry-spinout’) + + This command moves the selected COMMITS from the current branch + onto a new branch BRANCH, removing them from the former. When this + command succeeds, then the same branch is current as before. + + Applying the commits on the other branch or removing them from the + current branch can lead to conflicts. When that happens, then this + command stops and you have to resolve the conflicts and then finish + the process manually. + +‘A s’ (‘magit-cherry-spinoff’) + + This command moves the selected COMMITS from the current branch + onto a new branch BRANCH, removing them from the former. When this + command succeeds, then the new branch is checked out. + + Applying the commits on the other branch or removing them from the + current branch can lead to conflicts. When that happens, then this + command stops and you have to resolve the conflicts and then finish + the process manually. + + When a cherry-pick or revert is in progress, then the popup buffer +features these commands instead. + +‘A A’ (‘magit-sequence-continue’) + + Resume the current cherry-pick or revert sequence. + +‘A s’ (‘magit-sequence-skip’) + + Skip the stopped at commit during a cherry-pick or revert sequence. + +‘A a’ (‘magit-sequence-abort’) + + Abort the current cherry-pick or revert sequence. This discards + all changes made since the sequence started. + +* Menu: + +* Reverting:: + + +File: magit.info, Node: Reverting, Up: Cherry Picking + +6.9.1 Reverting +--------------- + +‘V’ (‘magit-revert-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + + When no cherry-pick or revert is in progress, then the popup buffer +features the following commands. + +‘V V’ (‘magit-revert-and-commit’) + + Revert a commit by creating a new commit. Prompt for a commit, + defaulting to the commit at point. If the region selects multiple + commits, then revert all of them, without prompting. + +‘V v’ (‘magit-revert-no-commit’) + + Revert a commit by applying it in reverse to the working tree. + Prompt for a commit, defaulting to the commit at point. If the + region selects multiple commits, then revert all of them, without + prompting. + + When a cherry-pick or revert is in progress, then the popup buffer +features these commands instead. + +‘V A’ (‘magit-sequence-continue’) + + Resume the current cherry-pick or revert sequence. + +‘V s’ (‘magit-sequence-skip’) + + Skip the stopped at commit during a cherry-pick or revert sequence. + +‘V a’ (‘magit-sequence-abort’) + + Abort the current cherry-pick or revert sequence. This discards + all changes made since the sequence started. + + +File: magit.info, Node: Resetting, Next: Stashing, Prev: Cherry Picking, Up: Manipulating + +6.10 Resetting +============== + +Also see *note (gitman)git-reset::. + +‘x’ (‘magit-reset-quickly’) + + Reset the ‘HEAD’ and index to some commit read from the user and + defaulting to the commit at point, and possibly also reset the + working tree. With a prefix argument reset the working tree + otherwise don’t. + +‘X m’ (‘magit-reset-mixed’) + + Reset the ‘HEAD’ and index to some commit read from the user and + defaulting to the commit at point. The working tree is kept as-is. + +‘X s’ (‘magit-reset-soft’) + + Reset the ‘HEAD’ to some commit read from the user and defaulting + to the commit at point. The index and the working tree are kept + as-is. + +‘X h’ (‘magit-reset-hard’) + + Reset the ‘HEAD’, index, and working tree to some commit read from + the user and defaulting to the commit at point. + +‘X i’ (‘magit-reset-index’) + + Reset the index to some commit read from the user and defaulting to + the commit at point. Keep the ‘HEAD’ and working tree as-is, so if + the commit refers to the ‘HEAD’, then this effectively unstages all + changes. + +‘X w’ (‘magit-reset-worktree’) + + Reset the working tree to some commit read from the user and + defaulting to the commit at point. Keep the ‘HEAD’ and index + as-is. + +‘X f’ (‘magit-file-checkout’) + + Update file in the working tree and index to the contents from a + revision. Both the revision and file are read from the user. + + +File: magit.info, Node: Stashing, Prev: Resetting, Up: Manipulating + +6.11 Stashing +============= + +Also see *note (gitman)git-stash::. + +‘z’ (‘magit-stash-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘z z’ (‘magit-stash-both’) + + Create a stash of the index and working tree. Untracked files are + included according to popup arguments. One prefix argument is + equivalent to ‘--include-untracked’ while two prefix arguments are + equivalent to ‘--all’. + +‘z i’ (‘magit-stash-index’) + + Create a stash of the index only. Unstaged and untracked changes + are not stashed. + +‘z w’ (‘magit-stash-worktree’) + + Create a stash of unstaged changes in the working tree. Untracked + files are included according to popup arguments. One prefix + argument is equivalent to ‘--include-untracked’ while two prefix + arguments are equivalent to ‘--all’. + +‘z x’ (‘magit-stash-keep-index’) + + Create a stash of the index and working tree, keeping index intact. + Untracked files are included according to popup arguments. One + prefix argument is equivalent to ‘--include-untracked’ while two + prefix arguments are equivalent to ‘--all’. + +‘z Z’ (‘magit-snapshot-both’) + + Create a snapshot of the index and working tree. Untracked files + are included according to popup arguments. One prefix argument is + equivalent to ‘--include-untracked’ while two prefix arguments are + equivalent to ‘--all’. + +‘z I’ (‘magit-snapshot-index’) + + Create a snapshot of the index only. Unstaged and untracked + changes are not stashed. + +‘z W’ (‘magit-snapshot-worktree’) + + Create a snapshot of unstaged changes in the working tree. + Untracked files are included according to popup arguments. One + prefix argument is equivalent to ‘--include-untracked’ while two + prefix arguments are equivalent to ‘--all’-. + +‘z a’ (‘magit-stash-apply’) + + Apply a stash to the working tree. Try to preserve the stash + index. If that fails because there are staged changes, apply + without preserving the stash index. + +‘z p’ (‘magit-stash-pop’) + + Apply a stash to the working tree and remove it from stash list. + Try to preserve the stash index. If that fails because there are + staged changes, apply without preserving the stash index and forgo + removing the stash. + +‘z k’ (‘magit-stash-drop’) + + Remove a stash from the stash list. When the region is active, + offer to drop all contained stashes. + +‘z v’ (‘magit-stash-show’) + + Show all diffs of a stash in a buffer. + +‘z b’ (‘magit-stash-branch’) + + Create and checkout a new BRANCH from STASH. The branch starts at + the commit that was current when the stash was created. + +‘z B’ (‘magit-stash-branch-here’) + + Create and checkout a new BRANCH using ‘magit-branch’ with the + current branch or ‘HEAD’ as the starting-point. Then apply STASH, + dropping it if it applies cleanly. + +‘z f’ (‘magit-stash-format-patch’) + + Create a patch from STASH. + +‘k’ (‘magit-stash-clear’) + + Remove all stashes saved in REF’s reflog by deleting REF. + +‘z l’ (‘magit-stash-list’) + + List all stashes in a buffer. + + -- User Option: magit-stashes-margin + + This option specifies whether the margin is initially shown in + stashes buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + + • STYLE controls how to format the committer date. It can be + one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. + + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + + • AUTHOR controls whether the name of the author is also shown + by default. + + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + +File: magit.info, Node: Transferring, Next: Miscellaneous, Prev: Manipulating, Up: Top + +7 Transferring +************** + +* Menu: + +* Remotes:: +* Fetching:: +* Pulling:: +* Pushing:: +* Creating and Sending Patches:: +* Applying Patches:: + + +File: magit.info, Node: Remotes, Next: Fetching, Up: Transferring + +7.1 Remotes +=========== + +* Menu: + +* The Remote Popup:: +* The Remote Config Popup:: + + +File: magit.info, Node: The Remote Popup, Next: The Remote Config Popup, Up: Remotes + +7.1.1 The Remote Popup +---------------------- + +The popup ‘magit-remote-popup’ is used to add remotes and to make +changes to existing remotes. This popup only deals with remotes +themselves, not with branches or the transfer of commits. Those +features are available from separate popups. + + Also see *note (gitman)git-remote::. + +‘M’ (‘magit-remote-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + + -- User Option: magit-remote-popup-show-variables + + This option controls whether the ‘magit-remote-popup’ shows remote + related Git variables. When set to nil, no variables are displayed + directly in this popup, and the sub-popup + ‘magit-remote-config-popup’ has to be used instead to view and + change remote related variables. + +‘M C’ (‘magit-remote-config-popup’) + + This command shows remote related variables in a separate popup. + By default this asks the user for which remote the variables should + be shown. When ‘magit-remote-popup-show-variables’ is ‘nil’, then + it shows the variables for the upstream of the current branch or + "origin" it that branch has no remote upstream. To select another + remote use a prefix argument. + +‘M a’ (‘magit-remote-add’) + + This command add a remote and fetches it. The remote name and url + are read in the minibuffer. + +‘M r’ (‘magit-remote-rename’) + + This command renames a remote. Both the old and the new names are + read in the minibuffer. + +‘M u’ (‘magit-remote-set-url’) + + This command changes the url of a remote. Both the remote and the + new url are read in the minibuffer. + +‘M k’ (‘magit-remote-remove’) + + This command deletes a remote, read in the minibuffer. + +‘M p’ (‘magit-remote-prune’) + + This command removes stale remote-tracking branches for a remote + read in the minibuffer. + +‘M P’ (‘magit-remote-prune-refspecs’) + + This command removes stale refspecs for a remote read in the + minibuffer. + + A refspec is stale if there no longer exists at least one branch on + the remote that would be fetched due to that refspec. A stale + refspec is problematic because its existence causes Git to refuse + to fetch according to the remaining non-stale refspecs. + + If only stale refspecs remain, then this command offers to either + delete the remote or to replace the stale refspecs with the default + refspec ("+refs/heads/*:refs/remotes/REMOTE/*"). + + This command also removes the remote-tracking branches that were + created due to the now stale refspecs. Other stale branches are + not removed. + + -- User Option: magit-remote-add-set-remote.pushDefault + + This option controls whether the user is asked whether they want to + set ‘remote.pushDefault’ after adding a remote. + + If ‘ask’, then users is always ask. If ‘ask-if-unset’, then the + user is only if the variable isn’t set already. If ‘nil’, then the + user isn’t asked and the variable isn’t set. If the value is a + string, then the variable is set without the user being asked, + provided that the name of the added remote is equal to that string + and the variable isn’t already set. + + +File: magit.info, Node: The Remote Config Popup, Prev: The Remote Popup, Up: Remotes + +7.1.2 The Remote Config Popup +----------------------------- + + -- Command: magit-remote-config-popup + + This prefix command shows the following remote-related Git + variables in a popup buffer. The values can be changed from that + buffer. + + This popup is a sub-popup of the ‘magit-remote-popup’ in which "C" + is bound to this popup. + + The following variables are used to configure a specific remote. The +values are being displayed for the upstream remote of the current +branch. To change the value for another remote invoke +‘magit-remote-config-popup’ with a prefix argument. + + -- Variable: remote.NAME.url + + This variable specifies the url of the remote named NAME. It can + have multiple values. + + -- Variable: remote.NAME.fetch + + The refspec used when fetching from the remote named NAME. It can + have multiple values. + + -- Variable: remote.NAME.pushurl + + This variable specifies the url used for fetching from the remote + named NAME. If it is not specified, then ‘remote.NAME.url’ is used + instead. It can have multiple values. + + -- Variable: remote.NAME.push + + The refspec used when pushing to the remote named NAME. It can + have multiple values. + + -- Variable: remote.NAME.tagOpts + + This variable specifies what tags are fetched by default. If the + value is ‘--no-tags’ then no tags are fetched. If the value is + ‘--tags’, then all tags are fetched. If this variable has not + value, then only tags are fetched that are reachable from fetched + branches. + + +File: magit.info, Node: Fetching, Next: Pulling, Prev: Remotes, Up: Transferring + +7.2 Fetching +============ + +For information about the differences between the _upstream_ and the +_push-remote_, see *note Branching::. + + Also see *note (gitman)git-fetch::. + +‘f’ (‘magit-fetch-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘f p’ (‘magit-fetch-from-pushremote’) + + Fetch from the push-remote of the current branch. + +‘f u’ (‘magit-fetch-from-upstream’) + + Fetch from the upstream of the current branch. + +‘f e’ (‘magit-fetch-other’) + + Fetch from another repository. + +‘f o’ (‘magit-fetch-branch’) + + Fetch a branch from a remote, both of which are read from the + minibuffer. + +‘f r’ (‘magit-fetch-refspec’) + + Fetch from a remote using an explicit refspec, both of which are + read from the minibuffer. + +‘f a’ (‘magit-fetch-all’) + + Fetch from all remotes. + +‘f m’ (‘magit-submodule-fetch’) + + Fetch all submodules. With a prefix argument fetch all remotes of + all submodules. + + Instead of using one popup for fetching and another for pulling, you +could also use ‘magit-pull-and-fetch-popup’. See its doc-string for +more information. + + +File: magit.info, Node: Pulling, Next: Pushing, Prev: Fetching, Up: Transferring + +7.3 Pulling +=========== + +For information about the differences between the _upstream_ and the +_push-remote_, see *note Branching::. + + Also see *note (gitman)git-pull::. + +‘F’ (‘magit-pull-popup’) + + This prefix command shows the following suffix commands in a popup + buffer. + +‘F p’ (‘magit-pull-from-pushremote’) + + Pull from the push-remote of the current branch. + +‘F u’ (‘magit-pull-from-upstream’) + + Pull from the upstream of the current branch. + +‘F e’ (‘magit-pull-branch’) + + Pull from a branch read in the minibuffer. + + Instead of using one popup for fetching and another for pulling, you +could also use ‘magit-pull-and-fetch-popup’. See its doc-string for +more information. + + +File: magit.info, Node: Pushing, Next: Creating and Sending Patches, Prev: Pulling, Up: Transferring + +7.4 Pushing +=========== + +For information about the differences between the _upstream_ and the +_push-remote_, see *note Branching::. + + Also see *note (gitman)git-push::. + +‘P’ (‘magit-push-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘P p’ (‘magit-push-current-to-pushremote’) + + Push the current branch to ‘branch..pushRemote’ or if that is + unset to ‘remote.pushDefault’. + + When ‘magit-push-current-set-remote-if-missing’ is non-nil and the + push-remote is not configured, then read the push-remote from the + user, set it, and then push to it. With a prefix argument the + push-remote can be changed before pushed to it. + +‘P u’ (‘magit-push-current-to-upstream’) + + Push the current branch to its upstream branch. + + When ‘magit-push-current-set-remote-if-missing’ is non-nil and the + push-remote is not configured, then read the upstream from the + user, set it, and then push to it. With a prefix argument the + push-remote can be changed before pushed to it. + +‘P e’ (‘magit-push-current’) + + Push the current branch to a branch read in the minibuffer. + +‘P o’ (‘magit-push-other’) + + Push an arbitrary branch or commit somewhere. Both the source and + the target are read in the minibuffer. + +‘P r’ (‘magit-push-refspecs’) + + Push one or multiple refspecs to a remote, both of which are read + in the minibuffer. + + To use multiple refspecs, separate them with commas. Completion is + only available for the part before the colon, or when no colon is + used. + +‘P m’ (‘magit-push-matching’) + + Push all matching branches to another repository. If multiple + remotes exit, then read one from the user. If just one exists, use + that without requiring confirmation. + +‘P t’ (‘magit-push-tags’) + + Push all tags to another repository. If only one remote exists, + then push to that. Otherwise prompt for a remote, offering the + remote configured for the current branch as default. + +‘P T’ (‘magit-push-tag’) + + Push a tag to another repository. + + Two more push commands exist, which by default are not available from +the push popup. See their doc-strings for instructions on how to add +them to the popup. + + -- Command: magit-push-implicitly args + + Push somewhere without using an explicit refspec. + + This command simply runs ‘git push -v [ARGS]’. ARGS are the + arguments specified in the popup buffer. No explicit refspec + arguments are used. Instead the behavior depends on at least these + Git variables: ‘push.default’, ‘remote.pushDefault’, + ‘branch..pushRemote’, ‘branch..remote’, + ‘branch..merge’, and ‘remote..push’. + + -- Command: magit-push-to-remote remote args + + Push to the remote REMOTE without using an explicit refspec. The + remote is read in the minibuffer. + + This command simply runs ‘git push -v [ARGS] REMOTE’. ARGS are the + arguments specified in the popup buffer. No refspec arguments are + used. Instead the behavior depends on at least these Git + variables: ‘push.default’, ‘remote.pushDefault’, + ‘branch..pushRemote’, ‘branch..remote’, + ‘branch..merge’, and ‘remote..push’. + + -- User Option: magit-push-current-set-remote-if-missing + + This option controls whether missing remotes are configured before + pushing. + + When ‘nil’, then the command ‘magit-push-current-to-pushremote’ and + ‘magit-push-current-to-upstream’ do not appear in the push popup if + the push-remote resp. upstream is not configured. If the user + invokes one of these commands anyway, then it raises an error. + + When ‘non-nil’, then these commands always appear in the push + popup. But if the required configuration is missing, then they do + appear in a way that indicates that this is the case. If the user + invokes one of them, then it asks for the necessary configuration, + stores the configuration, and then uses it to push a first time. + + This option also affects whether the argument ‘--set-upstream’ is + available in the popup. If the value is ‘non-nil’, then that + argument is redundant. But note that changing the value of this + option does not take affect immediately, the argument will only be + added or removed after restarting Emacs. + + +File: magit.info, Node: Creating and Sending Patches, Next: Applying Patches, Prev: Pushing, Up: Transferring + +7.5 Creating and Sending Patches +================================ + +‘W’ (‘magit-patch-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘W p’ (‘magit-format-patch’) + + Create patches for a set commits. If the region marks commits, + then create patches for those. Otherwise prompt for a range or a + single commit, defaulting to the commit at point. + +‘W r’ (‘magit-request-pull’) + + Request that upstream pulls from your public repository. + + It is also possible to save a plain patch file by using ‘C-x C-w’ +inside a ‘magit-diff-mode’ or ‘magit-revision-mode’ buffer. + + +File: magit.info, Node: Applying Patches, Prev: Creating and Sending Patches, Up: Transferring + +7.6 Applying Patches +==================== + +Also see *note (gitman)git-am::. and *note (gitman)git-apply::. + +‘w’ (‘magit-am-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘w w’ (‘magit-am-apply-patches’) + + Apply one or more patches. If the region marks files, then apply + those patches. Otherwise read a file name in the minibuffer + defaulting to the file at point. + +‘w m’ (‘magit-am-apply-maildir’) + + Apply the patches from a maildir. + + When an "am" operation is in progress, then the popup buffer features +these commands instead. + +‘w w’ (‘magit-am-continue’) + + Resume the current patch applying sequence. + +‘w s’ (‘magit-am-skip’) + + Skip the stopped at patch during a patch applying sequence. + +‘w a’ (‘magit-am-abort’) + + Abort the current patch applying sequence. This discards all + changes made since the sequence started. + + In addition to the commands listed at the top, the "am" popup also +has a binding for the related "patch" popup. + +‘w a’ (‘magit-patch-apply-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘w a a’ (‘magit-patch-apply’) + + This command applies a simple patch file, which may not contain any + Git metadata in addition to the actual diff. + + +File: magit.info, Node: Miscellaneous, Next: Customizing, Prev: Transferring, Up: Top + +8 Miscellaneous +*************** + +* Menu: + +* Tagging:: +* Notes:: +* Submodules:: +* Subtree:: +* Worktree:: +* Common Commands:: +* Wip Modes:: +* Minor Mode for Buffers Visiting Files:: +* Minor Mode for Buffers Visiting Blobs:: + + +File: magit.info, Node: Tagging, Next: Notes, Up: Miscellaneous + +8.1 Tagging +=========== + +Also see *note (gitman)git-tag::. + +‘t’ (‘magit-tag-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘t t’ (‘magit-tag-create’) + + Create a new tag with the given NAME at REV. With a prefix + argument annotate the tag. + +‘t k’ (‘magit-tag-delete’) + + Delete one or more tags. If the region marks multiple tags (and + nothing else), then offer to delete those. Otherwise, prompt for a + single tag to be deleted, defaulting to the tag at point. + +‘t p’ (‘magit-tag-prune’) + + Offer to delete tags missing locally from REMOTE, and vice versa. + + -- Command: magit-tag-release + + Create an opinionated release tag. + + Assume version tags that match "\\‘v?[0-9]\*\\’". Prompt for the + name of the new tag using the highest existing tag as initial input + and call "git tag –annotate –sign -m MSG" TAG, regardless of + whether these arguments are enabled in the popup. Given a TAG + "v1.2.3" and a repository "/path/to/foo-bar", the MESSAGE would be + "Foo-Bar 1.2.3". + + Because it is so opinionated, this command is not available from + the tag popup by default. + + +File: magit.info, Node: Notes, Next: Submodules, Prev: Tagging, Up: Miscellaneous + +8.2 Notes +========= + +Also see *note (gitman)git-notes::. + +‘T’ (‘magit-notes-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + +‘T T’ (‘magit-notes-edit’) + + Edit the note attached to a commit, defaulting to the commit at + point. + + By default use the value of Git variable ‘core.notesRef’ or + "refs/notes/commits" if that is undefined. + +‘T r’ (‘magit-notes-remove’) + + Remove the note attached to a commit, defaulting to the commit at + point. + + By default use the value of Git variable ‘core.notesRef’ or + "refs/notes/commits" if that is undefined. + +‘T p’ (‘magit-notes-prune’) + + Remove notes about unreachable commits. + + It is possible to merge one note ref into another. That may result +in conflicts which have to resolved in the temporary worktree +".git/NOTES_MERGE_WORKTREE". + +‘T m’ (‘magit-notes-merge’) + + Merge the notes of a ref read from the user into the current notes + ref. The current notes ref is the value of Git variable + ‘core.notesRef’ or "refs/notes/commits" if that is undefined. + + When a notes merge is in progress then the popup features the +following suffix commands, instead of those listed above. + +‘T c’ (‘magit-notes-merge-commit’) + + Commit the current notes ref merge, after manually resolving + conflicts. + +‘T a’ (‘magit-notes-merge-abort’) + + Abort the current notes ref merge. + + The following variables control what notes reference ‘magit-notes-*’, +‘git notes’ and ‘git show’ act on and display. Both the local and +global values are displayed and can be modified. + + -- Variable: core.notesRef + + This variable specifies the notes ref that is displayed by default + and which commands act on by default. + + -- Variable: notes.displayRef + + This variable specifies additional notes ref to be displayed in + addition to the ref specified by ‘core.notesRef’. It can have + multiple values and may end with ‘*’ to display all refs in the + ‘refs/notes/’ namespace (or ‘**’ if some names contain slashes). + + +File: magit.info, Node: Submodules, Next: Subtree, Prev: Notes, Up: Miscellaneous + +8.3 Submodules +============== + +Also see *note (gitman)git-submodule::. + +* Menu: + +* Listing Submodules:: +* Submodule Popup:: + + +File: magit.info, Node: Listing Submodules, Next: Submodule Popup, Up: Submodules + +8.3.1 Listing Submodules +------------------------ + +The command ‘magit-list-submodules’ displays a list of the current +repository’s submodules in a separate buffer. It’s also possible to +display information about submodules directly in the status buffer of +the super-repository by adding ‘magit-insert-submodules’ to the hook +‘magit-status-sections-hook’ as described in *note Status Module +Sections::. + + -- Command: magit-list-submodules + + This command displays a list of the current repository’s submodules + in a separate buffer. + + It can be invoked by pressing ‘RET’ on the section titled + "Modules". + + -- User Option: magit-submodule-list-columns + + This option controls what columns are displayed by the command + ‘magit-list-submodules’ and how they are displayed. + + Each element has the form ‘(HEADER WIDTH FORMAT PROPS)’. + + HEADER is the string displayed in the header. WIDTH is the width + of the column. FORMAT is a function that is called with one + argument, the repository identification (usually its basename), and + with ‘default-directory’ bound to the toplevel of its working tree. + It has to return a string to be inserted or nil. PROPS is an alist + that supports the keys ‘:right-align’ and ‘:pad-right’. + + -- Function: magit-insert-submodules + + Insert sections for all submodules. For each section insert the + path, the branch, and the output of ‘git describe --tags’, or, + failing that, the abbreviated HEAD commit hash. + + Press ‘RET’ on such a submodule section to show its own status + buffer. Press ‘RET’ on the "Modules" section to display a list of + submodules in a separate buffer. This shows additional information + not displayed in the super-repository’s status buffer. + + +File: magit.info, Node: Submodule Popup, Prev: Listing Submodules, Up: Submodules + +8.3.2 Submodule Popup +--------------------- + +‘o’ (‘magit-submodule-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + + Some of the below commands default to act on the modules that are +selected using the region. For brevity their description talk about +"the selected modules", but if no modules are selected, then they act on +the current module instead, or if point isn’t on a module, then the read +a single module to act on. With a prefix argument these commands ignore +the selection and the current module and instead act on all suitable +modules. + +‘o a’ (‘magit-submodule-add’) + + This commands adds the repository at URL as a module. Optional + PATH is the path to the module relative to the root of the + super-project. If it is nil then the path is determined based on + URL. + +‘o r’ (‘magit-submodule-register’) + + This command registers the selected modules by copying their urls + from ".gitmodules" to "$GIT_DIR/config". These values can then be + edited before running ‘magit-submodule-populate’. If you don’t + need to edit any urls, then use the latter directly. + +‘o p’ (‘magit-submodule-populate’) + + This command creates the working directory or directories of the + selected modules, checking out the recorded commits. + +‘o u’ (‘magit-submodule-update’) + + This command updates the selected modules checking out the recorded + commits. + +‘o s’ (‘magit-submodule-synchronize’) + + This command synchronizes the urls of the selected modules, copying + the values from ".gitmodules" to the ".git/config" of the + super-project as well those of the modules. + +‘o d’ (‘magit-submodule-unpopulate’) + + This command removes the working directory of the selected modules. + +‘o l’ (‘magit-list-submodules’) + + This command displays a list of the current repository’s modules. + +‘o f’ (‘magit-fetch-modules’) + + This command fetches all modules. + + Option ‘magit-fetch-modules-jobs’ controls how many submodules are + being fetched in parallel. Also fetch the super-repository, + because ‘git fetch’ does not support not doing that. With a prefix + argument fetch all remotes. + + +File: magit.info, Node: Subtree, Next: Worktree, Prev: Submodules, Up: Miscellaneous + +8.4 Subtree +=========== + +Also see *note (gitman)git-subtree::. + +‘O’ (‘magit-tree-popup’) + + This prefix command shows the following suffix commands along with + the appropriate infix arguments in a popup buffer. + + Most infix arguments only apply to some of the ‘git subtree’ +subcommands. When an argument that does not apply to the invoked +command is set, then it is silently ignored. + + When the ‘--prefix’ argument is set in the popup buffer, then that is +used. Otherwise the prefix is read in the minibuffer. + +‘O a’ (‘magit-subtree-add’) + + Add COMMIT from REPOSITORY as a new subtree at PREFIX. + +‘O c’ (‘magit-subtree-add-commit’) + + Add COMMIT as a new subtree at PREFIX. + +‘O m’ (‘magit-subtree-merge’) + + Merge COMMIT into the PREFIX subtree. + +‘O f’ (‘magit-subtree-pull’) + + Pull COMMIT from REPOSITORY into the PREFIX subtree. + +‘O p’ (‘magit-subtree-push’) + + Extract the history of the subtree PREFIX and push it to REF on + REPOSITORY. + +‘O s’ (‘magit-subtree-split’) + + Extract the history of the subtree PREFIX. + + +File: magit.info, Node: Worktree, Next: Common Commands, Prev: Subtree, Up: Miscellaneous + +8.5 Worktree +============ + +Also see *note (gitman)git-worktree::. + +‘%’ (‘magit-worktree-popup’) + + This prefix command shows the following suffix commands in a popup + buffer. + +‘% b’ (‘magit-worktree-checkout’) + + Checkout BRANCH in a new worktree at PATH. + +‘% c’ (‘magit-worktree-branch’) + + Create a new BRANCH and check it out in a new worktree at PATH. + +‘% p’ (‘magit-worktree-checkout-pull-request’) + + Create, configure and checkout a new worktree from a pull-request. + + This is like ‘magit-checkout-pull-request’ (which see) except that + it also creates a new worktree. + +‘% k’ (‘magit-worktree-delete’) + + Delete a worktree, defaulting to the worktree at point. The + primary worktree cannot be deleted. + +‘% g’ (‘magit-worktree-status’) + + Show the status for the worktree at point. + + If there is no worktree at point, then read one in the minibuffer. + If the worktree at point is the one whose status is already being + displayed in the current buffer, then show it in Dired instead. + + +File: magit.info, Node: Common Commands, Next: Wip Modes, Prev: Worktree, Up: Miscellaneous + +8.6 Common Commands +=================== + +These are some of the commands that can be used in all buffers whose +major-modes derive from ‘magit-mode’. There are other common commands +beside the ones below, but these didn’t fit well anywhere else. + +‘M-w’ (‘magit-copy-section-value’) + + This command saves the value of the current section to the + ‘kill-ring’, and, provided that the current section is a commit, + branch, or tag section, it also pushes the (referenced) revision to + the ‘magit-revision-stack’. + + When the current section is a branch or a tag, and a prefix + argument is used, then it saves the revision at its tip to the + ‘kill-ring’ instead of the reference name. + +‘C-w’ (‘magit-copy-buffer-revision’) + + This command saves the revision being displayed in the current + buffer to the ‘kill-ring’ and also pushes it to the + ‘magit-revision-stack’. It is mainly intended for use in + ‘magit-revision-mode’ buffers, the only buffers where it is always + unambiguous exactly which revision should be saved. + + Most other Magit buffers usually show more than one revision, in + some way or another, so this command has to select one of them, and + that choice might not always be the one you think would have been + the best pick. + + Outside of Magit ‘M-w’ and ‘C-w’ are usually bound to +‘kill-ring-save’ and ‘kill-region’, and these commands would also be +useful in Magit buffers. Therefore when the region is active, then both +of these commands behave like ‘kill-ring-save’ instead of as described +above. + + +File: magit.info, Node: Wip Modes, Next: Minor Mode for Buffers Visiting Files, Prev: Common Commands, Up: Miscellaneous + +8.7 Wip Modes +============= + +Git keeps *committed* changes around long enough for users to recover +changes they have accidentally deleted. It does so by not garbage +collecting any committed but no longer referenced objects for a certain +period of time, by default 30 days. + + But Git does *not* keep track of *uncommitted* changes in the working +tree and not even the index (the staging area). Because Magit makes it +so convenient to modify uncommitted changes, it also makes it easy to +shoot yourself in the foot in the process. + + For that reason Magit provides a global mode that saves *tracked* +files to work-in-progress references after or before certain actions. +(At present untracked files are never saved and for technical reasons +nothing is saved before the first commit has been created). + + Two separate work-in-progress references are used to track the state +of the index and of the working tree: ‘refs/wip/index/’ and +‘refs/wip/wtree/’, where ‘’ is the full ref of the +current branch, e.g. ‘refs/heads/master’. When the ‘HEAD’ is detached +then ‘HEAD’ is used in place of ‘’. + + Checking out another branch (or detaching ‘HEAD’) causes the use of +different wip refs for subsequent changes. + + -- User Option: magit-wip-mode + + When this mode is enabled, then uncommitted changes are committed + to dedicated work-in-progress refs whenever appropriate (i.e. when + dataloss would be a possibility otherwise). + + Setting this variable directly does not take effect; either use the + Custom interface to do so or call the respective mode function. + + For historic reasons this mode is implemented on top of four other + ‘magit-wip-*’ modes, which can also be used individually, if you + want finer control over when the wip refs are updated; but that is + discouraged. See *note Legacy Wip Modes::. + + To view the log for a branch and its wip refs use the commands +‘magit-wip-log’ and ‘magit-wip-log-current’. You should use ‘--graph’ +when using these commands. + + -- Command: magit-wip-log + + This command shows the log for a branch and its wip refs. With a + negative prefix argument only the worktree wip ref is shown. + + The absolute numeric value of the prefix argument controls how many + "branches" of each wip ref are shown. This is only relevant if the + value of ‘magit-wip-merge-branch’ is ‘nil’. + + -- Command: magit-wip-log-current + + This command shows the log for the current branch and its wip refs. + With a negative prefix argument only the worktree wip ref is shown. + + The absolute numeric value of the prefix argument controls how many + "branches" of each wip ref are shown. This is only relevant if the + value of ‘magit-wip-merge-branch’ is ‘nil’. + +‘X w’ (‘magit-reset-worktree’) + + This command resets the working tree to some commit read from the + user and defaulting to the commit at point, while keeping the + ‘HEAD’ and index as-is. + + This can be used to restore files to the state committed to a wip + ref. Note that this will discard any unstaged changes that might + have existed before invoking this command (but of course only after + committing that to the working tree wip ref). + + Note that even if you enable ‘magit-wip-mode’ this won’t give you +perfect protection. The most likely scenario for losing changes despite +the use of ‘magit-wip-mode’ is making a change outside Emacs and then +destroying it also outside Emacs. In some such a scenario, Magit, being +an Emacs package, didn’t get the opportunity to keep you from shooting +yourself in the foot. + + When you are unsure whether Magit did commit a change to the wip +refs, then you can explicitly request that all changes to all tracked +files are being committed. + +‘M-x magit-wip-commit’ (‘magit-wip-commit’) + + This command commits all changes to all tracked files to the index + and working tree work-in-progress refs. Like the modes described + above, it does not commit untracked files, but it does check all + tracked files for changes. Use this command when you suspect that + the modes might have overlooked a change made outside Emacs/Magit. + + -- User Option: magit-wip-namespace + + The namespace used for work-in-progress refs. It has to end with a + slash. The wip refs are named ‘index/’ and + ‘wtree/’. When snapshots are created while + the ‘HEAD’ is detached then ‘HEAD’ is used in place of + ‘’. + + -- User Option: magit-wip-mode-lighter + + Mode-line lighter for ‘magit-wip--mode’. + +* Menu: + +* Wip Graph:: +* Legacy Wip Modes:: + + +File: magit.info, Node: Wip Graph, Next: Legacy Wip Modes, Up: Wip Modes + +8.7.1 Wip Graph +--------------- + + -- User Option: magit-wip-merge-branch + + This option controls whether the current branch is merged into the + wip refs after a new commit was created on the branch. + + If non-nil and the current branch has new commits, then it is + merged into the wip ref before creating a new wip commit. This + makes it easier to inspect wip history and the wip commits are + never garbage collected. + + If nil and the current branch has new commits, then the wip ref is + reset to the tip of the branch before creating a new wip commit. + With this setting wip commits are eventually garbage collected. + + When ‘magit-wip-merge-branch’ is ‘t’, then the history looks like +this: + + *--*--*--*--*--* refs/wip/index/refs/heads/master + / / / + A-----B-----C refs/heads/master + + When ‘magit-wip-merge-branch’ is ‘nil’, then creating a commit on the +real branch and then making a change causes the wip refs to be recreated +to fork from the new commit. But the old commits on the wip refs are +not lost. They are still available from the reflog. To make it easier +to see when the fork point of a wip ref was changed, an additional +commit with the message "restart autosaving" is created on it (‘xxO’ +commits below are such boundary commits). + + Starting with + + BI0---BI1 refs/wip/index/refs/heads/master + / + A---B refs/heads/master + \ + BW0---BW1 refs/wip/wtree/refs/heads/master + + and committing the staged changes and editing and saving a file would +result in + + BI0---BI1 refs/wip/index/refs/heads/master + / + A---B---C refs/heads/master + \ \ + \ CW0---CW1 refs/wip/wtree/refs/heads/master + \ + BW0---BW1 refs/wip/wtree/refs/heads/master@{2} + + The fork-point of the index wip ref is not changed until some change +is being staged. Likewise just checking out a branch or creating a +commit does not change the fork-point of the working tree wip ref. The +fork-points are not adjusted until there actually is a change that +should be committed to the respective wip ref. + + +File: magit.info, Node: Legacy Wip Modes, Prev: Wip Graph, Up: Wip Modes + +8.7.2 Legacy Wip Modes +---------------------- + +It is recommended that you use the mode ‘magit-wip-mode’ (which see) and +ignore the existence of the following modes, which are preserved for +historic reasons. + + Setting the following variables directly does not take effect; either +use the Custom interface to do so or call the respective mode functions. + + -- User Option: magit-wip-after-save-mode + + When this mode is enabled, then saving a buffer that visits a file + tracked in a Git repository causes its current state to be + committed to the working tree wip ref for the current branch. + + -- User Option: magit-wip-after-apply-mode + + When this mode is enabled, then applying (i.e. staging, unstaging, + discarding, reversing, and regularly applying) a change to a file + tracked in a Git repository causes its current state to be + committed to the index and/or working tree wip refs for the current + branch. + + If you only ever edit files using Emacs and only ever interact with +Git using Magit, then the above two modes should be enough to protect +each and every change from accidental loss. In practice nobody does +that. Two additional modes exists that do commit to the wip refs before +making changes that could cause the loss of earlier changes. + + -- User Option: magit-wip-before-change-mode + + When this mode is enabled, then certain commands commit the + existing changes to the files they are about to make changes to. + + -- User Option: magit-wip-initial-backup-mode + + When this mode is enabled, then the current version of a file is + committed to the worktree wip ref before the buffer visiting that + file is saved for the first time since the buffer was created. + + This backs up the same version of the file that ‘backup-buffer’ + would save. While ‘backup-buffer’ uses a backup file, this mode + uses the same worktree wip ref as used by the other Magit Wip + modes. Like ‘backup-buffer’, it only does this once; unless you + kill the buffer and visit the file again only one backup will be + created per Emacs session. + + This mode ignores the variables that affect ‘backup-buffer’ and can + be used along-side that function, which is recommended because it + only backs up files that are tracked in a Git repository. + + -- User Option: magit-wip-after-save-local-mode-lighter + + Mode-line lighter for ‘magit-wip-after-save-local-mode’. + + -- User Option: magit-wip-after-apply-mode-lighter + + Mode-line lighter for ‘magit-wip-after-apply-mode’. + + -- User Option: magit-wip-before-change-mode-lighter + + Mode-line lighter for ‘magit-wip-before-change-mode’. + + -- User Option: magit-wip-initial-backup-mode-lighter + + Mode-line lighter for ‘magit-wip-initial-backup-mode’. + + +File: magit.info, Node: Minor Mode for Buffers Visiting Files, Next: Minor Mode for Buffers Visiting Blobs, Prev: Wip Modes, Up: Miscellaneous + +8.8 Minor Mode for Buffers Visiting Files +========================================= + +The ‘magit-file-mode’ enables certain Magit features in file-visiting +buffers belonging to a Git repository. It should be enabled globally +using ‘global-magit-file-mode’. Currently this mode only establishes a +few key bindings, but this might be extended in the future. + + -- User Option: magit-file-mode + + Whether to establish certain Magit key bindings in all + file-visiting buffers belonging to a Git repository. This + establishes the bindings suggested in *note Getting Started:: (but + only for file-visiting buffers), and additionally binds ‘C-c M-g’ + to ‘magit-file-popup’. + +‘C-c M-g’ (‘magit-file-popup’) + + This prefix command shows a popup buffer featuring suffix commands + that operate on the file being visited in the current buffer. + +‘C-c M-g s’ (‘magit-stage-file’) + + Stage all changes to the file being visited in the current buffer. + +‘C-c M-g u’ (‘magit-unstage-file’) + + Unstage all changes to the file being visited in the current + buffer. + +‘C-c M-g c’ (‘magit-commit-popup’) + + This prefix command shows suffix commands along with the + appropriate infix arguments in a popup buffer. See *note + Initiating a Commit::. + +‘C-c M-g D’ (‘magit-diff-buffer-file-popup’) + + This prefix command shows the same suffix commands and infix + arguments in a popup buffer as ‘magit-diff-popup’. But this + variant has to be called from a file-visiting buffer and the + visited file is automatically used in the popup to limit the diff + to that file. + +‘C-c M-g d’ (‘magit-diff-buffer-file’) + + This command shows the diff for the file of blob that the current + buffer visits. + + -- User Option: magit-diff-buffer-file-locked + + This option controls whether ‘magit-diff-buffer-file’ uses a + dedicated buffer. See *note Modes and Buffers::. + +‘C-c M-g L’ (‘magit-log-buffer-file-popup’) + + This prefix command shows the same suffix commands and infix + arguments in a popup buffer as ‘magit-log-popup’. But this variant + has to be called from a file-visiting buffer and the visited file + is automatically used in the popup to limit the log to that file. + +‘C-c M-g l’ (‘magit-log-buffer-file’) + + This command shows the log for the file of blob that the current + buffer visits. Renames are followed when a prefix argument is used + or when ‘--follow’ is part of ‘magit-log-arguments’. When the + region is active, the log is restricted to the selected line range. + +‘C-c M-g t’ (‘magit-log-trace-definition’) + + This command shows the log for the definition at point. + + -- User Option: magit-log-buffer-file-locked + + This option controls whether ‘magit-log-buffer-file’ uses a + dedicated buffer. See *note Modes and Buffers::. + +‘C-c M-g B’ (‘magit-blame-popup’) + + This prefix command shows all blaming suffix command along with the + appropriate infix arguments in a popup buffer. See *note + Blaming::. + +‘C-c M-g b’ (‘magit-blame-addition’) + + This command shows for each line the revision in which it was + added. + +‘C-c M-g r’ (‘magit-blame-removal’) + + This command shows for each line the revision in which it was + removed. This command is only available in blob-visiting buffers. + +‘C-c M-g f’ (‘magit-blame-reverse’) + + This command shows for each line the last revision in which it + still exists. This command is only available in blob-visiting + buffers. + +‘C-c M-g e’ (‘magit-edit-line-commit’) + + This command makes the commit editable that added the current line. + + With a prefix argument it makes the commit editable that removes + the line, if any. The commit is determined using ‘git blame’ and + made editable using ‘git rebase --interactive’ if it is reachable + from ‘HEAD’, or by checking out the commit (or a branch that points + at it) otherwise. + +‘C-c M-g p’ (‘magit-blob-previous’) + + Visit the previous blob which modified the current file. + + There are a few additional commands that operate on a single file but +are not available from the file popup by default: + + -- Command: magit-file-rename + + This command renames a file read from the user. + + -- Command: magit-file-delete + + This command deletes a file read from the user. + + -- Command: magit-file-untrack + + This command untracks a file read from the user. + + -- Command: magit-file-checkout + + This command updates a file in the working tree and index to the + contents from a revision. Both the revision and file are read from + the user. + + You could add them to the popup like so: + + (magit-define-popup-action 'magit-file-popup + ?R "Rename file" 'magit-file-rename) + (magit-define-popup-action 'magit-file-popup + ?K "Delete file" 'magit-file-delete) + (magit-define-popup-action 'magit-file-popup + ?U "Untrack file" 'magit-file-untrack) + (magit-define-popup-action 'magit-file-popup + ?C "Checkout file" 'magit-file-checkout) + + +File: magit.info, Node: Minor Mode for Buffers Visiting Blobs, Prev: Minor Mode for Buffers Visiting Files, Up: Miscellaneous + +8.9 Minor Mode for Buffers Visiting Blobs +========================================= + +The ‘magit-blob-mode’ enables certain Magit features in blob-visiting +buffers. Such buffers can be created using ‘magit-find-file’ and some +of the commands mentioned below, which also take care of turning on this +minor mode. Currently this mode only establishes a few key bindings, +but this might be extended. + +‘p’ (‘magit-blob-previous’) + + Visit the previous blob which modified the current file. + +‘n’ (‘magit-blob-next’) + + Visit the next blob which modified the current file. + +‘q’ (‘magit-kill-this-buffer’) + + Kill the current buffer. + + +File: magit.info, Node: Customizing, Next: Plumbing, Prev: Miscellaneous, Up: Top + +9 Customizing +************* + +Both Git and Emacs are highly customizable. Magit is both a Git +porcelain as well as an Emacs package, so it makes sense to customize it +using both Git variables as well as Emacs options. However this +flexibility doesn’t come without problems, including but not limited to +the following. + + • Some Git variables automatically have an effect in Magit without + requiring any explicit support. Sometimes that is desirable - in + other cases, it breaks Magit. + + When a certain Git setting breaks Magit but you want to keep using + that setting on the command line, then that can be accomplished by + overriding the value for Magit only by appending something like + ‘("-c" "some.variable=compatible-value")’ to + ‘magit-git-global-arguments’. + + • Certain settings like ‘fetch.prune=true’ are respected by Magit + commands (because they simply call the respective Git command) but + their value is not reflected in the respective popup buffers. In + this case the ‘--prune’ argument in ‘magit-fetch-popup’ might be + active or inactive depending on the value of + ‘magit-fetch-arguments’ only, but that doesn’t keep the Git + variable from being honored by the suffix commands anyway. So + pruning might happen despite the ‘--prune’ arguments being + displayed in a way that seems to indicate that no pruning will + happen. + + I intend to address these and similar issues in a future release. + +* Menu: + +* Per-Repository Configuration:: +* Essential Settings:: + + +File: magit.info, Node: Per-Repository Configuration, Next: Essential Settings, Up: Customizing + +9.1 Per-Repository Configuration +================================ + +Magit can be configured on a per-repository level using both Git +variables as well as Emacs options. + + To set a Git variable for one repository only, simply set it in +‘/path/to/repo/.git/config’ instead of ‘$HOME/.gitconfig’ or +‘/etc/gitconfig’. See *note (gitman)git-config::. + + Similarly, Emacs options can be set for one repository only by +editing ‘/path/to/repo/.dir-locals.el’. See *note (emacs)Directory +Variables::. For example to disable automatic refreshes of +file-visiting buffers in just one huge repository use this: + + • ‘/path/to/huge/repo/.dir-locals.el’ + + ((nil . ((magit-refresh-buffers . nil)))) + + If you want to apply the same settings to several, but not all, +repositories then keeping the repository-local config files in sync +would quickly become annoying. To avoid that you can create config +files for certain classes of repositories (e.g. "huge repositories") +and then include those files in the per-repository config files. For +example: + + • ‘/path/to/huge/repo/.git/config’ + + [include] + path = /path/to/huge-gitconfig + + • ‘/path/to/huge-gitconfig’ + + [status] + showUntrackedFiles = no + + • ‘$HOME/.emacs.d/init.el’ + + (dir-locals-set-class-variables 'huge-git-repository + '((nil . ((magit-refresh-buffers . nil))))) + + (dir-locals-set-directory-class + "/path/to/huge/repo/" 'huge-git-repository) + + +File: magit.info, Node: Essential Settings, Prev: Per-Repository Configuration, Up: Customizing + +9.2 Essential Settings +====================== + +The next two sections list and discuss several variables that many users +might want to customize, for safety and/or performance reasons. + +* Menu: + +* Safety:: +* Performance:: + + +File: magit.info, Node: Safety, Next: Performance, Up: Essential Settings + +9.2.1 Safety +------------ + +This section discusses various variables that you might want to change +(or *not* change) for safety reasons. + + Git keeps *committed* changes around long enough for users to recover +changes they have accidentally been deleted. It does not do the same +for *uncommitted* changes in the working tree and not even the index +(the staging area). Because Magit makes it so easy to modify +uncommitted changes, it also makes it easy to shoot yourself in the foot +in the process. For that reason Magit provides three global modes that +save *tracked* files to work-in-progress references after or before +certain actions. See *note Wip Modes::. + + These modes are not enabled by default because of performance +concerns. Instead a lot of potentially destructive commands require +confirmation every time they are used. In many cases this can be +disabled by adding a symbol to ‘magit-no-confirm’ (see *note Completion +and Confirmation::). If you enable the various wip modes then you +should add ‘safe-with-wip’ to this list. + + Similarly it isn’t necessary to require confirmation before moving a +file to the system trash - if you trashed a file by mistake then you can +recover it from the there. Option ‘magit-delete-by-moving-to-trash’ +controls whether the system trash is used, which is the case by default. +Nevertheless, ‘trash’ isn’t a member of ‘magit-no-confirm’ - you might +want to change that. + + By default buffers visiting files are automatically reverted when the +visited file changes on disk. This isn’t as risky as it might seem, but +to make an informed decision you should see *note Risk of Reverting +Automatically::. + + +File: magit.info, Node: Performance, Prev: Safety, Up: Essential Settings + +9.2.2 Performance +----------------- + +After Magit has run ‘git’ for side-effects, it also refreshes the +current Magit buffer and the respective status buffer. This is +necessary because otherwise outdated information might be displayed +without the user noticing. Magit buffers are updated by recreating +their content from scratch, which makes updating simpler and less +error-prone, but also more costly. Keeping it simple and just +re-creating everything from scratch is an old design decision and +departing from that will require major refactoring. + + I plan to do that in time for the next major release. I also intend +to create logs and diffs asynchronously, which should also help a lot +but also requires major refactoring. + + Meanwhile you can tell Magit to only automatically refresh the +current Magit buffer, but not the status buffer. If you do that, then +the status buffer is only refreshed automatically if it is the current +buffer. + + (setq magit-refresh-status-buffer nil) + + You should also check whether any third-party packages have added +anything to ‘magit-refresh-buffer-hook’, ‘magit-status-refresh-hook’, +‘magit-pre-refresh-hook’, and ‘magit-post-refresh-hook’. If so, then +check whether those additions impact performance significantly. Setting +‘magit-refresh-verbose’ and then inspecting the output in the +‘*Messages*’ buffer, should help doing so. + + Magit also reverts buffers for visited files located inside the +current repository when the visited file changes on disk. That is +implemented on top of ‘auto-revert-mode’ from the built-in library +‘autorevert’. To figure out whether that impacts performance, check +whether performance is significantly worse, when many buffers exist +and/or when some buffers visit files using TRAMP. If so, then this +should help. + + (setq auto-revert-buffer-list-filter + 'magit-auto-revert-repository-buffers-p) + + For alternative approaches see *note Automatic Reverting of +File-Visiting Buffers::. + + If you have enabled any features that are disabled by default, then +you should check whether they impact performance significantly. It’s +likely that they were not enabled by default because it is known that +they reduce performance at least in large repositories. + + If performance is only slow inside certain unusually large +repositories, then you might want to disable certain features on a +per-repository or per-repository-class basis only. See *note +Per-Repository Configuration::. + +* Menu: + +* Microsoft Windows Performance:: +* MacOS Performance:: + +Log Performance +............... + +When showing logs, Magit limits the number of commits initially shown in +the hope that this avoids unnecessary work. When using ‘--graph’ is +used, then this unfortunately does not have the desired effect for large +histories. Junio, Git’s maintainer, said on the git mailing list +(): "‘--graph’ wants to +compute the whole history and the max-count only affects the output +phase after ‘--graph’ does its computation". + + In other words, it’s not that Git is slow at outputting the +differences, or that Magit is slow at parsing the output - the problem +is that Git first goes outside and has a smoke. + + We actually work around this issue by limiting the number of commits +not only by using ‘-’ but by also using a range. But unfortunately +that’s not always possible. + + In repositories with more than a few thousand commits ‘--graph’ +should never be a member of ‘magit-log-section-arguments’. That +variable is used in the status buffer which is refreshed every time you +run any Magit command. + + Using ‘--color --graph’ is even slower. Magit uses code that is part +of Emacs to turn control characters into faces. That code is pretty +slow and this is quite noticeable when showing a log with many branches +and merges. For that reason ‘--color’ is not enabled by default +anymore. Consider leaving it at that. + +Diff Performance +................ + +If diffs are slow, then consider turning off some optional diff features +by setting all or some of the following variables to ‘nil’: +‘magit-diff-highlight-indentation’, ‘magit-diff-highlight-trailing’, +‘magit-diff-paint-whitespace’, ‘magit-diff-highlight-hunk-body’, and +‘magit-diff-refine-hunk’. + + When showing a commit instead of some arbitrary diff, then some +additional information is displayed. Calculating this information can +be quite expensive given certain circumstances. If looking at a commit +using ‘magit-revision-mode’ takes considerably more time than looking at +the same commit in ‘magit-diff-mode’, then consider setting +‘magit-revision-insert-related-refs’ to ‘nil’. + +Refs Buffer Performance +....................... + +When refreshing the "references buffer" is slow, then that’s usually +because several hundred refs are being displayed. The best way to +address that is to display fewer refs, obviously. + + If you are not, or only mildly, interested in seeing the list of +tags, then start by not displaying them: + + (remove-hook 'magit-refs-sections-hook 'magit-insert-tags) + + Then you should also make sure that the listed remote branches +actually all exist. You can do so by pruning branches which no longer +exist using ‘f-pa’. + +Committing Performance +...................... + +When you initiate a commit, then Magit by default automatically shows a +diff of the changes you are about to commit. For large commits this can +take a long time, which is especially distracting when you are +committing large amounts of generated data which you don’t actually +intend to inspect before committing. This behavior can be turned off +using: + + (remove-hook 'server-switch-hook 'magit-commit-diff) + + Then you can type ‘C-c C-d’ to show the diff when you actually want +to see it, but only then. Alternatively you can leave the hook alone +and just type ‘C-g’ in those cases when it takes too long to generate +the diff. If you do that, then you will end up with a broken diff +buffer, but doing it this way has the advantage that you usually get to +see the diff, which is useful because it increases the odds that you +spot potential issues. + +The Built-In VC Package +....................... + +Emacs comes with a version control interface called "VC", see *note +(emacs)Version Control::. It is enabled be default, and if you don’t +use it in addition to Magit, then you should disable it to keep it from +performing unnecessary work: + + (setq vc-handled-backends nil) + + You can also disable its use for Git but keep using it when using +another version control system: + + (setq vc-handled-backends (delq 'Git vc-handled-backends)) + diff --git a/elpa/magit-20181113.1837/magit.info-2 b/elpa/magit-20181113.1837/magit.info-2 new file mode 100644 index 00000000..18585bb4 --- /dev/null +++ b/elpa/magit-20181113.1837/magit.info-2 @@ -0,0 +1,2692 @@ +This is magit.info, produced by makeinfo version 6.5 from magit.texi. + + Copyright (C) 2015-2018 Jonas Bernoulli + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document 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. + +INFO-DIR-SECTION Emacs +START-INFO-DIR-ENTRY +* Magit: (magit). Using Git from Emacs with Magit. +END-INFO-DIR-ENTRY + + +File: magit.info, Node: Microsoft Windows Performance, Next: MacOS Performance, Up: Performance + +Microsoft Windows Performance +............................. + +In order to update the status buffer, ‘git’ has to be run a few dozen +times. That is problematic on Microsoft Windows, because that operating +system is exceptionally slow at starting processes. Sadly this is an +issue that can only be fixed by Microsoft itself, and they don’t appear +to be particularly interested in doing so. + + Beside the subprocess issue, there are also other Windows-specific +performance issues. Some of these have workarounds. The maintainers of +"Git for Windows" try to improve performance on Windows. Always use the +latest release in order to benefit from the latest performance tweaks. +Magit too tries to work around some Windows-specific issues. + + According to some sources, setting the following Git variables can +also help. + + git config --global core.preloadindex true # default since v2.1 + git config --global core.fscache true # default since v2.8 + git config --global gc.auto 256 + + You should also check whether an anti-virus program is affecting +performance. + + +File: magit.info, Node: MacOS Performance, Prev: Microsoft Windows Performance, Up: Performance + +MacOS Performance +................. + +On macOS Emacs currently creates child processes using ‘fork’. It +appears that this also copies GUI resources. The result is that forking +takes about 30 times as long on Darwin than on Linux. And because Magit +starts many ‘git’ processes even when doing simple things, that makes +quite a difference. + + On the ‘master’ branch Emacs now uses ‘vfork’ when possible, like +this was already done on Linux, and now child creation only takes about +twice as long on Darwin. See (1) for more information. + + Nobody knows when the changes on the ‘master’ branch will be released +as ‘26.1’, but it is still a long way off. You might want to get your +hands on this change before then. The easiest way to get a patched +Emacs is to install the ‘emacs-plus’ formula (2) using ‘homebrew’. The +change has been backported, so you get it not only when using ‘--HEAD’, +but also when using ‘--devel’ or when installing the latest release (by +not using a version argument). + + Alternatively you can apply the backport (3) manually. + + ---------- Footnotes ---------- + + (1) + + + (2) + + (3) + + + +File: magit.info, Node: Plumbing, Next: FAQ, Prev: Customizing, Up: Top + +10 Plumbing +*********** + +The following sections describe how to use several of Magit’s core +abstractions to extend Magit itself or implement a separate extension. + + A few of the low-level features used by Magit have been factored out +into separate libraries/packages, so that they can be used by other +packages, without having to depend on Magit. These libraries are +described in separate manuals, see *note (with-editor)Top:: and *note +(magit-popup)Top::. + + If you are trying to find an unused key that you can bind to a +command provided by your own Magit extension, then checkout +. + +* Menu: + +* Calling Git:: +* Section Plumbing:: +* Refreshing Buffers:: +* Conventions:: + + +File: magit.info, Node: Calling Git, Next: Section Plumbing, Up: Plumbing + +10.1 Calling Git +================ + +Magit provides many specialized functions for calling Git. All of these +functions are defined in either ‘magit-git.el’ or ‘magit-process.el’ and +have one of the prefixes ‘magit-run-’, ‘magit-call-’, ‘magit-start-’, or +‘magit-git-’ (which is also used for other things). + + All of these functions accept an indefinite number of arguments, +which are strings that specify command line arguments for Git (or in +some cases an arbitrary executable). These arguments are flattened +before being passed on to the executable; so instead of strings they can +also be lists of strings and arguments that are ‘nil’ are silently +dropped. Some of these functions also require a single mandatory +argument before these command line arguments. + + Roughly speaking, these functions run Git either to get some value or +for side-effects. The functions that return a value are useful to +collect the information necessary to populate a Magit buffer, while the +others are used to implement Magit commands. + + The functions in the value-only group always run synchronously, and +they never trigger a refresh. The function in the side-effect group can +be further divided into subgroups depending on whether they run Git +synchronously or asynchronously, and depending on whether they trigger a +refresh when the executable has finished. + +* Menu: + +* Getting a Value from Git:: +* Calling Git for Effect:: + + +File: magit.info, Node: Getting a Value from Git, Next: Calling Git for Effect, Up: Calling Git + +10.1.1 Getting a Value from Git +------------------------------- + +These functions run Git in order to get a value, an exit status, or +output. Of course you could also use them to run Git commands that have +side-effects, but that should be avoided. + + -- Function: magit-git-exit-code &rest args + + Executes git with ARGS and returns its exit code. + + -- Function: magit-git-success &rest args + + Executes git with ARGS and returns ‘t’ if the exit code is ‘0’, + ‘nil’ otherwise. + + -- Function: magit-git-failure &rest args + + Executes git with ARGS and returns ‘t’ if the exit code is ‘1’, + ‘nil’ otherwise. + + -- Function: magit-git-true &rest args + + Executes git with ARGS and returns ‘t’ if the first line printed by + git is the string "true", ‘nil’ otherwise. + + -- Function: magit-git-false &rest args + + Executes git with ARGS and returns ‘t’ if the first line printed by + git is the string "false", ‘nil’ otherwise. + + -- Function: magit-git-insert &rest args + + Executes git with ARGS and inserts its output at point. + + -- Function: magit-git-string &rest args + + Executes git with ARGS and returns the first line of its output. + If there is no output or if it begins with a newline character, + then this returns ‘nil’. + + -- Function: magit-git-lines &rest args + + Executes git with ARGS and returns its output as a list of lines. + Empty lines anywhere in the output are omitted. + + -- Function: magit-git-items &rest args + + Executes git with ARGS and returns its null-separated output as a + list. Empty items anywhere in the output are omitted. + + If the value of option ‘magit-git-debug’ is non-nil and git exits + with a non-zero exit status, then warn about that in the echo area + and add a section containing git’s standard error in the current + repository’s process buffer. + + If an error occurs when using one of the above functions, then that +is usually due to a bug, i.e. using an argument which is not actually +supported. Such errors are usually not reported, but when they occur we +need to be able to debug them. + + -- User Option: magit-git-debug + + Whether to report errors that occur when using ‘magit-git-insert’, + ‘magit-git-string’, ‘magit-git-lines’, or ‘magit-git-items’. This + does not actually raise an error. Instead a message is shown in + the echo area, and git’s standard error is insert into a new + section in the current repository’s process buffer. + + -- Function: magit-git-str &rest args + + This is a variant of ‘magit-git-string’ that ignores the option + ‘magit-git-debug’. It is mainly intended to be used while handling + errors in functions that do respect that option. Using such a + function while handing an error could cause yet another error and + therefore lead to an infinite recursion. You probably won’t ever + need to use this function. + + +File: magit.info, Node: Calling Git for Effect, Prev: Getting a Value from Git, Up: Calling Git + +10.1.2 Calling Git for Effect +----------------------------- + +These functions are used to run git to produce some effect. Most Magit +commands that actually run git do so by using such a function. + + Because we do not need to consume git’s output when using these +functions, their output is instead logged into a per-repository buffer, +which can be shown using ‘$’ from a Magit buffer or ‘M-x magit-process’ +elsewhere. + + These functions can have an effect in two distinct ways. Firstly, +running git may change something, i.e. create or push a new commit. +Secondly, that change may require that Magit buffers are refreshed to +reflect the changed state of the repository. But refreshing isn’t +always desirable, so only some of these functions do perform such a +refresh after git has returned. + + Sometimes it is useful to run git asynchronously. For example, when +the user has just initiated a push, then there is no reason to make her +wait until that has completed. In other cases it makes sense to wait +for git to complete before letting the user do something else. For +example after staging a change it is useful to wait until after the +refresh because that also automatically moves to the next change. + + -- Function: magit-call-git &rest args + + Calls git synchronously with ARGS. + + -- Function: magit-call-process program &rest args + + Calls PROGRAM synchronously with ARGS. + + -- Function: magit-run-git &rest args + + Calls git synchronously with ARGS and then refreshes. + + -- Function: magit-run-git-with-input input &rest args + + Calls git synchronously with ARGS and sends it INPUT on standard + input. + + INPUT should be a buffer or the name of an existing buffer. The + content of that buffer is used as the process’ standard input. + After the process returns a refresh is performed. + + As a special case, INPUT may also be nil. In that case the content + of the current buffer is used as standard input and *no* refresh is + performed. + + This function actually runs git asynchronously. But then it waits + for the process to return, so the function itself is synchronous. + + -- Function: magit-run-git-with-logfile file &rest args + + Calls git synchronously with ARGS. The process’ output is saved in + FILE. This is rarely useful and so this function might be removed + in the future. + + This function actually runs git asynchronously. But then it waits + for the process to return, so the function itself is synchronous. + + -- Function: magit-git &rest args + + Calls git synchronously with ARGS for side-effects only. This + function does not refresh the buffer. + + -- Function: magit-git-wash washer &rest args + + Execute Git with ARGS, inserting washed output at point. Actually + first insert the raw output at point. If there is no output call + ‘magit-cancel-section’. Otherwise temporarily narrow the buffer to + the inserted text, move to its beginning, and then call function + WASHER with ARGS as its sole argument. + + And now for the asynchronous variants. + + -- Function: magit-run-git-async &rest args + + Start Git, prepare for refresh, and return the process object. + ARGS is flattened and then used as arguments to Git. + + Display the command line arguments in the echo area. + + After Git returns some buffers are refreshed: the buffer that was + current when this function was called (if it is a Magit buffer and + still alive), as well as the respective Magit status buffer. + Unmodified buffers visiting files that are tracked in the current + repository are reverted if ‘magit-revert-buffers’ is non-nil. + + -- Function: magit-run-git-with-editor &rest args + + Export GIT_EDITOR and start Git. Also prepare for refresh and + return the process object. ARGS is flattened and then used as + arguments to Git. + + Display the command line arguments in the echo area. + + After Git returns some buffers are refreshed: the buffer that was + current when this function was called (if it is a Magit buffer and + still alive), as well as the respective Magit status buffer. + + -- Function: magit-start-git &rest args + + Start Git, prepare for refresh, and return the process object. + + If INPUT is non-nil, it has to be a buffer or the name of an + existing buffer. The buffer content becomes the processes standard + input. + + Option ‘magit-git-executable’ specifies the Git executable and + option ‘magit-git-global-arguments’ specifies constant arguments. + The remaining arguments ARGS specify arguments to Git. They are + flattened before use. + + After Git returns, some buffers are refreshed: the buffer that was + current when this function was called (if it is a Magit buffer and + still alive), as well as the respective Magit status buffer. + Unmodified buffers visiting files that are tracked in the current + repository are reverted if ‘magit-revert-buffers’ is non-nil. + + -- Function: magit-start-process &rest args + + Start PROGRAM, prepare for refresh, and return the process object. + + If optional argument INPUT is non-nil, it has to be a buffer or the + name of an existing buffer. The buffer content becomes the + processes standard input. + + The process is started using ‘start-file-process’ and then setup to + use the sentinel ‘magit-process-sentinel’ and the filter + ‘magit-process-filter’. Information required by these functions is + stored in the process object. When this function returns the + process has not started to run yet so it is possible to override + the sentinel and filter. + + After the process returns, ‘magit-process-sentinel’ refreshes the + buffer that was current when ‘magit-start-process’ was called (if + it is a Magit buffer and still alive), as well as the respective + Magit status buffer. Unmodified buffers visiting files that are + tracked in the current repository are reverted if + ‘magit-revert-buffers’ is non-nil. + + -- Variable: magit-this-process + + The child process which is about to start. This can be used to + change the filter and sentinel. + + -- Variable: magit-process-raise-error + + When this is non-nil, then ‘magit-process-sentinel’ raises an error + if git exits with a non-zero exit status. For debugging purposes. + + +File: magit.info, Node: Section Plumbing, Next: Refreshing Buffers, Prev: Calling Git, Up: Plumbing + +10.2 Section Plumbing +===================== + +* Menu: + +* Creating Sections:: +* Section Selection:: +* Matching Sections:: + + +File: magit.info, Node: Creating Sections, Next: Section Selection, Up: Section Plumbing + +10.2.1 Creating Sections +------------------------ + + -- Macro: magit-insert-section &rest args + + Insert a section at point. + + TYPE is the section type, a symbol. Many commands that act on the + current section behave differently depending on that type. Also if + a variable ‘magit-TYPE-section-map’ exists, then use that as the + text-property ‘keymap’ of all text belonging to the section (but + this may be overwritten in subsections). TYPE can also have the + form ‘(eval FORM)’ in which case FORM is evaluated at runtime. + + Optional VALUE is the value of the section, usually a string that + is required when acting on the section. + + When optional HIDE is non-nil collapse the section body by default, + i.e. when first creating the section, but not when refreshing the + buffer. Otherwise, expand it by default. This can be overwritten + using ‘magit-section-set-visibility-hook’. When a section is + recreated during a refresh, then the visibility of predecessor is + inherited and HIDE is ignored (but the hook is still honored). + + BODY is any number of forms that actually insert the section’s + heading and body. Optional NAME, if specified, has to be a symbol, + which is then bound to the struct of the section being inserted. + + Before BODY is evaluated the ‘start’ of the section object is set + to the value of ‘point’ and after BODY was evaluated its ‘end’ is + set to the new value of ‘point’; BODY is responsible for moving + ‘point’ forward. + + If it turns out inside BODY that the section is empty, then + ‘magit-cancel-section’ can be used to abort and remove all traces + of the partially inserted section. This can happen when creating a + section by washing Git’s output and Git didn’t actually output + anything this time around. + + -- Function: magit-insert-heading &rest args + + Insert the heading for the section currently being inserted. + + This function should only be used inside ‘magit-insert-section’. + + When called without any arguments, then just set the ‘content’ slot + of the object representing the section being inserted to a marker + at ‘point’. The section should only contain a single line when + this function is used like this. + + When called with arguments ARGS, which have to be strings, then + insert those strings at point. The section should not contain any + text before this happens and afterwards it should again only + contain a single line. If the ‘face’ property is set anywhere + inside any of these strings, then insert all of them unchanged. + Otherwise use the ‘magit-section-heading’ face for all inserted + text. + + The ‘content’ property of the section struct is the end of the + heading (which lasts from ‘start’ to ‘content’) and the beginning + of the body (which lasts from ‘content’ to ‘end’). If the value of + ‘content’ is nil, then the section has no heading and its body + cannot be collapsed. If a section does have a heading then its + height must be exactly one line, including a trailing newline + character. This isn’t enforced; you are responsible for getting it + right. The only exception is that this function does insert a + newline character if necessary. + + -- Function: magit-cancel-section + + Cancel the section currently being inserted. This exits the + innermost call to ‘magit-insert-section’ and removes all traces of + what has already happened inside that call. + + -- Function: magit-define-section-jumper sym title &optional value + + Define an interactive function to go to section SYM. TITLE is the + displayed title of the section. + + +File: magit.info, Node: Section Selection, Next: Matching Sections, Prev: Creating Sections, Up: Section Plumbing + +10.2.2 Section Selection +------------------------ + + -- Function: magit-current-section + + Return the section at point. + + -- Function: magit-region-sections &optional condition multiple + + Return a list of the selected sections. + + When the region is active and constitutes a valid section + selection, then return a list of all selected sections. This is + the case when the region begins in the heading of a section and + ends in the heading of the same section or in that of a sibling + section. If optional MULTIPLE is non-nil, then the region cannot + begin and end in the same section. + + When the selection is not valid, then return nil. In this case, + most commands that can act on the selected sections will instead + act on the section at point. + + When the region looks like it would in any other buffer then the + selection is invalid. When the selection is valid then the region + uses the ‘magit-section-highlight’ face. This does not apply to + diffs where things get a bit more complicated, but even here if the + region looks like it usually does, then that’s not a valid + selection as far as this function is concerned. + + If optional CONDITION is non-nil, then the selection not only has + to be valid; all selected sections additionally have to match + CONDITION, or nil is returned. See ‘magit-section-match’ for the + forms CONDITION can take. + + -- Function: magit-region-values &optional condition multiple + + Return a list of the values of the selected sections. + + Return the values that themselves would be returned by + ‘magit-region-sections’ (which see). + + +File: magit.info, Node: Matching Sections, Prev: Section Selection, Up: Section Plumbing + +10.2.3 Matching Sections +------------------------ + +‘M-x magit-describe-section-briefly’ (‘magit-describe-section-briefly’) + + Show information about the section at point. This command is + intended for debugging purposes. + + -- Function: magit-section-ident section + + Return an unique identifier for SECTION. The return value has the + form ‘((TYPE . VALUE)...)’. + + -- Function: magit-get-section ident &optional root + + Return the section identified by IDENT. IDENT has to be a list as + returned by ‘magit-section-ident’. + + -- Function: magit-section-match condition &optional section + + Return ‘t’ if SECTION matches CONDITION. SECTION defaults to the + section at point. If SECTION is not specified and there also is no + section at point, then return ‘nil’. + + CONDITION can take the following forms: + • ‘(CONDITION...)’ + + matches if any of the CONDITIONs matches. + + • ‘[CLASS...]’ + + matches if the section’s class is the same as the first CLASS + or a subclass of that; the section’s parent class matches the + second CLASS; and so on. + + • ‘[* CLASS...]’ + + matches sections that match ‘[CLASS...]’ and also recursively + all their child sections. + + • ‘CLASS’ + + matches if the section’s class is the same as CLASS or a + subclass of that; regardless of the classes of the parent + sections. + + Each CLASS should be a class symbol, identifying a class that + derives from ‘magit-section’. For backward compatibility CLASS can + also be a "type symbol". A section matches such a symbol if the + value of its ‘type’ slot is ‘eq’. If a type symbol has an entry in + ‘magit--section-type-alist’, then a section also matches that type + if its class is a subclass of the class that corresponds to the + type as per that alist. + + Note that it is not necessary to specify the complete section + lineage as printed by ‘magit-describe-section-briefly’, unless of + course you want to be that precise. + + -- Function: magit-section-value-if condition &optional section + + If the section at point matches CONDITION, then return its value. + + If optional SECTION is non-nil then test whether that matches + instead. If there is no section at point and SECTION is nil, then + return nil. If the section does not match, then return nil. + + See ‘magit-section-match’ for the forms CONDITION can take. + + -- Function: magit-section-case &rest clauses + + Choose among clauses on the type of the section at point. + + Each clause looks like (CONDITION BODY...). The type of the + section is compared against each CONDITION; the BODY forms of the + first match are evaluated sequentially and the value of the last + form is returned. Inside BODY the symbol ‘it’ is bound to the + section at point. If no clause succeeds or if there is no section + at point return nil. + + See ‘magit-section-match’ for the forms CONDITION can take. + Additionally a CONDITION of t is allowed in the final clause and + matches if no other CONDITION match, even if there is no section at + point. + + -- Variable: magit-root-section + + The root section in the current buffer. All other sections are + descendants of this section. The value of this variable is set by + ‘magit-insert-section’ and you should never modify it. + + For diff related sections a few additional tools exist. + + -- Function: magit-diff-type &optional section + + Return the diff type of SECTION. + + The returned type is one of the symbols ‘staged’, ‘unstaged’, + ‘committed’, or ‘undefined’. This type serves a similar purpose as + the general type common to all sections (which is stored in the + ‘type’ slot of the corresponding ‘magit-section’ struct) but takes + additional information into account. When the SECTION isn’t + related to diffs and the buffer containing it also isn’t a + diff-only buffer, then return nil. + + Currently the type can also be one of ‘tracked’ and ‘untracked’, + but these values are not handled explicitly in every place they + should be. A possible fix could be to just return nil here. + + The section has to be a ‘diff’ or ‘hunk’ section, or a section + whose children are of type ‘diff’. If optional SECTION is nil, + return the diff type for the current section. In buffers whose + major mode is ‘magit-diff-mode’ SECTION is ignored and the type is + determined using other means. In ‘magit-revision-mode’ buffers the + type is always ‘committed’. + + -- Function: magit-diff-scope &optional section strict + + Return the diff scope of SECTION or the selected section(s). + + A diff’s "scope" describes what part of a diff is selected, it is a + symbol, one of ‘region’, ‘hunk’, ‘hunks’, ‘file’, ‘files’, or + ‘list’. Do not confuse this with the diff "type", as returned by + ‘magit-diff-type’. + + If optional SECTION is non-nil, then return the scope of that, + ignoring the sections selected by the region. Otherwise return the + scope of the current section, or if the region is active and + selects a valid group of diff related sections, the type of these + sections, i.e. ‘hunks’ or ‘files’. If SECTION (or if the current + section that is nil) is a ‘hunk’ section and the region starts and + ends inside the body of a that section, then the type is ‘region’. + + If optional STRICT is non-nil then return nil if the diff type of + the section at point is ‘untracked’ or the section at point is not + actually a ‘diff’ but a ‘diffstat’ section. + + +File: magit.info, Node: Refreshing Buffers, Next: Conventions, Prev: Section Plumbing, Up: Plumbing + +10.3 Refreshing Buffers +======================= + +All commands that create a new Magit buffer or change what is being +displayed in an existing buffer do so by calling ‘magit-mode-setup’. +Among other things, that function sets the buffer local values of +‘default-directory’ (to the top-level of the repository), +‘magit-refresh-function’, and ‘magit-refresh-args’. + + Buffers are refreshed by calling the function that is the local value +of ‘magit-refresh-function’ (a function named ‘magit-*-refresh-buffer’, +where ‘*’ may be something like ‘diff’) with the value of +‘magit-refresh-args’ as arguments. + + -- Macro: magit-mode-setup buffer switch-func mode refresh-func + &optional refresh-args + + This function displays and selects BUFFER, turns on MODE, and + refreshes a first time. + + This function displays and optionally selects BUFFER by calling + ‘magit-mode-display-buffer’ with BUFFER, MODE and SWITCH-FUNC as + arguments. Then it sets the local value of + ‘magit-refresh-function’ to REFRESH-FUNC and that of + ‘magit-refresh-args’ to REFRESH-ARGS. Finally it creates the + buffer content by calling REFRESH-FUNC with REFRESH-ARGS as + arguments. + + All arguments are evaluated before switching to BUFFER. + + -- Function: magit-mode-display-buffer buffer mode &optional + switch-function + + This function display BUFFER in some window and select it. BUFFER + may be a buffer or a string, the name of a buffer. The buffer is + returned. + + Unless BUFFER is already displayed in the selected frame, store the + previous window configuration as a buffer local value, so that it + can later be restored by ‘magit-mode-bury-buffer’. + + The buffer is displayed and selected using SWITCH-FUNCTION. If + that is ‘nil’ then ‘pop-to-buffer’ is used if the current buffer’s + major mode derives from ‘magit-mode’. Otherwise ‘switch-to-buffer’ + is used. + + -- Variable: magit-refresh-function + + The value of this buffer-local variable is the function used to + refresh the current buffer. It is called with ‘magit-refresh-args’ + as arguments. + + -- Variable: magit-refresh-args + + The list of arguments used by ‘magit-refresh-function’ to refresh + the current buffer. ‘magit-refresh-function’ is called with these + arguments. + + The value is usually set using ‘magit-mode-setup’, but in some + cases it’s also useful to provide commands which can change the + value. For example, the ‘magit-diff-refresh-popup’ can be used to + change any of the arguments used to display the diff, without + having to specify again which differences should be shown. + ‘magit-diff-more-context’, ‘magit-diff-less-context’, and + ‘magit-diff-default-context’ change just the ‘-U’ argument. In + both case this is done by changing the value of this variable and + then calling this ‘magit-refresh-function’. + + +File: magit.info, Node: Conventions, Prev: Refreshing Buffers, Up: Plumbing + +10.4 Conventions +================ + +Also see *note Completion and Confirmation::. + +* Menu: + +* Theming Faces:: + + +File: magit.info, Node: Theming Faces, Up: Conventions + +10.4.1 Theming Faces +-------------------- + +The default theme uses blue for local branches, green for remote +branches, and goldenrod (brownish yellow) for tags. When creating a new +theme, you should probably follow that example. If your theme already +uses other colors, then stick to that. + + In older releases these reference faces used to have a background +color and a box around them. The basic default faces no longer do so, +to make Magit buffers much less noisy, and you should follow that +example at least with regards to boxes. (Boxes were used in the past to +work around a conflict between the highlighting overlay and text +property backgrounds. That’s no longer necessary because highlighting +no longer causes other background colors to disappear.) Alternatively +you can keep the background color and/or box, but then have to take +special care to adjust ‘magit-branch-current’ accordingly. By default +it looks mostly like ‘magit-branch-local’, but with a box (by default +the former is the only face that uses a box, exactly so that it sticks +out). If the former also uses a box, then you have to make sure that it +differs in some other way from the latter. + + The most difficult faces to theme are those related to diffs, +headings, highlighting, and the region. There are faces that fall into +all four groups - expect to spend some time getting this right. + + The ‘region’ face in the default theme, in both the light and dark +variants, as well as in many other themes, distributed with Emacs or by +third-parties, is very ugly. It is common to use a background color +that really sticks out, which is ugly but if that were the only problem +then it would be acceptable. Unfortunately many themes also set the +foreground color, which ensures that all text within the region is +readable. Without doing that there might be cases where some foreground +color is too close to the region background color to still be readable. +But it also means that text within the region loses all syntax +highlighting. + + I consider the work that went into getting the ‘region’ face right to +be a good indicator for the general quality of a theme. My +recommendation for the ‘region’ face is this: use a background color +slightly different from the background color of the ‘default’ face, and +do not set the foreground color at all. So for a light theme you might +use a light (possibly tinted) gray as the background color of ‘default’ +and a somewhat darker gray for the background of ‘region’. That should +usually be enough to not collide with the foreground color of any other +face. But if some other faces also set a light gray as background +color, then you should also make sure it doesn’t collide with those (in +some cases it might be acceptable though). + + Magit only uses the ‘region’ face when the region is "invalid" by its +own definition. In a Magit buffer the region is used to either select +multiple sibling sections, so that commands which support it act on all +of these sections instead of just the current section, or to select +lines within a single hunk section. In all other cases, the section is +considered invalid and Magit won’t act on it. But such invalid sections +happen, either because the user has not moved point enough yet to make +it valid or because she wants to use a non-magit command to act on the +region, e.g. ‘kill-region’. + + So using the regular ‘region’ face for invalid sections is a feature. +It tells the user that Magit won’t be able to act on it. It’s +acceptable if that face looks a bit odd and even (but less so) if it +collides with the background colors of section headings and other things +that have a background color. + + Magit highlights the current section. If a section has subsections, +then all of them are highlighted. This is done using faces that have +"highlight" in their names. For most sections, +‘magit-section-highlight’ is used for both the body and the heading. +Like the ‘region’ face, it should only set the background color to +something similar to that of ‘default’. The highlight background color +must be different from both the ‘region’ background color and the +‘default’ background color. + + For diff related sections Magit uses various faces to highlight +different parts of the selected section(s). Note that hunk headings, +unlike all other section headings, by default have a background color, +because it is useful to have very visible separators between hunks. +That face ‘magit-diff-hunk-heading’, should be different from both +‘magit-diff-hunk-heading-highlight’ and ‘magit-section-highlight’, as +well as from ‘magit-diff-context’ and ‘magit-diff-context-highlight’. +By default we do that by changing the foreground color. Changing the +background color would lead to complications, and there are already +enough we cannot get around. (Also note that it is generally a good +idea for section headings to always be bold, but only for sections that +have subsections). + + When there is a valid region selecting diff-related sibling sections, +i.e. multiple files or hunks, then the bodies of all these sections use +the respective highlight faces, but additionally the headings instead +use one of the faces ‘magit-diff-file-heading-selection’ or +‘magit-diff-hunk-heading-selection’. These faces have to be different +from the regular highlight variants to provide explicit visual +indication that the region is active. + + When theming diff related faces, start by setting the option +‘magit-diff-refine-hunk’ to ‘all’. You might personally prefer to only +refine the current hunk or not use hunk refinement at all, but some of +the users of your theme want all hunks to be refined, so you have to +cater to that. + + (Also turn on ‘magit-diff-highlight-indentation’, +‘magit-diff-highlight-trailing’, and ‘magit-diff-paint-whitespace’; and +insert some whitespace errors into the code you use for testing.) + + For e.g. "added lines" you have to adjust three faces: +‘magit-diff-added’, ‘magit-diff-added-highlight’, and +‘smerge-refined-added’. Make sure that the latter works well with both +of the former, as well as ‘smerge-other’ and ‘diff-added’. Then do the +same for the removed lines, context lines, lines added by us, and lines +added by them. Also make sure the respective added, removed, and +context faces use approximately the same saturation for both the +highlighted and unhighlighted variants. Also make sure the file and +diff headings work nicely with context lines (e.g. make them look +different). Line faces should set both the foreground and the +background color. For example, for added lines use two different +greens. + + It’s best if the foreground color of both the highlighted and the +unhighlighted variants are the same, so you will need to have to find a +color that works well on the highlight and unhighlighted background, the +refine background, and the highlight context background. When there is +an hunk internal region, then the added- and removed-lines background +color is used only within that region. Outside the region the +highlighted context background color is used. This makes it easier to +see what is being staged. With an hunk internal region the hunk heading +is shown using ‘magit-diff-hunk-heading-selection’, and so are the thin +lines that are added around the lines that fall within the region. The +background color of that has to be distinct enough from the various +other involved background colors. + + Nobody said this would be easy. If your theme restricts itself to a +certain set of colors, then you should make an exception here. +Otherwise it would be impossible to make the diffs look good in each and +every variation. Actually you might want to just stick to the default +definitions for these faces. You have been warned. Also please note +that if you do not get this right, this will in some cases look to users +like bugs in Magit - so please do it right or not at all. + + +File: magit.info, Node: FAQ, Next: Debugging Tools, Prev: Plumbing, Up: Top + +Appendix A FAQ +************** + +The next two nodes lists frequently asked questions. For a list of +frequently *and recently* asked questions, i.e. questions that haven’t +made it into the manual yet, see +. + + Please also use the *note Debugging Tools::. + +* Menu: + +* FAQ - How to ...?:: +* FAQ - Issues and Errors:: + + +File: magit.info, Node: FAQ - How to ...?, Next: FAQ - Issues and Errors, Up: FAQ + +A.1 FAQ - How to ...? +===================== + +* Menu: + +* How to show git's output?:: +* How to install the gitman info manual?:: +* How to show diffs for gpg-encrypted files?:: +* How does branching and pushing work?:: +* Can Magit be used as ediff-version-control-package?:: + + +File: magit.info, Node: How to show git's output?, Next: How to install the gitman info manual?, Up: FAQ - How to ...? + +A.1.1 How to show git’s output? +------------------------------- + +To show the output of recently run git commands, press ‘$’ (or, if that +isn’t available, ‘M-x magit-process-buffer’). This will show a buffer +containing a section per git invocation; as always press ‘TAB’ to expand +or collapse them. + + By default, git’s output is only inserted into the process buffer if +it is run for side-effects. When the output is consumed in some way, +also inserting it into the process buffer would be too expensive. For +debugging purposes, it’s possible to do so anyway by setting +‘magit-git-debug’ to ‘t’. + + +File: magit.info, Node: How to install the gitman info manual?, Next: How to show diffs for gpg-encrypted files?, Prev: How to show git's output?, Up: FAQ - How to ...? + +A.1.2 How to install the gitman info manual? +-------------------------------------------- + +Git’s manpages can be exported as an info manual called ‘gitman’. +Magit’s own info manual links to nodes in that manual instead of the +actual manpages because Info doesn’t support linking to manpages. + + Unfortunately some distributions do not install the ‘gitman’ manual +by default and you will have to install a separate documentation package +to get it. + + Magit patches Info adding the ability to visit links to the ‘gitman’ +Info manual by instead viewing the respective manpage. If you prefer +that approach, then set the value of ‘magit-view-git-manual-method’ to +one of the supported packages ‘man’ or ‘woman’, e.g.: + + (setq magit-view-git-manual-method 'man) + + +File: magit.info, Node: How to show diffs for gpg-encrypted files?, Next: How does branching and pushing work?, Prev: How to install the gitman info manual?, Up: FAQ - How to ...? + +A.1.3 How to show diffs for gpg-encrypted files? +------------------------------------------------ + +Git supports showing diffs for encrypted files, but has to be told to do +so. Since Magit just uses Git to get the diffs, configuring Git also +affects the diffs displayed inside Magit. + + git config --global diff.gpg.textconv "gpg --no-tty --decrypt" + echo "*.gpg filter=gpg diff=gpg" > .gitattributes + + +File: magit.info, Node: How does branching and pushing work?, Next: Can Magit be used as ediff-version-control-package?, Prev: How to show diffs for gpg-encrypted files?, Up: FAQ - How to ...? + +A.1.4 How does branching and pushing work? +------------------------------------------ + +Please see *note Branching:: and + + + +File: magit.info, Node: Can Magit be used as ediff-version-control-package?, Prev: How does branching and pushing work?, Up: FAQ - How to ...? + +A.1.5 Can Magit be used as ‘ediff-version-control-package’? +----------------------------------------------------------- + +No, it cannot. For that to work the functions ‘ediff-magit-internal’ +and ‘ediff-magit-merge-internal’ would have to be implemented, and they +are not. These two functions are only used by the three commands +‘ediff-revision’, ‘ediff-merge-revisions-with-ancestor’, and +‘ediff-merge-revisions’. + + These commands only delegate the task of populating buffers with +certain revisions to the "internal" functions. The equally important +task of determining which revisions are to be compared/merged is not +delegated. Instead this is done without any support whatsoever from the +version control package/system - meaning that the user has to enter the +revisions explicitly. Instead of implementing ‘ediff-magit-internal’ we +provide ‘magit-ediff-compare’, which handles both tasks like it is 2005. + + The other commands ‘ediff-merge-revisions’ and +‘ediff-merge-revisions-with-ancestor’ are normally not what you want +when using a modern version control system like Git. Instead of letting +the user resolve only those conflicts which Git could not resolve on its +own, they throw away all work done by Git and then expect the user to +manually merge all conflicts, including those that had already been +resolved. That made sense back in the days when version control systems +couldn’t merge (or so I have been told), but not anymore. Once in a +blue moon you might actually want to see all conflicts, in which case +you *can* use these commands, which then use ‘ediff-vc-merge-internal’. +So we don’t actually have to implement ‘ediff-magit-merge-internal’. +Instead we provide the more useful command ‘magit-ediff-resolve’ which +only shows yet-to-be resolved conflicts. + + +File: magit.info, Node: FAQ - Issues and Errors, Prev: FAQ - How to ...?, Up: FAQ + +A.2 FAQ - Issues and Errors +=========================== + +* Menu: + +* Magit is slow:: +* I changed several thousand files at once and now Magit is unusable:: +* I am having problems committing:: +* I am using MS Windows and cannot push with Magit:: +* I am using OS X and SOMETHING works in shell, but not in Magit: I am using OS X and SOMETHING works in shell but not in Magit. +* Diffs contain control sequences:: +* Expanding a file to show the diff causes it to disappear:: +* Point is wrong in the COMMIT_EDITMSG buffer:: +* The mode-line information isn't always up-to-date:: +* A branch and tag sharing the same name breaks SOMETHING:: +* My Git hooks work on the command-line but not inside Magit:: +* git-commit-mode isn't used when committing from the command-line:: +* Point ends up inside invisible text when jumping to a file-visiting buffer:: + + +File: magit.info, Node: Magit is slow, Next: I changed several thousand files at once and now Magit is unusable, Up: FAQ - Issues and Errors + +A.2.1 Magit is slow +------------------- + +See *note Performance::. + + +File: magit.info, Node: I changed several thousand files at once and now Magit is unusable, Next: I am having problems committing, Prev: Magit is slow, Up: FAQ - Issues and Errors + +A.2.2 I changed several thousand files at once and now Magit is unusable +------------------------------------------------------------------------ + +Magit is *currently* not expected to work under such conditions. It +sure would be nice if it did, and v2.5 will hopefully be a big step into +that direction. But it might take until v3.1 to accomplish fully +satisfactory performance, because that requires some heavy refactoring. + + But for now we recommend you use the command line to complete this +one commit. Also see *note Performance::. + + +File: magit.info, Node: I am having problems committing, Next: I am using MS Windows and cannot push with Magit, Prev: I changed several thousand files at once and now Magit is unusable, Up: FAQ - Issues and Errors + +A.2.3 I am having problems committing +------------------------------------- + +That likely means that Magit is having problems finding an appropriate +emacsclient executable. See *note (with-editor)Configuring +With-Editor:: and *note (with-editor)Debugging::. + + +File: magit.info, Node: I am using MS Windows and cannot push with Magit, Next: I am using OS X and SOMETHING works in shell but not in Magit, Prev: I am having problems committing, Up: FAQ - Issues and Errors + +A.2.4 I am using MS Windows and cannot push with Magit +------------------------------------------------------ + +It’s almost certain that Magit is only incidental to this issue. It is +much more likely that this is a configuration issue, even if you can +push on the command line. + + Detailed setup instructions can be found at +. + + +File: magit.info, Node: I am using OS X and SOMETHING works in shell but not in Magit, Next: Diffs contain control sequences, Prev: I am using MS Windows and cannot push with Magit, Up: FAQ - Issues and Errors + +A.2.5 I am using OS X and SOMETHING works in shell, but not in Magit +-------------------------------------------------------------------- + +This usually occurs because Emacs doesn’t have the same environment +variables as your shell. Try installing and configuring +. By default it +synchronizes ‘$PATH’, which helps Magit find the same ‘git’ as the one +you are using on the shell. + + If SOMETHING is "passphrase caching with gpg-agent for commit and/or +tag signing", then you’ll also need to synchronize ‘$GPG_AGENT_INFO’. + + +File: magit.info, Node: Diffs contain control sequences, Next: Expanding a file to show the diff causes it to disappear, Prev: I am using OS X and SOMETHING works in shell but not in Magit, Up: FAQ - Issues and Errors + +A.2.6 Diffs contain control sequences +------------------------------------- + +This happens when you configure Git to always color diffs and/or all of +its output. The valid values for relevant Git variables ‘color.ui’ and +‘color.diff’ are ‘false’, ‘true’ and ‘always’, and the default is +‘true’. You should leave it that way because then you get colorful +output in terminals by default but when git’s output is consumed by +something else, then no color control sequences are used. + + If you actually use some other tool that requires setting ‘color.ui’ +and/or ‘color.diff’ to ‘always’ (which is highly unlikely), then you can +override these settings just for Magit by using: + + (setq magit-git-global-arguments + (nconc magit-git-global-arguments + '("-c" "color.ui=false" + "-c" "color.diff=false"))) + + +File: magit.info, Node: Expanding a file to show the diff causes it to disappear, Next: Point is wrong in the COMMIT_EDITMSG buffer, Prev: Diffs contain control sequences, Up: FAQ - Issues and Errors + +A.2.7 Expanding a file to show the diff causes it to disappear +-------------------------------------------------------------- + +This is probably caused by a change of a ‘diff.*’ Git variable. You +probably set that variable for a reason, and should therefore only undo +that setting in Magit by customizing ‘magit-git-global-arguments’. + + +File: magit.info, Node: Point is wrong in the COMMIT_EDITMSG buffer, Next: The mode-line information isn't always up-to-date, Prev: Expanding a file to show the diff causes it to disappear, Up: FAQ - Issues and Errors + +A.2.8 Point is wrong in the ‘COMMIT_EDITMSG’ buffer +--------------------------------------------------- + +Neither Magit nor ‘git-commit‘ fiddle with point in the buffer used to +write commit messages, so something else must be doing it. + + You have probably globally enabled a mode which does restore point in +file-visiting buffers. It might be a bit surprising, but when you write +a commit message, then you are actually editing a file. + + So you have to figure out which package is doing. ‘saveplace’, +‘pointback’, and ‘session’ are likely candidates. These snippets might +help: + + (setq session-name-disable-regexp "\\(?:\\`'\\.git/[A-Z_]+\\'\\)") + + (with-eval-after-load 'pointback + (lambda () + (when (or git-commit-mode git-rebase-mode) + (pointback-mode -1)))) + + +File: magit.info, Node: The mode-line information isn't always up-to-date, Next: A branch and tag sharing the same name breaks SOMETHING, Prev: Point is wrong in the COMMIT_EDITMSG buffer, Up: FAQ - Issues and Errors + +A.2.9 The mode-line information isn’t always up-to-date +------------------------------------------------------- + +Magit is not responsible for the version control information that is +being displayed in the mode-line and looks something like ‘Git-master’. +The built-in "Version Control" package, also known as "VC", updates that +information, and can be told to do so more often: + + (setq auto-revert-check-vc-info t) + + But doing so isn’t good for performance. For more (overly +optimistic) information see *note (emacs)VC Mode Line::. + + If you don’t really care about seeing that information in the +mode-line, but just don’t want to see _incorrect_ information, then +consider disabling VC when using Git: + + (setq vc-handled-backends (delq 'Git vc-handled-backends)) + + Or to disable it completely: + + (setq vc-handled-backends nil) + + +File: magit.info, Node: A branch and tag sharing the same name breaks SOMETHING, Next: My Git hooks work on the command-line but not inside Magit, Prev: The mode-line information isn't always up-to-date, Up: FAQ - Issues and Errors + +A.2.10 A branch and tag sharing the same name breaks SOMETHING +-------------------------------------------------------------- + +Or more generally, ambiguous refnames break SOMETHING. + + Magit assumes that refs are named non-ambiguously across the +"refs/heads/", "refs/tags/", and "refs/remotes/" namespaces (i.e., all +the names remain unique when those prefixes are stripped). We consider +ambiguous refnames unsupported and recommend that you use a +non-ambiguous naming scheme. However, if you do work with a repository +that has ambiguous refnames, please report any issues you encounter so +that we can investigate whether there is a simple fix. + + +File: magit.info, Node: My Git hooks work on the command-line but not inside Magit, Next: git-commit-mode isn't used when committing from the command-line, Prev: A branch and tag sharing the same name breaks SOMETHING, Up: FAQ - Issues and Errors + +A.2.11 My Git hooks work on the command-line but not inside Magit +----------------------------------------------------------------- + +When Magit calls ‘git’ it adds a few global arguments including +‘--literal-pathspecs’ and the ‘git’ process started by Magit then passes +that setting on to other ‘git’ process it starts itself. It does so by +setting the environment variable ‘GIT_LITERAL_PATHSPECS’, not by calling +subprocesses with the ‘--literal-pathspecs’. You can therefore override +this setting in hook scripts using ‘unset GIT_LITERAL_PATHSPECS’. + + +File: magit.info, Node: git-commit-mode isn't used when committing from the command-line, Next: Point ends up inside invisible text when jumping to a file-visiting buffer, Prev: My Git hooks work on the command-line but not inside Magit, Up: FAQ - Issues and Errors + +A.2.12 ‘git-commit-mode’ isn’t used when committing from the command-line +------------------------------------------------------------------------- + +The reason for this is that ‘git-commit.el’ has not been loaded yet +and/or that the server has not been started yet. These things have +always already been taken care of when you commit from Magit because in +order to do so, Magit has to be loaded and doing that involves loading +‘git-commit’ and starting the server. + + If you want to commit from the command-line, then you have to take +care of these things yourself. Your ‘init.el’ file should contain: + + (require 'git-commit) + (server-mode) + + Instead of ‘(require ’git-commit)‘ you may also use: + + (load "/path/to/magit-autoloads.el") + + You might want to do that because loading ‘git-commit’ causes large +parts of Magit to be loaded. + + There are also some variations of ‘(server-mode)’ that you might want +to try. Personally I use: + + (use-package server + :config (or (server-running-p) (server-mode))) + + Now you can use: + + $ emacs& + $ EDITOR=emacsclient git commit + + However you cannot use: + + $ killall emacs + $ EDITOR="emacsclient --alternate-editor emacs" git commit + + This will actually end up using ‘emacs’, not ‘emacsclient’. If you +do this, then can still edit the commit message but ‘git-commit-mode’ +won’t be used and you have to exit ‘emacs’ to finish the process. + + Tautology ahead. If you want to be able to use ‘emacsclient’ to +connect to a running ‘emacs’ instance, even though no ‘emacs’ instance +is running, then you cannot use ‘emacsclient’ directly. + + Instead you have to create a script that does something like this: + + Try to use ‘emacsclient’ (without using ‘--alternate-editor’). If +that succeeds, do nothing else. Otherwise start ‘emacs &’ (and +‘init.el’ must call ‘server-start’) and try to use ‘emacsclient’ again. + + +File: magit.info, Node: Point ends up inside invisible text when jumping to a file-visiting buffer, Prev: git-commit-mode isn't used when committing from the command-line, Up: FAQ - Issues and Errors + +A.2.13 Point ends up inside invisible text when jumping to a file-visiting buffer +--------------------------------------------------------------------------------- + +This can happen when you type ‘RET’ on a hunk to visit the respective +file at the respective position. One solution to this problem is to use +‘global-reveal-mode’. It makes sure that text around point is always +visible. If that is too drastic for your taste, then you may instead +use ‘magit-diff-visit-file-hook’ to reveal the text, possibly using +‘reveal-post-command’ or for Org buffers ‘org-reveal’. + + +File: magit.info, Node: Debugging Tools, Next: Keystroke Index, Prev: FAQ, Up: Top + +B Debugging Tools +***************** + +Magit and its dependencies provide a few debugging tools, and we +appreciate it very much if you use those tools before reporting an +issue. Please include all relevant output when reporting an issue. + +‘M-x magit-version’ (‘magit-version’) + + This command shows the currently used versions of Magit, Git, and + Emacs in the echo area. Non-interactively this just returns the + Magit version. + +‘M-x magit-emacs-Q-command’ (‘magit-emacs-Q-command’) + + This command shows a debugging shell command in the echo area and + adds it to the kill ring. Paste that command into a shell and run + it. + + This shell command starts ‘emacs’ with only ‘magit’ and its + dependencies loaded. Neither your configuration nor other + installed packages are loaded. This makes it easier to determine + whether some issue lays with Magit or something else. + + If you run Magit from its Git repository, then you should be able + to use ‘make emacs-Q’ instead of the output of this command. + +‘M-x magit-debug-git-executable’ (‘magit-debug-git-executable’) + + This command displays a buffer containing information about the + available and used ‘git’ executable(s), and can be useful when + investigating ‘exec-path’ issues. + + Also see *note Git Executable::. + +‘M-x with-editor-debug’ (‘with-editor-debug’) + + This command displays a buffer containing information about the + available and used ‘~emacsclient’ executable(s), and can be useful + when investigating why Magit (or rather ‘with-editor’) cannot find + an appropriate ‘emacsclient’ executable. + + Also see *note (with-editor)Debugging::. + + Please also see the *note FAQ::. + + +File: magit.info, Node: Keystroke Index, Next: Command Index, Prev: Debugging Tools, Up: Top + +Appendix C Keystroke Index +************************** + +[index] +* Menu: + +* !: Running Git Manually. + (line 12) +* ! !: Running Git Manually. + (line 16) +* ! a: Running Git Manually. + (line 57) +* ! b: Running Git Manually. + (line 61) +* ! g: Running Git Manually. + (line 65) +* ! k: Running Git Manually. + (line 53) +* ! p: Running Git Manually. + (line 24) +* ! s: Running Git Manually. + (line 34) +* ! S: Running Git Manually. + (line 39) +* $: Viewing Git Output. (line 16) +* %: Worktree. (line 8) +* % b: Worktree. (line 13) +* % c: Worktree. (line 17) +* % g: Worktree. (line 33) +* % k: Worktree. (line 28) +* % p: Worktree. (line 21) +* +: Log Buffer. (line 59) +* + <1>: Refreshing Diffs. (line 68) +* -: Log Buffer. (line 63) +* - <1>: Refreshing Diffs. (line 64) +* 0: Refreshing Diffs. (line 72) +* 1: Section Visibility. (line 26) +* 2: Section Visibility. (line 27) +* 3: Section Visibility. (line 28) +* 4: Section Visibility. (line 29) +* =: Log Buffer. (line 53) +* ^: Section Movement. (line 31) +* a: Applying. (line 33) +* A: Cherry Picking. (line 8) +* A A: Cherry Picking. (line 16) +* A a: Cherry Picking. (line 23) +* A A <1>: Cherry Picking. (line 89) +* A a <1>: Cherry Picking. (line 97) +* A d: Cherry Picking. (line 53) +* A h: Cherry Picking. (line 41) +* A n: Cherry Picking. (line 64) +* A s: Cherry Picking. (line 75) +* A s <1>: Cherry Picking. (line 93) +* B: Bisecting. (line 8) +* b: Blaming. (line 86) +* b <1>: The Branch Popup. (line 12) +* B B: Bisecting. (line 16) +* B b: Bisecting. (line 31) +* b b: The Branch Popup. (line 37) +* b C: The Branch Popup. (line 29) +* b c: The Branch Popup. (line 55) +* B g: Bisecting. (line 36) +* B k: Bisecting. (line 41) +* b k: The Branch Popup. (line 240) +* b l: The Branch Popup. (line 62) +* b n: The Branch Popup. (line 45) +* B r: Bisecting. (line 47) +* b r: The Branch Popup. (line 246) +* B s: Bisecting. (line 24) +* b s: The Branch Popup. (line 85) +* b x: The Branch Popup. (line 224) +* b Y: The Branch Popup. (line 113) +* b y: The Branch Popup. (line 218) +* c: Blaming. (line 120) +* c <1>: Initiating a Commit. (line 8) +* c <2>: Editing Rebase Sequences. + (line 72) +* c a: Initiating a Commit. (line 18) +* c A: Initiating a Commit. (line 66) +* c c: Initiating a Commit. (line 13) +* c e: Initiating a Commit. (line 22) +* c f: Initiating a Commit. (line 42) +* c F: Initiating a Commit. (line 50) +* c s: Initiating a Commit. (line 54) +* c S: Initiating a Commit. (line 62) +* c w: Initiating a Commit. (line 32) +* C-: Diff Buffer. (line 48) +* C-: Section Visibility. (line 13) +* C-c C-a: Editing Commit Messages. + (line 128) +* C-c C-b: Log Buffer. (line 19) +* C-c C-b <1>: Refreshing Diffs. (line 90) +* C-c C-c: Popup Buffers and Prefix Commands. + (line 20) +* C-c C-c <1>: Select from Log. (line 20) +* C-c C-c <2>: Editing Commit Messages. + (line 19) +* C-c C-c <3>: Editing Rebase Sequences. + (line 6) +* C-c C-d: Refreshing Diffs. (line 80) +* C-c C-d <1>: Editing Commit Messages. + (line 57) +* C-c C-e: Diff Buffer. (line 80) +* C-c C-f: Log Buffer. (line 23) +* C-c C-f <1>: Refreshing Diffs. (line 94) +* C-c C-i: Editing Commit Messages. + (line 153) +* C-c C-k: Select from Log. (line 26) +* C-c C-k <1>: Editing Commit Messages. + (line 24) +* C-c C-k <2>: Editing Rebase Sequences. + (line 11) +* C-c C-n: Log Buffer. (line 27) +* C-c C-o: Editing Commit Messages. + (line 144) +* C-c C-p: Editing Commit Messages. + (line 148) +* C-c C-r: Editing Commit Messages. + (line 132) +* C-c C-s: Editing Commit Messages. + (line 136) +* C-c C-t: Diff Buffer. (line 70) +* C-c C-t <1>: Editing Commit Messages. + (line 140) +* C-c C-w: Editing Commit Messages. + (line 63) +* C-c M-g: Minor Mode for Buffers Visiting Files. + (line 19) +* C-c M-g B: Minor Mode for Buffers Visiting Files. + (line 80) +* C-c M-g b: Minor Mode for Buffers Visiting Files. + (line 86) +* C-c M-g c: Minor Mode for Buffers Visiting Files. + (line 33) +* C-c M-g D: Minor Mode for Buffers Visiting Files. + (line 39) +* C-c M-g d: Minor Mode for Buffers Visiting Files. + (line 47) +* C-c M-g e: Minor Mode for Buffers Visiting Files. + (line 102) +* C-c M-g f: Minor Mode for Buffers Visiting Files. + (line 96) +* C-c M-g L: Minor Mode for Buffers Visiting Files. + (line 57) +* C-c M-g l: Minor Mode for Buffers Visiting Files. + (line 64) +* C-c M-g p: Minor Mode for Buffers Visiting Files. + (line 112) +* C-c M-g r: Minor Mode for Buffers Visiting Files. + (line 91) +* C-c M-g s: Minor Mode for Buffers Visiting Files. + (line 24) +* C-c M-g t: Minor Mode for Buffers Visiting Files. + (line 71) +* C-c M-g u: Minor Mode for Buffers Visiting Files. + (line 28) +* C-c M-s: Editing Commit Messages. + (line 35) +* C-w: Common Commands. (line 21) +* C-x g: Status Buffer. (line 22) +* C-x u: Editing Rebase Sequences. + (line 89) +* d: Diffing. (line 20) +* D: Refreshing Diffs. (line 11) +* d c: Diffing. (line 67) +* d d: Diffing. (line 25) +* D f: Refreshing Diffs. (line 45) +* D F: Refreshing Diffs. (line 50) +* D g: Refreshing Diffs. (line 16) +* d p: Diffing. (line 59) +* d r: Diffing. (line 29) +* D r: Refreshing Diffs. (line 40) +* d s: Diffing. (line 49) +* D s: Refreshing Diffs. (line 21) +* d t: Diffing. (line 72) +* D t: Refreshing Diffs. (line 36) +* d u: Diffing. (line 55) +* d w: Diffing. (line 43) +* D w: Refreshing Diffs. (line 28) +* DEL: Log Buffer. (line 43) +* DEL <1>: Diff Buffer. (line 109) +* DEL <2>: Blaming. (line 73) +* DEL <3>: Editing Rebase Sequences. + (line 28) +* e: Ediffing. (line 9) +* E: Ediffing. (line 21) +* e <1>: Editing Rebase Sequences. + (line 55) +* E c: Ediffing. (line 65) +* E i: Ediffing. (line 57) +* E m: Ediffing. (line 35) +* E r: Ediffing. (line 26) +* E s: Ediffing. (line 48) +* E u: Ediffing. (line 53) +* E w: Ediffing. (line 61) +* E z: Ediffing. (line 69) +* f: Editing Rebase Sequences. + (line 63) +* f <1>: Fetching. (line 11) +* F: Pulling. (line 11) +* f a: Fetching. (line 38) +* f e: Fetching. (line 24) +* F e: Pulling. (line 24) +* f m: Fetching. (line 42) +* f o: Fetching. (line 28) +* f p: Fetching. (line 16) +* F p: Pulling. (line 16) +* f r: Fetching. (line 33) +* f u: Fetching. (line 20) +* F u: Pulling. (line 20) +* g: Automatic Refreshing of Magit Buffers. + (line 22) +* G: Automatic Refreshing of Magit Buffers. + (line 31) +* j: Diff Buffer. (line 99) +* k: Viewing Git Output. (line 24) +* k <1>: Applying. (line 40) +* k <2>: Editing Rebase Sequences. + (line 68) +* k <3>: Stashing. (line 95) +* l: Logging. (line 28) +* L: Refreshing Logs. (line 11) +* L <1>: Log Buffer. (line 6) +* L <2>: Log Margin. (line 47) +* l a: Logging. (line 58) +* l b: Logging. (line 54) +* L d: Log Margin. (line 64) +* L g: Refreshing Logs. (line 16) +* l h: Logging. (line 46) +* l H: Reflog. (line 19) +* l l: Logging. (line 33) +* l L: Logging. (line 50) +* L L: Log Margin. (line 56) +* L l: Log Margin. (line 60) +* l o: Logging. (line 39) +* l O: Reflog. (line 15) +* l r: Reflog. (line 11) +* L s: Refreshing Logs. (line 21) +* L t: Refreshing Logs. (line 36) +* L w: Refreshing Logs. (line 28) +* m: Merging. (line 9) +* M: The Remote Popup. (line 13) +* m a: Merging. (line 44) +* m a <1>: Merging. (line 94) +* M a: The Remote Popup. (line 35) +* M C: The Remote Popup. (line 26) +* m e: Merging. (line 30) +* m i: Merging. (line 57) +* M k: The Remote Popup. (line 50) +* m m: Merging. (line 17) +* m m <1>: Merging. (line 88) +* m n: Merging. (line 37) +* m p: Merging. (line 80) +* M p: The Remote Popup. (line 54) +* M P: The Remote Popup. (line 59) +* M r: The Remote Popup. (line 40) +* m s: Merging. (line 71) +* M u: The Remote Popup. (line 45) +* M-1: Section Visibility. (line 33) +* M-2: Section Visibility. (line 34) +* M-3: Section Visibility. (line 35) +* M-4: Section Visibility. (line 36) +* M-: Section Visibility. (line 17) +* M-n: Section Movement. (line 26) +* M-n <1>: Editing Commit Messages. + (line 45) +* M-n <2>: Editing Rebase Sequences. + (line 47) +* M-p: Section Movement. (line 20) +* M-p <1>: Editing Commit Messages. + (line 39) +* M-p <2>: Editing Rebase Sequences. + (line 43) +* M-w: Blaming. (line 112) +* M-w <1>: Common Commands. (line 10) +* M-x magit-clone: Repository Setup. (line 16) +* M-x magit-debug-git-executable: Git Executable. (line 45) +* M-x magit-debug-git-executable <1>: Debugging Tools. (line 30) +* M-x magit-describe-section-briefly: Section Types and Values. + (line 13) +* M-x magit-describe-section-briefly <1>: Matching Sections. (line 6) +* M-x magit-emacs-Q-command: Debugging Tools. (line 16) +* M-x magit-find-file: Visiting Blobs. (line 6) +* M-x magit-find-file-other-window: Visiting Blobs. (line 11) +* M-x magit-init: Repository Setup. (line 6) +* M-x magit-reset-index: Staging and Unstaging. + (line 87) +* M-x magit-reverse-in-index: Staging and Unstaging. + (line 62) +* M-x magit-stage-file: Staging from File-Visiting Buffers. + (line 10) +* M-x magit-toggle-buffer-lock: Modes and Buffers. (line 17) +* M-x magit-unstage-file: Staging from File-Visiting Buffers. + (line 18) +* M-x magit-version: Git Executable. (line 17) +* M-x magit-version <1>: Debugging Tools. (line 10) +* M-x magit-wip-commit: Wip Modes. (line 88) +* M-x with-editor-debug: Debugging Tools. (line 38) +* n: Section Movement. (line 16) +* n <1>: Blaming. (line 91) +* N: Blaming. (line 95) +* n <2>: Editing Rebase Sequences. + (line 39) +* n <3>: Minor Mode for Buffers Visiting Blobs. + (line 16) +* o: Submodule Popup. (line 6) +* O: Subtree. (line 8) +* o a: Submodule Popup. (line 19) +* O a: Subtree. (line 20) +* O c: Subtree. (line 24) +* o d: Submodule Popup. (line 49) +* o f: Submodule Popup. (line 57) +* O f: Subtree. (line 32) +* o l: Submodule Popup. (line 53) +* O m: Subtree. (line 28) +* o p: Submodule Popup. (line 33) +* O p: Subtree. (line 36) +* o r: Submodule Popup. (line 26) +* o s: Submodule Popup. (line 43) +* O s: Subtree. (line 41) +* o u: Submodule Popup. (line 38) +* p: Section Movement. (line 10) +* p <1>: Blaming. (line 99) +* P: Blaming. (line 103) +* p <2>: Editing Rebase Sequences. + (line 35) +* P <1>: Pushing. (line 11) +* p <3>: Minor Mode for Buffers Visiting Blobs. + (line 12) +* P e: Pushing. (line 35) +* P m: Pushing. (line 53) +* P o: Pushing. (line 39) +* P p: Pushing. (line 16) +* P r: Pushing. (line 44) +* P t: Pushing. (line 59) +* P T: Pushing. (line 65) +* P u: Pushing. (line 26) +* q: Quitting Windows. (line 6) +* q <1>: Log Buffer. (line 12) +* q <2>: Blaming. (line 107) +* q <3>: Minor Mode for Buffers Visiting Blobs. + (line 20) +* r: Rebasing. (line 9) +* r <1>: Editing Rebase Sequences. + (line 51) +* r a: Rebasing. (line 107) +* r e: Rebasing. (line 33) +* r e <1>: Rebasing. (line 103) +* r f: Rebasing. (line 73) +* r i: Rebasing. (line 69) +* r k: Rebasing. (line 85) +* r m: Rebasing. (line 77) +* r p: Rebasing. (line 24) +* r r: Rebasing. (line 92) +* r s: Rebasing. (line 39) +* r s <1>: Rebasing. (line 99) +* r u: Rebasing. (line 29) +* r w: Rebasing. (line 81) +* RET: Diff Buffer. (line 8) +* RET <1>: References Buffer. (line 166) +* RET <2>: Blaming. (line 59) +* RET <3>: Editing Rebase Sequences. + (line 16) +* s: Staging and Unstaging. + (line 28) +* S: Staging and Unstaging. + (line 36) +* s <1>: Editing Rebase Sequences. + (line 59) +* S-: Section Visibility. (line 22) +* SPC: Log Buffer. (line 33) +* SPC <1>: Diff Buffer. (line 105) +* SPC <2>: Blaming. (line 63) +* SPC <3>: Editing Rebase Sequences. + (line 21) +* t: Tagging. (line 8) +* T: Notes. (line 8) +* T a: Notes. (line 51) +* T c: Notes. (line 46) +* t k: Tagging. (line 18) +* T m: Notes. (line 37) +* t p: Tagging. (line 24) +* T p: Notes. (line 29) +* T r: Notes. (line 21) +* t t: Tagging. (line 13) +* T T: Notes. (line 13) +* TAB: Section Visibility. (line 9) +* u: Staging and Unstaging. + (line 43) +* U: Staging and Unstaging. + (line 52) +* v: Applying. (line 44) +* V: Reverting. (line 6) +* V A: Reverting. (line 30) +* V a: Reverting. (line 38) +* V s: Reverting. (line 34) +* V V: Reverting. (line 14) +* V v: Reverting. (line 20) +* W: Creating and Sending Patches. + (line 6) +* w: Applying Patches. (line 8) +* w a: Applying Patches. (line 34) +* w a <1>: Applying Patches. (line 42) +* w a a: Applying Patches. (line 47) +* w m: Applying Patches. (line 19) +* W p: Creating and Sending Patches. + (line 11) +* W r: Creating and Sending Patches. + (line 17) +* w s: Applying Patches. (line 30) +* w w: Applying Patches. (line 13) +* w w <1>: Applying Patches. (line 26) +* x: Editing Rebase Sequences. + (line 76) +* x <1>: Resetting. (line 8) +* X f: Resetting. (line 44) +* X h: Resetting. (line 26) +* X i: Resetting. (line 31) +* X m: Resetting. (line 15) +* X s: Resetting. (line 20) +* X w: Resetting. (line 38) +* X w <1>: Wip Modes. (line 66) +* Y: Cherries. (line 17) +* y: References Buffer. (line 6) +* y <1>: Editing Rebase Sequences. + (line 85) +* y c: References Buffer. (line 19) +* y o: References Buffer. (line 24) +* y y: References Buffer. (line 14) +* z: Stashing. (line 8) +* z a: Stashing. (line 58) +* z b: Stashing. (line 80) +* z B: Stashing. (line 85) +* z f: Stashing. (line 91) +* z i: Stashing. (line 20) +* z I: Stashing. (line 46) +* z k: Stashing. (line 71) +* z l: Stashing. (line 99) +* z p: Stashing. (line 64) +* z v: Stashing. (line 76) +* z w: Stashing. (line 25) +* z W: Stashing. (line 51) +* z x: Stashing. (line 32) +* z z: Stashing. (line 13) +* z Z: Stashing. (line 39) + + +File: magit.info, Node: Command Index, Next: Function Index, Prev: Keystroke Index, Up: Top + +Appendix D Command Index +************************ + +[index] +* Menu: + +* auto-revert-mode: Automatic Reverting of File-Visiting Buffers. + (line 62) +* forward-line: Editing Rebase Sequences. + (line 39) +* git-commit-ack: Editing Commit Messages. + (line 128) +* git-commit-cc: Editing Commit Messages. + (line 144) +* git-commit-next-message: Editing Commit Messages. + (line 45) +* git-commit-prev-message: Editing Commit Messages. + (line 39) +* git-commit-reported: Editing Commit Messages. + (line 148) +* git-commit-review: Editing Commit Messages. + (line 132) +* git-commit-save-message: Editing Commit Messages. + (line 35) +* git-commit-signoff: Editing Commit Messages. + (line 136) +* git-commit-suggested: Editing Commit Messages. + (line 153) +* git-commit-test: Editing Commit Messages. + (line 140) +* git-rebase-backward-line: Editing Rebase Sequences. + (line 35) +* git-rebase-edit: Editing Rebase Sequences. + (line 55) +* git-rebase-exec: Editing Rebase Sequences. + (line 76) +* git-rebase-fixup: Editing Rebase Sequences. + (line 63) +* git-rebase-insert: Editing Rebase Sequences. + (line 85) +* git-rebase-kill-line: Editing Rebase Sequences. + (line 68) +* git-rebase-move-line-down: Editing Rebase Sequences. + (line 47) +* git-rebase-move-line-up: Editing Rebase Sequences. + (line 43) +* git-rebase-pick: Editing Rebase Sequences. + (line 72) +* git-rebase-reword: Editing Rebase Sequences. + (line 51) +* git-rebase-show-commit: Editing Rebase Sequences. + (line 16) +* git-rebase-show-or-scroll-down: Editing Rebase Sequences. + (line 28) +* git-rebase-show-or-scroll-up: Editing Rebase Sequences. + (line 21) +* git-rebase-squash: Editing Rebase Sequences. + (line 59) +* git-rebase-undo: Editing Rebase Sequences. + (line 89) +* ido-enter-magit-status: Status Buffer. (line 47) +* magit-am-abort: Applying Patches. (line 34) +* magit-am-apply-maildir: Applying Patches. (line 19) +* magit-am-apply-patches: Applying Patches. (line 13) +* magit-am-continue: Applying Patches. (line 26) +* magit-am-popup: Applying Patches. (line 8) +* magit-am-skip: Applying Patches. (line 30) +* magit-apply: Applying. (line 33) +* magit-bisect-bad: Bisecting. (line 31) +* magit-bisect-good: Bisecting. (line 36) +* magit-bisect-popup: Bisecting. (line 8) +* magit-bisect-reset: Bisecting. (line 47) +* magit-bisect-run: Bisecting. (line 24) +* magit-bisect-skip: Bisecting. (line 41) +* magit-bisect-start: Bisecting. (line 16) +* magit-blame-addition: Blaming. (line 17) +* magit-blame-addition <1>: Minor Mode for Buffers Visiting Files. + (line 86) +* magit-blame-copy-hash: Blaming. (line 112) +* magit-blame-cycle-style: Blaming. (line 120) +* magit-blame-echo: Blaming. (line 32) +* magit-blame-next-chunk: Blaming. (line 91) +* magit-blame-next-chunk-same-commit: Blaming. (line 95) +* magit-blame-popup: Blaming. (line 86) +* magit-blame-popup <1>: Minor Mode for Buffers Visiting Files. + (line 80) +* magit-blame-previous-chunk: Blaming. (line 99) +* magit-blame-previous-chunk-same-commit: Blaming. (line 103) +* magit-blame-quit: Blaming. (line 107) +* magit-blame-removal: Blaming. (line 38) +* magit-blame-removal <1>: Minor Mode for Buffers Visiting Files. + (line 91) +* magit-blame-reverse: Blaming. (line 46) +* magit-blame-reverse <1>: Minor Mode for Buffers Visiting Files. + (line 96) +* magit-blob-next: Minor Mode for Buffers Visiting Blobs. + (line 16) +* magit-blob-previous: Minor Mode for Buffers Visiting Files. + (line 112) +* magit-blob-previous <1>: Minor Mode for Buffers Visiting Blobs. + (line 12) +* magit-branch-and-checkout: The Branch Popup. (line 55) +* magit-branch-checkout: The Branch Popup. (line 62) +* magit-branch-config-popup: The Branch Popup. (line 29) +* magit-branch-config-popup <1>: The Branch Config Popup. + (line 6) +* magit-branch-create: The Branch Popup. (line 45) +* magit-branch-delete: The Branch Popup. (line 240) +* magit-branch-or-checkout: The Branch Popup. (line 350) +* magit-branch-orphan: The Branch Popup. (line 345) +* magit-branch-popup: The Branch Popup. (line 12) +* magit-branch-pull-request: The Branch Popup. (line 113) +* magit-branch-rename: The Branch Popup. (line 246) +* magit-branch-reset: The Branch Popup. (line 224) +* magit-branch-shelve: Auxiliary Branch Commands. + (line 8) +* magit-branch-spinoff: The Branch Popup. (line 85) +* magit-branch-unshelve: Auxiliary Branch Commands. + (line 19) +* magit-checkout: The Branch Popup. (line 37) +* magit-checkout-pull-request: The Branch Popup. (line 218) +* magit-cherry: Cherries. (line 17) +* magit-cherry-apply: Cherry Picking. (line 23) +* magit-cherry-copy: Cherry Picking. (line 16) +* magit-cherry-donate: Cherry Picking. (line 53) +* magit-cherry-harvest: Cherry Picking. (line 41) +* magit-cherry-pick-popup: Cherry Picking. (line 8) +* magit-cherry-spinoff: Cherry Picking. (line 75) +* magit-cherry-spinout: Cherry Picking. (line 64) +* magit-clone: Repository Setup. (line 16) +* magit-commit-amend: Initiating a Commit. (line 18) +* magit-commit-augment: Initiating a Commit. (line 66) +* magit-commit-create: Initiating a Commit. (line 13) +* magit-commit-extend: Initiating a Commit. (line 22) +* magit-commit-fixup: Initiating a Commit. (line 42) +* magit-commit-instant-fixup: Initiating a Commit. (line 50) +* magit-commit-instant-squash: Initiating a Commit. (line 62) +* magit-commit-popup: Initiating a Commit. (line 8) +* magit-commit-popup <1>: Minor Mode for Buffers Visiting Files. + (line 33) +* magit-commit-reword: Initiating a Commit. (line 32) +* magit-commit-squash: Initiating a Commit. (line 54) +* magit-copy-buffer-revision: Common Commands. (line 21) +* magit-copy-section-value: Common Commands. (line 10) +* magit-cycle-margin-style: Log Margin. (line 60) +* magit-debug-git-executable: Git Executable. (line 45) +* magit-debug-git-executable <1>: Debugging Tools. (line 30) +* magit-describe-section-briefly: Section Types and Values. + (line 13) +* magit-describe-section-briefly <1>: Matching Sections. (line 6) +* magit-diff-buffer-file: Minor Mode for Buffers Visiting Files. + (line 47) +* magit-diff-buffer-file-popup: Minor Mode for Buffers Visiting Files. + (line 39) +* magit-diff-default-context: Refreshing Diffs. (line 72) +* magit-diff-dwim: Diffing. (line 25) +* magit-diff-edit-hunk-commit: Diff Buffer. (line 80) +* magit-diff-flip-revs: Refreshing Diffs. (line 45) +* magit-diff-less-context: Refreshing Diffs. (line 64) +* magit-diff-more-context: Refreshing Diffs. (line 68) +* magit-diff-paths: Diffing. (line 59) +* magit-diff-popup: Diffing. (line 20) +* magit-diff-range: Diffing. (line 29) +* magit-diff-refresh: Refreshing Diffs. (line 16) +* magit-diff-refresh-popup: Refreshing Diffs. (line 11) +* magit-diff-save-default-arguments: Refreshing Diffs. (line 28) +* magit-diff-set-default-arguments: Refreshing Diffs. (line 21) +* magit-diff-show-or-scroll-down: Log Buffer. (line 43) +* magit-diff-show-or-scroll-down <1>: Blaming. (line 73) +* magit-diff-show-or-scroll-up: Log Buffer. (line 33) +* magit-diff-show-or-scroll-up <1>: Blaming. (line 63) +* magit-diff-staged: Diffing. (line 49) +* magit-diff-switch-range-type: Refreshing Diffs. (line 40) +* magit-diff-toggle-file-filter: Refreshing Diffs. (line 50) +* magit-diff-toggle-refine-hunk: Refreshing Diffs. (line 36) +* magit-diff-trace-definition: Diff Buffer. (line 70) +* magit-diff-unstaged: Diffing. (line 55) +* magit-diff-visit-file: Diff Buffer. (line 8) +* magit-diff-visit-file-other-window: Diff Buffer. (line 65) +* magit-diff-visit-file-worktree: Diff Buffer. (line 48) +* magit-diff-while-committing: Refreshing Diffs. (line 80) +* magit-diff-while-committing <1>: Editing Commit Messages. + (line 57) +* magit-diff-working-tree: Diffing. (line 43) +* magit-discard: Applying. (line 40) +* magit-dispatch-popup: Popup Buffers and Prefix Commands. + (line 20) +* magit-ediff-compare: Ediffing. (line 26) +* magit-ediff-dwim: Ediffing. (line 9) +* magit-ediff-popup: Ediffing. (line 21) +* magit-ediff-resolve: Ediffing. (line 35) +* magit-ediff-show-commit: Ediffing. (line 65) +* magit-ediff-show-staged: Ediffing. (line 57) +* magit-ediff-show-stash: Ediffing. (line 69) +* magit-ediff-show-unstaged: Ediffing. (line 53) +* magit-ediff-show-working-tree: Ediffing. (line 61) +* magit-ediff-stage: Ediffing. (line 48) +* magit-edit-line-commit: Minor Mode for Buffers Visiting Files. + (line 102) +* magit-emacs-Q-command: Debugging Tools. (line 16) +* magit-fetch-all: Fetching. (line 38) +* magit-fetch-branch: Fetching. (line 28) +* magit-fetch-from-pushremote: Fetching. (line 16) +* magit-fetch-from-upstream: Fetching. (line 20) +* magit-fetch-modules: Submodule Popup. (line 57) +* magit-fetch-other: Fetching. (line 24) +* magit-fetch-popup: Fetching. (line 11) +* magit-fetch-refspec: Fetching. (line 33) +* magit-file-checkout: Resetting. (line 44) +* magit-file-checkout <1>: Minor Mode for Buffers Visiting Files. + (line 131) +* magit-file-delete: Minor Mode for Buffers Visiting Files. + (line 123) +* magit-file-popup: Minor Mode for Buffers Visiting Files. + (line 19) +* magit-file-rename: Minor Mode for Buffers Visiting Files. + (line 119) +* magit-file-untrack: Minor Mode for Buffers Visiting Files. + (line 127) +* magit-find-file: Visiting Blobs. (line 6) +* magit-find-file-other-window: Visiting Blobs. (line 11) +* magit-format-patch: Creating and Sending Patches. + (line 11) +* magit-git-command: Running Git Manually. + (line 24) +* magit-git-command-topdir: Running Git Manually. + (line 16) +* magit-go-backward: Log Buffer. (line 19) +* magit-go-backward <1>: Refreshing Diffs. (line 90) +* magit-go-forward: Log Buffer. (line 23) +* magit-go-forward <1>: Refreshing Diffs. (line 94) +* magit-init: Repository Setup. (line 6) +* magit-jump-to-diffstat-or-diff: Diff Buffer. (line 99) +* magit-kill-this-buffer: Minor Mode for Buffers Visiting Blobs. + (line 20) +* magit-list-repositories: Repository List. (line 6) +* magit-list-submodules: Listing Submodules. (line 13) +* magit-list-submodules <1>: Submodule Popup. (line 53) +* magit-log-all: Logging. (line 58) +* magit-log-all-branches: Logging. (line 54) +* magit-log-branches: Logging. (line 50) +* magit-log-buffer-file: Minor Mode for Buffers Visiting Files. + (line 64) +* magit-log-buffer-file-popup: Minor Mode for Buffers Visiting Files. + (line 57) +* magit-log-bury-buffer: Log Buffer. (line 12) +* magit-log-current: Logging. (line 33) +* magit-log-double-commit-limit: Log Buffer. (line 59) +* magit-log-half-commit-limit: Log Buffer. (line 63) +* magit-log-head: Logging. (line 46) +* magit-log-move-to-parent: Log Buffer. (line 27) +* magit-log-other: Logging. (line 39) +* magit-log-popup: Logging. (line 28) +* magit-log-refresh: Refreshing Logs. (line 16) +* magit-log-refresh-popup: Refreshing Logs. (line 11) +* magit-log-refresh-popup <1>: Log Buffer. (line 6) +* magit-log-save-default-arguments: Refreshing Logs. (line 28) +* magit-log-select-pick: Select from Log. (line 20) +* magit-log-select-quit: Select from Log. (line 26) +* magit-log-set-default-arguments: Refreshing Logs. (line 21) +* magit-log-toggle-commit-limit: Log Buffer. (line 53) +* magit-log-trace-definition: Minor Mode for Buffers Visiting Files. + (line 71) +* magit-margin-popup: Log Margin. (line 47) +* magit-merge: Merging. (line 88) +* magit-merge-abort: Merging. (line 94) +* magit-merge-absorb: Merging. (line 44) +* magit-merge-editmsg: Merging. (line 30) +* magit-merge-into: Merging. (line 57) +* magit-merge-nocommit: Merging. (line 37) +* magit-merge-plain: Merging. (line 17) +* magit-merge-popup: Merging. (line 9) +* magit-merge-preview: Merging. (line 80) +* magit-merge-squash: Merging. (line 71) +* magit-mode-bury-buffer: Quitting Windows. (line 6) +* magit-notes-edit: Notes. (line 13) +* magit-notes-merge: Notes. (line 37) +* magit-notes-merge-abort: Notes. (line 51) +* magit-notes-merge-commit: Notes. (line 46) +* magit-notes-popup: Notes. (line 8) +* magit-notes-prune: Notes. (line 29) +* magit-notes-remove: Notes. (line 21) +* magit-patch-apply: Applying Patches. (line 47) +* magit-patch-apply-popup: Applying Patches. (line 42) +* magit-patch-popup: Creating and Sending Patches. + (line 6) +* magit-pop-revision-stack: Editing Commit Messages. + (line 63) +* magit-process: Viewing Git Output. (line 16) +* magit-process-kill: Viewing Git Output. (line 24) +* magit-pull-branch: Pulling. (line 24) +* magit-pull-from-pushremote: Pulling. (line 16) +* magit-pull-from-upstream: Pulling. (line 20) +* magit-pull-popup: Pulling. (line 11) +* magit-push-current: Pushing. (line 35) +* magit-push-current-to-pushremote: Pushing. (line 16) +* magit-push-current-to-upstream: Pushing. (line 26) +* magit-push-implicitly args: Pushing. (line 73) +* magit-push-matching: Pushing. (line 53) +* magit-push-other: Pushing. (line 39) +* magit-push-popup: Pushing. (line 11) +* magit-push-refspecs: Pushing. (line 44) +* magit-push-tag: Pushing. (line 65) +* magit-push-tags: Pushing. (line 59) +* magit-push-to-remote remote args: Pushing. (line 84) +* magit-rebase-abort: Rebasing. (line 107) +* magit-rebase-autosquash: Rebasing. (line 73) +* magit-rebase-branch: Rebasing. (line 33) +* magit-rebase-continue: Rebasing. (line 92) +* magit-rebase-edit: Rebasing. (line 103) +* magit-rebase-edit-commit: Rebasing. (line 77) +* magit-rebase-interactive: Rebasing. (line 69) +* magit-rebase-onto-pushremote: Rebasing. (line 24) +* magit-rebase-onto-upstream: Rebasing. (line 29) +* magit-rebase-popup: Rebasing. (line 9) +* magit-rebase-remove-commit: Rebasing. (line 85) +* magit-rebase-reword-commit: Rebasing. (line 81) +* magit-rebase-skip: Rebasing. (line 99) +* magit-rebase-subset: Rebasing. (line 39) +* magit-reflog-current: Reflog. (line 11) +* magit-reflog-head: Reflog. (line 19) +* magit-reflog-other: Reflog. (line 15) +* magit-refresh: Automatic Refreshing of Magit Buffers. + (line 22) +* magit-refresh-all: Automatic Refreshing of Magit Buffers. + (line 31) +* magit-remote-add: The Remote Popup. (line 35) +* magit-remote-config-popup: The Remote Popup. (line 26) +* magit-remote-config-popup <1>: The Remote Config Popup. + (line 6) +* magit-remote-popup: The Remote Popup. (line 13) +* magit-remote-prune: The Remote Popup. (line 54) +* magit-remote-prune-refspecs: The Remote Popup. (line 59) +* magit-remote-remove: The Remote Popup. (line 50) +* magit-remote-rename: The Remote Popup. (line 40) +* magit-remote-set-url: The Remote Popup. (line 45) +* magit-request-pull: Creating and Sending Patches. + (line 17) +* magit-reset-hard: Resetting. (line 26) +* magit-reset-index: Staging and Unstaging. + (line 87) +* magit-reset-index <1>: Resetting. (line 31) +* magit-reset-mixed: Resetting. (line 15) +* magit-reset-quickly: Resetting. (line 8) +* magit-reset-soft: Resetting. (line 20) +* magit-reset-worktree: Resetting. (line 38) +* magit-reset-worktree <1>: Wip Modes. (line 66) +* magit-reverse: Applying. (line 44) +* magit-reverse-in-index: Staging and Unstaging. + (line 62) +* magit-revert-and-commit: Reverting. (line 14) +* magit-revert-no-commit: Reverting. (line 20) +* magit-revert-popup: Reverting. (line 6) +* magit-run-git-gui: Running Git Manually. + (line 65) +* magit-run-gitk: Running Git Manually. + (line 53) +* magit-run-gitk-all: Running Git Manually. + (line 57) +* magit-run-gitk-branches: Running Git Manually. + (line 61) +* magit-run-popup: Running Git Manually. + (line 12) +* magit-section-backward: Section Movement. (line 10) +* magit-section-backward-siblings: Section Movement. (line 20) +* magit-section-cycle: Section Visibility. (line 13) +* magit-section-cycle-diffs: Section Visibility. (line 17) +* magit-section-cycle-global: Section Visibility. (line 22) +* magit-section-forward: Section Movement. (line 16) +* magit-section-forward-siblings: Section Movement. (line 26) +* magit-section-hide: Section Visibility. (line 49) +* magit-section-hide-children: Section Visibility. (line 64) +* magit-section-show: Section Visibility. (line 45) +* magit-section-show-children: Section Visibility. (line 58) +* magit-section-show-headings: Section Visibility. (line 53) +* magit-section-show-level-1: Section Visibility. (line 26) +* magit-section-show-level-1-all: Section Visibility. (line 33) +* magit-section-show-level-2: Section Visibility. (line 27) +* magit-section-show-level-2-all: Section Visibility. (line 34) +* magit-section-show-level-3: Section Visibility. (line 28) +* magit-section-show-level-3-all: Section Visibility. (line 35) +* magit-section-show-level-4: Section Visibility. (line 29) +* magit-section-show-level-4-all: Section Visibility. (line 36) +* magit-section-toggle: Section Visibility. (line 9) +* magit-section-toggle-children: Section Visibility. (line 68) +* magit-section-up: Section Movement. (line 31) +* magit-sequence-abort: Cherry Picking. (line 97) +* magit-sequence-abort <1>: Reverting. (line 38) +* magit-sequence-continue: Cherry Picking. (line 89) +* magit-sequence-continue <1>: Reverting. (line 30) +* magit-sequence-skip: Cherry Picking. (line 93) +* magit-sequence-skip <1>: Reverting. (line 34) +* magit-shell-command: Running Git Manually. + (line 39) +* magit-shell-command-topdir: Running Git Manually. + (line 34) +* magit-show-commit: Diffing. (line 67) +* magit-show-commit <1>: Blaming. (line 59) +* magit-show-refs: References Buffer. (line 24) +* magit-show-refs-current: References Buffer. (line 19) +* magit-show-refs-head: References Buffer. (line 14) +* magit-show-refs-popup: References Buffer. (line 6) +* magit-snapshot-both: Stashing. (line 39) +* magit-snapshot-index: Stashing. (line 46) +* magit-snapshot-worktree: Stashing. (line 51) +* magit-stage: Staging and Unstaging. + (line 28) +* magit-stage-file: Staging from File-Visiting Buffers. + (line 10) +* magit-stage-file <1>: Minor Mode for Buffers Visiting Files. + (line 24) +* magit-stage-modified: Staging and Unstaging. + (line 36) +* magit-stash-apply: Stashing. (line 58) +* magit-stash-both: Stashing. (line 13) +* magit-stash-branch: Stashing. (line 80) +* magit-stash-branch-here: Stashing. (line 85) +* magit-stash-clear: Stashing. (line 95) +* magit-stash-drop: Stashing. (line 71) +* magit-stash-format-patch: Stashing. (line 91) +* magit-stash-index: Stashing. (line 20) +* magit-stash-keep-index: Stashing. (line 32) +* magit-stash-list: Stashing. (line 99) +* magit-stash-pop: Stashing. (line 64) +* magit-stash-popup: Stashing. (line 8) +* magit-stash-show: Diffing. (line 72) +* magit-stash-show <1>: Stashing. (line 76) +* magit-stash-worktree: Stashing. (line 25) +* magit-status: Status Buffer. (line 22) +* magit-submodule-add: Submodule Popup. (line 19) +* magit-submodule-fetch: Fetching. (line 42) +* magit-submodule-populate: Submodule Popup. (line 33) +* magit-submodule-popup: Submodule Popup. (line 6) +* magit-submodule-register: Submodule Popup. (line 26) +* magit-submodule-synchronize: Submodule Popup. (line 43) +* magit-submodule-unpopulate: Submodule Popup. (line 49) +* magit-submodule-update: Submodule Popup. (line 38) +* magit-subtree-add: Subtree. (line 20) +* magit-subtree-add-commit: Subtree. (line 24) +* magit-subtree-merge: Subtree. (line 28) +* magit-subtree-pull: Subtree. (line 32) +* magit-subtree-push: Subtree. (line 36) +* magit-subtree-split: Subtree. (line 41) +* magit-tag-create: Tagging. (line 13) +* magit-tag-delete: Tagging. (line 18) +* magit-tag-popup: Tagging. (line 8) +* magit-tag-prune: Tagging. (line 24) +* magit-tag-release: Tagging. (line 28) +* magit-toggle-buffer-lock: Modes and Buffers. (line 17) +* magit-toggle-margin: Refreshing Logs. (line 36) +* magit-toggle-margin <1>: Log Margin. (line 56) +* magit-toggle-margin-details: Log Margin. (line 64) +* magit-tree-popup: Subtree. (line 8) +* magit-unstage: Staging and Unstaging. + (line 43) +* magit-unstage-all: Staging and Unstaging. + (line 52) +* magit-unstage-file: Staging from File-Visiting Buffers. + (line 18) +* magit-unstage-file <1>: Minor Mode for Buffers Visiting Files. + (line 28) +* magit-version: Git Executable. (line 17) +* magit-version <1>: Debugging Tools. (line 10) +* magit-visit-ref: References Buffer. (line 166) +* magit-wip-commit: Wip Modes. (line 88) +* magit-wip-log: Wip Modes. (line 48) +* magit-wip-log-current: Wip Modes. (line 57) +* magit-worktree-branch: Worktree. (line 17) +* magit-worktree-checkout: Worktree. (line 13) +* magit-worktree-checkout-pull-request: Worktree. (line 21) +* magit-worktree-delete: Worktree. (line 28) +* magit-worktree-popup: Worktree. (line 8) +* magit-worktree-status: Worktree. (line 33) +* scroll-down: Diff Buffer. (line 109) +* scroll-up: Diff Buffer. (line 105) +* with-editor-cancel: Editing Commit Messages. + (line 24) +* with-editor-cancel <1>: Editing Rebase Sequences. + (line 11) +* with-editor-debug: Debugging Tools. (line 38) +* with-editor-finish: Editing Commit Messages. + (line 19) +* with-editor-finish <1>: Editing Rebase Sequences. + (line 6) + + +File: magit.info, Node: Function Index, Next: Variable Index, Prev: Command Index, Up: Top + +Appendix E Function Index +************************* + +[index] +* Menu: + +* auto-revert-mode: Automatic Reverting of File-Visiting Buffers. + (line 62) +* git-commit-check-style-conventions: Editing Commit Messages. + (line 247) +* git-commit-propertize-diff: Editing Commit Messages. + (line 206) +* git-commit-save-message: Editing Commit Messages. + (line 187) +* git-commit-setup-changelog-support: Editing Commit Messages. + (line 191) +* git-commit-turn-on-auto-fill: Editing Commit Messages. + (line 196) +* git-commit-turn-on-flyspell: Editing Commit Messages. + (line 201) +* ido-enter-magit-status: Status Buffer. (line 47) +* magit-add-section-hook: Section Hooks. (line 20) +* magit-after-save-refresh-status: Automatic Refreshing of Magit Buffers. + (line 56) +* magit-blame-addition: Blaming. (line 17) +* magit-blame-echo: Blaming. (line 32) +* magit-blame-removal: Blaming. (line 38) +* magit-blame-reverse: Blaming. (line 46) +* magit-branch-config-popup: The Branch Config Popup. + (line 6) +* magit-branch-or-checkout: The Branch Popup. (line 350) +* magit-branch-orphan: The Branch Popup. (line 345) +* magit-branch-shelve: Auxiliary Branch Commands. + (line 8) +* magit-branch-unshelve: Auxiliary Branch Commands. + (line 19) +* magit-builtin-completing-read: Support for Completion Frameworks. + (line 42) +* magit-call-git: Calling Git for Effect. + (line 28) +* magit-call-process: Calling Git for Effect. + (line 32) +* magit-cancel-section: Creating Sections. (line 71) +* magit-completing-read: Support for Completion Frameworks. + (line 60) +* magit-current-section: Section Selection. (line 6) +* magit-define-section-jumper: Creating Sections. (line 77) +* magit-diff-scope: Matching Sections. (line 118) +* magit-diff-type: Matching Sections. (line 95) +* magit-diff-visit-file-other-window: Diff Buffer. (line 65) +* magit-display-buffer: Switching Buffers. (line 6) +* magit-display-buffer-fullcolumn-most-v1: Switching Buffers. (line 72) +* magit-display-buffer-fullframe-status-topleft-v1: Switching Buffers. + (line 62) +* magit-display-buffer-fullframe-status-v1: Switching Buffers. + (line 56) +* magit-display-buffer-same-window-except-diff-v1: Switching Buffers. + (line 50) +* magit-display-buffer-traditional: Switching Buffers. (line 42) +* magit-file-checkout: Minor Mode for Buffers Visiting Files. + (line 131) +* magit-file-delete: Minor Mode for Buffers Visiting Files. + (line 123) +* magit-file-rename: Minor Mode for Buffers Visiting Files. + (line 119) +* magit-file-untrack: Minor Mode for Buffers Visiting Files. + (line 127) +* magit-generate-buffer-name-default-function: Naming Buffers. + (line 17) +* magit-get-section: Matching Sections. (line 16) +* magit-git: Calling Git for Effect. + (line 65) +* magit-git-exit-code: Getting a Value from Git. + (line 10) +* magit-git-failure: Getting a Value from Git. + (line 19) +* magit-git-false: Getting a Value from Git. + (line 29) +* magit-git-insert: Getting a Value from Git. + (line 34) +* magit-git-items: Getting a Value from Git. + (line 49) +* magit-git-lines: Getting a Value from Git. + (line 44) +* magit-git-str: Getting a Value from Git. + (line 72) +* magit-git-string: Getting a Value from Git. + (line 38) +* magit-git-success: Getting a Value from Git. + (line 14) +* magit-git-true: Getting a Value from Git. + (line 24) +* magit-git-wash: Calling Git for Effect. + (line 70) +* magit-hunk-set-window-start: Section Movement. (line 43) +* magit-ido-completing-read: Support for Completion Frameworks. + (line 48) +* magit-insert-am-sequence: Status Sections. (line 28) +* magit-insert-bisect-log: Status Sections. (line 46) +* magit-insert-bisect-output: Status Sections. (line 38) +* magit-insert-bisect-rest: Status Sections. (line 42) +* magit-insert-diff-filter-header: Status Header Sections. + (line 38) +* magit-insert-error-header: Status Header Sections. + (line 28) +* magit-insert-head-branch-header: Status Header Sections. + (line 42) +* magit-insert-heading: Creating Sections. (line 42) +* magit-insert-ignored-files: Status Sections. (line 100) +* magit-insert-local-branches: References Sections. (line 17) +* magit-insert-merge-log: Status Sections. (line 18) +* magit-insert-modules: Status Module Sections. + (line 12) +* magit-insert-modules-overview: Status Module Sections. + (line 33) +* magit-insert-modules-unpulled-from-pushremote: Status Module Sections. + (line 50) +* magit-insert-modules-unpulled-from-upstream: Status Module Sections. + (line 44) +* magit-insert-modules-unpushed-to-pushremote: Status Module Sections. + (line 62) +* magit-insert-modules-unpushed-to-upstream: Status Module Sections. + (line 56) +* magit-insert-push-branch-header: Status Header Sections. + (line 51) +* magit-insert-rebase-sequence: Status Sections. (line 23) +* magit-insert-recent-commits: Status Sections. (line 115) +* magit-insert-remote-branches: References Sections. (line 21) +* magit-insert-remote-header: Status Header Sections. + (line 67) +* magit-insert-repo-header: Status Header Sections. + (line 63) +* magit-insert-section: Creating Sections. (line 6) +* magit-insert-sequencer-sequence: Status Sections. (line 33) +* magit-insert-staged-changes: Status Sections. (line 63) +* magit-insert-stashes: Status Sections. (line 67) +* magit-insert-status-headers: Status Header Sections. + (line 12) +* magit-insert-submodules: Listing Submodules. (line 35) +* magit-insert-tags: References Sections. (line 25) +* magit-insert-tags-header: Status Header Sections. + (line 56) +* magit-insert-tracked-files: Status Sections. (line 96) +* magit-insert-unpulled-cherries: Status Sections. (line 126) +* magit-insert-unpulled-from-pushremote: Status Sections. (line 79) +* magit-insert-unpulled-from-upstream: Status Sections. (line 74) +* magit-insert-unpulled-or-recent-commits: Status Sections. (line 108) +* magit-insert-unpushed-cherries: Status Sections. (line 133) +* magit-insert-unpushed-to-pushremote: Status Sections. (line 89) +* magit-insert-unpushed-to-upstream: Status Sections. (line 84) +* magit-insert-unstaged-changes: Status Sections. (line 59) +* magit-insert-untracked-files: Status Sections. (line 50) +* magit-insert-upstream-branch-header: Status Header Sections. + (line 46) +* magit-insert-user-header: Status Header Sections. + (line 75) +* magit-list-repositories: Repository List. (line 6) +* magit-list-submodules: Listing Submodules. (line 13) +* magit-log-maybe-show-more-commits: Section Movement. (line 57) +* magit-log-maybe-update-blob-buffer: Section Movement. (line 71) +* magit-log-maybe-update-revision-buffer: Section Movement. (line 64) +* magit-maybe-set-dedicated: Switching Buffers. (line 97) +* magit-mode-display-buffer: Refreshing Buffers. (line 33) +* magit-mode-quit-window: Quitting Windows. (line 31) +* magit-mode-setup: Refreshing Buffers. (line 17) +* magit-push-implicitly: Pushing. (line 73) +* magit-push-to-remote: Pushing. (line 84) +* magit-region-sections: Section Selection. (line 10) +* magit-region-values: Section Selection. (line 37) +* magit-remote-config-popup: The Remote Config Popup. + (line 6) +* magit-repolist-column-ident: Repository List. (line 30) +* magit-repolist-column-path: Repository List. (line 35) +* magit-repolist-column-unpulled-from-pushremote: Repository List. + (line 49) +* magit-repolist-column-unpulled-from-upstream: Repository List. + (line 44) +* magit-repolist-column-unpushed-to-pushremote: Repository List. + (line 59) +* magit-repolist-column-unpushed-to-upstream: Repository List. + (line 54) +* magit-repolist-column-version: Repository List. (line 39) +* magit-restore-window-configuration: Quitting Windows. (line 20) +* magit-revert-buffers: Editing Commit Messages. + (line 178) +* magit-run-git: Calling Git for Effect. + (line 36) +* magit-run-git-async: Calling Git for Effect. + (line 80) +* magit-run-git-with-editor: Calling Git for Effect. + (line 93) +* magit-run-git-with-input: Calling Git for Effect. + (line 40) +* magit-run-git-with-logfile: Calling Git for Effect. + (line 56) +* magit-save-window-configuration: Switching Buffers. (line 86) +* magit-section-case: Matching Sections. (line 71) +* magit-section-hide: Section Visibility. (line 49) +* magit-section-hide-children: Section Visibility. (line 64) +* magit-section-ident: Matching Sections. (line 11) +* magit-section-match: Matching Sections. (line 21) +* magit-section-set-window-start: Section Movement. (line 50) +* magit-section-show: Section Visibility. (line 45) +* magit-section-show-children: Section Visibility. (line 58) +* magit-section-show-headings: Section Visibility. (line 53) +* magit-section-toggle-children: Section Visibility. (line 68) +* magit-section-value-if: Matching Sections. (line 61) +* magit-start-git: Calling Git for Effect. + (line 105) +* magit-start-process: Calling Git for Effect. + (line 124) +* magit-status-maybe-update-blob-buffer: Section Movement. (line 83) +* magit-status-maybe-update-revision-buffer: Section Movement. + (line 77) +* magit-tag-release: Tagging. (line 28) +* magit-wip-log: Wip Modes. (line 48) +* magit-wip-log-current: Wip Modes. (line 57) +* with-editor-usage-message: Editing Commit Messages. + (line 215) + + +File: magit.info, Node: Variable Index, Prev: Function Index, Up: Top + +Appendix F Variable Index +************************* + +[index] +* Menu: + +* auto-revert-buffer-list-filter: Automatic Reverting of File-Visiting Buffers. + (line 81) +* auto-revert-interval: Automatic Reverting of File-Visiting Buffers. + (line 76) +* auto-revert-stop-on-user-input: Automatic Reverting of File-Visiting Buffers. + (line 71) +* auto-revert-use-notify: Automatic Reverting of File-Visiting Buffers. + (line 49) +* auto-revert-verbose: Automatic Reverting of File-Visiting Buffers. + (line 103) +* branch.autoSetupMerge: The Branch Config Popup. + (line 94) +* branch.autoSetupRebase: The Branch Config Popup. + (line 111) +* branch.NAME.description: The Branch Config Popup. + (line 61) +* branch.NAME.merge: The Branch Config Popup. + (line 23) +* branch.NAME.pushRemote: The Branch Config Popup. + (line 47) +* branch.NAME.rebase: The Branch Config Popup. + (line 35) +* branch.NAME.remote: The Branch Config Popup. + (line 29) +* core.notesRef: Notes. (line 59) +* git-commit-fill-column: Editing Commit Messages. + (line 228) +* git-commit-finish-query-functions: Editing Commit Messages. + (line 233) +* git-commit-known-pseudo-headers: Editing Commit Messages. + (line 124) +* git-commit-major-mode: Editing Commit Messages. + (line 163) +* git-commit-setup-hook: Editing Commit Messages. + (line 174) +* git-commit-summary-max-length: Editing Commit Messages. + (line 222) +* git-rebase-auto-advance: Editing Rebase Sequences. + (line 94) +* git-rebase-confirm-cancel: Editing Rebase Sequences. + (line 102) +* git-rebase-show-instructions: Editing Rebase Sequences. + (line 98) +* global-auto-revert-mode: Automatic Reverting of File-Visiting Buffers. + (line 22) +* magit-auto-revert-immediately: Automatic Reverting of File-Visiting Buffers. + (line 32) +* magit-auto-revert-mode: Automatic Reverting of File-Visiting Buffers. + (line 17) +* magit-auto-revert-tracked-only: Automatic Reverting of File-Visiting Buffers. + (line 55) +* magit-bisect-show-graph: Bisecting. (line 55) +* magit-blame-disable-modes: Blaming. (line 150) +* magit-blame-echo-style: Blaming. (line 133) +* magit-blame-goto-chunk-hook: Blaming. (line 156) +* magit-blame-read-only: Blaming. (line 145) +* magit-blame-styles: Blaming. (line 128) +* magit-blame-time-format: Blaming. (line 140) +* magit-branch-adjust-remote-upstream-alist: The Branch Popup. + (line 303) +* magit-branch-popup-show-variables: The Branch Popup. (line 21) +* magit-branch-prefer-remote-upstream: The Branch Popup. (line 258) +* magit-branch-read-upstream-first: The Branch Popup. (line 252) +* magit-buffer-name-format: Naming Buffers. (line 27) +* magit-bury-buffer-function: Quitting Windows. (line 11) +* magit-cherry-margin: Cherries. (line 22) +* magit-clone-set-remote.pushDefault: Repository Setup. (line 23) +* magit-commit-ask-to-stage: Initiating a Commit. (line 74) +* magit-commit-extend-override-date: Initiating a Commit. (line 79) +* magit-commit-reword-override-date: Initiating a Commit. (line 83) +* magit-commit-squash-confirm: Initiating a Commit. (line 87) +* magit-completing-read-function: Support for Completion Frameworks. + (line 27) +* magit-diff-adjust-tab-width: Diff Options. (line 16) +* magit-diff-buffer-file-locked: Minor Mode for Buffers Visiting Files. + (line 52) +* magit-diff-hide-trailing-cr-characters: Diff Options. (line 67) +* magit-diff-highlight-hunk-region-functions: Diff Options. (line 71) +* magit-diff-highlight-indentation: Diff Options. (line 52) +* magit-diff-highlight-trailing: Diff Options. (line 47) +* magit-diff-paint-whitespace: Diff Options. (line 38) +* magit-diff-refine-hunk: Diff Options. (line 6) +* magit-diff-unmarked-lines-keep-foreground: Diff Options. (line 97) +* magit-diff-visit-previous-blob: Diff Buffer. (line 37) +* magit-display-buffer-function: Switching Buffers. (line 23) +* magit-display-buffer-noselect: Switching Buffers. (line 14) +* magit-dwim-selection: Completion and Confirmation. + (line 42) +* magit-ediff-dwim-show-on-hunks: Ediffing. (line 73) +* magit-ediff-quit-hook: Ediffing. (line 88) +* magit-ediff-show-stash-with-index: Ediffing. (line 81) +* magit-file-mode: Minor Mode for Buffers Visiting Files. + (line 11) +* magit-generate-buffer-name-function: Naming Buffers. (line 6) +* magit-git-debug: Viewing Git Output. (line 28) +* magit-git-debug <1>: Getting a Value from Git. + (line 64) +* magit-git-executable: Git Executable. (line 39) +* magit-git-global-arguments: Global Git Arguments. + (line 6) +* magit-keep-region-overlay: The Selection. (line 52) +* magit-list-refs-sortby: Additional Completion Options. + (line 6) +* magit-log-auto-more: Log Buffer. (line 67) +* magit-log-buffer-file-locked: Minor Mode for Buffers Visiting Files. + (line 75) +* magit-log-margin: Log Margin. (line 12) +* magit-log-section-args: Status Options. (line 36) +* magit-log-section-commit-count: Status Sections. (line 120) +* magit-log-select-margin: Select from Log. (line 30) +* magit-log-show-refname-after-summary: Log Buffer. (line 73) +* magit-log-trace-definition-function: Diff Buffer. (line 74) +* magit-module-sections-hook: Status Module Sections. + (line 20) +* magit-module-sections-nested: Status Module Sections. + (line 24) +* magit-no-confirm: Action Confirmation. (line 18) +* magit-pop-revision-stack-format: Editing Commit Messages. + (line 92) +* magit-post-display-buffer-hook: Switching Buffers. (line 92) +* magit-pre-display-buffer-hook: Switching Buffers. (line 81) +* magit-prefer-remote-upstream: The Branch Config Popup. + (line 139) +* magit-process-raise-error: Calling Git for Effect. + (line 151) +* magit-push-current-set-remote-if-missing: Pushing. (line 96) +* magit-reflog-margin: Reflog. (line 23) +* magit-refresh-args: Refreshing Buffers. (line 55) +* magit-refresh-buffer-hook: Automatic Refreshing of Magit Buffers. + (line 40) +* magit-refresh-function: Refreshing Buffers. (line 49) +* magit-refresh-status-buffer: Automatic Refreshing of Magit Buffers. + (line 46) +* magit-refs-filter-alist: References Buffer. (line 149) +* magit-refs-focus-column-width: References Buffer. (line 74) +* magit-refs-margin: References Buffer. (line 89) +* magit-refs-margin-for-tags: References Buffer. (line 115) +* magit-refs-pad-commit-counts: References Buffer. (line 41) +* magit-refs-primary-column-width: References Buffer. (line 61) +* magit-refs-sections-hook: References Sections. (line 13) +* magit-refs-show-commit-count: References Buffer. (line 29) +* magit-refs-show-remote-prefix: References Buffer. (line 54) +* magit-remote-add-set-remote.pushDefault: The Remote Popup. (line 77) +* magit-remote-popup-show-variables: The Remote Popup. (line 18) +* magit-repolist-columns: Repository List. (line 14) +* magit-repository-directories: Status Buffer. (line 30) +* magit-repository-directories-depth: Status Buffer. (line 40) +* magit-revision-insert-related-refs: Revision Buffer. (line 6) +* magit-revision-show-gravatars: Revision Buffer. (line 19) +* magit-revision-use-hash-sections: Revision Buffer. (line 36) +* magit-root-section: Matching Sections. (line 87) +* magit-save-repository-buffers: Automatic Saving of File-Visiting Buffers. + (line 13) +* magit-section-cache-visibility: Section Visibility. (line 95) +* magit-section-initial-visibility-alist: Section Visibility. (line 78) +* magit-section-movement-hook: Section Movement. (line 38) +* magit-section-set-visibility-hook: Section Visibility. (line 106) +* magit-section-show-child-count: Section Options. (line 9) +* magit-shell-command-verbose-prompt: Running Git Manually. + (line 46) +* magit-stashes-margin: Stashing. (line 103) +* magit-status-headers-hook: Status Header Sections. + (line 18) +* magit-status-margin: Status Options. (line 10) +* magit-status-refresh-hook: Status Options. (line 6) +* magit-status-sections-hook: Status Sections. (line 10) +* magit-submodule-list-columns: Listing Submodules. (line 21) +* magit-this-process: Calling Git for Effect. + (line 146) +* magit-uniquify-buffer-names: Naming Buffers. (line 74) +* magit-unstage-committed: Staging and Unstaging. + (line 56) +* magit-update-other-window-delay: Section Movement. (line 89) +* magit-use-sticky-arguments: Popup Buffers and Prefix Commands. + (line 36) +* magit-visit-ref-behavior: References Buffer. (line 177) +* magit-wip-after-apply-mode: Legacy Wip Modes. (line 19) +* magit-wip-after-apply-mode-lighter: Legacy Wip Modes. (line 59) +* magit-wip-after-save-local-mode-lighter: Legacy Wip Modes. (line 55) +* magit-wip-after-save-mode: Legacy Wip Modes. (line 13) +* magit-wip-before-change-mode: Legacy Wip Modes. (line 33) +* magit-wip-before-change-mode-lighter: Legacy Wip Modes. (line 63) +* magit-wip-initial-backup-mode: Legacy Wip Modes. (line 38) +* magit-wip-initial-backup-mode-lighter: Legacy Wip Modes. (line 67) +* magit-wip-merge-branch: Wip Graph. (line 6) +* magit-wip-mode: Wip Modes. (line 30) +* magit-wip-mode-lighter: Wip Modes. (line 104) +* magit-wip-namespace: Wip Modes. (line 96) +* notes.displayRef: Notes. (line 64) +* pull.rebase: The Branch Config Popup. + (line 70) +* remote.NAME.fetch: The Remote Config Popup. + (line 25) +* remote.NAME.push: The Remote Config Popup. + (line 36) +* remote.NAME.pushurl: The Remote Config Popup. + (line 30) +* remote.NAME.tagOpts: The Remote Config Popup. + (line 41) +* remote.NAME.url: The Remote Config Popup. + (line 20) +* remote.pushDefault: The Branch Config Popup. + (line 84) + diff --git a/elpa/magit-popup-20181003.921/dir b/elpa/magit-popup-20181003.921/dir new file mode 100644 index 00000000..ecec7cb7 --- /dev/null +++ b/elpa/magit-popup-20181003.921/dir @@ -0,0 +1,18 @@ +This is the file .../info/dir, which contains the +topmost node of the Info hierarchy, called (dir)Top. +The first time you invoke Info you start off looking at this node. + +File: dir, Node: Top This is the top of the INFO tree + + This (the Directory node) gives a menu of major topics. + Typing "q" exits, "H" lists all Info commands, "d" returns here, + "h" gives a primer for first-timers, + "mEmacs" visits the Emacs manual, etc. + + In Emacs, you can click mouse button 2 on a menu item or cross reference + to select it. + +* Menu: + +Emacs +* Magit-Popup: (magit-popup). Infix arguments with feedback. diff --git a/elpa/magit-popup-20181003.921/magit-popup-autoloads.el b/elpa/magit-popup-20181003.921/magit-popup-autoloads.el new file mode 100644 index 00000000..e6e027b2 --- /dev/null +++ b/elpa/magit-popup-20181003.921/magit-popup-autoloads.el @@ -0,0 +1,26 @@ +;;; magit-popup-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "magit-popup" "magit-popup.el" (0 0 0 0)) +;;; Generated autoloads from magit-popup.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "magit-popup" '("magit-"))) + +;;;*** + +;;;### (autoloads nil nil ("magit-popup-pkg.el") (0 0 0 0)) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; magit-popup-autoloads.el ends here diff --git a/elpa/magit-popup-20181003.921/magit-popup-pkg.el b/elpa/magit-popup-20181003.921/magit-popup-pkg.el new file mode 100644 index 00000000..dc89d651 --- /dev/null +++ b/elpa/magit-popup-20181003.921/magit-popup-pkg.el @@ -0,0 +1,14 @@ +(define-package "magit-popup" "20181003.921" "Define prefix-infix-suffix command combos" + '((emacs "24.4") + (async "1.9.2") + (dash "2.13.0")) + :keywords + '("bindings") + :authors + '(("Jonas Bernoulli" . "jonas@bernoul.li")) + :maintainer + '("Jonas Bernoulli" . "jonas@bernoul.li") + :url "https://github.com/magit/magit-popup") +;; Local Variables: +;; no-byte-compile: t +;; End: diff --git a/elpa/magit-popup-20181003.921/magit-popup.el b/elpa/magit-popup-20181003.921/magit-popup.el new file mode 100644 index 00000000..c5bed88e --- /dev/null +++ b/elpa/magit-popup-20181003.921/magit-popup.el @@ -0,0 +1,1372 @@ +;;; magit-popup.el --- Define prefix-infix-suffix command combos -*- lexical-binding: t -*- + +;; Copyright (C) 2010-2018 The Magit Project Contributors +;; +;; You should have received a copy of the AUTHORS.md file which +;; lists all contributors. If not, see http://magit.vc/authors. + +;; This library was inspired by and replaces library `magit-key-mode', +;; which was written by Phil Jackson and is +;; distributed under the GNU General Public License version 3 or later. + +;; Author: Jonas Bernoulli +;; Maintainer: Jonas Bernoulli + +;; Package-Requires: ((emacs "24.4") (async "1.9.2") (dash "2.13.0")) +;; Keywords: bindings +;; Homepage: https://github.com/magit/magit-popup + +;; Magit-Popup 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. +;; +;; Magit-Popup 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 Magit-Popup. If not, see http://www.gnu.org/licenses. + +;;; Commentary: + +;; This package implements a generic interface for toggling switches +;; and setting options and then invoking an Emacs command which does +;; something with these arguments. The prototypical use is for the +;; command to call an external process, passing on the arguments as +;; command line arguments. But this is only one of many possible +;; uses (though the one this library is optimized for). + +;; With the Emacs concept of "prefix arguments" in mind this could be +;; described as "infix arguments with feedback in a buffer". + +;; Commands that set the prefix argument for the subsequent command do +;; not limit what that next command could be. But entering a command +;; console popup does limit the selection to the commands defined for +;; that popup, and so we use the term "infix" instead of "prefix". + +;;; Code: + +(require 'button) +(require 'cl-lib) +(require 'dash) +(require 'format-spec) +(eval-when-compile (require 'subr-x)) + +(and (require 'async-bytecomp nil t) + (cl-intersection '(all magit) + (bound-and-true-p async-bytecomp-allowed-packages)) + (fboundp 'async-bytecomp-package-mode) + (async-bytecomp-package-mode 1)) + +(declare-function info 'info) +(declare-function Man-find-section 'man) +(declare-function Man-next-section 'man) + +;; For branch actions. +(declare-function magit-branch-set-face 'magit-git) + +;;; Settings +;;;; Custom Groups + +(defgroup magit-popup nil + "Infix arguments with a popup as feedback." + :link '(info-link "(magit-popup)") + :group 'bindings) + +(defgroup magit-popup-faces nil + "Faces used by Magit-Popup." + :group 'magit-popup) + +;;;; Custom Options + +(defcustom magit-popup-display-buffer-action '((display-buffer-below-selected)) + "The action used to display a popup buffer. + +Popup buffers are displayed using `display-buffer' with the value +of this option as ACTION argument. You can also set this to nil +and instead add an entry to `display-buffer-alist'." + :package-version '(magit-popup . "2.4.0") + :group 'magit-popup + :type 'sexp) + +(defcustom magit-popup-manpage-package + (if (memq system-type '(windows-nt ms-dos)) 'woman 'man) + "The package used to display manpages. +One of `man' or `woman'." + :group 'magit-popup + :type '(choice (const man) (const woman))) + +(defcustom magit-popup-show-help-echo t + "Show usage information in the echo area." + :group 'magit-popup + :type 'boolean) + +(defcustom magit-popup-show-common-commands nil + "Whether to initially show section with commands common to all popups. +This section can also be toggled temporarily using \ +\\\\[magit-popup-toggle-show-common-commands]." + :package-version '(magit-popup . "2.9.0") + :group 'magit-popup + :type 'boolean) + +(defcustom magit-popup-use-prefix-argument 'default + "Control how prefix arguments affect infix argument popups. + +This option controls the effect that the use of a prefix argument +before entering a popup has. + +`default' With a prefix argument directly invoke the popup's + default action (an Emacs command), instead of bringing + up the popup. + +`popup' With a prefix argument bring up the popup, otherwise + directly invoke the popup's default action. + +`nil' Ignore prefix arguments." + :group 'magit-popup + :type '(choice + (const :tag "Call default action instead of showing popup" default) + (const :tag "Show popup instead of calling default action" popup) + (const :tag "Ignore prefix argument" nil))) + +;;;; Custom Faces + +(defface magit-popup-heading + '((t :inherit font-lock-keyword-face)) + "Face for key mode header lines." + :group 'magit-popup-faces) + +(defface magit-popup-key + '((t :inherit font-lock-builtin-face)) + "Face for key mode buttons." + :group 'magit-popup-faces) + +(defface magit-popup-argument + '((t :inherit font-lock-warning-face)) + "Face used to display enabled arguments in popups." + :group 'magit-popup-faces) + +(defface magit-popup-disabled-argument + '((t :inherit shadow)) + "Face used to display disabled arguments in popups." + :group 'magit-popup-faces) + +(defface magit-popup-option-value + '((t :inherit font-lock-string-face)) + "Face used to display option values in popups." + :group 'magit-popup-faces) + +;;;; Keymap + +(defvar magit-popup-mode-map + (let ((map (make-sparse-keymap))) + (define-key map [remap self-insert-command] 'magit-invoke-popup-action) + (define-key map (kbd "- ") 'magit-invoke-popup-switch) + (define-key map (kbd "= ") 'magit-invoke-popup-option) + (define-key map (kbd "C-g") 'magit-popup-quit) + (define-key map (kbd "?") 'magit-popup-help) + (define-key map (kbd "C-h k") 'magit-popup-help) + (define-key map (kbd "C-h i") 'magit-popup-info) + (define-key map (kbd "C-t") 'magit-popup-toggle-show-common-commands) + (define-key map (kbd "C-c C-c") 'magit-popup-set-default-arguments) + (define-key map (kbd "C-x C-s") 'magit-popup-save-default-arguments) + (cond ((featurep 'jkl) + (define-key map (kbd "C-p") 'universal-argument) + (define-key map [return] 'push-button) + (define-key map (kbd "C-i") 'backward-button) + (define-key map (kbd "C-k") 'forward-button)) + (t + (define-key map (kbd "C-m") 'push-button) + (define-key map (kbd "DEL") 'backward-button) + (define-key map (kbd "C-p") 'backward-button) + (define-key map (kbd "C-i") 'forward-button) + (define-key map (kbd "C-n") 'forward-button))) + map) + "Keymap for `magit-popup-mode'. + +\\\ +This keymap contains bindings common to all popups. A section +listing these commands can be shown or hidden using \ +\\[magit-popup-toggle-show-common-commands]. + +The prefix used to toggle any switch can be changed by binding +another key to `magit-invoke-popup-switch'. Likewise binding +another key to `magit-invoke-popup-option' changes the prefixed +used to set any option. The two prefixes have to be different. +If you change these bindings, you should also change the `prefix' +property of the button types `magit-popup-switch-button' and +`magit-popup-option-button'. + +If you change any other binding, then you might have to also edit +`magit-popup-common-commands' for things to align correctly in +the section listing these commands. + +Never bind an alphabetic character in this keymap or you might +make it impossible to invoke certain actions.") + +(defvar magit-popup-common-commands + '(("Set defaults" magit-popup-set-default-arguments) + ("View popup manual" magit-popup-info) + ("Toggle this section" magit-popup-toggle-show-common-commands) + ("Save defaults" magit-popup-save-default-arguments) + (" Popup help prefix" magit-popup-help) + ("Abort" magit-popup-quit))) + +;;;; Buttons + +(define-button-type 'magit-popup-button + 'face nil + 'action (lambda (button) + (funcall (button-get button 'function) + (button-get button 'event)))) + +(define-button-type 'magit-popup-switch-button + 'supertype 'magit-popup-button + 'function 'magit-invoke-popup-switch + 'property :switches + 'heading "Switches\n" + 'formatter 'magit-popup-format-argument-button + 'format " %k %d (%a)" + 'prefix ?- + 'maxcols 1) + +(define-button-type 'magit-popup-option-button + 'supertype 'magit-popup-button + 'function 'magit-invoke-popup-option + 'property :options + 'heading "Options\n" + 'formatter 'magit-popup-format-argument-button + 'format " %k %d (%a%v)" + 'prefix ?= + 'maxcols 1) + +(define-button-type 'magit-popup-variable-button + 'supertype 'magit-popup-button + 'function 'magit-invoke-popup-action + 'property :variables + 'heading "Variables\n" + 'formatter 'magit-popup-format-variable-button + 'format " %k %d" + 'prefix nil + 'maxcols 1) + +(define-button-type 'magit-popup-action-button + 'supertype 'magit-popup-button + 'function 'magit-invoke-popup-action + 'property :actions + 'heading "Actions\n" + 'formatter 'magit-popup-format-action-button + 'format " %k %d" + 'prefix nil + 'maxcols :max-action-columns) + +(define-button-type 'magit-popup-command-button + 'supertype 'magit-popup-action-button + 'formatter 'magit-popup-format-command-button + 'action (lambda (button) + (let ((command (button-get button 'function))) + (unless (eq command 'push-button) + (call-interactively command))))) + +(define-button-type 'magit-popup-internal-command-button + 'supertype 'magit-popup-command-button + 'heading "Common Commands\n" + 'maxcols 3) + +;;; Events + +(defvar-local magit-this-popup nil + "The popup which is currently active. +This is intended for internal use only. +Don't confuse this with `magit-current-popup'.") + +(defvar-local magit-this-popup-events nil + "The events known to the active popup. +This is intended for internal use only. +Don't confuse this with `magit-current-popup-args'.") + +(defvar-local magit-previous-popup nil) + +(defvar-local magit-pre-popup-buffer nil + "The buffer that was current before invoking the active popup.") + +(defun magit-popup-get (prop) + "While a popup is active, get the value of PROP." + (if (memq prop '(:switches :options :variables :actions)) + (plist-get magit-this-popup-events prop) + (plist-get (symbol-value magit-this-popup) prop))) + +(defun magit-popup-put (prop val) + "While a popup is active, set the value of PROP to VAL." + (if (memq prop '(:switches :options :variables :actions)) + (setq magit-this-popup-events + (plist-put magit-this-popup-events prop val)) + (error "Property %s isn't supported" prop))) + +(defvar magit-current-popup nil + "The popup from which this editing command was invoked. + +Use this inside the `interactive' form of a popup aware command +to determine whether it was invoked from a popup and if so from +which popup. If the current command was invoked without the use +of a popup, then this is nil.") + +(defvar magit-current-popup-action nil + "The popup action now being executed.") + +(defvar magit-current-popup-args nil + "The value of the popup arguments for this editing command. + +If the current command was invoked from a popup, then this is +a list of strings of all the set switches and options. This +includes arguments which are set by default not only those +explicitly set during this invocation. + +When the value is nil, then that can be because no argument is +set, or because the current command wasn't invoked from a popup; +consult `magit-current-popup' to tell the difference. + +Generally it is better to use `NAME-arguments', which is created +by `magit-define-popup', instead of this variable or the function +by the same name, because `NAME-argument' uses the default value +for the arguments when the editing command is invoked directly +instead of from a popup. When the command is bound in several +popups that might not be feasible though.") + +(defun magit-current-popup-args (&rest filter) + "Return the value of the popup arguments for this editing command. + +The value is the same as that of the variable by the same name +\(which see), except that FILTER is applied. FILTER is a list +of regexps; only arguments that match one of them are returned. +The first element of FILTER may also be `:not' in which case +only arguments that don't match any of the regexps are returned, +or `:only' which doesn't change the behaviour." + (let ((-compare-fn (lambda (a b) (magit-popup-arg-match b a)))) + (-filter (if (eq (car filter) :not) + (lambda (arg) (not (-contains-p (cdr filter) arg))) + (when (eq (car filter) :only) + (pop filter)) + (lambda (arg) (-contains-p filter arg))) + magit-current-popup-args))) + +(defvar magit-current-pre-popup-buffer nil + "The buffer that was current before invoking the active popup. +This is bound when invoking an action or variable.") + +(defmacro magit-with-pre-popup-buffer (&rest body) + "Execute the forms in BODY in the buffer that current before the popup. +If `magit-current-pre-popup-buffer' is non-nil use that, else if +`magit-pre-popup-buffer' is non-nil use that, otherwise (when no +popup is involved) execute the forms in the current buffer." + (declare (indent 0)) + `(--if-let (or magit-current-pre-popup-buffer magit-pre-popup-buffer) + (with-current-buffer it ,@body) + ,@body)) + +(defun magit-popup-arg-match (pattern string) + (if (or (string-match-p "=$" pattern) + (string-match-p "^-[A-Z]$" pattern)) + (string-match (format "^%s\\(.*\\)$" pattern) string) + (string-equal string pattern))) + +(cl-defstruct magit-popup-event key dsc arg fun use val) + +(defun magit-popup-event-keydsc (ev) + (let ((key (magit-popup-event-key ev))) + (key-description (if (vectorp key) key (vector key))))) + +(defun magit-popup-lookup (event type) + (--first (equal (magit-popup-event-key it) event) + (-filter 'magit-popup-event-p (magit-popup-get type)))) + +(defun magit-popup-get-args () + (--mapcat (when (and (magit-popup-event-p it) + (magit-popup-event-use it)) + (list (format "%s%s" + (magit-popup-event-arg it) + (or (magit-popup-event-val it) "")))) + (append (magit-popup-get :switches) + (magit-popup-get :options)))) + +(defmacro magit-popup-convert-events (def form) + (declare (indent 1) (debug (form form))) + `(--map (if (or (null it) (stringp it) (functionp it)) it ,form) ,def)) + +(defun magit-popup-convert-switches (val def) + (magit-popup-convert-events def + (let ((a (nth 2 it))) + (make-magit-popup-event + :key (car it) :dsc (cadr it) :arg a + :use (and (member a val) t) + ;; For arguments implemented in lisp, this function's + ;; doc-string is used by `magit-popup-help'. That is + ;; the only thing it is used for. + :fun (and (string-prefix-p "\+\+" a) (nth 3 it)))))) + +(defun magit-popup-convert-options (val def) + (magit-popup-convert-events def + (let* ((a (nth 2 it)) + (r (format "^%s\\(.*\\)" a)) + (v (--first (string-match r it) val))) + (make-magit-popup-event + :key (car it) :dsc (cadr it) :arg a + :use (and v t) :val (and v (match-string 1 v)) + :fun (or (nth 3 it) 'read-from-minibuffer))))) + +(defun magit-popup-convert-variables (_val def) + (magit-popup-convert-events def + (make-magit-popup-event + :key (car it) :dsc (cadr it) :fun (nth 2 it) :arg (nth 3 it)))) + +(defun magit-popup-convert-actions (_val def) + (magit-popup-convert-events def + (make-magit-popup-event + :key (car it) :dsc (cadr it) :fun (nth 2 it)))) + +;;; Define + +(defmacro magit-define-popup (name doc &rest args) + "Define a popup command named NAME. + +NAME should begin with the package prefix and by convention end +with `-popup'. That name is used for the actual command as well +as for a variable used internally. DOC is used as the doc-string +of that command. + +Also define an option and a function named `SHORTNAME-arguments', +where SHORTNAME is NAME with the trailing `-popup' removed. The +name of this option and this function can be overwritten using +the optional argument OPTION, but that is rarely advisable. As a +special case if OPTION is specified but nil, do not define this +option and this function at all. + +The option `SHORTNAME-arguments' holds the default value for the +popup arguments. It can be customized from within the popup or +using the Custom interface. + +The function `SHORTNAME-arguments' is a wrapper around the +variable `magit-current-popup-args', both of which are intended +to be used inside the `interactive' form of commands commonly +invoked from the popup `NAME'. When such a command is invoked +from that popup, then the function `SHORTNAME-arguments' returns +the value of the variable `magit-current-popup-args'; however +when the command is invoked directly, then it returns the default +value of the variable `SHORTNAME-arguments'. + +Optional argument GROUP specifies the Custom group into which the +option is placed. If omitted, then the option is placed into some +group the same way it is done when directly using `defcustom' and +omitting the group, except when NAME begins with \"magit-\", in +which case the group `magit-git-arguments' is used. + +Optional argument MODE is deprecated, instead use the keyword +arguments `:setup-function' and/or `:refresh-function'. If MODE +is non-nil, then it specifies the mode used by the popup buffer, +instead of the default, which is `magit-popup-mode'. + +The remaining arguments should have the form + + [KEYWORD VALUE]... + +The following keywords are meaningful (and by convention are +usually specified in that order): + +`:actions' + The actions which can be invoked from the popup. VALUE is a + list whose members have the form (KEY DESC COMMAND), see + `magit-define-popup-action' for details. + + Actions are regular Emacs commands, which usually have an + `interactive' form setup to consume the values of the popup + `:switches' and `:options' when invoked from the corresponding + popup, else when invoked as the default action or directly + without using the popup, the default value of the variable + `SHORTNAME-arguments'. This is usually done by calling the + function `SHORTNAME-arguments'. + + Members of VALUE may also be strings and functions, assuming + the first member is a string or function. In that case the + members are split into sections and these special elements are + used as headings. If such an element is a function then it is + called with no arguments and must return either a string, which + is used as the heading, or nil, in which case the section is + not inserted. + + Members of VALUE may also be nil. This should only be used + together with `:max-action-columns' and allows having gaps in + the action grid, which can help arranging actions sensibly. + +`:default-action' + The default action of the popup which is used directly instead + of displaying the popup buffer, when the popup is invoked with + a prefix argument. Also see `magit-popup-use-prefix-argument' + and `:use-prefix', which can be used to inverse the meaning of + the prefix argument. + +`:use-prefix' + Controls when to display the popup buffer and when to invoke + the default action (if any) directly. This overrides the + global default set using `magit-popup-use-prefix-argument'. + The value, if specified, should be one of `default' or `popup', + or a function that is called with no arguments and returns one + of these symbols. + +`:max-action-columns' + The maximum number of actions to display on a single line, a + number or a function that returns a number and takes the name + of the section currently being inserted as argument. If there + isn't enough room to display as many columns as specified here, + then fewer are used. + +`:switches' + The popup arguments which can be toggled on and off. VALUE + is a list whose members have the form (KEY DESC SWITCH), see + `magit-define-popup-switch' for details. + + Members of VALUE may also be strings and functions, assuming + the first member is a string or function. In that case the + members are split into sections and these special elements are + used as headings. If such an element is a function then it is + called with no arguments and must return either a string, which + is used as the heading, or nil, in which case the section is + not inserted. + +`:options' + The popup arguments which take a value, as in \"--opt=OPTVAL\". + VALUE is a list whose members have the form (KEY DESC OPTION + READER), see `magit-define-popup-option' for details. + + Members of VALUE may also be strings and functions, assuming + the first member is a string or function. In that case the + members are split into sections and these special elements are + used as headings. If such an element is a function then it is + called with no arguments and must return either a string, which + is used as the heading, or nil, in which case the section is + not inserted. + +`:default-arguments' + The default arguments, a list of switches (which are then + enabled by default) and options with there default values, as + in \"--OPT=OPTVAL\". + +`:variables' + + Variables which can be set from the popup. VALUE is a list + whose members have the form (KEY DESC COMMAND FORMATTER), see + `magit-define-popup-variable' for details. + + Members of VALUE may also be strings and functions, assuming + the first member is a string or function. In that case the + members are split into sections and these special elements are + used as headings. If such an element is a function then it is + called with no arguments and must return either a string, which + is used as the heading, or nil, in which case the section is + not inserted. + + Members of VALUE may also be actions as described above for + `:actions'. + + VALUE may also be a function that returns a list as describe + above. + +`:sequence-predicate' + When this function returns non-nil, then the popup uses + `:sequence-actions' instead of `:actions', and does not show + the `:switches' and `:options'. + +`:sequence-actions' + The actions which can be invoked from the popup, when + `:sequence-predicate' returns non-nil. + +`:setup-function' + When this function is specified, then it is used instead of + `magit-popup-default-setup'. + +`:refresh-function' + When this function is specified, then it is used instead of + calling `magit-popup-insert-section' three times with symbols + `magit-popup-switch-button', `magit-popup-option-button', and + finally `magit-popup-action-button' as argument. + +`:man-page' + The name of the manpage to be displayed when the user requests + help for a switch or argument. + +\(fn NAME DOC [GROUP [MODE [OPTION]]] :KEYWORD VALUE...)" + (declare (indent defun) (doc-string 2)) + (let* ((str (symbol-name name)) + (grp (if (keywordp (car args)) + (and (string-prefix-p "magit-" str) ''magit-git-arguments) + (pop args))) + (mode (and (not (keywordp (car args))) (pop args))) + (opt (if (keywordp (car args)) + (intern (concat (if (string-suffix-p "-popup" str) + (substring str 0 -6) + str) + "-arguments")) + (eval (pop args))))) + `(progn + (defun ,name (&optional arg) ,doc + (interactive "P") + (magit-invoke-popup ',name ,mode arg)) + (defvar ,name + (list :variable ',opt ,@args)) + (magit-define-popup-keys-deferred ',name) + ,@(when opt + `((defcustom ,opt (plist-get ,name :default-arguments) + "" + ,@(and grp (list :group grp)) + :type '(repeat (string :tag "Argument"))) + (defun ,opt () + (if (eq magit-current-popup ',name) + magit-current-popup-args + ,opt)) + (put ',opt 'definition-name ',name)))))) + +(defun magit-define-popup-switch (popup key desc switch + &optional enable at prepend) + "In POPUP, define KEY as SWITCH. + +POPUP is a popup command defined using `magit-define-popup'. +SWITCH is a string representing an argument that takes no value. +KEY is a character representing the second event in the sequence +of keystrokes used to toggle the argument. (The first event, the +prefix, is shared among all switches, defaults to -, and can be +changed in `magit-popup-mode-keymap'). + +DESC is a string describing the purpose of the argument, it is +displayed in the popup. + +If optional ENABLE is non-nil, then the switch is on by default. + +SWITCH is inserted after all other switches already defined for +POPUP, unless optional PREPEND is non-nil, in which case it is +placed first. If optional AT is non-nil, then it should be the +KEY of another switch already defined for POPUP, the argument +is then placed before or after AT, depending on PREPEND." + (declare (indent defun)) + (magit-define-popup-key popup :switches key + (list desc switch enable) at prepend)) + +(defun magit-define-popup-option (popup key desc option + &optional reader value at prepend) + "In POPUP, define KEY as OPTION. + +POPUP is a popup command defined using `magit-define-popup'. +OPTION is a string representing an argument that takes a value. +KEY is a character representing the second event in the sequence +of keystrokes used to set the argument's value. (The first +event, the prefix, is shared among all options, defaults to =, +and can be changed in `magit-popup-mode-keymap'). + +DESC is a string describing the purpose of the argument, it is +displayed in the popup. + +If optional VALUE is non-nil then the option is on by default, +and VALUE is its default value. + +READER is used to read a value from the user when the option is +invoked and does not currently have a value. (When the option +has a value, then invoking the option causes it to be unset.) +This function must take two arguments but may choose to ignore +them. The first argument is the name of the option (with \": \" +appended, unless it ends with \"=\") and can be used as the +prompt. The second argument is nil or the value that was in +effect before the option was unset, which may be suitable as +initial completion input. If no reader is specified, then +`read-from-minibuffer' is used. + +OPTION is inserted after all other options already defined for +POPUP, unless optional PREPEND is non-nil, in which case it is +placed first. If optional AT is non-nil, then it should be the +KEY of another option already defined for POPUP, the argument +is then placed before or after AT, depending on PREPEND." + (declare (indent defun)) + (magit-define-popup-key popup :options key + (list desc option reader value) at prepend)) + +(defun magit-define-popup-variable (popup key desc command formatter + &optional at prepend) + "In POPUP, define KEY as COMMAND. + +POPUP is a popup command defined using `magit-define-popup'. +COMMAND is a command which calls `magit-popup-set-variable'. +FORMATTER is a function which calls `magit-popup-format-variable'. +These two functions have to be called with the same arguments. + +KEY is a character representing the event used interactively call +the COMMAND. + +DESC is the variable or a representation thereof. It's not +actually used for anything. + +COMMAND is inserted after all other commands already defined for +POPUP, unless optional PREPEND is non-nil, in which case it is +placed first. If optional AT is non-nil, then it should be the +KEY of another command already defined for POPUP, the command +is then placed before or after AT, depending on PREPEND." + (declare (indent defun)) + (magit-define-popup-key popup :variables key + (list desc command formatter) at prepend)) + +(defun magit-define-popup-action (popup key desc command + &optional at prepend) + "In POPUP, define KEY as COMMAND. + +POPUP is a popup command defined using `magit-define-popup'. +COMMAND can be any command but should usually consume the popup +arguments in its `interactive' form. +KEY is a character representing the event used invoke the action, +i.e. to interactively call the COMMAND. + +DESC is a string describing the purpose of the action, it is +displayed in the popup. + +COMMAND is inserted after all other commands already defined for +POPUP, unless optional PREPEND is non-nil, in which case it is +placed first. If optional AT is non-nil, then it should be the +KEY of another command already defined for POPUP, the command +is then placed before or after AT, depending on PREPEND." + (declare (indent defun)) + (magit-define-popup-key popup :actions key + (list desc command) at prepend)) + +(defun magit-define-popup-sequence-action + (popup key desc command &optional at prepend) + "Like `magit-define-popup-action' but for `:sequence-action'." + (declare (indent defun)) + (magit-define-popup-key popup :sequence-actions key + (list desc command) at prepend)) + +(defconst magit-popup-type-plural-alist + '((:switch . :switches) + (:option . :options) + (:variable . :variables) + (:action . :actions) + (:sequence-action . :sequence-actions))) + +(defun magit-popup-pluralize-type (type) + (or (cdr (assq type magit-popup-type-plural-alist)) + type)) + +(defun magit-define-popup-key + (popup type key def &optional at prepend) + "In POPUP, define KEY as an action, switch, or option. +It's better to use one of the specialized functions + `magit-define-popup-action', + `magit-define-popup-sequence-action', + `magit-define-popup-switch', + `magit-define-popup-option', or + `magit-define-popup-variable'." + (declare (indent defun)) + (setq type (magit-popup-pluralize-type type)) + (if (memq type '(:switches :options :variables :actions :sequence-actions)) + (if (boundp popup) + (let* ((plist (symbol-value popup)) + (value (plist-get plist type)) + (elt (assoc key value))) + (if elt + (setcdr elt def) + (setq elt (cons key def))) + (if at + (when (setq at (cl-member at value :key 'car-safe :test 'equal)) + (setq value (cl-delete key value :key 'car-safe :test 'equal)) + (if prepend + (progn (push (car at) (cdr at)) + (setcar at elt)) + (push elt (cdr at)))) + (setq value (cl-delete key value :key 'car-safe :test 'equal))) + (unless (assoc key value) + (setq value (if prepend + (cons elt value) + (append value (list elt))))) + (set popup (plist-put plist type value))) + (push (list type key def at prepend) + (get popup 'magit-popup-deferred))) + (error "Unknown popup event type: %s" type))) + +(defun magit-define-popup-keys-deferred (popup) + (dolist (args (get popup 'magit-popup-deferred)) + (condition-case err + (apply #'magit-define-popup-key popup args) + ((debug error) + (display-warning 'magit (error-message-string err) :error)))) + (put popup 'magit-popup-deferred nil)) + +(defun magit-change-popup-key (popup type from to) + "In POPUP, bind TO to what FROM was bound to. +TYPE is one of `:action', `:sequence-action', `:switch', or +`:option'. Bind TO and unbind FROM, both are characters." + (--if-let (assoc from (plist-get (symbol-value popup) + (magit-popup-pluralize-type type))) + (setcar it to) + (message "magit-change-popup-key: FROM key %c is unbound" from))) + +(defun magit-remove-popup-key (popup type key) + "In POPUP, remove KEY's binding of TYPE. +POPUP is a popup command defined using `magit-define-popup'. +TYPE is one of `:action', `:sequence-action', `:switch', or +`:option'. KEY is the character which is to be unbound." + (setq type (magit-popup-pluralize-type type)) + (let* ((plist (symbol-value popup)) + (alist (plist-get plist type)) + (value (assoc key alist))) + (set popup (plist-put plist type (delete value alist))))) + +;;; Invoke + +(defvar-local magit-popup-previous-winconf nil) + +(defun magit-invoke-popup (popup mode arg) + (let* ((def (symbol-value popup)) + (val (symbol-value (plist-get def :variable))) + (default (plist-get def :default-action)) + (local (plist-get def :use-prefix)) + (local (if (functionp local) + (funcall local) + local)) + (use-prefix (or local magit-popup-use-prefix-argument))) + (cond + ((or (and (eq use-prefix 'default) arg) + (and (eq use-prefix 'popup) (not arg))) + (if default + (let ((magit-current-popup (list popup 'default)) + (magit-current-popup-args + (let ((magit-this-popup popup) + (magit-this-popup-events nil)) + (magit-popup-default-setup val def) + (magit-popup-get-args)))) + (when (and arg (listp arg)) + (setq current-prefix-arg (and (not (= (car arg) 4)) + (list (/ (car arg) 4))))) + (call-interactively default)) + (message "%s has no default action; showing popup instead." popup) + (magit-popup-mode-setup popup mode))) + ((memq use-prefix '(default popup nil)) + (magit-popup-mode-setup popup mode) + (when magit-popup-show-help-echo + (message + (format + "[%s] show common commands, [%s] describe events, [%s] show manual" + (propertize "C-t" 'face 'magit-popup-key) + (propertize "?" 'face 'magit-popup-key) + (propertize "C-h i" 'face 'magit-popup-key))))) + (local + (error "Invalid :use-prefix popup property value: %s" use-prefix)) + (t + (error "Invalid magit-popup-use-prefix-argument value: %s" use-prefix))))) + +(defun magit-invoke-popup-switch (event) + (interactive (list last-command-event)) + (--if-let (magit-popup-lookup event :switches) + (progn + (setf (magit-popup-event-use it) + (not (magit-popup-event-use it))) + (magit-refresh-popup-buffer)) + (user-error "%c isn't bound to any switch" event))) + +(defun magit-invoke-popup-option (event) + (interactive (list last-command-event)) + (--if-let (magit-popup-lookup event :options) + (progn + (if (magit-popup-event-use it) + (setf (magit-popup-event-use it) nil) + (let* ((arg (magit-popup-event-arg it)) + (val (funcall + (magit-popup-event-fun it) + (concat arg (unless (string-match-p "=$" arg) ": ")) + (magit-popup-event-val it)))) + (setf (magit-popup-event-use it) t) + (setf (magit-popup-event-val it) val))) + (magit-refresh-popup-buffer)) + (user-error "%c isn't bound to any option" event))) + +(defun magit-invoke-popup-action (event) + (interactive (list last-command-event)) + (let ((action (magit-popup-lookup event :actions)) + (variable (magit-popup-lookup event :variables))) + (when (and variable (not (magit-popup-event-arg variable))) + (setq action variable) + (setq variable nil)) + (cond ((or action variable) + (let* ((magit-current-popup magit-this-popup) + (magit-current-popup-args (magit-popup-get-args)) + (magit-current-pre-popup-buffer magit-pre-popup-buffer) + (command (magit-popup-event-fun (or action variable))) + (magit-current-popup-action command)) + (when action + (magit-popup-quit)) + (setq this-command command) + (call-interactively command) + (unless action + (magit-refresh-popup-buffer)))) + ((eq event ?q) + (magit-popup-quit) + (when magit-previous-popup + (magit-popup-mode-setup magit-previous-popup nil))) + (t + (user-error "%c isn't bound to any action" event))))) + +(defun magit-popup-quit () + "Quit the current popup command without invoking an action." + (interactive) + (let ((winconf magit-popup-previous-winconf)) + (if (derived-mode-p 'magit-popup-mode) + (kill-buffer) + (magit-popup-help-mode -1) + (kill-local-variable 'magit-popup-previous-winconf)) + (when winconf + (set-window-configuration winconf)))) + +(defun magit-popup-read-number (prompt &optional default) + "Like `read-number' but DEFAULT may be a numeric string." + (read-number prompt (if (stringp default) + (string-to-number default) + default))) + +;;; Save + +(defun magit-popup-set-default-arguments (arg) + "Set default value for the arguments for the current popup. +Then close the popup without invoking an action; unless a prefix +argument is used in which case the popup remains open. + +For a popup named `NAME-popup' that usually means setting the +value of the custom option `NAME-arguments'." + (interactive "P") + (-if-let (var (magit-popup-get :variable)) + (progn (customize-set-variable var (magit-popup-get-args)) + (unless arg (magit-popup-quit))) + (user-error "Nothing to set"))) + +(defun magit-popup-save-default-arguments (arg) + "Save default value for the arguments for the current popup. +Then close the popup without invoking an action; unless a prefix +argument is used in which case the popup remains open. + +For a popup named `NAME-popup' that usually means saving the +value of the custom option `NAME-arguments'." + (interactive "P") + (-if-let (var (magit-popup-get :variable)) + (progn (customize-save-variable var (magit-popup-get-args)) + (unless arg (magit-popup-quit))) + (user-error "Nothing to save"))) + +;;; Help + +(defun magit-popup-toggle-show-common-commands () + "Show or hide an additional section with common commands. +The commands listed in this section are common to all popups +and are defined in `magit-popup-mode-map' (which see)." + (interactive) + (setq magit-popup-show-common-commands + (not magit-popup-show-common-commands)) + (magit-refresh-popup-buffer) + (fit-window-to-buffer)) + +(defun magit-popup-help () + "Show help for the argument or action at point." + (interactive) + (let* ((man (magit-popup-get :man-page)) + (key (read-key-sequence + (concat "Describe key" (and man " (? for manpage)") ": "))) + (int (aref key (1- (length key)))) + (def (or (lookup-key (current-local-map) key t) + (lookup-key (current-global-map) key)))) + (pcase def + (`magit-invoke-popup-switch + (--if-let (magit-popup-lookup int :switches) + (if (and (string-prefix-p "++" (magit-popup-event-arg it)) + (magit-popup-event-fun it)) + (magit-popup-describe-function (magit-popup-event-fun it)) + (magit-popup-manpage man it)) + (user-error "%c isn't bound to any switch" int))) + (`magit-invoke-popup-option + (--if-let (magit-popup-lookup int :options) + (if (and (string-prefix-p "++" (magit-popup-event-arg it)) + (magit-popup-event-fun it)) + (magit-popup-describe-function (magit-popup-event-fun it)) + (magit-popup-manpage man it)) + (user-error "%c isn't bound to any option" int))) + (`magit-popup-help + (magit-popup-manpage man nil)) + ((or `self-insert-command + `magit-invoke-popup-action) + (setq def (or (magit-popup-lookup int :actions) + (magit-popup-lookup int :variables))) + (if def + (magit-popup-describe-function (magit-popup-event-fun def)) + (ding) + (message nil))) + (`nil (ding) + (message nil)) + (_ (magit-popup-describe-function def))))) + +(defun magit-popup-manpage (topic arg) + (unless topic + (user-error "No man page associated with %s" + (magit-popup-get :man-page))) + (when arg + (setq arg (magit-popup-event-arg arg)) + (when (string-prefix-p "--" arg) + ;; handle '--' option and the '--[no-]' shorthand + (setq arg (cond ((string= "-- " arg) + "\\(?:\\[--\\] \\)?<[^[:space:]]+>\\.\\.\\.") + ((string-prefix-p "--no-" arg) + (concat "--" + "\\[?no-\\]?" + (substring arg 5))) + (t + (concat "--" + "\\(?:\\[no-\\]\\)?" + (substring arg 2))))))) + (let ((winconf (current-window-configuration)) buffer) + (pcase magit-popup-manpage-package + (`woman (delete-other-windows) + (split-window-below) + (with-no-warnings ; display-buffer-function is obsolete + (let ((display-buffer-alist nil) + (display-buffer-function nil) + (display-buffer-overriding-action nil)) + (woman topic))) + (setq buffer (current-buffer))) + (`man (cl-letf (((symbol-function #'fboundp) (lambda (_) nil))) + (setq buffer (man topic))) + (delete-other-windows) + (split-window-below) + (set-window-buffer (selected-window) buffer))) + (with-current-buffer buffer + (setq magit-popup-previous-winconf winconf) + (magit-popup-help-mode) + (fit-window-to-buffer (next-window)) + (if (and arg + (Man-find-section "OPTIONS") + (let ((case-fold-search nil) + ;; This matches preceding/proceeding options. + ;; Options such as '-a', '-S[]', and + ;; '--grep=' are matched by this regex + ;; without the shy group. The '. ' in the shy + ;; group is for options such as '-m + ;; parent-number', and the '-[^[:space:]]+ ' is + ;; for options such as '--mainline parent-number' + (others "-\\(?:. \\|-[^[:space:]]+ \\)?[^[:space:]]+")) + (re-search-forward + ;; should start with whitespace, and may have any + ;; number of options before/after + (format "^[\t\s]+\\(?:%s, \\)*?\\(?1:%s\\)%s\\(?:, %s\\)*$" + others + ;; options don't necessarily end in an '=' + ;; (e.g., '--gpg-sign[=]') + (string-remove-suffix "=" arg) + ;; Simple options don't end in an '='. + ;; Splitting this into 2 cases should make + ;; getting false positives less likely. + (if (string-suffix-p "=" arg) + ;; [^[:space:]]*[^.[:space:]] matches + ;; the option value, which is usually + ;; after the option name and either '=' + ;; or '[='. The value can't end in a + ;; period, as that means it's being used + ;; at the end of a sentence. The space + ;; is for options such as '--mainline + ;; parent-number'. + "\\(?: \\|\\[?=\\)[^[:space:]]*[^.[:space:]]" + ;; Either this doesn't match anything + ;; (e.g., '-a'), or the option is followed + ;; by a value delimited by a '[', '<', or + ;; ':'. A space might appear before this + ;; value, as in '-f '. The space + ;; alternative is for options such as '-m + ;; parent-number'. + "\\(?:\\(?: \\| ?[\\[<:]\\)[^[:space:]]*[^.[:space:]]\\)?") + others) + nil + t))) + (goto-char (match-beginning 1)) + (goto-char (point-min)))))) + +(defun magit-popup-describe-function (function) + (let ((winconf (current-window-configuration))) + (delete-other-windows) + (split-window-below) + (other-window 1) + (with-no-warnings ; display-buffer-function is obsolete + (let ((display-buffer-alist '(("" display-buffer-use-some-window))) + (display-buffer-function nil) + (display-buffer-overriding-action nil) + (help-window-select nil)) + (describe-function function))) + (fit-window-to-buffer) + (other-window 1) + (setq magit-popup-previous-winconf winconf) + (magit-popup-help-mode))) + +(defun magit-popup-info () + "Show the popup manual." + (interactive) + (let ((winconf (current-window-configuration))) + (delete-other-windows) + (split-window-below) + (info "(magit-popup.info)Usage") + (magit-popup-help-mode) + (setq magit-popup-previous-winconf winconf)) + (magit-popup-help-mode) + (fit-window-to-buffer (next-window))) + +(define-minor-mode magit-popup-help-mode + "Auxiliary minor mode used to restore previous window configuration. +When some sort of help buffer is created from within a popup, +then this minor mode is turned on in that buffer, so that when +the user quits it, the previous window configuration is also +restored." + :keymap '(([remap Man-quit] . magit-popup-quit) + ([remap Info-exit] . magit-popup-quit) + ([remap quit-window] . magit-popup-quit))) + +;;; Modes + +(define-derived-mode magit-popup-mode fundamental-mode "MagitPopup" + "Major mode for infix argument popups." + :mode 'magit-popup + (setq truncate-lines t) + (setq buffer-read-only t) + (setq-local scroll-margin 0) + (setq-local magit-popup-show-common-commands magit-popup-show-common-commands) + (hack-dir-local-variables-non-file-buffer)) + +(put 'magit-popup-mode 'mode-class 'special) + +(defun magit-popup-default-setup (val def) + (if (--when-let (magit-popup-get :sequence-predicate) + (funcall it)) + (magit-popup-put :actions (magit-popup-convert-actions + val (magit-popup-get :sequence-actions))) + (let ((vars (plist-get def :variables))) + (when (functionp vars) + (setq vars (funcall vars))) + (when vars + (magit-popup-put :variables (magit-popup-convert-variables val vars)))) + (magit-popup-put :switches (magit-popup-convert-switches + val (plist-get def :switches))) + (magit-popup-put :options (magit-popup-convert-options + val (plist-get def :options))) + (magit-popup-put :actions (magit-popup-convert-actions + val (plist-get def :actions))))) + +(defun magit-popup-mode-setup (popup mode) + (setq magit-previous-popup magit-current-popup) + (let ((val (symbol-value (plist-get (symbol-value popup) :variable))) + (def (symbol-value popup)) + (buf (current-buffer))) + (magit-popup-mode-display-buffer (get-buffer-create + (format "*%s*" popup)) + (or mode 'magit-popup-mode)) + (setq magit-this-popup popup) + (setq magit-pre-popup-buffer buf) + (if (bound-and-true-p magit-popup-setup-hook) ; obsolete + (run-hook-with-args 'magit-popup-setup-hook val def) + (funcall (or (magit-popup-get :setup-function) + 'magit-popup-default-setup) + val def))) + (magit-refresh-popup-buffer) + (fit-window-to-buffer nil nil (line-number-at-pos (point-max)))) + +(defun magit-popup-mode-display-buffer (buffer mode) + (let ((winconf (current-window-configuration))) + (select-window (display-buffer buffer magit-popup-display-buffer-action)) + (funcall mode) + (setq magit-popup-previous-winconf winconf))) + +(defvar magit-refresh-popup-buffer-hook nil + "Hook run by `magit-refresh-popup-buffer'. + +The hook is run right after inserting the representation of the +popup events but before optionally inserting the representation +of events shared by all popups and before point is adjusted.") + +(defun magit-refresh-popup-buffer () + (let* ((inhibit-read-only t) + (button (button-at (point))) + (prefix (and button (button-get button 'prefix))) + (event (and button (button-get button 'event)))) + (erase-buffer) + (save-excursion + (--if-let (magit-popup-get :refresh-function) + (funcall it) + (magit-popup-insert-section 'magit-popup-variable-button) + (magit-popup-insert-section 'magit-popup-switch-button) + (magit-popup-insert-section 'magit-popup-option-button) + (magit-popup-insert-section 'magit-popup-action-button)) + (run-hooks 'magit-refresh-popup-buffer-hook) + (when magit-popup-show-common-commands + (magit-popup-insert-command-section + 'magit-popup-internal-command-button + magit-popup-common-commands))) + (set-buffer-modified-p nil) + (when event + (while (and (ignore-errors (forward-button 1)) + (let ((b (button-at (point)))) + (or (not (equal (button-get b 'prefix) prefix)) + (not (equal (button-get b 'event) event))))))))) + +;;; Draw + +(defvar magit-popup-min-padding 3 + "Minimal amount of whitespace between columns in popup buffers.") + +(defun magit-popup-insert-section (type &optional spec heading) + (if (not spec) + (progn (setq spec (magit-popup-get (button-type-get type 'property))) + (when spec + (if (or (stringp (car spec)) + (functionp (car spec))) + (--each (--partition-by-header + (or (stringp it) (functionp it)) + spec) + (magit-popup-insert-section type (cdr it) (car it))) + (magit-popup-insert-section type spec)))) + (let* ((formatter (button-type-get type 'formatter)) + (items (mapcar (lambda (ev) + (and ev (or (funcall formatter type ev) '("")))) + (or spec (magit-popup-get + (button-type-get type 'property))))) + (maxcols (button-type-get type 'maxcols)) + (pred (magit-popup-get :sequence-predicate))) + (when items + (if (functionp heading) + (when (setq heading (funcall heading)) + (insert heading ?\n)) + (unless heading + (setq heading (button-type-get type 'heading))) + (insert (propertize heading 'face 'magit-popup-heading)) + (unless (string-match "\n$" heading) + (insert "\n"))) + (if (and pred (funcall pred)) + (setq maxcols nil) + (cl-typecase maxcols + (keyword (setq maxcols (magit-popup-get maxcols))) + (symbol (setq maxcols (symbol-value maxcols))))) + (when (functionp maxcols) + (setq maxcols (funcall maxcols heading))) + (when heading + (let ((colwidth + (+ (apply 'max (mapcar (lambda (e) (length (car e))) items)) + magit-popup-min-padding))) + (dolist (item items) + (unless (bolp) + (let ((padding (- colwidth (% (current-column) colwidth)))) + (if (and (< (+ (current-column) padding colwidth) + (window-width)) + (< (ceiling (/ (current-column) (* colwidth 1.0))) + (or maxcols 1000))) + (insert (make-string padding ?\s)) + (insert "\n")))) + (unless (equal item '("")) + (if item + (apply 'insert-button item) + (insert ?\s))))) + (insert (if (= (char-before) ?\n) "\n" "\n\n"))))))) + +(defun magit-popup-format-argument-button (type ev) + (list (format-spec + (button-type-get type 'format) + `((?k . ,(propertize (concat + (--when-let (button-type-get type 'prefix) + (char-to-string it)) + (magit-popup-event-keydsc ev)) + 'face 'magit-popup-key)) + (?d . ,(magit-popup-event-dsc ev)) + (?a . ,(propertize (magit-popup-event-arg ev) + 'face (if (magit-popup-event-use ev) + 'magit-popup-argument + 'magit-popup-disabled-argument))) + (?v . ,(let ((val (magit-popup-event-val ev))) + (if (and (magit-popup-event-use ev) + (not (equal val ""))) + (propertize (format "\"%s\"" val) + 'face 'magit-popup-option-value) + ""))))) + 'type type 'event (magit-popup-event-key ev))) + +(defun magit-popup-format-variable-button (type ev) + (if (not (magit-popup-event-arg ev)) + (magit-popup-format-action-button 'magit-popup-action-button ev) + (list (format-spec + (button-type-get type 'format) + `((?k . ,(propertize (magit-popup-event-keydsc ev) + 'face 'magit-popup-key)) + (?d . ,(funcall (magit-popup-event-arg ev))))) + 'type type 'event (magit-popup-event-key ev)))) + +(defun magit-popup-format-action-button (type ev) + (let* ((cmd (magit-popup-event-fun ev)) + (dsc (magit-popup-event-dsc ev)) + (fun (and (functionp dsc) dsc))) + (unless (and disabled-command-function + (symbolp cmd) + (get cmd 'disabled)) + (when fun + (setq dsc + (-when-let (branch (funcall fun)) + (if (text-property-not-all 0 (length branch) 'face nil branch) + branch + (magit-branch-set-face branch))))) + (when dsc + (list (format-spec + (button-type-get type 'format) + `((?k . ,(propertize (magit-popup-event-keydsc ev) + 'face 'magit-popup-key)) + (?d . ,dsc) + (?D . ,(if (and (not fun) + (eq cmd (magit-popup-get :default-action))) + (propertize dsc 'face 'bold) + dsc)))) + 'type type 'event (magit-popup-event-key ev)))))) + +(defun magit-popup-insert-command-section (type spec) + (magit-popup-insert-section + type (mapcar (lambda (elt) + (list (car (where-is-internal (cadr elt) + (current-local-map))) + (car elt))) + spec))) + +(defun magit-popup-format-command-button (type elt) + (nconc (magit-popup-format-action-button + type (make-magit-popup-event :key (car elt) + :dsc (cadr elt))) + (list 'function (lookup-key (current-local-map) (car elt))))) + +;;; Utilities + +(defun magit-popup-import-file-args (args files) + (if files + (cons (concat "-- " (mapconcat #'identity files ",")) args) + args)) + +(defun magit-popup-export-file-args (args) + (let ((files (--first (string-prefix-p "-- " it) args))) + (when files + (setq args (remove files args)) + (setq files (split-string (substring files 3) ","))) + (list args files))) + +(defconst magit-popup-font-lock-keywords + (eval-when-compile + `((,(concat "(\\(magit-define-popup\\)\\_>" + "[ \t'\(]*" + "\\(\\(?:\\sw\\|\\s_\\)+\\)?") + (1 'font-lock-keyword-face) + (2 'font-lock-function-name-face nil t))))) + +(font-lock-add-keywords 'emacs-lisp-mode magit-popup-font-lock-keywords) + +;;; _ +(provide 'magit-popup) +;; Local Variables: +;; indent-tabs-mode: nil +;; End: +;;; magit-popup.el ends here diff --git a/elpa/magit-popup-20181003.921/magit-popup.info b/elpa/magit-popup-20181003.921/magit-popup.info new file mode 100644 index 00000000..2c1e18fb --- /dev/null +++ b/elpa/magit-popup-20181003.921/magit-popup.info @@ -0,0 +1,745 @@ +This is magit-popup.info, produced by makeinfo version 6.5 from +magit-popup.texi. + + Copyright (C) 2015-2018 Jonas Bernoulli + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document 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. +INFO-DIR-SECTION Emacs +START-INFO-DIR-ENTRY +* Magit-Popup: (magit-popup). Infix arguments with feedback. +END-INFO-DIR-ENTRY + + +File: magit-popup.info, Node: Top, Next: Introduction, Up: (dir) + +Magit-Popup User Manual +*********************** + +Taking inspiration from regular prefix commands and prefix arguments, +this library implements a similar abstraction; a new kind of prefix +command that is associated with a specific set of infix arguments and +suffix commands. + +This manual is for Magit-Popup version 2.12.4 (v2.12.4+1). + + Copyright (C) 2015-2018 Jonas Bernoulli + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document 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. + +* Menu: + +* Introduction:: +* Usage:: +* Defining Prefix and Suffix Commands:: + +— The Detailed Node Listing — + +Usage + +* Customizing Existing Popups:: +* Other Options:: + +Defining Prefix and Suffix Commands + +* Defining Prefix Commands:: +* Defining Suffix Commands:: + + + +File: magit-popup.info, Node: Introduction, Next: Usage, Prev: Top, Up: Top + +1 Introduction +************** + +Taking inspiration from regular prefix commands and prefix arguments, +this library implements a similar abstraction; a new kind of prefix +command that is associated with a specific set of infix arguments and +suffix commands. + + Invoking such a prefix command displays a popup buffer which lists +the associated infix arguments and suffix commands. In that buffer each +argument is prefixed with the key sequence that can be used to toggle it +or change its value. Likewise each suffix command is prefixed with the +key used to invoke it. Such a popup buffer might look like this: + + ,----------------------------------------- + |Switches + | -l Show graph (--graph) + | -d Show refnames (--decorate) + | + |Options + | =m Search messages (--grep="popup") + | =p Search patches (-G) + | + |Action + | l Show log for current branch + | o Show log for another branch + '----------------------------------------- + + The user could then for example type ‘-l’ to toggle the ‘--graph’ +*switch* (when it is on then it is shown in green, otherwise in gray), +or ‘=m’ to change the value of the *option* ‘--grep’. + + Once all arguments are as desired one invokes a suffix command, which +causes the popup buffer to disappear. The suffix command should then +retrieve the infix arguments in its ‘interactive’ form like this is done +for prefix arguments. + + While such "prefix-infix-suffix" combos were inspired by regular +prefix commands and prefix arguments, they are also quite different. +This should illustrate the most basic differences: + + • A regular prefix command + + /- command1 + prefix --- command2 + \- command3 + + • Prefix arguments + + /- command1 + C-u ... --- command2 + \- well any command + + • A Prefix-Infix-Suffix combo + + /- argument1 -\ /- suffix1 + prefix----- argument2 --+-- suffix2 + ^ \- argument3 -/ + | | + '--------' + (refresh buffer) + + This library was written as a replacement for ‘magit-key-mode’, which +was used in Magit releases before 2.1.0. It is used to implement all +"popups" in the current Magit release but a future release will switch +to yet another implementation. + + This library does not depend on any other Magit libraries and it is +distributed as a separate package, which makes it possible to use it in +packages that are not related to Magit. But keep in mind that it will +be deprecated eventually. + + +File: magit-popup.info, Node: Usage, Next: Defining Prefix and Suffix Commands, Prev: Introduction, Up: Top + +2 Usage +******* + +Every popup buffers created with a prefix command contains a section +named "Actions" listing the available suffix commands. Most buffers +also contain a "Switches" and/or an "Options" section which list the two +types of infix arguments separately. + + Switches are arguments that can be toggled on or off. When a switch +is active then it is shown in color, when it is off then it is shown in +gray (of course the details depend on the color theme in use). + + Options are arguments that have a value. When an option has a value +then that is shown after the option itself. Because for some options +the empty string is a valid value, options are additionally colorized +like switches to indicate whether they are active or not. + + The events bound to suffix commands are always single alphabetic +characters. The bindings for arguments are always two events long. For +switches the first key is always ‘-’, for options it is always ‘=’. The +second key is always an alphabetic character. + + By default popup buffers also feature a section listing commands +common to all popups. To avoid conflicts with suffix commands, the +bindings of these common commands are not alphabetic characters. This +section is shown by default so that documentation-resistant users get a +chance to notice them. + + -- User Option: magit-popup-show-common-commands + + This option controls whether the section that lists the commands + that are common to all popups is initially shown. + + By default this is not the case, but note that you can temporarily + show this section using ‘C-t’, which therefore is the only common + command you actually have to memorize. + +‘C-t’ (‘magit-popup-toggle-show-common-commands’) + + Show or hide the section listing the commands shared by all popups. + +‘C-g’ (‘magit-popup-quit’) + + Quit popup buffer without invoking a suffix command. + + Without further action, setting arguments only affects the next +suffix command. Invoking the same prefix command again resets the +arguments to their default value, but the defaults can be changed +directly from the popup buffer itself. For a prefix command named +‘NAME-popup’ the default values are stored as the value of the custom +option named ‘NAME-arguments’. While this option can be customized +using the Custom interface, it is better to do so directly from the +popup buffer. + +‘C-c C-c’ (‘magit-popup-set-default-arguments’) + + This sets the default value for the arguments for the current + popup. + + Then the popup buffer is closed without invoking a suffix command; + unless a prefix argument is used in which case the popup remains + open. + +‘C-x C-s’ (‘magit-popup-save-default-arguments’) + + This sets the default value for the arguments for the current popup + and saves it for future Emacs sessions. + + Then the popup buffer is closed without invoking an action; unless + a prefix argument is used in which case the popup remains open. + + It is also possible to add additional arguments and commands to an +existing popup, but that cannot be done directly from the popup (or the +Custom interface). See *note Customizing Existing Popups::. + + Documentation about a popup’s arguments and commands can be shown +directly from the popup. + +‘C-h i’ (‘magit-popup-info’) + + Show this manual. + +‘?’ (‘magit-popup-help’) + + This command reads a key sequence and then shows the documentation + of the argument or command that sequence is bound to. In other + words type the same keys that you would use to invoke the argument + or command, but prefix the sequence with ‘?’. + + For suffix commands this shows the doc-string. For arguments this + command can only show something for popups that have an associated + man-page. If the man-page is set, then this command displays it in + a separate buffer and puts point on the entry about the argument in + question. + + The buffer which is used to display the documentation is selected. + Simply press ‘q’ to leave that buffer and restore the old window + configuration. + + While it isn’t very useful, it is possible to move around in a popup +buffer using ‘C-p’ and ‘C-n’, and to invoke the argument or command at +point using ‘RET’. But it is much more efficient to use the dedicated +key bindings instead, so these commands are not listed in popup buffers +along with the other common commands. + +* Menu: + +* Customizing Existing Popups:: +* Other Options:: + + +File: magit-popup.info, Node: Customizing Existing Popups, Next: Other Options, Up: Usage + +2.1 Customizing Existing Popups +=============================== + +It is possible to define additional infix arguments and suffix commands +to an existing popup using the following functions. + + You can find some examples which use the below commands at +. + + -- Function: magit-define-popup-switch popup key desc switch &optional + enable at prepend + + In POPUP, define KEY as SWITCH. + + POPUP is a popup command defined using ‘magit-define-popup’. + SWITCH is a string representing an argument that takes no value. + KEY is a character representing the second event in the sequence of + keystrokes used to toggle the argument. (The first event, the + prefix, is shared among all switches, defaults to ‘-’, and can be + changed in ‘magit-popup-mode-keymap’). + + DESC is a string describing the purpose of the argument, it is + displayed in the popup. + + If optional ENABLE is non-nil then the switch is on by default. + + SWITCH is inserted after all other switches already defined for + POPUP, unless optional PREPEND is non-nil, in which case it is + placed first. If optional AT is non-nil then it should be the KEY + of another switch already defined for POPUP, the argument is then + placed before or after AT, depending on PREPEND. + + -- Function: magit-define-popup-option popup key desc option &optional + reader value at prepend + + In POPUP, define KEY as OPTION. + + POPUP is a popup command defined using ‘magit-define-popup’. + OPTION is a string representing an argument that takes a value. + KEY is a character representing the second event in the sequence of + keystrokes used to set the argument’s value. (The first event, the + prefix, is shared among all options, defaults to ‘=’, and can be + changed in ‘magit-popup-mode-keymap’). + + DESC is a string describing the purpose of the argument, it is + displayed in the popup. + + If optional VALUE is non-nil then the option is on by default, and + VALUE is its default value. + + READER is used to read a value from the user when the option is + invoked and does not currently have a value. (When the option has + a value, then invoking the option causes it to be unset.) This + function must take two arguments but may choose to ignore them. + The first argument is the name of the option (with ": \" appended, + unless it ends with "=") and can be used as the prompt. The second + argument is nil or the value that was in effect before the option + was unset, which may be suitable as initial completion input. If + no reader is specified, then ‘read-from-minibuffer’ is used. + + OPTION is inserted after all other options already defined for + POPUP, unless optional PREPEND is non-nil, in which case it is + placed first. If optional AT is non-nil then it should be the KEY + of another option already defined for POPUP, the argument is then + placed before or after AT, depending on PREPEND. + + -- Function: magit-define-popup-action popup key desc command &optional + at prepend + + In POPUP, define KEY as COMMAND. + + POPUP is a popup command defined using ‘magit-define-popup’. + COMMAND can be any command but should usually consume the popup + arguments in its ‘interactive’ form. KEY is a character + representing the event used invoke the action, i.e. to + interactively call the COMMAND. + + DESC is a string describing the purpose of the action, it is + displayed in the popup. + + COMMAND is inserted after all other commands already defined for + POPUP, unless optional PREPEND is non-nil, in which case it is + placed first. If optional AT is non-nil then it should be the KEY + of another command already defined for POPUP, the command is then + placed before or after AT, depending on PREPEND. + + -- Function: magit-define-popup-sequence-action popup key desc command + &optional at prepend + + Like ‘magit-define-popup-action’, but modifies the value of the + ‘:sequence-actions’ property instead of ‘:actions’. + + -- Function: magit-define-popup-variable popup key desc command + formatter &optional at prepend + + In POPUP, define KEY as COMMAND. + + POPUP is a popup command defined using ‘magit-define-popup’. + COMMAND is a command which calls ‘magit-popup-set-variable’. + FORMATTER is a function which calls ‘magit-popup-format-variable’. + These two functions have to be called with the same arguments. + + KEY is a character representing the event used interactively call + the COMMAND. + + DESC is the variable or a representation thereof. It’s not + actually used for anything. + + COMMAND is inserted after all other commands already defined for + POPUP, unless optional PREPEND is non-nil, in which case it is + placed first. If optional AT is non-nil then it should be the KEY + of another command already defined for POPUP, the command is then + placed before or after AT, depending on PREPEND." + + -- Function: magit-change-popup-key popup type from to + + In POPUP, bind TO to what FROM was bound to. TYPE is one of + ‘:action’, ‘:sequence-action’, ‘:switch’, or ‘:option’. Bind TO + and unbind FROM, both are characters. + + -- Function: magit-remove-popup-key popup type key + + In POPUP, remove KEY’s binding of TYPE. POPUP is a popup command + defined using ‘magit-define-popup’. TYPE is one of ‘:action’, + ‘:sequence-action’, ‘:switch’, or ‘:option’. KEY is the character + which is to be unbound. + + It is also possible to change other aspects of a popup by setting a +property using ‘plist-put’. See *note Defining Prefix Commands:: for +valid properties. The most likely change Magit users might want to make +is: + + (plist-put magit-show-refs-popup :use-prefix nil) + + +File: magit-popup.info, Node: Other Options, Prev: Customizing Existing Popups, Up: Usage + +2.2 Other Options +================= + + -- User Option: magit-popup-use-prefix-argument + + This option controls the effect that the use of a prefix argument + before entering a popup has. + + • ‘default’ + + With a prefix argument directly invoke the popup’s default + action (an Emacs command), instead of bringing up the popup. + + • ‘popup’ + + With a prefix argument bring up the popup, otherwise directly + invoke the popup’s default action. + + • ‘nil’ + + Ignore prefix arguments. + + This option can be overridden for individual popups. + ‘magit-show-refs-popup’ for example defaults to invoking the + default action directly. It only shows the popup buffer when a + prefix argument is used. See *note Customizing Existing Popups::. + + -- User Option: magit-popup-manpage-package + + The Emacs package used to display man-pages, one of ‘man’ or + ‘woman’. + + -- User Option: magit-popup-display-buffer-action + + The option controls how the window used to display a popup buffer + is created. Popup buffers are displayed using ‘display-buffer’ + with the value of this option as ACTION argument. You can also set + this to nil and instead add an entry to ‘display-buffer-alist’. + + To emphasize the default action by making it bold use this: + + (button-type-put 'magit-popup-action-button 'format " %k %D") + + +File: magit-popup.info, Node: Defining Prefix and Suffix Commands, Prev: Usage, Up: Top + +3 Defining Prefix and Suffix Commands +************************************* + +If you write an extension for Magit then you should use this library now +and later when ‘transient’ is released port to that. + + If you are considering using this library to define popups for +packages not related to Magit, then keep in mind that it will be +superseded eventually. Once ‘transient’ has been released I will only +fix bugs in ‘magit-popup’ but not implement any new features. + + Also consider using ‘hydra’ instead. To some extend ‘magit-popup’ +and ‘hydra’ are similar but have a different focus. The main purpose of +‘magit-popup’ is to pass infix arguments to suffix commands. If all you +need is a command dispatcher then you are better of using ‘hydra’. Of +course ‘hydra’ may also be a better fit not only because of the features +it lacks, but also because of the features it provides, which are in +turn missing from ‘magit-popup’. + + Here is an example of how one defines a prefix command along with its +infix arguments, and then also one of its suffix commands. + + ;;;###autoload (autoload 'magit-tag-popup "magit" nil t) + (magit-define-popup magit-tag-popup + "Show popup buffer featuring tagging commands." + 'magit-commands + :man-page "git-tag" + :switches '((?a "Annotate" "--annotate") + (?s "Sign" "--sign") + (?f "Force" "--force")) + :actions '((?t "Create" magit-tag) + (?k "Delete" magit-tag-delete) + (?p "Prune" magit-tag-prune)) + :default-action 'magit-tag) + + ;;;###autoload + (defun magit-tag (name rev &optional args) + "Create a new tag with the given NAME at REV." + (interactive (list (magit-read-tag "Tag name") + (magit-read-branch-or-commit "Place tag on") + (magit-tag-arguments))) + (magit-run-git-with-editor "tag" args name rev)) + +* Menu: + +* Defining Prefix Commands:: +* Defining Suffix Commands:: + + +File: magit-popup.info, Node: Defining Prefix Commands, Next: Defining Suffix Commands, Up: Defining Prefix and Suffix Commands + +3.1 Defining Prefix Commands +============================ + +Prefix commands and their infix arguments are defined using the macro +‘magit-define-popup’. The key bindings and descriptions of suffix +commands are also defined using that macro, but the actual interactive +commands have to be defined separately using plain ‘defun’. + + -- Macro: magit-define-popup name doc [group [mode [option]]] :keyword + value... + + This macro defines a popup named NAME. The NAME should begin with + the package prefix and by convention end with ‘-popup’, it is used + as the name of the command which shows the popup and for an + internal variable (whose value is used to store information about + the popup and should not be accessed directly). DOC is the + doc-string of the popup command. + + This macro also defines an option and a function both named + ‘SHORTNAME-arguments’, where SHORTNAME is NAME with the trailing + ‘-popup’ removed. The name of this option and this function can be + overwritten using the optional argument OPTION, but that is rarely + advisable. As a special case if OPTION is specified but ‘nil’, + then this option and this function are not defined at all, which is + useful for popups that are used as simple dispatchers that offer no + arguments. + + The option ‘SHORTNAME-arguments’ holds the value for the popup + arguments. It can be customized from within the popup or using the + Custom interface. It can also have a buffer local value in any + non-popup buffer. The local value for the buffer from which the + popup command was invoked, can be set from within the popup buffer. + + The function ‘SHORTNAME-arguments’ returns the currently effective + value of the variable by the same name. See below for more + information. + + Optional argument GROUP specifies the Custom group into which the + option is placed. If omitted then the option is placed into some + group the same way it is done when directly using ‘defcustom’ and + omitting the group, except when NAME begins with "magit-", in which + case the group ‘magit-git-arguments’ is used. + + The optional argument MODE specifies the mode used by the popup + buffer. If it is omitted or ‘nil’ then ‘magit-popup-mode’ is used. + + The remaining arguments should have the form ‘[KEYWORD VALUE]...’. + + The following keywords are meaningful (and by convention are + usually specified in that order): + + • ‘:actions’ + + The actions which can be invoked from the popup. VALUE is a + list whose members have the form (KEY DESC COMMAND), see + ‘magit-define-popup-action’ for details. + + Actions are regular Emacs commands, which usually have an + ‘interactive’ form setup to consume the values of the popup + ‘:switches’ and ‘:options’ when invoked from the corresponding + popup, else when invoked as the default action or directly + without using the popup, the default value of the variable + ‘SHORTNAME-arguments’. This is usually done by calling the + function ‘SHORTNAME-arguments’. + + Members of VALUE may also be strings and functions, assuming + the first member is a string or function. In that case the + members are split into sections and these special elements are + used as headings. If such an element is a function then it is + called with no arguments and must return either a string, + which is used as the heading, or nil, in which case the + section is not inserted. + + Members of VALUE may also be nil. This should only be used + together with ‘:max-action-columns’ and allows having gaps in + the action grit, which can help arranging actions sensibly. + + • ‘:default-action’ + + The default action of the popup which is used directly instead + of displaying the popup buffer, when the popup is invoked with + a prefix argument. Also see ‘magit-popup-use-prefix-argument’ + and ‘:use-prefix’, which can be used to inverse the meaning of + the prefix argument. + + • ‘:use-prefix’ + + Controls when to display the popup buffer and when to invoke + the default action (if any) directly. This overrides the + global default set using ‘magit-popup-use-prefix-argument’. + The value, if specified, should be one of ‘default’ or + ‘prefix’, or a function that is called with no arguments and + returns one of these symbols. + + • ‘:max-action-columns’ + + The maximum number of actions to display on a single line, a + number or a function that return a number and takes the name + of the section currently being inserted as argument. If there + isn’t enough room to display as many columns as specified + here, then fewer are used. + + • ‘:switches’ + + The popup arguments which can be toggled on and off. VALUE is + a list whose members have the form ‘(KEY DESC SWITCH)’, see + ‘magit-define-popup-switch’ for details. + + Members of VALUE may also be strings and functions, assuming + the first member is a string or function. In that case the + members are split into sections and these special elements are + used as headings. If such an element is a function then it is + called with no arguments and must return either a string, + which is used as the heading, or nil, in which case the + section is not inserted. + + • ‘:options’ + + The popup arguments which take a value, as in "–opt~OPTVAL". + VALUE is a list whose members have the form ‘(KEY DESC OPTION + READER)’, see ‘magit-define-popup-option’ for details. + + Members of VALUE may also be strings and functions, assuming + the first member is a string or function. In that case the + members are split into sections and these special elements are + used as headings. If such an element is a function then it is + called with no arguments and must return either a string, + which is used as the heading, or nil, in which case the + section is not inserted. + + • ‘:default-arguments’ + + The default arguments, a list of switches (which are then + enabled by default) and options with there default values, as + in ‘"--OPT=OPTVAL"’. + + • ‘:variables’ + + Variables which can be set from the popup. VALUE is a list + whose members have the form ‘(KEY DESC COMMAND FORMATTER)’, + see ‘magit-define-popup-variable’ for details. + + Members of VALUE may also be strings and functions, assuming + the first member is a string or function. In that case the + members are split into sections and these special elements are + used as headings. If such an element is a function then it is + called with no arguments and must return either a string, + which is used as the heading, or nil, in which case the + section is not inserted. + + Members of VALUE may also be actions as described above for + ‘:actions’. + + VALUE may also be a function that returns a list as describe + above. + + • ‘:sequence-predicate’ + + When this function returns non-nil, then the popup uses + ‘:sequence-actions’ instead of ‘:actions’, and does not show + the ‘:switches’ and ‘:options’. + + • ‘:sequence-actions’ + + The actions which can be invoked from the popup, when + ‘:sequence-predicate’ returns non-nil. + + • ‘:setup-function’ + + When this function is specified, then it is used instead of + ‘magit-popup-default-setup’. + + • ‘:refresh-function’ + + When this function is specified, then it is used instead of + calling ‘magit-popup-insert-section’ three times with symbols + ‘magit-popup-switch-button’, ‘magit-popup-option-button’, and + finally ‘magit-popup-action-button’ as argument. + + • ‘:man-page’ + + The name of the manpage to be displayed when the user requests + help for an argument. + + +File: magit-popup.info, Node: Defining Suffix Commands, Prev: Defining Prefix Commands, Up: Defining Prefix and Suffix Commands + +3.2 Defining Suffix Commands +============================ + +Commands intended to be invoked from a particular popup should determine +the currently effective arguments by calling the function +‘SHORTNAME-arguments’ inside their ‘interactive’ form. This function is +created by the ‘magit-define-popup’ macro. For a popup named +‘prefix-foo-popup’ the name of this function is ‘prefix-foo-arguments’. + + When the command was invoked as an action in the respective popup, +then this function returns the arguments that were set in the popup. +Otherwise when the command was invoked as the default of the popup (by +calling the popup command with a prefix argument), or without using the +popup command at all, then this function returns the buffer-local or +global value of the variable ‘SHORTNAME-arguments’. + + Internally arguments are handled as a list of strings. This might +not be appropriate for the intended use inside commands, or it might be +necessary to manipulate that list somehow, i.e. to split "–ARG=VAL" +into "–ARG""VAL". This should be done by advising or redefining the +function ‘SHORTNAME-arguments’. + + Internally ‘SHORNAME-arguments’ used following variables and +function. Except when redefining the former, you should not use these +directly. + + -- Variable: magit-current-popup + + The popup from which this editing command was invoked. + + -- Variable: magit-current-popup-args + + The value of the popup arguments for this editing command. + + If the current command was invoked from a popup, then this is a + list of strings of all the set switches and options. This includes + arguments which are set by default not only those explicitly set + during this invocation. + + When the value is nil, then that can be because no argument is set, + or because the current command wasn’t invoked from a popup at all. + + -- Function: magit-current-popup-args &rest args + + This function returns the value of the popup arguments for this + editing command. The value is the same as that of the variable by + the same name, except that FILTER is applied. FILTER is a list of + regexps; only arguments that match one of them are returned. The + first element of FILTER may also be ‘:not’ in which case only + arguments that don’t match any of the regexps are returned, or + ‘:only’ which doesn’t change the behavior. + + + +Tag Table: +Node: Top769 +Node: Introduction2004 +Node: Usage4703 +Node: Customizing Existing Popups9400 +Node: Other Options15541 +Node: Defining Prefix and Suffix Commands17084 +Node: Defining Prefix Commands19236 +Node: Defining Suffix Commands27931 + +End Tag Table + + +Local Variables: +coding: utf-8 +End: diff --git a/elpa/magit-readme.txt b/elpa/magit-readme.txt new file mode 100644 index 00000000..52bcc521 --- /dev/null +++ b/elpa/magit-readme.txt @@ -0,0 +1,8 @@ +Magit is an interface to the version control system Git, +implemented as an Emacs package. Magit aspires to be a complete +Git porcelain. While we cannot (yet) claim, that Magit wraps and +improves upon each and every Git command, it is complete enough to +allow even experienced Git users to perform almost all of their +daily version control tasks directly from within Emacs. While many +fine Git clients exist, only Magit and Git itself deserve to be +called porcelains. diff --git a/elpa/ob-async-20180816.1553/ob-async-autoloads.el b/elpa/ob-async-20180816.1553/ob-async-autoloads.el new file mode 100644 index 00000000..67a4b63e --- /dev/null +++ b/elpa/ob-async-20180816.1553/ob-async-autoloads.el @@ -0,0 +1,46 @@ +;;; ob-async-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "ob-async" "ob-async.el" (0 0 0 0)) +;;; Generated autoloads from ob-async.el + +(defalias 'org-babel-execute-src-block:async 'ob-async-org-babel-execute-src-block) + +(autoload 'ob-async-org-babel-execute-src-block "ob-async" "\ +Like org-babel-execute-src-block, but run asynchronously. + +Original docstring for org-babel-execute-src-block: + +Execute the current source code block. Insert the results of +execution into the buffer. Source code execution and the +collection and formatting of results can be controlled through a +variety of header arguments. + +With prefix argument ARG, force re-execution even if an existing +result cached in the buffer would otherwise have been returned. + +Optionally supply a value for INFO in the form returned by +`org-babel-get-src-block-info'. + +Optionally supply a value for PARAMS which will be merged with +the header arguments specified at the front of the source code +block. + +\(fn &optional ORIG-FUN ARG INFO PARAMS)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-async" '("ob-async-"))) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; ob-async-autoloads.el ends here diff --git a/elpa/ob-async-20180816.1553/ob-async-pkg.el b/elpa/ob-async-20180816.1553/ob-async-pkg.el new file mode 100644 index 00000000..bec5f4b2 --- /dev/null +++ b/elpa/ob-async-20180816.1553/ob-async-pkg.el @@ -0,0 +1,2 @@ +;;; -*- no-byte-compile: t -*- +(define-package "ob-async" "20180816.1553" "Asynchronous org-babel src block execution" '((async "1.9") (org "9.0.1") (emacs "24.4") (dash "2.14.1")) :commit "2470490e6efb3f8efde1702f7986f6e31cc1ab6c" :keywords '("tools") :authors '(("Andrew Stahlman" . "andrewstahlman@gmail.com")) :maintainer '("Andrew Stahlman" . "andrewstahlman@gmail.com") :url "https://github.com/astahlman/ob-async") diff --git a/elpa/ob-async-20180816.1553/ob-async.el b/elpa/ob-async-20180816.1553/ob-async.el new file mode 100644 index 00000000..2a149459 --- /dev/null +++ b/elpa/ob-async-20180816.1553/ob-async.el @@ -0,0 +1,203 @@ +;;; ob-async.el --- Asynchronous org-babel src block execution + +;; Copyright (C) 2017 Andrew Stahlman + +;; Author: Andrew Stahlman +;; Created: 10 Feb 2017 +;; Version: 0.1 +;; Package-Version: 20180816.1553 + +;; Keywords: tools +;; Homepage: https://github.com/astahlman/ob-async + +;; This file is not part of GNU Emacs. + +;; 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 3 of the License, 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 this program. If not, see . + +;; Package-Requires: ((async "1.9") (org "9.0.1") (emacs "24.4") (dash "2.14.1")) + +;;; Commentary: +;; This file enables asynchronous execution of org-babel +;; src blocks through the ob-async-org-babel-execute-src-block function + +;;; Code: + +(provide 'ob-async) + +(require 'org) +(require 'async) +(require 'dash) + +(defvar ob-async-no-async-languages-alist nil + "async is not used for languages listed here. Enables +compatibility for other languages, e.g. ipython, for which async +functionality may be implemented separately.") + +(defvar ob-async-pre-execute-src-block-hook nil + "Hook run in the async child process prior to executing a src +block. You can use this hook to perform language-specific +initialization which would normally execute in your init file.") + +;;;###autoload +(defalias 'org-babel-execute-src-block:async 'ob-async-org-babel-execute-src-block) + +;;;###autoload +(defun ob-async-org-babel-execute-src-block (&optional orig-fun arg info params) + "Like org-babel-execute-src-block, but run asynchronously. + +Original docstring for org-babel-execute-src-block: + +Execute the current source code block. Insert the results of +execution into the buffer. Source code execution and the +collection and formatting of results can be controlled through a +variety of header arguments. + +With prefix argument ARG, force re-execution even if an existing +result cached in the buffer would otherwise have been returned. + +Optionally supply a value for INFO in the form returned by +`org-babel-get-src-block-info'. + +Optionally supply a value for PARAMS which will be merged with +the header arguments specified at the front of the source code +block." + (interactive "P") + (cond + ;; If this function is not called as advice, do nothing + ((not orig-fun) + (warn "ob-async-org-babel-execute-src-block is no longer needed in org-ctrl-c-ctrl-c-hook") + nil) + ;; If there is no :async parameter, call the original function + ((not (assoc :async (nth 2 (or info (org-babel-get-src-block-info))))) + (funcall orig-fun arg info params)) + ;; If the src block language is in the list of languages async is not to be + ;; used for, call the original function + ((member (nth 0 (or info (org-babel-get-src-block-info))) + ob-async-no-async-languages-alist) + (funcall orig-fun arg info params)) + ;; Otherwise, perform asynchronous execution + (t + (let ((placeholder (ob-async--generate-uuid))) + ;; Here begins the original source of org-babel-execute-src-block + (let* ((org-babel-current-src-block-location + (or org-babel-current-src-block-location + (nth 5 info) + (org-babel-where-is-src-block-head))) + (info (if info (copy-tree info) (org-babel-get-src-block-info)))) + ;; Merge PARAMS with INFO before considering source block + ;; evaluation since both could disagree. + (cl-callf org-babel-merge-params (nth 2 info) params) + (when (org-babel-check-evaluate info) + (cl-callf org-babel-process-params (nth 2 info)) + (let* ((params (nth 2 info)) + (cache (let ((c (cdr (assq :cache params)))) + (and (not arg) c (string= "yes" c)))) + (new-hash (and cache (org-babel-sha1-hash info))) + (old-hash (and cache (org-babel-current-result-hash))) + (current-cache (and new-hash (equal new-hash old-hash)))) + (cond + (current-cache + (save-excursion ;Return cached result. + (goto-char (org-babel-where-is-src-block-result nil info)) + (forward-line) + (skip-chars-forward " \t") + (let ((result (org-babel-read-result))) + (message (replace-regexp-in-string "%" "%%" (format "%S" result))) + result))) + ((org-babel-confirm-evaluate info) + ;; Insert a GUID as a placeholder in our RESULTS block + (org-babel-insert-result placeholder '("replace")) + (let* ((lang (nth 0 info)) + (result-params (cdr (assq :result-params params))) + ;; Expand noweb references in BODY and remove any + ;; coderef. + (body + (let ((coderef (nth 6 info)) + (expand + (if (org-babel-noweb-p params :eval) + (org-babel-expand-noweb-references info) + (nth 1 info)))) + (if (not coderef) expand + (replace-regexp-in-string + (org-src-coderef-regexp coderef) "" expand nil nil 1)))) + (dir (cdr (assq :dir params))) + (default-directory + (or (and dir (file-name-as-directory (expand-file-name dir))) + default-directory)) + (cmd (intern (concat "org-babel-execute:" lang))) + result) + (unless (fboundp cmd) + (error "No org-babel-execute function for %s!" lang)) + (message "executing %s code block%s..." + (capitalize lang) + (let ((name (nth 4 info))) + (if name (format " (%s)" name) ""))) + (progn + (async-start + `(lambda () + ;; TODO: Put this in a function so it can be overidden + ;; Initialize the new Emacs process with org-babel functions + (setq exec-path ',exec-path) + (setq load-path ',load-path) + (package-initialize) + (setq ob-async-pre-execute-src-block-hook ',ob-async-pre-execute-src-block-hook) + (run-hooks 'ob-async-pre-execute-src-block-hook) + (org-babel-do-load-languages 'org-babel-load-languages ',org-babel-load-languages) + (let ((default-directory ,default-directory)) + (,cmd ,body ',params))) + (if (member "none" ',result-params) + (progn (message "result silenced") + 'ignore) + `(lambda (result) + (with-current-buffer ,(current-buffer) + (save-excursion + (goto-char (point-min)) + (re-search-forward ,placeholder) + (org-backward-element) + (let ((result-block (split-string (thing-at-point 'line t)))) + ;; If block has name, search by name + (-if-let (block-name (nth 1 result-block)) + (org-babel-goto-named-src-block block-name) + (org-backward-element))) + (let ((file (cdr (assq :file ',params)))) + ;; If non-empty result and :file then write to :file. + (when file + (when result + (with-temp-file file + (insert (org-babel-format-result + result (cdr (assq :sep ',params)))))) + (setq result file)) + ;; Possibly perform post process provided its + ;; appropriate. Dynamically bind "*this*" to the + ;; actual results of the block. + (let ((post (cdr (assq :post ',params)))) + (when post + (let ((*this* (if (not file) result + (org-babel-result-to-file + file + (let ((desc (assq :file-desc ',params))) + (and desc (or (cdr desc) result))))))) + (setq result (org-babel-ref-resolve post)) + (when file + (setq result-params (remove "file" ',result-params)))))) + (org-babel-insert-result result ',result-params ',info ',new-hash ',lang) + (run-hooks 'org-babel-after-execute-hook)))))))))))))))))) + +(defun ob-async--generate-uuid () + "Generate a 32 character UUID." + (md5 (number-to-string (random 100000000)))) + +(advice-add 'org-babel-execute-src-block :around 'ob-async-org-babel-execute-src-block) + +;;; ob-async.el ends here diff --git a/elpa/ob-async-readme.txt b/elpa/ob-async-readme.txt new file mode 100644 index 00000000..f3384654 --- /dev/null +++ b/elpa/ob-async-readme.txt @@ -0,0 +1,2 @@ +This file enables asynchronous execution of org-babel +src blocks through the ob-async-org-babel-execute-src-block function diff --git a/elpa/org-9.1.14.signed b/elpa/org-9.1.14.signed new file mode 100644 index 00000000..607a6dc5 --- /dev/null +++ b/elpa/org-9.1.14.signed @@ -0,0 +1 @@ +Good signature from 474F05837FBDEF9B GNU ELPA Signing Agent (trust undefined) created at 2018-08-27T05:10:03-0400 using DSA \ No newline at end of file diff --git a/elpa/org-9.1.14/COPYING b/elpa/org-9.1.14/COPYING new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/elpa/org-9.1.14/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 3 of the License, 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 this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/elpa/org-9.1.14/README_ELPA b/elpa/org-9.1.14/README_ELPA new file mode 100644 index 00000000..7640a449 --- /dev/null +++ b/elpa/org-9.1.14/README_ELPA @@ -0,0 +1,41 @@ +This is the Emacs Org project, an Emacs library for organizing your life. + +The homepage of Org is at: + https://orgmode.org + +Installations instructions are at: + https://orgmode.org/org.html#Installation + +This distribution contains an ELPA packaged version of Org. +"ELPA" stands for the "Emacs Lisp Package Archive". + +The GNU ELPA is at: + http://elpa.gnu.org + +It contains the org-*.tar package, containing only the org files +that are also part of GNU Emacs. + +There are other ELPA online, offering more packages. + +Some contain the org-plus-contrib-*.tar ELPA package, which bundles +the core Org files plus many additional contributed libraries. + +All ELPA packages of Org contain: + +README_ELPA + This file. + +*.el + Elisp files. + +org + The Org info manual. + +orgcard.pdf + The Org reference card. + +etc/ + Libraries for the ODT exporter. + +org-*-pkg.el + The name of the package, requested GNU Emacs packaging system. diff --git a/elpa/org-9.1.14/dir b/elpa/org-9.1.14/dir new file mode 100644 index 00000000..9610c404 --- /dev/null +++ b/elpa/org-9.1.14/dir @@ -0,0 +1,18 @@ +This is the file .../info/dir, which contains the +topmost node of the Info hierarchy, called (dir)Top. +The first time you invoke Info you start off looking at this node. + +File: dir, Node: Top This is the top of the INFO tree + + This (the Directory node) gives a menu of major topics. + Typing "q" exits, "?" lists all Info commands, "d" returns here, + "h" gives a primer for first-timers, + "mEmacs" visits the Emacs manual, etc. + + In Emacs, you can click mouse button 2 on a menu item or cross reference + to select it. + +* Menu: + +Emacs +* Org Mode: (org). Outline-based notes management and organizer diff --git a/elpa/org-9.1.14/etc/ORG-NEWS b/elpa/org-9.1.14/etc/ORG-NEWS new file mode 100644 index 00000000..013c7b13 --- /dev/null +++ b/elpa/org-9.1.14/etc/ORG-NEWS @@ -0,0 +1,4314 @@ +ORG NEWS -- history of user-visible changes. -*- mode: org; coding: utf-8 -*- + +#+LINK: doc https://orgmode.org/worg/doc.html#%s +#+LINK: git https://code.orgmode.org/bzg/org-mode/commit/%s + +Copyright (C) 2012-2018 Free Software Foundation, Inc. +See the end of the file for license conditions. + +Please send Org bug reports to mailto:emacs-orgmode@gnu.org. + +* Version 9.1 + +** Incompatible changes + +*** Variables relative to clocksum duration are obsolete + +~org-time-clocksum-format~, ~org-time-clocksum-use-fractional~ and +~org-time-clocksum-fractional-format~ are obsolete. If you changed +them, consider modifying ~org-duration-format~ instead. + +Variable ~org-time-clocksum-use-effort-durations~ is also obsolete. +Consider setting ~org-duration-units~ instead. + +*** ~org-at-timestamp-p~ optional argument accepts different values + +See docstrings for the allowed values. For backward compatibility, +~(org-at-timestamp-p t)~ is still supported, but should be updated +accordingly. + +*** ~org-capture-templates~ no longer accepts S-expressions as file names + +Since functions are allowed there, a straightforward way to migrate +is to turn, e.g., + +: (file (sexp)) + +into + +: (file (lambda () (sexp))) + +*** Deleted contributed packages + +=org-ebib.el, =org-bullets.el= and =org-mime.el= have been deleted +from the contrib/ directory. + +You can now find them here : + +- https://github.com/joostkremers/ebib +- https://github.com/sabof/org-bullets +- https://github.com/org-mime/org-mime + +*** Change ~org-texinfo-classes~ value +The value cannot support functions to create sectioning commands +anymore. Also, the sectioning commands should include commands for +appendices. See the docstring for more information. +*** Removal of ~:sitemap-sans-extension~ + +The publishing property is no longer recognized, as a consequence of +changes to site-map generation. + +You can get the same functionality by setting ~:sitemap-format-entry~ +to the following + +#+BEGIN_SRC elisp +(lambda (entry style project) + (cond ((not (directory-name-p entry)) + (format "[[file:%s][%s]]" + (file-name-sans-extension entry) + (org-publish-find-title entry project))) + ((eq style 'tree) (file-name-nondirectory (directory-file-name entry))) + (t entry))) +#+END_SRC + +*** Change signature for ~:sitemap-function~ + +~:sitemap-function~ now expects to be called with two arguments. See +~org-publish-project-alist~ for details. + +*** Change signature for some properties in ~org-list-to-generic~ + +~:istart~, ~:icount~, ~:iend~ and ~:isep~ now expect the type of the +list as their first argument. + +*** Change signature for ~org-get-repeater~ +The optional argument is now a string to extract the repeater from. +See docstring for details. + +*** Change signature for ~org-time-string-to-time~ +See docstring for changes. + +*** Change order of items in ~org-agenda-time-grid~ +~org-agenda-time-grid~ gained an extra item to allow users to customize +the string displayed after times in the agenda. See docstring for +details. + +*** ~tags-todo~ custom searches now include DONE keywords + +Use "/!" markup when filtering TODO keywords to get only not-done TODO +keywords. + +*** ~org-split-string~ returns ~("")~ when called on an empty string +It used to return nil. +*** Removal of =ob-scala.el= + +See [[https://github.com/ensime/emacs-scala-mode/issues/114][this github issue]]. + +You can use =ob-scala.el= as packaged in scala-mode, available from the +MELPA repository. + +** New features +*** iCalendar export uses inheritance for TIMEZONE and LOCATION properties +Both these properties can be inherited during iCalendar export, +depending on the value of ~org-use-property-inheritance~. +*** iCalendar export respects a TIMEZONE property +Set the TIMEZONE property on an entry to specify a time zone for that +entry only during iCalendar export. The property value should be +specified as in "Europe/London". +*** ~org-attach~ can move directory contents +When setting a new directory for an entry, org-attach offers to move +files over from the old directory. Using a prefix arg will reset the +directory to old, ID based one. +*** New Org duration library +This new library implements tools to read and print time durations in +various formats (e.g., "H:MM", or "1d 2h 3min"...). + +See ~org-duration-to-minutes~ and ~org-duration-from-minutes~ +docstrings. + +*** Agenda +**** New variable : ~org-agenda-show-future-repeats~ +**** New variable : ~org-agenda-prefer-last-repeat~ +**** New variable : ~org-deadline-past-days~ +See docstring for details. +**** Binding C-c C-x < for ~org-agenda-set-restriction-lock-from-agenda~ +**** New auto-align default setting for =org-agenda-tags-column= + +=org-agenda-tags-column= can now be set to =auto=, which will +automatically align tags to the right edge of the window. This is now +the default setting. + +*** New value for ~org-publish-sitemap-sort-folders~ + +The new ~ignore~ value effectively allows toggling inclusion of +directories in published site-maps. + +*** Babel + +**** Scheme: support for tables +**** Scheme: new variable: ~org-babel-scheme-null-to~ + +This new custom option allows you to use an empty list or null symbol to +format the table output, initially assigned to ~hlines~. + +**** Scheme: new header ~:prologue~ + +A new block code header has been created for Org Babel that enables +developers to prepend code to the scheme block being processed. + +Multiple ~:prologue~ headers can be added each of them using a string +with the content to be added. + +The scheme blocks are prepared by surrounding the code in the block +with a let form. The content of the ~:prologue~ headers are prepended +before this let form. + +**** Support for hledger accounting reports added +**** Clojure: new setting ~org-babel-clojure-sync-nrepl-timeout~ + +Creation of a new setting to specify the Cider timeout. By setting +the =org-babel-clojure-sync-nrepl-timeout= setting option. The value +is in seconds and if set to =nil= then no timeout will occur. +**** Clojure: new header ~:show-process~ + +A new block code header has been created for Org Babel that enables +developers to output the process of an ongoing process into a new +window/buffer. + +You can tell Org Babel to output the process of a running code block. + +To show that output you only have to specify the =:show-process= +option in the code block's header like this: + +#+begin_example +,#+BEGIN_SRC clojure :results output :show-process t + (dotimes [n 10] + (println n ".") + (Thread/sleep 500)) +,#+END_SRC +#+end_example + +If =:show-process= is specified that way, then when you will run the +code using =C-c C-c= a new window will open in Emacs. Everything that +is output by the REPL will immediately be added to that new window. + +When the processing of the code is finished, then the window and its +buffer will be closed and the results will be reported in the +=#+RESULTS= section. + +Note that the =:results= parameter's behavior is *not* changed. If +=silent= is specified, then no result will be displayed. If =output= +is specified then all the output from the window will appears in the +results section. If =value= is specified, then only the last returned +value of the code will be displayed in the results section. + +**** Maxima: new headers ~:prologue~ and ~:epilogue~ +Babel options ~:prologue~ and ~:epilogue~ have been implemented for +Maxima src blocks which prepend and append, respectively, the given +code strings. This can be useful for specifying formatting settings +which would add clutter to exported code. For instance, you can use +this ~:prologue "fpprintprec: 2; linel: 50;"~ for presenting Maxima +results in a beamer presentation. +**** PlantUML: add support for header arguments + +[[http://plantuml.com/][Plantuml]] source blocks now support the [[https://orgmode.org/manual/prologue.html#prologue][~:prologue~]], [[https://orgmode.org/manual/epilogue.html#epilogue][~:epilogue~]] and +[[https://orgmode.org/manual/var.html#var][~:var~]] header arguments. + +**** SQL: new engine added ~sqsh~ + +A new engine was added to support ~sqsh~ command line utility for use +against Microsoft SQL Server or Sybase SQL server. + +More information on ~sqsh~ can be found here: [[https://sourceforge.net/projects/sqsh/][sourceforge/sqsh]] + +To use ~sqsh~ in an *sql* =SRC_BLK= set the =:engine= like this: + +#+begin_example +,#+BEGIN_SRC sql :engine sqsh :dbhost my_host :dbuser master :dbpassword pass :database support +Select * From Users +Where clue > 0 +,#+END_SRC +#+end_example + +**** SQL: new engine added =vertica= + +A new engine was added to support vsql command line utility for use +against HP Vertica. + +More information on =vsql= can be found here: [[https://my.vertica.com/docs/7.2.x/HTML/index.htm#Authoring/ConnectingToHPVertica/vsql/UsingVsql.htm][my.vertica.com]] + +To use =vertica= in an sql =SRC_BLK= set the =:engine= like this: + +#+BEGIN_EXAMPLE + ,#+BEGIN_SRC sql :engine vertica :dbhost my_host :dbuser dbadmin :dbpassword pw :database vmart + SELECT * FROM nodes; + ,#+END_SRC +#+END_EXAMPLE +**** C++: New header ~:namespaces~ + +The new ~:namespaces~ export option can be used to specify namespaces +to be used within a C++ org source block. Its usage is similar to +~:includes~, in that it can accept multiple, space-separated +namespaces to use. This header is equivalent to adding ~using +namespace ;~ in the source block. Here is a "Hello World" in C++ +using ~:namespaces~: + +#+begin_example + ,#+BEGIN_SRC C++ :results output :namespaces std :includes + cout << "Hello World" << endl; + ,#+END_SRC +#+end_example + +**** Support for Vala language + +[[https://wiki.gnome.org/Projects/Vala][Vala]] language blocks support two special header arguments: + +- ~:flags~ passes arguments to the compiler +- ~:cmdline~ passes commandline arguments to the generated executable + +Support for [[https://orgmode.org/manual/var.html#var][~:var~]] does not exist yet, also there is no [[https://orgmode.org/manual/session.html#session][~:session~]] +support because Vala is a compiled language. + +The Vala compiler binary can be changed via the ~defcustom~ +~org-babel-vala-compiler~. + +*** New ~function~ scope argument for the Clock Table +Added a nullary function that returns a list of files as a possible +argument for the scope of the clock table. +*** Export +**** Implement vernacular table of contents in Markdown exporter +Global table of contents are generated using vanilla Markdown syntax +instead of HTML. Also #+TOC keyword, including local table of +contents, are now supported. +**** Add Slovenian translations +**** Implement ~org-export-insert-image-links~ +This new function is meant to be used in back-ends supporting images +as descriptions of links, a.k.a. image links. See its docstring for +details. +**** New macro : ~{{{n}}}~ +This macro creates and increment multiple counters in a document. See +manual for details. +**** Add global macros through ~org-export-global-macros~ +With this variable, one can define macros available for all documents. +**** New keyword ~#+EXPORT_FILE_NAME~ +Similarly to ~:EXPORT_FILE_NAME:~ property, this keyword allows the +user to specify the name of the output file upon exporting the +document. This also has an effect on publishing. +**** Horizontal rules are no longer ignored in LaTeX table math mode +**** Use ~compilation-mode~ for compilation output +**** Plain lists accept a new ~:separator~ attribute in Texinfo + +The new ~:separator~ attribute splits a tag from a description list +item into multiple parts. This allows to have two-column tables with +multiple entries in the first column. See manual for more details. + +**** ~latex-environment~ elements support ~caption~ keywords for LaTeX export +*** ~org-edit-special~ can edit LaTeX environments + +Using ~C-c '~ on a LaTeX environment opens a sub-editing buffer. By +default, major mode in that buffer is ~latex-mode~, but it can be +changed by configuring ~org-src-lang-modes~. + +*** ~org-list-to-generic~ includes a new property: ~:ifmt~ + +~:ifmt~ is a function to be called on the body of each item. See +~org-list-to-generic~ documentation for details. + +*** New variable : ~org-bibtex-headline-format-function~ +This allow to use a different title than entry title. + +*** ~org-attach~ supports attaching files from URLs + +Using ~C-c C-a u~ prompts for a URL pointing to a file to be attached +to the document. + +*** New option for ~org-refile-use-outline-path~ +~org-refile-use-outline-path~ now supports the setting ~buffer-name~, +which causes refile targets to be prefixed with the buffer’s +name. This is particularly useful when used in conjunction with +~uniquify.el~. + +*** ~org-file-contents~ now allows the FILE argument to be a URL. +This allows ~#+SETUPFILE:~ to accept a URL instead of a local file +path. The URL contents are auto-downloaded and saved to a temporary +cache ~org--file-cache~. A new optional argument ~NOCACHE~ is added +to ~org-file-contents~. + +*** ~org-mode-restart~ now resets the newly added ~org--file-cache~. +Using ~C-c C-c~ on any keyword (like ~#+SETUPFILE~) will reset the +that file cache. + +*** New option : ~org-table-duration-hour-zero-padding~ +This variable allow computed durations in tables to be zero-padded. + +*** New mode switch for table formulas : =U= +This mode omits seconds in durations. + +** Removed functions + +*** Org Timeline + +This feature has been removed. Use a custom agenda view, possibly +narrowed to current buffer to achieve a similar functionality. + +*** ~org-agenda-skip-entry-when-regexp-matches~ is obsolete + +Use ~org-agenda-skip-if~ instead. + +*** ~org-agenda-skip-subtree-when-regexp-matches~ is obsolete + +Use ~org-agenda-skip-if~ instead. + +*** ~org-agenda-skip-entry-when-regexp-matches-in-subtree~ is obsolete + +Use ~org-agenda-skip-if~ instead. + +*** ~org-minutes-to-clocksum-string~ is obsolete + +Use ~org-duration-from-minutes~ instead. + +*** ~org-hh:mm-string-to-minutes~ is obsolete + +Use ~org-duration-to-minutes~ instead. + +*** ~org-duration-string-to-minutes~ is obsolete + +Use ~org-duration-to-minutes~ instead. + +*** ~org-gnus-nnimap-cached-article-number~ is removed. + +This function relied on ~nnimap-group-overview-filename~, which was +removed from Gnus circa September 2010. + +** Removed options + +*** ~org-agenda-repeating-timestamp-show-all~ is removed. + +For an equivalent to a ~nil~ value, set +~org-agenda-show-future-repeats~ to nil and +~org-agenda-prefer-last-repeat~ to ~t~. + +*** ~org-gnus-nnimap-query-article-no-from-file~ is removed. + +This variable has no effect, as it was relying on a function that was +removed from Gnus circa September 2010. + +*** ~org-usenet-links-prefer-google~ is obsolete. + +Use ~org-gnus-prefer-web-links~ instead. + +*** ~org-publish-sitemap-file-entry-format~ is deprecated + +One can provide new ~:sitemap-format-entry~ property for a function +equivalent to the removed format string. + +*** ~org-enable-table-editor~ is removed. + +Setting it to a ~nil~ value broke some other features (e.g., speed +keys). + +*** ~org-export-use-babel~ cannot be set to ~inline-only~ + +The variable is now a boolean. + +*** ~org-texinfo-def-table-markup~ is obsolete + +Use ~org-texinfo-table-default-markup~ instead. + +** New functions + +*** ~org-publish-find-property~ + +This function can be used as a tool to format entries in a site-map, +in addition to ~org-publish-find-title~ and ~org-publish-find-date~. + +*** ~org-list-to-org~ + +It is the reciprocal of ~org-list-to-lisp~, which see. + +*** ~org-agenda-set-restriction-lock-from-agenda~ + +Call ~org-agenda-set-restriction-lock~ from the agenda. + +** Miscellaneous + +*** The Library of Babel now on Worg + +The library-of-babel.org used to be accessible from the =doc/= +directory, distributed with Org’s core. It is now accessible +from the Worg community-driven documentation [[https://orgmode.org/worg/library-of-babel.html][here]]. + +If you want to contribute to it, please see [[https://orgmode.org/worg/org-contribute.html][how to contribute]]. + +*** Allow multiple columns view + +Columns view is not limited to a single buffer anymore. +*** Org Attach obeys ~dired-dwim-target~ + +When a Dired buffer is opened next to the Org document being edited, +the prompt for file to attach can start in the Dired buffer's +directory if `dired-dwim-target' in non-nil. + +*** ~org-fill-paragraph~ can now fill a whole region +*** More specific anniversary descriptions + +Anniversary descriptions (used in the agenda view, for instance) +include the point in time, when the anniversary appears. This is, +in its most general form, just the date of the anniversary. Or +more specific terms, like "today", "tomorrow" or "in n days" are +used to describe the time span. + +This feature allows to automatically change the description of an +anniversary, depending on if it occurs in the next few days or +far away in the future. + +*** Computed dates in tables appear as inactive time stamps + +*** Save point before opening a file with an unknown search option + +When following a file link with a search option (e.g., =::#custom-id=) +that doesn't exist in the target file, save position before raising an +error. As a consequence, it is possible to jump back to the original +document with ~org-mark-ring-goto~ (default binding =C-c &=). + +*** ~org-get-heading~ accepts two more optional arguments + +See docstring for details. + +*** New option ~org-babel-uppercase-example-markers~ + +This variable is a ~defcustom~ and replaces the variable +~org-babel-capitalize-example-region-markers~, which is a ~defvar~ and +is now obsolete. +*** =INCLUDE= keywords in commented trees are now ignored. +*** Default value for ~org-texinfo-text-markup-alist~ changed. + +Now ~=...=~ markup uses ~@samp{}~ instead of ~@verb{}~. You can use +~@verb{}~ again by customizing the variable. +*** Texinfo exports example blocks as ~@example~ +*** Texinfo exports inline src blocks as ~@code{}~ +*** Texinfo default table markup is ~@asis~ +It used to be ~@samp~ but ~@asis~ is neutral and, therefore, more +suitable as a default value. +*** Texinfo default process includes ~--no-split~ option +*** New entities : ~\dollar~ and ~\USD~ +*** Support for date style URLs in =org-protocol://open-source= + URLs like =https://cool-blog.com/2017/05/20/cool-post/= are + covered by rewrite rules. + +*** Add (C) =COMMENT= support to ~org-structure-template-alist~ + +* Version 9.0 + +** Incompatible changes + +*** Emacs 23 support has been dropped + +From now on, Org expects at least Emacs 24.3, although Emacs 24.4 or +above is suggested. + +*** XEmacs support has been dropped + +Incomplete compatibility layer with XEmacs has been removed. If you +want to take over maintenance of this compatibility, please contact +our mailing list. + +*** New syntax for export blocks + +Export blocks are explicitly marked as such at the syntax level to +disambiguate their parsing from special blocks. The new syntax is + +#+BEGIN_SRC org +,#+BEGIN_EXPORT backend +... +,#+END_EXPORT +#+END_SRC + +instead of + +#+BEGIN_SRC org +,#+BEGIN_backend +... +,#+END_backend +#+END_SRC + +As a consequence, =INCLUDE= keywords syntax is modified, e.g., + +#+BEGIN_SRC org +,#+INCLUDE: "file.org" HTML +#+END_SRC + +becomes + +#+BEGIN_SRC org +,#+INCLUDE: "file.org" export html +#+END_SRC + +The following function repairs export blocks and =INCLUDE= keywords +using previous syntax: + +#+BEGIN_SRC emacs-lisp +(defun org-repair-export-blocks () + "Repair export blocks and INCLUDE keywords in current buffer." + (interactive) + (when (eq major-mode 'org-mode) + (let ((case-fold-search t) + (back-end-re (regexp-opt + '("HTML" "ASCII" "LATEX" "ODT" "MARKDOWN" "MD" "ORG" + "MAN" "BEAMER" "TEXINFO" "GROFF" "KOMA-LETTER") + t))) + (org-with-wide-buffer + (goto-char (point-min)) + (let ((block-re (concat "^[ \t]*#\\+BEGIN_" back-end-re))) + (save-excursion + (while (re-search-forward block-re nil t) + (let ((element (save-match-data (org-element-at-point)))) + (when (eq (org-element-type element) 'special-block) + (save-excursion + (goto-char (org-element-property :end element)) + (save-match-data (search-backward "_")) + (forward-char) + (insert "EXPORT") + (delete-region (point) (line-end-position))) + (replace-match "EXPORT \\1" nil nil nil 1)))))) + (let ((include-re + (format "^[ \t]*#\\+INCLUDE: .*?%s[ \t]*$" back-end-re))) + (while (re-search-forward include-re nil t) + (let ((element (save-match-data (org-element-at-point)))) + (when (and (eq (org-element-type element) 'keyword) + (string= (org-element-property :key element) "INCLUDE")) + (replace-match "EXPORT \\1" nil nil nil 1))))))))) +#+END_SRC + +Moreover, ~:export-block~ keyword used in ~org-export-define-backend~ and +~org-export-define-derived-backend~ is no longer used and needs to be +removed. + +*** Footnotes + +**** [1]-like constructs are not valid footnotes + +Using =[1]= as a footnote was already discouraged in the manual, since +it introduced too many false-positives in many Org documents. These +constructs are now unsupported. + +If you used =[N]= in some of your documents, consider turning them into +=[fn:N]=. + +**** /Org Footnote/ library doesn't handle non-Org buffers + +Commands for footnotes in an Org document no longer try to do +something in non-Org ones. If you need to have footnotes there, +consider using the =footnote.el= library, shipped with Emacs. + +In particular, ~org-footnote-tag-for-non-org-mode-files~ no longer +exists. + +*** ~org-file-apps~ no longer accepts S-expressions as commands + +The variable now accepts functions of two arguments instead of plain +S-expressions. Replacing an S-expression with an appropriate function +is straightforward. For example + +: ("pdf" . (foo)) + +becomes + +: ("pdf" . (lambda (file link) (foo))) + +*** The ~{{{modification-time}}}~ macro can get time via =vc= + +The modification time will be determined via =vc.el= if the second +argument is non-nil. See the manual for details. + +*** Preparation and completion functions in publishing projects change signature + +Preparation and completion functions are now called with an argument, +which is the project property list. It used to be dynamically scoped +through the ~project-plist~ variable. + +*** Old Babel header properties are no longer supported + +Using header arguments as property names is no longer possible. As +such, the following + +#+BEGIN_EXAMPLE +,* Headline +:PROPERTIES: +:exports: code +:var: a=1 b=2 +:var+: c=3 +:END: +#+END_EXAMPLE + +should be written instead + +#+BEGIN_EXAMPLE +,* Headline +:PROPERTIES: +:header-args: :exports code +:header-args+: :var a=1 b=2 +:header-args+: :var c=3 +:END: +#+END_EXAMPLE + +Please note that, however, old properties were defined at the source +block definition. Current ones are defined where the block is called. + +** New features + +*** ~org-eww~ has been moved into core +*** New org-protocol key=value syntax + +Org-protocol can now handle query-style parameters such as: + +#+begin_example +org-protocol://store-link?url=http:%2F%2Flocalhost%2Findex.html&title=The%20title +org-protocol://capture?template=x&title=Hello&body=World&url=http:%2F%2Fexample.com +#+end_example + +Old-style links such as +: org-protocol://store-link:/http:%2F%2Flocalhost%2Findex.html/The%20title +continue to be supported. + +If you have defined your own handler functions for +~org-protocol-protocol-alist~, change them to accept either a property +list (for new-style links) or a string (for old-style links). Use +~org-protocol-parse-parameters~ to convert old-style links into property +lists. + +*** New Org linter library + +~org-lint~ can check syntax and report common issues in Org documents. + +*** New option ~date-tree-last~ for ~org-agenda-insert-diary-strategy~ + +When ~org-agenda-insert-diary-strategy~ is set to ~date-tree-last~, diary +entries are added to last in the date tree. + +*** New ~vbar~ entity + +~\vbar~ or ~\vbar{}~ will be exported unconditionally as a =|=, +unlike to existing ~\vert~, which is expanded as ~|~ when using +a HTML derived export back-end. + +*** Export + +**** New =#+latex_compiler= keyword to set LaTeX compiler. + +PDFLaTeX, XeLaTeX, and LuaLaTeX are supported. See the manual for +details. + +**** New option ~org-export-with-broken-links~ + +This option tells the export process how to behave when encountering +a broken internal link. See its docstring for more information. + +**** Attributes support in custom language environments for LaTeX export + +Custom language environments for LaTeX export can now define the +string to be inserted during export, using attributes to indicate the +position of the elements. See variable ~org-latex-custom-lang-environments~ +for more details. + +**** New Texinfo ~options~ attribute on special blocks + +Using ~:options~ as a Texinfo attribute, it is possible to add +information to custom environments. See manual for details. + +**** New HTML ~id~ attributes on special, example and quote blocks + +If the block has a =#+NAME:= attribute assigned, then the HTML element +will have an ~id~ attribute with that name in the HTML export. This +enables one to create links to these elements in other places, e.g., +~text~. + +**** Listings with captions are now numbered in HTML export + +The class associated to the numbering is "listing-number". If you +don't want these blocks to be numbered, as it was the case until now, +You may want to add ~.listing-number { display: none; }~ to the CSS +used. + +**** Line Numbering in SRC/EXAMPLE blocks support arbitrary start number + +The ~-n~ option to ~SRC~ and ~EXAMPLE~ blocks can now take a numeric +argument to specify the staring line number for the source or example +block. The ~+n~ option can now take a numeric argument that will be +added to the last line number from the previous block as the starting +point for the SRC/EXAMPLE block. + +#+BEGIN_SRC org +,#+BEGIN_SRC emacs-lisp -n 20 +;; this will export with line number 20 +(message "This is line 21") +,#+END_SRC +,#+BEGIN_SRC emacs-lisp +n 10 +;; This will be listed as line 31 +(message "This is line 32") +,#+END_SRC +#+END_SRC + +**** Allow toggling center for images in LaTeX export + +With the global variable ~org-latex-images-centered~ or the local +attribute ~:center~ it is now possible to center an image in LaTeX +export. + +**** Default CSS class ~org-svg~ for SVG images in HTML export + +SVG images exported in HTML are now by default assigned a CSS class +~org-svg~ if no CSS class is specified with the ~:class~ attribute. By +default, the CSS styling of class ~org-svg~ specifies an image width of +90\thinsp{}% of the container the image. + +**** Markdown footnote export customization + +Variables ~org-md-footnotes-section~ and ~org-md-footnote-format~ +introduced for =ox-md.el=. Both new variables define template strings +which can be used to customize the format of the exported footnotes +section and individual footnotes, respectively. + +*** Babel + +**** Blocks with coderefs labels can now be evaluated + +The labels are removed prior to evaluating the block. + +**** Support for Lua language +**** Support for SLY in Lisp blocks + +See ~org-babel-lisp-eval-fn~ to activate it. + +**** Support for Stan language + +New ob-stan.el library. + +Evaluating a Stan block can produce two different results. + +1. Dump the source code contents to a file. + + This file can then be used as a variable in other blocks, which + allows interfaces like RStan to use the model. + +2. Compile the contents to a model file. + + This provides access to the CmdStan interface. To use this, set + ~org-babel-stan-cmdstan-directory~ and provide a ~:file~ argument + that does not end in ".stan". + +For more information and usage examples, visit +https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-stan.html + +**** Support for Oracle databases via ~sqlplus~ + +=ob-sql= library supports running SQL blocks against an Oracle +database using ~sqlplus~. Use with properties like this (all +mandatory): + +#+BEGIN_EXAMPLE +:engine oracle +:dbhost +:dbport <1521> +:dbuser +:database +:dbpassword +#+END_EXAMPLE + +**** Improved support to Microsoft SQL Server via ~sqlcmd~ + +=ob-sql= library removes support to the ~msosql~ engine which uses the +deprecated ~osql~ command line tool, and replaces it with ~mssql~ +engine which uses the ~sqlcmd~ command line tool. Use with properties +like this: + +#+BEGIN_EXAMPLE +:engine mssql +:dbhost +:dbuser +:dbpassword +:database +#+END_EXAMPLE + +If you want to use the *trusted connection* feature, omit *both* the +=dbuser= and =dbpassword= properties and add =cmdline -E= to the properties. + +If your Emacs is running in a Cygwin environment, the =ob-sql= library +can pass the converted path to the =sqlcmd= tool. + +**** Improved support of header arguments for postgresql + +The postgresql engine in a sql code block supports now ~:dbport~ nd +~:dbpassword~ as header arguments. + +**** Support for additional plantuml output formats + +The support for output formats of [[http://plantuml.com/][plantuml]] has been extended to now +include: + +All Diagrams: +- png :: +- svg :: +- eps :: +- pdf :: +- vdx :: +- txt :: ASCII art +- utxt :: ASCII art using unicode characters + +Class Diagrams: +- xmi :: +- html :: + +State Diagrams: +- scxml :: + +The output formats are determined by the file extension specified +using the :file property, e.g.: + +#+begin_src plantuml :file diagram.png +@startuml +Alice -> Bob: Authentication Request +Bob --> Alice: Authentication Response + +Alice -> Bob: Another authentication Request +Alice <-- Bob: another authentication Response +@enduml +#+end_src + +Please note that *pdf* *does not work out of the box* and needs additional +setup in addition to plantuml. See [[http://plantuml.com/pdf.html]] for +details and setup information. + +*** Rewrite of radio lists + +Radio lists, i.e, Org plain lists in foreign buffers, have been +rewritten to be on par with Radio tables. You can use a large set of +parameters to control how a given list should be rendered. See manual +for details. + +*** org-bbdb-anniversaries-future + +Used like ~org-bbdb-anniversaries~, it provides a few days warning for +upcoming anniversaries (default: 7 days). + +*** Clear non-repeated SCHEDULED upon repeating a task + +If the task is repeated, and therefore done at least one, scheduling +information is no longer relevant. It is therefore removed. + +See [[git:481719fbd5751aaa9c672b762cb43aea8ee986b0][commit message]] for more information. + +*** Support for ISO week trees + +ISO week trees are an alternative date tree format that orders entries +by ISO week and not by month. + +For example: + +: * 2015 +: ** 2015-W35 +: ** 2015-W36 +: *** 2015-08-31 Monday + +They are supported in org-capture via ~file+weektree~ and +~file+weektree+prompt~ target specifications. + +*** Accept ~:indent~ parameter when capturing column view + +When defining a "columnview" dynamic block, it is now possible to add +an :indent parameter, much like the one in the clock table. + +On the other hand, stars no longer appear in an ITEM field. + +*** Columns view + +**** ~org-columns~ accepts a prefix argument + +When called with a prefix argument, ~org-columns~ apply to the whole +buffer unconditionally. + +**** New variable : ~org-agenda-view-columns-initially~ + +The variable used to be a ~defvar~, it is now a ~defcustom~. + +**** Allow custom summaries + +It is now possible to add new summary types, or override those +provided by Org by customizing ~org-columns-summary-types~, which see. + +**** Allow multiple summaries for any property + +Columns can now summarize the same property using different summary +types. + +*** Preview LaTeX snippets in buffers not visiting files +*** New option ~org-attach-commit~ + +When non-nil, commit attachments with git, assuming the document is in +a git repository. + +*** Allow conditional case-fold searches in ~org-occur~ + +When set to ~smart~, the new variable ~org-occur-case-fold-search~ allows +to mimic =isearch.el=: if the regexp searched contains any upper case +character (or character class), the search is case sensitive. +Otherwise, it is case insensitive. + +*** More robust repeated =ox-latex= footnote handling + +Repeated footnotes are now numbered by referring to a label in the +first footnote. + +*** The ~org-block~ face is inherited by ~src-blocks~ + +This works also when =org-src-fontify-natively= is non-nil. It is also +possible to specify per-languages faces. See =org-src-block-faces= and +the manual for details. + +*** Links are now customizable + +Links can now have custom colors, tooltips, keymaps, display behavior, +etc. Links are now centralized in ~org-link-parameters~. + +** New functions + +*** ~org-next-line-empty-p~ + +It replaces the deprecated ~next~ argument to ~org-previous-line-empty-p~. + +*** ~org-show-children~ + +It is a faster implementation of ~outline-show-children~. + +** Removed functions + +*** ~org-agenda-filter-by-tag-refine~ has been removed. + +Use ~org-agenda-filter-by-tag~ instead. + +*** ~org-agenda-todayp~ is deprecated. + +Use ~org-agenda-today-p~ instead. + +*** ~org-babel-get-header~ is removed. + +Use ~org-babel--get-vars~ or ~assq~ instead, as applicable. + +*** ~org-babel-trim~ is deprecated. + +Use ~org-trim~ instead. + +*** ~org-element-remove-indentation~ is deprecated. + +Use ~org-remove-indentation~ instead. + +*** ~org-image-file-name-regexp~ is deprecated + +Use ~image-file-name-regexp~ instead. +The never-used-in-core ~extensions~ argument has been dropped. + +*** ~org-list-parse-list~ is deprecated + +Use ~org-list-to-lisp~ instead. + +*** ~org-on-heading-p~ is deprecated + +A comment to this effect was in the source code since 7.8.03, but +now a byte-compiler warning will be generated as well. + +*** ~org-table-p~ is deprecated + +Use ~org-at-table-p~ instead. + +*** ~org-table-recognize-table.el~ is deprecated + +It was not called by any org code since 2010. + +*** Various reimplementations of cl-lib functions are deprecated + +The affected functions are: +- ~org-count~ +- ~org-remove-if~ +- ~org-remove-if-not~ +- ~org-reduce~ +- ~org-every~ +- ~org-some~ + +Additionally, ~org-sublist~ is deprecated in favor of ~cl-subseq~. Note +the differences in indexing conventions: ~org-sublist~ is 1-based and +end-inclusive; ~cl-subseq~ is 0-based and end-exclusive. + +** Removed options + +*** Remove all options related to ~ido~ or ~iswitchb~ + +This includes ~org-completion-use-iswitchb~ and ~org-completion-use-ido~. +Instead Org uses regular functions, e.g., ~completion-read~ so as to +let those libraries operate. + +*** Remove ~org-list-empty-line-terminates-plain-lists~ + +Two consecutive blank lines always terminate all levels of current +plain list. + +*** ~fixltx2e~ is removed from ~org-latex-default-packages-alist~ + +fixltx2e is obsolete, see LaTeX News 22. + +** Miscellaneous +*** Add Icelandic smart quotes +*** Allow multiple receiver locations in radio tables and lists +*** Allow angular links within link descriptions + +It is now allowed to write, e.g., +~[[http:orgmode.org][]]~ as an equivalent to +~[[http:orgmode.org][file:unicorn.png]]~. The advantage of the former +is that spaces are allowed within the path. + +*** Beamer export back-ends uses ~org-latex-prefer-user-labels~ +*** ~:preparation-function~ called earlier during publishing + +Functions in this list are called before any file is associated to the +current project. Thus, they can be used to generate to be published +Org files. + +*** Function ~org-remove-indentation~ changes. + +The new algorithm doesn't remove TAB characters not used for +indentation. + +*** Secure placeholders in capture templates + +Placeholders in capture templates are no longer expanded recursively. +However, ~%(...)~ constructs are expanded very late, so you can fill +the contents of the S-exp with the replacement text of non-interactive +placeholders. As before, interactive ones are still expanded as the +very last step, so the previous statement doesn't apply to them. + +Note that only ~%(...)~ placeholders initially present in the +template, or introduced using a file placeholder, i.e., ~%[...]~ are +expanded. This prevents evaluating potentially malicious code when +another placeholder, e.g., ~%i~ expands to a S-exp. + +*** Links stored by ~org-gnus-store-link~ in nnir groups + +Since gnus nnir groups are temporary, ~org-gnus-store-link~ now refers +to the article's original group. + +*** ~org-babel-check-confirm-evaluate~ is now a function instead of a macro + +The calling convention has changed. + +*** HTML export table row customization changes + +Variable ~org-html-table-row-tags~ has been split into +~org-html-table-row-open-tag~ and ~org-html-table-row-close-tag~. +Both new variables can be either a string or a function which will be +called with 6 parameters. + +*** =ITEM= special property returns headline without stars +*** Rename ~org-insert-columns-dblock~ into ~org-columns-insert-dblock~ + +The previous name is, for the time being, kept as an obsolete alias. + +*** ~org-trim~ can preserve leading indentation. + +When setting a new optional argument to a non-nil value, ~org-trim~ +preserves leading indentation while removing blank lines at the +beginning of the string. The behavior is identical for white space at +the end of the string. + +*** Function ~org-info-export~ changes. + +HTML links created from certain info links now point to =gnu.org= URL's rather +than just to local files. For example info links such as =info:emacs#List +Buffers= used to be converted to HTML links like this: + +: emacs#List Buffers + +where local file =emacs.html= is referenced. +For most folks this file does not exist. +Thus the new behavior is to generate this HTML link instead: + +: emacs#List Buffers + +All emacs related info links are similarly translated plus few other +=gnu.org= manuals. + +*** Repeaters with a ~++~ interval and a time can be shifted to later today + +Previously, if a recurring task had a timestamp of +~<2016-01-01 Fri 20:00 ++1d>~ and was completed on =2016-01-02= at +=08:00=, the task would skip =2016-01-02= and would be rescheduled for +=2016-01-03=. Timestamps with ~++~ cookies and a specific time will +now shift to the first possible future occurrence, even if the +occurrence is later the same day the task is completed. (Timestamps +already in the future are still shifted one time further into the +future.) + +*** ~org-mobile-action-alist~ is now a defconst + +It used to be a defcustom, with a warning that it shouldn't be +modified anyway. + +*** ~file+emacs~ and ~file+sys~ link types are deprecated + +They are still supported in Org 9.0 but will eventually be removed in +a later release. Use ~file~ link type along with universal arguments +to force opening it in either Emacs or with system application. + +*** New defcustom ~org-babel-J-command~ stores the j command +*** New defalias ~org-babel-execute:j~ + +Allows J source blocks be indicated by letter j. Previously the +indication letter was solely J. + +*** ~org-open-line~ ignores tables at the very beginning of the buffer + +When ~org-special-ctrl-o~ is non-nil, it is impractical to create +a blank line above a table at the beginning of the document. Now, as +a special case, ~org-open-line~ behaves normally in this situation. + +*** ~org-babel-hash-show-time~ is now customizable + +The experimental variable used to be more or less confidential, as +a ~defvar~. + +*** New ~:format~ property to parsed links + +It defines the format of the original link. Possible values are: +~plain~, ~bracket~ and ~angle~. + +* Version 8.3 + +** Incompatible changes + +*** Properties drawers syntax changes + +Properties drawers are now required to be located right after a +headline and its planning line, when applicable. + +It will break some documents as TODO states changes were sometimes +logged before the property drawer. + +The following function will repair them: + +#+BEGIN_SRC emacs-lisp +(defun org-repair-property-drawers () + "Fix properties drawers in current buffer. +Ignore non Org buffers." + (when (eq major-mode 'org-mode) + (org-with-wide-buffer + (goto-char (point-min)) + (let ((case-fold-search t) + (inline-re (and (featurep 'org-inlinetask) + (concat (org-inlinetask-outline-regexp) + "END[ \t]*$")))) + (org-map-entries + (lambda () + (unless (and inline-re (org-looking-at-p inline-re)) + (save-excursion + (let ((end (save-excursion (outline-next-heading) (point)))) + (forward-line) + (when (org-looking-at-p org-planning-line-re) (forward-line)) + (when (and (< (point) end) + (not (org-looking-at-p org-property-drawer-re)) + (save-excursion + (and (re-search-forward org-property-drawer-re end t) + (eq (org-element-type + (save-match-data (org-element-at-point))) + 'drawer)))) + (insert (delete-and-extract-region + (match-beginning 0) + (min (1+ (match-end 0)) end))) + (unless (bolp) (insert "\n")))))))))))) +#+END_SRC + +*** Using "COMMENT" is now equivalent to commenting with "#" + +If you used "COMMENT" in headlines to prevent a subtree from being +exported, you can still do it but all information within the subtree +is now commented out, i.e. no #+OPTIONS line will be parsed or taken +into account when exporting. + +If you want to exclude a headline from export while using its contents +for setting options, use =:noexport:= (see =org-export-exclude-tags=.) + +*** =#+CATEGORY= keywords no longer apply partially to document + +It was possible to use several such keywords and have them apply to +the text below until the next one, but strongly deprecated since Org +5.14 (2008). + +=#+CATEGORY= keywords are now global to the document. You can use node +properties to set category for a subtree, e.g., + +#+BEGIN_SRC org +,* Headline + :PROPERTIES: + :CATEGORY: some category + :END: +#+END_SRC + +*** New variable to control visibility when revealing a location + +~org-show-following-heading~, ~org-show-siblings~, ~org-show-entry-below~ +and ~org-show-hierarchy-above~ no longer exist. Instead, visibility is +controlled through a single variable: ~org-show-context-detail~, which +see. + +*** Replace disputed keys again when reading a date + +~org-replace-disputed-keys~ has been ignored when reading date since +version 8.1, but the former behavior is restored again. + +Keybinding for reading date can be customized with a new variable +~org-read-date-minibuffer-local-map~. + +*** No default title is provided when =TITLE= keyword is missing + +Skipping =TITLE= keyword no longer provides the current file name, or +buffer name, as the title. Instead, simply ignore the title. + +*** Default bindings of =C-c C-n= and =C-c C-p= changed + +The key sequences =C-c C-n= and =C-c C-p= are now bound to +~org-next-visible-heading~ and ~org-previous-visible-heading~ +respectively, rather than the =outline-mode= versions of these +functions. The Org version of these functions skips over inline tasks +(and even-level headlines when ~org-odd-levels-only~ is set). + +*** ~org-element-context~ no longer return objects in keywords + +~org-element-context~ used to return objects on some keywords, i.e., +=TITLE=, =DATE= and =AUTHOR=. It now returns only the keyword. + +*** ~org-timer-default-timer~ type changed from number to string + +If you have, in your configuration, something like =(setq +org-timer-default-timer 10)= replace it with =(setq +org-timer-default-timer "10")=. + +*** Functions signature changes + +The following functions require an additional argument. See their +docstring for more information. + +- ~org-export-collect-footnote-definitions~ +- ~org-html-format-headline-function~ +- ~org-html-format-inlinetask-function~ +- ~org-latex-format-headline-function~ +- ~org-latex-format-inlinetask-function~ +- ~org-link-search~ + +** New features + +*** Default lexical evaluation of emacs-lisp src blocks + +Emacs-lisp src blocks in babel are now evaluated using lexical +scoping. There is a new header to control this behavior. + +The default results in an eval with lexical scoping. +:lexical yes + +This turns lexical scoping off in the eval (the former behavior). +:lexical no + +This uses the lexical environment with x=42 in the eval. +:lexical '((x . 42)) + +*** Behavior of ~org-return~ changed + +If point is before or after the headline title, insert a new line +without changing the headline. + +*** Hierarchies of tags + +The functionality of nesting tags in hierarchies is added to org-mode. +This is the generalization of what was previously called "Tag groups" +in the manual. That term is now changed to "Tag hierarchy". + +The following in-buffer definition: + +#+BEGIN_SRC org + ,#+TAGS: [ Group : SubOne SubTwo ] + ,#+TAGS: [ SubOne : SubOne1 SubOne2 ] + ,#+TAGS: [ SubTwo : SubTwo1 SubTwo2 ] +#+END_SRC + +Should be seen as the following tree of tags: + +- Group + - SubOne + - SubOne1 + - SubOne2 + - SubTwo + - SubTwo1 + - SubTwo2 + +Searching for "Group" should return all tags defined above. Filtering +on SubOne filters also it's sub-tags. Etc. + +There is no limit on the depth for the tag hierarchy. + +*** Additional syntax for non-unique grouptags + +Additional syntax is defined for grouptags if the tags in the group +don't have to be distinct on a heading. + +Grouptags had to previously be defined with { }. This syntax is +already used for exclusive tags and Grouptags need their own, +non-exclusive syntax. This behavior is achieved with [ ]. Note: { } +can still be used also for Grouptags but then only one of the given +tags can be used on the headline at the same time. Example: + +[ group : sub1 sub2 ] + +#+BEGIN_SRC org +,* Test :sub1:sub2: +#+END_SRC + +This is a more general case than the already existing syntax for +grouptags; { }. + +*** Define regular expression patterns as tags + +Tags can be defined as grouptags with regular expressions as +"sub-tags". + +The regular expressions in the group must be marked up within { }. +Example use: + +: #+TAGS: [ Project : {P@.+} ] + +Searching for the tag Project will now list all tags also including +regular expression matches for P@.+. This is good for example for +projects tagged with a common identifier, i.e. P@2014_OrgTags. + +*** Filtering in the agenda on grouptags (Tag hierarchies) + +Filtering in the agenda on grouptags filters all of the related tags. +Except if a filter is applied with a (double) prefix-argument. + +Filtering in the agenda on subcategories does not filter the "above" +levels anymore. + +If a grouptag contains a regular expression the regular expression +is also used as a filter. + +*** Minor refactoring of ~org-agenda-filter-by-tag~ + +Now uses the argument ARG and optional argument exclude instead of +strip and narrow. ARG because the argument has multiple purposes and +makes more sense than strip now. The term "narrowing" is changed to +exclude. + +The main purpose is for the function to make more logical sense when +filtering on tags now when tags can be structured in hierarchies. + +*** Babel: support for sed scripts + +Thanks to Bjarte Johansen for this feature. + +*** Babel: support for Processing language + +New ob-processing.el library. + +This library implements necessary functions for implementing editing +of Processing code blocks, viewing the resulting sketches in an +external viewer, and HTML export of the sketches. + +Check the documentation for more details. + +Thanks to Jarmo Hurri for this feature. + +*** New behavior for ~org-toggle-latex-fragment~ + +The new behavior is the following: + +- With a double prefix argument or with a single prefix argument when + point is before the first headline, toggle overlays in the whole + buffer; + +- With a single prefix argument, toggle overlays in the current + subtree; + +- On latex code, toggle overlay at point; + +- Otherwise, toggle overlays in the current section. + +*** Additional markup with =#+INCLUDE= keyword + +The content of the included file can now be optionally marked up, for +instance as HTML. See the documentation for details. + +*** File links with =#+INCLUDE= keyword + +Objects can be extracted via =#+INCLUDE= using file links. It is +possible to include only the contents of the object. See manual for +more information. + +*** Drawers do not need anymore to be referenced in =#+DRAWERS= + +One can use a drawer without listing it in the =#+DRAWERS= keyword, +which is now obsolete. As a consequence, this change also deprecates +~org-drawers~ variable. + +*** ~org-edit-special~ can edit export blocks + +Using C-c ' on an export block now opens a sub-editing buffer. Major +mode in that buffer is determined by export backend name (e.g., +"latex" \to "latex-mode"). You can define exceptions to this rule by +configuring ~org-src-lang-modes~, which see. + +*** Additional =:hline= processing to ob-shell + +If the argument =:hlines yes= is present in a babel call, an optional +argument =:hlines-string= can be used to define a string to use as a +representation for the lisp symbol ='hline= in the shell program. The +default is =hline=. + +*** Markdown export supports switches in source blocks + +For example, it is now possible to number lines using the =-n= switch in +a source block. + +*** New option in ASCII export + +Plain lists can have an extra margin by setting ~org-ascii-list-margin~ +variable to an appropriate integer. + +*** New blocks in ASCII export + +ASCII export now supports =#+BEGIN_JUSTIFYRIGHT= and =#+BEGIN_JUSTIFYLEFT= +blocks. See documentation for details. + +*** More back-end specific publishing options + +The number of publishing options specific to each back-end has been +increased. See manual for details. + +*** Export inline source blocks + +Inline source code was used to be removed upon exporting. They are +now handled as standard code blocks, i.e., the source code can appear +in the output, depending on the parameters. + +*** Extend ~org-export-first-sibling-p~ and ~org-export-last-sibling-p~ + +These functions now support any element or object, not only headlines. + +*** New function: ~org-export-table-row-in-header-p~ + +*** New function: ~org-export-get-reference~ + +*** New function: ~org-element-lineage~ + +This function deprecates ~org-export-get-genealogy~. It also provides +more features. See docstring for details. + +*** New function: ~org-element-copy~ + +*** New filter: ~org-export-filter-body-functions~ + +Functions in this filter are applied on the body of the exported +document, before wrapping it within the template. + +*** New :environment parameter when exporting example blocks to LaTeX + +: #+ATTR_LATEX: :environment myverbatim +: #+BEGIN_EXAMPLE +: This sentence is false. +: #+END_EXAMPLE + +will be exported using =@samp(myverbatim)= instead of =@samp(verbatim)=. + +*** Various improvements on radio tables + +Radio tables feature now relies on Org's export framework ("ox.el"). +~:no-escape~ parameter no longer exists, but additional global +parameters are now supported: ~:raw~, ~:backend~. Moreover, there are new +parameters specific to some pre-defined translators, e.g., +~:environment~ and ~:booktabs~ for ~orgtbl-to-latex~. See translators +docstrings (including ~orgtbl-to-generic~) for details. + +*** Non-floating minted listings in Latex export + +It is not possible to specify =#+attr_latex: :float nil= in conjunction +with source blocks exported by the minted package. + +*** Field formulas can now create columns as needed + +Previously, evaluating formulas that referenced out-of-bounds columns +would throw an error. A new variable ~org-table-formula-create-columns~ +was added to adjust this behavior. It is now possible to silently add +new columns, to do so with a warning or to explicitly ask the user +each time. + +*** ASCII plot + +Ability to plot values in a column through ASCII-art bars. See manual +for details. + +*** New hook: ~org-archive-hook~ + +This hook is called after successfully archiving a subtree, with point +on the original subtree, not yet deleted. + +*** New option: ~org-attach-archive-delete~ + +When non-nil, attachments from archived subtrees are removed. + +*** New option: ~org-latex-caption-above~ + +This variable generalizes ~org-latex-table-caption-above~, which is now +deprecated. In addition to tables, it applies to source blocks, +special blocks and images. See docstring for more information. + +*** New option: ~org-latex-prefer-user-labels~ + +See the docstring for more information. + +*** Export unnumbered headlines + +Headlines, for which the property ~UNNUMBERED~ is non-nil, are now +exported without section numbers irrespective of their levels. The +property is inherited by children. + +*** Tables can be sorted with an arbitrary function + +It is now possible to specify a function, both programmatically, +through a new optional argument, and interactively with ~f~ or ~F~ keys, +to sort a table. + +*** Table of contents can be local to a section + +The ~TOC~ keywords now accepts an optional ~local~ parameter. See manual +for details. + +*** Countdown timers can now be paused + +~org-timer-pause-time~ now pauses and restarts both relative and +countdown timers. + +*** New option ~only-window~ for ~org-agenda-window-setup~ + +When ~org-agenda-window-setup~ is set to ~only-window~, the agenda is +displayed as the sole window of the current frame. + +*** ~{{{date}}}~ macro supports optional formatting argument + +It is now possible to supply and optional formatting argument to +~{{{date}}}~. See manual for details. + +*** ~{{{property}}}~ macro supports optional search argument + +It is now possible to supply an optional search option to +~{{{property}}}~ in order to retrieve remote properties optional. See +manual for details. + +*** New option ~org-export-with-title~ + +It is possible to suppress the title insertion with ~#+OPTIONS: +title:nil~ or globally using the variable ~org-export-with-title~. + +*** New entities family: "\_ " + +"\_ " are used to insert up to 20 contiguous spaces in various +back-ends. In particular, this family can be used to introduce +leading spaces within table cells. + +*** New MathJax configuration options + +Org uses the MathJax CDN by default. See the manual and the docstring +of ~org-html-mathjax-options~ for details. + +*** New behavior in `org-export-options-alist' + +When defining a back-end, it is now possible to specify to give +`parse' behavior on a keyword. It is equivalent to call +`org-element-parse-secondary-string' on the value. + +However, parsed =KEYWORD= is automatically associated to an +=:EXPORT_KEYWORD:= property, which can be used to override the keyword +value during a subtree export. Moreover, macros are expanded in such +keywords and properties. + +*** Viewport support in html export + +Viewport for mobile-optimized website is now automatically inserted +when exporting to html. See ~org-html-viewport~ for details. + +*** New ~#+SUBTITLE~ export keyword + +Org can typeset a subtitle in some export backends. See the manual +for details. + +*** Remotely edit a footnote definition + +Calling ~org-edit-footnote-reference~ (C-c ') on a footnote reference +allows to edit its definition, as long as it is not anonymous, in a +dedicated buffer. It works even if buffer is currently narrowed. + +*** New function ~org-delete-indentation~ bound to ~M-^~ + +Work as ~delete-indentation~ unless at heading, in which case text is +added to headline text. + +*** Support for images in Texinfo export + +~Texinfo~ back-end now handles images. See the manual for details. + +*** Support for captions in Texinfo export + +Tables and source blocks can now have captions. Additionally, lists +of tables and lists of listings can be inserted in the document with +=#+TOC= keyword. + +*** Countdown timer support hh:mm:ss format + +In addition to setting countdown timers in minutes, they can also be +set using the hh:mm:ss format. + +*** Extend ~org-clone-subtree-with-time-shift~ + +~org-clone-subtree-with-time-shift~ now accepts 0 as an argument for the +number of clones, which removes the repeater from the original subtree +and creates one shifted, repeating clone. + +*** New time block for clock tables: ~untilnow~ + +It encompasses all past closed clocks. + +*** Support for the ~polyglossia~ LaTeX package + +See the docstring of ~org-latex-classes~ and +~org-latex-guess-polyglossia-language~ for details. + +*** None-floating tables, graphics and blocks can have captions + +*** `org-insert-heading' can be forced to insert top-level headline + +** Removed functions + +*** Removed function ~org-translate-time~ + +Use ~org-timestamp-translate~ instead. + +*** Removed function ~org-beamer-insert-options-template~ + +This function inserted a Beamer specific template at point or in +current subtree. Use ~org-export-insert-default-template~ instead, as +it provides more features and covers all export back-ends. It is also +accessible from the export dispatcher. + +*** Removed function ~org-timer-cancel-timer~ + +~org-timer-stop~ now stops both relative and countdown timers. + +*** Removed function ~org-export-solidify-link-text~ + +This function, being non-bijective, introduced bug in internal +references. Use ~org-export-get-reference~ instead. + +*** Removed function ~org-end-of-meta-data-and-drawers~ + +The function is superseded by ~org-end-of-meta-data~, called with an +optional argument. + +*** Removed functions ~org-table-colgroup-line-p~, ~org-table-cookie-line-p~ + +These functions were left-over from pre 8.0 era. They are not correct +anymore. Since they are not needed, they have no replacement. + +** Removed options + +*** ~org-list-empty-line-terminates-plain-lists~ is deprecated + +It will be kept in code base until next release, for backward +compatibility. + +If you need to separate consecutive lists with blank lines, always use +two of them, as if this option was nil (default value). + +*** ~org-export-with-creator~ is a boolean + +Special ~comment~ value is no longer allowed. It is possible to use a +body filter to add comments about the creator at the end of the +document instead. + +*** Removed option =org-html-use-unicode-chars= + +Setting this to non-nil was problematic as it converted characters +everywhere in the buffer, possibly corrupting URLs. + +*** Removed option =org-babel-sh-command= + +This undocumented option defaulted to the value of =shell-file-name= at +the time of loading =ob-shell=. The new behavior is to use the value +of =shell-file-name= directly when the shell langage is =shell=. To chose +a different shell, either customize =shell-file-name= or bind this +variable locally. + +*** Removed option =org-babel-sh-var-quote-fmt= + +This undocumented option was supposed to provide different quoting +styles when changing the shell type. Changing the shell type can now +be done directly from the source block and the quoting style has to be +compatible across all shells, so a customization doesn't make sense +anymore. The chosen hard coded quoting style conforms to POSIX. + +*** Removed option ~org-insert-labeled-timestamps-at-point~ + +Setting this option to anything else that the default value (nil) +would create invalid planning info. This dangerous option is now +removed. + +*** Removed option ~org-koma-letter-use-title~ + +Use org-export-with-title instead. See also below. + +*** Removed option ~org-entities-ascii-explanatory~ + +This variable has no effect since Org 8.0. + +*** Removed option ~org-table-error-on-row-ref-crossing-hline~ + +This variable has no effect since August 2009. + +*** Removed MathML-related options from ~org-html-mathjax-options~ + +MathJax automatically chooses the best display technology based on the +end-users browser. You may force initial usage of MathML via +~org-html-mathjax-template~ or by setting the ~path~ property of +~org-html-mathjax-options~. + +*** Removed comment-related filters + +~org-export-filter-comment-functions~ and +~org-export-filter-comment-block-functions~ variables do not exist +anymore. + +** Miscellaneous + +*** Strip all meta data from ITEM special property + +ITEM special property does not contain TODO, priority or tags anymore. + +*** File names in links accept are now compatible with URI syntax + +Absolute file names can now start with =///= in addition to =/=. E.g., +=[[file:///home/me/unicorn.jpg]]=. + +*** Footnotes in included files are now local to the file + +As a consequence, it is possible to include multiple Org files with +footnotes in a master document without being concerned about footnote +labels colliding. + +*** Mailto links now use regular URI syntax + +This change deprecates old Org syntax for mailto links: +=mailto:user@domain::Subject=. + +*** =QUOTE= keywords do not exist anymore + +=QUOTE= keywords have been deprecated since Org 8.2. + +*** Select tests to perform with the build system + +The build system has been enhanced to allow test selection with a +regular expression by defining =BTEST_RE= during the test invocation. +This is especially useful during bisection to find just when a +particular test failure was introduced. + +*** Exact heading search for external links ignore spaces and cookies + +Exact heading search for links now ignore spaces and cookies. This is +the case for links of the form ~file:projects.org::*task title~, as well +as links of the form ~file:projects.org::some words~ when +~org-link-search-must-match-exact-headline~ is not nil. + +*** ~org-latex-hyperref-template~, ~org-latex-title-command~ formatting + +New formatting keys are supported. See the respective docstrings. +Note, ~org-latex-hyperref-template~ has a new default value. + +*** ~float, wasysym, marvosym~ are removed from ~org-latex-default-packages-alist~ + +If you require any of these package add them to your preamble via +~org-latex-packages-alist~. Org also uses default LaTeX ~\tolerance~ now. + +*** When exporting, throw an error on unresolved id/fuzzy links and code refs + +This helps spotting wrong links. + +* Version 8.2 + +** Incompatible changes +*** =ob-sh.el= renamed to =ob-shell= +This may require two changes in user config. + +1. In =org-babel-do-load-languages=, change =(sh . t)= to =(shell . t)=. +2. Edit =local.mk= files to change the value of =BTEST_OB_LANGUAGES= + to remove "sh" and include "shell". + +*** Combine org-mac-message.el and org-mac-link-grabber into org-mac-link.el + +Please remove calls to =(require 'org-mac-message)= and =(require +'org-mac-link-grabber)= in your =.emacs= initialization file. All you +need now is =(require 'org-mac-link)=. + +Additionally, replace any calls to =ogml-grab-link= to +=org-mac-grab-link=. For example, replace this line: + +: (define-key org-mode-map (kbd "C-c g") 'omgl-grab-link) + +with this: + +: (define-key org-mode-map (kbd "C-c g") 'org-mac-grab-link) + +*** HTML export: Replace =HTML_HTML5_FANCY= by =:html-html5-fancy= (...) + +Some of the HTML specific export options in Org <8.1 are either nil or +t, like =#+HTML_INCLUDE_STYLE=. We replaced these binary options with +option keywords like :html-include-style. + +So you need to replace + +: #+HTML_INCLUDE_STYLE: t + +by + +: #+OPTIONS: :html-include-style t + +Options affected by this change: =HTML5_FANCY=, =HTML_INCLUDE_SCRIPTS= +and =HTML_INCLUDE_STYLE=. + +*** Add an argument to ~org-export-to-file~ and ~org-export-to-buffer~ + +~org-export-to-file~ and ~org-export-to-file~ can run in a different +process when provided a non-nil =ASYNC= optional argument, without +relying on ~org-export-async-start~ macro. + +Since =ASYNC= is the first of optional arguments, you have to shift +the other optional arguments accordingly. + +*** Export back-ends are now structures + +Export back-ends are now structures, and stored as such in the +communication channel during an export process. In other words, from +now on, ~(plist-get info :back-end)~ will return a structure instead +of a symbol. + +Arguments in hooks and in filters are still symbols, though. + +** Important bugfixes + +*** [[doc:org-insert-heading][org-insert-heading]] has been rewritten and bugs are now fixed +*** The replacement of disputed keys is now turned of when reading a date + +*** Match string for sparse trees can now contain a slash in a property value + + You can now have searches like SOMEPROP="aaa/bbb". Until now, + this would break because the slash would be interpreted as the + separator starting a TOTO match string. +** New features + +*** =C-c ^ x= will now sort checklist items by their checked status + +See [[doc:org-sort-list][org-sort-list]]: hitting =C-c ^ x= will put checked items at the end +of the list. +*** Various LaTeX export enhancements + +- Support SVG images +- Support for .pgf files +- LaTeX Babel blocks can now be exported as =.tikz= files +- Allow =latexmk= as an option for [[doc:org-latex-pdf-process][org-latex-pdf-process]] +- When using =\usepackage[AUTO]{babel}=, AUTO will automatically be + replaced with a value compatible with ~org-export-default-language~ + or ~LANGUAGE~ keyword. +- The dependency on the =latexsym= LaTeX package has been removed, we + now use =amssymb= symbols by default instead. + +*** New functions for paragraph motion + + The commands =C-down= and =C-up= now invoke special commands + that use knowledge from the org-elements parser to move the cursor + in a paragraph-like way. + +*** New entities in =org-entities.el= + +Add support for ell, imath, jmath, varphi, varpi, aleph, gimel, beth, +dalet, cdots, S (§), dag, ddag, colon, therefore, because, triangleq, +leq, geq, lessgtr, lesseqgtr, ll, lll, gg, ggg, prec, preceq, +preccurlyeq, succ, succeq, succurlyeq, setminus, nexist(s), mho, +check, frown, diamond. Changes loz, vert, checkmark, smile and tilde. + +*** Anonymous export back-ends + +~org-export-create-backend~ can create anonymous export back-ends, +which can then be passed to export functions like +~org-export-to-file~, ~org-export-to-buffer~ or ~org-export-as~. + +It allows for quick translation of Org syntax without the overhead of +registering a new back-end. + +*** New agenda fortnight view + + The agenda has not, in addition to day, week, month, and year + views, also a fortnight view covering 14 days. +** New options + +*** New option [[doc:org-bookmark-names-plist][org-bookmark-names-plist]] + +This allows to specify the names of automatic bookmarks. +*** New option [[doc:org-agenda-ignore-drawer-properties][org-agenda-ignore-drawer-properties]] + +This allows more flexibility when optimizing the agenda generation. +See https://orgmode.org/worg/agenda-optimization.html for details. +*** New option: [[doc:org-html-link-use-abs-url][org-html-link-use-abs-url]] to force using absolute URLs + +This is an export/publishing option, and should be used either within +the =#+OPTIONS= line(s) or within a [[doc:org-publish-project-alist][org-publish-project-alist]]. + +Setting this option to =t= is needed when the HTML output does not +allow relative URLs. For example, the =contrib/lisp/ox-rss.el= +library produces a RSS feed, and RSS feeds need to use absolute URLs, +so a combination of =:html-link-home "..." and :html-link-use-abs-url +t= is required---see the configuration example in the comment section +of =ox-rss.el=. + +*** New option [[doc:org-babel-ditaa-java-cmd][org-babel-ditaa-java-cmd]] + +This makes java executable configurable for ditaa blocks. + +*** New options [[doc:org-babel-latex-htlatex][org-babel-latex-htlatex]] and [[doc:org-babel-latex-htlatex-packages][org-babel-latex-htlatex-packages]] + +This enables SVG generation from latex code blocks. + +*** New option: [[doc:org-habit-show-done-always-green][org-habit-show-done-always-green]] + +See [[https://lists.gnu.org/r/emacs-orgmode/2013-05/msg00214.html][this message]] from Max Mikhanosha. + +*** New option: [[doc:org-babel-inline-result-wrap][org-babel-inline-result-wrap]] + +If you set this to the following + +: (setq org-babel-inline-result-wrap "$%s$") + +then inline code snippets will be wrapped into the formatting string. + +*** New option: [[doc:org-special-ctrl-o][org-special-ctrl-o]] + + This variable can be used to turn off the special behavior of + =C-o= in tables. +** New contributed packages + +- =ox-bibtex.el= by Nicolas Goaziou :: an utility to handle BibTeX + export to both LaTeX and HTML exports. It uses the [[http://www.lri.fr/~filliatr/bibtex2html/][bibtex2html]] + software. + +- =org-screenshot.el= by Max Mikhanosha :: an utility to handle + screenshots easily from Org, using the external tool [[http://freecode.com/projects/scrot][scrot]]. + +** Miscellaneous + +*** "QUOTE" keywords in headlines are deprecated + +"QUOTE" keywords are an undocumented feature in Org. When a headline +starts with the keyword "QUOTE", its contents are parsed as +a ~quote-section~ and treated as an example block. You can achieve +the same with example blocks. + +This feature is deprecated and will be removed in the next Org +release. + +* Version 8.0.1 + +** Installation + +Installation instructions have been updated and simplified. + +If you have troubles installing or updating Org, focus on these +instructions: + +- when updating via a =.zip/.tar.gz= file, you only need to set the + =load-path= in your =.emacs=. Set it before any other Org + customization that would call autoloaded Org functions. + +- when updating by pulling Org's Git repository, make sure to create the + correct autoloads. You can do this by running =~$ make autoloads= (to + only create the autoloads) or by running =~$ make= (to also compile + the Emacs lisp files.) =~$ make help= and =~$ make helpall= gives you + detailed explanations. + +- when updating through ELPA (either from GNU ELPA or from Org ELPA), + you have to install Org's ELPA package in a session where no Org + function has been called already. + +When in doubt, run =M-x org-version RET= and see if you have a mixed-up +installation. + +See https://orgmode.org/org.html#Installation for details. + +** Incompatible changes + +Org 8.0 is the most disruptive major version of Org. + +If you configured export options, you will have to update some of them. + +If you used =#+ATTR_*= keywords, the syntax of the attributes changed and +you will have to update them. + +Below is a list of changes for which you need to take action. + +See https://orgmode.org/worg/org-8.0.html for the most recent version of +this list and for detailed instructions on how to migrate. + +**** New export engine + +Org 8.0 comes with a new export engine written by Nicolas Goaziou. This +export engine relies on ~org-element.el~ (Org's syntax parser), which was +already in Org's core. This new export engine triggered the rewriting of +/all/ export back-ends. + +The most visible change is the export dispatcher, accessible through the +keybinding =C-c C-e=. By default, this menu only shows some of the +built-in export formats, but you can add more formats by loading them +directly (e.g., =(require 'ox-texinfo)= or by configuring the option +[[doc:org-export-backends][org-export-backends]]. + +More contributed back-ends are available from the =contrib/= directory, the +corresponding files start with the =ox-= prefix. + +If you customized an export back-end (like HTML or LaTeX), you will need to +rename some options so that your customization is not lost. Typically, an +option starting with =org-export-html-= is now named =org-html-=. See the +manual for details and check [[https://orgmode.org/worg/org-8.0.html][this Worg page]] for directions. + +**** New syntax for #+ATTR_HTML/LaTeX/... options + + : #+ATTR_HTML width="200px" + + should now be written + + : #+ATTR_HTML :width 200px + + Keywords like =#+ATTR_HTML= and =#+ATTR_LaTeX= are defined in their + respective back-ends, and the list of supported parameters depends on + each backend. See Org's manual for details. + +**** ~org-remember.el~ has been removed + + You cannot use =remember.el= anymore to capture notes. + + Support for remember templates has been obsoleted since long, it is + now fully removed. + + Use =M-x org-capture-import-remember-templates RET= to import your + remember templates into capture templates. + +**** ~org-jsinfo.el~ has been merged into ~ox-html.el~ + + If you were requiring ~ox-jsinfo.el~ in your ~.emacs.el~ file, you + will have to remove this requirement from your initialization file. + +**** Note for third-party developers + + The name of the files for export back-end have changed: we now use the + prefix =ox-= for those files (like we use the =ob-= prefix for Babel + files.) For example ~org-html.el~ is now ~ox-html.el~. + + If your code relies on these files, please update the names in your + code. + +**** Packages moved from core to contrib + + Since packages in Org's core are meant to be part of GNU Emacs, we try + to be minimalist when it comes to adding files into core. For 8.0, we + moved some contributions into the =contrib/= directory. + + The rationale for deciding that these files should live in =contrib/= + is either because they rely on third-party software that is not + included in Emacs, or because they are not targeting a significant + user-base. + + - org-colview-xemacs.el + - org-mac-message.el + - org-mew.el + - org-wl.el + - ox-freedmind.el + - ox-taskjuggler.el + + Note that ~ox-freedmind.el~ has been rewritten by Jambunathan, + ~org-mew.el~ has been enhanced by Tokuya Kameshima and + ~ox-taskjuggler.el~ by Nicolas Goaziou and others. + + Also, the Taskjuggler exporter now uses TJ3 by default. John Hendy + wrote [[https://orgmode.org/worg/org-tutorials/org-taskjuggler3.html][a tutorial on Worg]] for the TJ3 export. + +** New packages in core + +*** ~ob-makefile.el~ by Eric Schulte and Thomas S. Dye + + =ob-makefile.el= implements Org Babel support for Makefile tangling. + +*** ~ox-man.el~ by Luis Anaya + + =ox-man.el= allows you to export Org files to =man= pages. + +*** ~ox-md.el~ by Nicolas Goaziou + + =ox-md.el= allows you to export Org files to Markdown files, using the + vanilla [[http://daringfireball.net/projects/markdown/][Markdown syntax]]. + +*** ~ox-texinfo.el~ by Jonathan Leech-Pepin + + =ox-texinfo.el= allows you to export Org files to [[https://www.gnu.org/software/texinfo/][Texinfo]] files. + +** New packages in contrib + +*** ~ob-julia.el~ by G. Jay Kerns + + [[http://julialang.org/][Julia]] is a new programming language. + + =ob-julia.el= provides Org Babel support for evaluating Julia source + code. + +*** ~ob-mathomatic.el~ by Luis Anaya + + [[http://www.mathomatic.org/][mathomatic]] a portable, command-line, educational CAS and calculator + software, written entirely in the C programming language. + + ~ob-mathomatic.el~ provides Org Babel support for evaluating mathomatic + entries. + +*** ~ob-tcl.el~ by Luis Anaya + + ~ob-tcl.el~ provides Org Babel support for evaluating [[http://www.tcl.tk/][Tcl]] source code. + +*** ~org-bullets.el~ by Evgeni Sabof + + Display bullets instead of stars for headlines. + + Also see [[https://orgmode.org/worg/org-faq.html#sec-8-12][this updated FAQ]] on how to display another character than "*" + for starting headlines. + +*** ~org-favtable.el~ by Marc-Oliver Ihm + + ~org-favtable.el~ helps you to create and update a table of favorite + locations in org, keeping the most frequently visited lines right at + the top. This table is called "favtable". See the documentation on + [[https://orgmode.org/worg/org-contrib/org-favtable.html][Worg]]. + +*** ~ox-confluence.el~ by Sébastien Delafond + + ~ox-confluence.el~ lets you convert Org files to [[https://confluence.atlassian.com/display/DOC/Confluence%2BWiki%2BMarkup][Confluence Wiki]] files. + +*** ~ox-deck.el~ and ~ox-s5.el~ by Rick Frankel + + [[http://imakewebthings.com/deck.js/][deck.js]] is a javascript library for displaying HTML ages as + presentations. ~ox-deck.el~ exports Org files to HTML presentations + using =deck.js=. + + [[http://meyerweb.com/eric/tools/s5/][s5]] is a set of scripts which also allows to display HTML pages as + presentations. ~ox-s5.el~ exports Org files to HTML presentations + using =s5=. + +*** ~ox-groff.el~ by Luis Anaya and Nicolas Goaziou + + The [[https://www.gnu.org/software/groff/][groff]] (GNU troff) software is a typesetting package which reads + plain text mixed with formatting commands and produces formatted + output. + + Luis Anaya and Nicolas Goaziou implemented ~ox-groff.el~ to allow + conversion from Org files to groff. + +*** ~ox-koma-letter.el~ by Nicolas Goaziou and Alan Schmitt + + This back-end allow to export Org pages to the =KOMA Scrlttr2= format. + +*** ~ox-rss.el~ by Bastien + + This back-end lets you export Org pages to RSS 2.0 feeds. Combined + with the HTML publishing feature, this allows you to build a blog + entirely with Org. + +** New features + +*** Export + +**** New export generic options + +If you use Org exporter, we advise you to re-read [[https://orgmode.org/org.html#Exporting][the manual section about +it]]. It has been updated and includes new options. + +Among the new/updated export options, three are of particular importance: + +- [[doc:org-export-allow-bind-keywords][org-export-allow-bind-keywords]] :: This option replaces the old option + =org-export-allow-BIND= and the default value is =nil=, not =confirm=. + You will need to explicitly set this to =t= in your initialization + file if you want to allow =#+BIND= keywords. + +- [[doc:org-export-with-planning][org-export-with-planning]] :: This new option controls the export of + =SCHEDULED:, DEADLINE:, CLOSED:= lines, and planning information is + now skipped by default during export. This use to be the job of + [[doc:org-export-with-timestamps][org-export-with-timestamps]], but this latter option has been given a + new role: it controls the export of /standalone time-stamps/. When + set to =nil=, Org will not export active and inactive time-stamps + standing on a line by themselves or within a paragraph that only + contains time-stamps. + +To check if an option has been introduced or its default value changed in +Org 8.0, do =C-h v [option] RET= and check if the documentation says that +the variable has been introduced (or changed) in version 24.4 of Emacs. + +**** Enhanced default stylesheet for the HTML exporter + +See the new default value of [[doc:org-html-style-default][org-html-style-default]]. + +**** New tags, classes and ids for the HTML exporter + +See the new default value of [[doc:org-html-divs][org-html-divs]]. + +**** Support for tikz pictures in LaTeX export +**** ~org-man.el~: New export function for "man" links +**** ~org-docview.el~: New export function for docview links +*** Structure editing + +**** =C-u C-u M-RET= inserts a heading at the end of the parent subtree +**** Cycling to the =CONTENTS= view keeps inline tasks folded + +[[doc:org-cycle-hook][org-cycle-hook]] as a new function [[doc:org-cycle-hide-inline-tasks][org-cycle-hide-inline-tasks]] which +prevents the display of inline tasks when showing the content of a subtree. + +**** =C-c -= in a region makes a list item for each line + +This is the opposite of the previous behavior, where =C-c -= on a region +would create one item for the whole region, and where =C-u C-c -= would +create an item for each line. Now =C-c -= on the selected region creates +an item per line, and =C-u C-c -= creates a single item for the whole +region. + +**** When transposing words, markup characters are now part of the words + +In Emacs, you can transpose words with =M-t=. Transposing =*these* +_words__= will preserve markup. + +**** New command [[doc:org-set-property-and-value][org-set-property-and-value]] bound to =C-c C-x P= + +This command allows you to quickly add both the property and its value. It +is useful in buffers where there are many properties and where =C-c C-x p= +can slow down the flow of editing too much. + +**** New commands [[doc:org-next-block][org-next-block]] and [[doc:org-previous-block][org-previous-block]] + +These commands allow you to go to the previous block (=C-c M-b= or the +speedy key =B=) or to the next block (=C-c M-f= or the speedy key =F=.) + +**** New commands [[doc:org-drag-line-forward][org-drag-line-forward]] and [[doc:org-drag-line-backward][org-drag-line-backward]] + +These commands emulate the old behavior of =M-= and =M-= but are +now bound to =S-M-= and =S-M-= respectively, since =M-= and +=M-= now drag the whole element at point (a paragraph, a table, etc.) +forward and backward. + +**** When a list item has a checkbox, inserting a new item uses a checkbox too +**** When sorting entries/items, only the description of links is considered + +Now Org will sort this list + +: - [[http://abc.org][B]] +: - [[http://def.org][A]] + +like this: + +: - [[http://def.org][A]] +: - [[http://abc.org][B]] + +by comparing the descriptions, not the links. +Same when sorting headlines instead of list items. +**** New option =orgstruct-heading-prefix-regexp= + +For example, setting this option to "^;;; " in Emacs lisp files and using +=orgstruct-mode= in those files will allow you to cycle through visibility +states as if lines starting with ";;; *..." where headlines. + +In general, you want to set =orgstruct-heading-prefix-regexp= as a file +local variable. + +**** New behavior of [[doc:org-clone-subtree-with-time-shift][org-clone-subtree-with-time-shift]] + +The default is now to ask for a time-shift only when there is a time-stamp. +When called with a universal prefix argument =C-u=, it will not ask for a +time-shift even if there is a time-stamp. + +**** New option [[doc:org-agenda-restriction-lock-highlight-subtree][org-agenda-restriction-lock-highlight-subtree]] + +This defaults to =t= so that the whole subtree is highlighted when you +restrict the agenda view to it with =C-c C-x <= (or the speed command =<=). +The default setting helps ensuring that you are not adding tasks after the +restricted region. If you find this highlighting too intrusive, set this +option to =nil=. +**** New option [[doc:org-closed-keep-when-no-todo][org-closed-keep-when-no-todo]] + +When switching back from a =DONE= keyword to a =TODO= keyword, Org now +removes the =CLOSED= planning information, if any. It also removes this +information when going back to a non-TODO state (e.g., with =C-c C-t SPC=). +If you want to keep the =CLOSED= planning information when removing the +TODO keyword, set [[doc:org-closed-keep-when-no-todo][org-closed-keep-when-no-todo]] to =t=. + +**** New option [[doc:org-image-actual-width][org-image-actual-width]] + +This option allows you to change the width of in-buffer displayed images. +The default is to use the actual width of the image, but you can use a +fixed value for all images, or fall back on an attribute like + +: #+attr_html: :width 300px +*** Scheduled/deadline + +**** Implement "delay" cookies for scheduled items + +If you want to delay the display of a scheduled task in the agenda, you can +now use a delay cookie like this: =SCHEDULED: <2004-12-25 Sat -2d>=. The +task is still scheduled on the 25th but will appear in your agenda starting +from two days later (i.e. from March 27th.) + +Imagine for example that your co-workers are not done in due time and tell +you "we need two more days". In that case, you may want to delay the +display of the task in your agenda by two days, but you still want the task +to appear as scheduled on March 25th. + +In case the task contains a repeater, the delay is considered to affect all +occurrences; if you want the delay to only affect the first scheduled +occurrence of the task, use =--2d= instead. See [[doc:org-scheduled-delay-days][org-scheduled-delay-days]] +and [[doc:org-agenda-skip-scheduled-delay-if-deadline][org-agenda-skip-scheduled-delay-if-deadline]] for details on how to +control this globally or per agenda. + +**** Use =C-u C-u C-c C-s= will insert a delay cookie for scheduled tasks + +See the previous section for why delay cookies may be useful. + +**** Use =C-u C-u C-c C-d= will insert a warning delay for deadline tasks + +=C-u C-u C-c C-d= now inserts a warning delay to deadlines. +*** Calendar, diary and appts + +**** New variable [[doc:org-read-date-minibuffer-local-map][org-read-date-minibuffer-local-map]] + +By default, this new local map uses "." to go to today's date, like in the +normal =M-x calendar RET=. If you want to deactivate this and to reassign +the "@" key to =calendar-goto-today=, use this: + +#+BEGIN_SRC emacs-lisp + ;; Unbind "." in Org's calendar: + (define-key org-read-date-minibuffer-local-map (kbd ".") nil) + + ;; Bind "@" to `calendar-goto-today': + (define-key org-read-date-minibuffer-local-map + (kbd "@") + (lambda () (interactive) (org-eval-in-calendar '(calendar-goto-today)))) +#+END_SRC + +**** In Org's calendar, =!= displays diary entries of the date at point + +This is useful when you want to check if you don't already have an +appointment when setting new ones with =C-c .= or =C-c s=. =!= will +call =diary-view-entries= and display the diary in a separate buffer. + +**** [[doc:org-diary][org-diary]]: only keep the descriptions of links + +[[doc:org-diary][org-diary]] returns diary information from Org files, but it returns it +in a diary buffer, not in an Org mode buffer. When links are displayed, +only show their description, not the full links. +*** Agenda + +**** New agenda type =agenda*= and entry types =:scheduled* :deadline*= + +When defining agenda custom commands, you can now use =agenda*=: this will +list entries that have both a date and a time. This is useful when you +want to build a list of appointments. + +You can also set [[doc:org-agenda-entry-types][org-agenda-entry-types]] either globally or locally in +each agenda custom command and use =:timestamp*= and/or =:deadline*= there. + +Another place where this is useful is your =.diary= file: + +: %%(org-diary :scheduled*) ~/org/rdv.org + +This will list only entries from =~/org/rdv.org= that are scheduled with a +time value (i.e. appointments). + +**** New agenda sorting strategies + +[[doc:org-agenda-sorting-strategy][org-agenda-sorting-strategy]] allows these new sorting strategies: + +| Strategy | Explanations | +|----------------+------------------------------------------| +| timestamp-up | Sort by any timestamp, early first | +| timestamp-down | Sort by any timestamp, late first | +| scheduled-up | Sort by scheduled timestamp, early first | +| scheduled-down | Sort by scheduled timestamp, late first | +| deadline-up | Sort by deadline timestamp, early first | +| deadline-down | Sort by deadline timestamp, late first | +| ts-up | Sort by active timestamp, early first | +| ts-down | Sort by active timestamp, late first | +| tsia-up | Sort by inactive timestamp, early first | +| tsia-down | Sort by inactive timestamp, late first | + +**** New options to limit the number of agenda entries + +You can now limit the number of entries in an agenda view. This is +different from filters: filters only /hide/ the entries in the agenda, +while limits are set while generating the list of agenda entries. + +These new options are available: + +- [[doc:org-agenda-max-entries][org-agenda-max-entries]] :: limit by number of entries. +- [[doc:org-agenda-max-todos][org-agenda-max-todos]] :: limit by number of TODOs. +- [[doc:org-agenda-max-tags][org-agenda-max-tags]] :: limit by number of tagged entries. +- [[doc:org-agenda-max-effort][org-agenda-max-effort]] :: limit by effort (minutes). + +For example, if you locally set [[doc:org-agenda-max-todos][org-agenda-max-todos]] to 3 in an agenda +view, the agenda will be limited to the first three todos. Other entries +without a TODO keyword or beyond the third TODO headline will be ignored. + +When setting a limit (e.g. about an effort's sum), the default behavior is +to exclude entries that cannot be checked against (e.g. entries that have +no effort property.) To include other entries too, you can set the limit +to a negative number. For example =(setq org-agenda-max-tags -3)= will not +show the fourth tagged headline (and beyond), but it will also show +non-tagged headlines. + +**** =~= in agenda view sets temporary limits + +You can hit =~= in the agenda to temporarily set limits: this will +regenerate the agenda as if the limits were set. This is useful for +example when you want to only see a list of =N= tasks, or a list of tasks +that take only =N= minutes. + +**** "=" in agenda view filters by regular expressions + +You can now filter agenda entries by regular expressions using ~=~. =C-u +== will filter entries out. Regexp filters are cumulative. You can set +[[doc:org-agenda-regexp-filter-preset][org-agenda-regexp-filter-preset]] to suit your needs in each agenda view. + +**** =|= in agenda view resets all filters + +Since it's common to combine tag filters, category filters, and now regexp +filters, there is a new command =|= to reset all filters at once. + +**** Allow writing an agenda to an =.org= file + +You can now write an agenda view to an =.org= file. It copies the +headlines and their content (but not subheadings) into the new file. + +This is useful when you want to quickly share an agenda containing the full +list of notes. + +**** New commands to drag an agenda line forward (=M-=) or backward (=M-=) + +It sometimes handy to move agenda lines around, just to quickly reorganize +your tasks, or maybe before saving the agenda to a file. Now you can use +=M-= and =M-= to move the line forward or backward. + +This does not persist after a refresh of the agenda, and this does not +change the =.org= files who contribute to the agenda. + +**** Use =%b= for displaying "breadcrumbs" in the agenda view + +[[doc:org-agenda-prefix-format][org-agenda-prefix-format]] now allows to use a =%b= formatter to tell Org +to display "breadcrumbs" in the agenda view. + +This is useful when you want to display the task hierarchy in your agenda. + +**** Use =%l= for displaying the headline's level in the agenda view + +[[doc:org-agenda-prefix-format][org-agenda-prefix-format]] allows to use a =%l= formatter to tell Org to +display entries with additional spaces corresponding to their level in the +outline tree. + +**** [[doc:org-agenda-write][org-agenda-write]] will ask before overwriting an existing file + +=M-x org-agenda-write RET= (or =C-c C-w= from an agenda buffer) used to +overwrite preexisting file with the same name without confirmation. It now +asks for a confirmation. + +**** New commands =M-m= and =M-*= to toggle (all) mark(s) for bulk action + +- [[doc:org-agenda-bulk-toggle][org-agenda-bulk-toggle]] :: this command is bound to =M-m= and toggles + the mark of the entry at point. + +- [[doc:org-agenda-bulk-toggle-all][org-agenda-bulk-toggle-all]] :: this command is bound to =M-*= and + toggles all the marks in the current agenda. + +**** New option [[doc:org-agenda-search-view-max-outline-level][org-agenda-search-view-max-outline-level]] + +This option sets the maximum outline level to display in search view. +E.g. when this is set to 1, the search view will only show headlines of +level 1. + +**** New option [[doc:org-agenda-todo-ignore-time-comparison-use-seconds][org-agenda-todo-ignore-time-comparison-use-seconds]] + +This allows to compare times using seconds instead of days when honoring +options like =org-agenda-todo-ignore-*= in the agenda display. + +**** New option [[doc:org-agenda-entry-text-leaders][org-agenda-entry-text-leaders]] + +This allows you to get rid of the ">" character that gets added in front of +entries excerpts when hitting =E= in the agenda view. + +**** New formatting string for past deadlines in [[doc:org-agenda-deadline-leaders][org-agenda-deadline-leaders]] + +The default formatting for past deadlines is ="%2d d. ago: "=, which makes +it explicit that the deadline is in the past. You can configure this via +[[doc:org-agenda-deadline-leaders][org-agenda-deadline-leaders]]. Note that the width of the formatting +string is important to keep the agenda alignment clean. + +**** New allowed value =repeated-after-deadline= for [[doc:org-agenda-skip-scheduled-if-deadline-is-shown][org-agenda-skip-scheduled-if-deadline-is-shown]] + +When [[doc:org-agenda-skip-scheduled-if-deadline-is-shown][org-agenda-skip-scheduled-if-deadline-is-shown]] is set to +=repeated-after-deadline=, the agenda will skip scheduled items if they are +repeated beyond the current deadline. + +**** New option for [[doc:org-agenda-skip-deadline-prewarning-if-scheduled][org-agenda-skip-deadline-prewarning-if-scheduled]] + +This variable may be set to nil, t, the symbol `pre-scheduled', or a number +which will then give the number of days before the actual deadline when the +prewarnings should resume. The symbol `pre-scheduled' eliminates the +deadline prewarning only prior to the scheduled date. + +Read the full docstring for details. + +**** [[doc:org-class][org-class]] now supports holiday strings in the skip-weeks parameter + +For example, this task will now be skipped only on new year's day: + + : * Task + : <%%(org-class 2012 1 1 2013 12 12 2 "New Year's Day")> +*** Capture + +**** Allow =C-1= as a prefix for [[doc:org-agenda-capture][org-agenda-capture]] and [[doc:org-capture][org-capture]] + +With a =C-1= prefix, the capture mechanism will use the =HH:MM= value at +point (if any) or the current =HH:MM= time as the default time for the +capture template. + +**** Expand keywords within %(sexp) placeholder in capture templates + +If you use a =%:keyword= construct within a =%(sexp)= construct, Org will +expand the keywords before expanding the =%(sexp)=. + +**** Allow to contextualize capture (and agenda) commands by checking the name of the buffer + +[[doc:org-capture-templates-contexts][org-capture-templates-contexts]] and [[doc:org-agenda-custom-commands-contexts][org-agenda-custom-commands-contexts]] +allow you to define what capture templates and what agenda commands should +be available in various contexts. It is now possible for the context to +check against the name of the buffer. +*** Tag groups + +Using =#+TAGS: { Tag1 : Tag2 Tag3 }= will define =Tag1= as a /group tag/ +(note the colon after =Tag1=). If you search for =Tag1=, it will return +headlines containing either =Tag1=, =Tag2= or =Tag3= (or any combination +of those tags.) + +You can use group tags for sparse tree in an Org buffer, for creating +agenda views, and for filtering. + +See https://orgmode.org/org.html#Tag-groups for details. + +*** Links + +**** =C-u C-u M-x org-store-link RET= will ignore non-core link functions + +Org knows how to store links from Org buffers, from info files and from +other Emacs buffers. Org can be taught how to store links from any buffer +through new link protocols (see [[https://orgmode.org/org.html#Adding-hyperlink-types]["Adding hyperlink types"]] in the manual.) + +Sometimes you want Org to ignore added link protocols and store the link +as if the protocol was not known. + +You can now do this with =C-u C-u M-x org-store-link RET=. + +**** =C-u C-u C-u M-x org-store-link RET= on an active region will store links for each lines + +Imagine for example that you want to store a link for every message in a +Gnus summary buffer. In that case =C-x h C-u C-u C-u M-x org-store-link +RET= will store a link for every line (i.e. message) if the region is +active. + +**** =C-c C-M-l= will add a default description for links which don't have one + +=C-c C-M-l= inserts all stored links. If a link does not have a +description, this command now adds a default one, so that we are not mixing +with-description and without-description links when inserting them. + +**** No curly braces to bracket links within internal links + +When storing a link to a headline like + +: * See [[https://orgmode.org][Org website]] + +[[doc:org-store-link][org-store-link]] used to convert the square brackets into curly brackets. +It does not anymore, taking the link description or the link path, when +there is no description. +*** Table + +**** Switching between #+TBLFM lines + +If you have several =#+TBLFM= lines below a table, =C-c C-c= on a line will +apply the formulas from this line, and =C-c C-c= on another line will apply +those other formulas. + +**** You now use "nan" for empty fields in Calc formulas + +If empty fields are of interest, it is recommended to reread the section +[[https://orgmode.org/org.html#Formula-syntax-for-Calc][3.5.2 Formula syntax for Calc]] of the manual because the description for the +mode strings has been clarified and new examples have been added towards +the end. + +**** Handle localized time-stamps in formulas evaluation + +If your =LOCALE= is set so that Org time-stamps use another language than +english, and if you make time computations in Org's table, it now works by +internally converting the time-stamps with a temporary =LOCALE=C= before +doing computation. + +**** New lookup functions + +There are now three lookup functions: + +- [[doc:org-loopup-first][org-loopup-first]] +- [[doc:org-loopup-last][org-loopup-last]] +- [[doc:org-loopup-all][org-loopup-all]] + +See [[https://orgmode.org/org.html#Lookup-functions][the manual]] for details. +*** Startup keywords + +These new startup keywords are now available: + +| Startup keyword | Option | +|----------------------------------+---------------------------------------------| +| =#+STARTUP: logdrawer= | =(setq org-log-into-drawer t)= | +| =#+STARTUP: nologdrawer= | =(setq org-log-into-drawer nil)= | +|----------------------------------+---------------------------------------------| +| =#+STARTUP: logstatesreversed= | =(setq org-log-states-order-reversed t)= | +| =#+STARTUP: nologstatesreversed= | =(setq org-log-states-order-reversed nil)= | +|----------------------------------+---------------------------------------------| +| =#+STARTUP: latexpreview= | =(setq org-startup-with-latex-preview t)= | +| =#+STARTUP: nolatexpreview= | =(setq org-startup-with-latex-preview nil)= | + +*** Clocking + +**** New option [[doc:org-clock-rounding-minutes][org-clock-rounding-minutes]] + +E.g. if [[doc:org-clock-rounding-minutes][org-clock-rounding-minutes]] is set to 5, time is 14:47 and you +clock in: then the clock starts at 14:45. If you clock out within the next +5 minutes, the clock line will be removed; if you clock out 8 minutes after +your clocked in, the clock out time will be 14:50. + +**** New option [[doc:org-time-clocksum-use-effort-durations][org-time-clocksum-use-effort-durations]] + +When non-nil, =C-c C-x C-d= uses effort durations. E.g., by default, one +day is considered to be a 8 hours effort, so a task that has been clocked +for 16 hours will be displayed as during 2 days in the clock display or in +the clocktable. + +See [[doc:org-effort-durations][org-effort-durations]] on how to set effort durations and +[[doc:org-time-clocksum-format][org-time-clocksum-format]] for more on time clock formats. + +**** New option [[doc:org-clock-x11idle-program-name][org-clock-x11idle-program-name]] + +This allows to set the name of the program which prints X11 idle time in +milliseconds. The default is to use =x11idle=. + +**** New option [[doc:org-use-last-clock-out-time-as-effective-time][org-use-last-clock-out-time-as-effective-time]] + +When non-nil, use the last clock out time for [[doc:org-todo][org-todo]]. Note that this +option has precedence over the combined use of [[doc:org-use-effective-time][org-use-effective-time]] and +[[doc:org-extend-today-until][org-extend-today-until]]. + +**** =S-= on a clocksum column will update the sum by updating the last clock +**** =C-u 3 C-S-= will update clock timestamps synchronously by 3 units +**** New parameter =:wstart= for clocktables to define the week start day +**** New parameter =:mstart= to state the starting day of the month +**** Allow relative times in clocktable tstart and tend options +**** The clocktable summary is now a caption +**** =:tstart= and =:tend= and friends allow relative times like "<-1w>" or "" +*** Babel + +**** You can now use =C-c C-k= for [[doc:org-edit-src-abort][org-edit-src-abort]] + +This allows you to quickly cancel editing a source block. + +**** =C-u C-u M-x org-babel-tangle RET= tangles by the target file of the block at point + +This is handy if you want to tangle all source code blocks that have the +same target than the block at point. + +**** New options for auto-saving the base buffer or the source block editing buffer + +When [[doc:org-edit-src-turn-on-auto-save][org-edit-src-turn-on-auto-save]] is set to =t=, editing a source block +in a new window will turn on =auto-save-mode= and save the code in a new +file under the same directory than the base Org file. + +When [[doc:org-edit-src-auto-save-idle-delay][org-edit-src-auto-save-idle-delay]] is set to a number of minutes =N=, +the base Org buffer will be saved after this number of minutes of idle +time. + +**** New =:post= header argument post-processes results + + This header argument may be used to pass the results of the current + code block through another code block for post-processing. See the + manual for a usage example. + +**** Commented out heading are ignored when collecting blocks for tangling + +If you comment out a heading (with =C-c ;= anywhere on the heading or in +the subtree), code blocks from within this heading are now ignored when +collecting blocks for tangling. + +**** New option [[doc:org-babel-hash-show-time][org-babel-hash-show-time]] to show a time-stamp in the result hash +**** Do not ask for confirmation if cached value is current + +Do not run [[doc:org-babel-confirm-evaluate][org-babel-confirm-evaluate]] if source block has a cache and the +cache value is current as there is no evaluation involved in this case. +**** =ob-sql.el= and =ob-python.el= have been improved. +**** New Babel files only need to =(require 'ob)= + +When writing a new Babel file, you now only need to use =(require 'ob)= +instead of requiring each Babel library one by one. +*** Faces + +- Org now fontifies radio link targets by default +- In the agenda, use [[doc:org-todo-keyword-faces][org-todo-keyword-faces]] to highlight selected TODO keywords +- New face [[doc:org-priority][org-priority]], enhanced fontification of priority cookies in agenda +- New face [[doc:org-tag-group][org-tag-group]] for group tags + +** Miscellaneous + +- New speedy key =s= pour [[doc:org-narrow-to-subtree][org-narrow-to-subtree]] +- Handling of [[doc:org-html-table-row][org-html-table-row]] has been updated (incompatible change) +- [[doc:org-export-html-table-tag][org-export-html-table-tag]] is replaced by [[doc:org-html-table-default-attributes][org-html-table-default-attributes]] +- Support using =git-annex= with Org attachments +- org-protocol: Pass optional value using query in url to capture from protocol +- When the refile history is empty, use the current filename as default +- When you cannot change the TODO state of a task, Org displays the blocking task +- New option [[doc:org-mobile-allpriorities][org-mobile-allpriorities]] +- org-bibtex.el now use =visual-line-mode= instead of the deprecated =longlines-mode= +- [[doc:org-format-latex-options][org-format-latex-options]] allows to set the foreground/background colors automatically +- New option [[doc:org-archive-file-header-format][org-archive-file-header-format]] +- New "neg" entity in [[doc:org-entities][org-entities]] +- New function [[doc:org-docview-export][org-docview-export]] to export docview links +- New =:eps= header argument for ditaa code blocks +- New option [[doc:org-gnus-no-server][org-gnus-no-server]] to start Gnus with =gnus-no-server= +- Org is now distributed with =htmlize.el= version 1.43 +- ~org-drill.el~ has been updated to version 2.3.7 +- ~org-mac-iCal.el~ now supports OS X versions up to 10.8 +- Various improvements to ~org-contacts.el~ and =orgpan.el= + +** Outside Org + +*** Spanish translation of the Org guide by David Arroyo Menéndez + +David (and others) translated the Org compact guide in spanish: + +You can read the [[https://orgmode.org/worg/orgguide/orgguide.es.pdf][PDF guide]]. + +*** ~poporg.el~ and ~outorg.el~ + +Two new libraries (~poporg.el~ by François Pinard and ~outorg.el~ by +Thorsten Jolitz) now enable editing of comment-sections from source-code +buffers in temporary Org-mode buffers, making the full editing power of +Org-mode available. ~outorg.el~ comes together with ~outshine.el~ and +~navi-mode.el~, two more libraries by Thorsten Jolitz with the goal to give +source-code buffers the /look & feel/ of Org-mode buffers while greatly +improving navigation and structure editing. A detailed description can be +found here: https://orgmode.org/worg/org-tutorials/org-outside-org.html + +Here are two screencasts demonstrating Thorsten's tools: + +- [[http://youtu.be/nqE6YxlY0rw]["Modern conventions for Emacs Lisp files"]] +- [[http://www.youtube.com/watch?v%3DII-xYw5VGFM][Exploring Bernt Hansen's Org-mode tutorial with 'navi-mode']] + +*** MobileOrg for iOS + +MobileOrg for iOS back in the App Store The 1.6.0 release was focused on +the new Dropbox API and minor bug fixes but also includes a new ability to +launch in Capture mode. Track development and contribute [[https://github.com/MobileOrg/mobileorg/issues][on github]]. + +* Version 7.9.3 + +** New option [[doc::org-agenda-use-tag-inheritance][org-agenda-use-tag-inheritance]] + +[[doc::org-use-tag-inheritance][org-use-tag-inheritance]] controls whether tags are inherited when +org-tags-view is called (either in =tags=, =tags-tree= or =tags-todo= +agenda views.) + +When generating other agenda types such as =agenda=, =todo= and +=todo-tree=, tags inheritance is not used when selecting the entries +to display. Still, you might want to have all tag information correct +in the agenda buffer, e.g. for tag filtering. In that case, add the +agenda type to this variable. + +Setting this variable to nil should considerably speeds up the agenda +generation. + +Note that the default was to display inherited tags in the agenda +lines even if `org-use-tag-inheritance' was nil. The default is now +to *never* display inherited tags in agenda lines, but to /know/ about +them when the agenda type is listed in [[doc::org-agenda-use-tag-inheritance][org-agenda-use-tag-inheritance]]. + +** New default value nil for [[doc::org-agenda-dim-blocked-tasks][org-agenda-dim-blocked-tasks]] + +Using `nil' as the default value speeds up the agenda generation. You +can hit `#' (or `C-u #') in agenda buffers to temporarily dim (or turn +invisible) blocked tasks. + +** New speedy keys for [[doc::org-speed-commands-default][org-speed-commands-default]] + +You can now use `:' (instead of `;') for setting tags---this is +consistent with using the `:' key in agenda view. + +You can now use `=' for [[doc::org-columns][org-columns]]. + +** =org-float= is now obsolete, use =diary-float= instead +** No GPL manual anymore + +There used to be a GPL version of the Org manual, but this is not the +case anymore, the Free Software Foundation does not permit this. + +The GNU FDL license is now included in the manual directly. + +** Enhanced compatibility with Emacs 22 and XEmacs + +Thanks to Achim for his work on enhancing Org's compatibility with +various Emacsen. Things may not be perfect, but Org should work okay +in most environments. + +* Version 7.9.2 + +** New ELPA repository for Org packages + +You can now add the Org ELPA repository like this: + +#+BEGIN_SRC emacs-lisp +(add-to-list 'package-archives '("org" . "https://orgmode.org/elpa/") t) +#+END_SRC + +It contains both the =org-*.tar= package (the core Org distribution, also +available through https://elpa.gnu.org) and the =org-plus*.tar= package (the +extended Org distribution, with non-GNU packages from the =contrib/= +directory.) + +See https://orgmode.org/elpa/ + +** Overview of the new keybindings + + | Keybinding | Speedy | Command | + |-----------------+--------+-----------------------------| + | =C-c C-x C-z= | | [[doc::org-clock-resolve][org-clock-resolve]] | + | =C-c C-x C-q= | | [[doc::org-clock-cancel][org-clock-cancel]] | + | =C-c C-x C-x= | | [[doc::org-clock-in-last][org-clock-in-last]] | + | =M-h= | | [[doc::org-mark-element][org-mark-element]] | + | =*= | | [[doc::org-agenda-bulk-mark-all][org-agenda-bulk-mark-all]] | + | =C-c C-M-l= | | [[doc::org-insert-all-links][org-insert-all-links]] | + | =C-c C-x C-M-v= | | [[doc::org-redisplay-inline-images][org-redisplay-inline-images]] | + | =C-c C-x E= | =E= | [[doc::org-inc-effort][org-inc-effort]] | + | | =#= | [[doc::org-toggle-comment][org-toggle-comment]] | + | | =:= | [[doc::org-columns][org-columns]] | + | | =W= | Set =APPT_WARNTIME= | + | =k= | | [[doc::org-agenda-capture][org-agenda-capture]] | + | C-c , | , | [[doc::org-priority][org-priority]] | + +** New package and Babel language + +*** =org-eshell.el= by Konrad Hinsen is now in Org + + =org-eshell.el= allows you to create links from [[https://www.gnu.org/software/emacs/manual/html_node/eshell/index.html][Eshell]]. + +*** Support for execution of Scala code blocks (see ob-scala.el) +*** Support for execution of IO code blocks (see ob-io.el) + +** Incompatible changes + + - If your code relies on =org-write-agenda=, please use + [[doc::org-agenda-write][org-agenda-write]] from now on. + + - If your code relies on =org-make-link=, please use =concat= + instead. + + - =org-link-to-org-use-id= has been renamed to + =org-id-link-to-org-use-id= and its default value is nil. The + previous default was =create-if-interactive-and-no-custom-id=. + +** New features and user-visible changes + +*** Org Element + + =org-element.el= is a toolbox for parsing and analyzing "elements" + in an Org-mode buffer. This has been written by Nicolas Goaziou + and has been tested for quite some time. It is now part of Org's + core and many core functions rely on this package. + + Two functions might be particularly handy for users: + =org-element-at-point= and =org-element-context=. + + See the docstrings for more details. + + Below is a list of editing and navigating commands that now rely + on =org-element.el=. + +**** [[doc::org-fill-paragraph][org-fill-paragraph]] has been completely rewritten + + The filling mechanisms now rely on org-element, trying to do the + right thing on each element in various contexts. E.g. filling in + a list item will preserve indentation; filling in message-mode + will fall back on the relevant filling functions; etc. + +**** [[doc::org-metaup][org-metaup]] and [[doc::org-metadown][org-metadown]] will drag the element backward/forward + + If you want to get the old behavior (i.e. moving a line up and + down), you can first select the line as an active region, then + =org-metaup= or =org-metadown= to move the region backward or + forward. This also works with regions bigger than just one line. + +**** [[doc::org-up-element][org-up-element]] and [[doc::org-down-element][org-down-element]] (respectively =C-c C-^= and =C-c C-_=) + + This will move the point up/down in the hierarchy of elements. + +**** [[doc::org-backward-element][org-backward-element]] and [[doc::org-forward-element][org-forward-element]] (respectively =M-{= and =M-}=) + + This will move the point backward/forward in the hierarchy of + elements. + +**** [[doc::org-narrow-to-element][org-narrow-to-element]] will narrow to the element at point +**** [[doc::org-mark-element][org-mark-element]] will mark the element at point + + This command is bound to =M-h= and will mark the element at + point. If the point is at a paragraph, it will mark the + paragraph. If the point is at a list item, it will mark the list + item. Etc. + + Note that if point is at the beginning of a list, it will mark + the whole list. + + To mark a subtree, you can either use =M-h= on the headline + (since there is no ambiguity about the element you're at) or + [[doc::org-mark-subtree][org-mark-subtree]] (=C-c @=) anywhere in the subtree. + + Invoking [[doc::org-mark-element][org-mark-element]] repeatedly will try to mark the next + element on top of the previous one(s). E.g. hitting =M-h= twice + on a headline will mark the current subtree and the next one on + the same level. + +*** Org Agenda + +**** New option [[doc::org-agenda-sticky][org-agenda-sticky]] + + There is a new option =org-agenda-sticky= which enables "sticky" + agendas. Sticky agendas remain opened in the background so that + you don't need to regenerate them each time you hit the + corresponding keystroke. This is a big time saver. + + When [[doc::org-agenda-sticky][org-agenda-sticky]] is =non-nil=, the agenda buffer will be + named using the agenda key and its description. In sticky + agendas, the =q= key will just bury the agenda buffers and + further agenda commands will show existing buffer instead of + generating new ones. + + If [[doc::org-agenda-sticky][org-agenda-sticky]] is set to =nil=, =q= will kill the single + agenda buffer. + +**** New option [[doc::org-agenda-custom-commands-contexts][org-agenda-custom-commands-contexts]] + + Setting this option allows you to define specific context where + agenda commands should be available from. For example, when set + to this value + + #+BEGIN_SRC emacs-lisp + (setq org-agenda-custom-commands-contexts + '(("p" (in-file . "\\.txt")))) +#+END_SRC + + then the =p= agenda command will only be available from buffers + visiting *.txt files. See the docstring and the manual for more + details on how to use this. + +**** Changes in bulk actions + + The set of commands starting with =k ...= as been deleted and the + features have been merged into the "bulk action" feature. + + After you marked some entries in the agenda, if you call =B s=, + the agenda entries will be rescheduled using the date at point if + on a date header. If you are on an entry with a timestamp, you + will be prompted for a date to reschedule your marked entries to, + using the timestamp at point as the default prompt. + + You can now use =k= to capture the marked entry and use the date + at point as an overriding date for the capture template. + + To bind this behavior to =M-x org-capture RET= (or its + keybinding), set the new option [[doc::org-capture-use-agenda-date][org-capture-use-agenda-date]] to + =t=. + +**** =N= and =P= in the agenda will move to the next/previous item + +**** New command [[doc::org-agenda-bulk-mark-all][org-agenda-bulk-mark-all]] to mark all items + + This new command is bound to =*= in agenda mode. + + There is also a new option [[doc::org-agenda-bulk-mark-char][org-agenda-bulk-mark-char]] to set the + character to use as a mark for bulk actions. + +**** New option [[doc::org-agenda-persistent-marks][org-agenda-persistent-marks]] + + When set to =non-nil=, marks will remain visible after a bulk + action. You can temporarily toggle this by pressing =p= when + invoking [[doc::org-agenda-bulk-action][org-agenda-bulk-action]]. Marks are deleted if your + rebuild the agenda buffer or move to another date/span (e.g. with + =f= or =w=). + +**** New option [[doc::org-agenda-skip-timestamp-if-deadline-is-shown][org-agenda-skip-timestamp-if-deadline-is-shown]] + + =Non-nil= means skip timestamp line if same entry shows because + of deadline. + + In the agenda of today, an entry can show up multiple times + because it has both a plain timestamp and has a nearby deadline. + When this variable is t, then only the deadline is shown and the + fact that the entry has a timestamp for or including today is not + shown. When this variable is =nil=, the entry will be shown + several times. + +**** New =todo-unblocked= and =nottodo-unblocked= skip conditions + + See the [[https://orgmode.org/cgit.cgi/org-mode.git/commit/?id=f426da][git commit]] for more explanations. + +**** Allow category filtering in the agenda + + You can now filter the agenda by category. Pressing "<" will + filter by the category of the item on the current line, and + pressing "<" again will remove the filter. You can combine tag + filters and category filters. + + You can use =org-agenda-category-filter= in your custom agenda + views and =org-agenda-category-filter-preset= in your main + configuration. + + See also the new command [[doc::org-agenda-filter-by-top-category][org-agenda-filter-by-top-category]]: + hitting =^= will filter by "Top" category: only show entries that + are of the same category than the Top category of the entry at + point. + +*** Org Links + +**** Inserting links + + When inserting links through [[doc::org-insert-link][org-insert-link]], the description is + now displayed first, followed by the literal link, as the + description is often more useful when you look for the link you + want to insert. + + Completion now complete both literal links and description. If + you complete a description, the literal link and its description + will be inserted directly, whereas when you complete the literal + link, you will be prompted for a description (as with Org 7.8.) + + In the completion buffer, links to the current buffer are now + highlighted. + +**** New templates =%h= and =%(sexp)= for abbreviated links + + On top of =%s= template, which is replaced by the link tag in + abbreviated links, you can now use =%h= (which does the same than =%s= + but does not hexify the tag) and =%(sexp)= (which can run a function + that takes the tag as its own argument.) + +**** New link type =help= + + You can now create links from =help= buffers. + + For example, if you request help for the command [[doc::org-agenda][org-agenda]] with + =C-h f org-agenda RET=, creating a link from this buffer will let + you go back to the same buffer. + +**** New command [[doc::org-insert-all-links][org-insert-all-links]] + + This will insert all links as list items. With a universal + prefix argument, links will not be deleted from the variable + =org-stored-links=. + + This new command is bound to =C-c C-M-l=. + +**** New option [[doc::org-url-hexify-p][org-url-hexify-p]] + + When set to =nil=, the =URL= part of a link will not be hexified. + +**** Org can now open multiple shell links + +**** New option [[doc::org-doi-server-url][org-doi-server-url]] to specify an alternate DOI server + +**** RET now follows time stamps links + +*** Org Editing + +**** [[doc::org-todo][org-todo]] and =org-archive-*= can now loop in the active region + + When [[doc::org-loop-over-headlines-in-active-region][org-loop-over-headlines-in-active-region]] is =non-nil=, using + [[doc::org-todo][org-todo]] or =org-archive-*= commands in the active region will + loop over headlines. This is handy if you want to set the TODO + keyword for several items, or archive them quickly. + +**** You can now set tags for headlines in a region + + If [[doc::org-loop-over-headlines-in-active-region][org-loop-over-headlines-in-active-region]] is =non-nil=, then + selecting the region and hitting =C-c C-q= will set the tags for + all headlines in the region. + +**** New command [[doc::org-insert-drawer][org-insert-drawer]] to insert a drawer interactively + +**** Comments start with "^[ \t]*# " anywhere on a line + + Note that the space after the hashtag is mandatory. Comments + with "^#+" are not supported anymore. + +**** New speed key =#= to toggle the COMMENT cookie on a headline + +**** =indent-region-function= is now set to [[doc::org-indent-region][org-indent-region]] + + =C-M-\= should now produce useful results. + + You can unindent the buffer with [[doc::org-unindent-buffer][org-unindent-buffer]]. + +**** New option [[doc::org-allow-promoting-top-level-subtree][org-allow-promoting-top-level-subtree]] + + When =non-nil=, =S-M-= will promote level-1 subtrees + containing other subtrees. The level-1 headline will be + commented out. You can revert to the previous state with =M-x + undo RET=. + +*** Org Clock + +**** New keybinding =C-c C-x C-z= for [[doc::org-clock-resolve][org-clock-resolve]] + +**** New keybinding =C-c C-x C-q= for [[doc::org-clock-cancel][org-clock-cancel]] + +**** New command [[doc::org-clock-in-last][org-clock-in-last]] to clock in the last clocked item + + This command is bound to =C-c C-x C-x= and will clock in the last + clocked entry, if any. + +**** =C-u M-x= [[doc::org-clock-out][org-clock-out]] =RET= now prompts for a state to switch to + +**** =S-M-= on a clock timestamps adjusts the previous/next clock + +**** New option [[doc::org-clock-continuously][org-clock-continuously]] + + When set to =nil=, clocking in a task will first try to find the + last clocked out task and restart from when that task was clocked + out. + + You can temporarily activate continuous clocking with =C-u C-u + C-u M-x= [[doc::org-clock-in][org-clock-in]] =RET= (three universal prefix arguments) + and =C-u C-u M-x= [[org-clock-in-last][org-clock-in-last]] =RET= (two universal prefix + arguments). + + +**** New option [[doc::org-clock-frame-title-format][org-clock-frame-title-format]] + + This option sets the value of =frame-title-format= when clocking + in. + +**** New options for controlling the clockreport display + + [[doc::org-clock-file-time-cell-format][org-clock-file-time-cell-format]]: Format string for the file time + cells in clockreport. + + [[doc::org-clock-total-time-cell-format][org-clock-total-time-cell-format]]: Format string for the total + time cells in clockreport. + + +**** New options for controlling the clock/timer display + + [[doc::org-clock-clocked-in-display][org-clock-clocked-in-display]]: control whether the current clock + is displayed in the mode line and/or frame title. + + [[doc::org-timer-display][org-timer-display]]: control whether the current timer is displayed + in the mode line and/or frame title. + + This allows the clock and timer to be displayed in the frame + title instead of, or as well as, the mode line. This is useful + for people with limited space in the mode line but with ample + space in the frame title. + +*** Org Appearance + +**** New option [[doc::org-custom-properties][org-custom-properties]] + + The visibility of properties listed in this options can be turn + on/off with [[doc::org-toggle-custom-properties-visibility][org-toggle-custom-properties-visibility]]. This might + be useful for properties used by third-part tools or that you + don't want to see temporarily. + +**** New command [[doc::org-redisplay-inline-images][org-redisplay-inline-images]] + + This will redisplay all images. It is bound to =C-c C-x C-M-v=. + +**** New entities in =org-entities.el= + + There are these new entities: + + : ("tilde" "\\~{}" nil "˜" "~" "~" "~") + : ("slash" "/" nil "/" "/" "/" "/") + : ("plus" "+" nil "+" "+" "+" "+") + : ("under" "\\_" nil "_" "_" "_" "_") + : ("equal" "=" nil "=" "=" "=" "=") + : ("asciicirc" "\\textasciicircum{}" nil "^" "^" "^" "^") + +**** New face =org-list-dt= for definition terms +**** New face =org-date-selected= for the selected calendar day +**** New face value for =org-document-title= + + The face is back to a normal height. + +*** Org Columns + +**** New speed command =:= to activate the column view +**** New special property =CLOCKSUM_T= to display today's clocked time + + You can use =CLOCKSUM_T= the same way you use =CLOCKSUM=. It + will display the time spent on tasks for today only. + +**** Use the =:COLUMNS:= property in columnview dynamic blocks + + If the =:COLUMNS:= is set in a subtree, the columnview dynamic + block will use its value as the column format. + +**** Consider inline tasks when computing a sum + +*** Org Dates and Time Stamps + +**** Enhanced [[doc::org-sparse-tree][org-sparse-tree]] + + =C-c /= can now check for time ranges. + + When checking for dates with =C-c /= it is useful to change the + type of dates that you are interested in. You can now do this + interactively with =c= after =C-c /= and/or by setting + [[doc::org-sparse-tree-default-date-type][org-sparse-tree-default-date-type]] to the default value you want. + +**** Support for hourly repeat cookies + + You can now use + + : SCHEDULED: <2012-08-20 lun. 08:00 +1h> + + if you want to add an hourly repeater to an entry. + +**** =C-u C-u C-c .= inserts a time-stamp with no prompt + +**** When (setq [[doc::org-read-date-prefer-future][org-read-date-prefer-future]] 'time), accept days in the prompt + + "8am Wed" and "Wed 8am" are now acceptable values when entering a + date from the prompt. If [[doc::org-read-date-prefer-future][org-read-date-prefer-future]] is set to + =time=, this will produce the expected prompt indication. + +**** New option [[doc::org-datetree-add-timestamp][org-datetree-add-timestamp]] + + When set to =non-nil=, datetree entries will also have a + timestamp. This is useful if you want to see these entries in a + sparse tree with =C-c /=. + +*** Org Capture + +**** New command [[doc::org-capture-string][org-capture-string]] + + M-x [[doc::org-capture-string][org-capture-string]] RET will prompt for a string and a capture + template. The string will be used as an annotation for the + template. This is useful when capturing in batch mode as it lets + you define the content of the template without being in Emacs. + +**** New option [[doc::org-capture-templates-contexts][org-capture-templates-contexts]] + + Setting this option allows you to define specific context where + capture templates should be available from. For example, when + set to this value + + #+BEGIN_SRC emacs-lisp + (setq org-capture-templates-contexts + '(("c" (in-mode . "message-mode")))) +#+END_SRC + + then the =c= capture template will only be available from + =message-mode= buffers. See the docstring and the manual for + more details on how to use this. + +**** New =%l= template to insert the literal link +**** New option [[doc::org-capture-bookmark][org-capture-bookmark]] + + Org used to automatically add a bookmark with capture a note. + You can now turn this on by setting [[doc::org-capture-bookmark][org-capture-bookmark]] to + =nil=. + +**** Expand =%= escape sequences into text entered for 'th =%^{PROMPT}= escape + + See the manual for more explanations. + +**** More control over empty lines + + You can use =:empty-lines-before= and =:empty-lines-after= to + control the insertion of empty lines. Check the manual for more + explanations. + +**** New hook [[doc::org-capture-prepare-finalize-hook][org-capture-prepare-finalize-hook]] + + This new hook runs before the finalization process starts. + +*** Org Export + +**** New functions =orgtbl-to-table.el= and =orgtbl-to-unicode= + + =orgtbl-to-table.el= convert the table to a =table.el= table, and + =orgtbl-to-unicode= will use =ascii-art-to-unicode.el= (when + available) to print beautiful tables. + +**** [[doc::org-table-export][org-table-export]] now a bit clever about the target format + + When you specify a file name like =table.csv=, [[doc::org-table-export][org-table-export]] + will now suggest =orgtbl-to-csv= the default method for exporting + the table. + +**** New option [[doc::org-export-date-timestamp-format][org-export-date-timestamp-format]] + + The option allows to set a time string format for Org timestamps + in the #+DATE option. + +**** LaTeX: New options for exporting table rules :tstart, :hline and :tend + + See [[doc::org-export-latex-tables-hline][org-export-latex-tables-hline]] and [[doc::org-export-latex-tables-tend][org-export-latex-tables-tend]]. + +**** LaTeX: You can now set =:hfmt= from =#+ATTR_LaTeX= +**** Beamer: Add support and keybinding for the =exampleblock= environment + + Add support for these languages in [[doc::org-export-language-setup][org-export-language-setup]]. + More languages are always welcome. + +**** Beamer: New option [[doc::org-beamer-inherited-properties][org-beamer-inherited-properties]] + + This option allows Beamer export to inherit some properties. + Thanks to Carsten for implementing this. + +**** ODT: Add support for ODT export in org-bbdb.el +**** ODT: Add support for indented tables (see [[https://orgmode.org/cgit.cgi/org-mode.git/commit/?id=e9fd33][this commit]] for details) +**** ODT: Improve the conversion from ODT to other formats +**** ASCII: Swap the level-1/level-2 characters to underline the headlines +**** Support for Chinese, simplified Chinese, Russian, Ukrainian and Japanese +**** HTML: New option [[doc::org-export-html-date-format-string][org-export-html-date-format-string]] + + Format string to format the date and time in HTML export. Thanks + to Sébastien Vauban for this patch. + +*** Org Babel + +**** New =:results drawer= parameter + +=:results drawer= replaces =:results wrap=, which is deprecated but still +supported. + +**** =:results org= now put results in a =#+BEGIN_SRC org= block + +=:results org= used to put results in a =#+BEGIN_ORG= block but it now puts +results in a =#+BEGIN_SRC org= block, with comma-escaped lines. + +=#+BEGIN_ORG= blocks are obsolete. + +**** Exporting =#+BEGIN_SRC org= blocks exports the code + +It used to exports the results of the code. + +*** Miscellaneous + +**** New menu entry for [[doc::org-refile][org-refile]] +**** Allow capturing to encrypted entries + +If you capture to an encrypted entry, it will be decrypted before +inserting the template then re-encrypted after finalizing the capture. + +**** Inactive timestamps are now handled in tables + +Calc can do computation on active time-stamps like <2012-09-29 sat.>. +Inactive time-stamps in a table's cell are now internally deactivated so +that Calc formulas can operate on them. + +**** [[doc::org-table-number-regexp][org-table-number-regexp]] can now accept comma as decimal mark +**** Org allows a new property =APPT_WARNTIME= + + You can set it with the =W= speedy key or set it manually. When + set, exporting to iCalendar and [[doc::org-agenda-to-appt][org-agenda-to-appt]] will use the + value of this property as the number of minutes for the warning + alarm. + +**** New command [[doc::org-inc-effort][org-inc-effort]] + + This will increment the effort value. + + It is bound to =C-c C-x E= and to =E= as a speedy command. + +**** Attach: Add support for creating symbolic links + + =org-attach-method= now supports a new method =lns=, allowing to + attach symbolic links. + +**** Archive: you can now archive to a datetree + +**** New option [[doc::org-inlinetask-show-first-star][org-inlinetask-show-first-star]] + + =Non-nil= means display the first star of an inline task as + additional marker. When =nil=, the first star is not shown. + +**** New option [[doc::org-latex-preview-ltxpng-directory][org-latex-preview-ltxpng-directory]] + + This lets you define the path for the =ltxpng/= directory. + +**** You can now use imagemagick instead of dvipng to preview LaTeX fragments +**** You can now turn off [[doc::orgstruct++-mode][orgstruct++-mode]] safely +**** =C-u C-c C-c= on list items to add check boxes + + =C-u C-c C-c= will add an empty check box on a list item. + + When hit from the top of the list, it will add check boxes for + all top level list items. + +**** =org-list-ending-method= and =org-list-end-regexp= are now obsolete + + Fall back on using =org-list-end-re= only, which see. + +**** org-feed.el now expands =%(sexp)= templates +**** New option [[doc::org-protocol-data-separator][org-protocol-data-separator]] + +**** New option [[doc::org-ditaa-jar-option][org-ditaa-jar-option]] to specify the ditaa jar file + +**** New possible value for [[doc::org-loop-over-headlines-in-active-region][org-loop-over-headlines-in-active-region]] + + When [[doc::org-loop-over-headlines-in-active-region][org-loop-over-headlines-in-active-region]] is set to + =start-level=, the command will loop over the active region but + will only act upon entries that are of the same level than the + first headline in the region. + +**** New option [[doc::org-habit-show-all-today][org-habit-show-all-today]] + + When set to =t=, show all (even unscheduled) habits on today's + agenda. + +** Important bug fixes + +*** M-TAB on options keywords perform completion correctly again + + If you hit =M-TAB= on keywords like =#+TITLE=, Org will try to + perform completion with meaningful values. + +*** Add licenses to javascript embedded and external code snippets + + Embedded javascript code produced when exporting an Org file to + HTML is now licensed under GPLv3 (or later), and the copyright is + owned by the Free Software Foundation, Inc. + + The javascript code for embedding MathJax in the browser mentions + the MathJax copyright and the Apache 2.0 license. + + The javascript code for embedding =org-injo.js= in the browser + mentions the copyright of Sebastian Rose and the GPLv3 (or later) + license. + + =org-export-html-scripts= is now a variable, so that you can adapt + the code and the license to your needs. + + See https://www.gnu.org/philosophy/javascript-trap.html for + explanations on why these changes were necessary. + +* Version 7.8.11 + +** Incompatible changes + +*** Emacs 21 support has been dropped + + Do not use Org mode 7.xx with Emacs 21, use [[https://orgmode.org/org-6.36c.zip][version 6.36c]] instead. + +*** XEmacs support requires the XEmacs development version + + To use Org mode 7.xx with XEmacs, you need to run the developer + version of XEmacs. We were about to drop XEmacs support entirely, + but Michael Sperber stepped in and made changes to XEmacs that + made it easier to keep the support. Thanks to Michael for this + last-minute save. + +*** New keys for TODO sparse trees + + The key =C-c C-v= is now reserved for Org Babel action. TODO + sparse trees can still be made with =C-c / t= (all not-done + states) and =C-c / T= (specific states). + +*** The Agenda =org-agenda-ndays= is now obsolete + + The variable =org-agenda-ndays= is obsolete - please use + =org-agenda-span= instead. + + Thanks to Julien Danjou for this. + +*** Changes to the intended use of =org-export-latex-classes= + + So far this variable has been used to specify the complete header + of the LaTeX document, including all the =\usepackage= calls + necessary for the document. This setup makes it difficult to + maintain the list of packages that Org itself would like to call, + for example for the special symbol support it needs. + + First of all, you can *opt out of this change* in the following + way: You can say: /I want to have full control over headers, and I + will take responsibility to include the packages Org needs/. If + that is what you want, add this to your configuration and skip the + rest of this section (except maybe for the description of the + =[EXTRA]= place holder): + + #+begin_src emacs-lisp + (setq org-export-latex-default-packages-alist nil + org-export-latex-packages-alist nil) + #+end_src + + /Continue to read here if you want to go along with the modified + setup./ + + There are now two variables that should be used to list the LaTeX + packages that need to be included in all classes. The header + definition in =org-export-latex-classes= should then not contain + the corresponding =\usepackage= calls (see below). + + The two new variables are: + + 1. =org-export-latex-default-packages-alist= :: This is the + variable where Org-mode itself puts the packages it needs. + Normally you should not change this variable. The only + reason to change it anyway is when one of these packages + causes a conflict with another package you want to use. Then + you can remove that packages and hope that you are not using + Org-mode functionality that needs it. + + 2. =org-export-latex-packages-alist= :: This is the variable where + you can put the packages that you'd like to use across all + classes. + + The sequence how these customizations will show up in the LaTeX + document are: + + 1. Header from =org-export-latex-classes= + 2. =org-export-latex-default-packages-alist= + 3. =org-export-latex-packages-alist= + 4. Buffer-specific things set with =#+LaTeX_HEADER:= + + If you want more control about which segment is placed where, or + if you want, for a specific class, have full control over the + header and exclude some of the automatic building blocks, you can + put the following macro-like place holders into the header: + + #+begin_example + [DEFAULT-PACKAGES] \usepackage statements for default packages + [NO-DEFAULT-PACKAGES] do not include any of the default packages + [PACKAGES] \usepackage statements for packages + [NO-PACKAGES] do not include the packages + [EXTRA] the stuff from #+LaTeX_HEADER + [NO-EXTRA] do not include #+LaTeX_HEADER stuff + #+end_example + + If you have currently customized =org-export-latex-classes=, you + should revise that customization and remove any package calls that + are covered by =org-export-latex-default-packages-alist=. This + applies to the following packages: + + - inputenc + - fontenc + - fixltx2e + - graphicx + - longtable + - float + - wrapfig + - soul + - t1enc + - textcomp + - marvosym + - wasysym + - latexsym + - amssymb + - hyperref + + If one of these packages creates a conflict with another package + you are using, you can remove it from + =org-export-latex-default-packages-alist=. But then you risk that + some of the advertised export features of Org will not work + properly. + + You can also consider moving packages that you use in all classes + to =org-export-latex-packages-alist=. If necessary, put the place + holders so that the packages get loaded in the right sequence. As + said above, for backward compatibility, if you omit the place + holders, all the variables will dump their content at the end of + the header. + +*** The constant =org-html-entities= is obsolete + + Its content is now part of the new constant =org-entities=, which + is defined in the file org-entities.el. =org-html-entities= was + an internal variable, but it is possible that some users did write + code using it. + +*** =org-bbdb-anniversary-format-alist= has changed + + Please check the docstring and update your settings accordingly. + +*** Deleted =org-mode-p= + + This function has been deleted: please update your code. + +** Important new features + +*** New Org to ODT exporter + + Jambunathan's Org to ODT exporter is now part of Org. + + To use it, it `C-c C-e o' in an Org file. See the documentation + for more information on how to customize it. + +*** org-capture.el is now the default capture system + + This replaces the earlier system org-remember. The manual only + describes org-capture, but for people who prefer to continue to + use org-remember, we keep a static copy of the former manual + section [[https://orgmode.org/org-remember.pdf][chapter about remember]]. + + The new system has a technically cleaner implementation and more + possibilities for capturing different types of data. See + [[http://thread.gmane.org/gmane.emacs.orgmode/26441/focus%3D26441][Carsten's announcement]] for more details. + + To switch over to the new system: + + 1. Run + + : M-x org-capture-import-remember-templates RET + + to get a translated version of your remember templates into the + new variable =org-capture-templates=. This will "mostly" work, + but maybe not for all cases. At least it will give you a good + place to modify your templates. After running this command, + enter the customize buffer for this variable with + + : M-x customize-variable RET org-capture-templates RET + + and convince yourself that everything is OK. Then save the + customization. + + 2. Bind the command =org-capture= to a key, similar to what you did + with org-remember: + + : (define-key global-map "\C-cc" 'org-capture) + + If your fingers prefer =C-c r=, you can also use this key once + you have decided to move over completely to the new + implementation. During a test time, there is nothing wrong + with using both system in parallel. + +** New libraries + +*** New Org libraries +**** org-eshell.el (Konrad Hinsen) + + Implement links to eshell buffers. + +**** org-special-blocks (Carsten Dominik) + + This package generalizes the #+begin_foo and #+end_foo tokens. + + To use, put the following in your init file: + + #+BEGIN_EXAMPLE +(require 'org-special-blocks) +#+END_EXAMPLE + + The tokens #+begin_center, #+begin_verse, etc. existed + previously. This package generalizes them (at least for the + LaTeX and html exporters). When a #+begin_foo token is + encountered by the LaTeX exporter, it is expanded + into \begin{foo}. The text inside the environment is not + protected, as text inside environments generally is. + When #+begin_foo is encountered by the html exporter, a div with + class foo is inserted into the HTML file. It is up to the user + to add this class to his or her stylesheet if this div is to mean + anything. + +**** org-taskjuggler.el (Christian Egli) + + Christian Egli's /org-taskjuggler.el/ module is now part of Org. + He also wrote a [[https://orgmode.org/worg/org-tutorials/org-taskjuggler.php][tutorial]] for it. + +**** org-ctags.el (Paul Sexton) + + Targets like =<>= can now be found by Emacs' etag + functionality, and Org-mode links can be used to to link to + etags, also in non-Org-mode files. For details, see the file + /org-ctags.el/. + + This feature uses a new hook =org-open-link-functions= which will + call function to do something special with text links. + + Thanks to Paul Sexton for this contribution. + +**** org-docview.el (Jan Böcker) + + This new module allows links to various file types using docview, where + Emacs displays images of document pages. Docview link types can point + to a specific page in a document, for example to page 131 of the + Org-mode manual: + + : [[docview:~/.elisp/org/doc/org.pdf::131][Org-Mode Manual]] + + Thanks to Jan Böcker for this contribution. + +*** New Babel libraries + +- ob-picolisp.el (Thorsten Jolitz) +- ob-fortran.el (Sergey Litvinov) +- ob-shen.el (Eric Schulte) +- ob-maxima.el (Eric S Fraga) +- ob-java.el (Eric Schulte) +- ob-lilypond.el (Martyn Jago) +- ob-awk.el (Eric Schulte) + +** Other new features and various enhancements + +*** Hyperlinks + +**** Org-Bibtex -- major improvements + + Provides support for managing bibtex bibliographical references + data in headline properties. Each headline corresponds to a + single reference and the relevant bibliographic meta-data is + stored in headline properties, leaving the body of the headline + free to hold notes and comments. Org-bibtex is aware of all + standard bibtex reference types and fields. + + The key new functions are + + - org-bibtex-check :: queries the user to flesh out all required + (and with prefix argument optional) bibtex fields available + for the specific reference =type= of the current headline. + + - org-bibtex-create :: Create a new entry at the given level, + using org-bibtex-check to flesh out the relevant fields. + + - org-bibtex-yank :: Yank a bibtex entry on the kill ring as a + formatted Org-mode headline into the current buffer + + - org-bibtex-export-to-kill-ring :: Export the current headline + to the kill ring as a formatted bibtex entry. + +**** org-gnus.el now allows link creation from messages + + You can now create links from messages. This is particularly + useful when the user wants to stored messages that he sends, for + later check. Thanks to Ulf Stegemann for the patch. + +**** Modified link escaping + + David Maus worked on `org-link-escape'. See [[http://article.gmane.org/gmane.emacs.orgmode/37888][his message]]: + + : Percent escaping is used in Org mode to escape certain characters + : in links that would either break the parser (e.g. square brackets + : in link target oder description) or are not allowed to appear in + : a particular link type (e.g. non-ascii characters in a http: + : link). + : + : With this change in place Org will apply percent escaping and + : unescaping more consistently especially for non-ascii characters. + : Additionally some of the outstanding bugs or glitches concerning + : percent escaped links are solved. + + Thanks a lot to David for this work. + +**** Make =org-store-link= point to directory in a dired buffer + + When, in a dired buffer, the cursor is not in a line listing a + file, `org-store-link' will store a link to the directory. + + Patch by Stephen Eglen. + +**** Allow regexps in =org-file-apps= to capture link parameters + + The way extension regexps in =org-file-apps= are handled has + changed. Instead of matching against the file name, the regexps + are now matched against the whole link, and you can use grouping + to extract link parameters which you can then use in a command + string to be executed. + + For example, to allow linking to PDF files using the syntax + =file:/doc.pdf::=, you can add the following entry + to org-file-apps: + + #+begin_example + Extension: \.pdf::\([0-9]+\)\' + Command: evince "%s" -p %1 + #+end_example + + Thanks to Jan Böcker for a patch to this effect. + +*** Dates and time + +**** Allow relative time when scheduling/adding a deadline + + You can now use relative duration strings like "-2d" or "++3w" + when calling =org-schedule= or =org-deadline=: it will schedule + (or set the deadline for) the item respectively two days before + today and three weeks after the current timestamp, if any. + + You can use this programmatically: =(org-schedule nil "+2d")= + will work on the current entry. + + You can also use this while (bulk-)rescheduling and + (bulk-)resetting the deadline of (several) items from the agenda. + + Thanks to Memnon Anon for a heads up about this! + +**** American-style dates are now understood by =org-read-date= + + So when you are prompted for a date, you can now answer like this + + #+begin_example + 2/5/3 --> 2003-02-05 + 2/5 --> -02-05 + #+end_example + +*** Agenda + +**** =org-agenda-custom-commands= has a default value + + This option used to be `nil' by default. This now has a default + value, displaying an agenda and all TODOs. See the docstring for + details. Thanks to Carsten for this. + +**** Improved filtering through =org-agenda-to-appt= + + The new function allows the user to refine the scope of entries + to pass to =org-agenda-get-day-entries= and allows to filter out + entries using a function. + + Thanks to Peter Münster for raising a related issue and to + Tassilo Horn for this idea. Also thanks to Peter Münster for + [[git:68ffb7a7][fixing a small bug]] in the final implementation. + +**** Allow ap/pm times in agenda time grid + + Times in the agenda can now be displayed in am/pm format. See + the new variable =org-agenda-timegrid-use-ampm=. Thanks to + C. A. Webber for a patch to this effect. + +**** Agenda: Added a bulk "scattering" command + + =B S= in the agenda buffer will cause tasks to be rescheduled a + random number of days into the future, with 7 as the default. + This is useful if you've got a ton of tasks scheduled for today, + you realize you'll never deal with them all, and you just want + them to be distributed across the next N days. When called with + a prefix arg, rescheduling will avoid weekend days. + + Thanks to John Wiegley for this. + +*** Exporting + +**** Simplification of org-export-html-preamble/postamble + + When set to `t', export the preamble/postamble as usual, honoring + the =org-export-email/author/creator-info= variables. + + When set to a formatting string, insert this string. See the + docstring of these variable for details about available + %-sequences. + + You can set =:html-preamble= in publishing project in the same + way: `t' means to honor =:email/creator/author-info=, and a + formatting string will insert a string. + +**** New exporters to Latin-1 and UTF-8 + + While Ulf Stegemann was going through the entities list to + improve the LaTeX export, he had the great idea to provide + representations for many of the entities in Latin-1, and for all + of them in UTF-8. This means that we can now export files rich + in special symbols to Latin-1 and to UTF-8 files. These new + exporters can be reached with the commands =C-c C-e n= and =C-c + C-e u=, respectively. + + When there is no representation for a given symbol in the + targeted coding system, you can choose to keep the TeX-macro-like + representation, or to get an "explanatory" representation. For + example, =\simeq= could be represented as "[approx. equal to]". + Please use the variable =org-entities-ascii-explanatory= to state + your preference. + +**** HTML export: Add class to outline containers using property + + The =HTML_CONTAINER_CLASS= property can now be used to add a + class name to the outline container of a node in HTML export. + +**** Throw an error when creating an image from a LaTeX snippet fails + + This behavior can be configured with the new option variable + =org-format-latex-signal-error=. + +**** Support for creating BEAMER presentations from Org-mode documents + + Org-mode documents or subtrees can now be converted directly in + to BEAMER presentation. Turning a tree into a simple + presentations is straight forward, and there is also quite some + support to make richer presentations as well. See the [[https://orgmode.org/manual/Beamer-class-export.html#Beamer-class-export][BEAMER + section]] in the manual for more details. + + Thanks to everyone who has contributed to the discussion about + BEAMER support and how it should work. This was a great example + for how this community can achieve a much better result than any + individual could. + +*** Refiling + +**** Refile targets can now be cached + + You can turn on caching of refile targets by setting the variable + =org-refile-use-cache=. This should speed up refiling if you + have many eligible targets in many files. If you need to update + the cache because Org misses a newly created entry or still + offers a deleted one, press =C-0 C-c C-w=. + +**** New logging support for refiling + + Whenever you refile an item, a time stamp and even a note can be + added to this entry. For details, see the new option + =org-log-refile=. + + Thanks to Charles Cave for this idea. + +*** Completion + +**** In-buffer completion is now done using John Wiegley's pcomplete.el + + Thanks to John Wiegley for much of this code. + +*** Tables + +**** New command =org-table-transpose-table-at-point= + + See the docstring. This hack from Juan Pechiar is now part of + Org's core. Thanks to Juan! + +**** Display field's coordinates when editing it with =C-c `= + + When editing a field with =C-c `=, the field's coordinate will + the displayed in the buffer. + + Thanks to Michael Brand for a patch to this effect. + +**** Spreadsheet computation of durations and time values + + If you want to compute time values use the =T= flag, either in + Calc formulas or Elisp formulas: + + | Task 1 | Task 2 | Total | + |--------+--------+---------| + | 35:00 | 35:00 | 1:10:00 | + #+TBLFM: @2$3=$1+$2;T + + Values must be of the form =[HH:]MM:SS=, where hours are + optional. + + Thanks to Martin Halder, Eric Schulte and Carsten for code and + feedback on this. + +**** Implement formulas applying to field ranges + + Carsten implemented this field-ranges formulas. + + : A frequently requested feature for tables has been to be able to define + : row formulas in a way similar to column formulas. The patch below allows + : things like + : + : @3= + : @2$2..@5$7= + : @I$2..@II$4= + : + : as the left hand side for table formulas in order to write a formula that + : is valid for an entire column or for a rectangular section in a + : table. + + Thanks a lot to Carsten for this. + +**** Sending radio tables from org buffers is now allowed + + Org radio tables can no also be sent inside Org buffers. Also, + there is a new hook which get called after a table has been sent. + + Thanks to Seweryn Kokot. + +*** Lists + +**** Improved handling of lists + + Nicolas Goaziou extended and improved the way Org handles lists. + + 1. Indentation of text determines again end of items in + lists. So, some text less indented than the previous item + doesn't close the whole list anymore, only all items more + indented than it. + + 2. Alphabetical bullets are implemented, through the use of the + variable `org-alphabetical-lists'. This also adds alphabetical + counters like [@c] or [@W]. + + 3. Lists can now safely contain drawers, inline tasks, or various + blocks, themselves containing lists. Two variables are + controlling this: `org-list-forbidden-blocks', and + `org-list-export-context'. + + 4. Improve `newline-and-indent' (C-j): used in an item, it will + keep text from moving at column 0. This allows to split text + and make paragraphs and still not break the list. + + 5. Improve `org-toggle-item' (C-c -): used on a region with + standard text, it will change the region into one item. With a + prefix argument, it will fallback to the previous behavior and + make every line in region an item. It permits to easily + integrate paragraphs inside a list. + + 6. `fill-paragraph' (M-q) now understands lists. It can freely be + used inside items, or on text just after a list, even with no + blank line around, without breaking list structure. + + Thanks a lot to Nicolas for all this! + +*** Inline display of linked images + + Images can now be displayed inline. The key C-c C-x C-v does + toggle the display of such images. Note that only image links + that have no description part will be inlined. + +*** Implement offsets for ordered lists + + If you want to start an ordered plain list with a number different + from 1, you can now do it like this: + + : 1. [@start:12] will star a lit a number 12 + +*** Babel: code block body expansion for table and preview + + In org-babel, code is "expanded" prior to evaluation. I.e. the + code that is actually evaluated comprises the code block contents, + augmented with the extra code which assigns the referenced data to + variables. It is now possible to preview expanded contents, and + also to expand code during during tangling. This expansion takes + into account all header arguments, and variables. + + A new keybinding `C-c M-b p' bound to `org-babel-expand-src-block' + can be used from inside of a source code block to preview its + expanded contents (which can be very useful for debugging). + tangling + + The expanded body can now be tangled, this includes variable + values which may be the results of other source-code blocks, or + stored in headline properties or tables. One possible use for this + is to allow those using org-babel for their emacs initialization + to store values (e.g. usernames, passwords, etc...) in headline + properties or in tables. + + Org-babel now supports three new header arguments, and new default + behavior for handling horizontal lines in tables (hlines), column + names, and rownames across all languages. + +*** Editing Convenience and Appearance + +**** New command =org-copy-visible= (=C-c C-x v=) + + This command will copy the visible text in the region into the + kill ring. Thanks to Florian Beck for this function and to + Carsten for adding it to org.el and documenting it! + +**** Make it possible to protect hidden subtrees from being killed by =C-k= + + See the new variable =org-ctrl-k-protect-subtree=. This was a + request by Scott Otterson. + +**** Implement pretty display of entities, sub-, and superscripts. + + The command =C-c C-x \= toggles the display of Org's special + entities like =\alpha= as pretty unicode characters. Also, sub + and superscripts are displayed in a pretty way (raised/lower + display, in a smaller font). If you want to exclude sub- and + superscripts, see the variable + =org-pretty-entities-include-sub-superscripts=. + + Thanks to Eric Schulte and Ulf Stegeman for making this possible. + +**** New faces for title, date, author and email address lines + + The keywords in these lines are now dimmed out, and the title is + displayed in a larger font, and a special font is also used for + author, date, and email information. This is implemented by the + following new faces: + + =org-document-title= + =org-document-info= + =org-document-info-keyword= + + In addition, the variable =org-hidden-keywords= can be used to + make the corresponding keywords disappear. + + Thanks to Dan Davison for this feature. + +**** Simpler way to specify faces for tags and todo keywords + + The variables =org-todo-keyword-faces=, =org-tag-faces=, and + =org-priority-faces= now accept simple color names as + specifications. The colors will be used as either foreground or + background color for the corresponding keyword. See also the + variable =org-faces-easy-properties=, which governs which face + property is affected by this setting. + + This is really a great simplification for setting keyword faces. + The change is based on an idea and patch by Ryan Thompson. + +**** in tables now means fixed width, not maximum width + + Requested by Michael Brand. + +**** Better level cycling function + + =TAB= in an empty headline cycles the level of that headline + through likely states. Ryan Thompson implemented an improved + version of this function, which does not depend upon when exactly + this command is used. Thanks to Ryan for this improvement. + +**** Adaptive filling + + For paragraph text, =org-adaptive-fill-function= did not handle + the base case of regular text which needed to be filled. This is + now fixed. Among other things, it allows email-style ">" + comments to be filled correctly. + + Thanks to Dan Hackney for this patch. + +**** `org-reveal' (=C-c C-r=) also decrypts encrypted entries (org-crypt.el) + + Thanks to Richard Riley for triggering this change. + +**** Better automatic letter selection for TODO keywords + + When all first letters of keywords have been used, Org now + assigns more meaningful characters based on the keywords. + + Thanks to Mikael Fornius for this patch. + +*** Clocking + +**** Clock: Allow synchronous update of timestamps in CLOCK log + + Using =S-M-= on CLOCK log timestamps will + increase/decrease the two timestamps on this line so that + duration will keep the same. Note that duration can still be + slightly modified in case a timestamp needs some rounding. + + Thanks to Rainer Stengele for this idea. + +**** Localized clock tables + + Clock tables now support a new new =:lang= parameter, allowing + the user to customize the localization of the table headers. See + the variable =org-clock-clocktable-language-setup= which controls + available translated strings. + +**** Show clock overruns in mode line + + When clocking an item with a planned effort, overrunning the + planned time is now made visible in the mode line, for example + using the new face =org-mode-line-clock-overrun=, or by adding an + extra string given by =org-task-overrun-text=. + + Thanks to Richard Riley for a patch to this effect. + +**** Clock reports can now include the running, incomplete clock + + If you have a clock running, and the entry being clocked falls + into the scope when creating a clock table, the time so far spent + can be added to the total. This behavior depends on the setting + of =org-clock-report-include-clocking-task=. The default is + =nil=. + + Thanks to Bernt Hansen for this useful addition. + +*** Misc + +**** Improvements with inline tasks and indentation + + There is now a configurable way on how to export inline tasks. + See the new variable =org-inlinetask-export-templates=. + + Thanks to Nicolas Goaziou for coding these changes. + +**** A property value of "nil" now means to unset a property + + This can be useful in particular with property inheritance, if + some upper level has the property, and some grandchild of it + would like to have the default settings (i.e. not overruled by a + property) back. + + Thanks to Robert Goldman and Bernt Hansen for suggesting this + change. + +**** New helper functions in org-table.el + + There are new functions to access and write to a specific table field. + This is for hackers, and maybe for the org-babel people. + + #+begin_example + org-table-get + org-table-put + org-table-current-line + org-table-goto-line + #+end_example + +**** Archiving: Allow to reverse order in target node + + The new option =org-archive-reversed-order= allows to have + archived entries inserted in a last-on-top fashion in the target + node. + + This was requested by Tom. + +**** Org-reveal: Double prefix arg shows the entire subtree of the parent + + This can help to get out of an inconsistent state produced for + example by viewing from the agenda. + + This was a request by Matt Lundin. + +* License + + This file is part of GNU Emacs. + + GNU Emacs 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 of the License, or + (at your option) any later version. + + GNU Emacs 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 . diff --git a/elpa/org-9.1.14/etc/styles/OrgOdtContentTemplate.xml b/elpa/org-9.1.14/etc/styles/OrgOdtContentTemplate.xml new file mode 100644 index 00000000..d0c98a3e --- /dev/null +++ b/elpa/org-9.1.14/etc/styles/OrgOdtContentTemplate.xml @@ -0,0 +1,275 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/elpa/org-9.1.14/etc/styles/OrgOdtStyles.xml b/elpa/org-9.1.14/etc/styles/OrgOdtStyles.xml new file mode 100644 index 00000000..1a8edee9 --- /dev/null +++ b/elpa/org-9.1.14/etc/styles/OrgOdtStyles.xml @@ -0,0 +1,861 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + / + + / + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/elpa/org-9.1.14/etc/styles/README b/elpa/org-9.1.14/etc/styles/README new file mode 100644 index 00000000..7c175e34 --- /dev/null +++ b/elpa/org-9.1.14/etc/styles/README @@ -0,0 +1,36 @@ +The files OrgOdtContentTemplate.xml and OrgOdtStyles.xml have the +following copyright information: + +Copyright (C) 2010-2018 Free Software Foundation, Inc. + +These files are part of GNU Emacs. + +GNU Emacs 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 of the License, or +(at your option) any later version. + +GNU Emacs 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 . + + +Author: Jambunathan K +Keywords: outlines, hypermedia, calendar, wp +Homepage: https://orgmode.org + +Commentary: + +These files are part of Org-mode's OpenDocument export module. + +OrgOdtContentTemplate.xml provides a template within which the content +of an exported document is enclosed. This file contributes to +"content.xml" file within an exported document and acts as a +repository of automatic styles. + +OrgOdtStyles.xml contributes to "styles.xml" file within an exported +document and acts as a repository of custom styles. diff --git a/elpa/org-9.1.14/ob-C.el b/elpa/org-9.1.14/ob-C.el new file mode 100644 index 00000000..ff5be349 --- /dev/null +++ b/elpa/org-9.1.14/ob-C.el @@ -0,0 +1,469 @@ +;;; ob-C.el --- Babel Functions for C and Similar Languages -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Thierry Banel +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating C, C++, D code. +;; +;; very limited implementation: +;; - currently only support :results output +;; - not much in the way of error feedback + +;;; Code: + +(require 'cc-mode) +(require 'ob) + + +(declare-function org-entry-get "org" (pom property &optional inherit literal-nil)) +(declare-function org-remove-indentation "org" (code &optional n)) +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("C++" . "cpp")) +(add-to-list 'org-babel-tangle-lang-exts '("D" . "d")) + +(defvar org-babel-default-header-args:C '()) + +(defconst org-babel-header-args:C '((includes . :any) + (defines . :any) + (main . :any) + (flags . :any) + (cmdline . :any) + (libs . :any)) + "C/C++-specific header arguments.") + +(defconst org-babel-header-args:C++ + (append '((namespaces . :any)) + org-babel-header-args:C) + "C++-specific header arguments.") + +(defcustom org-babel-C-compiler "gcc" + "Command used to compile a C source code file into an executable. +May be either a command in the path, like gcc +or an absolute path name, like /usr/local/bin/gcc +parameter may be used, like gcc -v" + :group 'org-babel + :version "24.3" + :type 'string) + +(defcustom org-babel-C++-compiler "g++" + "Command used to compile a C++ source code file into an executable. +May be either a command in the path, like g++ +or an absolute path name, like /usr/local/bin/g++ +parameter may be used, like g++ -v" + :group 'org-babel + :version "24.3" + :type 'string) + +(defcustom org-babel-D-compiler "rdmd" + "Command used to compile and execute a D source code file. +May be either a command in the path, like rdmd +or an absolute path name, like /usr/local/bin/rdmd +parameter may be used, like rdmd --chatty" + :group 'org-babel + :version "24.3" + :type 'string) + +(defvar org-babel-c-variant nil + "Internal variable used to hold which type of C (e.g. C or C++ or D) +is currently being evaluated.") + +(defun org-babel-execute:cpp (body params) + "Execute BODY according to PARAMS. +This function calls `org-babel-execute:C++'." + (org-babel-execute:C++ body params)) + +(defun org-babel-expand-body:cpp (body params) + "Expand a block of C++ code with org-babel according to its +header arguments." + (org-babel-expand-body:C++ body params)) + +(defun org-babel-execute:C++ (body params) + "Execute a block of C++ code with org-babel. +This function is called by `org-babel-execute-src-block'." + (let ((org-babel-c-variant 'cpp)) (org-babel-C-execute body params))) + +(defun org-babel-expand-body:C++ (body params) + "Expand a block of C++ code with org-babel according to its +header arguments." + (let ((org-babel-c-variant 'cpp)) (org-babel-C-expand-C++ body params))) + +(defun org-babel-execute:D (body params) + "Execute a block of D code with org-babel. +This function is called by `org-babel-execute-src-block'." + (let ((org-babel-c-variant 'd)) (org-babel-C-execute body params))) + +(defun org-babel-expand-body:D (body params) + "Expand a block of D code with org-babel according to its +header arguments." + (let ((org-babel-c-variant 'd)) (org-babel-C-expand-D body params))) + +(defun org-babel-execute:C (body params) + "Execute a block of C code with org-babel. +This function is called by `org-babel-execute-src-block'." + (let ((org-babel-c-variant 'c)) (org-babel-C-execute body params))) + +(defun org-babel-expand-body:C (body params) + "Expand a block of C code with org-babel according to its +header arguments." + (let ((org-babel-c-variant 'c)) (org-babel-C-expand-C body params))) + +(defun org-babel-C-execute (body params) + "This function should only be called by `org-babel-execute:C' +or `org-babel-execute:C++' or `org-babel-execute:D'." + (let* ((tmp-src-file (org-babel-temp-file + "C-src-" + (pcase org-babel-c-variant + (`c ".c") (`cpp ".cpp") (`d ".d")))) + (tmp-bin-file ;not used for D + (org-babel-process-file-name + (org-babel-temp-file "C-bin-" org-babel-exeext))) + (cmdline (cdr (assq :cmdline params))) + (cmdline (if cmdline (concat " " cmdline) "")) + (flags (cdr (assq :flags params))) + (flags (mapconcat 'identity + (if (listp flags) flags (list flags)) " ")) + (libs (org-babel-read + (or (cdr (assq :libs params)) + (org-entry-get nil "libs" t)) + nil)) + (libs (mapconcat #'identity + (if (listp libs) libs (list libs)) + " ")) + (full-body + (pcase org-babel-c-variant + (`c (org-babel-C-expand-C body params)) + (`cpp (org-babel-C-expand-C++ body params)) + (`d (org-babel-C-expand-D body params))))) + (with-temp-file tmp-src-file (insert full-body)) + (pcase org-babel-c-variant + ((or `c `cpp) + (org-babel-eval + (format "%s -o %s %s %s %s" + (pcase org-babel-c-variant + (`c org-babel-C-compiler) + (`cpp org-babel-C++-compiler)) + tmp-bin-file + flags + (org-babel-process-file-name tmp-src-file) + libs) + "")) + (`d nil)) ;; no separate compilation for D + (let ((results + (org-babel-eval + (pcase org-babel-c-variant + ((or `c `cpp) + (concat tmp-bin-file cmdline)) + (`d + (format "%s %s %s %s" + org-babel-D-compiler + flags + (org-babel-process-file-name tmp-src-file) + cmdline))) + ""))) + (when results + (setq results (org-trim (org-remove-indentation results))) + (org-babel-reassemble-table + (org-babel-result-cond (cdr (assq :result-params params)) + (org-babel-read results t) + (let ((tmp-file (org-babel-temp-file "c-"))) + (with-temp-file tmp-file (insert results)) + (org-babel-import-elisp-from-file tmp-file))) + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))) + ))) + +(defun org-babel-C-expand-C++ (body params) + "Expand a block of C or C++ code with org-babel according to +its header arguments." + (org-babel-C-expand-C body params)) + +(defun org-babel-C-expand-C (body params) + "Expand a block of C or C++ code with org-babel according to +its header arguments." + (let ((vars (org-babel--get-vars params)) + (colnames (cdr (assq :colname-names params))) + (main-p (not (string= (cdr (assq :main params)) "no"))) + (includes (org-babel-read + (cdr (assq :includes params)) + nil)) + (defines (org-babel-read + (cdr (assq :defines params)) + nil)) + (namespaces (org-babel-read + (cdr (assq :namespaces params)) + nil))) + (when (stringp includes) + (setq includes (split-string includes))) + (when (stringp namespaces) + (setq namespaces (split-string namespaces))) + (when (stringp defines) + (let ((y nil) + (result (list t))) + (dolist (x (split-string defines)) + (if (null y) + (setq y x) + (nconc result (list (concat y " " x))) + (setq y nil))) + (setq defines (cdr result)))) + (mapconcat 'identity + (list + ;; includes + (mapconcat + (lambda (inc) (format "#include %s" inc)) + includes "\n") + ;; defines + (mapconcat + (lambda (inc) (format "#define %s" inc)) + (if (listp defines) defines (list defines)) "\n") + ;; namespaces + (mapconcat + (lambda (inc) (format "using namespace %s;" inc)) + namespaces + "\n") + ;; variables + (mapconcat 'org-babel-C-var-to-C vars "\n") + ;; table sizes + (mapconcat 'org-babel-C-table-sizes-to-C vars "\n") + ;; tables headers utility + (when colnames + (org-babel-C-utility-header-to-C)) + ;; tables headers + (mapconcat 'org-babel-C-header-to-C colnames "\n") + ;; body + (if main-p + (org-babel-C-ensure-main-wrap body) + body) "\n") "\n"))) + +(defun org-babel-C-expand-D (body params) + "Expand a block of D code with org-babel according to +its header arguments." + (let ((vars (org-babel--get-vars params)) + (colnames (cdr (assq :colname-names params))) + (main-p (not (string= (cdr (assq :main params)) "no"))) + (imports (or (cdr (assq :imports params)) + (org-babel-read (org-entry-get nil "imports" t))))) + (when (stringp imports) + (setq imports (split-string imports))) + (setq imports (append imports '("std.stdio" "std.conv"))) + (mapconcat 'identity + (list + "module mmm;" + ;; imports + (mapconcat + (lambda (inc) (format "import %s;" inc)) + imports "\n") + ;; variables + (mapconcat 'org-babel-C-var-to-C vars "\n") + ;; table sizes + (mapconcat 'org-babel-C-table-sizes-to-C vars "\n") + ;; tables headers utility + (when colnames + (org-babel-C-utility-header-to-C)) + ;; tables headers + (mapconcat 'org-babel-C-header-to-C colnames "\n") + ;; body + (if main-p + (org-babel-C-ensure-main-wrap body) + body) "\n") "\n"))) + +(defun org-babel-C-ensure-main-wrap (body) + "Wrap BODY in a \"main\" function call if none exists." + (if (string-match "^[ \t]*[intvod]+[ \t\n\r]*main[ \t]*(.*)" body) + body + (format "int main() {\n%s\nreturn 0;\n}\n" body))) + +(defun org-babel-prep-session:C (_session _params) + "This function does nothing as C is a compiled language with no +support for sessions" + (error "C is a compiled language -- no support for sessions")) + +(defun org-babel-load-session:C (_session _body _params) + "This function does nothing as C is a compiled language with no +support for sessions" + (error "C is a compiled language -- no support for sessions")) + +;; helper functions + +(defun org-babel-C-format-val (type val) + "Handle the FORMAT part of TYPE with the data from VAL." + (let ((format-data (cadr type))) + (if (stringp format-data) + (cons "" (format format-data val)) + (funcall format-data val)))) + +(defun org-babel-C-val-to-C-type (val) + "Determine the type of VAL. +Return a list (TYPE-NAME FORMAT). TYPE-NAME should be the name of the type. +FORMAT can be either a format string or a function which is called with VAL." + (let* ((basetype (org-babel-C-val-to-base-type val)) + (type + (pcase basetype + (`integerp '("int" "%d")) + (`floatp '("double" "%f")) + (`stringp + (list + (if (eq org-babel-c-variant 'd) "string" "const char*") + "\"%s\"")) + (_ (error "unknown type %S" basetype))))) + (cond + ((integerp val) type) ;; an integer declared in the #+begin_src line + ((floatp val) type) ;; a numeric declared in the #+begin_src line + ((and (listp val) (listp (car val))) ;; a table + `(,(car type) + (lambda (val) + (cons + (format "[%d][%d]" (length val) (length (car val))) + (concat + (if (eq org-babel-c-variant 'd) "[\n" "{\n") + (mapconcat + (lambda (v) + (concat + (if (eq org-babel-c-variant 'd) " [" " {") + (mapconcat (lambda (w) (format ,(cadr type) w)) v ",") + (if (eq org-babel-c-variant 'd) "]" "}"))) + val + ",\n") + (if (eq org-babel-c-variant 'd) "\n]" "\n}")))))) + ((or (listp val) (vectorp val)) ;; a list declared in the #+begin_src line + `(,(car type) + (lambda (val) + (cons + (format "[%d]" (length val)) + (concat + (if (eq org-babel-c-variant 'd) "[" "{") + (mapconcat (lambda (v) (format ,(cadr type) v)) val ",") + (if (eq org-babel-c-variant 'd) "]" "}")))))) + (t ;; treat unknown types as string + type)))) + +(defun org-babel-C-val-to-base-type (val) + "Determine the base type of VAL which may be +`integerp' if all base values are integers +`floatp' if all base values are either floating points or integers +`stringp' otherwise." + (cond + ((integerp val) 'integerp) + ((floatp val) 'floatp) + ((or (listp val) (vectorp val)) + (let ((type nil)) + (mapc (lambda (v) + (pcase (org-babel-C-val-to-base-type v) + (`stringp (setq type 'stringp)) + (`floatp + (if (or (not type) (eq type 'integerp)) + (setq type 'floatp))) + (`integerp + (unless type (setq type 'integerp))))) + val) + type)) + (t 'stringp))) + +(defun org-babel-C-var-to-C (pair) + "Convert an elisp val into a string of C code specifying a var +of the same value." + ;; TODO list support + (let ((var (car pair)) + (val (cdr pair))) + (when (symbolp val) + (setq val (symbol-name val)) + (when (= (length val) 1) + (setq val (string-to-char val)))) + (let* ((type-data (org-babel-C-val-to-C-type val)) + (type (car type-data)) + (formated (org-babel-C-format-val type-data val)) + (suffix (car formated)) + (data (cdr formated))) + (format "%s %s%s = %s;" + type + var + suffix + data)))) + +(defun org-babel-C-table-sizes-to-C (pair) + "Create constants of table dimensions, if PAIR is a table." + (when (listp (cdr pair)) + (cond + ((listp (cadr pair)) ;; a table + (concat + (format "const int %s_rows = %d;" (car pair) (length (cdr pair))) + "\n" + (format "const int %s_cols = %d;" (car pair) (length (cadr pair))))) + (t ;; a list declared in the #+begin_src line + (format "const int %s_cols = %d;" (car pair) (length (cdr pair))))))) + +(defun org-babel-C-utility-header-to-C () + "Generate a utility function to convert a column name +into a column number." + (pcase org-babel-c-variant + ((or `c `cpp) + "int get_column_num (int nbcols, const char** header, const char* column) +{ + int c; + for (c=0; c. + +;;; Commentary: + +;; Org-Babel support for evaluating J code. +;; +;; Session interaction depends on `j-console' from package `j-mode' +;; (available in MELPA). + +;;; Code: + +(require 'ob) + +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function j-console-ensure-session "ext:j-console" ()) + +(defcustom org-babel-J-command "jconsole" + "Command to call J." + :group 'org-babel + :version "26.1" + :package-version '(Org . "9.0") + :type 'string) + +(defun org-babel-expand-body:J (body _params &optional _processed-params) + "Expand BODY according to PARAMS, return the expanded body. +PROCESSED-PARAMS isn't used yet." + (org-babel-J-interleave-echos-except-functions body)) + +(defun org-babel-J-interleave-echos (body) + "Interleave echo',' between each source line of BODY." + (mapconcat #'identity (split-string body "\n") "\necho','\n")) + +(defun org-babel-J-interleave-echos-except-functions (body) + "Interleave echo',' between source lines of BODY that aren't functions." + (if (obj-string-match-m "\\(?:^\\|\n\\)[^\n]*\\(?:0\\|1\\|2\\|3\\|4\\|dyad\\) : 0\n.*\n)\\(?:\n\\|$\\)" body) + (let ((s1 (substring body 0 (match-beginning 0))) + (s2 (match-string 0 body)) + (s3 (substring body (match-end 0)))) + (concat + (if (string= s1 "") + "" + (concat (org-babel-J-interleave-echos s1) + "\necho','\n")) + s2 + "\necho','\n" + (org-babel-J-interleave-echos-except-functions s3))) + (org-babel-J-interleave-echos body))) + +(defalias 'org-babel-execute:j 'org-babel-execute:J) + +(defun org-babel-execute:J (body params) + "Execute a block of J code BODY. +PARAMS are given by org-babel. +This function is called by `org-babel-execute-src-block'" + (message "executing J source code block") + (let* ((processed-params (org-babel-process-params params)) + (sessionp (cdr (assq :session params))) + (full-body (org-babel-expand-body:J + body params processed-params)) + (tmp-script-file (org-babel-temp-file "J-src"))) + (org-babel-j-initiate-session sessionp) + (org-babel-J-strip-whitespace + (if (string= sessionp "none") + (progn + (with-temp-file tmp-script-file + (insert full-body)) + (org-babel-eval (format "%s < %s" org-babel-J-command tmp-script-file) "")) + (org-babel-J-eval-string full-body))))) + +(defun org-babel-J-eval-string (str) + "Sends STR to the `j-console-cmd' session and executes it." + (let ((session (j-console-ensure-session))) + (with-current-buffer (process-buffer session) + (goto-char (point-max)) + (insert (format "\n%s\n" str)) + (let ((beg (point))) + (comint-send-input) + (sit-for .1) + (buffer-substring-no-properties + beg (point-max)))))) + +(defun org-babel-J-strip-whitespace (str) + "Remove whitespace from jconsole output STR." + (mapconcat + #'identity + (delete "" (mapcar + #'org-babel-J-print-block + (split-string str "^ *,\n" t))) + "\n\n")) + +(defun obj-get-string-alignment (str) + "Return a number to describe STR alignment. +STR represents a table. +Positive/negative/zero result means right/left/undetermined. +Don't trust first line." + (let* ((str (org-trim str)) + (lines (split-string str "\n" t)) + n1 n2) + (cond ((<= (length lines) 1) + 0) + ((= (length lines) 2) + ;; numbers are right-aligned + (if (and + (numberp (read (car lines))) + (numberp (read (cadr lines))) + (setq n1 (obj-match-second-space-right (nth 0 lines))) + (setq n2 (obj-match-second-space-right (nth 1 lines)))) + n2 + 0)) + ((not (obj-match-second-space-left (nth 0 lines))) + 0) + ((and + (setq n1 (obj-match-second-space-left (nth 1 lines))) + (setq n2 (obj-match-second-space-left (nth 2 lines))) + (= n1 n2)) + n1) + ((and + (setq n1 (obj-match-second-space-right (nth 1 lines))) + (setq n2 (obj-match-second-space-right (nth 2 lines))) + (= n1 n2)) + (- n1)) + (t 0)))) + +(defun org-babel-J-print-block (x) + "Prettify jconsole output X." + (let* ((x (org-trim x)) + (a (obj-get-string-alignment x)) + (lines (split-string x "\n" t)) + b) + (cond ((< a 0) + (setq b (obj-match-second-space-right (nth 0 lines))) + (concat (make-string (+ a b) ? ) x)) + ((> a 0) + (setq b (obj-match-second-space-left (nth 0 lines))) + (concat (make-string (- a b) ? ) x)) + (t x)))) + +(defun obj-match-second-space-left (s) + "Return position of leftmost space in second space block of S or nil." + (and (string-match "^ *[^ ]+\\( \\)" s) + (match-beginning 1))) + +(defun obj-match-second-space-right (s) + "Return position of rightmost space in second space block of S or nil." + (and (string-match "^ *[^ ]+ *\\( \\)[^ ]" s) + (match-beginning 1))) + +(defun obj-string-match-m (regexp string &optional start) + "Call (string-match REGEXP STRING START). +REGEXP is modified so that .* matches newlines as well." + (string-match + (replace-regexp-in-string "\\.\\*" "[\0-\377[:nonascii:]]*" regexp) + string + start)) + +(defun org-babel-j-initiate-session (&optional session) + "Initiate a J session. +SESSION is a parameter given by org-babel." + (unless (string= session "none") + (require 'j-console) + (j-console-ensure-session))) + +(provide 'ob-J) + +;;; ob-J.el ends here diff --git a/elpa/org-9.1.14/ob-R.el b/elpa/org-9.1.14/ob-R.el new file mode 100644 index 00000000..d7e936eb --- /dev/null +++ b/elpa/org-9.1.14/ob-R.el @@ -0,0 +1,469 @@ +;;; ob-R.el --- Babel Functions for R -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Dan Davison +;; Keywords: literate programming, reproducible research, R, statistics +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating R code + +;;; Code: + +(require 'cl-lib) +(require 'ob) + +(declare-function orgtbl-to-tsv "org-table" (table params)) +(declare-function R "ext:essd-r" (&optional start-args)) +(declare-function inferior-ess-send-input "ext:ess-inf" ()) +(declare-function ess-make-buffer-current "ext:ess-inf" ()) +(declare-function ess-eval-buffer "ext:ess-inf" (vis)) +(declare-function ess-wait-for-process "ext:ess-inf" + (&optional proc sec-prompt wait force-redisplay)) + +(defconst org-babel-header-args:R + '((width . :any) + (height . :any) + (bg . :any) + (units . :any) + (pointsize . :any) + (antialias . :any) + (quality . :any) + (compression . :any) + (res . :any) + (type . :any) + (family . :any) + (title . :any) + (fonts . :any) + (version . :any) + (paper . :any) + (encoding . :any) + (pagecentre . :any) + (colormodel . :any) + (useDingbats . :any) + (horizontal . :any) + (results . ((file list vector table scalar verbatim) + (raw html latex org code pp drawer) + (replace silent none append prepend) + (output value graphics)))) + "R-specific header arguments.") + +(defconst ob-R-safe-header-args + (append org-babel-safe-header-args + '(:width :height :bg :units :pointsize :antialias :quality + :compression :res :type :family :title :fonts + :version :paper :encoding :pagecentre :colormodel + :useDingbats :horizontal)) + "Header args which are safe for R babel blocks. + +See `org-babel-safe-header-args' for documentation of the format of +this variable.") + +(defvar org-babel-default-header-args:R '()) +(put 'org-babel-default-header-args:R 'safe-local-variable + (org-babel-header-args-safe-fn ob-R-safe-header-args)) + +(defcustom org-babel-R-command "R --slave --no-save" + "Name of command to use for executing R code." + :group 'org-babel + :version "24.1" + :type 'string) + +(defvar ess-current-process-name) ; dynamically scoped +(defvar ess-local-process-name) ; dynamically scoped +(defun org-babel-edit-prep:R (info) + (let ((session (cdr (assq :session (nth 2 info))))) + (when (and session + (string-prefix-p "*" session) + (string-suffix-p "*" session)) + (org-babel-R-initiate-session session nil)))) + +;; The usage of utils::read.table() ensures that the command +;; read.table() can be found even in circumstances when the utils +;; package is not in the search path from R. +(defconst ob-R-transfer-variable-table-with-header + "%s <- local({ + con <- textConnection( + %S + ) + res <- utils::read.table( + con, + header = %s, + row.names = %s, + sep = \"\\t\", + as.is = TRUE + ) + close(con) + res + })" + "R code used to transfer a table defined as a variable from org to R. + +This function is used when the table contains a header.") + +(defconst ob-R-transfer-variable-table-without-header + "%s <- local({ + con <- textConnection( + %S + ) + res <- utils::read.table( + con, + header = %s, + row.names = %s, + sep = \"\\t\", + as.is = TRUE, + fill = TRUE, + col.names = paste(\"V\", seq_len(%d), sep =\"\") + ) + close(con) + res + })" + "R code used to transfer a table defined as a variable from org to R. + +This function is used when the table does not contain a header.") + +(defun org-babel-expand-body:R (body params &optional _graphics-file) + "Expand BODY according to PARAMS, return the expanded body." + (mapconcat 'identity + (append + (when (cdr (assq :prologue params)) + (list (cdr (assq :prologue params)))) + (org-babel-variable-assignments:R params) + (list body) + (when (cdr (assq :epilogue params)) + (list (cdr (assq :epilogue params))))) + "\n")) + +(defun org-babel-execute:R (body params) + "Execute a block of R code. +This function is called by `org-babel-execute-src-block'." + (save-excursion + (let* ((result-params (cdr (assq :result-params params))) + (result-type (cdr (assq :result-type params))) + (session (org-babel-R-initiate-session + (cdr (assq :session params)) params)) + (graphics-file (and (member "graphics" (assq :result-params params)) + (org-babel-graphical-output-file params))) + (colnames-p (unless graphics-file (cdr (assq :colnames params)))) + (rownames-p (unless graphics-file (cdr (assq :rownames params)))) + (full-body + (let ((inside + (list (org-babel-expand-body:R body params graphics-file)))) + (mapconcat 'identity + (if graphics-file + (append + (list (org-babel-R-construct-graphics-device-call + graphics-file params)) + inside + (list "},error=function(e){plot(x=-1:1, y=-1:1, type='n', xlab='', ylab='', axes=FALSE); text(x=0, y=0, labels=e$message, col='red'); paste('ERROR', e$message, sep=' : ')}); dev.off()")) + inside) + "\n"))) + (result + (org-babel-R-evaluate + session full-body result-type result-params + (or (equal "yes" colnames-p) + (org-babel-pick-name + (cdr (assq :colname-names params)) colnames-p)) + (or (equal "yes" rownames-p) + (org-babel-pick-name + (cdr (assq :rowname-names params)) rownames-p))))) + (if graphics-file nil result)))) + +(defun org-babel-prep-session:R (session params) + "Prepare SESSION according to the header arguments specified in PARAMS." + (let* ((session (org-babel-R-initiate-session session params)) + (var-lines (org-babel-variable-assignments:R params))) + (org-babel-comint-in-buffer session + (mapc (lambda (var) + (end-of-line 1) (insert var) (comint-send-input nil t) + (org-babel-comint-wait-for-output session)) var-lines)) + session)) + +(defun org-babel-load-session:R (session body params) + "Load BODY into SESSION." + (save-window-excursion + (let ((buffer (org-babel-prep-session:R session params))) + (with-current-buffer buffer + (goto-char (process-mark (get-buffer-process (current-buffer)))) + (insert (org-babel-chomp body))) + buffer))) + +;; helper functions + +(defun org-babel-variable-assignments:R (params) + "Return list of R statements assigning the block's variables." + (let ((vars (org-babel--get-vars params))) + (mapcar + (lambda (pair) + (org-babel-R-assign-elisp + (car pair) (cdr pair) + (equal "yes" (cdr (assq :colnames params))) + (equal "yes" (cdr (assq :rownames params))))) + (mapcar + (lambda (i) + (cons (car (nth i vars)) + (org-babel-reassemble-table + (cdr (nth i vars)) + (cdr (nth i (cdr (assq :colname-names params)))) + (cdr (nth i (cdr (assq :rowname-names params))))))) + (number-sequence 0 (1- (length vars))))))) + +(defun org-babel-R-quote-tsv-field (s) + "Quote field S for export to R." + (if (stringp s) + (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"") + (format "%S" s))) + +(defun org-babel-R-assign-elisp (name value colnames-p rownames-p) + "Construct R code assigning the elisp VALUE to a variable named NAME." + (if (listp value) + (let* ((lengths (mapcar 'length (cl-remove-if-not 'sequencep value))) + (max (if lengths (apply 'max lengths) 0)) + (min (if lengths (apply 'min lengths) 0))) + ;; Ensure VALUE has an orgtbl structure (depth of at least 2). + (unless (listp (car value)) (setq value (list value))) + (let ((file (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field))) + (header (if (or (eq (nth 1 value) 'hline) colnames-p) + "TRUE" "FALSE")) + (row-names (if rownames-p "1" "NULL"))) + (if (= max min) + (format ob-R-transfer-variable-table-with-header + name file header row-names) + (format ob-R-transfer-variable-table-without-header + name file header row-names max)))) + (cond ((integerp value) (format "%s <- %s" name (concat (number-to-string value) "L"))) + ((floatp value) (format "%s <- %s" name value)) + ((stringp value) (format "%s <- %S" name (org-no-properties value))) + (t (format "%s <- %S" name (prin1-to-string value)))))) + + +(defvar ess-ask-for-ess-directory) ; dynamically scoped +(defun org-babel-R-initiate-session (session params) + "If there is not a current R process then create one." + (unless (string= session "none") + (let ((session (or session "*R*")) + (ess-ask-for-ess-directory + (and (boundp 'ess-ask-for-ess-directory) + ess-ask-for-ess-directory + (not (cdr (assq :dir params)))))) + (if (org-babel-comint-buffer-livep session) + session + (save-window-excursion + (when (get-buffer session) + ;; Session buffer exists, but with dead process + (set-buffer session)) + (require 'ess) (R) + (let ((R-proc (get-process (or ess-local-process-name + ess-current-process-name)))) + (while (process-get R-proc 'callbacks) + (ess-wait-for-process R-proc))) + (rename-buffer + (if (bufferp session) + (buffer-name session) + (if (stringp session) + session + (buffer-name)))) + (current-buffer)))))) + +(defun org-babel-R-associate-session (session) + "Associate R code buffer with an R session. +Make SESSION be the inferior ESS process associated with the +current code buffer." + (setq ess-local-process-name + (process-name (get-buffer-process session))) + (ess-make-buffer-current)) + +(defvar org-babel-R-graphics-devices + '((:bmp "bmp" "filename") + (:jpg "jpeg" "filename") + (:jpeg "jpeg" "filename") + (:tikz "tikz" "file") + (:tiff "tiff" "filename") + (:png "png" "filename") + (:svg "svg" "file") + (:pdf "pdf" "file") + (:ps "postscript" "file") + (:postscript "postscript" "file")) + "An alist mapping graphics file types to R functions. + +Each member of this list is a list with three members: +1. the file extension of the graphics file, as an elisp :keyword +2. the R graphics device function to call to generate such a file +3. the name of the argument to this function which specifies the + file to write to (typically \"file\" or \"filename\")") + +(defun org-babel-R-construct-graphics-device-call (out-file params) + "Construct the call to the graphics device." + (let* ((allowed-args '(:width :height :bg :units :pointsize + :antialias :quality :compression :res + :type :family :title :fonts :version + :paper :encoding :pagecentre :colormodel + :useDingbats :horizontal)) + (device (file-name-extension out-file)) + (device-info (or (assq (intern (concat ":" device)) + org-babel-R-graphics-devices) + (assq :png org-babel-R-graphics-devices))) + (extra-args (cdr (assq :R-dev-args params))) filearg args) + (setq device (nth 1 device-info)) + (setq filearg (nth 2 device-info)) + (setq args (mapconcat + (lambda (pair) + (if (member (car pair) allowed-args) + (format ",%s=%S" + (substring (symbol-name (car pair)) 1) + (cdr pair)) "")) + params "")) + (format "%s(%s=\"%s\"%s%s%s); tryCatch({" + device filearg out-file args + (if extra-args "," "") (or extra-args "")))) + +(defconst org-babel-R-eoe-indicator "'org_babel_R_eoe'") +(defconst org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"") + +(defconst org-babel-R-write-object-command "{ + function(object,transfer.file) { + object + invisible( + if ( + inherits( + try( + { + tfile<-tempfile() + write.table(object, file=tfile, sep=\"\\t\", + na=\"nil\",row.names=%s,col.names=%s, + quote=FALSE) + file.rename(tfile,transfer.file) + }, + silent=TRUE), + \"try-error\")) + { + if(!file.exists(transfer.file)) + file.create(transfer.file) + } + ) + } +}(object=%s,transfer.file=\"%s\")" + "A template for an R command to evaluate a block of code and write the result to a file. + +Has four %s escapes to be filled in: +1. Row names, \"TRUE\" or \"FALSE\" +2. Column names, \"TRUE\" or \"FALSE\" +3. The code to be run (must be an expression, not a statement) +4. The name of the file to write to") + +(defun org-babel-R-evaluate + (session body result-type result-params column-names-p row-names-p) + "Evaluate R code in BODY." + (if session + (org-babel-R-evaluate-session + session body result-type result-params column-names-p row-names-p) + (org-babel-R-evaluate-external-process + body result-type result-params column-names-p row-names-p))) + +(defun org-babel-R-evaluate-external-process + (body result-type result-params column-names-p row-names-p) + "Evaluate BODY in external R process. +If RESULT-TYPE equals `output' then return standard output as a +string. If RESULT-TYPE equals `value' then return the value of the +last statement in BODY, as elisp." + (cl-case result-type + (value + (let ((tmp-file (org-babel-temp-file "R-"))) + (org-babel-eval org-babel-R-command + (format org-babel-R-write-object-command + (if row-names-p "TRUE" "FALSE") + (if column-names-p + (if row-names-p "NA" "TRUE") + "FALSE") + (format "{function ()\n{\n%s\n}}()" body) + (org-babel-process-file-name tmp-file 'noquote))) + (org-babel-R-process-value-result + (org-babel-result-cond result-params + (with-temp-buffer + (insert-file-contents tmp-file) + (org-babel-chomp (buffer-string) "\n")) + (org-babel-import-elisp-from-file tmp-file '(16))) + column-names-p))) + (output (org-babel-eval org-babel-R-command body)))) + +(defvar ess-eval-visibly-p) + +(defun org-babel-R-evaluate-session + (session body result-type result-params column-names-p row-names-p) + "Evaluate BODY in SESSION. +If RESULT-TYPE equals `output' then return standard output as a +string. If RESULT-TYPE equals `value' then return the value of the +last statement in BODY, as elisp." + (cl-case result-type + (value + (with-temp-buffer + (insert (org-babel-chomp body)) + (let ((ess-local-process-name + (process-name (get-buffer-process session))) + (ess-eval-visibly-p nil)) + (ess-eval-buffer nil))) + (let ((tmp-file (org-babel-temp-file "R-"))) + (org-babel-comint-eval-invisibly-and-wait-for-file + session tmp-file + (format org-babel-R-write-object-command + (if row-names-p "TRUE" "FALSE") + (if column-names-p + (if row-names-p "NA" "TRUE") + "FALSE") + ".Last.value" (org-babel-process-file-name tmp-file 'noquote))) + (org-babel-R-process-value-result + (org-babel-result-cond result-params + (with-temp-buffer + (insert-file-contents tmp-file) + (org-babel-chomp (buffer-string) "\n")) + (org-babel-import-elisp-from-file tmp-file '(16))) + column-names-p))) + (output + (mapconcat + 'org-babel-chomp + (butlast + (delq nil + (mapcar + (lambda (line) (when (> (length line) 0) line)) + (mapcar + (lambda (line) ;; cleanup extra prompts left in output + (if (string-match + "^\\([>+.]\\([ ][>.+]\\)*[ ]\\)" + (car (split-string line "\n"))) + (substring line (match-end 1)) + line)) + (org-babel-comint-with-output (session org-babel-R-eoe-output) + (insert (mapconcat 'org-babel-chomp + (list body org-babel-R-eoe-indicator) + "\n")) + (inferior-ess-send-input)))))) "\n")))) + +(defun org-babel-R-process-value-result (result column-names-p) + "R-specific processing of return value. +Insert hline if column names in output have been requested." + (if column-names-p + (cons (car result) (cons 'hline (cdr result))) + result)) + +(provide 'ob-R) + + + +;;; ob-R.el ends here diff --git a/elpa/org-9.1.14/ob-abc.el b/elpa/org-9.1.14/ob-abc.el new file mode 100644 index 00000000..75881cc3 --- /dev/null +++ b/elpa/org-9.1.14/ob-abc.el @@ -0,0 +1,90 @@ +;;; ob-abc.el --- Org Babel Functions for ABC -*- lexical-binding: t; -*- + +;; Copyright (C) 2013-2018 Free Software Foundation, Inc. + +;; Author: William Waites +;; Keywords: literate programming, music +;; Homepage: http://www.tardis.ed.ac.uk/wwaites +;; Version: 0.01 + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;;; This file adds support to Org Babel for music in ABC notation. +;;; It requires that the abcm2ps program is installed. +;;; See http://moinejf.free.fr/ + +(require 'ob) + +;; optionally define a file extension for this language +(add-to-list 'org-babel-tangle-lang-exts '("abc" . "abc")) + +;; optionally declare default header arguments for this language +(defvar org-babel-default-header-args:abc + '((:results . "file") (:exports . "results")) + "Default arguments to use when evaluating an ABC source block.") + +(defun org-babel-expand-body:abc (body params) + "Expand BODY according to PARAMS, return the expanded body." + (let ((vars (org-babel--get-vars params))) + (mapc + (lambda (pair) + (let ((name (symbol-name (car pair))) + (value (cdr pair))) + (setq body + (replace-regexp-in-string + (concat "\$" (regexp-quote name)) + (if (stringp value) value (format "%S" value)) + body)))) + vars) + body)) + +(defun org-babel-execute:abc (body params) + "Execute a block of ABC code with org-babel. This function is + called by `org-babel-execute-src-block'" + (message "executing Abc source code block") + (let* ((cmdline (cdr (assq :cmdline params))) + (out-file (let ((file (cdr (assq :file params)))) + (if file (replace-regexp-in-string "\.pdf$" ".ps" file) + (error "abc code block requires :file header argument")))) + (in-file (org-babel-temp-file "abc-")) + (render (concat "abcm2ps" " " cmdline + " -O " (org-babel-process-file-name out-file) + " " (org-babel-process-file-name in-file)))) + (with-temp-file in-file (insert (org-babel-expand-body:abc body params))) + (org-babel-eval render "") + ;;; handle where abcm2ps changes the file name (to support multiple files + (when (or (string= (file-name-extension out-file) "eps") + (string= (file-name-extension out-file) "svg")) + (rename-file (concat + (file-name-sans-extension out-file) "001." + (file-name-extension out-file)) + out-file t)) + ;;; if we were asked for a pdf... + (when (string= (file-name-extension (cdr (assq :file params))) "pdf") + (org-babel-eval (concat "ps2pdf" " " out-file " " (cdr (assq :file params))) "")) + ;;; indicate that the file has been written + nil)) + +;; This function should be used to assign any variables in params in +;; the context of the session environment. +(defun org-babel-prep-session:abc (_session _params) + "Return an error because abc does not support sessions." + (error "ABC does not support sessions")) + +(provide 'ob-abc) +;;; ob-abc.el ends here diff --git a/elpa/org-9.1.14/ob-asymptote.el b/elpa/org-9.1.14/ob-asymptote.el new file mode 100644 index 00000000..84e23648 --- /dev/null +++ b/elpa/org-9.1.14/ob-asymptote.el @@ -0,0 +1,139 @@ +;;; ob-asymptote.el --- Babel Functions for Asymptote -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating asymptote source code. +;; +;; This differs from most standard languages in that +;; +;; 1) there is no such thing as a "session" in asymptote +;; +;; 2) we are generally only going to return results of type "file" +;; +;; 3) we are adding the "file" and "cmdline" header arguments, if file +;; is omitted then the -V option is passed to the asy command for +;; interactive viewing + +;;; Requirements: + +;; - The asymptote program :: http://asymptote.sourceforge.net/ +;; +;; - asy-mode :: Major mode for editing asymptote files + +;;; Code: +(require 'ob) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("asymptote" . "asy")) + +(defvar org-babel-default-header-args:asymptote + '((:results . "file") (:exports . "results")) + "Default arguments when evaluating an Asymptote source block.") + +(defun org-babel-execute:asymptote (body params) + "Execute a block of Asymptote code. +This function is called by `org-babel-execute-src-block'." + (let* ((out-file (cdr (assq :file params))) + (format (or (file-name-extension out-file) + "pdf")) + (cmdline (cdr (assq :cmdline params))) + (in-file (org-babel-temp-file "asymptote-")) + (cmd + (concat "asy " + (if out-file + (concat + "-globalwrite -f " format + " -o " (org-babel-process-file-name out-file)) + "-V") + " " cmdline + " " (org-babel-process-file-name in-file)))) + (with-temp-file in-file + (insert (org-babel-expand-body:generic + body params + (org-babel-variable-assignments:asymptote params)))) + (message cmd) (shell-command cmd) + nil)) ;; signal that output has already been written to file + +(defun org-babel-prep-session:asymptote (_session _params) + "Return an error if the :session header argument is set. +Asymptote does not support sessions" + (error "Asymptote does not support sessions")) + +(defun org-babel-variable-assignments:asymptote (params) + "Return list of asymptote statements assigning the block's variables." + (mapcar #'org-babel-asymptote-var-to-asymptote + (org-babel--get-vars params))) + +(defun org-babel-asymptote-var-to-asymptote (pair) + "Convert an elisp value into an Asymptote variable. +The elisp value PAIR is converted into Asymptote code specifying +a variable of the same value." + (let ((var (car pair)) + (val (let ((v (cdr pair))) + (if (symbolp v) (symbol-name v) v)))) + (cond + ((integerp val) + (format "int %S=%S;" var val)) + ((floatp val) + (format "real %S=%S;" var val)) + ((stringp val) + (format "string %S=\"%s\";" var val)) + ((and (listp val) (not (listp (car val)))) + (let* ((type (org-babel-asymptote-define-type val)) + (fmt (if (eq 'string type) "\"%s\"" "%s")) + (vect (mapconcat (lambda (e) (format fmt e)) val ", "))) + (format "%s[] %S={%s};" type var vect))) + ((listp val) + (let* ((type (org-babel-asymptote-define-type val)) + (fmt (if (eq 'string type) "\"%s\"" "%s")) + (array (mapconcat (lambda (row) + (concat "{" + (mapconcat (lambda (e) (format fmt e)) + row ", ") + "}")) + val ","))) + (format "%S[][] %S={%s};" type var array)))))) + +(defun org-babel-asymptote-define-type (data) + "Determine type of DATA. + +DATA is a list. Return type as a symbol. + +The type is `string' if any element in DATA is a string. +Otherwise, it is either `real', if some elements are floats, or +`int'." + (letrec ((type 'int) + (find-type + (lambda (row) + (dolist (e row type) + (cond ((listp e) (setq type (funcall find-type e))) + ((stringp e) (throw 'exit 'string)) + ((floatp e) (setq type 'real))))))) + (catch 'exit (funcall find-type data)) type)) + +(provide 'ob-asymptote) + + + +;;; ob-asymptote.el ends here diff --git a/elpa/org-9.1.14/ob-awk.el b/elpa/org-9.1.14/ob-awk.el new file mode 100644 index 00000000..1ee4552e --- /dev/null +++ b/elpa/org-9.1.14/ob-awk.el @@ -0,0 +1,111 @@ +;;; ob-awk.el --- Babel Functions for Awk -*- lexical-binding: t; -*- + +;; Copyright (C) 2011-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Babel's awk can use special header argument: +;; +;; - :in-file takes a path to a file of data to be processed by awk +;; +;; - :stdin takes an Org data or code block reference, the value of +;; which will be passed to the awk process through STDIN + +;;; Code: +(require 'ob) +(require 'org-compat) + +(declare-function org-babel-ref-resolve "ob-ref" (ref)) +(declare-function orgtbl-to-generic "org-table" (table params)) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("awk" . "awk")) + +(defvar org-babel-awk-command "awk" + "Name of the awk executable command.") + +(defun org-babel-expand-body:awk (body _params) + "Expand BODY according to PARAMS, return the expanded body." + body) + +(defun org-babel-execute:awk (body params) + "Execute a block of Awk code with org-babel. This function is +called by `org-babel-execute-src-block'" + (message "executing Awk source code block") + (let* ((result-params (cdr (assq :result-params params))) + (cmd-line (cdr (assq :cmd-line params))) + (in-file (cdr (assq :in-file params))) + (full-body (org-babel-expand-body:awk body params)) + (code-file (let ((file (org-babel-temp-file "awk-"))) + (with-temp-file file (insert full-body)) file)) + (stdin (let ((stdin (cdr (assq :stdin params)))) + (when stdin + (let ((tmp (org-babel-temp-file "awk-stdin-")) + (res (org-babel-ref-resolve stdin))) + (with-temp-file tmp + (insert (org-babel-awk-var-to-awk res))) + tmp)))) + (cmd (mapconcat #'identity + (append + (list org-babel-awk-command + "-f" code-file cmd-line) + (mapcar (lambda (pair) + (format "-v %s='%s'" + (car pair) + (org-babel-awk-var-to-awk + (cdr pair)))) + (org-babel--get-vars params)) + (list in-file)) + " "))) + (org-babel-reassemble-table + (let ((results + (cond + (stdin (with-temp-buffer + (call-process-shell-command cmd stdin (current-buffer)) + (buffer-string))) + (t (org-babel-eval cmd ""))))) + (when results + (org-babel-result-cond result-params + results + (let ((tmp (org-babel-temp-file "awk-results-"))) + (with-temp-file tmp (insert results)) + (org-babel-import-elisp-from-file tmp))))) + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))) + +(defun org-babel-awk-var-to-awk (var &optional sep) + "Return a printed value of VAR suitable for parsing with awk." + (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v))))) + (cond + ((and (listp var) (listp (car var))) + (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var))) + ((listp var) + (mapconcat echo-var var "\n")) + (t (funcall echo-var var))))) + +(provide 'ob-awk) + + + +;;; ob-awk.el ends here diff --git a/elpa/org-9.1.14/ob-calc.el b/elpa/org-9.1.14/ob-calc.el new file mode 100644 index 00000000..387cba21 --- /dev/null +++ b/elpa/org-9.1.14/ob-calc.el @@ -0,0 +1,110 @@ +;;; ob-calc.el --- Babel Functions for Calc -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating calc code + +;;; Code: +(require 'ob) +(require 'calc) +(require 'calc-trail) +(require 'calc-store) + +(declare-function calc-store-into "calc-store" (&optional var)) +(declare-function calc-recall "calc-store" (&optional var)) +(declare-function math-evaluate-expr "calc-ext" (x)) +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-babel-default-header-args:calc nil + "Default arguments for evaluating a calc source block.") + +(defun org-babel-expand-body:calc (body _params) + "Expand BODY according to PARAMS, return the expanded body." body) + +(defvar org--var-syms) ; Dynamically scoped from org-babel-execute:calc + +(defun org-babel-execute:calc (body params) + "Execute a block of calc code with Babel." + (unless (get-buffer "*Calculator*") + (save-window-excursion (calc) (calc-quit))) + (let* ((vars (org-babel--get-vars params)) + (org--var-syms (mapcar #'car vars)) + (var-names (mapcar #'symbol-name org--var-syms))) + (mapc + (lambda (pair) + (calc-push-list (list (cdr pair))) + (calc-store-into (car pair))) + vars) + (mapc + (lambda (line) + (when (> (length line) 0) + (cond + ;; simple variable name + ((member line var-names) (calc-recall (intern line))) + ;; stack operation + ((string= "'" (substring line 0 1)) + (funcall (lookup-key calc-mode-map (substring line 1)) nil)) + ;; complex expression + (t + (calc-push-list + (list (let ((res (calc-eval line))) + (cond + ((numberp res) res) + ((math-read-number res) (math-read-number res)) + ((listp res) (error "Calc error \"%s\" on input \"%s\"" + (cadr res) line)) + (t (replace-regexp-in-string + "'" "" + (calc-eval + (math-evaluate-expr + ;; resolve user variables, calc built in + ;; variables are handled automatically + ;; upstream by calc + (mapcar #'org-babel-calc-maybe-resolve-var + ;; parse line into calc objects + (car (math-read-exprs line))))))))) + )))))) + (mapcar #'org-trim + (split-string (org-babel-expand-body:calc body params) "[\n\r]")))) + (save-excursion + (with-current-buffer (get-buffer "*Calculator*") + (prog1 + (calc-eval (calc-top 1)) + (calc-pop 1))))) + +(defun org-babel-calc-maybe-resolve-var (el) + (if (consp el) + (if (and (eq 'var (car el)) (member (cadr el) org--var-syms)) + (progn + (calc-recall (cadr el)) + (prog1 (calc-top 1) + (calc-pop 1))) + (mapcar #'org-babel-calc-maybe-resolve-var el)) + el)) + +(provide 'ob-calc) + + + +;;; ob-calc.el ends here diff --git a/elpa/org-9.1.14/ob-clojure.el b/elpa/org-9.1.14/ob-clojure.el new file mode 100644 index 00000000..890f60ad --- /dev/null +++ b/elpa/org-9.1.14/ob-clojure.el @@ -0,0 +1,198 @@ +;;; ob-clojure.el --- Babel Functions for Clojure -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Joel Boehland, Eric Schulte, Oleh Krehel, Frederick Giasson +;; +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Support for evaluating clojure code + +;; Requirements: + +;; - clojure (at least 1.2.0) +;; - clojure-mode +;; - either cider or SLIME + +;; For Cider, see https://github.com/clojure-emacs/cider + +;; For SLIME, the best way to install these components is by following +;; the directions as set out by Phil Hagelberg (Technomancy) on the +;; web page: http://technomancy.us/126 + +;;; Code: +(require 'cl-lib) +(require 'ob) + +(declare-function cider-current-connection "ext:cider-client" (&optional type)) +(declare-function cider-current-ns "ext:cider-client" ()) +(declare-function nrepl--merge "ext:nrepl-client" (dict1 dict2)) +(declare-function nrepl-dict-get "ext:nrepl-client" (dict key)) +(declare-function nrepl-dict-put "ext:nrepl-client" (dict key value)) +(declare-function nrepl-request:eval "ext:nrepl-client" + (input callback connection &optional session ns line column additional-params)) +(declare-function nrepl-sync-request:eval "ext:nrepl-client" + (input connection session &optional ns)) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function slime-eval "ext:slime" (sexp &optional package)) + +(defvar nrepl-sync-request-timeout) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("clojure" . "clj")) + +(defvar org-babel-default-header-args:clojure '()) +(defvar org-babel-header-args:clojure '((package . :any))) + +(defcustom org-babel-clojure-sync-nrepl-timeout 10 + "Timeout value, in seconds, of a Clojure sync call. +If the value is nil, timeout is disabled." + :group 'org-babel + :type 'integer + :version "26.1" + :package-version '(Org . "9.1") + :safe #'wholenump) + +(defcustom org-babel-clojure-backend + (cond ((featurep 'cider) 'cider) + (t 'slime)) + "Backend used to evaluate Clojure code blocks." + :group 'org-babel + :type '(choice + (const :tag "cider" cider) + (const :tag "SLIME" slime))) + +(defun org-babel-expand-body:clojure (body params) + "Expand BODY according to PARAMS, return the expanded body." + (let* ((vars (org-babel--get-vars params)) + (result-params (cdr (assq :result-params params))) + (print-level nil) (print-length nil) + (body (org-trim + (if (null vars) (org-trim body) + (concat "(let [" + (mapconcat + (lambda (var) + (format "%S (quote %S)" (car var) (cdr var))) + vars "\n ") + "]\n" body ")"))))) + (if (or (member "code" result-params) + (member "pp" result-params)) + (format "(clojure.pprint/pprint (do %s))" body) + body))) + +(defun org-babel-execute:clojure (body params) + "Execute a block of Clojure code with Babel. +The underlying process performed by the code block can be output +using the :show-process parameter." + (let ((expanded (org-babel-expand-body:clojure body params)) + (response (list 'dict)) + result) + (cl-case org-babel-clojure-backend + (cider + (require 'cider) + (let ((result-params (cdr (assq :result-params params))) + (show (cdr (assq :show-process params)))) + (if (member show '(nil "no")) + ;; Run code without showing the process. + (progn + (setq response + (let ((nrepl-sync-request-timeout + org-babel-clojure-sync-nrepl-timeout)) + (nrepl-sync-request:eval expanded + (cider-current-connection) + (cider-current-ns)))) + (setq result + (concat + (nrepl-dict-get response + (if (or (member "output" result-params) + (member "pp" result-params)) + "out" + "value")) + (nrepl-dict-get response "ex") + (nrepl-dict-get response "root-ex") + (nrepl-dict-get response "err")))) + ;; Show the process in an output buffer/window. + (let ((process-buffer (switch-to-buffer-other-window + "*Clojure Show Process Sub Buffer*")) + status) + ;; Run the Clojure code in nREPL. + (nrepl-request:eval + expanded + (lambda (resp) + (when (member "out" resp) + ;; Print the output of the nREPL in the output buffer. + (princ (nrepl-dict-get resp "out") process-buffer)) + (when (member "ex" resp) + ;; In case there is an exception, then add it to the + ;; output buffer as well. + (princ (nrepl-dict-get resp "ex") process-buffer) + (princ (nrepl-dict-get resp "root-ex") process-buffer)) + (when (member "err" resp) + ;; In case there is an error, then add it to the + ;; output buffer as well. + (princ (nrepl-dict-get resp "err") process-buffer)) + (nrepl--merge response resp) + ;; Update the status of the nREPL output session. + (setq status (nrepl-dict-get response "status"))) + (cider-current-connection) + (cider-current-ns)) + + ;; Wait until the nREPL code finished to be processed. + (while (not (member "done" status)) + (nrepl-dict-put response "status" (remove "need-input" status)) + (accept-process-output nil 0.01) + (redisplay)) + + ;; Delete the show buffer & window when the processing is + ;; finalized. + (mapc #'delete-window + (get-buffer-window-list process-buffer nil t)) + (kill-buffer process-buffer) + + ;; Put the output or the value in the result section of + ;; the code block. + (setq result + (concat + (nrepl-dict-get response + (if (or (member "output" result-params) + (member "pp" result-params)) + "out" + "value")) + (nrepl-dict-get response "ex") + (nrepl-dict-get response "root-ex") + (nrepl-dict-get response "err"))))))) + (slime + (require 'slime) + (with-temp-buffer + (insert expanded) + (setq result + (slime-eval + `(swank:eval-and-grab-output + ,(buffer-substring-no-properties (point-min) (point-max))) + (cdr (assq :package params))))))) + (org-babel-result-cond (cdr (assq :result-params params)) + result + (condition-case nil (org-babel-script-escape result) + (error result))))) + +(provide 'ob-clojure) + +;;; ob-clojure.el ends here diff --git a/elpa/org-9.1.14/ob-comint.el b/elpa/org-9.1.14/ob-comint.el new file mode 100644 index 00000000..e9c6f937 --- /dev/null +++ b/elpa/org-9.1.14/ob-comint.el @@ -0,0 +1,156 @@ +;;; ob-comint.el --- Babel Functions for Interaction with Comint Buffers -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research, comint +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; These functions build on comint to ease the sending and receiving +;; of commands and results from comint buffers. + +;; Note that the buffers in this file are analogous to sessions in +;; org-babel at large. + +;;; Code: +(require 'ob-core) +(require 'org-compat) +(require 'comint) + +(defun org-babel-comint-buffer-livep (buffer) + "Check if BUFFER is a comint buffer with a live process." + (let ((buffer (if buffer (get-buffer buffer)))) + (and buffer (buffer-live-p buffer) (get-buffer-process buffer) buffer))) + +(defmacro org-babel-comint-in-buffer (buffer &rest body) + "Check BUFFER and execute BODY. +BUFFER is checked with `org-babel-comint-buffer-livep'. BODY is +executed inside the protection of `save-excursion' and +`save-match-data'." + (declare (indent 1)) + `(progn + (unless (org-babel-comint-buffer-livep ,buffer) + (error "Buffer %s does not exist or has no process" ,buffer)) + (save-match-data + (with-current-buffer ,buffer + (save-excursion + (let ((comint-input-filter (lambda (_input) nil))) + ,@body)))))) +(def-edebug-spec org-babel-comint-in-buffer (form body)) + +(defmacro org-babel-comint-with-output (meta &rest body) + "Evaluate BODY in BUFFER and return process output. +Will wait until EOE-INDICATOR appears in the output, then return +all process output. If REMOVE-ECHO and FULL-BODY are present and +non-nil, then strip echo'd body from the returned output. META +should be a list containing the following where the last two +elements are optional. + + (BUFFER EOE-INDICATOR REMOVE-ECHO FULL-BODY) + +This macro ensures that the filter is removed in case of an error +or user `keyboard-quit' during execution of body." + (declare (indent 1)) + (let ((buffer (nth 0 meta)) + (eoe-indicator (nth 1 meta)) + (remove-echo (nth 2 meta)) + (full-body (nth 3 meta))) + `(org-babel-comint-in-buffer ,buffer + (let* ((string-buffer "") + (comint-output-filter-functions + (cons (lambda (text) (setq string-buffer (concat string-buffer text))) + comint-output-filter-functions)) + dangling-text) + ;; got located, and save dangling text + (goto-char (process-mark (get-buffer-process (current-buffer)))) + (let ((start (point)) + (end (point-max))) + (setq dangling-text (buffer-substring start end)) + (delete-region start end)) + ;; pass FULL-BODY to process + ,@body + ;; wait for end-of-evaluation indicator + (while (progn + (goto-char comint-last-input-end) + (not (save-excursion + (and (re-search-forward + (regexp-quote ,eoe-indicator) nil t) + (re-search-forward + comint-prompt-regexp nil t))))) + (accept-process-output (get-buffer-process (current-buffer))) + ;; thought the following this would allow async + ;; background running, but I was wrong... + ;; (run-with-timer .5 .5 'accept-process-output + ;; (get-buffer-process (current-buffer))) + ) + ;; replace cut dangling text + (goto-char (process-mark (get-buffer-process (current-buffer)))) + (insert dangling-text) + + ;; remove echo'd FULL-BODY from input + (when (and ,remove-echo ,full-body + (string-match + (replace-regexp-in-string + "\n" "[\r\n]+" (regexp-quote (or ,full-body ""))) + string-buffer)) + (setq string-buffer (substring string-buffer (match-end 0)))) + (split-string string-buffer comint-prompt-regexp))))) +(def-edebug-spec org-babel-comint-with-output (sexp body)) + +(defun org-babel-comint-input-command (buffer cmd) + "Pass CMD to BUFFER. +The input will not be echoed." + (org-babel-comint-in-buffer buffer + (goto-char (process-mark (get-buffer-process buffer))) + (insert cmd) + (comint-send-input) + (org-babel-comint-wait-for-output buffer))) + +(defun org-babel-comint-wait-for-output (buffer) + "Wait until output arrives from BUFFER. +Note: this is only safe when waiting for the result of a single +statement (not large blocks of code)." + (org-babel-comint-in-buffer buffer + (while (progn + (goto-char comint-last-input-end) + (not (and (re-search-forward comint-prompt-regexp nil t) + (goto-char (match-beginning 0)) + (string= (face-name (face-at-point)) + "comint-highlight-prompt")))) + (accept-process-output (get-buffer-process buffer))))) + +(defun org-babel-comint-eval-invisibly-and-wait-for-file + (buffer file string &optional period) + "Evaluate STRING in BUFFER invisibly. +Don't return until FILE exists. Code in STRING must ensure that +FILE exists at end of evaluation." + (unless (org-babel-comint-buffer-livep buffer) + (error "Buffer %s does not exist or has no process" buffer)) + (when (file-exists-p file) (delete-file file)) + (process-send-string + (get-buffer-process buffer) + (if (= (aref string (1- (length string))) ?\n) string (concat string "\n"))) + (while (not (file-exists-p file)) (sit-for (or period 0.25)))) + +(provide 'ob-comint) + + + +;;; ob-comint.el ends here diff --git a/elpa/org-9.1.14/ob-coq.el b/elpa/org-9.1.14/ob-coq.el new file mode 100644 index 00000000..875c794b --- /dev/null +++ b/elpa/org-9.1.14/ob-coq.el @@ -0,0 +1,78 @@ +;;; ob-coq.el --- Babel Functions for Coq -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Rudimentary support for evaluating Coq code blocks. Currently only +;; session evaluation is supported. Requires both coq.el and +;; coq-inferior.el, both of which are distributed with Coq. +;; +;; http://coq.inria.fr/ + +;;; Code: +(require 'ob) + +(declare-function run-coq "ext:coq-inferior.el" (cmd)) +(declare-function coq-proc "ext:coq-inferior.el" ()) + +(defvar coq-program-name "coqtop" + "Name of the coq toplevel to run.") + +(defvar org-babel-coq-buffer "*coq*" + "Buffer in which to evaluate coq code blocks.") + +(defun org-babel-coq-clean-prompt (string) + (if (string-match "^[^[:space:]]+ < " string) + (substring string 0 (match-beginning 0)) + string)) + +(defun org-babel-execute:coq (body params) + (let ((full-body (org-babel-expand-body:generic body params)) + (session (org-babel-coq-initiate-session)) + (pt (lambda () + (marker-position + (process-mark (get-buffer-process (current-buffer))))))) + (org-babel-coq-clean-prompt + (org-babel-comint-in-buffer session + (let ((start (funcall pt))) + (with-temp-buffer + (insert full-body) + (comint-send-region (coq-proc) (point-min) (point-max)) + (comint-send-string (coq-proc) + (if (string= (buffer-substring (- (point-max) 1) (point-max)) ".") + "\n" + ".\n"))) + (while (equal start (funcall pt)) (sleep-for 0.1)) + (buffer-substring start (funcall pt))))))) + +(defun org-babel-coq-initiate-session () + "Initiate a coq session. +If there is not a current inferior-process-buffer in SESSION then +create one. Return the initialized session." + (unless (fboundp 'run-coq) + (error "`run-coq' not defined, load coq-inferior.el")) + (save-window-excursion (run-coq coq-program-name)) + (sit-for 0.1) + (get-buffer org-babel-coq-buffer)) + +(provide 'ob-coq) diff --git a/elpa/org-9.1.14/ob-core.el b/elpa/org-9.1.14/ob-core.el new file mode 100644 index 00000000..5d5faaa6 --- /dev/null +++ b/elpa/org-9.1.14/ob-core.el @@ -0,0 +1,3161 @@ +;;; ob-core.el --- Working with Code Blocks -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Authors: Eric Schulte +;; Dan Davison +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Code: +(require 'cl-lib) +(require 'ob-eval) +(require 'org-macs) +(require 'org-compat) + +(defconst org-babel-exeext + (if (memq system-type '(windows-nt cygwin)) + ".exe" + nil)) + +(defvar org-babel-library-of-babel) +(defvar org-edit-src-content-indentation) +(defvar org-src-lang-modes) +(defvar org-src-preserve-indentation) + +(declare-function org-at-item-p "org-list" ()) +(declare-function org-at-table-p "org" (&optional table-type)) +(declare-function org-babel-lob-execute-maybe "ob-lob" ()) +(declare-function org-babel-ref-goto-headline-id "ob-ref" (id)) +(declare-function org-babel-ref-headline-body "ob-ref" ()) +(declare-function org-babel-ref-parse "ob-ref" (assignment)) +(declare-function org-babel-ref-resolve "ob-ref" (ref)) +(declare-function org-babel-ref-split-args "ob-ref" (arg-string)) +(declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info)) +(declare-function org-completing-read "org" (&rest args)) +(declare-function org-current-level "org" ()) +(declare-function org-cycle "org" (&optional arg)) +(declare-function org-do-remove-indentation "org" (&optional n)) +(declare-function org-edit-src-code "org-src" (&optional code edit-buffer-name)) +(declare-function org-edit-src-exit "org-src" ()) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-context "org-element" (&optional element)) +(declare-function org-element-normalize-string "org-element" (s)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-type "org-element" (element)) +(declare-function org-entry-get "org" (pom property &optional inherit literal-nil)) +(declare-function org-escape-code-in-region "org-src" (beg end)) +(declare-function org-get-indentation "org" (&optional line)) +(declare-function org-get-indentation "org" (&optional line)) +(declare-function org-in-regexp "org" (regexp &optional nlines visually)) +(declare-function org-indent-line "org" ()) +(declare-function org-list-get-list-end "org-list" (item struct prevs)) +(declare-function org-list-prevs-alist "org-list" (struct)) +(declare-function org-list-struct "org-list" ()) +(declare-function org-list-to-generic "org-list" (LIST PARAMS)) +(declare-function org-list-to-lisp "org-list" (&optional delete)) +(declare-function org-macro-escape-arguments "org-macro" (&rest args)) +(declare-function org-make-options-regexp "org" (kwds &optional extra)) +(declare-function org-mark-ring-push "org" (&optional pos buffer)) +(declare-function org-narrow-to-subtree "org" ()) +(declare-function org-next-block "org" (arg &optional backward block-regexp)) +(declare-function org-open-at-point "org" (&optional in-emacs reference-buffer)) +(declare-function org-outline-overlay-data "org" (&optional use-markers)) +(declare-function org-previous-block "org" (arg &optional block-regexp)) +(declare-function org-remove-indentation "org" (code &optional n)) +(declare-function org-reverse-string "org" (string)) +(declare-function org-set-outline-overlay-data "org" (data)) +(declare-function org-show-context "org" (&optional key)) +(declare-function org-src-coderef-format "org-src" (&optional element)) +(declare-function org-src-coderef-regexp "org-src" (fmt &optional label)) +(declare-function org-table-align "org-table" ()) +(declare-function org-table-end "org-table" (&optional table-type)) +(declare-function org-table-import "org-table" (file arg)) +(declare-function org-table-to-lisp "org-table" (&optional txt)) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function org-unescape-code-in-string "org-src" (s)) +(declare-function org-uniquify "org" (list)) +(declare-function orgtbl-to-generic "org-table" (table params)) +(declare-function orgtbl-to-orgtbl "org-table" (table params)) +(declare-function outline-show-all "outline" ()) +(declare-function tramp-compat-make-temp-file "tramp-compat" (filename &optional dir-flag)) + +(defgroup org-babel nil + "Code block evaluation and management in `org-mode' documents." + :tag "Babel" + :group 'org) + +(defcustom org-confirm-babel-evaluate t + "Confirm before evaluation. +\\\ +Require confirmation before interactively evaluating code +blocks in Org buffers. The default value of this variable is t, +meaning confirmation is required for any code block evaluation. +This variable can be set to nil to inhibit any future +confirmation requests. This variable can also be set to a +function which takes two arguments the language of the code block +and the body of the code block. Such a function should then +return a non-nil value if the user should be prompted for +execution or nil if no prompt is required. + +Warning: Disabling confirmation may result in accidental +evaluation of potentially harmful code. It may be advisable +remove code block execution from `\\[org-ctrl-c-ctrl-c]' \ +as further protection +against accidental code block evaluation. The +`org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to +remove code block execution from the `\\[org-ctrl-c-ctrl-c]' keybinding." + :group 'org-babel + :version "24.1" + :type '(choice boolean function)) +;; don't allow this variable to be changed through file settings +(put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t))) + +(defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil + "\\\ +Remove code block evaluation from the `\\[org-ctrl-c-ctrl-c]' key binding." + :group 'org-babel + :version "24.1" + :type 'boolean) + +(defcustom org-babel-results-keyword "RESULTS" + "Keyword used to name results generated by code blocks. +It should be \"RESULTS\". However any capitalization may be +used." + :group 'org-babel + :version "24.4" + :package-version '(Org . "8.0") + :type 'string + :safe (lambda (v) + (and (stringp v) + (eq (compare-strings "RESULTS" nil nil v nil nil t) + t)))) + +(defcustom org-babel-noweb-wrap-start "<<" + "String used to begin a noweb reference in a code block. +See also `org-babel-noweb-wrap-end'." + :group 'org-babel + :type 'string) + +(defcustom org-babel-noweb-wrap-end ">>" + "String used to end a noweb reference in a code block. +See also `org-babel-noweb-wrap-start'." + :group 'org-babel + :type 'string) + +(defcustom org-babel-inline-result-wrap "=%s=" + "Format string used to wrap inline results. +This string must include a \"%s\" which will be replaced by the results." + :group 'org-babel + :type 'string) +(put 'org-babel-inline-result-wrap + 'safe-local-variable + (lambda (value) + (and (stringp value) + (string-match-p "%s" value)))) + +(defcustom org-babel-hash-show-time nil + "Non-nil means show the time the code block was evaluated in the result hash." + :group 'org-babel + :type 'boolean + :version "26.1" + :package-version '(Org . "9.0") + :safe #'booleanp) + +(defcustom org-babel-uppercase-example-markers nil + "When non-nil, begin/end example markers will be inserted in upper case." + :group 'org-babel + :type 'boolean + :version "26.1" + :package-version '(Org . "9.1") + :safe #'booleanp) + +(defun org-babel-noweb-wrap (&optional regexp) + (concat org-babel-noweb-wrap-start + (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)") + org-babel-noweb-wrap-end)) + +(defvar org-babel-src-name-regexp + "^[ \t]*#\\+name:[ \t]*" + "Regular expression used to match a source name line.") + +(defvar org-babel-multi-line-header-regexp + "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$" + "Regular expression used to match multi-line header arguments.") + +(defvar org-babel-src-block-regexp + (concat + ;; (1) indentation (2) lang + "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*" + ;; (3) switches + "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)" + ;; (4) header arguments + "\\([^\n]*\\)\n" + ;; (5) body + "\\([^\000]*?\n\\)??[ \t]*#\\+end_src") + "Regexp used to identify code blocks.") + +(defun org-babel--get-vars (params) + "Return the babel variable assignments in PARAMS. + +PARAMS is a quasi-alist of header args, which may contain +multiple entries for the key `:var'. This function returns a +list of the cdr of all the `:var' entries." + (mapcar #'cdr + (cl-remove-if-not (lambda (x) (eq (car x) :var)) params))) + +(defvar org-babel-exp-reference-buffer nil + "Buffer containing original contents of the exported buffer. +This is used by Babel to resolve references in source blocks. +Its value is dynamically bound during export.") + +(defun org-babel-check-confirm-evaluate (info) + "Check whether INFO allows code block evaluation. + +Returns nil if evaluation is disallowed, t if it is +unconditionally allowed, and the symbol `query' if the user +should be asked whether to allow evaluation." + (let* ((headers (nth 2 info)) + (eval (or (cdr (assq :eval headers)) + (when (assq :noeval headers) "no"))) + (eval-no (member eval '("no" "never"))) + (export org-babel-exp-reference-buffer) + (eval-no-export (and export (member eval '("no-export" "never-export")))) + (noeval (or eval-no eval-no-export)) + (query (or (equal eval "query") + (and export (equal eval "query-export")) + (if (functionp org-confirm-babel-evaluate) + (funcall org-confirm-babel-evaluate + ;; Language, code block body. + (nth 0 info) (nth 1 info)) + org-confirm-babel-evaluate)))) + (cond + (noeval nil) + (query 'query) + (t t)))) + +(defun org-babel-check-evaluate (info) + "Check if code block INFO should be evaluated. +Do not query the user, but do display an informative message if +evaluation is blocked. Returns non-nil if evaluation is not blocked." + (let ((confirmed (org-babel-check-confirm-evaluate info))) + (unless confirmed + (message "Evaluation of this %s code block%sis disabled." + (nth 0 info) + (let ((name (nth 4 info))) + (if name (format " (%s) " name) " ")))) + confirmed)) + +;; Dynamically scoped for asynchronous export. +(defvar org-babel-confirm-evaluate-answer-no) + +(defun org-babel-confirm-evaluate (info) + "Confirm evaluation of the code block INFO. + +This query can also be suppressed by setting the value of +`org-confirm-babel-evaluate' to nil, in which case all future +interactive code block evaluations will proceed without any +confirmation from the user. + +Note disabling confirmation may result in accidental evaluation +of potentially harmful code. + +The variable `org-babel-confirm-evaluate-answer-no' is used by +the async export process, which requires a non-interactive +environment, to override this check." + (let* ((evalp (org-babel-check-confirm-evaluate info)) + (lang (nth 0 info)) + (name (nth 4 info)) + (name-string (if name (format " (%s) " name) " "))) + (pcase evalp + (`nil nil) + (`t t) + (`query (or + (and (not (bound-and-true-p + org-babel-confirm-evaluate-answer-no)) + (yes-or-no-p + (format "Evaluate this %s code block%son your system? " + lang name-string))) + (progn + (message "Evaluation of this %s code block%sis aborted." + lang name-string) + nil))) + (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x))))) + +;;;###autoload +(defun org-babel-execute-safely-maybe () + (unless org-babel-no-eval-on-ctrl-c-ctrl-c + (org-babel-execute-maybe))) + +;;;###autoload +(defun org-babel-execute-maybe () + (interactive) + (or (org-babel-execute-src-block-maybe) + (org-babel-lob-execute-maybe))) + +(defmacro org-babel-when-in-src-block (&rest body) + "Execute BODY if point is in a source block and return t. + +Otherwise do nothing and return nil." + `(if (memq (org-element-type (org-element-context)) + '(inline-src-block src-block)) + (progn + ,@body + t) + nil)) + +(defun org-babel-execute-src-block-maybe () + "Conditionally execute a source block. +Detect if this is context for a Babel src-block and if so +then run `org-babel-execute-src-block'." + (interactive) + (org-babel-when-in-src-block + (org-babel-eval-wipe-error-buffer) + (org-babel-execute-src-block current-prefix-arg))) + +;;;###autoload +(defun org-babel-view-src-block-info () + "Display information on the current source block. +This includes header arguments, language and name, and is largely +a window into the `org-babel-get-src-block-info' function." + (interactive) + (let ((info (org-babel-get-src-block-info 'light)) + (full (lambda (it) (> (length it) 0))) + (printf (lambda (fmt &rest args) (princ (apply #'format fmt args))))) + (when info + (with-help-window (help-buffer) + (let ((name (nth 4 info)) + (lang (nth 0 info)) + (switches (nth 3 info)) + (header-args (nth 2 info))) + (when name (funcall printf "Name: %s\n" name)) + (when lang (funcall printf "Lang: %s\n" lang)) + (funcall printf "Properties:\n") + (funcall printf "\t:header-args \t%s\n" (org-entry-get (point) "header-args" t)) + (funcall printf "\t:header-args:%s \t%s\n" lang (org-entry-get (point) (concat "header-args:" lang) t)) + + (when (funcall full switches) (funcall printf "Switches: %s\n" switches)) + (funcall printf "Header Arguments:\n") + (dolist (pair (sort header-args + (lambda (a b) (string< (symbol-name (car a)) + (symbol-name (car b)))))) + (when (funcall full (format "%s" (cdr pair))) + (funcall printf "\t%S%s\t%s\n" + (car pair) + (if (> (length (format "%S" (car pair))) 7) "" "\t") + (cdr pair))))))))) + +;;;###autoload +(defun org-babel-expand-src-block-maybe () + "Conditionally expand a source block. +Detect if this is context for an org-babel src-block and if so +then run `org-babel-expand-src-block'." + (interactive) + (org-babel-when-in-src-block + (org-babel-expand-src-block current-prefix-arg))) + +;;;###autoload +(defun org-babel-load-in-session-maybe () + "Conditionally load a source block in a session. +Detect if this is context for an org-babel src-block and if so +then run `org-babel-load-in-session'." + (interactive) + (org-babel-when-in-src-block + (org-babel-load-in-session current-prefix-arg))) + +(add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe) + +;;;###autoload +(defun org-babel-pop-to-session-maybe () + "Conditionally pop to a session. +Detect if this is context for an org-babel src-block and if so +then run `org-babel-switch-to-session'." + (interactive) + (org-babel-when-in-src-block + (org-babel-switch-to-session current-prefix-arg))) + +(add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe) + +(defconst org-babel-common-header-args-w-values + '((cache . ((no yes))) + (cmdline . :any) + (colnames . ((nil no yes))) + (comments . ((no link yes org both noweb))) + (dir . :any) + (eval . ((yes no no-export strip-export never-export eval never + query))) + (exports . ((code results both none))) + (epilogue . :any) + (file . :any) + (file-desc . :any) + (file-ext . :any) + (hlines . ((no yes))) + (mkdirp . ((yes no))) + (no-expand) + (noeval) + (noweb . ((yes no tangle no-export strip-export))) + (noweb-ref . :any) + (noweb-sep . :any) + (output-dir . :any) + (padline . ((yes no))) + (post . :any) + (prologue . :any) + (results . ((file list vector table scalar verbatim) + (raw html latex org code pp drawer) + (replace silent none append prepend) + (output value))) + (rownames . ((no yes))) + (sep . :any) + (session . :any) + (shebang . :any) + (tangle . ((tangle yes no :any))) + (tangle-mode . ((#o755 #o555 #o444 :any))) + (var . :any) + (wrap . :any))) + +(defconst org-babel-header-arg-names + (mapcar #'car org-babel-common-header-args-w-values) + "Common header arguments used by org-babel. +Note that individual languages may define their own language +specific header arguments as well.") + +(defconst org-babel-safe-header-args + '(:cache :colnames :comments :exports :epilogue :hlines :noeval + :noweb :noweb-ref :noweb-sep :padline :prologue :rownames + :sep :session :tangle :wrap + (:eval . ("never" "query")) + (:results . (lambda (str) (not (string-match "file" str))))) + "A list of safe header arguments for babel source blocks. + +The list can have entries of the following forms: +- :ARG -> :ARG is always a safe header arg +- (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is + `equal' to one of the VALs. +- (:ARG . FN) -> :ARG is safe as a header arg if the function FN + returns non-nil. FN is passed one + argument, the value of the header arg + (as a string).") + +(defmacro org-babel-header-args-safe-fn (safe-list) + "Return a function that determines whether a list of header args are safe. + +Intended usage is: +\(put \\='org-babel-default-header-args \\='safe-local-variable + (org-babel-header-args-safe-p org-babel-safe-header-args) + +This allows org-babel languages to extend the list of safe values for +their `org-babel-default-header-args:foo' variable. + +For the format of SAFE-LIST, see `org-babel-safe-header-args'." + `(lambda (value) + (and (listp value) + (cl-every + (lambda (pair) + (and (consp pair) + (org-babel-one-header-arg-safe-p pair ,safe-list))) + value)))) + +(defvar org-babel-default-header-args + '((:session . "none") (:results . "replace") (:exports . "code") + (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no")) + "Default arguments to use when evaluating a source block.") +(put 'org-babel-default-header-args 'safe-local-variable + (org-babel-header-args-safe-fn org-babel-safe-header-args)) + +(defvar org-babel-default-inline-header-args + '((:session . "none") (:results . "replace") + (:exports . "results") (:hlines . "yes")) + "Default arguments to use when evaluating an inline source block.") +(put 'org-babel-default-inline-header-args 'safe-local-variable + (org-babel-header-args-safe-fn org-babel-safe-header-args)) + +(defconst org-babel-name-regexp + (format "^[ \t]*#\\+%s:[ \t]*" + ;; FIXME: TBLNAME is for backward compatibility. + (regexp-opt '("NAME" "TBLNAME"))) + "Regexp matching a NAME keyword.") + +(defconst org-babel-result-regexp + (format "^[ \t]*#\\+%s\\(?:\\[\\(?:%s \\)?\\([[:alnum:]]+\\)\\]\\)?:[ \t]*" + org-babel-results-keyword + ;; <%Y-%m-%d %H:%M:%S> + "<\\(?:[0-9]\\{4\\}-[0-1][0-9]-[0-3][0-9] \ +[0-2][0-9]\\(?::[0-5][0-9]\\)\\{2\\}\\)>") + "Regular expression used to match result lines. +If the results are associated with a hash key then the hash will +be saved in match group 1.") + +(defconst org-babel-result-w-name-regexp + (concat org-babel-result-regexp "\\(?9:[^ \t\n\r\v\f]+\\)") + "Regexp matching a RESULTS keyword with a name. +Name is saved in match group 9.") + +(defvar org-babel-min-lines-for-block-output 10 + "The minimum number of lines for block output. +If number of lines of output is equal to or exceeds this +value, the output is placed in a #+begin_example...#+end_example +block. Otherwise the output is marked as literal by inserting +colons at the starts of the lines. This variable only takes +effect if the :results output option is in effect.") + +(defvar org-babel-noweb-error-all-langs nil + "Raise errors when noweb references don't resolve. +Also see `org-babel-noweb-error-langs' to control noweb errors on +a language by language bases.") + +(defvar org-babel-noweb-error-langs nil + "Languages for which Babel will raise literate programming errors. +List of languages for which errors should be raised when the +source code block satisfying a noweb reference in this language +can not be resolved. Also see `org-babel-noweb-error-all-langs' +to raise errors for all languages.") + +(defvar org-babel-hash-show 4 + "Number of initial characters to show of a hidden results hash.") + +(defvar org-babel-after-execute-hook nil + "Hook for functions to be called after `org-babel-execute-src-block'") + +(defun org-babel-named-src-block-regexp-for-name (&optional name) + "This generates a regexp used to match a src block named NAME. +If NAME is nil, match any name. Matched name is then put in +match group 9. Other match groups are defined in +`org-babel-src-block-regexp'." + (concat org-babel-src-name-regexp + (concat (if name (regexp-quote name) "\\(?9:.*?\\)") "[ \t]*" ) + "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?" + "\n" + (substring org-babel-src-block-regexp 1))) + +(defun org-babel-named-data-regexp-for-name (name) + "This generates a regexp used to match data named NAME." + (concat org-babel-name-regexp (regexp-quote name) "[ \t]*$")) + +(defun org-babel--normalize-body (datum) + "Normalize body for element or object DATUM. +DATUM is a source block element or an inline source block object. +Remove final newline character and spurious indentation." + (let* ((value (org-element-property :value datum)) + (body (if (string-suffix-p "\n" value) + (substring value 0 -1) + value))) + (cond ((eq (org-element-type datum) 'inline-src-block) + ;; Newline characters and indentation in an inline + ;; src-block are not meaningful, since they could come from + ;; some paragraph filling. Treat them as a white space. + (replace-regexp-in-string "\n[ \t]*" " " body)) + ((or org-src-preserve-indentation + (org-element-property :preserve-indent datum)) + body) + (t (org-remove-indentation body))))) + +;;; functions +(defvar org-babel-current-src-block-location nil + "Marker pointing to the src block currently being executed. +This may also point to a call line or an inline code block. If +multiple blocks are being executed (e.g., in chained execution +through use of the :var header argument) this marker points to +the outer-most code block.") + +(defvar *this*) + +(defun org-babel-get-src-block-info (&optional light datum) + "Extract information from a source block or inline source block. + +Optional argument LIGHT does not resolve remote variable +references; a process which could likely result in the execution +of other code blocks. + +By default, consider the block at point. However, when optional +argument DATUM is provided, extract information from that parsed +object instead. + +Return nil if point is not on a source block. Otherwise, return +a list with the following pattern: + + (language body arguments switches name start coderef)" + (let* ((datum (or datum (org-element-context))) + (type (org-element-type datum)) + (inline (eq type 'inline-src-block))) + (when (memq type '(inline-src-block src-block)) + (let* ((lang (org-element-property :language datum)) + (lang-headers (intern + (concat "org-babel-default-header-args:" lang))) + (name (org-element-property :name datum)) + (info + (list + lang + (org-babel--normalize-body datum) + (apply #'org-babel-merge-params + (if inline org-babel-default-inline-header-args + org-babel-default-header-args) + (and (boundp lang-headers) (eval lang-headers t)) + (append + ;; If DATUM is provided, make sure we get node + ;; properties applicable to its location within + ;; the document. + (org-with-point-at (org-element-property :begin datum) + (org-babel-params-from-properties lang)) + (mapcar #'org-babel-parse-header-arguments + (cons (org-element-property :parameters datum) + (org-element-property :header datum))))) + (or (org-element-property :switches datum) "") + name + (org-element-property (if inline :begin :post-affiliated) + datum) + (and (not inline) (org-src-coderef-format datum))))) + (unless light + (setf (nth 2 info) (org-babel-process-params (nth 2 info)))) + (setf (nth 2 info) (org-babel-generate-file-param name (nth 2 info))) + info)))) + +;;;###autoload +(defun org-babel-execute-src-block (&optional arg info params) + "Execute the current source code block. +Insert the results of execution into the buffer. Source code +execution and the collection and formatting of results can be +controlled through a variety of header arguments. + +With prefix argument ARG, force re-execution even if an existing +result cached in the buffer would otherwise have been returned. + +Optionally supply a value for INFO in the form returned by +`org-babel-get-src-block-info'. + +Optionally supply a value for PARAMS which will be merged with +the header arguments specified at the front of the source code +block." + (interactive) + (let* ((org-babel-current-src-block-location + (or org-babel-current-src-block-location + (nth 5 info) + (org-babel-where-is-src-block-head))) + (info (if info (copy-tree info) (org-babel-get-src-block-info)))) + ;; Merge PARAMS with INFO before considering source block + ;; evaluation since both could disagree. + (cl-callf org-babel-merge-params (nth 2 info) params) + (when (org-babel-check-evaluate info) + (cl-callf org-babel-process-params (nth 2 info)) + (let* ((params (nth 2 info)) + (cache (let ((c (cdr (assq :cache params)))) + (and (not arg) c (string= "yes" c)))) + (new-hash (and cache (org-babel-sha1-hash info))) + (old-hash (and cache (org-babel-current-result-hash))) + (current-cache (and new-hash (equal new-hash old-hash)))) + (cond + (current-cache + (save-excursion ;Return cached result. + (goto-char (org-babel-where-is-src-block-result nil info)) + (forward-line) + (skip-chars-forward " \t") + (let ((result (org-babel-read-result))) + (message (replace-regexp-in-string "%" "%%" (format "%S" result))) + result))) + ((org-babel-confirm-evaluate info) + (let* ((lang (nth 0 info)) + (result-params (cdr (assq :result-params params))) + ;; Expand noweb references in BODY and remove any + ;; coderef. + (body + (let ((coderef (nth 6 info)) + (expand + (if (org-babel-noweb-p params :eval) + (org-babel-expand-noweb-references info) + (nth 1 info)))) + (if (not coderef) expand + (replace-regexp-in-string + (org-src-coderef-regexp coderef) "" expand nil nil 1)))) + (dir (cdr (assq :dir params))) + (default-directory + (or (and dir (file-name-as-directory (expand-file-name dir))) + default-directory)) + (cmd (intern (concat "org-babel-execute:" lang))) + result) + (unless (fboundp cmd) + (error "No org-babel-execute function for %s!" lang)) + (message "executing %s code block%s..." + (capitalize lang) + (let ((name (nth 4 info))) + (if name (format " (%s)" name) ""))) + (if (member "none" result-params) + (progn (funcall cmd body params) + (message "result silenced")) + (setq result + (let ((r (funcall cmd body params))) + (if (and (eq (cdr (assq :result-type params)) 'value) + (or (member "vector" result-params) + (member "table" result-params)) + (not (listp r))) + (list (list r)) + r))) + (let ((file (cdr (assq :file params)))) + ;; If non-empty result and :file then write to :file. + (when file + (when result + (with-temp-file file + (insert (org-babel-format-result + result (cdr (assq :sep params)))))) + (setq result file)) + ;; Possibly perform post process provided its + ;; appropriate. Dynamically bind "*this*" to the + ;; actual results of the block. + (let ((post (cdr (assq :post params)))) + (when post + (let ((*this* (if (not file) result + (org-babel-result-to-file + file + (let ((desc (assq :file-desc params))) + (and desc (or (cdr desc) result))))))) + (setq result (org-babel-ref-resolve post)) + (when file + (setq result-params (remove "file" result-params)))))) + (org-babel-insert-result + result result-params info new-hash lang))) + (run-hooks 'org-babel-after-execute-hook) + result))))))) + +(defun org-babel-expand-body:generic (body params &optional var-lines) + "Expand BODY with PARAMS. +Expand a block of code with org-babel according to its header +arguments. This generic implementation of body expansion is +called for languages which have not defined their own specific +org-babel-expand-body:lang function." + (let ((pro (cdr (assq :prologue params))) + (epi (cdr (assq :epilogue params)))) + (mapconcat #'identity + (append (when pro (list pro)) + var-lines + (list body) + (when epi (list epi))) + "\n"))) + +;;;###autoload +(defun org-babel-expand-src-block (&optional _arg info params) + "Expand the current source code block. +Expand according to the source code block's header +arguments and pop open the results in a preview buffer." + (interactive) + (let* ((info (or info (org-babel-get-src-block-info))) + (lang (nth 0 info)) + (params (setf (nth 2 info) + (sort (org-babel-merge-params (nth 2 info) params) + (lambda (el1 el2) (string< (symbol-name (car el1)) + (symbol-name (car el2))))))) + (body (setf (nth 1 info) + (if (org-babel-noweb-p params :eval) + (org-babel-expand-noweb-references info) (nth 1 info)))) + (expand-cmd (intern (concat "org-babel-expand-body:" lang))) + (assignments-cmd (intern (concat "org-babel-variable-assignments:" + lang))) + (expanded + (if (fboundp expand-cmd) (funcall expand-cmd body params) + (org-babel-expand-body:generic + body params (and (fboundp assignments-cmd) + (funcall assignments-cmd params)))))) + (if (called-interactively-p 'any) + (org-edit-src-code + expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*")) + expanded))) + +(defun org-babel-edit-distance (s1 s2) + "Return the edit (levenshtein) distance between strings S1 S2." + (let* ((l1 (length s1)) + (l2 (length s2)) + (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil)) + (number-sequence 1 (1+ l1))))) + (in (lambda (i j) (aref (aref dist i) j)))) + (setf (aref (aref dist 0) 0) 0) + (dolist (j (number-sequence 1 l2)) + (setf (aref (aref dist 0) j) j)) + (dolist (i (number-sequence 1 l1)) + (setf (aref (aref dist i) 0) i) + (dolist (j (number-sequence 1 l2)) + (setf (aref (aref dist i) j) + (min + (1+ (funcall in (1- i) j)) + (1+ (funcall in i (1- j))) + (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1) + (funcall in (1- i) (1- j))))))) + (funcall in l1 l2))) + +(defun org-babel-combine-header-arg-lists (original &rest others) + "Combine a number of lists of header argument names and arguments." + (let ((results (copy-sequence original))) + (dolist (new-list others) + (dolist (arg-pair new-list) + (let ((header (car arg-pair))) + (setq results + (cons arg-pair (cl-remove-if + (lambda (pair) (equal header (car pair))) + results)))))) + results)) + +;;;###autoload +(defun org-babel-check-src-block () + "Check for misspelled header arguments in the current code block." + (interactive) + ;; TODO: report malformed code block + ;; TODO: report incompatible combinations of header arguments + ;; TODO: report uninitialized variables + (let ((too-close 2) ;; <- control closeness to report potential match + (names (mapcar #'symbol-name org-babel-header-arg-names))) + (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1)) + (and (org-babel-where-is-src-block-head) + (org-babel-parse-header-arguments + (org-no-properties + (match-string 4)))))) + (dolist (name names) + (when (and (not (string= header name)) + (<= (org-babel-edit-distance header name) too-close) + (not (member header names))) + (error "Supplied header \"%S\" is suspiciously close to \"%S\"" + header name)))) + (message "No suspicious header arguments found."))) + +;;;###autoload +(defun org-babel-insert-header-arg (&optional header-arg value) + "Insert a header argument selecting from lists of common args and values." + (interactive) + (let* ((info (org-babel-get-src-block-info 'light)) + (lang (car info)) + (begin (nth 5 info)) + (lang-headers (intern (concat "org-babel-header-args:" lang))) + (headers (org-babel-combine-header-arg-lists + org-babel-common-header-args-w-values + (when (boundp lang-headers) (eval lang-headers t)))) + (header-arg (or header-arg + (completing-read + "Header Arg: " + (mapcar + (lambda (header-spec) (symbol-name (car header-spec))) + headers)))) + (vals (cdr (assoc (intern header-arg) headers))) + (value (or value + (cond + ((eq vals :any) + (read-from-minibuffer "value: ")) + ((listp vals) + (mapconcat + (lambda (group) + (let ((arg (completing-read + "Value: " + (cons "default" + (mapcar #'symbol-name group))))) + (if (and arg (not (string= "default" arg))) + (concat arg " ") + ""))) + vals "")))))) + (save-excursion + (goto-char begin) + (goto-char (point-at-eol)) + (unless (= (char-before (point)) ?\ ) (insert " ")) + (insert ":" header-arg) (when value (insert " " value))))) + +;; Add support for completing-read insertion of header arguments after ":" +(defun org-babel-header-arg-expand () + "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts." + (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head)) + (org-babel-enter-header-arg-w-completion (match-string 2)))) + +(defun org-babel-enter-header-arg-w-completion (&optional lang) + "Insert header argument appropriate for LANG with completion." + (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang))) + (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var t))) + (headers-w-values (org-babel-combine-header-arg-lists + org-babel-common-header-args-w-values lang-headers)) + (headers (mapcar #'symbol-name (mapcar #'car headers-w-values))) + (header (org-completing-read "Header Arg: " headers)) + (args (cdr (assoc (intern header) headers-w-values))) + (arg (when (and args (listp args)) + (org-completing-read + (format "%s: " header) + (mapcar #'symbol-name (apply #'append args)))))) + (insert (concat header " " (or arg ""))) + (cons header arg))) + +(add-hook 'org-tab-first-hook 'org-babel-header-arg-expand) + +;;;###autoload +(defun org-babel-load-in-session (&optional _arg info) + "Load the body of the current source-code block. +Evaluate the header arguments for the source block before +entering the session. After loading the body this pops open the +session." + (interactive) + (let* ((info (or info (org-babel-get-src-block-info))) + (lang (nth 0 info)) + (params (nth 2 info)) + (body (if (not info) + (user-error "No src code block at point") + (setf (nth 1 info) + (if (org-babel-noweb-p params :eval) + (org-babel-expand-noweb-references info) + (nth 1 info))))) + (session (cdr (assq :session params))) + (dir (cdr (assq :dir params))) + (default-directory + (or (and dir (file-name-as-directory dir)) default-directory)) + (cmd (intern (concat "org-babel-load-session:" lang)))) + (unless (fboundp cmd) + (error "No org-babel-load-session function for %s!" lang)) + (pop-to-buffer (funcall cmd session body params)) + (end-of-line 1))) + +;;;###autoload +(defun org-babel-initiate-session (&optional arg info) + "Initiate session for current code block. +If called with a prefix argument then resolve any variable +references in the header arguments and assign these variables in +the session. Copy the body of the code block to the kill ring." + (interactive "P") + (let* ((info (or info (org-babel-get-src-block-info (not arg)))) + (lang (nth 0 info)) + (body (nth 1 info)) + (params (nth 2 info)) + (session (cdr (assq :session params))) + (dir (cdr (assq :dir params))) + (default-directory + (or (and dir (file-name-as-directory dir)) default-directory)) + (init-cmd (intern (format "org-babel-%s-initiate-session" lang))) + (prep-cmd (intern (concat "org-babel-prep-session:" lang)))) + (when (and (stringp session) (string= session "none")) + (error "This block is not using a session!")) + (unless (fboundp init-cmd) + (error "No org-babel-initiate-session function for %s!" lang)) + (with-temp-buffer (insert (org-trim body)) + (copy-region-as-kill (point-min) (point-max))) + (when arg + (unless (fboundp prep-cmd) + (error "No org-babel-prep-session function for %s!" lang)) + (funcall prep-cmd session params)) + (funcall init-cmd session params))) + +;;;###autoload +(defun org-babel-switch-to-session (&optional arg info) + "Switch to the session of the current code block. +Uses `org-babel-initiate-session' to start the session. If called +with a prefix argument then this is passed on to +`org-babel-initiate-session'." + (interactive "P") + (pop-to-buffer (org-babel-initiate-session arg info)) + (end-of-line 1)) + +(defalias 'org-babel-pop-to-session 'org-babel-switch-to-session) + +(defvar org-src-window-setup) + +;;;###autoload +(defun org-babel-switch-to-session-with-code (&optional arg _info) + "Switch to code buffer and display session." + (interactive "P") + (let ((swap-windows + (lambda () + (let ((other-window-buffer (window-buffer (next-window)))) + (set-window-buffer (next-window) (current-buffer)) + (set-window-buffer (selected-window) other-window-buffer)) + (other-window 1))) + (info (org-babel-get-src-block-info)) + (org-src-window-setup 'reorganize-frame)) + (save-excursion + (org-babel-switch-to-session arg info)) + (org-edit-src-code) + (funcall swap-windows))) + +;;;###autoload +(defmacro org-babel-do-in-edit-buffer (&rest body) + "Evaluate BODY in edit buffer if there is a code block at point. +Return t if a code block was found at point, nil otherwise." + (declare (debug (body))) + `(let* ((element (org-element-at-point)) + ;; This function is not supposed to move point. However, + ;; `org-edit-src-code' always moves point back into the + ;; source block. It is problematic if the point was before + ;; the code, e.g., on block's opening line. In this case, + ;; we want to restore this location after executing BODY. + (outside-position + (and (<= (line-beginning-position) + (org-element-property :post-affiliated element)) + (point-marker))) + (org-src-window-setup 'switch-invisibly)) + (when (and (org-babel-where-is-src-block-head element) + (org-edit-src-code)) + (unwind-protect (progn ,@body) + (org-edit-src-exit) + (when outside-position (goto-char outside-position))) + t))) + +(defun org-babel-do-key-sequence-in-edit-buffer (key) + "Read key sequence and execute the command in edit buffer. +Enter a key sequence to be executed in the language major-mode +edit buffer. For example, TAB will alter the contents of the +Org code block according to the effect of TAB in the language +major mode buffer. For languages that support interactive +sessions, this can be used to send code from the Org buffer +to the session for evaluation using the native major mode +evaluation mechanisms." + (interactive "kEnter key-sequence to execute in edit buffer: ") + (org-babel-do-in-edit-buffer + (call-interactively + (key-binding (or key (read-key-sequence nil)))))) + +(defvar org-bracket-link-regexp) + +(defun org-babel-active-location-p () + (memq (org-element-type (save-match-data (org-element-context))) + '(babel-call inline-babel-call inline-src-block src-block))) + +;;;###autoload +(defun org-babel-open-src-block-result (&optional re-run) + "If `point' is on a src block then open the results of the +source code block, otherwise return nil. With optional prefix +argument RE-RUN the source-code block is evaluated even if +results already exist." + (interactive "P") + (let ((info (org-babel-get-src-block-info 'light))) + (when info + (save-excursion + ;; go to the results, if there aren't any then run the block + (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result)) + (progn (org-babel-execute-src-block) + (org-babel-where-is-src-block-result)))) + (end-of-line 1) + (while (looking-at "[\n\r\t\f ]") (forward-char 1)) + ;; open the results + (if (looking-at org-bracket-link-regexp) + ;; file results + (org-open-at-point) + (let ((r (org-babel-format-result + (org-babel-read-result) (cdr (assq :sep (nth 2 info)))))) + (pop-to-buffer (get-buffer-create "*Org-Babel Results*")) + (delete-region (point-min) (point-max)) + (insert r))) + t)))) + +;;;###autoload +(defmacro org-babel-map-src-blocks (file &rest body) + "Evaluate BODY forms on each source-block in FILE. +If FILE is nil evaluate BODY forms on source blocks in current +buffer. During evaluation of BODY the following local variables +are set relative to the currently matched code block. + +full-block ------- string holding the entirety of the code block +beg-block -------- point at the beginning of the code block +end-block -------- point at the end of the matched code block +lang ------------- string holding the language of the code block +beg-lang --------- point at the beginning of the lang +end-lang --------- point at the end of the lang +switches --------- string holding the switches +beg-switches ----- point at the beginning of the switches +end-switches ----- point at the end of the switches +header-args ------ string holding the header-args +beg-header-args -- point at the beginning of the header-args +end-header-args -- point at the end of the header-args +body ------------- string holding the body of the code block +beg-body --------- point at the beginning of the body +end-body --------- point at the end of the body" + (declare (indent 1)) + (let ((tempvar (make-symbol "file"))) + `(let* ((case-fold-search t) + (,tempvar ,file) + (visited-p (or (null ,tempvar) + (get-file-buffer (expand-file-name ,tempvar)))) + (point (point)) to-be-removed) + (save-window-excursion + (when ,tempvar (find-file ,tempvar)) + (setq to-be-removed (current-buffer)) + (goto-char (point-min)) + (while (re-search-forward org-babel-src-block-regexp nil t) + (when (org-babel-active-location-p) + (goto-char (match-beginning 0)) + (let ((full-block (match-string 0)) + (beg-block (match-beginning 0)) + (end-block (match-end 0)) + (lang (match-string 2)) + (beg-lang (match-beginning 2)) + (end-lang (match-end 2)) + (switches (match-string 3)) + (beg-switches (match-beginning 3)) + (end-switches (match-end 3)) + (header-args (match-string 4)) + (beg-header-args (match-beginning 4)) + (end-header-args (match-end 4)) + (body (match-string 5)) + (beg-body (match-beginning 5)) + (end-body (match-end 5))) + ;; Silence byte-compiler in case `body' doesn't use all + ;; those variables. + (ignore full-block beg-block end-block lang + beg-lang end-lang switches beg-switches + end-switches header-args beg-header-args + end-header-args body beg-body end-body) + ,@body + (goto-char end-block))))) + (unless visited-p (kill-buffer to-be-removed)) + (goto-char point)))) +(def-edebug-spec org-babel-map-src-blocks (form body)) + +;;;###autoload +(defmacro org-babel-map-inline-src-blocks (file &rest body) + "Evaluate BODY forms on each inline source block in FILE. +If FILE is nil evaluate BODY forms on source blocks in current +buffer." + (declare (indent 1) (debug (form body))) + (org-with-gensyms (datum end point tempvar to-be-removed visitedp) + `(let* ((case-fold-search t) + (,tempvar ,file) + (,visitedp (or (null ,tempvar) + (get-file-buffer (expand-file-name ,tempvar)))) + (,point (point)) + ,to-be-removed) + (save-window-excursion + (when ,tempvar (find-file ,tempvar)) + (setq ,to-be-removed (current-buffer)) + (goto-char (point-min)) + (while (re-search-forward "src_\\S-" nil t) + (let ((,datum (save-match-data (org-element-context)))) + (when (eq (org-element-type ,datum) 'inline-src-block) + (goto-char (match-beginning 0)) + (let ((,end (copy-marker (org-element-property :end ,datum)))) + ,@body + (goto-char ,end) + (set-marker ,end nil)))))) + (unless ,visitedp (kill-buffer ,to-be-removed)) + (goto-char ,point)))) + +;;;###autoload +(defmacro org-babel-map-call-lines (file &rest body) + "Evaluate BODY forms on each call line in FILE. +If FILE is nil evaluate BODY forms on source blocks in current +buffer." + (declare (indent 1) (debug (form body))) + (org-with-gensyms (datum end point tempvar to-be-removed visitedp) + `(let* ((case-fold-search t) + (,tempvar ,file) + (,visitedp (or (null ,tempvar) + (get-file-buffer (expand-file-name ,tempvar)))) + (,point (point)) + ,to-be-removed) + (save-window-excursion + (when ,tempvar (find-file ,tempvar)) + (setq ,to-be-removed (current-buffer)) + (goto-char (point-min)) + (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t) + (let ((,datum (save-match-data (org-element-context)))) + (when (memq (org-element-type ,datum) + '(babel-call inline-babel-call)) + (goto-char (match-beginning 0)) + (let ((,end (copy-marker (org-element-property :end ,datum)))) + ,@body + (goto-char ,end) + (set-marker ,end nil)))))) + (unless ,visitedp (kill-buffer ,to-be-removed)) + (goto-char ,point)))) + +;;;###autoload +(defmacro org-babel-map-executables (file &rest body) + "Evaluate BODY forms on each active Babel code in FILE. +If FILE is nil evaluate BODY forms on source blocks in current +buffer." + (declare (indent 1) (debug (form body))) + (org-with-gensyms (datum end point tempvar to-be-removed visitedp) + `(let* ((case-fold-search t) + (,tempvar ,file) + (,visitedp (or (null ,tempvar) + (get-file-buffer (expand-file-name ,tempvar)))) + (,point (point)) + ,to-be-removed) + (save-window-excursion + (when ,tempvar (find-file ,tempvar)) + (setq ,to-be-removed (current-buffer)) + (goto-char (point-min)) + (while (re-search-forward + "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t) + (let ((,datum (save-match-data (org-element-context)))) + (when (memq (org-element-type ,datum) + '(babel-call inline-babel-call inline-src-block + src-block)) + (goto-char (match-beginning 0)) + (let ((,end (copy-marker (org-element-property :end ,datum)))) + ,@body + (goto-char ,end) + (set-marker ,end nil)))))) + (unless ,visitedp (kill-buffer ,to-be-removed)) + (goto-char ,point)))) + +;;;###autoload +(defun org-babel-execute-buffer (&optional arg) + "Execute source code blocks in a buffer. +Call `org-babel-execute-src-block' on every source block in +the current buffer." + (interactive "P") + (org-babel-eval-wipe-error-buffer) + (org-save-outline-visibility t + (org-babel-map-executables nil + (if (memq (org-element-type (org-element-context)) + '(babel-call inline-babel-call)) + (org-babel-lob-execute-maybe) + (org-babel-execute-src-block arg))))) + +;;;###autoload +(defun org-babel-execute-subtree (&optional arg) + "Execute source code blocks in a subtree. +Call `org-babel-execute-src-block' on every source block in +the current subtree." + (interactive "P") + (save-restriction + (save-excursion + (org-narrow-to-subtree) + (org-babel-execute-buffer arg) + (widen)))) + +;;;###autoload +(defun org-babel-sha1-hash (&optional info) + "Generate an sha1 hash based on the value of info." + (interactive) + (let ((print-level nil) + (info (or info (org-babel-get-src-block-info)))) + (setf (nth 2 info) + (sort (copy-sequence (nth 2 info)) + (lambda (a b) (string< (car a) (car b))))) + (let* ((rm (lambda (lst) + (dolist (p '("replace" "silent" "none" + "append" "prepend")) + (setq lst (remove p lst))) + lst)) + (norm (lambda (arg) + (let ((v (if (and (listp (cdr arg)) (null (cddr arg))) + (copy-sequence (cdr arg)) + (cdr arg)))) + (when (and v (not (and (sequencep v) + (not (consp v)) + (= (length v) 0)))) + (cond + ((and (listp v) ; lists are sorted + (member (car arg) '(:result-params))) + (sort (funcall rm v) #'string<)) + ((and (stringp v) ; strings are sorted + (member (car arg) '(:results :exports))) + (mapconcat #'identity (sort (funcall rm (split-string v)) + #'string<) " ")) + (t v)))))) + ;; expanded body + (lang (nth 0 info)) + (params (nth 2 info)) + (body (if (org-babel-noweb-p params :eval) + (org-babel-expand-noweb-references info) (nth 1 info))) + (expand-cmd (intern (concat "org-babel-expand-body:" lang))) + (assignments-cmd (intern (concat "org-babel-variable-assignments:" + lang))) + (expanded + (if (fboundp expand-cmd) (funcall expand-cmd body params) + (org-babel-expand-body:generic + body params (and (fboundp assignments-cmd) + (funcall assignments-cmd params)))))) + (let* ((it (format "%s-%s" + (mapconcat + #'identity + (delq nil (mapcar (lambda (arg) + (let ((normalized (funcall norm arg))) + (when normalized + (format "%S" normalized)))) + (nth 2 info))) ":") + expanded)) + (hash (sha1 it))) + (when (called-interactively-p 'interactive) (message hash)) + hash)))) + +(defun org-babel-current-result-hash (&optional info) + "Return the current in-buffer hash." + (let ((result (org-babel-where-is-src-block-result nil info))) + (when result + (org-with-wide-buffer + (goto-char result) + (looking-at org-babel-result-regexp) + (match-string-no-properties 1))))) + +(defun org-babel-set-current-result-hash (hash info) + "Set the current in-buffer hash to HASH." + (org-with-wide-buffer + (goto-char (org-babel-where-is-src-block-result nil info)) + (looking-at org-babel-result-regexp) + (goto-char (match-beginning 1)) + (mapc #'delete-overlay (overlays-at (point))) + (forward-char org-babel-hash-show) + (mapc #'delete-overlay (overlays-at (point))) + (replace-match hash nil nil nil 1) + (beginning-of-line) + (org-babel-hide-hash))) + +(defun org-babel-hide-hash () + "Hide the hash in the current results line. +Only the initial `org-babel-hash-show' characters of the hash +will remain visible." + (add-to-invisibility-spec '(org-babel-hide-hash . t)) + (save-excursion + (when (and (re-search-forward org-babel-result-regexp nil t) + (match-string 1)) + (let* ((start (match-beginning 1)) + (hide-start (+ org-babel-hash-show start)) + (end (match-end 1)) + (hash (match-string 1)) + ov1 ov2) + (setq ov1 (make-overlay start hide-start)) + (setq ov2 (make-overlay hide-start end)) + (overlay-put ov2 'invisible 'org-babel-hide-hash) + (overlay-put ov1 'babel-hash hash))))) + +(defun org-babel-hide-all-hashes () + "Hide the hash in the current buffer. +Only the initial `org-babel-hash-show' characters of each hash +will remain visible. This function should be called as part of +the `org-mode-hook'." + (save-excursion + (while (and (not org-babel-hash-show-time) + (re-search-forward org-babel-result-regexp nil t)) + (goto-char (match-beginning 0)) + (org-babel-hide-hash) + (goto-char (match-end 0))))) +(add-hook 'org-mode-hook 'org-babel-hide-all-hashes) + +(defun org-babel-hash-at-point (&optional point) + "Return the value of the hash at POINT. +\\\ +The hash is also added as the last element of the kill ring. +This can be called with `\\[org-ctrl-c-ctrl-c]'." + (interactive) + (let ((hash (car (delq nil (mapcar + (lambda (ol) (overlay-get ol 'babel-hash)) + (overlays-at (or point (point)))))))) + (when hash (kill-new hash) (message hash)))) + +(defun org-babel-result-hide-spec () + "Hide portions of results lines. +Add `org-babel-hide-result' as an invisibility spec for hiding +portions of results lines." + (add-to-invisibility-spec '(org-babel-hide-result . t))) +(add-hook 'org-mode-hook 'org-babel-result-hide-spec) + +(defvar org-babel-hide-result-overlays nil + "Overlays hiding results.") + +(defun org-babel-result-hide-all () + "Fold all results in the current buffer." + (interactive) + (org-babel-show-result-all) + (save-excursion + (while (re-search-forward org-babel-result-regexp nil t) + (save-excursion (goto-char (match-beginning 0)) + (org-babel-hide-result-toggle-maybe))))) + +(defun org-babel-show-result-all () + "Unfold all results in the current buffer." + (mapc 'delete-overlay org-babel-hide-result-overlays) + (setq org-babel-hide-result-overlays nil)) + +;;;###autoload +(defun org-babel-hide-result-toggle-maybe () + "Toggle visibility of result at point." + (interactive) + (let ((case-fold-search t)) + (if (save-excursion + (beginning-of-line 1) + (looking-at org-babel-result-regexp)) + (progn (org-babel-hide-result-toggle) + t) ;; to signal that we took action + nil))) ;; to signal that we did not + +(defun org-babel-hide-result-toggle (&optional force) + "Toggle the visibility of the current result." + (interactive) + (save-excursion + (beginning-of-line) + (if (re-search-forward org-babel-result-regexp nil t) + (let ((start (progn (beginning-of-line 2) (- (point) 1))) + (end (progn + (while (looking-at org-babel-multi-line-header-regexp) + (forward-line 1)) + (goto-char (- (org-babel-result-end) 1)) (point))) + ov) + (if (memq t (mapcar (lambda (overlay) + (eq (overlay-get overlay 'invisible) + 'org-babel-hide-result)) + (overlays-at start))) + (when (or (not force) (eq force 'off)) + (mapc (lambda (ov) + (when (member ov org-babel-hide-result-overlays) + (setq org-babel-hide-result-overlays + (delq ov org-babel-hide-result-overlays))) + (when (eq (overlay-get ov 'invisible) + 'org-babel-hide-result) + (delete-overlay ov))) + (overlays-at start))) + (setq ov (make-overlay start end)) + (overlay-put ov 'invisible 'org-babel-hide-result) + ;; make the block accessible to isearch + (overlay-put + ov 'isearch-open-invisible + (lambda (ov) + (when (member ov org-babel-hide-result-overlays) + (setq org-babel-hide-result-overlays + (delq ov org-babel-hide-result-overlays))) + (when (eq (overlay-get ov 'invisible) + 'org-babel-hide-result) + (delete-overlay ov)))) + (push ov org-babel-hide-result-overlays))) + (error "Not looking at a result line")))) + +;; org-tab-after-check-for-cycling-hook +(add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe) +;; Remove overlays when changing major mode +(add-hook 'org-mode-hook + (lambda () (add-hook 'change-major-mode-hook + 'org-babel-show-result-all 'append 'local))) + +(defvar org-file-properties) +(defun org-babel-params-from-properties (&optional lang) + "Retrieve parameters specified as properties. +Return a list of association lists of source block params +specified in the properties of the current outline entry." + (save-match-data + (list + ;; header arguments specified with the header-args property at + ;; point of call. + (org-babel-parse-header-arguments + (org-entry-get org-babel-current-src-block-location + "header-args" + 'inherit)) + (and lang ; language-specific header arguments at point of call + (org-babel-parse-header-arguments + (org-entry-get org-babel-current-src-block-location + (concat "header-args:" lang) + 'inherit)))))) + +(defun org-babel-balanced-split (string alts) + "Split STRING on instances of ALTS. +ALTS is a character, or cons of two character options where each +option may be either the numeric code of a single character or +a list of character alternatives. For example, to split on +balanced instances of \"[ \t]:\", set ALTS to ((32 9) . 58)." + (with-temp-buffer + (insert string) + (goto-char (point-min)) + (let ((splitp (lambda (past next) + ;; Non-nil when there should be a split after NEXT + ;; character. PAST is the character before NEXT. + (pcase alts + (`(,(and first (pred consp)) . ,(and second (pred consp))) + (and (memq past first) (memq next second))) + (`(,first . ,(and second (pred consp))) + (and (eq past first) (memq next second))) + (`(,(and first (pred consp)) . ,second) + (and (memq past first) (eq next second))) + (`(,first . ,second) + (and (eq past first) (eq next second))) + ((pred (eq next)) t) + (_ nil)))) + (partial nil) + (result nil)) + (while (not (eobp)) + (cond + ((funcall splitp (char-before) (char-after)) + ;; There is a split after point. If ALTS is two-folds, + ;; remove last parsed character as it belongs to ALTS. + (when (consp alts) (pop partial)) + ;; Include elements parsed so far in RESULTS and flush + ;; partial parsing. + (when partial + (push (apply #'string (nreverse partial)) result) + (setq partial nil)) + (forward-char)) + ((memq (char-after) '(?\( ?\[)) + ;; Include everything between balanced brackets. + (let* ((origin (point)) + (after (char-after)) + (openings (list after))) + (forward-char) + (while (and openings (re-search-forward "[]()]" nil t)) + (pcase (char-before) + ((and match (or ?\[ ?\()) (push match openings)) + (?\] (when (eq ?\[ (car openings)) (pop openings))) + (_ (when (eq ?\( (car openings)) (pop openings))))) + (if (null openings) + (setq partial + (nconc (nreverse (string-to-list + (buffer-substring origin (point)))) + partial)) + ;; Un-balanced bracket. Backtrack. + (push after partial) + (goto-char (1+ origin))))) + ((and (eq ?\" (char-after)) (not (eq ?\\ (char-before)))) + ;; Include everything from current double quote to next + ;; non-escaped double quote. + (let ((origin (point))) + (if (re-search-forward "[^\\]\"" nil t) + (setq partial + (nconc (nreverse (string-to-list + (buffer-substring origin (point)))) + partial)) + ;; No closing double quote. Backtrack. + (push ?\" partial) + (forward-char)))) + (t (push (char-after) partial) + (forward-char)))) + ;; Add pending parsing and return result. + (when partial (push (apply #'string (nreverse partial)) result)) + (nreverse result)))) + +(defun org-babel-join-splits-near-ch (ch list) + "Join splits where \"=\" is on either end of the split." + (let ((last= (lambda (str) (= ch (aref str (1- (length str)))))) + (first= (lambda (str) (= ch (aref str 0))))) + (reverse + (cl-reduce (lambda (acc el) + (let ((head (car acc))) + (if (and head (or (funcall last= head) (funcall first= el))) + (cons (concat head el) (cdr acc)) + (cons el acc)))) + list :initial-value nil)))) + +(defun org-babel-parse-header-arguments (arg-string) + "Parse a string of header arguments returning an alist." + (when (> (length arg-string) 0) + (org-babel-parse-multiple-vars + (delq nil + (mapcar + (lambda (arg) + (if (string-match + "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)" + arg) + (cons (intern (match-string 1 arg)) + (org-babel-read (org-babel-chomp (match-string 2 arg)))) + (cons (intern (org-babel-chomp arg)) nil))) + (let ((raw (org-babel-balanced-split arg-string '((32 9) . 58)))) + (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw))))))))) + +(defun org-babel-parse-multiple-vars (header-arguments) + "Expand multiple variable assignments behind a single :var keyword. + +This allows expression of multiple variables with one :var as +shown below. + +#+PROPERTY: var foo=1, bar=2" + (let (results) + (mapc (lambda (pair) + (if (eq (car pair) :var) + (mapcar (lambda (v) (push (cons :var (org-trim v)) results)) + (org-babel-join-splits-near-ch + 61 (org-babel-balanced-split (cdr pair) 32))) + (push pair results))) + header-arguments) + (nreverse results))) + +(defun org-babel-process-params (params) + "Expand variables in PARAMS and add summary parameters." + (let* ((processed-vars (mapcar (lambda (el) + (if (consp el) + el + (org-babel-ref-parse el))) + (org-babel--get-vars params))) + (vars-and-names (if (and (assq :colname-names params) + (assq :rowname-names params)) + (list processed-vars) + (org-babel-disassemble-tables + processed-vars + (cdr (assq :hlines params)) + (cdr (assq :colnames params)) + (cdr (assq :rownames params))))) + (raw-result (or (cdr (assq :results params)) "")) + (result-params (delete-dups + (append + (split-string (if (stringp raw-result) + raw-result + (eval raw-result t))) + (cdr (assq :result-params params)))))) + (append + (mapcar (lambda (var) (cons :var var)) (car vars-and-names)) + (list + (cons :colname-names (or (cdr (assq :colname-names params)) + (cadr vars-and-names))) + (cons :rowname-names (or (cdr (assq :rowname-names params)) + (cl-caddr vars-and-names))) + (cons :result-params result-params) + (cons :result-type (cond ((member "output" result-params) 'output) + ((member "value" result-params) 'value) + (t 'value)))) + (cl-remove-if + (lambda (x) (memq (car x) '(:colname-names :rowname-names :result-params + :result-type :var))) + params)))) + +;; row and column names +(defun org-babel-del-hlines (table) + "Remove all `hline's from TABLE." + (remq 'hline table)) + +(defun org-babel-get-colnames (table) + "Return the column names of TABLE. +Return a cons cell, the `car' of which contains the TABLE less +colnames, and the `cdr' of which contains a list of the column +names." + (if (eq 'hline (nth 1 table)) + (cons (cddr table) (car table)) + (cons (cdr table) (car table)))) + +(defun org-babel-get-rownames (table) + "Return the row names of TABLE. +Return a cons cell, the `car' of which contains the TABLE less +rownames, and the `cdr' of which contains a list of the rownames. +Note: this function removes any hlines in TABLE." + (let* ((table (org-babel-del-hlines table)) + (rownames (funcall (lambda () + (let ((tp table)) + (mapcar + (lambda (_row) + (prog1 + (pop (car tp)) + (setq tp (cdr tp)))) + table)))))) + (cons table rownames))) + +(defun org-babel-put-colnames (table colnames) + "Add COLNAMES to TABLE if they exist." + (if colnames (apply 'list colnames 'hline table) table)) + +(defun org-babel-put-rownames (table rownames) + "Add ROWNAMES to TABLE if they exist." + (if rownames + (mapcar (lambda (row) + (if (listp row) + (cons (or (pop rownames) "") row) + row)) table) + table)) + +(defun org-babel-pick-name (names selector) + "Select one out of an alist of row or column names. +SELECTOR can be either a list of names in which case those names +will be returned directly, or an index into the list NAMES in +which case the indexed names will be return." + (if (listp selector) + selector + (when names + (if (and selector (symbolp selector) (not (equal t selector))) + (cdr (assoc selector names)) + (if (integerp selector) + (nth (- selector 1) names) + (cdr (car (last names)))))))) + +(defun org-babel-disassemble-tables (vars hlines colnames rownames) + "Parse tables for further processing. +Process the variables in VARS according to the HLINES, +ROWNAMES and COLNAMES header arguments. Return a list consisting +of the vars, cnames and rnames." + (let (cnames rnames) + (list + (mapcar + (lambda (var) + (when (listp (cdr var)) + (when (and (not (equal colnames "no")) + (or colnames (and (eq (nth 1 (cdr var)) 'hline) + (not (member 'hline (cddr (cdr var))))))) + (let ((both (org-babel-get-colnames (cdr var)))) + (setq cnames (cons (cons (car var) (cdr both)) + cnames)) + (setq var (cons (car var) (car both))))) + (when (and rownames (not (equal rownames "no"))) + (let ((both (org-babel-get-rownames (cdr var)))) + (setq rnames (cons (cons (car var) (cdr both)) + rnames)) + (setq var (cons (car var) (car both))))) + (when (and hlines (not (equal hlines "yes"))) + (setq var (cons (car var) (org-babel-del-hlines (cdr var)))))) + var) + vars) + (reverse cnames) (reverse rnames)))) + +(defun org-babel-reassemble-table (table colnames rownames) + "Add column and row names to a table. +Given a TABLE and set of COLNAMES and ROWNAMES add the names +to the table for reinsertion to org-mode." + (if (listp table) + (let ((table (if (and rownames (= (length table) (length rownames))) + (org-babel-put-rownames table rownames) table))) + (if (and colnames (listp (car table)) (= (length (car table)) + (length colnames))) + (org-babel-put-colnames table colnames) table)) + table)) + +(defun org-babel-where-is-src-block-head (&optional src-block) + "Find where the current source block begins. + +If optional argument SRC-BLOCK is `src-block' type element, find +its current beginning instead. + +Return the point at the beginning of the current source block. +Specifically at the beginning of the #+BEGIN_SRC line. Also set +match-data relatively to `org-babel-src-block-regexp', which see. +If the point is not on a source block then return nil." + (let ((element (or src-block (org-element-at-point)))) + (when (eq (org-element-type element) 'src-block) + (let ((end (org-element-property :end element))) + (org-with-wide-buffer + ;; Ensure point is not on a blank line after the block. + (beginning-of-line) + (skip-chars-forward " \r\t\n" end) + (when (< (point) end) + (prog1 (goto-char (org-element-property :post-affiliated element)) + (looking-at org-babel-src-block-regexp)))))))) + +;;;###autoload +(defun org-babel-goto-src-block-head () + "Go to the beginning of the current code block." + (interactive) + (let ((head (org-babel-where-is-src-block-head))) + (if head (goto-char head) (error "Not currently in a code block")))) + +;;;###autoload +(defun org-babel-goto-named-src-block (name) + "Go to a named source-code block." + (interactive + (let ((completion-ignore-case t) + (case-fold-search t) + (all-block-names (org-babel-src-block-names))) + (list (completing-read + "source-block name: " all-block-names nil t + (let* ((context (org-element-context)) + (type (org-element-type context)) + (noweb-ref + (and (memq type '(inline-src-block src-block)) + (org-in-regexp (org-babel-noweb-wrap))))) + (cond + (noweb-ref + (buffer-substring + (+ (car noweb-ref) (length org-babel-noweb-wrap-start)) + (- (cdr noweb-ref) (length org-babel-noweb-wrap-end)))) + ((memq type '(babel-call inline-babel-call)) ;#+CALL: + (org-element-property :call context)) + ((car (org-element-property :results context))) ;#+RESULTS: + ((let ((symbol (thing-at-point 'symbol))) ;Symbol. + (and symbol + (member-ignore-case symbol all-block-names) + symbol))) + (t ""))))))) + (let ((point (org-babel-find-named-block name))) + (if point + ;; Taken from `org-open-at-point'. + (progn (org-mark-ring-push) (goto-char point) (org-show-context)) + (message "source-code block `%s' not found in this buffer" name)))) + +(defun org-babel-find-named-block (name) + "Find a named source-code block. +Return the location of the source block identified by source +NAME, or nil if no such block exists. Set match data according +to `org-babel-named-src-block-regexp'." + (save-excursion + (goto-char (point-min)) + (let ((regexp (org-babel-named-src-block-regexp-for-name name))) + (or (and (looking-at regexp) + (progn (goto-char (match-beginning 1)) + (line-beginning-position))) + (ignore-errors (org-next-block 1 nil regexp)))))) + +(defun org-babel-src-block-names (&optional file) + "Returns the names of source blocks in FILE or the current buffer." + (with-current-buffer (if file (find-file-noselect file) (current-buffer)) + (org-with-point-at 1 + (let ((regexp "^[ \t]*#\\+begin_src ") + (case-fold-search t) + (names nil)) + (while (re-search-forward regexp nil t) + (let ((element (org-element-at-point))) + (when (eq 'src-block (org-element-type element)) + (let ((name (org-element-property :name element))) + (when name (push name names)))))) + names)))) + +;;;###autoload +(defun org-babel-goto-named-result (name) + "Go to a named result." + (interactive + (let ((completion-ignore-case t)) + (list (completing-read "Source-block name: " + (org-babel-result-names) nil t)))) + (let ((point (org-babel-find-named-result name))) + (if point + ;; taken from `org-open-at-point' + (progn (goto-char point) (org-show-context)) + (message "result `%s' not found in this buffer" name)))) + +(defun org-babel-find-named-result (name) + "Find a named result. +Return the location of the result named NAME in the current +buffer or nil if no such result exists." + (save-excursion + (goto-char (point-min)) + (let ((case-fold-search t) + (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$" + org-babel-results-keyword + (regexp-quote name)))) + (catch :found + (while (re-search-forward re nil t) + (let ((element (org-element-at-point))) + (when (or (eq (org-element-type element) 'keyword) + (< (point) + (org-element-property :post-affiliated element))) + (throw :found (line-beginning-position))))))))) + +(defun org-babel-result-names (&optional file) + "Returns the names of results in FILE or the current buffer." + (save-excursion + (when file (find-file file)) (goto-char (point-min)) + (let ((case-fold-search t) names) + (while (re-search-forward org-babel-result-w-name-regexp nil t) + (setq names (cons (match-string-no-properties 9) names))) + names))) + +;;;###autoload +(defun org-babel-next-src-block (&optional arg) + "Jump to the next source block. +With optional prefix argument ARG, jump forward ARG many source blocks." + (interactive "p") + (org-next-block arg nil org-babel-src-block-regexp)) + +;;;###autoload +(defun org-babel-previous-src-block (&optional arg) + "Jump to the previous source block. +With optional prefix argument ARG, jump backward ARG many source blocks." + (interactive "p") + (org-previous-block arg org-babel-src-block-regexp)) + +(defvar org-babel-load-languages) + +;;;###autoload +(defun org-babel-mark-block () + "Mark current src block." + (interactive) + (let ((head (org-babel-where-is-src-block-head))) + (when head + (save-excursion + (goto-char head) + (looking-at org-babel-src-block-regexp)) + (push-mark (match-end 5) nil t) + (goto-char (match-beginning 5))))) + +(defun org-babel-demarcate-block (&optional arg) + "Wrap or split the code in the region or on the point. +When called from inside of a code block the current block is +split. When called from outside of a code block a new code block +is created. In both cases if the region is demarcated and if the +region is not active then the point is demarcated." + (interactive "P") + (let* ((info (org-babel-get-src-block-info 'light)) + (start (org-babel-where-is-src-block-head)) + (block (and start (match-string 0))) + (headers (and start (match-string 4))) + (stars (concat (make-string (or (org-current-level) 1) ?*) " ")) + (lower-case-p (and block + (let (case-fold-search) + (string-match-p "#\\+begin_src" block))))) + (if info + (mapc + (lambda (place) + (save-excursion + (goto-char place) + (let ((lang (nth 0 info)) + (indent (make-string (org-get-indentation) ?\s))) + (when (string-match "^[[:space:]]*$" + (buffer-substring (point-at-bol) + (point-at-eol))) + (delete-region (point-at-bol) (point-at-eol))) + (insert (concat + (if (looking-at "^") "" "\n") + indent (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n") + (if arg stars indent) "\n" + indent (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ") + lang + (if (> (length headers) 1) + (concat " " headers) headers) + (if (looking-at "[\n\r]") + "" + (concat "\n" (make-string (current-column) ? ))))))) + (move-end-of-line 2)) + (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>)) + (let ((start (point)) + (lang (completing-read + "Lang: " + (mapcar #'symbol-name + (delete-dups + (append (mapcar #'car org-babel-load-languages) + (mapcar (lambda (el) (intern (car el))) + org-src-lang-modes)))))) + (body (delete-and-extract-region + (if (org-region-active-p) (mark) (point)) (point)))) + (insert (concat (if (looking-at "^") "" "\n") + (if arg (concat stars "\n") "") + (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ") + lang "\n" + body + (if (or (= (length body) 0) + (string-suffix-p "\r" body) + (string-suffix-p "\n" body)) "" "\n") + (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n"))) + (goto-char start) (move-end-of-line 1))))) + +(defun org-babel--insert-results-keyword (name hash) + "Insert RESULTS keyword with NAME value at point. +If NAME is nil, results are anonymous. HASH is a string used as +the results hash, or nil. Leave point before the keyword." + (save-excursion (insert "\n")) ;open line to indent. + (org-indent-line) + (delete-char 1) + (insert (concat "#+" org-babel-results-keyword + (cond ((not hash) nil) + (org-babel-hash-show-time + (format "[%s %s]" + (format-time-string "<%F %T>") + hash)) + (t (format "[%s]" hash))) + ":" + (when name (concat " " name)) + "\n")) + ;; Make sure results are going to be followed by at least one blank + ;; line so they do not get merged with the next element, e.g., + ;; + ;; #+results: + ;; : 1 + ;; + ;; : fixed-width area, unrelated to the above. + (unless (looking-at "^[ \t]*$") (save-excursion (insert "\n"))) + (beginning-of-line 0) + (when hash (org-babel-hide-hash))) + +(defun org-babel--clear-results-maybe (hash) + "Clear results when hash doesn't match HASH. + +When results hash does not match HASH, remove RESULTS keyword at +point, along with related contents. Do nothing if HASH is nil. + +Return a non-nil value if results were cleared. In this case, +leave point where new results should be inserted." + (when hash + (looking-at org-babel-result-regexp) + (unless (string= (match-string 1) hash) + (let* ((e (org-element-at-point)) + (post (copy-marker (org-element-property :post-affiliated e)))) + ;; Delete contents. + (delete-region post + (save-excursion + (goto-char (org-element-property :end e)) + (skip-chars-backward " \t\n") + (line-beginning-position 2))) + ;; Delete RESULT keyword. However, if RESULTS keyword is + ;; orphaned, ignore this part. The deletion above already + ;; took care of it. + (unless (= (point) post) + (delete-region (line-beginning-position) + (line-beginning-position 2))) + (goto-char post) + (set-marker post nil) + t)))) + +(defun org-babel-where-is-src-block-result (&optional insert _info hash) + "Find where the current source block results begin. + +Return the point at the beginning of the result of the current +source block, specifically at the beginning of the results line. + +If no result exists for this block return nil, unless optional +argument INSERT is non-nil. In this case, create a results line +following the source block and return the position at its +beginning. In the case of inline code, remove the results part +instead. + +If optional argument HASH is a string, remove contents related to +RESULTS keyword if its hash is different. Then update the latter +to HASH." + (let ((context (org-element-context))) + (catch :found + (org-with-wide-buffer + (pcase (org-element-type context) + ((or `inline-babel-call `inline-src-block) + ;; Results for inline objects are located right after them. + ;; There is no RESULTS line to insert either. + (let ((limit (org-element-property + :contents-end (org-element-property :parent context)))) + (goto-char (org-element-property :end context)) + (skip-chars-forward " \t\n" limit) + (throw :found + (and + (< (point) limit) + (let ((result (org-element-context))) + (and (eq (org-element-type result) 'macro) + (string= (org-element-property :key result) + "results") + (if (not insert) (point) + (delete-region + (point) + (progn + (goto-char (org-element-property :end result)) + (skip-chars-backward " \t") + (point))) + (point)))))))) + ((or `babel-call `src-block) + (let* ((name (org-element-property :name context)) + (named-results (and name (org-babel-find-named-result name)))) + (goto-char (or named-results (org-element-property :end context))) + (cond + ;; Existing results named after the current source. + (named-results + (when (org-babel--clear-results-maybe hash) + (org-babel--insert-results-keyword name hash)) + (throw :found (point))) + ;; Named results expect but none to be found. + (name) + ;; No possible anonymous results at the very end of + ;; buffer or outside CONTEXT parent. + ((eq (point) + (or (org-element-property + :contents-end (org-element-property :parent context)) + (point-max)))) + ;; Check if next element is an anonymous result below + ;; the current block. + ((let* ((next (org-element-at-point)) + (end (save-excursion + (goto-char + (org-element-property :post-affiliated next)) + (line-end-position))) + (empty-result-re (concat org-babel-result-regexp "$")) + (case-fold-search t)) + (re-search-forward empty-result-re end t)) + (beginning-of-line) + (when (org-babel--clear-results-maybe hash) + (org-babel--insert-results-keyword nil hash)) + (throw :found (point)))))) + ;; Ignore other elements. + (_ (throw :found nil)))) + ;; No result found. Insert a RESULTS keyword below element, if + ;; appropriate. In this case, ensure there is an empty line + ;; after the previous element. + (when insert + (save-excursion + (goto-char (min (org-element-property :end context) (point-max))) + (skip-chars-backward " \t\n") + (forward-line) + (unless (bolp) (insert "\n")) + (insert "\n") + (org-babel--insert-results-keyword + (org-element-property :name context) hash) + (point)))))) + +(defun org-babel-read-element (element) + "Read ELEMENT into emacs-lisp. +Return nil if ELEMENT cannot be read." + (org-with-wide-buffer + (goto-char (org-element-property :post-affiliated element)) + (pcase (org-element-type element) + (`fixed-width + (let ((v (org-trim (org-element-property :value element)))) + (or (org-babel--string-to-number v) v))) + (`table (org-babel-read-table)) + (`plain-list (org-babel-read-list)) + (`example-block + (let ((v (org-element-property :value element))) + (if (or org-src-preserve-indentation + (org-element-property :preserve-indent element)) + v + (org-remove-indentation v)))) + (`export-block + (org-remove-indentation (org-element-property :value element))) + (`paragraph + ;; Treat paragraphs containing a single link specially. + (skip-chars-forward " \t") + (if (and (looking-at org-bracket-link-regexp) + (save-excursion + (goto-char (match-end 0)) + (skip-chars-forward " \r\t\n") + (<= (org-element-property :end element) + (point)))) + (org-babel-read-link) + (buffer-substring-no-properties + (org-element-property :contents-begin element) + (org-element-property :contents-end element)))) + ((or `center-block `quote-block `verse-block `special-block) + (org-remove-indentation + (buffer-substring-no-properties + (org-element-property :contents-begin element) + (org-element-property :contents-end element)))) + (_ nil)))) + +(defun org-babel-read-result () + "Read the result at point into emacs-lisp." + (and (not (save-excursion + (beginning-of-line) + (looking-at-p "[ \t]*$"))) + (org-babel-read-element (org-element-at-point)))) + +(defun org-babel-read-table () + "Read the table at point into emacs-lisp." + (mapcar (lambda (row) + (if (and (symbolp row) (equal row 'hline)) row + (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row))) + (org-table-to-lisp))) + +(defun org-babel-read-list () + "Read the list at point into emacs-lisp." + (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) + (cdr (org-list-to-lisp)))) + +(defvar org-link-types-re) +(defun org-babel-read-link () + "Read the link at point into emacs-lisp. +If the path of the link is a file path it is expanded using +`expand-file-name'." + (let* ((case-fold-search t) + (raw (and (looking-at org-bracket-link-regexp) + (org-no-properties (match-string 1)))) + (type (and (string-match org-link-types-re raw) + (match-string 1 raw)))) + (cond + ((not type) (expand-file-name raw)) + ((string= type "file") + (and (string-match "file\\(.*\\):\\(.+\\)" raw) + (expand-file-name (match-string 2 raw)))) + (t raw)))) + +(defun org-babel-format-result (result &optional sep) + "Format RESULT for writing to file." + (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r))))) + (if (listp result) + ;; table result + (orgtbl-to-generic + result (list :sep (or sep "\t") :fmt echo-res)) + ;; scalar result + (funcall echo-res result)))) + +(defun org-babel-insert-result (result &optional result-params info hash lang) + "Insert RESULT into the current buffer. + +By default RESULT is inserted after the end of the current source +block. The RESULT of an inline source block usually will be +wrapped inside a `results' macro and placed on the same line as +the inline source block. The macro is stripped upon export. +Multiline and non-scalar RESULTS from inline source blocks are +not allowed. With optional argument RESULT-PARAMS controls +insertion of results in the Org mode file. RESULT-PARAMS can +take the following values: + +replace - (default option) insert results after the source block + or inline source block replacing any previously + inserted results. + +silent -- no results are inserted into the Org buffer but + the results are echoed to the minibuffer and are + ingested by Emacs (a potentially time consuming + process). + +file ---- the results are interpreted as a file path, and are + inserted into the buffer using the Org file syntax. + +list ---- the results are interpreted as an Org list. + +raw ----- results are added directly to the Org file. This is + a good option if you code block will output Org + formatted text. + +drawer -- results are added directly to the Org file as with + \"raw\", but are wrapped in a RESULTS drawer or results + macro, allowing them to later be replaced or removed + automatically. + +org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC + org\" block depending on whether the current source block is + inline or not. They are not comma-escaped when inserted, + but Org syntax here will be discarded when exporting the + file. + +html ---- results are added inside of a #+BEGIN_EXPORT HTML block + or html export snippet depending on whether the current + source block is inline or not. This is a good option + if your code block will output html formatted text. + +latex --- results are added inside of a #+BEGIN_EXPORT LATEX + block or latex export snippet depending on whether the + current source block is inline or not. This is a good + option if your code block will output latex formatted + text. + +code ---- the results are extracted in the syntax of the source + code of the language being evaluated and are added + inside of a source block with the source-code language + set appropriately. Also, source block inlining is + preserved in this case. Note this relies on the + optional LANG argument. + +list ---- the results are rendered as a list. This option not + allowed for inline src blocks. + +table --- the results are rendered as a table. This option not + allowed for inline src blocks. + +INFO may provide the values of these header arguments (in the +`header-arguments-alist' see the docstring for +`org-babel-get-src-block-info'): + +:file --- the name of the file to which output should be written. + +:wrap --- the effect is similar to `latex' in RESULT-PARAMS but + using the argument supplied to specify the export block + or snippet type." + (cond ((stringp result) + (setq result (org-no-properties result)) + (when (member "file" result-params) + (setq result (org-babel-result-to-file + result (when (assq :file-desc (nth 2 info)) + (or (cdr (assq :file-desc (nth 2 info))) + result)))))) + ((listp result)) + (t (setq result (format "%S" result)))) + (if (and result-params (member "silent" result-params)) + (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result))) + result) + (let ((inline (let ((context (org-element-context))) + (and (memq (org-element-type context) + '(inline-babel-call inline-src-block)) + context)))) + (when inline + (let ((warning + (or (and (member "table" result-params) "`:results table'") + (and (listp result) "list result") + (and (string-match-p "\n." result) "multiline result") + (and (member "list" result-params) "`:results list'")))) + (when warning + (user-error "Inline error: %s cannot be used" warning)))) + (save-excursion + (let* ((visible-beg (point-min-marker)) + (visible-end (copy-marker (point-max) t)) + (inline (let ((context (org-element-context))) + (and (memq (org-element-type context) + '(inline-babel-call inline-src-block)) + context))) + (existing-result (org-babel-where-is-src-block-result t nil hash)) + (results-switches (cdr (assq :results_switches (nth 2 info)))) + ;; When results exist outside of the current visible + ;; region of the buffer, be sure to widen buffer to + ;; update them. + (outside-scope (and existing-result + (buffer-narrowed-p) + (or (> visible-beg existing-result) + (<= visible-end existing-result)))) + beg end indent) + ;; Ensure non-inline results end in a newline. + (when (and (org-string-nw-p result) + (not inline) + (not (string-equal (substring result -1) "\n"))) + (setq result (concat result "\n"))) + (unwind-protect + (progn + (when outside-scope (widen)) + (if existing-result (goto-char existing-result) + (goto-char (org-element-property :end inline)) + (skip-chars-backward " \t")) + (unless inline + (setq indent (org-get-indentation)) + (forward-line 1)) + (setq beg (point)) + (cond + (inline + ;; Make sure new results are separated from the + ;; source code by one space. + (unless existing-result + (insert " ") + (setq beg (point)))) + ((member "replace" result-params) + (delete-region (point) (org-babel-result-end))) + ((member "append" result-params) + (goto-char (org-babel-result-end)) (setq beg (point-marker))) + ((member "prepend" result-params))) ; already there + (setq results-switches + (if results-switches (concat " " results-switches) "")) + (let ((wrap + (lambda (start finish &optional no-escape no-newlines + inline-start inline-finish) + (when inline + (setq start inline-start) + (setq finish inline-finish) + (setq no-newlines t)) + (let ((before-finish (marker-position end))) + (goto-char end) + (insert (concat finish (unless no-newlines "\n"))) + (goto-char beg) + (insert (concat start (unless no-newlines "\n"))) + (unless no-escape + (org-escape-code-in-region + (min (point) before-finish) before-finish)) + (goto-char end)))) + (tabulablep + (lambda (r) + ;; Non-nil when result R can be turned into + ;; a table. + (and (listp r) + (null (cdr (last r))) + (cl-every + (lambda (e) (or (atom e) (null (cdr (last e))))) + result))))) + ;; insert results based on type + (cond + ;; Do nothing for an empty result. + ((null result)) + ;; Insert a list if preferred. + ((member "list" result-params) + (insert + (org-trim + (org-list-to-generic + (cons 'unordered + (mapcar + (lambda (e) + (list (if (stringp e) e (format "%S" e)))) + (if (listp result) result + (split-string result "\n" t)))) + '(:splicep nil :istart "- " :iend "\n"))) + "\n")) + ;; Try hard to print RESULT as a table. Give up if + ;; it contains an improper list. + ((funcall tabulablep result) + (goto-char beg) + (insert (concat (orgtbl-to-orgtbl + (if (cl-every + (lambda (e) + (or (eq e 'hline) (listp e))) + result) + result + (list result)) + nil) + "\n")) + (goto-char beg) + (when (org-at-table-p) (org-table-align)) + (goto-char (org-table-end))) + ;; Print verbatim a list that cannot be turned into + ;; a table. + ((listp result) (insert (format "%s\n" result))) + ((member "file" result-params) + (when inline + (setq result (org-macro-escape-arguments result))) + (insert result)) + ((and inline (not (member "raw" result-params))) + (insert (org-macro-escape-arguments + (org-babel-chomp result "\n")))) + (t (goto-char beg) (insert result))) + (setq end (copy-marker (point) t)) + ;; possibly wrap result + (cond + ((assq :wrap (nth 2 info)) + (let ((name (or (cdr (assq :wrap (nth 2 info))) "RESULTS"))) + (funcall wrap (concat "#+BEGIN_" name) + (concat "#+END_" (car (split-string name))) + nil nil (concat "{{{results(@@" name ":") "@@)}}}"))) + ((member "html" result-params) + (funcall wrap "#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil + "{{{results(@@html:" "@@)}}}")) + ((member "latex" result-params) + (funcall wrap "#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil + "{{{results(@@latex:" "@@)}}}")) + ((member "org" result-params) + (goto-char beg) (when (org-at-table-p) (org-cycle)) + (funcall wrap "#+BEGIN_SRC org" "#+END_SRC" nil nil + "{{{results(src_org{" "})}}}")) + ((member "code" result-params) + (let ((lang (or lang "none"))) + (funcall wrap (format "#+BEGIN_SRC %s%s" lang results-switches) + "#+END_SRC" nil nil + (format "{{{results(src_%s[%s]{" lang results-switches) + "})}}}"))) + ((member "raw" result-params) + (goto-char beg) (when (org-at-table-p) (org-cycle))) + ((or (member "drawer" result-params) + ;; Stay backward compatible with <7.9.2 + (member "wrap" result-params)) + (goto-char beg) (when (org-at-table-p) (org-cycle)) + (funcall wrap ":RESULTS:" ":END:" 'no-escape nil + "{{{results(" ")}}}")) + ((and inline (member "file" result-params)) + (funcall wrap nil nil nil nil "{{{results(" ")}}}")) + ((and (not (funcall tabulablep result)) + (not (member "file" result-params))) + (let ((org-babel-inline-result-wrap + ;; Hard code {{{results(...)}}} on top of + ;; customization. + (format "{{{results(%s)}}}" + org-babel-inline-result-wrap))) + (org-babel-examplify-region + beg end results-switches inline))))) + ;; Possibly indent results in par with #+results line. + (when (and (not inline) (numberp indent) (> indent 0) + ;; In this case `table-align' does the work + ;; for us. + (not (and (listp result) + (member "append" result-params)))) + (indent-rigidly beg end indent)) + (if (null result) + (if (member "value" result-params) + (message "Code block returned no value.") + (message "Code block produced no output.")) + (message "Code block evaluation complete."))) + (set-marker end nil) + (when outside-scope (narrow-to-region visible-beg visible-end)) + (set-marker visible-beg nil) + (set-marker visible-end nil))))))) + +(defun org-babel-remove-result (&optional info keep-keyword) + "Remove the result of the current source block." + (interactive) + (let ((location (org-babel-where-is-src-block-result nil info))) + (when location + (save-excursion + (goto-char location) + (when (looking-at (concat org-babel-result-regexp ".*$")) + (delete-region + (if keep-keyword (line-beginning-position 2) + (save-excursion + (skip-chars-backward " \r\t\n") + (line-beginning-position 2))) + (progn (forward-line) (org-babel-result-end)))))))) + +(defun org-babel-remove-inline-result (&optional datum) + "Remove the result of the current inline-src-block or babel call. +The result must be wrapped in a `results' macro to be removed. +Leading white space is trimmed." + (interactive) + (let* ((el (or datum (org-element-context)))) + (when (memq (org-element-type el) '(inline-src-block inline-babel-call)) + (org-with-wide-buffer + (goto-char (org-element-property :end el)) + (skip-chars-backward " \t") + (let ((result (save-excursion + (skip-chars-forward + " \t\n" + (org-element-property + :contents-end (org-element-property :parent el))) + (org-element-context)))) + (when (and (eq (org-element-type result) 'macro) + (string= (org-element-property :key result) "results")) + (delete-region ; And leading whitespace. + (point) + (progn (goto-char (org-element-property :end result)) + (skip-chars-backward " \t\n") + (point))))))))) + +(defun org-babel-remove-result-one-or-many (x) + "Remove the result of the current source block. +If called with a prefix argument, remove all result blocks +in the buffer." + (interactive "P") + (if x + (org-babel-map-src-blocks nil (org-babel-remove-result)) + (org-babel-remove-result))) + +(defun org-babel-result-end () + "Return the point at the end of the current set of results." + (cond ((looking-at-p "^[ \t]*$") (point)) ;no result + ((looking-at-p (format "^[ \t]*%s[ \t]*$" org-bracket-link-regexp)) + (line-beginning-position 2)) + (t + (let ((element (org-element-at-point))) + (if (memq (org-element-type element) + ;; Possible results types. + '(drawer example-block export-block fixed-width item + plain-list src-block table)) + (save-excursion + (goto-char (min (point-max) ;for narrowed buffers + (org-element-property :end element))) + (skip-chars-backward " \r\t\n") + (line-beginning-position 2)) + (point)))))) + +(defun org-babel-result-to-file (result &optional description) + "Convert RESULT into an Org link with optional DESCRIPTION. +If the `default-directory' is different from the containing +file's directory then expand relative links." + (when (stringp result) + (format "[[file:%s]%s]" + (if (and default-directory + buffer-file-name + (not (string= (expand-file-name default-directory) + (expand-file-name + (file-name-directory buffer-file-name))))) + (expand-file-name result default-directory) + result) + (if description (concat "[" description "]") "")))) + +(defun org-babel-examplify-region (beg end &optional results-switches inline) + "Comment out region using the inline `==' or `: ' org example quote." + (interactive "*r") + (let ((maybe-cap + (lambda (str) + (if org-babel-uppercase-example-markers (upcase str) str)))) + (if inline + (save-excursion + (goto-char beg) + (insert (format org-babel-inline-result-wrap + (delete-and-extract-region beg end)))) + (let ((size (count-lines beg end))) + (save-excursion + (cond ((= size 0)) ; do nothing for an empty result + ((< size org-babel-min-lines-for-block-output) + (goto-char beg) + (dotimes (_ size) + (beginning-of-line 1) (insert ": ") (forward-line 1))) + (t + (goto-char beg) + (insert (if results-switches + (format "%s%s\n" + (funcall maybe-cap "#+begin_example") + results-switches) + (funcall maybe-cap "#+begin_example\n"))) + (let ((p (point))) + (if (markerp end) (goto-char end) (forward-char (- end beg))) + (org-escape-code-in-region p (point))) + (insert (funcall maybe-cap "#+end_example\n"))))))))) + +(defun org-babel-update-block-body (new-body) + "Update the body of the current code block to NEW-BODY." + (let ((element (org-element-at-point))) + (unless (eq (org-element-type element) 'src-block) + (error "Not in a source block")) + (goto-char (org-babel-where-is-src-block-head element)) + (let* ((ind (org-get-indentation)) + (body-start (line-beginning-position 2)) + (body (org-element-normalize-string + (if (or org-src-preserve-indentation + (org-element-property :preserve-indent element)) + new-body + (with-temp-buffer + (insert (org-remove-indentation new-body)) + (indent-rigidly + (point-min) + (point-max) + (+ ind org-edit-src-content-indentation)) + (buffer-string)))))) + (delete-region body-start + (org-with-wide-buffer + (goto-char (org-element-property :end element)) + (skip-chars-backward " \t\n") + (line-beginning-position))) + (goto-char body-start) + (insert body)))) + +(defun org-babel-merge-params (&rest plists) + "Combine all parameter association lists in PLISTS. +Later elements of PLISTS override the values of previous elements. +This takes into account some special considerations for certain +parameters when merging lists." + (let* ((results-exclusive-groups + (mapcar (lambda (group) (mapcar #'symbol-name group)) + (cdr (assq 'results org-babel-common-header-args-w-values)))) + (exports-exclusive-groups + (mapcar (lambda (group) (mapcar #'symbol-name group)) + (cdr (assq 'exports org-babel-common-header-args-w-values)))) + (merge + (lambda (exclusive-groups &rest result-params) + ;; Maintain exclusivity of mutually exclusive parameters, + ;; as defined in EXCLUSIVE-GROUPS while merging lists in + ;; RESULT-PARAMS. + (let (output) + (dolist (new-params result-params (delete-dups output)) + (dolist (new-param new-params) + (dolist (exclusive-group exclusive-groups) + (when (member new-param exclusive-group) + (setq output (cl-remove-if + (lambda (o) (member o exclusive-group)) + output)))) + (push new-param output)))))) + (variable-index 0) ;Handle positional arguments. + clearnames + params ;Final parameters list. + ;; Some keywords accept multiple values. We need to treat + ;; them specially. + vars results exports) + (dolist (plist plists) + (dolist (pair plist) + (pcase pair + (`(:var . ,value) + (let ((name (cond + ((listp value) (car value)) + ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value) + (intern (match-string 1 value))) + (t nil)))) + (cond + (name + (setq vars + (append (if (not (assoc name vars)) vars + (push name clearnames) + (cl-remove-if (lambda (p) (equal name (car p))) + vars)) + (list (cons name pair))))) + ((and vars (nth variable-index vars)) + ;; If no name is given and we already have named + ;; variables then assign to named variables in order. + (let ((name (car (nth variable-index vars)))) + ;; Clear out colnames and rownames for replace vars. + (push name clearnames) + (setf (cddr (nth variable-index vars)) + (concat (symbol-name name) "=" value)) + (cl-incf variable-index))) + (t (error "Variable \"%s\" must be assigned a default value" + (cdr pair)))))) + (`(:results . ,value) + (setq results (funcall merge + results-exclusive-groups + results + (split-string + (if (stringp value) value (eval value t)))))) + (`(,(or :file :file-ext) . ,value) + ;; `:file' and `:file-ext' are regular keywords but they + ;; imply a "file" `:results' and a "results" `:exports'. + (when value + (setq results + (funcall merge results-exclusive-groups results '("file"))) + (unless (or (member "both" exports) + (member "none" exports) + (member "code" exports)) + (setq exports + (funcall merge + exports-exclusive-groups exports '("results")))) + (push pair params))) + (`(:exports . ,value) + (setq exports (funcall merge + exports-exclusive-groups + exports + (split-string (or value ""))))) + ;; Regular keywords: any value overwrites the previous one. + (_ (setq params (cons pair (assq-delete-all (car pair) params))))))) + ;; Handle `:var' and clear out colnames and rownames for replaced + ;; variables. + (setq params (nconc (mapcar (lambda (v) (cons :var (cddr v))) vars) + params)) + (dolist (name clearnames) + (dolist (param '(:colname-names :rowname-names)) + (when (assq param params) + (setf (cdr (assq param params)) + (cl-remove-if (lambda (pair) (equal name (car pair))) + (cdr (assq param params)))) + (setq params + (cl-remove-if (lambda (pair) (and (equal (car pair) param) + (null (cdr pair)))) + params))))) + ;; Handle other special keywords, which accept multiple values. + (setq params (nconc (list (cons :results (mapconcat #'identity results " ")) + (cons :exports (mapconcat #'identity exports " "))) + params)) + ;; Return merged params. + params)) + +(defvar org-babel-use-quick-and-dirty-noweb-expansion nil + "Set to true to use regular expressions to expand noweb references. +This results in much faster noweb reference expansion but does +not properly allow code blocks to inherit the \":noweb-ref\" +header argument from buffer or subtree wide properties.") + +(defun org-babel-noweb-p (params context) + "Check if PARAMS require expansion in CONTEXT. +CONTEXT may be one of :tangle, :export or :eval." + (let ((allowed-values (cl-case context + (:tangle '("yes" "tangle" "no-export" "strip-export")) + (:eval '("yes" "no-export" "strip-export" "eval")) + (:export '("yes"))))) + (cl-some (lambda (v) (member v allowed-values)) + (split-string (or (cdr (assq :noweb params)) ""))))) + +(defun org-babel-expand-noweb-references (&optional info parent-buffer) + "Expand Noweb references in the body of the current source code block. + +For example the following reference would be replaced with the +body of the source-code block named `example-block'. + +<> + +Note that any text preceding the <> construct on a line will +be interposed between the lines of the replacement text. So for +example if <> is placed behind a comment, then the entire +replacement text will also be commented. + +This function must be called from inside of the buffer containing +the source-code block which holds BODY. + +In addition the following syntax can be used to insert the +results of evaluating the source-code block named `example-block'. + +<> + +Any optional arguments can be passed to example-block by placing +the arguments inside the parenthesis following the convention +defined by `org-babel-lob'. For example + +<> + +would set the value of argument \"a\" equal to \"9\". Note that +these arguments are not evaluated in the current source-code +block but are passed literally to the \"example-block\"." + (let* ((parent-buffer (or parent-buffer (current-buffer))) + (info (or info (org-babel-get-src-block-info 'light))) + (lang (nth 0 info)) + (body (nth 1 info)) + (ob-nww-start org-babel-noweb-wrap-start) + (ob-nww-end org-babel-noweb-wrap-end) + (comment (string= "noweb" (cdr (assq :comments (nth 2 info))))) + (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|" + ":noweb-ref[ \t]+" "\\)")) + (new-body "") + (nb-add (lambda (text) (setq new-body (concat new-body text)))) + (c-wrap (lambda (text) + (with-temp-buffer + (funcall (intern (concat lang "-mode"))) + (comment-region (point) (progn (insert text) (point))) + (org-trim (buffer-string))))) + index source-name evaluate prefix) + (with-temp-buffer + (setq-local org-babel-noweb-wrap-start ob-nww-start) + (setq-local org-babel-noweb-wrap-end ob-nww-end) + (insert body) (goto-char (point-min)) + (setq index (point)) + (while (and (re-search-forward (org-babel-noweb-wrap) nil t)) + (save-match-data (setf source-name (match-string 1))) + (save-match-data (setq evaluate (string-match "(.*)" source-name))) + (save-match-data + (setq prefix + (buffer-substring (match-beginning 0) + (save-excursion + (beginning-of-line 1) (point))))) + ;; add interval to new-body (removing noweb reference) + (goto-char (match-beginning 0)) + (funcall nb-add (buffer-substring index (point))) + (goto-char (match-end 0)) + (setq index (point)) + (funcall + nb-add + (with-current-buffer parent-buffer + (save-restriction + (widen) + (mapconcat ;; Interpose PREFIX between every line. + #'identity + (split-string + (if evaluate + (let ((raw (org-babel-ref-resolve source-name))) + (if (stringp raw) raw (format "%S" raw))) + (or + ;; Retrieve from the library of babel. + (nth 2 (assoc (intern source-name) + org-babel-library-of-babel)) + ;; Return the contents of headlines literally. + (save-excursion + (when (org-babel-ref-goto-headline-id source-name) + (org-babel-ref-headline-body))) + ;; Find the expansion of reference in this buffer. + (let ((rx (concat rx-prefix source-name "[ \t\n]")) + expansion) + (save-excursion + (goto-char (point-min)) + (if org-babel-use-quick-and-dirty-noweb-expansion + (while (re-search-forward rx nil t) + (let* ((i (org-babel-get-src-block-info 'light)) + (body (if (org-babel-noweb-p (nth 2 i) :eval) + (org-babel-expand-noweb-references i) + (nth 1 i))) + (sep (or (cdr (assq :noweb-sep (nth 2 i))) + "\n")) + (full (if comment + (let ((cs (org-babel-tangle-comment-links i))) + (concat (funcall c-wrap (car cs)) "\n" + body "\n" + (funcall c-wrap (cadr cs)))) + body))) + (setq expansion (cons sep (cons full expansion))))) + (org-babel-map-src-blocks nil + (let ((i (let ((org-babel-current-src-block-location (point))) + (org-babel-get-src-block-info 'light)))) + (when (equal (or (cdr (assq :noweb-ref (nth 2 i))) + (nth 4 i)) + source-name) + (let* ((body (if (org-babel-noweb-p (nth 2 i) :eval) + (org-babel-expand-noweb-references i) + (nth 1 i))) + (sep (or (cdr (assq :noweb-sep (nth 2 i))) + "\n")) + (full (if comment + (let ((cs (org-babel-tangle-comment-links i))) + (concat (funcall c-wrap (car cs)) "\n" + body "\n" + (funcall c-wrap (cadr cs)))) + body))) + (setq expansion + (cons sep (cons full expansion))))))))) + (and expansion + (mapconcat #'identity (nreverse (cdr expansion)) ""))) + ;; Possibly raise an error if named block doesn't exist. + (if (or org-babel-noweb-error-all-langs + (member lang org-babel-noweb-error-langs)) + (error "%s" (concat + (org-babel-noweb-wrap source-name) + "could not be resolved (see " + "`org-babel-noweb-error-langs')")) + ""))) + "[\n\r]") (concat "\n" prefix)))))) + (funcall nb-add (buffer-substring index (point-max)))) + new-body)) + +(defun org-babel--script-escape-inner (str) + (let (in-single in-double backslash out) + (mapc + (lambda (ch) + (setq + out + (if backslash + (progn + (setq backslash nil) + (cond + ((and in-single (eq ch ?')) + ;; Escaped single quote inside single quoted string: + ;; emit just a single quote, since we've changed the + ;; outer quotes to double. + (cons ch out)) + ((eq ch ?\") + ;; Escaped double quote + (if in-single + ;; This should be interpreted as backslash+quote, + ;; not an escape. Emit a three backslashes + ;; followed by a quote (because one layer of + ;; quoting will be stripped by `org-babel-read'). + (append (list ch ?\\ ?\\ ?\\) out) + ;; Otherwise we are in a double-quoted string. Emit + ;; a single escaped quote + (append (list ch ?\\) out))) + ((eq ch ?\\) + ;; Escaped backslash: emit a single escaped backslash + (append (list ?\\ ?\\) out)) + ;; Other: emit a quoted backslash followed by whatever + ;; the character was (because one layer of quoting will + ;; be stripped by `org-babel-read'). + (t (append (list ch ?\\ ?\\) out)))) + (cl-case ch + (?\[ (if (or in-double in-single) + (cons ?\[ out) + (cons ?\( out))) + (?\] (if (or in-double in-single) + (cons ?\] out) + (cons ?\) out))) + (?\{ (if (or in-double in-single) + (cons ?\{ out) + (cons ?\( out))) + (?\} (if (or in-double in-single) + (cons ?\} out) + (cons ?\) out))) + (?, (if (or in-double in-single) + (cons ?, out) (cons ?\s out))) + (?\' (if in-double + (cons ?\' out) + (setq in-single (not in-single)) (cons ?\" out))) + (?\" (if in-single + (append (list ?\" ?\\) out) + (setq in-double (not in-double)) (cons ?\" out))) + (?\\ (unless (or in-single in-double) + (error "Can't handle backslash outside string in `org-babel-script-escape'")) + (setq backslash t) + out) + (t (cons ch out)))))) + (string-to-list str)) + (when (or in-single in-double) + (error "Unterminated string in `org-babel-script-escape'")) + (apply #'string (reverse out)))) + +(defun org-babel-script-escape (str &optional force) + "Safely convert tables into elisp lists." + (unless (stringp str) + (error "`org-babel-script-escape' expects a string")) + (let ((escaped + (cond + ((and (> (length str) 2) + (or (and (string-equal "[" (substring str 0 1)) + (string-equal "]" (substring str -1))) + (and (string-equal "{" (substring str 0 1)) + (string-equal "}" (substring str -1))) + (and (string-equal "(" (substring str 0 1)) + (string-equal ")" (substring str -1))))) + + (concat "'" (org-babel--script-escape-inner str))) + ((or force + (and (> (length str) 2) + (or (and (string-equal "'" (substring str 0 1)) + (string-equal "'" (substring str -1))) + ;; We need to pass double-quoted strings + ;; through the backslash-twiddling bits, even + ;; though we don't need to change their + ;; delimiters. + (and (string-equal "\"" (substring str 0 1)) + (string-equal "\"" (substring str -1)))))) + (org-babel--script-escape-inner str)) + (t str)))) + (condition-case nil (org-babel-read escaped) (error escaped)))) + +(defun org-babel-read (cell &optional inhibit-lisp-eval) + "Convert the string value of CELL to a number if appropriate. +Otherwise if CELL looks like lisp (meaning it starts with a +\"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as +lisp, otherwise return it unmodified as a string. Optional +argument INHIBIT-LISP-EVAL inhibits lisp evaluation for +situations in which is it not appropriate." + (cond ((not (org-string-nw-p cell)) cell) + ((org-babel--string-to-number cell)) + ((and (not inhibit-lisp-eval) + (or (memq (string-to-char cell) '(?\( ?' ?` ?\[)) + (string= cell "*this*"))) + (eval (read cell) t)) + ((eq (string-to-char cell) ?\") (read cell)) + (t (org-no-properties cell)))) + +(defun org-babel--string-to-number (string) + "If STRING represents a number return its value. +Otherwise return nil." + (and (string-match-p "\\`-?[0-9]*\\.?[0-9]*\\'" string) + (string-to-number string))) + +(defun org-babel-import-elisp-from-file (file-name &optional separator) + "Read the results located at FILE-NAME into an elisp table. +If the table is trivial, then return it as a scalar." + (let (result) + (save-window-excursion + (with-temp-buffer + (condition-case err + (progn + (org-table-import file-name separator) + (delete-file file-name) + (setq result (mapcar (lambda (row) + (mapcar #'org-babel-string-read row)) + (org-table-to-lisp)))) + (error (message "Error reading results: %s" err) nil))) + (if (null (cdr result)) ;; if result is trivial vector, then scalarize it + (if (consp (car result)) + (if (null (cdr (car result))) + (caar result) + result) + (car result)) + result)))) + +(defun org-babel-string-read (cell) + "Strip nested \"s from around strings." + (org-babel-read (or (and (stringp cell) + (string-match "\\\"\\(.+\\)\\\"" cell) + (match-string 1 cell)) + cell) t)) + +(defun org-babel-chomp (string &optional regexp) + "Strip a trailing space or carriage return from STRING. +The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one +can be specified as the REGEXP argument." + (let ((regexp (or regexp "[ \f\t\n\r\v]"))) + (while (and (> (length string) 0) + (string-match regexp (substring string -1))) + (setq string (substring string 0 -1))) + string)) + +(defun org-babel-process-file-name (name &optional no-quote-p) + "Prepare NAME to be used in an external process. +If NAME specifies a remote location, the remote portion of the +name is removed, since in that case the process will be executing +remotely. The file name is then processed by `expand-file-name'. +Unless second argument NO-QUOTE-P is non-nil, the file name is +additionally processed by `shell-quote-argument'" + (let ((f (org-babel-local-file-name (expand-file-name name)))) + (if no-quote-p f (shell-quote-argument f)))) + +(defvar org-babel-temporary-directory) +(unless (or noninteractive (boundp 'org-babel-temporary-directory)) + (defvar org-babel-temporary-directory + (or (and (boundp 'org-babel-temporary-directory) + (file-exists-p org-babel-temporary-directory) + org-babel-temporary-directory) + (make-temp-file "babel-" t)) + "Directory to hold temporary files created to execute code blocks. +Used by `org-babel-temp-file'. This directory will be removed on +Emacs shutdown.")) + +(defcustom org-babel-remote-temporary-directory "/tmp/" + "Directory to hold temporary files on remote hosts." + :group 'org-babel + :type 'string) + +(defmacro org-babel-result-cond (result-params scalar-form &rest table-forms) + "Call the code to parse raw string results according to RESULT-PARAMS." + (declare (indent 1) + (debug (form form &rest form))) + (org-with-gensyms (params) + `(let ((,params ,result-params)) + (unless (member "none" ,params) + (if (or (member "scalar" ,params) + (member "verbatim" ,params) + (member "html" ,params) + (member "code" ,params) + (member "pp" ,params) + (member "file" ,params) + (and (or (member "output" ,params) + (member "raw" ,params) + (member "org" ,params) + (member "drawer" ,params)) + (not (member "table" ,params)))) + ,scalar-form + ,@table-forms))))) +(def-edebug-spec org-babel-result-cond (form form body)) + +(defun org-babel-temp-file (prefix &optional suffix) + "Create a temporary file in the `org-babel-temporary-directory'. +Passes PREFIX and SUFFIX directly to `make-temp-file' with the +value of `temporary-file-directory' temporarily set to the value +of `org-babel-temporary-directory'." + (if (file-remote-p default-directory) + (let ((prefix + (concat (file-remote-p default-directory) + (expand-file-name + prefix org-babel-remote-temporary-directory)))) + (make-temp-file prefix nil suffix)) + (let ((temporary-file-directory + (or (and (boundp 'org-babel-temporary-directory) + (file-exists-p org-babel-temporary-directory) + org-babel-temporary-directory) + temporary-file-directory))) + (make-temp-file prefix nil suffix)))) + +(defun org-babel-remove-temporary-directory () + "Remove `org-babel-temporary-directory' on Emacs shutdown." + (when (and (boundp 'org-babel-temporary-directory) + (file-exists-p org-babel-temporary-directory)) + ;; taken from `delete-directory' in files.el + (condition-case nil + (progn + (mapc (lambda (file) + ;; This test is equivalent to + ;; (and (file-directory-p fn) (not (file-symlink-p fn))) + ;; but more efficient + (if (eq t (car (file-attributes file))) + (delete-directory file) + (delete-file file))) + ;; We do not want to delete "." and "..". + (directory-files org-babel-temporary-directory 'full + "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*")) + (delete-directory org-babel-temporary-directory)) + (error + (message "Failed to remove temporary Org-babel directory %s" + (if (boundp 'org-babel-temporary-directory) + org-babel-temporary-directory + "[directory not defined]")))))) + +(add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory) + +(defun org-babel-one-header-arg-safe-p (pair safe-list) + "Determine if the PAIR is a safe babel header arg according to SAFE-LIST. + +For the format of SAFE-LIST, see `org-babel-safe-header-args'." + (and (consp pair) + (keywordp (car pair)) + (stringp (cdr pair)) + (or + (memq (car pair) safe-list) + (let ((entry (assq (car pair) safe-list))) + (and entry + (consp entry) + (cond ((functionp (cdr entry)) + (funcall (cdr entry) (cdr pair))) + ((listp (cdr entry)) + (member (cdr pair) (cdr entry))) + (t nil))))))) + +(defun org-babel-generate-file-param (src-name params) + "Calculate the filename for source block results. + +The directory is calculated from the :output-dir property of the +source block; if not specified, use the current directory. + +If the source block has a #+NAME and the :file parameter does not +contain any period characters, then the :file parameter is +treated as an extension, and the output file name is the +concatenation of the directory (as calculated above), the block +name, a period, and the parameter value as a file extension. +Otherwise, the :file parameter is treated as a full file name, +and the output file name is the directory (as calculated above) +plus the parameter value." + (let* ((file-cons (assq :file params)) + (file-ext-cons (assq :file-ext params)) + (file-ext (cdr-safe file-ext-cons)) + (dir (cdr-safe (assq :output-dir params))) + fname) + ;; create the output-dir if it does not exist + (when dir + (make-directory dir t)) + (if file-cons + ;; :file given; add :output-dir if given + (when dir + (setcdr file-cons (concat (file-name-as-directory dir) (cdr file-cons)))) + ;; :file not given; compute from name and :file-ext if possible + (when (and src-name file-ext) + (if dir + (setq fname (concat (file-name-as-directory (or dir "")) + src-name "." file-ext)) + (setq fname (concat src-name "." file-ext))) + (setq params (cons (cons :file fname) params)))) + params)) + +(defun org-babel-graphical-output-file (params) + "File where a babel block should send graphical output, per PARAMS. +Return nil if no graphical output is expected. Raise an error if +the output file is ill-defined." + (let ((file (cdr (assq :file params)))) + (cond (file (and (member "graphics" (cdr (assq :result-params params))) + file)) + ((assq :file-ext params) + (user-error ":file-ext given but no :file generated; did you forget \ +to name a block?")) + (t (user-error "No :file header argument given; cannot create \ +graphical result"))))) + +(defun org-babel-make-language-alias (new old) + "Make source blocks of type NEW aliases for those of type OLD. + +NEW and OLD should be strings. This function should be called +after the babel API for OLD-type source blocks is fully defined. + +Callers of this function will probably want to add an entry to +`org-src-lang-modes' as well." + (dolist (fn '("execute" "expand-body" "prep-session" + "variable-assignments" "load-session")) + (let ((sym (intern-soft (concat "org-babel-" fn ":" old)))) + (when (and sym (fboundp sym)) + (defalias (intern (concat "org-babel-" fn ":" new)) sym)))) + ;; Technically we don't need a `dolist' for just one variable, but + ;; we keep it for symmetry/ease of future expansion. + (dolist (var '("default-header-args")) + (let ((sym (intern-soft (concat "org-babel-" var ":" old)))) + (when (and sym (boundp sym)) + (defvaralias (intern (concat "org-babel-" var ":" new)) sym))))) + +(defun org-babel-strip-quotes (string) + "Strip \\\"s from around a string, if applicable." + (org-unbracket-string "\"" "\"" string)) + +(provide 'ob-core) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; ob-core.el ends here diff --git a/elpa/org-9.1.14/ob-css.el b/elpa/org-9.1.14/ob-css.el new file mode 100644 index 00000000..8cabf2bc --- /dev/null +++ b/elpa/org-9.1.14/ob-css.el @@ -0,0 +1,48 @@ +;;; ob-css.el --- Babel Functions for CSS -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Since CSS can't be executed, this file exists solely for tangling +;; CSS from Org files. + +;;; Code: +(require 'ob) + +(defvar org-babel-default-header-args:css '()) + +(defun org-babel-execute:css (body _params) + "Execute a block of CSS code. +This function is called by `org-babel-execute-src-block'." + body) + +(defun org-babel-prep-session:css (_session _params) + "Return an error if the :session header argument is set. +CSS does not support sessions." + (error "CSS sessions are nonsensical")) + +(provide 'ob-css) + + + +;;; ob-css.el ends here diff --git a/elpa/org-9.1.14/ob-ditaa.el b/elpa/org-9.1.14/ob-ditaa.el new file mode 100644 index 00000000..9507630b --- /dev/null +++ b/elpa/org-9.1.14/ob-ditaa.el @@ -0,0 +1,124 @@ +;;; ob-ditaa.el --- Babel Functions for ditaa -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating ditaa source code. +;; +;; This differs from most standard languages in that +;; +;; 1) there is no such thing as a "session" in ditaa +;; +;; 2) we are generally only going to return results of type "file" +;; +;; 3) we are adding the "file" and "cmdline" header arguments +;; +;; 4) there are no variables (at least for now) + +;;; Code: +(require 'ob) +(require 'org-compat) + +(defvar org-babel-default-header-args:ditaa + '((:results . "file") + (:exports . "results") + (:java . "-Dfile.encoding=UTF-8")) + "Default arguments for evaluating a ditaa source block.") + +(defcustom org-ditaa-jar-path (expand-file-name + "ditaa.jar" + (file-name-as-directory + (expand-file-name + "scripts" + (file-name-as-directory + (expand-file-name + "../contrib" + (file-name-directory (org-find-library-dir "org"))))))) + "Path to the ditaa jar executable." + :group 'org-babel + :type 'string) + +(defcustom org-babel-ditaa-java-cmd "java" + "Java executable to use when evaluating ditaa blocks." + :group 'org-babel + :type 'string) + +(defcustom org-ditaa-eps-jar-path + (expand-file-name "DitaaEps.jar" (file-name-directory org-ditaa-jar-path)) + "Path to the DitaaEps.jar executable." + :group 'org-babel + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-ditaa-jar-option "-jar" + "Option for the ditaa jar file. +Do not leave leading or trailing spaces in this string." + :group 'org-babel + :version "24.1" + :type 'string) + +(defun org-babel-execute:ditaa (body params) + "Execute a block of Ditaa code with org-babel. +This function is called by `org-babel-execute-src-block'." + (let* ((out-file (or (cdr (assq :file params)) + (error + "ditaa code block requires :file header argument"))) + (cmdline (cdr (assq :cmdline params))) + (java (cdr (assq :java params))) + (in-file (org-babel-temp-file "ditaa-")) + (eps (cdr (assq :eps params))) + (eps-file (when eps + (org-babel-process-file-name (concat in-file ".eps")))) + (pdf-cmd (when (and (or (string= (file-name-extension out-file) "pdf") + (cdr (assq :pdf params)))) + (concat + "epstopdf" + " " eps-file + " -o=" (org-babel-process-file-name out-file)))) + (cmd (concat org-babel-ditaa-java-cmd + " " java " " org-ditaa-jar-option " " + (shell-quote-argument + (expand-file-name + (if eps org-ditaa-eps-jar-path org-ditaa-jar-path))) + " " cmdline + " " (org-babel-process-file-name in-file) + " " (if pdf-cmd + eps-file + (org-babel-process-file-name out-file))))) + (unless (file-exists-p org-ditaa-jar-path) + (error "Could not find ditaa.jar at %s" org-ditaa-jar-path)) + (with-temp-file in-file (insert body)) + (message cmd) (shell-command cmd) + (when pdf-cmd (message pdf-cmd) (shell-command pdf-cmd)) + nil)) ;; signal that output has already been written to file + +(defun org-babel-prep-session:ditaa (_session _params) + "Return an error because ditaa does not support sessions." + (error "Ditaa does not support sessions")) + +(provide 'ob-ditaa) + + + +;;; ob-ditaa.el ends here diff --git a/elpa/org-9.1.14/ob-dot.el b/elpa/org-9.1.14/ob-dot.el new file mode 100644 index 00000000..31e0a4f3 --- /dev/null +++ b/elpa/org-9.1.14/ob-dot.el @@ -0,0 +1,90 @@ +;;; ob-dot.el --- Babel Functions for dot -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating dot source code. +;; +;; For information on dot see http://www.graphviz.org/ +;; +;; This differs from most standard languages in that +;; +;; 1) there is no such thing as a "session" in dot +;; +;; 2) we are generally only going to return results of type "file" +;; +;; 3) we are adding the "file" and "cmdline" header arguments +;; +;; 4) there are no variables (at least for now) + +;;; Code: +(require 'ob) + +(defvar org-babel-default-header-args:dot + '((:results . "file") (:exports . "results")) + "Default arguments to use when evaluating a dot source block.") + +(defun org-babel-expand-body:dot (body params) + "Expand BODY according to PARAMS, return the expanded body." + (let ((vars (org-babel--get-vars params))) + (mapc + (lambda (pair) + (let ((name (symbol-name (car pair))) + (value (cdr pair))) + (setq body + (replace-regexp-in-string + (concat "$" (regexp-quote name)) + (if (stringp value) value (format "%S" value)) + body + t + t)))) + vars) + body)) + +(defun org-babel-execute:dot (body params) + "Execute a block of Dot code with org-babel. +This function is called by `org-babel-execute-src-block'." + (let* ((out-file (cdr (or (assq :file params) + (error "You need to specify a :file parameter")))) + (cmdline (or (cdr (assq :cmdline params)) + (format "-T%s" (file-name-extension out-file)))) + (cmd (or (cdr (assq :cmd params)) "dot")) + (in-file (org-babel-temp-file "dot-"))) + (with-temp-file in-file + (insert (org-babel-expand-body:dot body params))) + (org-babel-eval + (concat cmd + " " (org-babel-process-file-name in-file) + " " cmdline + " -o " (org-babel-process-file-name out-file)) "") + nil)) ;; signal that output has already been written to file + +(defun org-babel-prep-session:dot (_session _params) + "Return an error because Dot does not support sessions." + (error "Dot does not support sessions")) + +(provide 'ob-dot) + + + +;;; ob-dot.el ends here diff --git a/elpa/org-9.1.14/ob-ebnf.el b/elpa/org-9.1.14/ob-ebnf.el new file mode 100644 index 00000000..8c7c5415 --- /dev/null +++ b/elpa/org-9.1.14/ob-ebnf.el @@ -0,0 +1,81 @@ +;;; ob-ebnf.el --- Babel Functions for EBNF -*- lexical-binding: t; -*- + +;; Copyright (C) 2013-2018 Free Software Foundation, Inc. + +;; Author: Michael Gauland +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org +;; Version: 1.00 + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;;; Org-Babel support for using ebnf2ps to generate encapsulated postscript +;;; railroad diagrams. It recognizes these arguments: +;;; +;;; :file is required; it must include the extension '.eps.' All the rules +;;; in the block will be drawn in the same file. This is done by +;;; inserting a '[' comment at the start of the block (see the +;;; documentation for ebnf-eps-buffer for more information). +;;; +;;; :style specifies a value in ebnf-style-database. This provides the +;;; ability to customize the output. The style can also specify the +;;; grammar syntax (by setting ebnf-syntax); note that only ebnf, +;;; iso-ebnf, and yacc are supported by this file. + +;;; Requirements: + +;;; Code: +(require 'ob) +(require 'ebnf2ps) + +;; optionally declare default header arguments for this language +(defvar org-babel-default-header-args:ebnf '((:style . nil))) + +;; Use ebnf-eps-buffer to produce an encapsulated postscript file. +;; +(defun org-babel-execute:ebnf (body params) + "Execute a block of Ebnf code with org-babel. This function is +called by `org-babel-execute-src-block'" + (save-excursion + (let* ((dest-file (cdr (assq :file params))) + (dest-dir (file-name-directory dest-file)) + (dest-root (file-name-sans-extension + (file-name-nondirectory dest-file))) + (style (cdr (assq :style params))) + (result nil)) + (with-temp-buffer + (when style (ebnf-push-style style)) + (let ((comment-format + (cond ((string= ebnf-syntax 'yacc) "/*%s*/") + ((string= ebnf-syntax 'ebnf) ";%s") + ((string= ebnf-syntax 'iso-ebnf) "(*%s*)") + (t (setq result + (format "EBNF error: format %s not supported." + ebnf-syntax)))))) + (setq ebnf-eps-prefix dest-dir) + (insert (format comment-format (format "[%s" dest-root))) + (newline) + (insert body) + (newline) + (insert (format comment-format (format "]%s" dest-root))) + (ebnf-eps-buffer) + (when style (ebnf-pop-style)))) + result))) + +(provide 'ob-ebnf) +;;; ob-ebnf.el ends here diff --git a/elpa/org-9.1.14/ob-emacs-lisp.el b/elpa/org-9.1.14/ob-emacs-lisp.el new file mode 100644 index 00000000..8ea2ec12 --- /dev/null +++ b/elpa/org-9.1.14/ob-emacs-lisp.el @@ -0,0 +1,91 @@ +;;; ob-emacs-lisp.el --- Babel Functions for Emacs-lisp Code -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating emacs-lisp code + +;;; Code: +(require 'ob) + +(defconst org-babel-header-args:emacs-lisp '((lexical . :any)) + "Emacs-lisp specific header arguments.") + +(defvar org-babel-default-header-args:emacs-lisp '((:lexical . "no")) + "Default arguments for evaluating an emacs-lisp source block. + +A value of \"yes\" or t causes src blocks to be eval'd using +lexical scoping. It can also be an alist mapping symbols to +their value. It is used as the optional LEXICAL argument to +`eval', which see.") + +(defun org-babel-expand-body:emacs-lisp (body params) + "Expand BODY according to PARAMS, return the expanded body." + (let ((vars (org-babel--get-vars params)) + (print-level nil) + (print-length nil)) + (if (null vars) (concat body "\n") + (format "(let (%s)\n%s\n)" + (mapconcat + (lambda (var) + (format "%S" (print `(,(car var) ',(cdr var))))) + vars "\n ") + body)))) + +(defun org-babel-execute:emacs-lisp (body params) + "Execute a block of emacs-lisp code with Babel." + (save-window-excursion + (let* ((lexical (cdr (assq :lexical params))) + (result-params (cdr (assq :result-params params))) + (body (format (if (member "output" result-params) + "(with-output-to-string %s\n)" + "(progn %s\n)") + (org-babel-expand-body:emacs-lisp body params))) + (result (eval (read (if (or (member "code" result-params) + (member "pp" result-params)) + (concat "(pp " body ")") + body)) + (if (listp lexical) + lexical + (member lexical '("yes" "t")))))) + (org-babel-result-cond result-params + (let ((print-level nil) + (print-length nil)) + (if (or (member "scalar" result-params) + (member "verbatim" result-params)) + (format "%S" result) + (format "%s" result))) + (org-babel-reassemble-table + result + (org-babel-pick-name (cdr (assq :colname-names params)) + (cdr (assq :colnames params))) + (org-babel-pick-name (cdr (assq :rowname-names params)) + (cdr (assq :rownames params)))))))) + +(org-babel-make-language-alias "elisp" "emacs-lisp") + +(provide 'ob-emacs-lisp) + + + +;;; ob-emacs-lisp.el ends here diff --git a/elpa/org-9.1.14/ob-eval.el b/elpa/org-9.1.14/ob-eval.el new file mode 100644 index 00000000..2bfaa08a --- /dev/null +++ b/elpa/org-9.1.14/ob-eval.el @@ -0,0 +1,149 @@ +;;; ob-eval.el --- Babel Functions for External Code Evaluation -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research, comint +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; These functions build existing Emacs support for executing external +;; shell commands. + +;;; Code: +(require 'org-macs) + +(defvar org-babel-error-buffer-name "*Org-Babel Error Output*") +(declare-function org-babel-temp-file "ob-core" (prefix &optional suffix)) + +(defun org-babel-eval-error-notify (exit-code stderr) + "Open a buffer to display STDERR and a message with the value of EXIT-CODE." + (let ((buf (get-buffer-create org-babel-error-buffer-name))) + (with-current-buffer buf + (goto-char (point-max)) + (save-excursion (insert stderr))) + (display-buffer buf)) + (message "Babel evaluation exited with code %S" exit-code)) + +(defun org-babel-eval (cmd body) + "Run CMD on BODY. +If CMD succeeds then return its results, otherwise display +STDERR with `org-babel-eval-error-notify'." + (let ((err-buff (get-buffer-create " *Org-Babel Error*")) exit-code) + (with-current-buffer err-buff (erase-buffer)) + (with-temp-buffer + (insert body) + (setq exit-code + (org-babel--shell-command-on-region + (point-min) (point-max) cmd err-buff)) + (if (or (not (numberp exit-code)) (> exit-code 0)) + (progn + (with-current-buffer err-buff + (org-babel-eval-error-notify exit-code (buffer-string))) + (save-excursion + (when (get-buffer org-babel-error-buffer-name) + (with-current-buffer org-babel-error-buffer-name + (unless (derived-mode-p 'compilation-mode) + (compilation-mode)) + ;; Compilation-mode enforces read-only, but Babel expects the buffer modifiable. + (setq buffer-read-only nil)))) + nil) + (buffer-string))))) + +(defun org-babel-eval-read-file (file) + "Return the contents of FILE as a string." + (with-temp-buffer (insert-file-contents file) + (buffer-string))) + +(defun org-babel--shell-command-on-region (start end command error-buffer) + "Execute COMMAND in an inferior shell with region as input. + +Stripped down version of shell-command-on-region for internal use +in Babel only. This lets us work around errors in the original +function in various versions of Emacs. +" + (let ((input-file (org-babel-temp-file "ob-input-")) + (error-file (if error-buffer (org-babel-temp-file "ob-error-") nil)) + ;; Unfortunately, `executable-find' does not support file name + ;; handlers. Therefore, we could use it in the local case + ;; only. + (shell-file-name + (cond ((and (not (file-remote-p default-directory)) + (executable-find shell-file-name)) + shell-file-name) + ((file-executable-p + (concat (file-remote-p default-directory) shell-file-name)) + shell-file-name) + ("/bin/sh"))) + exit-status) + ;; There is an error in `process-file' when `error-file' exists. + ;; This is fixed in Emacs trunk as of 2012-12-21; let's use this + ;; workaround for now. + (unless (file-remote-p default-directory) + (delete-file error-file)) + ;; we always call this with 'replace, remove conditional + ;; Replace specified region with output from command. + (let ((swap (< start end))) + (goto-char start) + (push-mark (point) 'nomsg) + (write-region start end input-file) + (delete-region start end) + (setq exit-status + (process-file shell-file-name input-file + (if error-file + (list t error-file) + t) + nil shell-command-switch command)) + (when swap (exchange-point-and-mark))) + + (when (and input-file (file-exists-p input-file) + ;; bind org-babel--debug-input around the call to keep + ;; the temporary input files available for inspection + (not (when (boundp 'org-babel--debug-input) + org-babel--debug-input))) + (delete-file input-file)) + + (when (and error-file (file-exists-p error-file)) + (when (< 0 (nth 7 (file-attributes error-file))) + (with-current-buffer (get-buffer-create error-buffer) + (let ((pos-from-end (- (point-max) (point)))) + (or (bobp) + (insert "\f\n")) + ;; Do no formatting while reading error file, + ;; because that can run a shell command, and we + ;; don't want that to cause an infinite recursion. + (format-insert-file error-file nil) + ;; Put point after the inserted errors. + (goto-char (- (point-max) pos-from-end))) + (current-buffer))) + (delete-file error-file)) + exit-status)) + +(defun org-babel-eval-wipe-error-buffer () + "Delete the contents of the Org code block error buffer. +This buffer is named by `org-babel-error-buffer-name'." + (when (get-buffer org-babel-error-buffer-name) + (with-current-buffer org-babel-error-buffer-name + (delete-region (point-min) (point-max))))) + +(provide 'ob-eval) + + + +;;; ob-eval.el ends here diff --git a/elpa/org-9.1.14/ob-exp.el b/elpa/org-9.1.14/ob-exp.el new file mode 100644 index 00000000..264dc0ed --- /dev/null +++ b/elpa/org-9.1.14/ob-exp.el @@ -0,0 +1,413 @@ +;;; ob-exp.el --- Exportation of Babel Source Blocks -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Authors: Eric Schulte +;; Dan Davison +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Code: +(require 'ob-core) + +(declare-function org-babel-lob-get-info "ob-lob" (&optional datum)) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-context "org-element" (&optional element)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-type "org-element" (element)) +(declare-function org-escape-code-in-string "org-src" (s)) +(declare-function org-export-copy-buffer "ox" ()) +(declare-function org-fill-template "org" (template alist)) +(declare-function org-get-indentation "org" (&optional line)) +(declare-function org-in-commented-heading-p "org" (&optional no-inheritance)) + +(defvar org-src-preserve-indentation) + +(defcustom org-export-use-babel t + "Switch controlling code evaluation and header processing during export. +When set to nil no code will be evaluated as part of the export +process and no header arguments will be obeyed. Users who wish +to avoid evaluating code on export should use the header argument +`:eval never-export'." + :group 'org-babel + :version "24.1" + :type '(choice (const :tag "Never" nil) + (const :tag "Always" t)) + :safe #'null) + + +(defmacro org-babel-exp--at-source (&rest body) + "Evaluate BODY at the source of the Babel block at point. +Source is located in `org-babel-exp-reference-buffer'. The value +returned is the value of the last form in BODY. Assume that +point is at the beginning of the Babel block." + (declare (indent 1) (debug body)) + `(let ((source (get-text-property (point) 'org-reference))) + ;; Source blocks created during export process (e.g., by other + ;; source blocks) are not referenced. In this case, do not move + ;; point at all. + (with-current-buffer (if source org-babel-exp-reference-buffer + (current-buffer)) + (org-with-wide-buffer + (when source (goto-char source)) + ,@body)))) + +(defun org-babel-exp-src-block () + "Process source block for export. +Depending on the \":export\" header argument, replace the source +code block like this: + +both ---- display the code and the results + +code ---- the default, display the code inside the block but do + not process + +results - just like none only the block is run on export ensuring + that its results are present in the Org mode buffer + +none ---- do not display either code or results upon export + +Assume point is at block opening line." + (interactive) + (save-excursion + (let* ((info (org-babel-get-src-block-info 'light)) + (lang (nth 0 info)) + (raw-params (nth 2 info)) + hash) + ;; bail if we couldn't get any info from the block + (unless noninteractive + (message "org-babel-exp process %s at position %d..." + lang + (line-beginning-position))) + (when info + ;; if we're actually going to need the parameters + (when (member (cdr (assq :exports (nth 2 info))) '("both" "results")) + (let ((lang-headers (intern (concat "org-babel-default-header-args:" + lang)))) + (org-babel-exp--at-source + (setf (nth 2 info) + (org-babel-process-params + (apply #'org-babel-merge-params + org-babel-default-header-args + (and (boundp lang-headers) + (symbol-value lang-headers)) + (append (org-babel-params-from-properties lang) + (list raw-params))))))) + (setf hash (org-babel-sha1-hash info))) + (org-babel-exp-do-export info 'block hash))))) + +(defcustom org-babel-exp-call-line-template + "" + "Template used to export call lines. +This template may be customized to include the call line name +with any export markup. The template is filled out using +`org-fill-template', and the following %keys may be used. + + line --- call line + +An example value would be \"\\n: call: %line\" to export the call line +wrapped in a verbatim environment. + +Note: the results are inserted separately after the contents of +this template." + :group 'org-babel + :type 'string) + +(defun org-babel-exp-process-buffer () + "Execute all Babel blocks in current buffer." + (interactive) + (when org-export-use-babel + (save-window-excursion + (let ((case-fold-search t) + (regexp "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)") + ;; Get a pristine copy of current buffer so Babel + ;; references are properly resolved and source block + ;; context is preserved. + (org-babel-exp-reference-buffer (org-export-copy-buffer))) + (unwind-protect + (save-excursion + ;; First attach to every source block their original + ;; position, so that they can be retrieved within + ;; `org-babel-exp-reference-buffer', even after heavy + ;; modifications on current buffer. + ;; + ;; False positives are harmless, so we don't check if + ;; we're really at some Babel object. Moreover, + ;; `line-end-position' ensures that we propertize + ;; a noticeable part of the object, without affecting + ;; multiple objects on the same line. + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (let ((s (match-beginning 0))) + (put-text-property s (line-end-position) 'org-reference s))) + ;; Evaluate from top to bottom every Babel block + ;; encountered. + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (unless (save-match-data (org-in-commented-heading-p)) + (let* ((object? (match-end 1)) + (element (save-match-data + (if object? (org-element-context) + ;; No deep inspection if we're + ;; just looking for an element. + (org-element-at-point)))) + (type + (pcase (org-element-type element) + ;; Discard block elements if we're looking + ;; for inline objects. False results + ;; happen when, e.g., "call_" syntax is + ;; located within affiliated keywords: + ;; + ;; #+name: call_src + ;; #+begin_src ... + ((and (or `babel-call `src-block) (guard object?)) + nil) + (type type))) + (begin + (copy-marker (org-element-property :begin element))) + (end + (copy-marker + (save-excursion + (goto-char (org-element-property :end element)) + (skip-chars-backward " \r\t\n") + (point))))) + (pcase type + (`inline-src-block + (let* ((info + (org-babel-get-src-block-info nil element)) + (params (nth 2 info))) + (setf (nth 1 info) + (if (and (cdr (assq :noweb params)) + (string= "yes" + (cdr (assq :noweb params)))) + (org-babel-expand-noweb-references + info org-babel-exp-reference-buffer) + (nth 1 info))) + (goto-char begin) + (let ((replacement + (org-babel-exp-do-export info 'inline))) + (if (equal replacement "") + ;; Replacement code is empty: remove + ;; inline source block, including extra + ;; white space that might have been + ;; created when inserting results. + (delete-region begin + (progn (goto-char end) + (skip-chars-forward " \t") + (point))) + ;; Otherwise: remove inline src block but + ;; preserve following white spaces. Then + ;; insert value. + (delete-region begin end) + (insert replacement))))) + ((or `babel-call `inline-babel-call) + (org-babel-exp-do-export (org-babel-lob-get-info element) + 'lob) + (let ((rep + (org-fill-template + org-babel-exp-call-line-template + `(("line" . + ,(org-element-property :value element)))))) + ;; If replacement is empty, completely remove + ;; the object/element, including any extra + ;; white space that might have been created + ;; when including results. + (if (equal rep "") + (delete-region + begin + (progn (goto-char end) + (if (not (eq type 'babel-call)) + (progn (skip-chars-forward " \t") + (point)) + (skip-chars-forward " \r\t\n") + (line-beginning-position)))) + ;; Otherwise, preserve trailing + ;; spaces/newlines and then, insert + ;; replacement string. + (goto-char begin) + (delete-region begin end) + (insert rep)))) + (`src-block + (let ((match-start (copy-marker (match-beginning 0))) + (ind (org-get-indentation))) + ;; Take care of matched block: compute + ;; replacement string. In particular, a nil + ;; REPLACEMENT means the block is left as-is + ;; while an empty string removes the block. + (let ((replacement + (progn (goto-char match-start) + (org-babel-exp-src-block)))) + (cond ((not replacement) (goto-char end)) + ((equal replacement "") + (goto-char end) + (skip-chars-forward " \r\t\n") + (beginning-of-line) + (delete-region begin (point))) + (t + (goto-char match-start) + (delete-region (point) + (save-excursion + (goto-char end) + (line-end-position))) + (insert replacement) + (if (or org-src-preserve-indentation + (org-element-property + :preserve-indent element)) + ;; Indent only code block + ;; markers. + (save-excursion + (skip-chars-backward " \r\t\n") + (indent-line-to ind) + (goto-char match-start) + (indent-line-to ind)) + ;; Indent everything. + (indent-rigidly + match-start (point) ind))))) + (set-marker match-start nil)))) + (set-marker begin nil) + (set-marker end nil))))) + (kill-buffer org-babel-exp-reference-buffer) + (remove-text-properties (point-min) (point-max) '(org-reference))))))) + +(defun org-babel-exp-do-export (info type &optional hash) + "Return a string with the exported content of a code block. +The function respects the value of the :exports header argument." + (let ((silently (lambda () (let ((session (cdr (assq :session (nth 2 info))))) + (unless (equal "none" session) + (org-babel-exp-results info type 'silent))))) + (clean (lambda () (if (eq type 'inline) + (org-babel-remove-inline-result) + (org-babel-remove-result info))))) + (pcase (or (cdr (assq :exports (nth 2 info))) "code") + ("none" (funcall silently) (funcall clean) "") + ("code" (funcall silently) (funcall clean) (org-babel-exp-code info type)) + ("results" (org-babel-exp-results info type nil hash) "") + ("both" + (org-babel-exp-results info type nil hash) + (org-babel-exp-code info type))))) + +(defcustom org-babel-exp-code-template + "#+BEGIN_SRC %lang%switches%flags\n%body\n#+END_SRC" + "Template used to export the body of code blocks. +This template may be customized to include additional information +such as the code block name, or the values of particular header +arguments. The template is filled out using `org-fill-template', +and the following %keys may be used. + + lang ------ the language of the code block + name ------ the name of the code block + body ------ the body of the code block + switches -- the switches associated to the code block + flags ----- the flags passed to the code block + +In addition to the keys mentioned above, every header argument +defined for the code block may be used as a key and will be +replaced with its value." + :group 'org-babel + :type 'string) + +(defcustom org-babel-exp-inline-code-template + "src_%lang[%switches%flags]{%body}" + "Template used to export the body of inline code blocks. +This template may be customized to include additional information +such as the code block name, or the values of particular header +arguments. The template is filled out using `org-fill-template', +and the following %keys may be used. + + lang ------ the language of the code block + name ------ the name of the code block + body ------ the body of the code block + switches -- the switches associated to the code block + flags ----- the flags passed to the code block + +In addition to the keys mentioned above, every header argument +defined for the code block may be used as a key and will be +replaced with its value." + :group 'org-babel + :type 'string + :version "26.1" + :package-version '(Org . "8.3")) + +(defun org-babel-exp-code (info type) + "Return the original code block formatted for export." + (setf (nth 1 info) + (if (string= "strip-export" (cdr (assq :noweb (nth 2 info)))) + (replace-regexp-in-string + (org-babel-noweb-wrap) "" (nth 1 info)) + (if (org-babel-noweb-p (nth 2 info) :export) + (org-babel-expand-noweb-references + info org-babel-exp-reference-buffer) + (nth 1 info)))) + (org-fill-template + (if (eq type 'inline) + org-babel-exp-inline-code-template + org-babel-exp-code-template) + `(("lang" . ,(nth 0 info)) + ("body" . ,(org-escape-code-in-string (nth 1 info))) + ("switches" . ,(let ((f (nth 3 info))) + (and (org-string-nw-p f) (concat " " f)))) + ("flags" . ,(let ((f (assq :flags (nth 2 info)))) + (and f (concat " " (cdr f))))) + ,@(mapcar (lambda (pair) + (cons (substring (symbol-name (car pair)) 1) + (format "%S" (cdr pair)))) + (nth 2 info)) + ("name" . ,(or (nth 4 info) ""))))) + +(defun org-babel-exp-results (info type &optional silent hash) + "Evaluate and return the results of the current code block for export. +Results are prepared in a manner suitable for export by Org mode. +This function is called by `org-babel-exp-do-export'. The code +block will be evaluated. Optional argument SILENT can be used to +inhibit insertion of results into the buffer." + (unless (and hash (equal hash (org-babel-current-result-hash))) + (let ((lang (nth 0 info)) + (body (if (org-babel-noweb-p (nth 2 info) :eval) + (org-babel-expand-noweb-references + info org-babel-exp-reference-buffer) + (nth 1 info))) + (info (copy-sequence info)) + (org-babel-current-src-block-location (point-marker))) + ;; Skip code blocks which we can't evaluate. + (when (fboundp (intern (concat "org-babel-execute:" lang))) + (org-babel-eval-wipe-error-buffer) + (setf (nth 1 info) body) + (setf (nth 2 info) + (org-babel-exp--at-source + (org-babel-process-params + (org-babel-merge-params + (nth 2 info) + `((:results . ,(if silent "silent" "replace"))))))) + (pcase type + (`block (org-babel-execute-src-block nil info)) + (`inline + ;; Position the point on the inline source block + ;; allowing `org-babel-insert-result' to check that the + ;; block is inline. + (goto-char (nth 5 info)) + (org-babel-execute-src-block nil info)) + (`lob + (save-excursion + (goto-char (nth 5 info)) + (let (org-confirm-babel-evaluate) + (org-babel-execute-src-block nil info))))))))) + + +(provide 'ob-exp) + +;;; ob-exp.el ends here diff --git a/elpa/org-9.1.14/ob-forth.el b/elpa/org-9.1.14/ob-forth.el new file mode 100644 index 00000000..efd57593 --- /dev/null +++ b/elpa/org-9.1.14/ob-forth.el @@ -0,0 +1,87 @@ +;;; ob-forth.el --- Babel Functions for Forth -*- lexical-binding: t; -*- + +;; Copyright (C) 2014-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research, forth +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Requires the gforth forth compiler and `forth-mode' (see below). +;; https://www.gnu.org/software/gforth/ + +;;; Requirements: + +;; Session evaluation requires the gforth forth compiler as well as +;; `forth-mode' which is distributed with gforth (in gforth.el). + +;;; Code: +(require 'ob) + +(declare-function forth-proc "ext:gforth" ()) +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-babel-default-header-args:forth '((:session . "yes")) + "Default header arguments for forth code blocks.") + +(defun org-babel-execute:forth (body params) + "Execute a block of Forth code with org-babel. +This function is called by `org-babel-execute-src-block'" + (if (string= "none" (cdr (assq :session params))) + (error "Non-session evaluation not supported for Forth code blocks") + (let ((all-results (org-babel-forth-session-execute body params))) + (if (member "output" (cdr (assq :result-params params))) + (mapconcat #'identity all-results "\n") + (car (last all-results)))))) + +(defun org-babel-forth-session-execute (body params) + (require 'forth-mode) + (let ((proc (forth-proc)) + (rx " \\(\n:\\|compiled\n\\\|ok\n\\)") + (result-start)) + (with-current-buffer (process-buffer (forth-proc)) + (mapcar (lambda (line) + (setq result-start (progn (goto-char (process-mark proc)) + (point))) + (comint-send-string proc (concat line "\n")) + ;; wait for forth to say "ok" + (while (not (progn (goto-char result-start) + (re-search-forward rx nil t))) + (accept-process-output proc 0.01)) + (let ((case (match-string 1))) + (cond + ((string= "ok\n" case) + ;; Collect intermediate output. + (buffer-substring (+ result-start 1 (length line)) + (match-beginning 0))) + ((string= "compiled\n" case)) + ;; Ignore partial compilation. + ((string= "\n:" case) + ;; Report errors. + (org-babel-eval-error-notify 1 + (buffer-substring + (+ (match-beginning 0) 1) (point-max))) nil)))) + (split-string (org-trim + (org-babel-expand-body:generic body params)) + "\n" + 'omit-nulls))))) + +(provide 'ob-forth) + +;;; ob-forth.el ends here diff --git a/elpa/org-9.1.14/ob-fortran.el b/elpa/org-9.1.14/ob-fortran.el new file mode 100644 index 00000000..49e960ff --- /dev/null +++ b/elpa/org-9.1.14/ob-fortran.el @@ -0,0 +1,168 @@ +;;; ob-fortran.el --- Babel Functions for Fortran -*- lexical-binding: t; -*- + +;; Copyright (C) 2011-2018 Free Software Foundation, Inc. + +;; Authors: Sergey Litvinov +;; Eric Schulte +;; Keywords: literate programming, reproducible research, fortran +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating fortran code. + +;;; Code: +(require 'ob) +(require 'cc-mode) +(require 'cl-lib) + +(declare-function org-entry-get "org" + (pom property &optional inherit literal-nil)) +(declare-function org-remove-indentation "org" (code &optional n)) +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("fortran" . "F90")) + +(defvar org-babel-default-header-args:fortran '()) + +(defvar org-babel-fortran-compiler "gfortran" + "fortran command used to compile a fortran source code file into an + executable.") + +(defun org-babel-execute:fortran (body params) + "This function should only be called by `org-babel-execute:fortran'" + (let* ((tmp-src-file (org-babel-temp-file "fortran-src-" ".F90")) + (tmp-bin-file (org-babel-temp-file "fortran-bin-" org-babel-exeext)) + (cmdline (cdr (assq :cmdline params))) + (flags (cdr (assq :flags params))) + (full-body (org-babel-expand-body:fortran body params))) + (with-temp-file tmp-src-file (insert full-body)) + (org-babel-eval + (format "%s -o %s %s %s" + org-babel-fortran-compiler + (org-babel-process-file-name tmp-bin-file) + (mapconcat 'identity + (if (listp flags) flags (list flags)) " ") + (org-babel-process-file-name tmp-src-file)) "") + (let ((results + (org-trim + (org-remove-indentation + (org-babel-eval + (concat tmp-bin-file (if cmdline (concat " " cmdline) "")) ""))))) + (org-babel-reassemble-table + (org-babel-result-cond (cdr (assq :result-params params)) + (org-babel-read results) + (let ((tmp-file (org-babel-temp-file "f-"))) + (with-temp-file tmp-file (insert results)) + (org-babel-import-elisp-from-file tmp-file))) + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))) + +(defun org-babel-expand-body:fortran (body params) + "Expand a block of fortran or fortran code with org-babel according to +its header arguments." + (let ((vars (org-babel--get-vars params)) + (main-p (not (string= (cdr (assq :main params)) "no"))) + (includes (or (cdr (assq :includes params)) + (org-babel-read (org-entry-get nil "includes" t)))) + (defines (org-babel-read + (or (cdr (assq :defines params)) + (org-babel-read (org-entry-get nil "defines" t)))))) + (mapconcat 'identity + (list + ;; includes + (mapconcat + (lambda (inc) (format "#include %s" inc)) + (if (listp includes) includes (list includes)) "\n") + ;; defines + (mapconcat + (lambda (inc) (format "#define %s" inc)) + (if (listp defines) defines (list defines)) "\n") + ;; body + (if main-p + (org-babel-fortran-ensure-main-wrap + (concat + ;; variables + (mapconcat 'org-babel-fortran-var-to-fortran vars "\n") + body) params) + body) "\n") "\n"))) + +(defun org-babel-fortran-ensure-main-wrap (body params) + "Wrap body in a \"program ... end program\" block if none exists." + (if (string-match "^[ \t]*program[ \t]*.*" (capitalize body)) + (let ((vars (org-babel--get-vars params))) + (if vars (error "Cannot use :vars if `program' statement is present")) + body) + (format "program main\n%s\nend program main\n" body))) + +(defun org-babel-prep-session:fortran (_session _params) + "This function does nothing as fortran is a compiled language with no +support for sessions" + (error "Fortran is a compiled languages -- no support for sessions")) + +(defun org-babel-load-session:fortran (_session _body _params) + "This function does nothing as fortran is a compiled language with no +support for sessions" + (error "Fortran is a compiled languages -- no support for sessions")) + +;; helper functions + +(defun org-babel-fortran-var-to-fortran (pair) + "Convert an elisp val into a string of fortran code specifying a var +of the same value." + ;; TODO list support + (let ((var (car pair)) + (val (cdr pair))) + (when (symbolp val) + (setq val (symbol-name val)) + (when (= (length val) 1) + (setq val (string-to-char val)))) + (cond + ((integerp val) + (format "integer, parameter :: %S = %S\n" var val)) + ((floatp val) + (format "real, parameter :: %S = %S\n" var val)) + ((or (integerp val)) + (format "character, parameter :: %S = '%S'\n" var val)) + ((stringp val) + (format "character(len=%d), parameter :: %S = '%s'\n" + (length val) var val)) + ;; val is a matrix + ((and (listp val) (cl-every #'listp val)) + (format "real, parameter :: %S(%d,%d) = transpose( reshape( %s , (/ %d, %d /) ) )\n" + var (length val) (length (car val)) + (org-babel-fortran-transform-list val) + (length (car val)) (length val))) + ((listp val) + (format "real, parameter :: %S(%d) = %s\n" + var (length val) (org-babel-fortran-transform-list val))) + (t + (error "the type of parameter %s is not supported by ob-fortran" var))))) + +(defun org-babel-fortran-transform-list (val) + "Return a fortran representation of enclose syntactic lists." + (if (listp val) + (concat "(/" (mapconcat #'org-babel-fortran-transform-list val ", ") "/)") + (format "%S" val))) + +(provide 'ob-fortran) + +;;; ob-fortran.el ends here diff --git a/elpa/org-9.1.14/ob-gnuplot.el b/elpa/org-9.1.14/ob-gnuplot.el new file mode 100644 index 00000000..b2f49133 --- /dev/null +++ b/elpa/org-9.1.14/ob-gnuplot.el @@ -0,0 +1,283 @@ +;;; ob-gnuplot.el --- Babel Functions for Gnuplot -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating gnuplot source code. +;; +;; This differs from most standard languages in that +;; +;; 1) we are generally only going to return results of type "file" +;; +;; 2) we are adding the "file" and "cmdline" header arguments + +;;; Requirements: + +;; - gnuplot :: http://www.gnuplot.info/ +;; +;; - gnuplot-mode :: http://cars9.uchicago.edu/~ravel/software/gnuplot-mode.html + +;;; Code: +(require 'ob) + +(declare-function org-time-string-to-time "org" (s)) +(declare-function org-combine-plists "org" (&rest plists)) +(declare-function orgtbl-to-generic "org-table" (table params)) +(declare-function gnuplot-mode "ext:gnuplot-mode" ()) +(declare-function gnuplot-send-string-to-gnuplot "ext:gnuplot-mode" (str txt)) +(declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot-mode" ()) + +(defvar org-babel-default-header-args:gnuplot + '((:results . "file") (:exports . "results") (:session . nil)) + "Default arguments to use when evaluating a gnuplot source block.") + +(defvar org-babel-header-args:gnuplot + '((title . :any) + (lines . :any) + (sets . :any) + (x-labels . :any) + (y-labels . :any) + (timefmt . :any) + (time-ind . :any) + (missing . :any) + (term . :any)) + "Gnuplot specific header args.") + +(defvar org-babel-gnuplot-timestamp-fmt nil) ; Dynamically scoped. + +(defvar *org-babel-gnuplot-missing* nil) + +(defcustom *org-babel-gnuplot-terms* + '((eps . "postscript eps")) + "List of file extensions and the associated gnuplot terminal." + :group 'org-babel + :type '(repeat (cons (symbol :tag "File extension") + (string :tag "Gnuplot terminal")))) + +(defun org-babel-gnuplot-process-vars (params) + "Extract variables from PARAMS and process the variables. +Dumps all vectors into files and returns an association list +of variable names and the related value to be used in the gnuplot +code." + (let ((*org-babel-gnuplot-missing* (cdr (assq :missing params)))) + (mapcar + (lambda (pair) + (cons + (car pair) ;; variable name + (let* ((val (cdr pair)) ;; variable value + (lp (listp val))) + (if lp + (org-babel-gnuplot-table-to-data + (let* ((first (car val)) + (tablep (or (listp first) (symbolp first)))) + (if tablep val (mapcar 'list val))) + (org-babel-temp-file "gnuplot-") params) + val)))) + (org-babel--get-vars params)))) + +(defun org-babel-expand-body:gnuplot (body params) + "Expand BODY according to PARAMS, return the expanded body." + (save-window-excursion + (let* ((vars (org-babel-gnuplot-process-vars params)) + (out-file (cdr (assq :file params))) + (prologue (cdr (assq :prologue params))) + (epilogue (cdr (assq :epilogue params))) + (term (or (cdr (assq :term params)) + (when out-file + (let ((ext (file-name-extension out-file))) + (or (cdr (assoc (intern (downcase ext)) + *org-babel-gnuplot-terms*)) + ext))))) + (title (cdr (assq :title params))) + (lines (cdr (assq :line params))) + (sets (cdr (assq :set params))) + (x-labels (cdr (assq :xlabels params))) + (y-labels (cdr (assq :ylabels params))) + (timefmt (cdr (assq :timefmt params))) + (time-ind (or (cdr (assq :timeind params)) + (when timefmt 1))) + (directory (and (buffer-file-name) + (file-name-directory (buffer-file-name)))) + (add-to-body (lambda (text) (setq body (concat text "\n" body))))) + ;; append header argument settings to body + (when title (funcall add-to-body (format "set title '%s'" title))) + (when lines (mapc (lambda (el) (funcall add-to-body el)) lines)) + (when sets + (mapc (lambda (el) (funcall add-to-body (format "set %s" el))) sets)) + (when x-labels + (funcall add-to-body + (format "set xtics (%s)" + (mapconcat (lambda (pair) + (format "\"%s\" %d" + (cdr pair) (car pair))) + x-labels ", ")))) + (when y-labels + (funcall add-to-body + (format "set ytics (%s)" + (mapconcat (lambda (pair) + (format "\"%s\" %d" + (cdr pair) (car pair))) + y-labels ", ")))) + (when time-ind + (funcall add-to-body "set xdata time") + (funcall add-to-body (concat "set timefmt \"" + (or timefmt + "%Y-%m-%d-%H:%M:%S") "\""))) + (when out-file + ;; set the terminal at the top of the block + (funcall add-to-body (format "set output \"%s\"" out-file)) + ;; and close the terminal at the bottom of the block + (setq body (concat body "\nset output\n"))) + (when term (funcall add-to-body (format "set term %s" term))) + ;; insert variables into code body: this should happen last + ;; placing the variables at the *top* of the code in case their + ;; values are used later + (funcall add-to-body + (mapconcat #'identity + (org-babel-variable-assignments:gnuplot params) + "\n")) + ;; replace any variable names preceded by '$' with the actual + ;; value of the variable + (mapc (lambda (pair) + (setq body (replace-regexp-in-string + (format "\\$%s" (car pair)) (cdr pair) body))) + vars) + (when prologue (funcall add-to-body prologue)) + (when epilogue (setq body (concat body "\n" epilogue))) + ;; Setting the directory needs to be done first so that + ;; subsequent 'output' directive goes to the right place. + (when directory (funcall add-to-body (format "cd '%s'" directory)))) + body)) + +(defun org-babel-execute:gnuplot (body params) + "Execute a block of Gnuplot code. +This function is called by `org-babel-execute-src-block'." + (require 'gnuplot) + (let ((session (cdr (assq :session params))) + (result-type (cdr (assq :results params))) + (body (org-babel-expand-body:gnuplot body params)) + output) + (save-window-excursion + ;; evaluate the code body with gnuplot + (if (string= session "none") + (let ((script-file (org-babel-temp-file "gnuplot-script-"))) + (with-temp-file script-file + (insert (concat body "\n"))) + (message "gnuplot \"%s\"" script-file) + (setq output + (shell-command-to-string + (format + "gnuplot \"%s\"" + (org-babel-process-file-name + script-file + (if (member system-type '(cygwin windows-nt ms-dos)) + t nil))))) + (message "%s" output)) + (with-temp-buffer + (insert (concat body "\n")) + (gnuplot-mode) + (gnuplot-send-buffer-to-gnuplot))) + (if (member "output" (split-string result-type)) + output + nil)))) ;; signal that output has already been written to file + +(defun org-babel-prep-session:gnuplot (session params) + "Prepare SESSION according to the header arguments in PARAMS." + (let* ((session (org-babel-gnuplot-initiate-session session)) + (var-lines (org-babel-variable-assignments:gnuplot params))) + (message "%S" session) + (org-babel-comint-in-buffer session + (dolist (var-line var-lines) + (insert var-line) + (comint-send-input nil t) + (org-babel-comint-wait-for-output session) + (sit-for .1) + (goto-char (point-max)))) + session)) + +(defun org-babel-load-session:gnuplot (session body params) + "Load BODY into SESSION." + (save-window-excursion + (let ((buffer (org-babel-prep-session:gnuplot session params))) + (with-current-buffer buffer + (goto-char (process-mark (get-buffer-process (current-buffer)))) + (insert (org-babel-chomp body))) + buffer))) + +(defun org-babel-variable-assignments:gnuplot (params) + "Return list of gnuplot statements assigning the block's variables." + (mapcar + (lambda (pair) (format "%s = \"%s\"" (car pair) (cdr pair))) + (org-babel-gnuplot-process-vars params))) + +(defvar gnuplot-buffer) +(defun org-babel-gnuplot-initiate-session (&optional session _params) + "Initiate a gnuplot session. +If there is not a current inferior-process-buffer in SESSION +then create one. Return the initialized session. The current +`gnuplot-mode' doesn't provide support for multiple sessions." + (require 'gnuplot) + (unless (string= session "none") + (save-window-excursion + (gnuplot-send-string-to-gnuplot "" "line") + gnuplot-buffer))) + +(defun org-babel-gnuplot-quote-timestamp-field (s) + "Convert S from timestamp to Unix time and export to gnuplot." + (format-time-string org-babel-gnuplot-timestamp-fmt + (org-time-string-to-time s))) + +(defvar org-table-number-regexp) +(defvar org-ts-regexp3) +(defun org-babel-gnuplot-quote-tsv-field (s) + "Quote S for export to gnuplot." + (unless (stringp s) + (setq s (format "%s" s))) + (if (string-match org-table-number-regexp s) s + (if (string-match org-ts-regexp3 s) + (org-babel-gnuplot-quote-timestamp-field s) + (if (zerop (length s)) + (or *org-babel-gnuplot-missing* s) + (if (string-match "[ \"]" s) + (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") + "\"") + s))))) + +(defun org-babel-gnuplot-table-to-data (table data-file params) + "Export TABLE to DATA-FILE in a format readable by gnuplot. +Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE." + (with-temp-file data-file + (insert (let ((org-babel-gnuplot-timestamp-fmt + (or (plist-get params :timefmt) "%Y-%m-%d-%H:%M:%S"))) + (orgtbl-to-generic + table + (org-combine-plists + '(:sep "\t" :fmt org-babel-gnuplot-quote-tsv-field) + params))))) + data-file) + +(provide 'ob-gnuplot) + + + +;;; ob-gnuplot.el ends here diff --git a/elpa/org-9.1.14/ob-groovy.el b/elpa/org-9.1.14/ob-groovy.el new file mode 100644 index 00000000..565b0975 --- /dev/null +++ b/elpa/org-9.1.14/ob-groovy.el @@ -0,0 +1,116 @@ +;;; ob-groovy.el --- Babel Functions for Groovy -*- lexical-binding: t; -*- + +;; Copyright (C) 2013-2018 Free Software Foundation, Inc. + +;; Author: Miro Bezjak +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: +;; Currently only supports the external execution. No session support yet. + +;;; Requirements: +;; - Groovy language :: http://groovy.codehaus.org +;; - Groovy major mode :: Can be installed from MELPA or +;; https://github.com/russel/Emacs-Groovy-Mode + +;;; Code: +(require 'ob) + +(defvar org-babel-tangle-lang-exts) ;; Autoloaded +(add-to-list 'org-babel-tangle-lang-exts '("groovy" . "groovy")) +(defvar org-babel-default-header-args:groovy '()) +(defcustom org-babel-groovy-command "groovy" + "Name of the command to use for executing Groovy code. +May be either a command in the path, like groovy +or an absolute path name, like /usr/local/bin/groovy +parameters may be used, like groovy -v" + :group 'org-babel + :version "24.3" + :type 'string) + +(defun org-babel-execute:groovy (body params) + "Execute a block of Groovy code with org-babel. This function is +called by `org-babel-execute-src-block'" + (message "executing Groovy source code block") + (let* ((processed-params (org-babel-process-params params)) + (session (org-babel-groovy-initiate-session (nth 0 processed-params))) + (result-params (nth 2 processed-params)) + (result-type (cdr (assq :result-type params))) + (full-body (org-babel-expand-body:generic + body params)) + (result (org-babel-groovy-evaluate + session full-body result-type result-params))) + + (org-babel-reassemble-table + result + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))) + +(defvar org-babel-groovy-wrapper-method + + "class Runner extends Script { + def out = new PrintWriter(new ByteArrayOutputStream()) + def run() { %s } +} + +println(new Runner().run()) +") + + +(defun org-babel-groovy-evaluate + (session body &optional result-type result-params) + "Evaluate BODY in external Groovy process. +If RESULT-TYPE equals `output' then return standard output as a string. +If RESULT-TYPE equals `value' then return the value of the last statement +in BODY as elisp." + (when session (error "Sessions are not (yet) supported for Groovy")) + (pcase result-type + (`output + (let ((src-file (org-babel-temp-file "groovy_"))) + (progn (with-temp-file src-file (insert body)) + (org-babel-eval + (concat org-babel-groovy-command " " src-file) "")))) + (`value + (let* ((src-file (org-babel-temp-file "groovy_")) + (wrapper (format org-babel-groovy-wrapper-method body))) + (with-temp-file src-file (insert wrapper)) + (let ((raw (org-babel-eval + (concat org-babel-groovy-command " " src-file) ""))) + (org-babel-result-cond result-params + raw + (org-babel-script-escape raw))))))) + + +(defun org-babel-prep-session:groovy (_session _params) + "Prepare SESSION according to the header arguments specified in PARAMS." + (error "Sessions are not (yet) supported for Groovy")) + +(defun org-babel-groovy-initiate-session (&optional _session) + "If there is not a current inferior-process-buffer in SESSION +then create. Return the initialized session. Sessions are not +supported in Groovy." + nil) + +(provide 'ob-groovy) + + + +;;; ob-groovy.el ends here diff --git a/elpa/org-9.1.14/ob-haskell.el b/elpa/org-9.1.14/ob-haskell.el new file mode 100644 index 00000000..e607ee0c --- /dev/null +++ b/elpa/org-9.1.14/ob-haskell.el @@ -0,0 +1,222 @@ +;;; ob-haskell.el --- Babel Functions for Haskell -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating haskell source code. This one will +;; be sort of tricky because haskell programs must be compiled before +;; they can be run, but haskell code can also be run through an +;; interactive interpreter. +;; +;; For now lets only allow evaluation using the haskell interpreter. + +;;; Requirements: + +;; - haskell-mode :: http://www.iro.umontreal.ca/~monnier/elisp/#haskell-mode +;; +;; - inf-haskell :: http://www.iro.umontreal.ca/~monnier/elisp/#haskell-mode +;; +;; - (optionally) lhs2tex :: http://people.cs.uu.nl/andres/lhs2tex/ + +;;; Code: +(require 'ob) +(require 'comint) + +(declare-function org-remove-indentation "org" (code &optional n)) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function haskell-mode "ext:haskell-mode" ()) +(declare-function run-haskell "ext:inf-haskell" (&optional arg)) +(declare-function inferior-haskell-load-file + "ext:inf-haskell" (&optional reload)) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("haskell" . "hs")) + +(defvar org-babel-default-header-args:haskell + '((:padlines . "no"))) + +(defvar org-babel-haskell-lhs2tex-command "lhs2tex") + +(defvar org-babel-haskell-eoe "\"org-babel-haskell-eoe\"") + +(defvar haskell-prompt-regexp) + +(defun org-babel-execute:haskell (body params) + "Execute a block of Haskell code." + (require 'inf-haskell) + (add-hook 'inferior-haskell-hook + (lambda () + (setq-local comint-prompt-regexp + (concat haskell-prompt-regexp "\\|^λ?> ")))) + (let* ((session (cdr (assq :session params))) + (result-type (cdr (assq :result-type params))) + (full-body (org-babel-expand-body:generic + body params + (org-babel-variable-assignments:haskell params))) + (session (org-babel-haskell-initiate-session session params)) + (comint-preoutput-filter-functions + (cons 'ansi-color-filter-apply comint-preoutput-filter-functions)) + (raw (org-babel-comint-with-output + (session org-babel-haskell-eoe t full-body) + (insert (org-trim full-body)) + (comint-send-input nil t) + (insert org-babel-haskell-eoe) + (comint-send-input nil t))) + (results (mapcar + #'org-babel-strip-quotes + (cdr (member org-babel-haskell-eoe + (reverse (mapcar #'org-trim raw))))))) + (org-babel-reassemble-table + (let ((result + (pcase result-type + (`output (mapconcat #'identity (reverse (cdr results)) "\n")) + (`value (car results))))) + (org-babel-result-cond (cdr (assq :result-params params)) + result (org-babel-script-escape result))) + (org-babel-pick-name (cdr (assq :colname-names params)) + (cdr (assq :colname-names params))) + (org-babel-pick-name (cdr (assq :rowname-names params)) + (cdr (assq :rowname-names params)))))) + +(defun org-babel-haskell-initiate-session (&optional _session _params) + "Initiate a haskell session. +If there is not a current inferior-process-buffer in SESSION +then create one. Return the initialized session." + (require 'inf-haskell) + (or (get-buffer "*haskell*") + (save-window-excursion (run-haskell) (sleep-for 0.25) (current-buffer)))) + +(defun org-babel-load-session:haskell (session body params) + "Load BODY into SESSION." + (save-window-excursion + (let* ((buffer (org-babel-prep-session:haskell session params)) + (load-file (concat (org-babel-temp-file "haskell-load-") ".hs"))) + (with-temp-buffer + (insert body) (write-file load-file) + (haskell-mode) (inferior-haskell-load-file)) + buffer))) + +(defun org-babel-prep-session:haskell (session params) + "Prepare SESSION according to the header arguments in PARAMS." + (save-window-excursion + (let ((buffer (org-babel-haskell-initiate-session session))) + (org-babel-comint-in-buffer buffer + (mapc (lambda (line) + (insert line) + (comint-send-input nil t)) + (org-babel-variable-assignments:haskell params))) + (current-buffer)))) + +(defun org-babel-variable-assignments:haskell (params) + "Return list of haskell statements assigning the block's variables." + (mapcar (lambda (pair) + (format "let %s = %s" + (car pair) + (org-babel-haskell-var-to-haskell (cdr pair)))) + (org-babel--get-vars params))) + +(defun org-babel-haskell-var-to-haskell (var) + "Convert an elisp value VAR into a haskell variable. +The elisp VAR is converted to a string of haskell source code +specifying a variable of the same value." + (if (listp var) + (concat "[" (mapconcat #'org-babel-haskell-var-to-haskell var ", ") "]") + (format "%S" var))) + +(defvar org-export-copy-to-kill-ring) +(declare-function org-export-to-file "ox" + (backend file + &optional async subtreep visible-only body-only + ext-plist post-process)) +(defun org-babel-haskell-export-to-lhs (&optional arg) + "Export to a .lhs file with all haskell code blocks escaped. +When called with a prefix argument the resulting +.lhs file will be exported to a .tex file. This function will +create two new files, base-name.lhs and base-name.tex where +base-name is the name of the current Org file. + +Note that all standard Babel literate programming +constructs (header arguments, no-web syntax etc...) are ignored." + (interactive "P") + (let* ((contents (buffer-string)) + (haskell-regexp + (concat "^\\([ \t]*\\)#\\+begin_src[ \t]haskell*\\(.*\\)?[\r\n]" + "\\([^\000]*?\\)[\r\n][ \t]*#\\+end_src.*")) + (base-name (file-name-sans-extension (buffer-file-name))) + (tmp-file (org-babel-temp-file "haskell-")) + (tmp-org-file (concat tmp-file ".org")) + (tmp-tex-file (concat tmp-file ".tex")) + (lhs-file (concat base-name ".lhs")) + (tex-file (concat base-name ".tex")) + (command (concat org-babel-haskell-lhs2tex-command + " " (org-babel-process-file-name lhs-file) + " > " (org-babel-process-file-name tex-file))) + (preserve-indentp org-src-preserve-indentation) + indentation) + ;; escape haskell source-code blocks + (with-temp-file tmp-org-file + (insert contents) + (goto-char (point-min)) + (while (re-search-forward haskell-regexp nil t) + (save-match-data (setq indentation (length (match-string 1)))) + (replace-match (save-match-data + (concat + "#+begin_export latex\n\\begin{code}\n" + (if (or preserve-indentp + (string-match "-i" (match-string 2))) + (match-string 3) + (org-remove-indentation (match-string 3))) + "\n\\end{code}\n#+end_export\n")) + t t) + (indent-code-rigidly (match-beginning 0) (match-end 0) indentation))) + (save-excursion + ;; export to latex w/org and save as .lhs + (require 'ox-latex) + (find-file tmp-org-file) + ;; Ensure we do not clutter kill ring with incomplete results. + (let (org-export-copy-to-kill-ring) + (org-export-to-file 'latex tmp-tex-file)) + (kill-buffer nil) + (delete-file tmp-org-file) + (find-file tmp-tex-file) + (goto-char (point-min)) (forward-line 2) + (insert "%include polycode.fmt\n") + ;; ensure all \begin/end{code} statements start at the first column + (while (re-search-forward "^[ \t]+\\\\begin{code}[^\000]+\\\\end{code}" nil t) + (replace-match (save-match-data (org-remove-indentation (match-string 0))) + t t)) + (setq contents (buffer-string)) + (save-buffer) (kill-buffer nil)) + (delete-file tmp-tex-file) + ;; save org exported latex to a .lhs file + (with-temp-file lhs-file (insert contents)) + (if (not arg) + (find-file lhs-file) + ;; process .lhs file with lhs2tex + (message "running %s" command) (shell-command command) (find-file tex-file)))) + +(provide 'ob-haskell) + + + +;;; ob-haskell.el ends here diff --git a/elpa/org-9.1.14/ob-hledger.el b/elpa/org-9.1.14/ob-hledger.el new file mode 100644 index 00000000..727fb1f1 --- /dev/null +++ b/elpa/org-9.1.14/ob-hledger.el @@ -0,0 +1,70 @@ +;; ob-hledger.el --- Babel Functions for hledger -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Simon Michael +;; Keywords: literate programming, reproducible research, plain text accounting +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Babel support for evaluating hledger entries. +;; +;; Based on ob-ledger.el. +;; If the source block is empty, hledger will use a default journal file, +;; probably ~/.hledger.journal (it may not notice your $LEDGER_FILE env var). +;; So make ~/.hledger.journal a symbolic link to the real file if necessary. + +;;; Code: +(require 'ob) + +(defvar org-babel-default-header-args:hledger + '((:results . "output") (:exports . "results") (:cmdline . "bal")) + "Default arguments to use when evaluating a hledger source block.") + +(defun org-babel-execute:hledger (body params) + "Execute a block of hledger entries with org-babel. +This function is called by `org-babel-execute-src-block'." + (message "executing hledger source code block") + (letrec ( ;(result-params (split-string (or (cdr (assq :results params)) ""))) + (cmdline (cdr (assq :cmdline params))) + (in-file (org-babel-temp-file "hledger-")) + (out-file (org-babel-temp-file "hledger-output-")) + (hledgercmd (concat "hledger" + (if (> (length body) 0) + (concat " -f " (org-babel-process-file-name in-file)) + "") + " " cmdline))) + (with-temp-file in-file (insert body)) +;; TODO This is calling for some refactoring: +;; (concat "hledger" (if ...) " " cmdline) +;; could be built only once and bound to a symbol. + (message "%s" hledgercmd) + (with-output-to-string + (shell-command (concat hledgercmd " > " (org-babel-process-file-name out-file)))) + (with-temp-buffer (insert-file-contents out-file) (buffer-string)))) + +(defun org-babel-prep-session:hledger (_session _params) + (error "hledger does not support sessions")) + +(provide 'ob-hledger) + + + +;;; ob-hledger.el ends here +;; TODO Unit tests are more than welcome, too. diff --git a/elpa/org-9.1.14/ob-io.el b/elpa/org-9.1.14/ob-io.el new file mode 100644 index 00000000..4f407cc5 --- /dev/null +++ b/elpa/org-9.1.14/ob-io.el @@ -0,0 +1,108 @@ +;;; ob-io.el --- Babel Functions for Io -*- lexical-binding: t; -*- + +;; Copyright (C) 2012-2018 Free Software Foundation, Inc. + +;; Author: Andrzej Lichnerowicz +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: +;; Currently only supports the external execution. No session support yet. +;; :results output -- runs in scripting mode +;; :results output repl -- runs in repl mode + +;;; Requirements: +;; - Io language :: http://iolanguage.org/ +;; - Io major mode :: Can be installed from Io sources +;; https://github.com/stevedekorte/io/blob/master/extras/SyntaxHighlighters/Emacs/io-mode.el + +;;; Code: +(require 'ob) + +(defvar org-babel-tangle-lang-exts) ;; Autoloaded +(add-to-list 'org-babel-tangle-lang-exts '("io" . "io")) +(defvar org-babel-default-header-args:io '()) +(defvar org-babel-io-command "io" + "Name of the command to use for executing Io code.") + +(defun org-babel-execute:io (body params) + "Execute a block of Io code with org-babel. This function is +called by `org-babel-execute-src-block'" + (message "executing Io source code block") + (let* ((processed-params (org-babel-process-params params)) + (session (org-babel-io-initiate-session (nth 0 processed-params))) + (result-params (nth 2 processed-params)) + (result-type (cdr (assq :result-type params))) + (full-body (org-babel-expand-body:generic + body params)) + (result (org-babel-io-evaluate + session full-body result-type result-params))) + + (org-babel-reassemble-table + result + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))) + +(defvar org-babel-io-wrapper-method + "( +%s +) asString print +") + + +(defun org-babel-io-evaluate (session body &optional result-type result-params) + "Evaluate BODY in external Io process. +If RESULT-TYPE equals `output' then return standard output as a string. +If RESULT-TYPE equals `value' then return the value of the last statement +in BODY as elisp." + (when session (error "Sessions are not (yet) supported for Io")) + (pcase result-type + (`output + (if (member "repl" result-params) + (org-babel-eval org-babel-io-command body) + (let ((src-file (org-babel-temp-file "io-"))) + (progn (with-temp-file src-file (insert body)) + (org-babel-eval + (concat org-babel-io-command " " src-file) ""))))) + (`value (let* ((src-file (org-babel-temp-file "io-")) + (wrapper (format org-babel-io-wrapper-method body))) + (with-temp-file src-file (insert wrapper)) + (let ((raw (org-babel-eval + (concat org-babel-io-command " " src-file) ""))) + (org-babel-result-cond result-params + raw + (org-babel-script-escape raw))))))) + + +(defun org-babel-prep-session:io (_session _params) + "Prepare SESSION according to the header arguments specified in PARAMS." + (error "Sessions are not (yet) supported for Io")) + +(defun org-babel-io-initiate-session (&optional _session) + "If there is not a current inferior-process-buffer in SESSION +then create. Return the initialized session. Sessions are not +supported in Io." + nil) + +(provide 'ob-io) + + + +;;; ob-io.el ends here diff --git a/elpa/org-9.1.14/ob-java.el b/elpa/org-9.1.14/ob-java.el new file mode 100644 index 00000000..d6301bff --- /dev/null +++ b/elpa/org-9.1.14/ob-java.el @@ -0,0 +1,85 @@ +;;; ob-java.el --- Babel Functions for Java -*- lexical-binding: t; -*- + +;; Copyright (C) 2011-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Currently this only supports the external compilation and execution +;; of java code blocks (i.e., no session support). + +;;; Code: +(require 'ob) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("java" . "java")) + +(defcustom org-babel-java-command "java" + "Name of the java command. +May be either a command in the path, like java +or an absolute path name, like /usr/local/bin/java +parameters may be used, like java -verbose" + :group 'org-babel + :version "24.3" + :type 'string) + +(defcustom org-babel-java-compiler "javac" + "Name of the java compiler. +May be either a command in the path, like javac +or an absolute path name, like /usr/local/bin/javac +parameters may be used, like javac -verbose" + :group 'org-babel + :version "24.3" + :type 'string) + +(defun org-babel-execute:java (body params) + (let* ((classname (or (cdr (assq :classname params)) + (error + "Can't compile a java block without a classname"))) + (packagename (file-name-directory classname)) + (src-file (concat classname ".java")) + (cmpflag (or (cdr (assq :cmpflag params)) "")) + (cmdline (or (cdr (assq :cmdline params)) "")) + (full-body (org-babel-expand-body:generic body params))) + (with-temp-file src-file (insert full-body)) + (org-babel-eval + (concat org-babel-java-compiler " " cmpflag " " src-file) "") + ;; created package-name directories if missing + (unless (or (not packagename) (file-exists-p packagename)) + (make-directory packagename 'parents)) + (let ((results (org-babel-eval (concat org-babel-java-command + " " cmdline " " classname) ""))) + (org-babel-reassemble-table + (org-babel-result-cond (cdr (assq :result-params params)) + (org-babel-read results) + (let ((tmp-file (org-babel-temp-file "c-"))) + (with-temp-file tmp-file (insert results)) + (org-babel-import-elisp-from-file tmp-file))) + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))) + +(provide 'ob-java) + + + +;;; ob-java.el ends here diff --git a/elpa/org-9.1.14/ob-js.el b/elpa/org-9.1.14/ob-js.el new file mode 100644 index 00000000..38c8c39a --- /dev/null +++ b/elpa/org-9.1.14/ob-js.el @@ -0,0 +1,164 @@ +;;; ob-js.el --- Babel Functions for Javascript -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research, js +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Now working with SBCL for both session and external evaluation. +;; +;; This certainly isn't optimally robust, but it seems to be working +;; for the basic use cases. + +;;; Requirements: + +;; - a non-browser javascript engine such as node.js http://nodejs.org/ +;; or mozrepl http://wiki.github.com/bard/mozrepl/ +;; +;; - for session based evaluation mozrepl and moz.el are required see +;; http://wiki.github.com/bard/mozrepl/emacs-integration for +;; configuration instructions + +;;; Code: +(require 'ob) + +(declare-function run-mozilla "ext:moz" (arg)) + +(defvar org-babel-default-header-args:js '() + "Default header arguments for js code blocks.") + +(defvar org-babel-js-eoe "org-babel-js-eoe" + "String to indicate that evaluation has completed.") + +(defcustom org-babel-js-cmd "node" + "Name of command used to evaluate js blocks." + :group 'org-babel + :version "24.1" + :type 'string) + +(defvar org-babel-js-function-wrapper + "require('sys').print(require('sys').inspect(function(){\n%s\n}()));" + "Javascript code to print value of body.") + +(defun org-babel-execute:js (body params) + "Execute a block of Javascript code with org-babel. +This function is called by `org-babel-execute-src-block'" + (let* ((org-babel-js-cmd (or (cdr (assq :cmd params)) org-babel-js-cmd)) + (result-type (cdr (assq :result-type params))) + (full-body (org-babel-expand-body:generic + body params (org-babel-variable-assignments:js params))) + (result (if (not (string= (cdr (assq :session params)) "none")) + ;; session evaluation + (let ((session (org-babel-prep-session:js + (cdr (assq :session params)) params))) + (nth 1 + (org-babel-comint-with-output + (session (format "%S" org-babel-js-eoe) t body) + (mapc + (lambda (line) + (insert (org-babel-chomp line)) + (comint-send-input nil t)) + (list body (format "%S" org-babel-js-eoe)))))) + ;; external evaluation + (let ((script-file (org-babel-temp-file "js-script-"))) + (with-temp-file script-file + (insert + ;; return the value or the output + (if (string= result-type "value") + (format org-babel-js-function-wrapper full-body) + full-body))) + (org-babel-eval + (format "%s %s" org-babel-js-cmd + (org-babel-process-file-name script-file)) ""))))) + (org-babel-result-cond (cdr (assq :result-params params)) + result (org-babel-js-read result)))) + +(defun org-babel-js-read (results) + "Convert RESULTS into an appropriate elisp value. +If RESULTS look like a table, then convert them into an +Emacs-lisp table, otherwise return the results as a string." + (org-babel-read + (if (and (stringp results) + (string-prefix-p "[" results) + (string-suffix-p "]" results)) + (org-babel-read + (concat "'" + (replace-regexp-in-string + "\\[" "(" (replace-regexp-in-string + "\\]" ")" (replace-regexp-in-string + ",[[:space:]]" " " + (replace-regexp-in-string + "'" "\"" results)))))) + results))) + +(defun org-babel-js-var-to-js (var) + "Convert VAR into a js variable. +Convert an elisp value into a string of js source code +specifying a variable of the same value." + (if (listp var) + (concat "[" (mapconcat #'org-babel-js-var-to-js var ", ") "]") + (replace-regexp-in-string "\n" "\\\\n" (format "%S" var)))) + +(defun org-babel-prep-session:js (session params) + "Prepare SESSION according to the header arguments specified in PARAMS." + (let* ((session (org-babel-js-initiate-session session)) + (var-lines (org-babel-variable-assignments:js params))) + (when session + (org-babel-comint-in-buffer session + (sit-for .5) (goto-char (point-max)) + (mapc (lambda (var) + (insert var) (comint-send-input nil t) + (org-babel-comint-wait-for-output session) + (sit-for .1) (goto-char (point-max))) var-lines))) + session)) + +(defun org-babel-variable-assignments:js (params) + "Return list of Javascript statements assigning the block's variables." + (mapcar + (lambda (pair) (format "var %s=%s;" + (car pair) (org-babel-js-var-to-js (cdr pair)))) + (org-babel--get-vars params))) + +(defun org-babel-js-initiate-session (&optional session) + "If there is not a current inferior-process-buffer in SESSION +then create. Return the initialized session." + (unless (string= session "none") + (cond + ((string= "mozrepl" org-babel-js-cmd) + (require 'moz) + (let ((session-buffer (save-window-excursion + (run-mozilla nil) + (rename-buffer session) + (current-buffer)))) + (if (org-babel-comint-buffer-livep session-buffer) + (progn (sit-for .25) session-buffer) + (sit-for .5) + (org-babel-js-initiate-session session)))) + ((string= "node" org-babel-js-cmd ) + (error "Session evaluation with node.js is not supported")) + (t + (error "Sessions are only supported with mozrepl add \":cmd mozrepl\""))))) + +(provide 'ob-js) + + + +;;; ob-js.el ends here diff --git a/elpa/org-9.1.14/ob-keys.el b/elpa/org-9.1.14/ob-keys.el new file mode 100644 index 00000000..fc96df47 --- /dev/null +++ b/elpa/org-9.1.14/ob-keys.el @@ -0,0 +1,106 @@ +;;; ob-keys.el --- Key Bindings for Babel -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Add Org Babel keybindings to the Org mode keymap for exposing +;; Org Babel functions. These will all share a common prefix. See +;; the value of `org-babel-key-bindings' for a list of interactive +;; functions and their associated keys. + +;;; Code: +(require 'ob-core) + +(defvar org-babel-key-prefix "\C-c\C-v" + "The key prefix for Babel interactive key-bindings. +See `org-babel-key-bindings' for the list of interactive babel +functions which are assigned key bindings, and see +`org-babel-map' for the actual babel keymap.") + +(defvar org-babel-map (make-sparse-keymap) + "The keymap for interactive Babel functions.") + +;;;###autoload +(defun org-babel-describe-bindings () + "Describe all keybindings behind `org-babel-key-prefix'." + (interactive) + (describe-bindings org-babel-key-prefix)) + +(defvar org-babel-key-bindings + '(("p" . org-babel-previous-src-block) + ("\C-p" . org-babel-previous-src-block) + ("n" . org-babel-next-src-block) + ("\C-n" . org-babel-next-src-block) + ("e" . org-babel-execute-maybe) + ("\C-e" . org-babel-execute-maybe) + ("o" . org-babel-open-src-block-result) + ("\C-o" . org-babel-open-src-block-result) + ("\C-v" . org-babel-expand-src-block) + ("v" . org-babel-expand-src-block) + ("u" . org-babel-goto-src-block-head) + ("\C-u" . org-babel-goto-src-block-head) + ("g" . org-babel-goto-named-src-block) + ("r" . org-babel-goto-named-result) + ("\C-r" . org-babel-goto-named-result) + ("\C-b" . org-babel-execute-buffer) + ("b" . org-babel-execute-buffer) + ("\C-s" . org-babel-execute-subtree) + ("s" . org-babel-execute-subtree) + ("\C-d" . org-babel-demarcate-block) + ("d" . org-babel-demarcate-block) + ("\C-t" . org-babel-tangle) + ("t" . org-babel-tangle) + ("\C-f" . org-babel-tangle-file) + ("f" . org-babel-tangle-file) + ("\C-c" . org-babel-check-src-block) + ("c" . org-babel-check-src-block) + ("\C-j" . org-babel-insert-header-arg) + ("j" . org-babel-insert-header-arg) + ("\C-l" . org-babel-load-in-session) + ("l" . org-babel-load-in-session) + ("\C-i" . org-babel-lob-ingest) + ("i" . org-babel-lob-ingest) + ("\C-I" . org-babel-view-src-block-info) + ("I" . org-babel-view-src-block-info) + ("\C-z" . org-babel-switch-to-session) + ("z" . org-babel-switch-to-session-with-code) + ("\C-a" . org-babel-sha1-hash) + ("a" . org-babel-sha1-hash) + ("h" . org-babel-describe-bindings) + ("\C-x" . org-babel-do-key-sequence-in-edit-buffer) + ("x" . org-babel-do-key-sequence-in-edit-buffer) + ("k" . org-babel-remove-result-one-or-many) + ("\C-\M-h" . org-babel-mark-block)) + "Alist of key bindings and interactive Babel functions. +This list associates interactive Babel functions +with keys. Each element of this list will add an entry to the +`org-babel-map' using the letter key which is the `car' of the +a-list placed behind the generic `org-babel-key-prefix'.") + +(provide 'ob-keys) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; ob-keys.el ends here diff --git a/elpa/org-9.1.14/ob-latex.el b/elpa/org-9.1.14/ob-latex.el new file mode 100644 index 00000000..6a963e52 --- /dev/null +++ b/elpa/org-9.1.14/ob-latex.el @@ -0,0 +1,226 @@ +;;; ob-latex.el --- Babel Functions for LaTeX -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating LaTeX source code. +;; +;; Currently on evaluation this returns raw LaTeX code, unless a :file +;; header argument is given in which case small png or pdf files will +;; be created directly form the latex source code. + +;;; Code: +(require 'ob) + +(declare-function org-create-formula-image "org" (string tofile options buffer &optional type)) +(declare-function org-latex-compile "ox-latex" (texfile &optional snippet)) +(declare-function org-latex-guess-inputenc "ox-latex" (header)) +(declare-function org-splice-latex-header "org" (tpl def-pkg pkg snippets-p &optional extra)) +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("latex" . "tex")) + +(defvar org-format-latex-header) ; From org.el +(defvar org-format-latex-options) ; From org.el +(defvar org-latex-default-packages-alist) ; From org.el +(defvar org-latex-packages-alist) ; From org.el + +(defvar org-babel-default-header-args:latex + '((:results . "latex") (:exports . "results")) + "Default arguments to use when evaluating a LaTeX source block.") + +(defconst org-babel-header-args:latex + '((border . :any) + (fit . :any) + (imagemagick . ((nil t))) + (iminoptions . :any) + (imoutoptions . :any) + (packages . :any) + (pdfheight . :any) + (pdfpng . :any) + (pdfwidth . :any) + (headers . :any) + (packages . :any) + (buffer . ((yes no)))) + "LaTeX-specific header arguments.") + +(defcustom org-babel-latex-htlatex "htlatex" + "The htlatex command to enable conversion of latex to SVG or HTML." + :group 'org-babel + :type 'string) + +(defcustom org-babel-latex-htlatex-packages + '("[usenames]{color}" "{tikz}" "{color}" "{listings}" "{amsmath}") + "Packages to use for htlatex export." + :group 'org-babel + :type '(repeat (string))) + +(defun org-babel-expand-body:latex (body params) + "Expand BODY according to PARAMS, return the expanded body." + (mapc (lambda (pair) ;; replace variables + (setq body + (replace-regexp-in-string + (regexp-quote (format "%S" (car pair))) + (if (stringp (cdr pair)) + (cdr pair) (format "%S" (cdr pair))) + body))) (org-babel--get-vars params)) + (org-trim body)) + +(defun org-babel-execute:latex (body params) + "Execute a block of Latex code with Babel. +This function is called by `org-babel-execute-src-block'." + (setq body (org-babel-expand-body:latex body params)) + (if (cdr (assq :file params)) + (let* ((out-file (cdr (assq :file params))) + (extension (file-name-extension out-file)) + (tex-file (org-babel-temp-file "latex-" ".tex")) + (border (cdr (assq :border params))) + (imagemagick (cdr (assq :imagemagick params))) + (im-in-options (cdr (assq :iminoptions params))) + (im-out-options (cdr (assq :imoutoptions params))) + (fit (or (cdr (assq :fit params)) border)) + (height (and fit (cdr (assq :pdfheight params)))) + (width (and fit (cdr (assq :pdfwidth params)))) + (headers (cdr (assq :headers params))) + (in-buffer (not (string= "no" (cdr (assq :buffer params))))) + (org-latex-packages-alist + (append (cdr (assq :packages params)) org-latex-packages-alist))) + (cond + ((and (string-suffix-p ".png" out-file) (not imagemagick)) + (org-create-formula-image + body out-file org-format-latex-options in-buffer)) + ((string-suffix-p ".tikz" out-file) + (when (file-exists-p out-file) (delete-file out-file)) + (with-temp-file out-file + (insert body))) + ((and (or (string= "svg" extension) + (string= "html" extension)) + (executable-find org-babel-latex-htlatex)) + ;; TODO: this is a very different way of generating the + ;; frame latex document than in the pdf case. Ideally, both + ;; would be unified. This would prevent bugs creeping in + ;; such as the one fixed on Aug 16 2014 whereby :headers was + ;; not included in the SVG/HTML case. + (with-temp-file tex-file + (insert (concat + "\\documentclass[preview]{standalone} +\\def\\pgfsysdriver{pgfsys-tex4ht.def} +" + (mapconcat (lambda (pkg) + (concat "\\usepackage" pkg)) + org-babel-latex-htlatex-packages + "\n") + (if headers + (concat "\n" + (if (listp headers) + (mapconcat #'identity headers "\n") + headers) "\n") + "") + "\\begin{document}" + body + "\\end{document}"))) + (when (file-exists-p out-file) (delete-file out-file)) + (let ((default-directory (file-name-directory tex-file))) + (shell-command (format "%s %s" org-babel-latex-htlatex tex-file))) + (cond + ((file-exists-p (concat (file-name-sans-extension tex-file) "-1.svg")) + (if (string-suffix-p ".svg" out-file) + (progn + (shell-command "pwd") + (shell-command (format "mv %s %s" + (concat (file-name-sans-extension tex-file) "-1.svg") + out-file))) + (error "SVG file produced but HTML file requested"))) + ((file-exists-p (concat (file-name-sans-extension tex-file) ".html")) + (if (string-suffix-p ".html" out-file) + (shell-command "mv %s %s" + (concat (file-name-sans-extension tex-file) + ".html") + out-file) + (error "HTML file produced but SVG file requested"))))) + ((or (string= "pdf" extension) imagemagick) + (with-temp-file tex-file + (require 'ox-latex) + (insert + (org-latex-guess-inputenc + (org-splice-latex-header + org-format-latex-header + (delq + nil + (mapcar + (lambda (el) + (unless (and (listp el) (string= "hyperref" (cadr el))) + el)) + org-latex-default-packages-alist)) + org-latex-packages-alist + nil)) + (if fit "\n\\usepackage[active, tightpage]{preview}\n" "") + (if border (format "\\setlength{\\PreviewBorder}{%s}" border) "") + (if height (concat "\n" (format "\\pdfpageheight %s" height)) "") + (if width (concat "\n" (format "\\pdfpagewidth %s" width)) "") + (if headers + (concat "\n" + (if (listp headers) + (mapconcat #'identity headers "\n") + headers) "\n") + "") + (if fit + (concat "\n\\begin{document}\n\\begin{preview}\n" body + "\n\\end{preview}\n\\end{document}\n") + (concat "\n\\begin{document}\n" body "\n\\end{document}\n")))) + (when (file-exists-p out-file) (delete-file out-file)) + (let ((transient-pdf-file (org-babel-latex-tex-to-pdf tex-file))) + (cond + ((string= "pdf" extension) + (rename-file transient-pdf-file out-file)) + (imagemagick + (org-babel-latex-convert-pdf + transient-pdf-file out-file im-in-options im-out-options) + (when (file-exists-p transient-pdf-file) + (delete-file transient-pdf-file))) + (t + (error "Can not create %s files, please specify a .png or .pdf file or try the :imagemagick header argument" + extension)))))) + nil) ;; signal that output has already been written to file + body)) + +(defun org-babel-latex-convert-pdf (pdffile out-file im-in-options im-out-options) + "Generate a file from a pdf file using imagemagick." + (let ((cmd (concat "convert " im-in-options " " pdffile " " + im-out-options " " out-file))) + (message "Converting pdffile file %s..." cmd) + (shell-command cmd))) + +(defun org-babel-latex-tex-to-pdf (file) + "Generate a pdf file according to the contents FILE." + (require 'ox-latex) + (org-latex-compile file)) + +(defun org-babel-prep-session:latex (_session _params) + "Return an error because LaTeX doesn't support sessions." + (error "LaTeX does not support sessions")) + + +(provide 'ob-latex) +;;; ob-latex.el ends here diff --git a/elpa/org-9.1.14/ob-ledger.el b/elpa/org-9.1.14/ob-ledger.el new file mode 100644 index 00000000..2a133144 --- /dev/null +++ b/elpa/org-9.1.14/ob-ledger.el @@ -0,0 +1,70 @@ +;;; ob-ledger.el --- Babel Functions for Ledger -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Eric S Fraga +;; Keywords: literate programming, reproducible research, accounting +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating ledger entries. +;; +;; This differs from most standard languages in that +;; +;; 1) there is no such thing as a "session" in ledger +;; +;; 2) we are generally only going to return output from the ledger program +;; +;; 3) we are adding the "cmdline" header argument +;; +;; 4) there are no variables + +;;; Code: +(require 'ob) + +(defvar org-babel-default-header-args:ledger + '((:results . "output") (:cmdline . "bal")) + "Default arguments to use when evaluating a ledger source block.") + +(defun org-babel-execute:ledger (body params) + "Execute a block of Ledger entries with org-babel. This function is +called by `org-babel-execute-src-block'." + (message "executing Ledger source code block") + (let ((cmdline (cdr (assq :cmdline params))) + (in-file (org-babel-temp-file "ledger-")) + (out-file (org-babel-temp-file "ledger-output-"))) + (with-temp-file in-file (insert body)) + (message "%s" (concat "ledger" + " -f " (org-babel-process-file-name in-file) + " " cmdline)) + (with-output-to-string + (shell-command (concat "ledger" + " -f " (org-babel-process-file-name in-file) + " " cmdline + " > " (org-babel-process-file-name out-file)))) + (with-temp-buffer (insert-file-contents out-file) (buffer-string)))) + +(defun org-babel-prep-session:ledger (_session _params) + (error "Ledger does not support sessions")) + +(provide 'ob-ledger) + + + +;;; ob-ledger.el ends here diff --git a/elpa/org-9.1.14/ob-lilypond.el b/elpa/org-9.1.14/ob-lilypond.el new file mode 100644 index 00000000..3d3cc07f --- /dev/null +++ b/elpa/org-9.1.14/ob-lilypond.el @@ -0,0 +1,412 @@ +;;; ob-lilypond.el --- Babel Functions for Lilypond -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Martyn Jago +;; Keywords: babel language, literate programming +;; Homepage: https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-lilypond.html + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Installation, ob-lilypond documentation, and examples are available at +;; https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-lilypond.html +;; +;; Lilypond documentation can be found at +;; http://lilypond.org/manuals.html +;; +;; This depends on epstopdf --- See http://www.ctan.org/pkg/epstopdf. + +;;; Code: +(require 'ob) +(require 'outline) +(defalias 'lilypond-mode 'LilyPond-mode) + +(add-to-list 'org-babel-tangle-lang-exts '("LilyPond" . "ly")) + +(defvar org-babel-default-header-args:lilypond '() + "Default header arguments for lilypond code blocks. +NOTE: The arguments are determined at lilypond compile time. +See (org-babel-lilypond-set-header-args)") + +(defvar org-babel-lilypond-compile-post-tangle t + "Following the org-babel-tangle (C-c C-v t) command, +org-babel-lilypond-compile-post-tangle determines whether ob-lilypond should +automatically attempt to compile the resultant tangled file. +If the value is nil, no automated compilation takes place. +Default value is t") + +(defvar org-babel-lilypond-display-pdf-post-tangle t + "Following a successful LilyPond compilation +org-babel-lilypond-display-pdf-post-tangle determines whether to automate the +drawing / redrawing of the resultant pdf. If the value is nil, +the pdf is not automatically redrawn. Default value is t") + +(defvar org-babel-lilypond-play-midi-post-tangle t + "Following a successful LilyPond compilation +org-babel-lilypond-play-midi-post-tangle determines whether to automate the +playing of the resultant midi file. If the value is nil, +the midi file is not automatically played. Default value is t") + +(defvar org-babel-lilypond-ly-command "" + "Command to execute lilypond on your system. +Do not set it directly. Customize `org-babel-lilypond-commands' instead.") +(defvar org-babel-lilypond-pdf-command "" + "Command to show a PDF file on your system. +Do not set it directly. Customize `org-babel-lilypond-commands' instead.") +(defvar org-babel-lilypond-midi-command "" + "Command to play a MIDI file on your system. +Do not set it directly. Customize `org-babel-lilypond-commands' instead.") +(defcustom org-babel-lilypond-commands + (cond + ((eq system-type 'darwin) + '("/Applications/lilypond.app/Contents/Resources/bin/lilypond" "open" "open")) + ((eq system-type 'windows-nt) + '("lilypond" "" "")) + (t + '("lilypond" "xdg-open" "xdg-open"))) + "Commands to run lilypond and view or play the results. +These should be executables that take a filename as an argument. +On some system it is possible to specify the filename directly +and the viewer or player will be determined from the file type; +you can leave the string empty on this case." + :group 'org-babel + :type '(list + (string :tag "Lilypond ") + (string :tag "PDF Viewer ") + (string :tag "MIDI Player")) + :version "24.4" + :package-version '(Org . "8.2.7") + :set + (lambda (_symbol value) + (setq + org-babel-lilypond-ly-command (nth 0 value) + org-babel-lilypond-pdf-command (nth 1 value) + org-babel-lilypond-midi-command (nth 2 value)))) + +(defvar org-babel-lilypond-gen-png nil + "Non-nil means image generation (PNG) is turned on by default.") + +(defvar org-babel-lilypond-gen-svg nil + "Non-nil means image generation (SVG) is be turned on by default.") + +(defvar org-babel-lilypond-gen-html nil + "Non-nil means HTML generation is turned on by default.") + +(defvar org-babel-lilypond-gen-pdf nil + "Non-nil means PDF generation is be turned on by default.") + +(defvar org-babel-lilypond-use-eps nil + "Non-nil forces the compiler to use the EPS backend.") + +(defvar org-babel-lilypond-arrange-mode nil + "Non-nil turns Arrange mode on. +In Arrange mode the following settings are altered from default: +:tangle yes, :noweb yes +:results silent :comments yes. +In addition lilypond block execution causes tangling of all lilypond +blocks.") + +(defun org-babel-expand-body:lilypond (body params) + "Expand BODY according to PARAMS, return the expanded body." + (let ((vars (org-babel--get-vars params))) + (mapc + (lambda (pair) + (let ((name (symbol-name (car pair))) + (value (cdr pair))) + (setq body + (replace-regexp-in-string + (concat "$" (regexp-quote name)) + (if (stringp value) value (format "%S" value)) + body)))) + vars) + body)) + +(defun org-babel-execute:lilypond (body params) + "This function is called by `org-babel-execute-src-block'. +Depending on whether we are in arrange mode either: +1. Attempt to execute lilypond block according to header settings + (This is the default basic mode) +2. Tangle all lilypond blocks and process the result (arrange mode)" + (org-babel-lilypond-set-header-args org-babel-lilypond-arrange-mode) + (if org-babel-lilypond-arrange-mode + (org-babel-lilypond-tangle) + (org-babel-lilypond-process-basic body params))) + +(defun org-babel-lilypond-tangle () + "ob-lilypond specific tangle, attempts to invoke +=ly-execute-tangled-ly= if tangle is successful. Also passes +specific arguments to =org-babel-tangle=" + (interactive) + (if (org-babel-tangle nil "yes" "lilypond") + (org-babel-lilypond-execute-tangled-ly) nil)) + +(defun org-babel-lilypond-process-basic (body params) + "Execute a lilypond block in basic mode." + (let* ((out-file (cdr (assq :file params))) + (cmdline (or (cdr (assq :cmdline params)) + "")) + (in-file (org-babel-temp-file "lilypond-"))) + + (with-temp-file in-file + (insert (org-babel-expand-body:generic body params))) + (org-babel-eval + (concat + org-babel-lilypond-ly-command + " -dbackend=eps " + "-dno-gs-load-fonts " + "-dinclude-eps-fonts " + (or (cdr (assoc (file-name-extension out-file) + '(("pdf" . "--pdf ") + ("ps" . "--ps ") + ("png" . "--png ")))) + "--png ") + "--output=" + (file-name-sans-extension out-file) + " " + cmdline + in-file) "")) nil) + +(defun org-babel-prep-session:lilypond (_session _params) + "Return an error because LilyPond exporter does not support sessions." + (error "Sorry, LilyPond does not currently support sessions!")) + +(defun org-babel-lilypond-execute-tangled-ly () + "Compile result of block tangle with lilypond. +If error in compilation, attempt to mark the error in lilypond org file" + (when org-babel-lilypond-compile-post-tangle + (let ((org-babel-lilypond-tangled-file (org-babel-lilypond-switch-extension + (buffer-file-name) ".lilypond")) + (org-babel-lilypond-temp-file (org-babel-lilypond-switch-extension + (buffer-file-name) ".ly"))) + (if (not (file-exists-p org-babel-lilypond-tangled-file)) + (error "Error: Tangle Failed!") + (when (file-exists-p org-babel-lilypond-temp-file) + (delete-file org-babel-lilypond-temp-file)) + (rename-file org-babel-lilypond-tangled-file + org-babel-lilypond-temp-file)) + (switch-to-buffer-other-window "*lilypond*") + (erase-buffer) + (org-babel-lilypond-compile-lilyfile org-babel-lilypond-temp-file) + (goto-char (point-min)) + (if (org-babel-lilypond-check-for-compile-error org-babel-lilypond-temp-file) + (error "Error in Compilation!") + (other-window -1) + (org-babel-lilypond-attempt-to-open-pdf org-babel-lilypond-temp-file) + (org-babel-lilypond-attempt-to-play-midi org-babel-lilypond-temp-file))))) + +(defun org-babel-lilypond-compile-lilyfile (file-name &optional test) + "Compile lilypond file and check for compile errors +FILE-NAME is full path to lilypond (.ly) file" + (message "Compiling LilyPond...") + (let ((arg-1 org-babel-lilypond-ly-command) ;program + (arg-2 nil) ;infile + (arg-3 "*lilypond*") ;buffer + (arg-4 t) ;display + (arg-5 (if org-babel-lilypond-gen-png "--png" "")) ;&rest... + (arg-6 (if org-babel-lilypond-gen-html "--html" "")) + (arg-7 (if org-babel-lilypond-gen-pdf "--pdf" "")) + (arg-8 (if org-babel-lilypond-use-eps "-dbackend=eps" "")) + (arg-9 (if org-babel-lilypond-gen-svg "-dbackend=svg" "")) + (arg-10 (concat "--output=" (file-name-sans-extension file-name))) + (arg-11 file-name)) + (if test + `(,arg-1 ,arg-2 ,arg-3 ,arg-4 ,arg-5 ,arg-6 + ,arg-7 ,arg-8 ,arg-9 ,arg-10 ,arg-11) + (call-process + arg-1 arg-2 arg-3 arg-4 arg-5 arg-6 + arg-7 arg-8 arg-9 arg-10 arg-11)))) + +(defun org-babel-lilypond-check-for-compile-error (file-name &optional test) + "Check for compile error. +This is performed by parsing the *lilypond* buffer +containing the output message from the compilation. +FILE-NAME is full path to lilypond file. +If TEST is t just return nil if no error found, and pass +nil as file-name since it is unused in this context" + (let ((is-error (search-forward "error:" nil t))) + (if test + is-error + (when is-error + (org-babel-lilypond-process-compile-error file-name))))) + +(defun org-babel-lilypond-process-compile-error (file-name) + "Process the compilation error that has occurred. +FILE-NAME is full path to lilypond file" + (let ((line-num (org-babel-lilypond-parse-line-num))) + (let ((error-lines (org-babel-lilypond-parse-error-line file-name line-num))) + (org-babel-lilypond-mark-error-line file-name error-lines) + (error "Error: Compilation Failed!")))) + +(defun org-babel-lilypond-mark-error-line (file-name line) + "Mark the erroneous lines in the lilypond org buffer. +FILE-NAME is full path to lilypond file. +LINE is the erroneous line" + (switch-to-buffer-other-window + (concat (file-name-nondirectory + (org-babel-lilypond-switch-extension file-name ".org")))) + (let ((temp (point))) + (goto-char (point-min)) + (setq case-fold-search nil) + (if (search-forward line nil t) + (progn + (outline-show-all) + (set-mark (point)) + (goto-char (- (point) (length line)))) + (goto-char temp)))) + +(defun org-babel-lilypond-parse-line-num (&optional buffer) + "Extract error line number." + (when buffer (set-buffer buffer)) + (let ((start + (and (search-backward ":" nil t) + (search-backward ":" nil t) + (search-backward ":" nil t) + (search-backward ":" nil t)))) + (when start + (forward-char) + (let ((num (string-to-number + (buffer-substring + (+ 1 start) + (- (search-forward ":" nil t) 1))))) + (and (numberp num) num))))) + +(defun org-babel-lilypond-parse-error-line (file-name lineNo) + "Extract the erroneous line from the tangled .ly file +FILE-NAME is full path to lilypond file. +LINENO is the number of the erroneous line" + (with-temp-buffer + (insert-file-contents (org-babel-lilypond-switch-extension file-name ".ly") + nil nil nil t) + (if (> lineNo 0) + (progn + (goto-char (point-min)) + (forward-line (- lineNo 1)) + (buffer-substring (point) (point-at-eol))) + nil))) + +(defun org-babel-lilypond-attempt-to-open-pdf (file-name &optional test) + "Attempt to display the generated pdf file +FILE-NAME is full path to lilypond file +If TEST is non-nil, the shell command is returned and is not run" + (when org-babel-lilypond-display-pdf-post-tangle + (let ((pdf-file (org-babel-lilypond-switch-extension file-name ".pdf"))) + (if (file-exists-p pdf-file) + (let ((cmd-string + (concat org-babel-lilypond-pdf-command " " pdf-file))) + (if test + cmd-string + (start-process + "\"Audition pdf\"" + "*lilypond*" + org-babel-lilypond-pdf-command + pdf-file))) + (message "No pdf file generated so can't display!"))))) + +(defun org-babel-lilypond-attempt-to-play-midi (file-name &optional test) + "Attempt to play the generated MIDI file +FILE-NAME is full path to lilypond file +If TEST is non-nil, the shell command is returned and is not run" + (when org-babel-lilypond-play-midi-post-tangle + (let ((midi-file (org-babel-lilypond-switch-extension file-name ".midi"))) + (if (file-exists-p midi-file) + (let ((cmd-string + (concat org-babel-lilypond-midi-command " " midi-file))) + (if test + cmd-string + (start-process + "\"Audition midi\"" + "*lilypond*" + org-babel-lilypond-midi-command + midi-file))) + (message "No midi file generated so can't play!"))))) + +(defun org-babel-lilypond-toggle-midi-play () + "Toggle whether midi will be played following a successful compilation." + (interactive) + (setq org-babel-lilypond-play-midi-post-tangle + (not org-babel-lilypond-play-midi-post-tangle)) + (message (concat "Post-Tangle MIDI play has been " + (if org-babel-lilypond-play-midi-post-tangle + "ENABLED." "DISABLED.")))) + +(defun org-babel-lilypond-toggle-pdf-display () + "Toggle whether pdf will be displayed following a successful compilation." + (interactive) + (setq org-babel-lilypond-display-pdf-post-tangle + (not org-babel-lilypond-display-pdf-post-tangle)) + (message (concat "Post-Tangle PDF display has been " + (if org-babel-lilypond-display-pdf-post-tangle + "ENABLED." "DISABLED.")))) + +(defun org-babel-lilypond-toggle-png-generation () + "Toggle whether png image will be generated by compilation." + (interactive) + (setq org-babel-lilypond-gen-png (not org-babel-lilypond-gen-png)) + (message (concat "PNG image generation has been " + (if org-babel-lilypond-gen-png "ENABLED." "DISABLED.")))) + +(defun org-babel-lilypond-toggle-html-generation () + "Toggle whether html will be generated by compilation." + (interactive) + (setq org-babel-lilypond-gen-html (not org-babel-lilypond-gen-html)) + (message (concat "HTML generation has been " + (if org-babel-lilypond-gen-html "ENABLED." "DISABLED.")))) + +(defun org-babel-lilypond-toggle-pdf-generation () + "Toggle whether pdf will be generated by compilation." + (interactive) + (setq org-babel-lilypond-gen-pdf (not org-babel-lilypond-gen-pdf)) + (message (concat "PDF generation has been " + (if org-babel-lilypond-gen-pdf "ENABLED." "DISABLED.")))) + +(defun org-babel-lilypond-toggle-arrange-mode () + "Toggle whether in Arrange mode or Basic mode." + (interactive) + (setq org-babel-lilypond-arrange-mode + (not org-babel-lilypond-arrange-mode)) + (message (concat "Arrange mode has been " + (if org-babel-lilypond-arrange-mode "ENABLED." "DISABLED.")))) + +(defun org-babel-lilypond-switch-extension (file-name ext) + "Utility command to swap current FILE-NAME extension with EXT" + (concat (file-name-sans-extension + file-name) ext)) + +(defun org-babel-lilypond-get-header-args (mode) + "Default arguments to use when evaluating a lilypond +source block. These depend upon whether we are in arrange +mode i.e. ARRANGE-MODE is t" + (cond (mode + '((:tangle . "yes") + (:noweb . "yes") + (:results . "silent") + (:cache . "yes") + (:comments . "yes"))) + (t + '((:results . "file") + (:exports . "results"))))) + +(defun org-babel-lilypond-set-header-args (mode) + "Set org-babel-default-header-args:lilypond +dependent on ORG-BABEL-LILYPOND-ARRANGE-MODE" + (setq org-babel-default-header-args:lilypond + (org-babel-lilypond-get-header-args mode))) + +(provide 'ob-lilypond) + +;;; ob-lilypond.el ends here diff --git a/elpa/org-9.1.14/ob-lisp.el b/elpa/org-9.1.14/ob-lisp.el new file mode 100644 index 00000000..b846138f --- /dev/null +++ b/elpa/org-9.1.14/ob-lisp.el @@ -0,0 +1,127 @@ +;;; ob-lisp.el --- Babel Functions for Common Lisp -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Authors: Joel Boehland +;; Eric Schulte +;; David T. O'Toole +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;;; Support for evaluating Common Lisp code, relies on SLY or SLIME +;;; for all eval. + +;;; Requirements: + +;; Requires SLY (Sylvester the Cat's Common Lisp IDE) or SLIME +;; (Superior Lisp Interaction Mode for Emacs). See: +;; - https://github.com/capitaomorte/sly +;; - http://common-lisp.net/project/slime/ + +;;; Code: +(require 'ob) + +(declare-function sly-eval "ext:sly" (sexp &optional package)) +(declare-function slime-eval "ext:slime" (sexp &optional package)) +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("lisp" . "lisp")) + +(defvar org-babel-default-header-args:lisp '()) +(defvar org-babel-header-args:lisp '((package . :any))) + +(defcustom org-babel-lisp-eval-fn #'slime-eval + "The function to be called to evaluate code on the Lisp side. +Valid values include `slime-eval' and `sly-eval'." + :group 'org-babel + :version "26.1" + :package-version '(Org . "9.0") + :type 'symbol) + +(defcustom org-babel-lisp-dir-fmt + "(let ((*default-pathname-defaults* #P%S\n)) %%s\n)" + "Format string used to wrap code bodies to set the current directory. +For example a value of \"(progn ;; %s\\n %%s)\" would ignore the +current directory string." + :group 'org-babel + :version "24.1" + :type 'string) + +(defun org-babel-expand-body:lisp (body params) + "Expand BODY according to PARAMS, return the expanded body." + (let* ((vars (org-babel--get-vars params)) + (result-params (cdr (assq :result-params params))) + (print-level nil) (print-length nil) + (body (if (null vars) (org-trim body) + (concat "(let (" + (mapconcat + (lambda (var) + (format "(%S (quote %S))" (car var) (cdr var))) + vars "\n ") + ")\n" body ")")))) + (if (or (member "code" result-params) + (member "pp" result-params)) + (format "(pprint %s)" body) + body))) + +(defun org-babel-execute:lisp (body params) + "Execute a block of Common Lisp code with Babel. +BODY is the contents of the block, as a string. PARAMS is +a property list containing the parameters of the block." + (require (pcase org-babel-lisp-eval-fn + (`slime-eval 'slime) + (`sly-eval 'sly))) + (org-babel-reassemble-table + (let ((result + (funcall (if (member "output" (cdr (assq :result-params params))) + #'car #'cadr) + (with-temp-buffer + (insert (org-babel-expand-body:lisp body params)) + (funcall org-babel-lisp-eval-fn + `(swank:eval-and-grab-output + ,(let ((dir (if (assq :dir params) + (cdr (assq :dir params)) + default-directory))) + (format + (if dir (format org-babel-lisp-dir-fmt dir) + "(progn %s\n)") + (buffer-substring-no-properties + (point-min) (point-max))))) + (cdr (assq :package params))))))) + (org-babel-result-cond (cdr (assq :result-params params)) + result + (condition-case nil + (read (org-babel-lisp-vector-to-list result)) + (error result)))) + (org-babel-pick-name (cdr (assq :colname-names params)) + (cdr (assq :colnames params))) + (org-babel-pick-name (cdr (assq :rowname-names params)) + (cdr (assq :rownames params))))) + +(defun org-babel-lisp-vector-to-list (results) + ;; TODO: better would be to replace #(...) with [...] + (replace-regexp-in-string "#(" "(" results)) + +(provide 'ob-lisp) + + + +;;; ob-lisp.el ends here diff --git a/elpa/org-9.1.14/ob-lob.el b/elpa/org-9.1.14/ob-lob.el new file mode 100644 index 00000000..6af6bf07 --- /dev/null +++ b/elpa/org-9.1.14/ob-lob.el @@ -0,0 +1,165 @@ +;;; ob-lob.el --- Functions Supporting the Library of Babel -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Authors: Eric Schulte +;; Dan Davison +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Code: +(require 'cl-lib) +(require 'ob-core) +(require 'ob-table) + +(declare-function org-babel-ref-split-args "ob-ref" (arg-string)) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-context "org-element" (&optional element)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-type "org-element" (element)) + +(defvar org-babel-library-of-babel nil + "Library of source-code blocks. +This is an association list. Populate the library by calling +`org-babel-lob-ingest' on files containing source blocks.") + +(defvar org-babel-default-lob-header-args '((:exports . "results")) + "Default header arguments to use when exporting Babel calls. +By default, a Babel call inherits its arguments from the source +block being called. Header arguments defined in this variable +take precedence over these. It is useful for properties that +should not be inherited from a source block.") + +(defun org-babel-lob-ingest (&optional file) + "Add all named source blocks defined in FILE to `org-babel-library-of-babel'." + (interactive "fFile: ") + (let ((lob-ingest-count 0)) + (org-babel-map-src-blocks file + (let* ((info (org-babel-get-src-block-info 'light)) + (source-name (nth 4 info))) + (when source-name + (setf (nth 1 info) + (if (org-babel-noweb-p (nth 2 info) :eval) + (org-babel-expand-noweb-references info) + (nth 1 info))) + (let ((source (intern source-name))) + (setq org-babel-library-of-babel + (cons (cons source info) + (assq-delete-all source org-babel-library-of-babel)))) + (cl-incf lob-ingest-count)))) + (message "%d src block%s added to Library of Babel" + lob-ingest-count (if (> lob-ingest-count 1) "s" "")) + lob-ingest-count)) + +;; Functions for executing lob one-liners. + +;;;###autoload +(defun org-babel-lob-execute-maybe () + "Execute a Library of Babel source block, if appropriate. +Detect if this is context for a Library Of Babel source block and +if so then run the appropriate source block from the Library." + (interactive) + (let ((info (org-babel-lob-get-info))) + (when info + (org-babel-execute-src-block nil info) + t))) + +(defun org-babel-lob--src-info (ref) + "Return internal representation for Babel data referenced as REF. +REF is a string. This function looks into the current document +for a Babel call or source block. If none is found, it looks +after REF in the Library of Babel." + (let ((name ref) + (file nil)) + ;; Extract the remote file, if specified in the reference. + (when (string-match "\\`\\(.+\\):\\(.+\\)\\'" ref) + (setq file (match-string 1 ref)) + (setq name (match-string 2 ref))) + ;; During export, look into the pristine copy of the document + ;; being exported instead of the current one, which could miss + ;; some data. + (with-current-buffer (cond (file (find-file-noselect file t)) + (org-babel-exp-reference-buffer) + (t (current-buffer))) + (org-with-point-at 1 + (catch :found + (let ((case-fold-search t) + (regexp (org-babel-named-data-regexp-for-name name))) + (while (re-search-forward regexp nil t) + (let ((element (org-element-at-point))) + (when (equal name (org-element-property :name element)) + (throw :found + (pcase (org-element-type element) + (`src-block (org-babel-get-src-block-info t element)) + (`babel-call (org-babel-lob-get-info element)) + ;; Non-executable data found. Since names + ;; are supposed to be unique throughout + ;; a document, bail out. + (_ nil)))))) + (cdr (assoc-string ref org-babel-library-of-babel)))))))) + +;;;###autoload +(defun org-babel-lob-get-info (&optional datum) + "Return internal representation for Library of Babel function call. + +Consider DATUM, when provided, or element at point otherwise. + +Return nil when not on an appropriate location. Otherwise return +a list compatible with `org-babel-get-src-block-info', which +see." + (let* ((context (or datum (org-element-context))) + (type (org-element-type context)) + (reference (org-element-property :call context))) + (when (memq type '(babel-call inline-babel-call)) + (pcase (org-babel-lob--src-info reference) + (`(,language ,body ,header ,_ ,_ ,_ ,coderef) + (let ((begin (org-element-property (if (eq type 'inline-babel-call) + :begin + :post-affiliated) + context))) + (list language + body + (apply #'org-babel-merge-params + header + org-babel-default-lob-header-args + (append + (org-with-wide-buffer + (goto-char begin) + (org-babel-params-from-properties language)) + (list + (org-babel-parse-header-arguments + (org-element-property :inside-header context)) + (let ((args (org-element-property :arguments context))) + (and args + (mapcar (lambda (ref) (cons :var ref)) + (org-babel-ref-split-args args)))) + (org-babel-parse-header-arguments + (org-element-property :end-header context))))) + nil + (org-element-property :name context) + begin + coderef))) + (_ nil))))) + +(provide 'ob-lob) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; ob-lob.el ends here diff --git a/elpa/org-9.1.14/ob-lua.el b/elpa/org-9.1.14/ob-lua.el new file mode 100644 index 00000000..6ae72c7e --- /dev/null +++ b/elpa/org-9.1.14/ob-lua.el @@ -0,0 +1,403 @@ +;;; ob-lua.el --- Org Babel functions for Lua evaluation -*- lexical-binding: t; -*- + +;; Copyright (C) 2014, 2016-2018 Free Software Foundation, Inc. + +;; Authors: Dieter Schoen +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;; Requirements: +;; for session support, lua-mode is needed. +;; lua-mode is not part of GNU Emacs/orgmode, but can be obtained +;; from marmalade or melpa. +;; The source repository is here: +;; https://github.com/immerrr/lua-mode + +;; However, sessions are not yet working. + +;; Org-Babel support for evaluating lua source code. + +;;; Code: +(require 'ob) +(require 'cl-lib) + +(declare-function org-remove-indentation "org" (code &optional n)) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function lua-shell "ext:lua-mode" (&optional argprompt)) +(declare-function lua-toggle-shells "ext:lua-mode" (arg)) +(declare-function run-lua "ext:lua" (cmd &optional dedicated show)) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("lua" . "lua")) + +(defvar org-babel-default-header-args:lua '()) + +(defcustom org-babel-lua-command "lua" + "Name of the command for executing Lua code." + :version "26.1" + :package-version '(Org . "8.3") + :group 'org-babel + :type 'string) + +(defcustom org-babel-lua-mode 'lua-mode + "Preferred lua mode for use in running lua interactively. +This will typically be 'lua-mode." + :group 'org-babel + :version "26.1" + :package-version '(Org . "8.3") + :type 'symbol) + +(defcustom org-babel-lua-hline-to "None" + "Replace hlines in incoming tables with this when translating to lua." + :group 'org-babel + :version "26.1" + :package-version '(Org . "8.3") + :type 'string) + +(defcustom org-babel-lua-None-to 'hline + "Replace 'None' in lua tables with this before returning." + :group 'org-babel + :version "26.1" + :package-version '(Org . "8.3") + :type 'symbol) + +(defun org-babel-execute:lua (body params) + "Execute a block of Lua code with Babel. +This function is called by `org-babel-execute-src-block'." + (let* ((session (org-babel-lua-initiate-session + (cdr (assq :session params)))) + (result-params (cdr (assq :result-params params))) + (result-type (cdr (assq :result-type params))) + (return-val (when (and (eq result-type 'value) (not session)) + (cdr (assq :return params)))) + (preamble (cdr (assq :preamble params))) + (full-body + (org-babel-expand-body:generic + (concat body (if return-val (format "\nreturn %s" return-val) "")) + params (org-babel-variable-assignments:lua params))) + (result (org-babel-lua-evaluate + session full-body result-type result-params preamble))) + (org-babel-reassemble-table + result + (org-babel-pick-name (cdr (assq :colname-names params)) + (cdr (assq :colnames params))) + (org-babel-pick-name (cdr (assq :rowname-names params)) + (cdr (assq :rownames params)))))) + +(defun org-babel-prep-session:lua (session params) + "Prepare SESSION according to the header arguments in PARAMS. +VARS contains resolved variable references" + (let* ((session (org-babel-lua-initiate-session session)) + (var-lines + (org-babel-variable-assignments:lua params))) + (org-babel-comint-in-buffer session + (mapc (lambda (var) + (end-of-line 1) (insert var) (comint-send-input) + (org-babel-comint-wait-for-output session)) var-lines)) + session)) + +(defun org-babel-load-session:lua (session body params) + "Load BODY into SESSION." + (save-window-excursion + (let ((buffer (org-babel-prep-session:lua session params))) + (with-current-buffer buffer + (goto-char (process-mark (get-buffer-process (current-buffer)))) + (insert (org-babel-chomp body))) + buffer))) + +;; helper functions + +(defun org-babel-variable-assignments:lua (params) + "Return a list of Lua statements assigning the block's variables." + (mapcar + (lambda (pair) + (format "%s=%s" + (car pair) + (org-babel-lua-var-to-lua (cdr pair)))) + (org-babel--get-vars params))) + +(defun org-babel-lua-var-to-lua (var) + "Convert an elisp value to a lua variable. +Convert an elisp value, VAR, into a string of lua source code +specifying a variable of the same value." + (if (listp var) + (if (and (= 1 (length var)) (not (listp (car var)))) + (org-babel-lua-var-to-lua (car var)) + (if (and + (= 2 (length var)) + (not (listp (car var)))) + (concat + (substring-no-properties (car var)) + "=" + (org-babel-lua-var-to-lua (cdr var))) + (concat "{" (mapconcat #'org-babel-lua-var-to-lua var ", ") "}"))) + (if (eq var 'hline) + org-babel-lua-hline-to + (format + (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S") + (if (stringp var) (substring-no-properties var) var))))) + +(defun org-babel-lua-table-or-string (results) + "Convert RESULTS into an appropriate elisp value. +If the results look like a list or tuple, then convert them into an +Emacs-lisp table, otherwise return the results as a string." + (let ((res (org-babel-script-escape results))) + (if (listp res) + (mapcar (lambda (el) (if (eq el 'None) + org-babel-lua-None-to el)) + res) + res))) + +(defvar org-babel-lua-buffers '((:default . "*Lua*"))) + +(defun org-babel-lua-session-buffer (session) + "Return the buffer associated with SESSION." + (cdr (assoc session org-babel-lua-buffers))) + +(defun org-babel-lua-with-earmuffs (session) + (let ((name (if (stringp session) session (format "%s" session)))) + (if (and (string= "*" (substring name 0 1)) + (string= "*" (substring name (- (length name) 1)))) + name + (format "*%s*" name)))) + +(defun org-babel-lua-without-earmuffs (session) + (let ((name (if (stringp session) session (format "%s" session)))) + (if (and (string= "*" (substring name 0 1)) + (string= "*" (substring name (- (length name) 1)))) + (substring name 1 (- (length name) 1)) + name))) + +(defvar lua-default-interpreter) +(defvar lua-which-bufname) +(defvar lua-shell-buffer-name) +(defun org-babel-lua-initiate-session-by-key (&optional session) + "Initiate a lua session. +If there is not a current inferior-process-buffer in SESSION +then create. Return the initialized session." + ;; (require org-babel-lua-mode) + (save-window-excursion + (let* ((session (if session (intern session) :default)) + (lua-buffer (org-babel-lua-session-buffer session)) + ;; (cmd (if (member system-type '(cygwin windows-nt ms-dos)) + ;; (concat org-babel-lua-command " -i") + ;; org-babel-lua-command)) + ) + (cond + ((and (eq 'lua-mode org-babel-lua-mode) + (fboundp 'lua-start-process)) ; lua-mode.el + ;; Make sure that lua-which-bufname is initialized, as otherwise + ;; it will be overwritten the first time a Lua buffer is + ;; created. + ;;(lua-toggle-shells lua-default-interpreter) + ;; `lua-shell' creates a buffer whose name is the value of + ;; `lua-which-bufname' with '*'s at the beginning and end + (let* ((bufname (if (and lua-buffer (buffer-live-p lua-buffer)) + (replace-regexp-in-string ;; zap surrounding * + "^\\*\\([^*]+\\)\\*$" "\\1" (buffer-name lua-buffer)) + (concat "Lua-" (symbol-name session)))) + (lua-which-bufname bufname)) + (lua-start-process) + (setq lua-buffer (org-babel-lua-with-earmuffs bufname)))) + (t + (error "No function available for running an inferior Lua"))) + (setq org-babel-lua-buffers + (cons (cons session lua-buffer) + (assq-delete-all session org-babel-lua-buffers))) + session))) + +(defun org-babel-lua-initiate-session (&optional session _params) + "Create a session named SESSION according to PARAMS." + (unless (string= session "none") + (error "Sessions currently not supported, work in progress") + (org-babel-lua-session-buffer + (org-babel-lua-initiate-session-by-key session)))) + +(defvar org-babel-lua-eoe-indicator "--eoe" + "A string to indicate that evaluation has completed.") + +(defvar org-babel-lua-wrapper-method + " +function main() +%s +end + +fd=io.open(\"%s\", \"w\") +fd:write( main() ) +fd:close()") +(defvar org-babel-lua-pp-wrapper-method + " +-- table to string +function t2s(t, indent) + if indent == nil then + indent = \"\" + end + if type(t) == \"table\" then + ts = \"\" + for k,v in pairs(t) do + if type(v) == \"table\" then + ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \\n\" .. + t2s(v, indent .. \" \") + else + ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \" .. + t2s(v, indent .. \" \") .. \"\\n\" + end + end + return ts + else + return tostring(t) + end +end + + +function main() +%s +end + +fd=io.open(\"%s\", \"w\") +fd:write(t2s(main())) +fd:close()") + +(defun org-babel-lua-evaluate + (session body &optional result-type result-params preamble) + "Evaluate BODY as Lua code." + (if session + (org-babel-lua-evaluate-session + session body result-type result-params) + (org-babel-lua-evaluate-external-process + body result-type result-params preamble))) + +(defun org-babel-lua-evaluate-external-process + (body &optional result-type result-params preamble) + "Evaluate BODY in external lua process. +If RESULT-TYPE equals 'output then return standard output as a +string. If RESULT-TYPE equals 'value then return the value of the +last statement in BODY, as elisp." + (let ((raw + (pcase result-type + (`output (org-babel-eval org-babel-lua-command + (concat (if preamble (concat preamble "\n")) + body))) + (`value (let ((tmp-file (org-babel-temp-file "lua-"))) + (org-babel-eval + org-babel-lua-command + (concat + (if preamble (concat preamble "\n") "") + (format + (if (member "pp" result-params) + org-babel-lua-pp-wrapper-method + org-babel-lua-wrapper-method) + (mapconcat + (lambda (line) (format "\t%s" line)) + (split-string + (org-remove-indentation + (org-trim body)) + "[\r\n]") "\n") + (org-babel-process-file-name tmp-file 'noquote)))) + (org-babel-eval-read-file tmp-file)))))) + (org-babel-result-cond result-params + raw + (org-babel-lua-table-or-string (org-trim raw))))) + +(defun org-babel-lua-evaluate-session + (session body &optional result-type result-params) + "Pass BODY to the Lua process in SESSION. +If RESULT-TYPE equals 'output then return standard output as a +string. If RESULT-TYPE equals 'value then return the value of the +last statement in BODY, as elisp." + (let* ((send-wait (lambda () (comint-send-input nil t) (sleep-for 0 5))) + (dump-last-value + (lambda + (tmp-file pp) + (mapc + (lambda (statement) (insert statement) (funcall send-wait)) + (if pp + (list + "-- table to string +function t2s(t, indent) + if indent == nil then + indent = \"\" + end + if type(t) == \"table\" then + ts = \"\" + for k,v in pairs(t) do + if type(v) == \"table\" then + ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \\n\" .. + t2s(v, indent .. \" \") + else + ts = ts .. indent .. t2s(k,indent .. \" \") .. \" = \" .. + t2s(v, indent .. \" \") .. \"\\n\" + end + end + return ts + else + return tostring(t) + end +end +" + (concat "fd:write(_)) +fd:close()" + (org-babel-process-file-name tmp-file 'noquote))) + (list (format "fd=io.open(\"%s\", \"w\") +fd:write( _ ) +fd:close()" + (org-babel-process-file-name tmp-file + 'noquote))))))) + (input-body (lambda (body) + (mapc (lambda (line) (insert line) (funcall send-wait)) + (split-string body "[\r\n]")) + (funcall send-wait))) + (results + (pcase result-type + (`output + (mapconcat + #'org-trim + (butlast + (org-babel-comint-with-output + (session org-babel-lua-eoe-indicator t body) + (funcall input-body body) + (funcall send-wait) (funcall send-wait) + (insert org-babel-lua-eoe-indicator) + (funcall send-wait)) + 2) "\n")) + (`value + (let ((tmp-file (org-babel-temp-file "lua-"))) + (org-babel-comint-with-output + (session org-babel-lua-eoe-indicator nil body) + (let ((comint-process-echoes nil)) + (funcall input-body body) + (funcall dump-last-value tmp-file + (member "pp" result-params)) + (funcall send-wait) (funcall send-wait) + (insert org-babel-lua-eoe-indicator) + (funcall send-wait))) + (org-babel-eval-read-file tmp-file)))))) + (unless (string= (substring org-babel-lua-eoe-indicator 1 -1) results) + (org-babel-result-cond result-params + results + (org-babel-lua-table-or-string results))))) + +(defun org-babel-lua-read-string (string) + "Strip 's from around Lua string." + (org-unbracket-string "'" "'" string)) + +(provide 'ob-lua) + + + +;;; ob-lua.el ends here diff --git a/elpa/org-9.1.14/ob-makefile.el b/elpa/org-9.1.14/ob-makefile.el new file mode 100644 index 00000000..46870378 --- /dev/null +++ b/elpa/org-9.1.14/ob-makefile.el @@ -0,0 +1,48 @@ +;;; ob-makefile.el --- Babel Functions for Makefile -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Thomas S. Dye +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; This file exists solely for tangling a Makefile from Org files. + +;;; Code: +(require 'ob) + +(defvar org-babel-default-header-args:makefile '()) + +(defun org-babel-execute:makefile (body _params) + "Execute a block of makefile code. +This function is called by `org-babel-execute-src-block'." + body) + +(defun org-babel-prep-session:makefile (_session _params) + "Return an error if the :session header argument is set. Make +does not support sessions." + (error "Makefile sessions are nonsensical")) + +(provide 'ob-makefile) + + + +;;; ob-makefile.el ends here diff --git a/elpa/org-9.1.14/ob-matlab.el b/elpa/org-9.1.14/ob-matlab.el new file mode 100644 index 00000000..5baac777 --- /dev/null +++ b/elpa/org-9.1.14/ob-matlab.el @@ -0,0 +1,47 @@ +;;; ob-matlab.el --- Babel support for Matlab -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Dan Davison +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Functions that are common to org-babel support for matlab and +;; octave are in org-babel-octave.el + +;;; Requirements: + +;; Matlab + +;; matlab.el required for interactive emacs sessions and matlab-mode +;; major mode for source code editing buffer +;; http://matlab-emacs.sourceforge.net/ + +;;; Code: +(require 'ob) +(require 'ob-octave) + +;; see ob-octave for matlab implementation + +(provide 'ob-matlab) + + + +;;; ob-matlab.el ends here diff --git a/elpa/org-9.1.14/ob-maxima.el b/elpa/org-9.1.14/ob-maxima.el new file mode 100644 index 00000000..b42a4b8a --- /dev/null +++ b/elpa/org-9.1.14/ob-maxima.el @@ -0,0 +1,133 @@ +;;; ob-maxima.el --- Babel Functions for Maxima -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric S Fraga +;; Eric Schulte +;; Keywords: literate programming, reproducible research, maxima +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating maxima entries. +;; +;; This differs from most standard languages in that +;; +;; 1) there is no such thing as a "session" in maxima +;; +;; 2) we are adding the "cmdline" header argument + +;;; Code: +(require 'ob) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("maxima" . "max")) + +(defvar org-babel-default-header-args:maxima '()) + +(defcustom org-babel-maxima-command + (if (boundp 'maxima-command) maxima-command "maxima") + "Command used to call maxima on the shell." + :group 'org-babel + :type 'string) + +(defun org-babel-maxima-expand (body params) + "Expand a block of Maxima code according to its header arguments." + (let ((vars (org-babel--get-vars params)) + (epilogue (cdr (assq :epilogue params))) + (prologue (cdr (assq :prologue params)))) + (mapconcat 'identity + (list + ;; Any code from the specified prologue at the start. + prologue + ;; graphic output + (let ((graphic-file (ignore-errors (org-babel-graphical-output-file params)))) + (if graphic-file + (format + "set_plot_option ([gnuplot_term, png]); set_plot_option ([gnuplot_out_file, %S]);" + graphic-file) + "")) + ;; variables + (mapconcat 'org-babel-maxima-var-to-maxima vars "\n") + ;; body + body + ;; Any code from the specified epilogue at the end. + epilogue + "gnuplot_close ()$") + "\n"))) + +(defun org-babel-execute:maxima (body params) + "Execute a block of Maxima entries with org-babel. +This function is called by `org-babel-execute-src-block'." + (message "executing Maxima source code block") + (let ((result-params (split-string (or (cdr (assq :results params)) ""))) + (result + (let* ((cmdline (or (cdr (assq :cmdline params)) "")) + (in-file (org-babel-temp-file "maxima-" ".max")) + (cmd (format "%s --very-quiet -r 'batchload(%S)$' %s" + org-babel-maxima-command in-file cmdline))) + (with-temp-file in-file (insert (org-babel-maxima-expand body params))) + (message cmd) + ;; " | grep -v batch | grep -v 'replaced' | sed '/^$/d' " + (let ((raw (org-babel-eval cmd ""))) + (mapconcat + #'identity + (delq nil + (mapcar (lambda (line) + (unless (or (string-match "batch" line) + (string-match "^rat: replaced .*$" line) + (string-match "^;;; Loading #P" line) + (= 0 (length line))) + line)) + (split-string raw "[\r\n]"))) "\n"))))) + (if (ignore-errors (org-babel-graphical-output-file params)) + nil + (org-babel-result-cond result-params + result + (let ((tmp-file (org-babel-temp-file "maxima-res-"))) + (with-temp-file tmp-file (insert result)) + (org-babel-import-elisp-from-file tmp-file)))))) + + +(defun org-babel-prep-session:maxima (_session _params) + (error "Maxima does not support sessions")) + +(defun org-babel-maxima-var-to-maxima (pair) + "Convert an elisp val into a string of maxima code specifying a var +of the same value." + (let ((var (car pair)) + (val (cdr pair))) + (when (symbolp val) + (setq val (symbol-name val)) + (when (= (length val) 1) + (setq val (string-to-char val)))) + (format "%S: %s$" var + (org-babel-maxima-elisp-to-maxima val)))) + +(defun org-babel-maxima-elisp-to-maxima (val) + "Return a string of maxima code which evaluates to VAL." + (if (listp val) + (concat "[" (mapconcat #'org-babel-maxima-elisp-to-maxima val ", ") "]") + (format "%s" val))) + + +(provide 'ob-maxima) + + + +;;; ob-maxima.el ends here diff --git a/elpa/org-9.1.14/ob-mscgen.el b/elpa/org-9.1.14/ob-mscgen.el new file mode 100644 index 00000000..b2c2443c --- /dev/null +++ b/elpa/org-9.1.14/ob-mscgen.el @@ -0,0 +1,84 @@ +;;; ob-msc.el --- Babel Functions for Mscgen -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Juan Pechiar +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: +;; +;; This software provides EMACS org-babel export support for message +;; sequence charts. The mscgen utility is used for processing the +;; sequence definition, and must therefore be installed in the system. +;; +;; Mscgen is available and documented at +;; http://www.mcternan.me.uk/mscgen/index.html +;; +;; This code is directly inspired by Eric Schulte's ob-dot.el +;; +;; Example: +;; +;; #+begin_src mscgen :file example.png +;; msc { +;; A,B; +;; A -> B [ label = "send message" ]; +;; A <- B [ label = "get answer" ]; +;; } +;; #+end_src +;; +;; Header for alternative file type: +;; +;; #+begin_src mscgen :file ex2.svg :filetype svg + +;; This differs from most standard languages in that +;; +;; 1) there is no such thing as a "session" in mscgen +;; 2) we are generally only going to return results of type "file" +;; 3) we are adding the "file" and "filetype" header arguments +;; 4) there are no variables + +;;; Code: +(require 'ob) + +(defvar org-babel-default-header-args:mscgen + '((:results . "file") (:exports . "results")) + "Default arguments to use when evaluating a mscgen source block.") + +(defun org-babel-execute:mscgen (body params) + "Execute a block of Mscgen code with Babel. +This function is called by `org-babel-execute-src-block'. +Default filetype is png. Modify by setting :filetype parameter to +mscgen supported formats." + (let* ((out-file (or (cdr (assq :file params)) "output.png" )) + (filetype (or (cdr (assq :filetype params)) "png" ))) + (unless (cdr (assq :file params)) + (error " +ERROR: no output file specified. Add \":file name.png\" to the src header")) + (org-babel-eval (concat "mscgen -T " filetype " -o " out-file) body) + nil)) ;; signal that output has already been written to file + +(defun org-babel-prep-session:mscgen (_session _params) + "Raise an error because Mscgen doesn't support sessions." + (error "Mscgen does not support sessions")) + +(provide 'ob-mscgen) + + + +;;; ob-msc.el ends here diff --git a/elpa/org-9.1.14/ob-ocaml.el b/elpa/org-9.1.14/ob-ocaml.el new file mode 100644 index 00000000..90926b5c --- /dev/null +++ b/elpa/org-9.1.14/ob-ocaml.el @@ -0,0 +1,171 @@ +;;; ob-ocaml.el --- Babel Functions for Ocaml -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating ocaml source code. This one will +;; be sort of tricky because ocaml programs must be compiled before +;; they can be run, but ocaml code can also be run through an +;; interactive interpreter. +;; +;; For now lets only allow evaluation using the ocaml interpreter. + +;;; Requirements: + +;; - tuareg-mode :: http://www-rocq.inria.fr/~acohen/tuareg/ + +;;; Code: +(require 'ob) +(require 'comint) + +(declare-function tuareg-run-caml "ext:tuareg" ()) +(declare-function tuareg-run-ocaml "ext:tuareg" ()) +(declare-function tuareg-interactive-send-input "ext:tuareg" ()) +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("ocaml" . "ml")) + +(defvar org-babel-default-header-args:ocaml '()) + +(defvar org-babel-ocaml-eoe-indicator "\"org-babel-ocaml-eoe\";;") +(defvar org-babel-ocaml-eoe-output "org-babel-ocaml-eoe") + +(defcustom org-babel-ocaml-command "ocaml" + "Name of the command for executing Ocaml code." + :version "24.4" + :package-version '(Org . "8.0") + :group 'org-babel + :type 'string) + +(defun org-babel-execute:ocaml (body params) + "Execute a block of Ocaml code with Babel." + (let* ((full-body (org-babel-expand-body:generic + body params + (org-babel-variable-assignments:ocaml params))) + (session (org-babel-prep-session:ocaml + (cdr (assq :session params)) params)) + (raw (org-babel-comint-with-output + (session org-babel-ocaml-eoe-output nil full-body) + (insert + (concat + (org-babel-chomp full-body) ";;\n" + org-babel-ocaml-eoe-indicator)) + (tuareg-interactive-send-input))) + (clean + (car (let ((re (regexp-quote org-babel-ocaml-eoe-output)) out) + (delq nil (mapcar (lambda (line) + (if out + (progn (setq out nil) line) + (when (string-match re line) + (progn (setq out t) nil)))) + (mapcar #'org-trim (reverse raw))))))) + (raw (org-trim clean)) + (result-params (cdr (assq :result-params params)))) + (string-match + "\\(\\(.*\n\\)*\\)[^:\n]+ : \\([^=\n]+\\) =\\(\n\\| \\)\\(.+\\)$" + raw) + (let ((output (match-string 1 raw)) + (type (match-string 3 raw)) + (value (match-string 5 raw))) + (org-babel-reassemble-table + (org-babel-result-cond result-params + (cond + ((member "verbatim" result-params) raw) + ((member "output" result-params) output) + (t raw)) + (if (and value type) + (org-babel-ocaml-parse-output value type) + raw)) + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))) + +(defvar tuareg-interactive-buffer-name) +(defun org-babel-prep-session:ocaml (session _params) + "Prepare SESSION according to the header arguments in PARAMS." + (require 'tuareg) + (let ((tuareg-interactive-buffer-name (if (and (not (string= session "none")) + (not (string= session "default")) + (stringp session)) + session + tuareg-interactive-buffer-name))) + (save-window-excursion (if (fboundp 'tuareg-run-process-if-needed) + (tuareg-run-process-if-needed org-babel-ocaml-command) + (tuareg-run-caml))) + (get-buffer tuareg-interactive-buffer-name))) + +(defun org-babel-variable-assignments:ocaml (params) + "Return list of ocaml statements assigning the block's variables." + (mapcar + (lambda (pair) (format "let %s = %s;;" (car pair) + (org-babel-ocaml-elisp-to-ocaml (cdr pair)))) + (org-babel--get-vars params))) + +(defun org-babel-ocaml-elisp-to-ocaml (val) + "Return a string of ocaml code which evaluates to VAL." + (if (listp val) + (concat "[|" (mapconcat #'org-babel-ocaml-elisp-to-ocaml val "; ") "|]") + (format "%S" val))) + +(defun org-babel-ocaml-parse-output (value type) + "Parse VALUE of type TYPE. +VALUE and TYPE are string output from an ocaml process." + (cond + ((string= "string" type) + (org-babel-read value)) + ((or (string= "int" type) + (string= "float" type)) + (string-to-number value)) + ((string-match "list" type) + (org-babel-ocaml-read-list value)) + ((string-match "array" type) + (org-babel-ocaml-read-array value)) + (t (message "don't recognize type %s" type) value))) + +(defun org-babel-ocaml-read-list (results) + "Convert RESULTS into an elisp table or string. +If the results look like a table, then convert them into an +Emacs-lisp table, otherwise return the results as a string." + ;; XXX: This probably does not behave as expected when a semicolon + ;; is in a string in a list. The same comment applies to + ;; `org-babel-ocaml-read-array' below (with even more failure + ;; modes). + (org-babel-script-escape (replace-regexp-in-string ";" "," results))) + +(defun org-babel-ocaml-read-array (results) + "Convert RESULTS into an elisp table or string. +If the results look like a table, then convert them into an +Emacs-lisp table, otherwise return the results as a string." + (org-babel-script-escape + (replace-regexp-in-string + "\\[|" "[" (replace-regexp-in-string + "|\\]" "]" (replace-regexp-in-string + "; " "," results))))) + +(provide 'ob-ocaml) + + + +;;; ob-ocaml.el ends here diff --git a/elpa/org-9.1.14/ob-octave.el b/elpa/org-9.1.14/ob-octave.el new file mode 100644 index 00000000..c7339cf9 --- /dev/null +++ b/elpa/org-9.1.14/ob-octave.el @@ -0,0 +1,266 @@ +;;; ob-octave.el --- Babel Functions for Octave and Matlab -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Dan Davison +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;;; Requirements: + +;; octave +;; octave-mode.el and octave-inf.el come with GNU emacs + +;;; Code: +(require 'ob) + +(declare-function matlab-shell "ext:matlab-mode") +(declare-function matlab-shell-run-region "ext:matlab-mode") +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-babel-default-header-args:matlab '()) +(defvar org-babel-default-header-args:octave '()) + +(defvar org-babel-matlab-shell-command "matlab -nosplash" + "Shell command to run matlab as an external process.") +(defvar org-babel-octave-shell-command "octave -q" + "Shell command to run octave as an external process.") + +(defvar org-babel-matlab-with-emacs-link nil + "If non-nil use matlab-shell-run-region for session evaluation. + This will use EmacsLink if (matlab-with-emacs-link) evaluates + to a non-nil value.") + +(defvar org-babel-matlab-emacs-link-wrapper-method + "%s +if ischar(ans), fid = fopen('%s', 'w'); fprintf(fid, '%%s\\n', ans); fclose(fid); +else, save -ascii %s ans +end +delete('%s') +") +(defvar org-babel-octave-wrapper-method + "%s +if ischar(ans), fid = fopen('%s', 'w'); fprintf(fid, '%%s\\n', ans); fclose(fid); +else, dlmwrite('%s', ans, '\\t') +end") + +(defvar org-babel-octave-eoe-indicator "'org_babel_eoe'") + +(defvar org-babel-octave-eoe-output "ans = org_babel_eoe") + +(defun org-babel-execute:matlab (body params) + "Execute a block of matlab code with Babel." + (org-babel-execute:octave body params 'matlab)) + +(defun org-babel-execute:octave (body params &optional matlabp) + "Execute a block of octave code with Babel." + (let* ((session + (funcall (intern (format "org-babel-%s-initiate-session" + (if matlabp "matlab" "octave"))) + (cdr (assq :session params)) params)) + (result-type (cdr (assq :result-type params))) + (full-body + (org-babel-expand-body:generic + body params (org-babel-variable-assignments:octave params))) + (gfx-file (ignore-errors (org-babel-graphical-output-file params))) + (result (org-babel-octave-evaluate + session + (if gfx-file + (mapconcat 'identity + (list + "set (0, \"defaultfigurevisible\", \"off\");" + full-body + (format "print -dpng %s" gfx-file)) + "\n") + full-body) + result-type matlabp))) + (if gfx-file + nil + (org-babel-reassemble-table + result + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))) + +(defun org-babel-prep-session:matlab (session params) + "Prepare SESSION according to PARAMS." + (org-babel-prep-session:octave session params 'matlab)) + +(defun org-babel-variable-assignments:octave (params) + "Return list of octave statements assigning the block's variables." + (mapcar + (lambda (pair) + (format "%s=%s;" + (car pair) + (org-babel-octave-var-to-octave (cdr pair)))) + (org-babel--get-vars params))) + +(defalias 'org-babel-variable-assignments:matlab + 'org-babel-variable-assignments:octave) + +(defun org-babel-octave-var-to-octave (var) + "Convert an emacs-lisp value into an octave variable. +Converts an emacs-lisp variable into a string of octave code +specifying a variable of the same value." + (if (listp var) + (concat "[" (mapconcat #'org-babel-octave-var-to-octave var + (if (listp (car var)) "; " ",")) "]") + (cond + ((stringp var) + (format "'%s'" var)) + (t + (format "%s" var))))) + +(defun org-babel-prep-session:octave (session params &optional matlabp) + "Prepare SESSION according to the header arguments specified in PARAMS." + (let* ((session (org-babel-octave-initiate-session session params matlabp)) + (var-lines (org-babel-variable-assignments:octave params))) + (org-babel-comint-in-buffer session + (mapc (lambda (var) + (end-of-line 1) (insert var) (comint-send-input nil t) + (org-babel-comint-wait-for-output session)) var-lines)) + session)) + +(defun org-babel-matlab-initiate-session (&optional session params) + "Create a matlab inferior process buffer. +If there is not a current inferior-process-buffer in SESSION then +create. Return the initialized session." + (org-babel-octave-initiate-session session params 'matlab)) + +(defun org-babel-octave-initiate-session (&optional session _params matlabp) + "Create an octave inferior process buffer. +If there is not a current inferior-process-buffer in SESSION then +create. Return the initialized session." + (if matlabp (require 'matlab) (or (require 'octave-inf nil 'noerror) + (require 'octave))) + (unless (string= session "none") + (let ((session (or session + (if matlabp "*Inferior Matlab*" "*Inferior Octave*")))) + (if (org-babel-comint-buffer-livep session) session + (save-window-excursion + (if matlabp (unless org-babel-matlab-with-emacs-link (matlab-shell)) + (run-octave)) + (rename-buffer (if (bufferp session) (buffer-name session) + (if (stringp session) session (buffer-name)))) + (current-buffer)))))) + +(defun org-babel-octave-evaluate + (session body result-type &optional matlabp) + "Pass BODY to the octave process in SESSION. +If RESULT-TYPE equals `output' then return the outputs of the +statements in BODY, if RESULT-TYPE equals `value' then return the +value of the last statement in BODY, as elisp." + (if session + (org-babel-octave-evaluate-session session body result-type matlabp) + (org-babel-octave-evaluate-external-process body result-type matlabp))) + +(defun org-babel-octave-evaluate-external-process (body result-type matlabp) + "Evaluate BODY in an external octave process." + (let ((cmd (if matlabp + org-babel-matlab-shell-command + org-babel-octave-shell-command))) + (pcase result-type + (`output (org-babel-eval cmd body)) + (`value (let ((tmp-file (org-babel-temp-file "octave-"))) + (org-babel-eval + cmd + (format org-babel-octave-wrapper-method body + (org-babel-process-file-name tmp-file 'noquote) + (org-babel-process-file-name tmp-file 'noquote))) + (org-babel-octave-import-elisp-from-file tmp-file)))))) + +(defun org-babel-octave-evaluate-session + (session body result-type &optional matlabp) + "Evaluate BODY in SESSION." + (let* ((tmp-file (org-babel-temp-file (if matlabp "matlab-" "octave-"))) + (wait-file (org-babel-temp-file "matlab-emacs-link-wait-signal-")) + (full-body + (pcase result-type + (`output + (mapconcat + #'org-babel-chomp + (list body org-babel-octave-eoe-indicator) "\n")) + (`value + (if (and matlabp org-babel-matlab-with-emacs-link) + (concat + (format org-babel-matlab-emacs-link-wrapper-method + body + (org-babel-process-file-name tmp-file 'noquote) + (org-babel-process-file-name tmp-file 'noquote) wait-file) "\n") + (mapconcat + #'org-babel-chomp + (list (format org-babel-octave-wrapper-method + body + (org-babel-process-file-name tmp-file 'noquote) + (org-babel-process-file-name tmp-file 'noquote)) + org-babel-octave-eoe-indicator) "\n"))))) + (raw (if (and matlabp org-babel-matlab-with-emacs-link) + (save-window-excursion + (with-temp-buffer + (insert full-body) + (write-region "" 'ignored wait-file nil nil nil 'excl) + (matlab-shell-run-region (point-min) (point-max)) + (message "Waiting for Matlab Emacs Link") + (while (file-exists-p wait-file) (sit-for 0.01)) + "")) ;; matlab-shell-run-region doesn't seem to + ;; make *matlab* buffer contents easily + ;; available, so :results output currently + ;; won't work + (org-babel-comint-with-output + (session + (if matlabp + org-babel-octave-eoe-indicator + org-babel-octave-eoe-output) + t full-body) + (insert full-body) (comint-send-input nil t)))) results) + (pcase result-type + (`value + (org-babel-octave-import-elisp-from-file tmp-file)) + (`output + (setq results + (if matlabp + (cdr (reverse (delq "" (mapcar + #'org-babel-strip-quotes + (mapcar #'org-trim raw))))) + (cdr (member org-babel-octave-eoe-output + (reverse (mapcar + #'org-babel-strip-quotes + (mapcar #'org-trim raw))))))) + (mapconcat #'identity (reverse results) "\n"))))) + +(defun org-babel-octave-import-elisp-from-file (file-name) + "Import data from FILE-NAME. +This removes initial blank and comment lines and then calls +`org-babel-import-elisp-from-file'." + (let ((temp-file (org-babel-temp-file "octave-matlab-")) beg end) + (with-temp-file temp-file + (insert-file-contents file-name) + (re-search-forward "^[ \t]*[^# \t]" nil t) + (if (< (setq beg (point-min)) + (setq end (point-at-bol))) + (delete-region beg end))) + (org-babel-import-elisp-from-file temp-file '(16)))) + +(provide 'ob-octave) + + + +;;; ob-octave.el ends here diff --git a/elpa/org-9.1.14/ob-org.el b/elpa/org-9.1.14/ob-org.el new file mode 100644 index 00000000..7a495faa --- /dev/null +++ b/elpa/org-9.1.14/ob-org.el @@ -0,0 +1,72 @@ +;;; ob-org.el --- Babel Functions for Org Code Blocks -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; This is the simplest of code blocks, where upon evaluation the +;; contents of the code block are returned in a raw result. + +;;; Code: +(require 'ob) + +(declare-function org-export-string-as "ox" + (string backend &optional body-only ext-plist)) + +(defvar org-babel-default-header-args:org + '((:results . "raw silent") (:exports . "code")) + "Default arguments for evaluating an org source block.") + +(defvar org-babel-org-default-header + "#+TITLE: default empty header\n" + "Default header inserted during export of org blocks.") + +(defun org-babel-expand-body:org (body params) + (dolist (var (org-babel--get-vars params)) + (setq body (replace-regexp-in-string + (regexp-quote (format "$%s" (car var))) + (format "%s" (cdr var)) + body nil 'literal))) + body) + +(defun org-babel-execute:org (body params) + "Execute a block of Org code with. +This function is called by `org-babel-execute-src-block'." + (let ((result-params (split-string (or (cdr (assq :results params)) ""))) + (body (org-babel-expand-body:org + (replace-regexp-in-string "^," "" body) params))) + (cond + ((member "latex" result-params) + (org-export-string-as (concat "#+Title: \n" body) 'latex t)) + ((member "html" result-params) (org-export-string-as body 'html t)) + ((member "ascii" result-params) (org-export-string-as body 'ascii t)) + (t body)))) + +(defun org-babel-prep-session:org (_session _params) + "Return an error because org does not support sessions." + (error "Org does not support sessions")) + +(provide 'ob-org) + + + +;;; ob-org.el ends here diff --git a/elpa/org-9.1.14/ob-perl.el b/elpa/org-9.1.14/ob-perl.el new file mode 100644 index 00000000..85806fd5 --- /dev/null +++ b/elpa/org-9.1.14/ob-perl.el @@ -0,0 +1,157 @@ +;;; ob-perl.el --- Babel Functions for Perl -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Authors: Dan Davison +;; Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating perl source code. + +;;; Code: +(require 'ob) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("perl" . "pl")) + +(defvar org-babel-default-header-args:perl '()) + +(defvar org-babel-perl-command "perl" + "Name of command to use for executing perl code.") + +(defun org-babel-execute:perl (body params) + "Execute a block of Perl code with Babel. +This function is called by `org-babel-execute-src-block'." + (let* ((session (cdr (assq :session params))) + (result-params (cdr (assq :result-params params))) + (result-type (cdr (assq :result-type params))) + (full-body (org-babel-expand-body:generic + body params (org-babel-variable-assignments:perl params))) + (session (org-babel-perl-initiate-session session))) + (org-babel-reassemble-table + (org-babel-perl-evaluate session full-body result-type result-params) + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))) + +(defun org-babel-prep-session:perl (_session _params) + "Prepare SESSION according to the header arguments in PARAMS." + (error "Sessions are not supported for Perl")) + +(defun org-babel-variable-assignments:perl (params) + "Return list of perl statements assigning the block's variables." + (mapcar + (lambda (pair) + (org-babel-perl--var-to-perl (cdr pair) (car pair))) + (org-babel--get-vars params))) + +;; helper functions + +(defvar org-babel-perl-var-wrap "q(%s)" + "Wrapper for variables inserted into Perl code.") + +(defvar org-babel-perl--lvl) +(defun org-babel-perl--var-to-perl (var &optional varn) + "Convert an elisp value to a perl variable. +The elisp value, VAR, is converted to a string of perl source code +specifying a var of the same value." + (if varn + (let ((org-babel-perl--lvl 0) (lvar (listp var))) + (concat "my $" (symbol-name varn) "=" (when lvar "\n") + (org-babel-perl--var-to-perl var) + ";\n")) + (let ((prefix (make-string (* 2 org-babel-perl--lvl) ?\ ))) + (concat prefix + (if (listp var) + (let ((org-babel-perl--lvl (1+ org-babel-perl--lvl))) + (concat "[\n" + (mapconcat #'org-babel-perl--var-to-perl var "") + prefix "]")) + (format "q(%s)" var)) + (unless (zerop org-babel-perl--lvl) ",\n"))))) + +(defvar org-babel-perl-buffers '(:default . nil)) + +(defun org-babel-perl-initiate-session (&optional _session _params) + "Return nil because sessions are not supported by perl." + nil) + +(defvar org-babel-perl-wrapper-method "{ + my $babel_sub = sub { + %s + }; + open my $BOH, qq(>%s) or die qq(Perl: Could not open output file.$/); + my $rv = &$babel_sub(); + my $rt = ref $rv; + select $BOH; + if (qq(ARRAY) eq $rt) { + local $\\=$/; + local $,=qq(\t); + foreach my $rv ( @$rv ) { + my $rt = ref $rv; + if (qq(ARRAY) eq $rt) { + print @$rv; + } else { + print $rv; + } + } + } else { + print $rv; + } +}") + +(defvar org-babel-perl-preface nil) + +(defvar org-babel-perl-pp-wrapper-method + nil) + +(defun org-babel-perl-evaluate (session ibody &optional result-type result-params) + "Pass BODY to the Perl process in SESSION. +If RESULT-TYPE equals `output' then return a list of the outputs +of the statements in BODY, if RESULT-TYPE equals `value' then +return the value of the last statement in BODY, as elisp." + (when session (error "Sessions are not supported for Perl")) + (let* ((body (concat org-babel-perl-preface ibody)) + (tmp-file (org-babel-temp-file "perl-")) + (tmp-babel-file (org-babel-process-file-name + tmp-file 'noquote))) + (let ((results + (pcase result-type + (`output + (with-temp-file tmp-file + (insert + (org-babel-eval org-babel-perl-command body)) + (buffer-string))) + (`value + (org-babel-eval org-babel-perl-command + (format org-babel-perl-wrapper-method + body tmp-babel-file)))))) + (when results + (org-babel-result-cond result-params + (org-babel-eval-read-file tmp-file) + (org-babel-import-elisp-from-file tmp-file '(16))))))) + +(provide 'ob-perl) + + + +;;; ob-perl.el ends here diff --git a/elpa/org-9.1.14/ob-picolisp.el b/elpa/org-9.1.14/ob-picolisp.el new file mode 100644 index 00000000..cc2c8a8d --- /dev/null +++ b/elpa/org-9.1.14/ob-picolisp.el @@ -0,0 +1,187 @@ +;;; ob-picolisp.el --- Babel Functions for Picolisp -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Authors: Thorsten Jolitz +;; Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; This library enables the use of PicoLisp in the multi-language +;; programming framework Org-Babel. PicoLisp is a minimal yet +;; fascinating lisp dialect and a highly productive application +;; framework for web-based client-server applications on top of +;; object-oriented databases. A good way to learn PicoLisp is to first +;; read Paul Grahams essay "The hundred year language" +;; (http://www.paulgraham.com/hundred.html) and then study the various +;; documents and essays published in the PicoLisp wiki +;; (http://picolisp.com/5000/-2.html). PicoLisp is included in some +;; GNU/Linux Distributions, and can be downloaded here: +;; http://software-lab.de/down.html. It ships with a picolisp-mode and +;; an inferior-picolisp-mode for Emacs (to be found in the /lib/el/ +;; directory). + +;; Although it might seem more natural to use Emacs Lisp for most +;; Lisp-based programming tasks inside Org, an Emacs library written +;; in Emacs Lisp, PicoLisp has at least two outstanding features that +;; make it a valuable addition to Org Babel: + +;; PicoLisp _is_ an object-oriented database with a Prolog-based query +;; language implemented in PicoLisp (Pilog). Database objects are +;; first-class members of the language. + +;; PicoLisp is an extremely productive framework for the development +;; of interactive web-applications (on top of a database). + +;;; Requirements: + +;;; Code: +(require 'ob) +(require 'comint) + +(declare-function run-picolisp "ext:inferior-picolisp" (cmd)) +(defvar org-babel-tangle-lang-exts) ;; Autoloaded + +;; optionally define a file extension for this language +(add-to-list 'org-babel-tangle-lang-exts '("picolisp" . "l")) + +;;; interferes with settings in org-babel buffer? +;; optionally declare default header arguments for this language +;; (defvar org-babel-default-header-args:picolisp +;; '((:colnames . "no")) +;; "Default arguments for evaluating a picolisp source block.") + +(defvar org-babel-picolisp-eoe "org-babel-picolisp-eoe" + "String to indicate that evaluation has completed.") + +(defcustom org-babel-picolisp-cmd "pil" + "Name of command used to evaluate picolisp blocks." + :group 'org-babel + :version "24.1" + :type 'string) + +(defun org-babel-expand-body:picolisp (body params) + "Expand BODY according to PARAMS, return the expanded body." + (let ((vars (org-babel--get-vars params)) + (print-level nil) + (print-length nil)) + (if (> (length vars) 0) + (concat "(prog (let (" + (mapconcat + (lambda (var) + (format "%S '%S)" + (print (car var)) + (print (cdr var)))) + vars "\n ") + " \n" body ") )") + body))) + +(defun org-babel-execute:picolisp (body params) + "Execute a block of Picolisp code with org-babel. This function is + called by `org-babel-execute-src-block'" + (message "executing Picolisp source code block") + (let* ( + ;; Name of the session or "none". + (session-name (cdr (assq :session params))) + ;; Set the session if the session variable is non-nil. + (session (org-babel-picolisp-initiate-session session-name)) + ;; Either OUTPUT or VALUE which should behave as described above. + (result-params (cdr (assq :result-params params))) + ;; Expand the body with `org-babel-expand-body:picolisp'. + (full-body (org-babel-expand-body:picolisp body params)) + ;; Wrap body appropriately for the type of evaluation and results. + (wrapped-body + (cond + ((or (member "code" result-params) + (member "pp" result-params)) + (format "(pretty (out \"/dev/null\" %s))" full-body)) + ((and (member "value" result-params) (not session)) + (format "(print (out \"/dev/null\" %s))" full-body)) + ((member "value" result-params) + (format "(out \"/dev/null\" %s)" full-body)) + (t full-body))) + (result + (if (not (string= session-name "none")) + ;; Session based evaluation. + (mapconcat ;; <- joins the list back into a single string + #'identity + (butlast ;; <- remove the org-babel-picolisp-eoe line + (delq nil + (mapcar + (lambda (line) + (org-babel-chomp ;; Remove trailing newlines. + (when (> (length line) 0) ;; Remove empty lines. + (cond + ;; Remove leading "-> " from return values. + ((and (>= (length line) 3) + (string= "-> " (substring line 0 3))) + (substring line 3)) + ;; Remove trailing "-> <>" on the + ;; last line of output. + ((and (member "output" result-params) + (string-match-p "->" line)) + (substring line 0 (string-match "->" line))) + (t line) + ) + ;;(if (and (>= (length line) 3);Remove leading "<-" + ;; (string= "-> " (substring line 0 3))) + ;; (substring line 3) + ;; line) + ))) + ;; Returns a list of the output of each evaluated exp. + (org-babel-comint-with-output + (session org-babel-picolisp-eoe) + (insert wrapped-body) (comint-send-input) + (insert "'" org-babel-picolisp-eoe) + (comint-send-input))))) + "\n") + ;; external evaluation + (let ((script-file (org-babel-temp-file "picolisp-script-"))) + (with-temp-file script-file + (insert (concat wrapped-body "(bye)"))) + (org-babel-eval + (format "%s %s" + org-babel-picolisp-cmd + (org-babel-process-file-name script-file)) + ""))))) + (org-babel-result-cond result-params + result + (read result)))) + +(defun org-babel-picolisp-initiate-session (&optional session-name) + "If there is not a current inferior-process-buffer in SESSION +then create. Return the initialized session." + (unless (string= session-name "none") + (require 'inferior-picolisp) + ;; provide a reasonable default session name + (let ((session (or session-name "*inferior-picolisp*"))) + ;; check if we already have a live session by this name + (if (org-babel-comint-buffer-livep session) + (get-buffer session) + (save-window-excursion + (run-picolisp org-babel-picolisp-cmd) + (rename-buffer session-name) + (current-buffer)))))) + +(provide 'ob-picolisp) + + + +;;; ob-picolisp.el ends here diff --git a/elpa/org-9.1.14/ob-plantuml.el b/elpa/org-9.1.14/ob-plantuml.el new file mode 100644 index 00000000..9a9313e7 --- /dev/null +++ b/elpa/org-9.1.14/ob-plantuml.el @@ -0,0 +1,126 @@ +;;; ob-plantuml.el --- Babel Functions for Plantuml -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Zhang Weize +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating plantuml script. +;; +;; Inspired by Ian Yang's org-export-blocks-format-plantuml +;; http://www.emacswiki.org/emacs/org-export-blocks-format-plantuml.el + +;;; Requirements: + +;; plantuml | http://plantuml.sourceforge.net/ +;; plantuml.jar | `org-plantuml-jar-path' should point to the jar file + +;;; Code: +(require 'ob) + +(defvar org-babel-default-header-args:plantuml + '((:results . "file") (:exports . "results")) + "Default arguments for evaluating a plantuml source block.") + +(defcustom org-plantuml-jar-path "" + "Path to the plantuml.jar file." + :group 'org-babel + :version "24.1" + :type 'string) + +(defun org-babel-variable-assignments:plantuml (params) + "Return a list of PlantUML statements assigning the block's variables. +PARAMS is a property list of source block parameters, which may +contain multiple entries for the key `:var'. `:var' entries in PARAMS +are expected to be scalar variables." + (mapcar + (lambda (pair) + (format "!define %s %s" + (car pair) + (replace-regexp-in-string "\"" "" (cdr pair)))) + (org-babel--get-vars params))) + +(defun org-babel-plantuml-make-body (body params) + "Return PlantUML input string. +BODY is the content of the source block and PARAMS is a property list +of source block parameters. This function relies on the +`org-babel-expand-body:generic' function to extract `:var' entries +from PARAMS and on the `org-babel-variable-assignments:plantuml' +function to convert variables to PlantUML assignments." + (concat + "@startuml\n" + (org-babel-expand-body:generic + body params (org-babel-variable-assignments:plantuml params)) + "\n@enduml")) + +(defun org-babel-execute:plantuml (body params) + "Execute a block of plantuml code with org-babel. +This function is called by `org-babel-execute-src-block'." + (let* ((out-file (or (cdr (assq :file params)) + (error "PlantUML requires a \":file\" header argument"))) + (cmdline (cdr (assq :cmdline params))) + (in-file (org-babel-temp-file "plantuml-")) + (java (or (cdr (assq :java params)) "")) + (full-body (org-babel-plantuml-make-body body params)) + (cmd (if (string= "" org-plantuml-jar-path) + (error "`org-plantuml-jar-path' is not set") + (concat "java " java " -jar " + (shell-quote-argument + (expand-file-name org-plantuml-jar-path)) + (if (string= (file-name-extension out-file) "png") + " -tpng" "") + (if (string= (file-name-extension out-file) "svg") + " -tsvg" "") + (if (string= (file-name-extension out-file) "eps") + " -teps" "") + (if (string= (file-name-extension out-file) "pdf") + " -tpdf" "") + (if (string= (file-name-extension out-file) "vdx") + " -tvdx" "") + (if (string= (file-name-extension out-file) "xmi") + " -txmi" "") + (if (string= (file-name-extension out-file) "scxml") + " -tscxml" "") + (if (string= (file-name-extension out-file) "html") + " -thtml" "") + (if (string= (file-name-extension out-file) "txt") + " -ttxt" "") + (if (string= (file-name-extension out-file) "utxt") + " -utxt" "") + " -p " cmdline " < " + (org-babel-process-file-name in-file) + " > " + (org-babel-process-file-name out-file))))) + (unless (file-exists-p org-plantuml-jar-path) + (error "Could not find plantuml.jar at %s" org-plantuml-jar-path)) + (with-temp-file in-file (insert full-body)) + (message "%s" cmd) (org-babel-eval cmd "") + nil)) ;; signal that output has already been written to file + +(defun org-babel-prep-session:plantuml (_session _params) + "Return an error because plantuml does not support sessions." + (error "Plantuml does not support sessions")) + +(provide 'ob-plantuml) + + + +;;; ob-plantuml.el ends here diff --git a/elpa/org-9.1.14/ob-processing.el b/elpa/org-9.1.14/ob-processing.el new file mode 100644 index 00000000..1a889302 --- /dev/null +++ b/elpa/org-9.1.14/ob-processing.el @@ -0,0 +1,195 @@ +;;; ob-processing.el --- Babel functions for processing -*- lexical-binding: t; -*- + +;; Copyright (C) 2015-2018 Free Software Foundation, Inc. + +;; Author: Jarmo Hurri (adapted from ob-asymptote.el written by Eric Schulte) +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Babel support for evaluating processing source code. +;; +;; This differs from most standard languages in that +;; +;; 1) there is no such thing as a "session" in processing +;; +;; 2) results can only be exported as html; in this case, the +;; processing code is embedded via a file into a javascript block +;; using the processing.js module; the script then draws the +;; resulting output when the web page is viewed in a browser; note +;; that the user is responsible for making sure that processing.js +;; is available on the website +;; +;; 3) it is possible to interactively view the sketch of the +;; Processing code block via Processing 2.0 Emacs mode, using +;; `org-babel-processing-view-sketch'. You can bind this command +;; to, e.g., C-c C-v C-k with +;; +;; (define-key org-babel-map (kbd "C-k") 'org-babel-processing-view-sketch) + + +;;; Requirements: + +;; - processing2-emacs mode :: https://github.com/ptrv/processing2-emacs +;; - Processing.js module :: http://processingjs.org/ + +;;; Code: +(require 'ob) +(require 'sha1) + +(declare-function processing-sketch-run "ext:processing-mode" ()) + +(defvar org-babel-temporary-directory) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("processing" . "pde")) + +;; Default header tags depend on whether exporting html or not; if not +;; exporting html, then no results are produced; otherwise results are +;; HTML. +(defvar org-babel-default-header-args:processing + '((:results . "html") (:exports . "results")) + "Default arguments when evaluating a Processing source block.") + +(defvar org-babel-processing-processing-js-filename "processing.js" + "Filename of the processing.js file.") + +(defun org-babel-processing-view-sketch () + "Show the sketch of the Processing block under point in an external viewer." + (interactive) + (require 'processing-mode) + (let ((info (org-babel-get-src-block-info))) + (if (string= (nth 0 info) "processing") + (let* ((body (nth 1 info)) + (params (org-babel-process-params (nth 2 info))) + (sketch-code + (org-babel-expand-body:generic + body + params + (org-babel-variable-assignments:processing params)))) + ;; Note: sketch filename can not contain a hyphen, since it + ;; has to be a valid java class name; for this reason + ;; make-temp-file is repeated until no hyphen is in the + ;; name; also sketch dir name must be the same as the + ;; basename of the sketch file. + (let* ((temporary-file-directory org-babel-temporary-directory) + (sketch-dir + (let (sketch-dir-candidate) + (while + (progn + (setq sketch-dir-candidate + (make-temp-file "processing" t)) + (when (string-match-p + "-" + (file-name-nondirectory sketch-dir-candidate)) + (delete-directory sketch-dir-candidate) + t))) + sketch-dir-candidate)) + (sketch-filename + (concat sketch-dir + "/" + (file-name-nondirectory sketch-dir) + ".pde"))) + (with-temp-file sketch-filename (insert sketch-code)) + (find-file sketch-filename) + (processing-sketch-run) + (kill-buffer))) + (message "Not inside a Processing source block.")))) + +(defun org-babel-execute:processing (body params) + "Execute a block of Processing code. +This function is called by `org-babel-execute-src-block'." + (let ((sketch-code + (org-babel-expand-body:generic + body + params + (org-babel-variable-assignments:processing params)))) + ;; Results are HTML. + (let ((sketch-canvas-id (concat "ob-" (sha1 sketch-code)))) + (concat "\n ")))) + +(defun org-babel-prep-session:processing (_session _params) + "Return an error if the :session header argument is set. +Processing does not support sessions" + (error "Processing does not support sessions")) + +(defun org-babel-variable-assignments:processing (params) + "Return list of processing statements assigning the block's variables." + (mapcar #'org-babel-processing-var-to-processing + (org-babel--get-vars params))) + +(defun org-babel-processing-var-to-processing (pair) + "Convert an elisp value into a Processing variable. +The elisp value PAIR is converted into Processing code specifying +a variable of the same value." + (let ((var (car pair)) + (val (let ((v (cdr pair))) + (if (symbolp v) (symbol-name v) v)))) + (cond + ((integerp val) + (format "int %S=%S;" var val)) + ((floatp val) + (format "float %S=%S;" var val)) + ((stringp val) + (format "String %S=\"%s\";" var val)) + ((and (listp val) (not (listp (car val)))) + (let* ((type (org-babel-processing-define-type val)) + (fmt (if (eq 'String type) "\"%s\"" "%s")) + (vect (mapconcat (lambda (e) (format fmt e)) val ", "))) + (format "%s[] %S={%s};" type var vect))) + ((listp val) + (let* ((type (org-babel-processing-define-type val)) + (fmt (if (eq 'String type) "\"%s\"" "%s")) + (array (mapconcat (lambda (row) + (concat "{" + (mapconcat (lambda (e) (format fmt e)) + row ", ") + "}")) + val ","))) + (format "%S[][] %S={%s};" type var array)))))) + +(defun org-babel-processing-define-type (data) + "Determine type of DATA. + +DATA is a list. Return type as a symbol. + +The type is `String' if any element in DATA is a string. +Otherwise, it is either `float', if some elements are floats, or +`int'." + (letrec ((type 'int) + (find-type + (lambda (row) + (dolist (e row type) + (cond ((listp e) (setq type (funcall find-type e))) + ((stringp e) (throw 'exit 'String)) + ((floatp e) (setq type 'float))))))) + (catch 'exit (funcall find-type data)))) + +(provide 'ob-processing) + +;;; ob-processing.el ends here diff --git a/elpa/org-9.1.14/ob-python.el b/elpa/org-9.1.14/ob-python.el new file mode 100644 index 00000000..a44e5a51 --- /dev/null +++ b/elpa/org-9.1.14/ob-python.el @@ -0,0 +1,375 @@ +;;; ob-python.el --- Babel Functions for Python -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Authors: Eric Schulte +;; Dan Davison +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating python source code. + +;;; Code: +(require 'ob) + +(declare-function org-remove-indentation "org" ) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function py-shell "ext:python-mode" (&optional argprompt)) +(declare-function py-toggle-shells "ext:python-mode" (arg)) +(declare-function run-python "ext:python" (&optional cmd dedicated show)) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("python" . "py")) + +(defvar org-babel-default-header-args:python '()) + +(defcustom org-babel-python-command "python" + "Name of the command for executing Python code." + :version "24.4" + :package-version '(Org . "8.0") + :group 'org-babel + :type 'string) + +(defcustom org-babel-python-mode + (if (featurep 'python-mode) 'python-mode 'python) + "Preferred python mode for use in running python interactively. +This will typically be either `python' or `python-mode'." + :group 'org-babel + :version "24.4" + :package-version '(Org . "8.0") + :type 'symbol) + +(defcustom org-babel-python-hline-to "None" + "Replace hlines in incoming tables with this when translating to python." + :group 'org-babel + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-babel-python-None-to 'hline + "Replace `None' in python tables with this before returning." + :group 'org-babel + :version "24.4" + :package-version '(Org . "8.0") + :type 'symbol) + +(defun org-babel-execute:python (body params) + "Execute a block of Python code with Babel. +This function is called by `org-babel-execute-src-block'." + (let* ((org-babel-python-command + (or (cdr (assq :python params)) + org-babel-python-command)) + (session (org-babel-python-initiate-session + (cdr (assq :session params)))) + (result-params (cdr (assq :result-params params))) + (result-type (cdr (assq :result-type params))) + (return-val (when (and (eq result-type 'value) (not session)) + (cdr (assq :return params)))) + (preamble (cdr (assq :preamble params))) + (full-body + (org-babel-expand-body:generic + (concat body (if return-val (format "\nreturn %s" return-val) "")) + params (org-babel-variable-assignments:python params))) + (result (org-babel-python-evaluate + session full-body result-type result-params preamble))) + (org-babel-reassemble-table + result + (org-babel-pick-name (cdr (assq :colname-names params)) + (cdr (assq :colnames params))) + (org-babel-pick-name (cdr (assq :rowname-names params)) + (cdr (assq :rownames params)))))) + +(defun org-babel-prep-session:python (session params) + "Prepare SESSION according to the header arguments in PARAMS. +VARS contains resolved variable references" + (let* ((session (org-babel-python-initiate-session session)) + (var-lines + (org-babel-variable-assignments:python params))) + (org-babel-comint-in-buffer session + (mapc (lambda (var) + (end-of-line 1) (insert var) (comint-send-input) + (org-babel-comint-wait-for-output session)) var-lines)) + session)) + +(defun org-babel-load-session:python (session body params) + "Load BODY into SESSION." + (save-window-excursion + (let ((buffer (org-babel-prep-session:python session params))) + (with-current-buffer buffer + (goto-char (process-mark (get-buffer-process (current-buffer)))) + (insert (org-babel-chomp body))) + buffer))) + +;; helper functions + +(defun org-babel-variable-assignments:python (params) + "Return a list of Python statements assigning the block's variables." + (mapcar + (lambda (pair) + (format "%s=%s" + (car pair) + (org-babel-python-var-to-python (cdr pair)))) + (org-babel--get-vars params))) + +(defun org-babel-python-var-to-python (var) + "Convert an elisp value to a python variable. +Convert an elisp value, VAR, into a string of python source code +specifying a variable of the same value." + (if (listp var) + (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]") + (if (eq var 'hline) + org-babel-python-hline-to + (format + (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S") + (if (stringp var) (substring-no-properties var) var))))) + +(defun org-babel-python-table-or-string (results) + "Convert RESULTS into an appropriate elisp value. +If the results look like a list or tuple, then convert them into an +Emacs-lisp table, otherwise return the results as a string." + (let ((res (org-babel-script-escape results))) + (if (listp res) + (mapcar (lambda (el) (if (eq el 'None) + org-babel-python-None-to el)) + res) + res))) + +(defvar org-babel-python-buffers '((:default . "*Python*"))) + +(defun org-babel-python-session-buffer (session) + "Return the buffer associated with SESSION." + (cdr (assoc session org-babel-python-buffers))) + +(defun org-babel-python-with-earmuffs (session) + (let ((name (if (stringp session) session (format "%s" session)))) + (if (and (string= "*" (substring name 0 1)) + (string= "*" (substring name (- (length name) 1)))) + name + (format "*%s*" name)))) + +(defun org-babel-python-without-earmuffs (session) + (let ((name (if (stringp session) session (format "%s" session)))) + (if (and (string= "*" (substring name 0 1)) + (string= "*" (substring name (- (length name) 1)))) + (substring name 1 (- (length name) 1)) + name))) + +(defvar py-default-interpreter) +(defvar py-which-bufname) +(defvar python-shell-buffer-name) +(defun org-babel-python-initiate-session-by-key (&optional session) + "Initiate a python session. +If there is not a current inferior-process-buffer in SESSION +then create. Return the initialized session." + (require org-babel-python-mode) + (save-window-excursion + (let* ((session (if session (intern session) :default)) + (python-buffer (org-babel-python-session-buffer session)) + (cmd (if (member system-type '(cygwin windows-nt ms-dos)) + (concat org-babel-python-command " -i") + org-babel-python-command))) + (cond + ((and (eq 'python org-babel-python-mode) + (fboundp 'run-python)) ; python.el + (if (not (version< "24.1" emacs-version)) + (run-python cmd) + (unless python-buffer + (setq python-buffer (org-babel-python-with-earmuffs session))) + (let ((python-shell-buffer-name + (org-babel-python-without-earmuffs python-buffer))) + (run-python cmd)))) + ((and (eq 'python-mode org-babel-python-mode) + (fboundp 'py-shell)) ; python-mode.el + ;; Make sure that py-which-bufname is initialized, as otherwise + ;; it will be overwritten the first time a Python buffer is + ;; created. + (py-toggle-shells py-default-interpreter) + ;; `py-shell' creates a buffer whose name is the value of + ;; `py-which-bufname' with '*'s at the beginning and end + (let* ((bufname (if (and python-buffer (buffer-live-p python-buffer)) + (replace-regexp-in-string ;; zap surrounding * + "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer) + (concat "Python-" (symbol-name session)))) + (py-which-bufname bufname)) + (py-shell) + (setq python-buffer (org-babel-python-with-earmuffs bufname)))) + (t + (error "No function available for running an inferior Python"))) + (setq org-babel-python-buffers + (cons (cons session python-buffer) + (assq-delete-all session org-babel-python-buffers))) + session))) + +(defun org-babel-python-initiate-session (&optional session _params) + "Create a session named SESSION according to PARAMS." + (unless (string= session "none") + (org-babel-python-session-buffer + (org-babel-python-initiate-session-by-key session)))) + +(defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'" + "A string to indicate that evaluation has completed.") +(defconst org-babel-python-wrapper-method + " +def main(): +%s + +open('%s', 'w').write( str(main()) )") +(defconst org-babel-python-pp-wrapper-method + " +import pprint +def main(): +%s + +open('%s', 'w').write( pprint.pformat(main()) )") + +(defconst org-babel-python--exec-tmpfile + (concat + "__org_babel_python_fname = '%s'; " + "__org_babel_python_fh = open(__org_babel_python_fname); " + "exec(compile(" + "__org_babel_python_fh.read(), __org_babel_python_fname, 'exec'" + ")); " + "__org_babel_python_fh.close()")) + +(defun org-babel-python-evaluate + (session body &optional result-type result-params preamble) + "Evaluate BODY as Python code." + (if session + (org-babel-python-evaluate-session + session body result-type result-params) + (org-babel-python-evaluate-external-process + body result-type result-params preamble))) + +(defun org-babel-python-evaluate-external-process + (body &optional result-type result-params preamble) + "Evaluate BODY in external python process. +If RESULT-TYPE equals `output' then return standard output as a +string. If RESULT-TYPE equals `value' then return the value of the +last statement in BODY, as elisp." + (let ((raw + (pcase result-type + (`output (org-babel-eval org-babel-python-command + (concat (if preamble (concat preamble "\n")) + body))) + (`value (let ((tmp-file (org-babel-temp-file "python-"))) + (org-babel-eval + org-babel-python-command + (concat + (if preamble (concat preamble "\n") "") + (format + (if (member "pp" result-params) + org-babel-python-pp-wrapper-method + org-babel-python-wrapper-method) + (mapconcat + (lambda (line) (format "\t%s" line)) + (split-string (org-remove-indentation (org-trim body)) + "[\r\n]") + "\n") + (org-babel-process-file-name tmp-file 'noquote)))) + (org-babel-eval-read-file tmp-file)))))) + (org-babel-result-cond result-params + raw + (org-babel-python-table-or-string (org-trim raw))))) + +(defun org-babel-python-evaluate-session + (session body &optional result-type result-params) + "Pass BODY to the Python process in SESSION. +If RESULT-TYPE equals `output' then return standard output as a +string. If RESULT-TYPE equals `value' then return the value of the +last statement in BODY, as elisp." + (let* ((send-wait (lambda () (comint-send-input nil t) (sleep-for 0 5))) + (dump-last-value + (lambda + (tmp-file pp) + (mapc + (lambda (statement) (insert statement) (funcall send-wait)) + (if pp + (list + "import pprint" + (format "open('%s', 'w').write(pprint.pformat(_))" + (org-babel-process-file-name tmp-file 'noquote))) + (list (format "open('%s', 'w').write(str(_))" + (org-babel-process-file-name tmp-file + 'noquote))))))) + (last-indent 0) + (input-body (lambda (body) + (dolist (line (split-string body "[\r\n]")) + ;; Insert a blank line to end an indent + ;; block. + (let ((curr-indent (string-match "\\S-" line))) + (if curr-indent + (progn + (when (< curr-indent last-indent) + (insert "") + (funcall send-wait)) + (setq last-indent curr-indent)) + (setq last-indent 0))) + (insert line) + (funcall send-wait)) + (funcall send-wait))) + (results + (pcase result-type + (`output + (let ((body (if (string-match-p ".\n+." body) ; Multiline + (let ((tmp-src-file (org-babel-temp-file + "python-"))) + (with-temp-file tmp-src-file (insert body)) + (format org-babel-python--exec-tmpfile + tmp-src-file)) + body))) + (mapconcat + #'org-trim + (butlast + (org-babel-comint-with-output + (session org-babel-python-eoe-indicator t body) + (funcall input-body body) + (funcall send-wait) (funcall send-wait) + (insert org-babel-python-eoe-indicator) + (funcall send-wait)) + 2) "\n"))) + (`value + (let ((tmp-file (org-babel-temp-file "python-"))) + (org-babel-comint-with-output + (session org-babel-python-eoe-indicator nil body) + (let ((comint-process-echoes nil)) + (funcall input-body body) + (funcall dump-last-value tmp-file + (member "pp" result-params)) + (funcall send-wait) (funcall send-wait) + (insert org-babel-python-eoe-indicator) + (funcall send-wait))) + (org-babel-eval-read-file tmp-file)))))) + (unless (string= (substring org-babel-python-eoe-indicator 1 -1) results) + (org-babel-result-cond result-params + results + (org-babel-python-table-or-string results))))) + +(defun org-babel-python-read-string (string) + "Strip \\='s from around Python string." + (if (and (string-prefix-p "'" string) + (string-suffix-p "'" string)) + (substring string 1 -1) + string)) + +(provide 'ob-python) + + + +;;; ob-python.el ends here diff --git a/elpa/org-9.1.14/ob-ref.el b/elpa/org-9.1.14/ob-ref.el new file mode 100644 index 00000000..3efa17f9 --- /dev/null +++ b/elpa/org-9.1.14/ob-ref.el @@ -0,0 +1,246 @@ +;;; ob-ref.el --- Babel Functions for Referencing External Data -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Authors: Eric Schulte +;; Dan Davison +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Functions for referencing data from the header arguments of a +;; org-babel block. The syntax of such a reference should be + +;; #+VAR: variable-name=file:resource-id + +;; - variable-name :: the name of the variable to which the value +;; will be assigned + +;; - file :: path to the file containing the resource, or omitted if +;; resource is in the current file + +;; - resource-id :: the id or name of the resource + +;; So an example of a simple src block referencing table data in the +;; same file would be + +;; #+NAME: sandbox +;; | 1 | 2 | 3 | +;; | 4 | org-babel | 6 | +;; +;; #+begin_src emacs-lisp :var table=sandbox +;; (message table) +;; #+end_src + +;;; Code: +(require 'ob-core) +(require 'cl-lib) + +(declare-function org-babel-lob-get-info "ob-lob" (&optional datum)) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-type "org-element" (element)) +(declare-function org-end-of-meta-data "org" (&optional full)) +(declare-function org-find-property "org" (property &optional value)) +(declare-function org-id-find-id-file "org-id" (id)) +(declare-function org-id-find-id-in-file "org-id" (id file &optional markerp)) +(declare-function org-in-commented-heading-p "org" (&optional no-inheritance)) +(declare-function org-narrow-to-subtree "org" ()) +(declare-function org-show-context "org" (&optional key)) +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-babel-update-intermediate nil + "Update the in-buffer results of code blocks executed to resolve references.") + +(defun org-babel-ref-parse (assignment) + "Parse a variable ASSIGNMENT in a header argument. + +If the right hand side of the assignment has a literal value +return that value, otherwise interpret it as a reference to an +external resource and find its value using `org-babel-ref-resolve'. + +Return a list with two elements: the name of the variable, and an +Emacs Lisp representation of the value of the variable." + (when (string-match "\\(.+?\\)=" assignment) + (let ((var (org-trim (match-string 1 assignment))) + (ref (org-trim (substring assignment (match-end 0))))) + (cons (intern var) + (let ((out (save-excursion + (when org-babel-current-src-block-location + (goto-char (if (markerp org-babel-current-src-block-location) + (marker-position org-babel-current-src-block-location) + org-babel-current-src-block-location))) + (org-babel-read ref)))) + (if (equal out ref) + (if (and (string-prefix-p "\"" ref) + (string-suffix-p "\"" ref)) + (read ref) + (org-babel-ref-resolve ref)) + out)))))) + +(defun org-babel-ref-goto-headline-id (id) + (or (let ((h (org-find-property "CUSTOM_ID" id))) + (when h (goto-char h))) + (let* ((file (org-id-find-id-file id)) + (m (when file (org-id-find-id-in-file id file 'marker)))) + (when (and file m) + (message "file:%S" file) + (pop-to-buffer-same-window (marker-buffer m)) + (goto-char m) + (move-marker m nil) + (org-show-context) + t)))) + +(defun org-babel-ref-headline-body () + (save-restriction + (org-narrow-to-subtree) + (buffer-substring + (save-excursion (goto-char (point-min)) + (org-end-of-meta-data) + (point)) + (point-max)))) + +(defvar org-babel-library-of-babel) +(defun org-babel-ref-resolve (ref) + "Resolve the reference REF and return its value." + (save-window-excursion + (with-current-buffer (or org-babel-exp-reference-buffer (current-buffer)) + (save-excursion + (let ((case-fold-search t) + args new-refere new-header-args new-referent split-file split-ref + index) + ;; if ref is indexed grab the indices -- beware nested indices + (when (and (string-match "\\[\\([^\\[]+\\)\\]$" ref) + (let ((str (substring ref 0 (match-beginning 0)))) + (= (cl-count ?\( str) (cl-count ?\) str)))) + (setq index (match-string 1 ref)) + (setq ref (substring ref 0 (match-beginning 0)))) + ;; assign any arguments to pass to source block + (when (string-match + "^\\(.+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\(.*\\))$" ref) + (setq new-refere (match-string 1 ref)) + (setq new-header-args (match-string 3 ref)) + (setq new-referent (match-string 5 ref)) + (when (> (length new-refere) 0) + (when (> (length new-referent) 0) + (setq args (mapcar (lambda (ref) (cons :var ref)) + (org-babel-ref-split-args new-referent)))) + (when (> (length new-header-args) 0) + (setq args (append (org-babel-parse-header-arguments + new-header-args) args))) + (setq ref new-refere))) + (when (string-match "^\\(.+\\):\\(.+\\)$" ref) + (setq split-file (match-string 1 ref)) + (setq split-ref (match-string 2 ref)) + (find-file split-file) + (setq ref split-ref)) + (org-with-wide-buffer + (goto-char (point-min)) + (let* ((params (append args '((:results . "silent")))) + (regexp (org-babel-named-data-regexp-for-name ref)) + (result + (catch :found + ;; Check for code blocks or named data. + (while (re-search-forward regexp nil t) + ;; Ignore COMMENTed headings and orphaned + ;; affiliated keywords. + (unless (org-in-commented-heading-p) + (let ((e (org-element-at-point))) + (when (equal (org-element-property :name e) ref) + (goto-char + (org-element-property :post-affiliated e)) + (pcase (org-element-type e) + (`babel-call + (throw :found + (org-babel-execute-src-block + nil (org-babel-lob-get-info e) params))) + (`src-block + (throw :found + (org-babel-execute-src-block + nil nil + (and + (not org-babel-update-intermediate) + params)))) + ((and (let v (org-babel-read-element e)) + (guard v)) + (throw :found v)) + (_ (error "Reference not found"))))))) + ;; Check for local or global headlines by ID. + (when (org-babel-ref-goto-headline-id ref) + (throw :found (org-babel-ref-headline-body))) + ;; Check the Library of Babel. + (let ((info (cdr (assq (intern ref) + org-babel-library-of-babel)))) + (when info + (throw :found + (org-babel-execute-src-block nil info params)))) + (error "Reference `%s' not found in this buffer" ref)))) + (cond + ((symbolp result) (format "%S" result)) + ((and index (listp result)) + (org-babel-ref-index-list index result)) + (t result))))))))) + +(defun org-babel-ref-index-list (index lis) + "Return the subset of LIS indexed by INDEX. + +Indices are 0 based and negative indices count from the end of +LIS, so 0 references the first element of LIS and -1 references +the last. If INDEX is separated by \",\"s then each \"portion\" +is assumed to index into the next deepest nesting or dimension. + +A valid \"portion\" can consist of either an integer index, two +integers separated by a \":\" in which case the entire range is +returned, or an empty string or \"*\" both of which are +interpreted to mean the entire range and as such are equivalent +to \"0:-1\"." + (if (and (> (length index) 0) (string-match "^\\([^,]*\\),?" index)) + (let* ((ind-re "\\(\\([-[:digit:]]+\\):\\([-[:digit:]]+\\)\\|\\*\\)") + (lgth (length lis)) + (portion (match-string 1 index)) + (remainder (substring index (match-end 0))) + (wrap (lambda (num) (if (< num 0) (+ lgth num) num))) + (open (lambda (ls) (if (and (listp ls) (= (length ls) 1)) (car ls) ls)))) + (funcall + open + (mapcar + (lambda (sub-lis) + (if (listp sub-lis) + (org-babel-ref-index-list remainder sub-lis) + sub-lis)) + (if (or (= 0 (length portion)) (string-match ind-re portion)) + (mapcar + (lambda (n) (nth n lis)) + (apply 'org-number-sequence + (if (and (> (length portion) 0) (match-string 2 portion)) + (list + (funcall wrap (string-to-number (match-string 2 portion))) + (funcall wrap (string-to-number (match-string 3 portion)))) + (list (funcall wrap 0) (funcall wrap -1))))) + (list (nth (funcall wrap (string-to-number portion)) lis)))))) + lis)) + +(defun org-babel-ref-split-args (arg-string) + "Split ARG-STRING into top-level arguments of balanced parenthesis." + (mapcar #'org-trim (org-babel-balanced-split arg-string 44))) + + +(provide 'ob-ref) + +;;; ob-ref.el ends here diff --git a/elpa/org-9.1.14/ob-ruby.el b/elpa/org-9.1.14/ob-ruby.el new file mode 100644 index 00000000..7686ac4e --- /dev/null +++ b/elpa/org-9.1.14/ob-ruby.el @@ -0,0 +1,268 @@ +;;; ob-ruby.el --- Babel Functions for Ruby -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating ruby source code. + +;;; Requirements: + +;; - ruby and irb executables :: http://www.ruby-lang.org/ +;; +;; - ruby-mode :: Can be installed through ELPA, or from +;; http://github.com/eschulte/rinari/raw/master/util/ruby-mode.el +;; +;; - inf-ruby mode :: Can be installed through ELPA, or from +;; http://github.com/eschulte/rinari/raw/master/util/inf-ruby.el + +;;; Code: +(require 'ob) + +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function run-ruby "ext:inf-ruby" (&optional command name)) +(declare-function xmp "ext:rcodetools" (&optional option)) + +(defvar inf-ruby-default-implementation) +(defvar inf-ruby-implementations) + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("ruby" . "rb")) + +(defvar org-babel-default-header-args:ruby '()) + +(defvar org-babel-ruby-command "ruby" + "Name of command to use for executing ruby code.") + +(defcustom org-babel-ruby-hline-to "nil" + "Replace hlines in incoming tables with this when translating to ruby." + :group 'org-babel + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-babel-ruby-nil-to 'hline + "Replace nil in ruby tables with this before returning." + :group 'org-babel + :version "24.4" + :package-version '(Org . "8.0") + :type 'symbol) + +(defun org-babel-execute:ruby (body params) + "Execute a block of Ruby code with Babel. +This function is called by `org-babel-execute-src-block'." + (let* ((session (org-babel-ruby-initiate-session + (cdr (assq :session params)))) + (result-params (cdr (assq :result-params params))) + (result-type (cdr (assq :result-type params))) + (full-body (org-babel-expand-body:generic + body params (org-babel-variable-assignments:ruby params))) + (result (if (member "xmp" result-params) + (with-temp-buffer + (require 'rcodetools) + (insert full-body) + (xmp (cdr (assq :xmp-option params))) + (buffer-string)) + (org-babel-ruby-evaluate + session full-body result-type result-params)))) + (org-babel-reassemble-table + (org-babel-result-cond result-params + result + (org-babel-ruby-table-or-string result)) + (org-babel-pick-name (cdr (assq :colname-names params)) + (cdr (assq :colnames params))) + (org-babel-pick-name (cdr (assq :rowname-names params)) + (cdr (assq :rownames params)))))) + +(defun org-babel-prep-session:ruby (session params) + "Prepare SESSION according to the header arguments specified in PARAMS." + ;; (message "params=%S" params) ;; debugging + (let* ((session (org-babel-ruby-initiate-session session)) + (var-lines (org-babel-variable-assignments:ruby params))) + (org-babel-comint-in-buffer session + (sit-for .5) (goto-char (point-max)) + (mapc (lambda (var) + (insert var) (comint-send-input nil t) + (org-babel-comint-wait-for-output session) + (sit-for .1) (goto-char (point-max))) var-lines)) + session)) + +(defun org-babel-load-session:ruby (session body params) + "Load BODY into SESSION." + (save-window-excursion + (let ((buffer (org-babel-prep-session:ruby session params))) + (with-current-buffer buffer + (goto-char (process-mark (get-buffer-process (current-buffer)))) + (insert (org-babel-chomp body))) + buffer))) + +;; helper functions + +(defun org-babel-variable-assignments:ruby (params) + "Return list of ruby statements assigning the block's variables." + (mapcar + (lambda (pair) + (format "%s=%s" + (car pair) + (org-babel-ruby-var-to-ruby (cdr pair)))) + (org-babel--get-vars params))) + +(defun org-babel-ruby-var-to-ruby (var) + "Convert VAR into a ruby variable. +Convert an elisp value into a string of ruby source code +specifying a variable of the same value." + (if (listp var) + (concat "[" (mapconcat #'org-babel-ruby-var-to-ruby var ", ") "]") + (if (eq var 'hline) + org-babel-ruby-hline-to + (format "%S" var)))) + +(defun org-babel-ruby-table-or-string (results) + "Convert RESULTS into an appropriate elisp value. +If RESULTS look like a table, then convert them into an +Emacs-lisp table, otherwise return the results as a string." + (let ((res (org-babel-script-escape results))) + (if (listp res) + (mapcar (lambda (el) (if (not el) + org-babel-ruby-nil-to el)) + res) + res))) + +(defun org-babel-ruby-initiate-session (&optional session _params) + "Initiate a ruby session. +If there is not a current inferior-process-buffer in SESSION +then create one. Return the initialized session." + (unless (string= session "none") + (require 'inf-ruby) + (let* ((cmd (cdr (assoc inf-ruby-default-implementation + inf-ruby-implementations))) + (buffer (get-buffer (format "*%s*" session))) + (session-buffer (or buffer (save-window-excursion + (run-ruby cmd session) + (current-buffer))))) + (if (org-babel-comint-buffer-livep session-buffer) + (progn (sit-for .25) session-buffer) + (sit-for .5) + (org-babel-ruby-initiate-session session))))) + +(defvar org-babel-ruby-eoe-indicator ":org_babel_ruby_eoe" + "String to indicate that evaluation has completed.") +(defvar org-babel-ruby-f-write + "File.open('%s','w'){|f| f.write((_.class == String) ? _ : _.inspect)}") +(defvar org-babel-ruby-pp-f-write + "File.open('%s','w'){|f| $stdout = f; pp(results); $stdout = orig_out}") +(defvar org-babel-ruby-wrapper-method + " +def main() +%s +end +results = main() +File.open('%s', 'w'){ |f| f.write((results.class == String) ? results : results.inspect) } +") +(defvar org-babel-ruby-pp-wrapper-method + " +require 'pp' +def main() +%s +end +results = main() +File.open('%s', 'w') do |f| + $stdout = f + pp results +end +") + +(defun org-babel-ruby-evaluate + (buffer body &optional result-type result-params) + "Pass BODY to the Ruby process in BUFFER. +If RESULT-TYPE equals `output' then return a list of the outputs +of the statements in BODY, if RESULT-TYPE equals `value' then +return the value of the last statement in BODY, as elisp." + (if (not buffer) + ;; external process evaluation + (pcase result-type + (`output (org-babel-eval org-babel-ruby-command body)) + (`value (let ((tmp-file (org-babel-temp-file "ruby-"))) + (org-babel-eval + org-babel-ruby-command + (format (if (member "pp" result-params) + org-babel-ruby-pp-wrapper-method + org-babel-ruby-wrapper-method) + body (org-babel-process-file-name tmp-file 'noquote))) + (org-babel-eval-read-file tmp-file)))) + ;; comint session evaluation + (pcase result-type + (`output + (let ((eoe-string (format "puts \"%s\"" org-babel-ruby-eoe-indicator))) + ;; Force the session to be ready before the actual session + ;; code is run. There is some problem in comint that will + ;; sometimes show the prompt after the the input has already + ;; been inserted and that throws off the extraction of the + ;; result for Babel. + (org-babel-comint-with-output + (buffer org-babel-ruby-eoe-indicator t eoe-string) + (insert eoe-string) (comint-send-input nil t)) + ;; Now we can start the evaluation. + (mapconcat + #'identity + (butlast + (split-string + (mapconcat + #'org-trim + (org-babel-comint-with-output + (buffer org-babel-ruby-eoe-indicator t body) + (mapc + (lambda (line) + (insert (org-babel-chomp line)) (comint-send-input nil t)) + (list "conf.echo=false;_org_prompt_mode=conf.prompt_mode;conf.prompt_mode=:NULL" + body + "conf.prompt_mode=_org_prompt_mode;conf.echo=true" + eoe-string))) + "\n") "[\r\n]") 4) "\n"))) + (`value + (let* ((tmp-file (org-babel-temp-file "ruby-")) + (ppp (or (member "code" result-params) + (member "pp" result-params)))) + (org-babel-comint-with-output + (buffer org-babel-ruby-eoe-indicator t body) + (when ppp (insert "require 'pp';") (comint-send-input nil t)) + (mapc + (lambda (line) + (insert (org-babel-chomp line)) (comint-send-input nil t)) + (append + (list body) + (if (not ppp) + (list (format org-babel-ruby-f-write + (org-babel-process-file-name tmp-file 'noquote))) + (list + "results=_" "require 'pp'" "orig_out = $stdout" + (format org-babel-ruby-pp-f-write + (org-babel-process-file-name tmp-file 'noquote)))) + (list org-babel-ruby-eoe-indicator))) + (comint-send-input nil t)) + (org-babel-eval-read-file tmp-file)))))) + +(provide 'ob-ruby) + + + +;;; ob-ruby.el ends here diff --git a/elpa/org-9.1.14/ob-sass.el b/elpa/org-9.1.14/ob-sass.el new file mode 100644 index 00000000..af55d763 --- /dev/null +++ b/elpa/org-9.1.14/ob-sass.el @@ -0,0 +1,70 @@ +;;; ob-sass.el --- Babel Functions for the Sass CSS generation language -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; For more information on sass see http://sass-lang.com/ +;; +;; This accepts a 'file' header argument which is the target of the +;; compiled sass. The default output type for sass evaluation is +;; either file (if a 'file' header argument was given) or scalar if no +;; such header argument was supplied. +;; +;; A 'cmdline' header argument can be supplied to pass arguments to +;; the sass command line. + +;;; Requirements: + +;; - sass-mode :: http://github.com/nex3/haml/blob/master/extra/sass-mode.el + +;;; Code: +(require 'ob) + +(defvar org-babel-default-header-args:sass '()) + +(defun org-babel-execute:sass (body params) + "Execute a block of Sass code with Babel. +This function is called by `org-babel-execute-src-block'." + (let* ((file (cdr (assq :file params))) + (out-file (or file (org-babel-temp-file "sass-out-"))) + (cmdline (cdr (assq :cmdline params))) + (in-file (org-babel-temp-file "sass-in-")) + (cmd (concat "sass " (or cmdline "") + " " (org-babel-process-file-name in-file) + " " (org-babel-process-file-name out-file)))) + (with-temp-file in-file + (insert (org-babel-expand-body:generic body params))) + (org-babel-eval cmd "") + (if file + nil ;; signal that output has already been written to file + (with-temp-buffer (insert-file-contents out-file) (buffer-string))))) + +(defun org-babel-prep-session:sass (_session _params) + "Raise an error because sass does not support sessions." + (error "Sass does not support sessions")) + +(provide 'ob-sass) + + + +;;; ob-sass.el ends here diff --git a/elpa/org-9.1.14/ob-scheme.el b/elpa/org-9.1.14/ob-scheme.el new file mode 100644 index 00000000..0efe5f34 --- /dev/null +++ b/elpa/org-9.1.14/ob-scheme.el @@ -0,0 +1,233 @@ +;;; ob-scheme.el --- Babel Functions for Scheme -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Authors: Eric Schulte +;; Michael Gauland +;; Keywords: literate programming, reproducible research, scheme +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Now working with SBCL for both session and external evaluation. +;; +;; This certainly isn't optimally robust, but it seems to be working +;; for the basic use cases. + +;;; Requirements: + +;; - a working scheme implementation +;; (e.g. guile https://www.gnu.org/software/guile/guile.html) +;; +;; - for session based evaluation geiser is required, which is available from +;; ELPA. + +;;; Code: +(require 'ob) +(require 'geiser nil t) +(require 'geiser-impl nil t) +(defvar geiser-repl--repl) ; Defined in geiser-repl.el +(defvar geiser-impl--implementation) ; Defined in geiser-impl.el +(defvar geiser-default-implementation) ; Defined in geiser-impl.el +(defvar geiser-active-implementations) ; Defined in geiser-impl.el +(defvar geiser-debug-show-debug-p) ; Defined in geiser-debug.el +(defvar geiser-debug-jump-to-debug-p) ; Defined in geiser-debug.el +(defvar geiser-repl-use-other-window) ; Defined in geiser-repl.el +(defvar geiser-repl-window-allow-split) ; Defined in geiser-repl.el + +(declare-function run-geiser "ext:geiser-repl" (impl)) +(declare-function geiser-mode "ext:geiser-mode" ()) +(declare-function geiser-eval-region "ext:geiser-mode" + (start end &optional and-go raw nomsg)) +(declare-function geiser-repl-exit "ext:geiser-repl" (&optional arg)) +(declare-function geiser-eval--retort-output "ext:geiser-eval" (ret)) +(declare-function geiser-eval--retort-result-str "ext:geiser-eval" (ret prefix)) + +(defcustom org-babel-scheme-null-to 'hline + "Replace `null' and empty lists in scheme tables with this before returning." + :group 'org-babel + :version "26.1" + :package-version '(Org . "9.1") + :type 'symbol) + +(defvar org-babel-default-header-args:scheme '() + "Default header arguments for scheme code blocks.") + +(defun org-babel-expand-body:scheme (body params) + "Expand BODY according to PARAMS, return the expanded body." + (let ((vars (org-babel--get-vars params)) + (prepends (cdr (assq :prologue params)))) + (concat (and prepends (concat prepends "\n")) + (if (null vars) body + (format "(let (%s)\n%s\n)" + (mapconcat + (lambda (var) + (format "%S" (print `(,(car var) ',(cdr var))))) + vars + "\n ") + body))))) + + +(defvar org-babel-scheme-repl-map (make-hash-table :test #'equal) + "Map of scheme sessions to session names.") + +(defun org-babel-scheme-cleanse-repl-map () + "Remove dead buffers from the REPL map." + (maphash + (lambda (x y) (unless (buffer-name y) (remhash x org-babel-scheme-repl-map))) + org-babel-scheme-repl-map)) + +(defun org-babel-scheme-get-session-buffer (session-name) + "Look up the scheme buffer for a session; return nil if it doesn't exist." + (org-babel-scheme-cleanse-repl-map) ; Prune dead sessions + (gethash session-name org-babel-scheme-repl-map)) + +(defun org-babel-scheme-set-session-buffer (session-name buffer) + "Record the scheme buffer used for a given session." + (puthash session-name buffer org-babel-scheme-repl-map)) + +(defun org-babel-scheme-get-buffer-impl (buffer) + "Returns the scheme implementation geiser associates with the buffer." + (with-current-buffer (set-buffer buffer) + geiser-impl--implementation)) + +(defun org-babel-scheme-get-repl (impl name) + "Switch to a scheme REPL, creating it if it doesn't exist:" + (let ((buffer (org-babel-scheme-get-session-buffer name))) + (or buffer + (progn + (run-geiser impl) + (if name + (progn + (rename-buffer name t) + (org-babel-scheme-set-session-buffer name (current-buffer)))) + (current-buffer))))) + +(defun org-babel-scheme-make-session-name (buffer name impl) + "Generate a name for the session buffer. + +For a named session, the buffer name will be the session name. + +If the session is unnamed (nil), generate a name. + +If the session is `none', use nil for the session name, and +org-babel-scheme-execute-with-geiser will use a temporary session." + (cond ((not name) (concat buffer " " (symbol-name impl) " REPL")) + ((string= name "none") nil) + (name))) + +(defmacro org-babel-scheme-capture-current-message (&rest body) + "Capture current message in both interactive and noninteractive mode" + `(if noninteractive + (let ((original-message (symbol-function 'message)) + (current-message nil)) + (unwind-protect + (progn + (defun message (&rest args) + (setq current-message (apply original-message args))) + ,@body + current-message) + (fset 'message original-message))) + (progn + ,@body + (current-message)))) + +(defun org-babel-scheme-execute-with-geiser (code output impl repl) + "Execute code in specified REPL. If the REPL doesn't exist, create it +using the given scheme implementation. + +Returns the output of executing the code if the output parameter +is true; otherwise returns the last value." + (let ((result nil)) + (with-temp-buffer + (insert (format ";; -*- geiser-scheme-implementation: %s -*-" impl)) + (newline) + (insert code) + (geiser-mode) + (let ((geiser-repl-window-allow-split nil) + (geiser-repl-use-other-window nil)) + (let ((repl-buffer (save-current-buffer + (org-babel-scheme-get-repl impl repl)))) + (when (not (eq impl (org-babel-scheme-get-buffer-impl + (current-buffer)))) + (message "Implementation mismatch: %s (%s) %s (%s)" impl (symbolp impl) + (org-babel-scheme-get-buffer-impl (current-buffer)) + (symbolp (org-babel-scheme-get-buffer-impl + (current-buffer))))) + (setq geiser-repl--repl repl-buffer) + (setq geiser-impl--implementation nil) + (let ((geiser-debug-jump-to-debug-p nil) + (geiser-debug-show-debug-p nil)) + (let ((ret (geiser-eval-region (point-min) (point-max)))) + (setq result (if output + (geiser-eval--retort-output ret) + (geiser-eval--retort-result-str ret ""))))) + (when (not repl) + (save-current-buffer (set-buffer repl-buffer) + (geiser-repl-exit)) + (set-process-query-on-exit-flag (get-buffer-process repl-buffer) nil) + (kill-buffer repl-buffer))))) + result)) + +(defun org-babel-scheme--table-or-string (results) + "Convert RESULTS into an appropriate elisp value. +If the results look like a list or tuple, then convert them into an +Emacs-lisp table, otherwise return the results as a string." + (let ((res (org-babel-script-escape results))) + (cond ((listp res) + (mapcar (lambda (el) + (if (or (null el) (eq el 'null)) + org-babel-scheme-null-to + el)) + res)) + (t res)))) + +(defun org-babel-execute:scheme (body params) + "Execute a block of Scheme code with org-babel. +This function is called by `org-babel-execute-src-block'" + (let* ((source-buffer (current-buffer)) + (source-buffer-name (replace-regexp-in-string ;; zap surrounding * + "^ ?\\*\\([^*]+\\)\\*" "\\1" + (buffer-name source-buffer)))) + (save-excursion + (let* ((result-type (cdr (assq :result-type params))) + (impl (or (when (cdr (assq :scheme params)) + (intern (cdr (assq :scheme params)))) + geiser-default-implementation + (car geiser-active-implementations))) + (session (org-babel-scheme-make-session-name + source-buffer-name (cdr (assq :session params)) impl)) + (full-body (org-babel-expand-body:scheme body params)) + (result + (org-babel-scheme-execute-with-geiser + full-body ; code + (string= result-type "output") ; output? + impl ; implementation + (and (not (string= session "none")) session)))) ; session + (let ((table + (org-babel-reassemble-table + result + (org-babel-pick-name (cdr (assq :colname-names params)) + (cdr (assq :colnames params))) + (org-babel-pick-name (cdr (assq :rowname-names params)) + (cdr (assq :rownames params)))))) + (org-babel-scheme--table-or-string table)))))) + +(provide 'ob-scheme) + +;;; ob-scheme.el ends here diff --git a/elpa/org-9.1.14/ob-screen.el b/elpa/org-9.1.14/ob-screen.el new file mode 100644 index 00000000..fb7c8e2d --- /dev/null +++ b/elpa/org-9.1.14/ob-screen.el @@ -0,0 +1,143 @@ +;;; ob-screen.el --- Babel Support for Interactive Terminal -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Benjamin Andresen +;; Keywords: literate programming, interactive shell +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for interactive terminals. Mostly shell scripts. +;; Heavily inspired by 'eev' from Eduardo Ochs +;; +;; Adding :cmd and :terminal as header arguments +;; :terminal must support the -T (title) and -e (command) parameter +;; +;; You can test the default setup. (xterm + sh) with +;; M-x org-babel-screen-test RET + +;;; Code: +(require 'ob) + +(defvar org-babel-screen-location "screen" + "The command location for screen. +In case you want to use a different screen than one selected by your $PATH") + +(defvar org-babel-default-header-args:screen + '((:results . "silent") (:session . "default") (:cmd . "sh") (:terminal . "xterm")) + "Default arguments to use when running screen source blocks.") + +(defun org-babel-execute:screen (body params) + "Send a block of code via screen to a terminal using Babel. +\"default\" session is used when none is specified." + (message "Sending source code block to interactive terminal session...") + (save-window-excursion + (let* ((session (cdr (assq :session params))) + (socket (org-babel-screen-session-socketname session))) + (unless socket (org-babel-prep-session:screen session params)) + (org-babel-screen-session-execute-string + session (org-babel-expand-body:generic body params))))) + +(defun org-babel-prep-session:screen (_session params) + "Prepare SESSION according to the header arguments specified in PARAMS." + (let* ((session (cdr (assq :session params))) + (cmd (cdr (assq :cmd params))) + (terminal (cdr (assq :terminal params))) + (process-name (concat "org-babel: terminal (" session ")"))) + (apply 'start-process process-name "*Messages*" + terminal `("-T" ,(concat "org-babel: " session) "-e" ,org-babel-screen-location + "-c" "/dev/null" "-mS" ,(concat "org-babel-session-" session) + ,cmd)) + ;; XXX: Is there a better way than the following? + (while (not (org-babel-screen-session-socketname session)) + ;; wait until screen session is available before returning + ))) + +;; helper functions + +(defun org-babel-screen-session-execute-string (session body) + "If SESSION exists, send BODY to it." + (let ((socket (org-babel-screen-session-socketname session))) + (when socket + (let ((tmpfile (org-babel-screen-session-write-temp-file session body))) + (apply 'start-process (concat "org-babel: screen (" session ")") "*Messages*" + org-babel-screen-location + `("-S" ,socket "-X" "eval" "msgwait 0" + ,(concat "readreg z " tmpfile) + "paste z")))))) + +(defun org-babel-screen-session-socketname (session) + "Check if SESSION exists by parsing output of \"screen -ls\"." + (let* ((screen-ls (shell-command-to-string "screen -ls")) + (sockets (delq + nil + (mapcar + (lambda (x) + (when (string-match (rx (or "(Attached)" "(Detached)")) x) + x)) + (split-string screen-ls "\n")))) + (match-socket (car + (delq + nil + (mapcar + (lambda (x) + (when (string-match + (concat "org-babel-session-" session) x) + x)) + sockets))))) + (when match-socket (car (split-string match-socket))))) + +(defun org-babel-screen-session-write-temp-file (_session body) + "Save BODY in a temp file that is named after SESSION." + (let ((tmpfile (org-babel-temp-file "screen-"))) + (with-temp-file tmpfile + (insert body) + + ;; org-babel has superfluous spaces + (goto-char (point-min)) + (delete-matching-lines "^ +$")) + tmpfile)) + +(defun org-babel-screen-test () + "Test if the default setup works. +The terminal should shortly flicker." + (interactive) + (let* ((random-string (format "%s" (random 99999))) + (tmpfile (org-babel-temp-file "ob-screen-test-")) + (body (concat "echo '" random-string "' > " tmpfile "\nexit\n")) + tmp-string) + (org-babel-execute:screen body org-babel-default-header-args:screen) + ;; XXX: need to find a better way to do the following + (while (not (file-readable-p tmpfile)) + ;; do something, otherwise this will be optimized away + (format "org-babel-screen: File not readable yet.")) + (setq tmp-string (with-temp-buffer + (insert-file-contents-literally tmpfile) + (buffer-substring (point-min) (point-max)))) + (delete-file tmpfile) + (message (concat "org-babel-screen: Setup " + (if (string-match random-string tmp-string) + "WORKS." + "DOESN'T work."))))) + +(provide 'ob-screen) + + + +;;; ob-screen.el ends here diff --git a/elpa/org-9.1.14/ob-sed.el b/elpa/org-9.1.14/ob-sed.el new file mode 100644 index 00000000..ca8b7545 --- /dev/null +++ b/elpa/org-9.1.14/ob-sed.el @@ -0,0 +1,105 @@ +;;; ob-sed.el --- Babel Functions for Sed Scripts -*- lexical-binding: t; -*- + +;; Copyright (C) 2015-2018 Free Software Foundation, Inc. + +;; Author: Bjarte Johansen +;; Keywords: literate programming, reproducible research +;; Version: 0.1.1 + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Provides a way to evaluate sed scripts in Org mode. + +;;; Usage: + +;; Add to your Emacs config: + +;; (org-babel-do-load-languages +;; 'org-babel-load-languages +;; '((sed . t))) + +;; In addition to the normal header arguments, ob-sed also provides +;; :cmd-line and :in-file. :cmd-line allows one to pass other flags to +;; the sed command like the "--in-place" flag which makes sed edit the +;; file pass to it instead of outputting to standard out or to a +;; different file. :in-file is a header arguments that allows one to +;; tell Org Babel which file the sed script to act on. + +;;; Code: +(require 'ob) + +(defvar org-babel-sed-command "sed" + "Name of the sed executable command.") + +(defvar org-babel-tangle-lang-exts) +(add-to-list 'org-babel-tangle-lang-exts '("sed" . "sed")) + +(defconst org-babel-header-args:sed + '((:cmd-line . :any) + (:in-file . :any)) + "Sed specific header arguments.") + +(defvar org-babel-default-header-args:sed '() + "Default arguments for evaluating a sed source block.") + +(defun org-babel-execute:sed (body params) + "Execute a block of sed code with Org Babel. +BODY is the source inside a sed source block and PARAMS is an +association list over the source block configurations. This +function is called by `org-babel-execute-src-block'." + (message "executing sed source code block") + (let* ((result-params (cdr (assq :result-params params))) + (cmd-line (cdr (assq :cmd-line params))) + (in-file (cdr (assq :in-file params))) + (code-file (let ((file (org-babel-temp-file "sed-"))) + (with-temp-file file + (insert body)) file)) + (stdin (let ((stdin (cdr (assq :stdin params)))) + (when stdin + (let ((tmp (org-babel-temp-file "sed-stdin-")) + (res (org-babel-ref-resolve stdin))) + (with-temp-file tmp + (insert res)) + tmp)))) + (cmd (mapconcat #'identity + (remq nil + (list org-babel-sed-command + (format "-f \"%s\"" code-file) + cmd-line + in-file)) + " "))) + (org-babel-reassemble-table + (let ((results + (cond + (stdin (with-temp-buffer + (call-process-shell-command cmd stdin (current-buffer)) + (buffer-string))) + (t (org-babel-eval cmd ""))))) + (when results + (org-babel-result-cond result-params + results + (let ((tmp (org-babel-temp-file "sed-results-"))) + (with-temp-file tmp (insert results)) + (org-babel-import-elisp-from-file tmp))))) + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))) + +(provide 'ob-sed) +;;; ob-sed.el ends here diff --git a/elpa/org-9.1.14/ob-shell.el b/elpa/org-9.1.14/ob-shell.el new file mode 100644 index 00000000..362dfd52 --- /dev/null +++ b/elpa/org-9.1.14/ob-shell.el @@ -0,0 +1,283 @@ +;;; ob-shell.el --- Babel Functions for Shell Evaluation -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating shell source code. + +;;; Code: +(require 'ob) +(require 'shell) +(require 'cl-lib) + +(declare-function org-babel-comint-in-buffer "ob-comint" (buffer &rest body) + t) +(declare-function org-babel-comint-wait-for-output "ob-comint" (buffer)) +(declare-function org-babel-comint-buffer-livep "ob-comint" (buffer)) +(declare-function org-babel-comint-with-output "ob-comint" (meta &rest body) + t) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function orgtbl-to-generic "org-table" (table params)) + +(defvar org-babel-default-header-args:shell '()) +(defvar org-babel-shell-names) + +(defun org-babel-shell-initialize () + "Define execution functions associated to shell names. +This function has to be called whenever `org-babel-shell-names' +is modified outside the Customize interface." + (interactive) + (dolist (name org-babel-shell-names) + (eval `(defun ,(intern (concat "org-babel-execute:" name)) + (body params) + ,(format "Execute a block of %s commands with Babel." name) + (let ((shell-file-name ,name)) + (org-babel-execute:shell body params)))) + (eval `(defalias ',(intern (concat "org-babel-variable-assignments:" name)) + 'org-babel-variable-assignments:shell + ,(format "Return list of %s statements assigning to the block's \ +variables." + name))))) + +(defcustom org-babel-shell-names + '("sh" "bash" "csh" "ash" "dash" "ksh" "mksh" "posh") + "List of names of shell supported by babel shell code blocks. +Call `org-babel-shell-initialize' when modifying this variable +outside the Customize interface." + :group 'org-babel + :type '(repeat (string :tag "Shell name: ")) + :set (lambda (symbol value) + (set-default symbol value) + (org-babel-shell-initialize))) + +(defun org-babel-execute:shell (body params) + "Execute a block of Shell commands with Babel. +This function is called by `org-babel-execute-src-block'." + (let* ((session (org-babel-sh-initiate-session + (cdr (assq :session params)))) + (stdin (let ((stdin (cdr (assq :stdin params)))) + (when stdin (org-babel-sh-var-to-string + (org-babel-ref-resolve stdin))))) + (cmdline (cdr (assq :cmdline params))) + (full-body (org-babel-expand-body:generic + body params (org-babel-variable-assignments:shell params)))) + (org-babel-reassemble-table + (org-babel-sh-evaluate session full-body params stdin cmdline) + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))) + +(defun org-babel-prep-session:shell (session params) + "Prepare SESSION according to the header arguments specified in PARAMS." + (let* ((session (org-babel-sh-initiate-session session)) + (var-lines (org-babel-variable-assignments:shell params))) + (org-babel-comint-in-buffer session + (mapc (lambda (var) + (insert var) (comint-send-input nil t) + (org-babel-comint-wait-for-output session)) var-lines)) + session)) + +(defun org-babel-load-session:shell (session body params) + "Load BODY into SESSION." + (save-window-excursion + (let ((buffer (org-babel-prep-session:shell session params))) + (with-current-buffer buffer + (goto-char (process-mark (get-buffer-process (current-buffer)))) + (insert (org-babel-chomp body))) + buffer))) + + +;;; Helper functions +(defun org-babel--variable-assignments:sh-generic + (varname values &optional sep hline) + "Returns a list of statements declaring the values as a generic variable." + (format "%s=%s" varname (org-babel-sh-var-to-sh values sep hline))) + +(defun org-babel--variable-assignments:bash_array + (varname values &optional sep hline) + "Returns a list of statements declaring the values as a bash array." + (format "unset %s\ndeclare -a %s=( %s )" + varname varname + (mapconcat + (lambda (value) (org-babel-sh-var-to-sh value sep hline)) + values + " "))) + +(defun org-babel--variable-assignments:bash_assoc + (varname values &optional sep hline) + "Returns a list of statements declaring the values as bash associative array." + (format "unset %s\ndeclare -A %s\n%s" + varname varname + (mapconcat + (lambda (items) + (format "%s[%s]=%s" + varname + (org-babel-sh-var-to-sh (car items) sep hline) + (org-babel-sh-var-to-sh (cdr items) sep hline))) + values + "\n"))) + +(defun org-babel--variable-assignments:bash (varname values &optional sep hline) + "Represents the parameters as useful Bash shell variables." + (pcase values + (`((,_ ,_ . ,_) . ,_) ;two-dimensional array + (org-babel--variable-assignments:bash_assoc varname values sep hline)) + (`(,_ . ,_) ;simple list + (org-babel--variable-assignments:bash_array varname values sep hline)) + (_ ;scalar value + (org-babel--variable-assignments:sh-generic varname values sep hline)))) + +(defun org-babel-variable-assignments:shell (params) + "Return list of shell statements assigning the block's variables." + (let ((sep (cdr (assq :separator params))) + (hline (when (string= "yes" (cdr (assq :hlines params))) + (or (cdr (assq :hline-string params)) + "hline")))) + (mapcar + (lambda (pair) + (if (string-suffix-p "bash" shell-file-name) + (org-babel--variable-assignments:bash + (car pair) (cdr pair) sep hline) + (org-babel--variable-assignments:sh-generic + (car pair) (cdr pair) sep hline))) + (org-babel--get-vars params)))) + +(defun org-babel-sh-var-to-sh (var &optional sep hline) + "Convert an elisp value to a shell variable. +Convert an elisp var into a string of shell commands specifying a +var of the same value." + (concat "'" (replace-regexp-in-string + "'" "'\"'\"'" + (org-babel-sh-var-to-string var sep hline)) + "'")) + +(defun org-babel-sh-var-to-string (var &optional sep hline) + "Convert an elisp value to a string." + (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v))))) + (cond + ((and (listp var) (or (listp (car var)) (eq (car var) 'hline))) + (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var + :hline hline))) + ((listp var) + (mapconcat echo-var var "\n")) + (t (funcall echo-var var))))) + +(defun org-babel-sh-initiate-session (&optional session _params) + "Initiate a session named SESSION according to PARAMS." + (when (and session (not (string= session "none"))) + (save-window-excursion + (or (org-babel-comint-buffer-livep session) + (progn + (shell session) + ;; Needed for Emacs 23 since the marker is initially + ;; undefined and the filter functions try to use it without + ;; checking. + (set-marker comint-last-output-start (point)) + (get-buffer (current-buffer))))))) + +(defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'" + "String to indicate that evaluation has completed.") +(defvar org-babel-sh-eoe-output "org_babel_sh_eoe" + "String to indicate that evaluation has completed.") + +(defun org-babel-sh-evaluate (session body &optional params stdin cmdline) + "Pass BODY to the Shell process in BUFFER. +If RESULT-TYPE equals `output' then return a list of the outputs +of the statements in BODY, if RESULT-TYPE equals `value' then +return the value of the last statement in BODY." + (let ((results + (cond + ((or stdin cmdline) ; external shell script w/STDIN + (let ((script-file (org-babel-temp-file "sh-script-")) + (stdin-file (org-babel-temp-file "sh-stdin-")) + (shebang (cdr (assq :shebang params))) + (padline (not (string= "no" (cdr (assq :padline params)))))) + (with-temp-file script-file + (when shebang (insert (concat shebang "\n"))) + (when padline (insert "\n")) + (insert body)) + (set-file-modes script-file #o755) + (with-temp-file stdin-file (insert (or stdin ""))) + (with-temp-buffer + (call-process-shell-command + (concat (if shebang script-file + (format "%s %s" shell-file-name script-file)) + (and cmdline (concat " " cmdline))) + stdin-file + (current-buffer)) + (buffer-string)))) + (session ; session evaluation + (mapconcat + #'org-babel-sh-strip-weird-long-prompt + (mapcar + #'org-trim + (butlast + (org-babel-comint-with-output + (session org-babel-sh-eoe-output t body) + (mapc + (lambda (line) + (insert line) + (comint-send-input nil t) + (while (save-excursion + (goto-char comint-last-input-end) + (not (re-search-forward + comint-prompt-regexp nil t))) + (accept-process-output + (get-buffer-process (current-buffer))))) + (append + (split-string (org-trim body) "\n") + (list org-babel-sh-eoe-indicator)))) + 2)) "\n")) + ('otherwise ; external shell script + (if (and (cdr (assq :shebang params)) + (> (length (cdr (assq :shebang params))) 0)) + (let ((script-file (org-babel-temp-file "sh-script-")) + (shebang (cdr (assq :shebang params))) + (padline (not (equal "no" (cdr (assq :padline params)))))) + (with-temp-file script-file + (when shebang (insert (concat shebang "\n"))) + (when padline (insert "\n")) + (insert body)) + (set-file-modes script-file #o755) + (org-babel-eval script-file "")) + (org-babel-eval shell-file-name (org-trim body))))))) + (when results + (let ((result-params (cdr (assq :result-params params)))) + (org-babel-result-cond result-params + results + (let ((tmp-file (org-babel-temp-file "sh-"))) + (with-temp-file tmp-file (insert results)) + (org-babel-import-elisp-from-file tmp-file))))))) + +(defun org-babel-sh-strip-weird-long-prompt (string) + "Remove prompt cruft from a string of shell output." + (while (string-match "^% +[\r\n$]+ *" string) + (setq string (substring string (match-end 0)))) + string) + +(provide 'ob-shell) + + + +;;; ob-shell.el ends here diff --git a/elpa/org-9.1.14/ob-shen.el b/elpa/org-9.1.14/ob-shen.el new file mode 100644 index 00000000..d81e7d60 --- /dev/null +++ b/elpa/org-9.1.14/ob-shen.el @@ -0,0 +1,78 @@ +;;; ob-shen.el --- Babel Functions for Shen -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research, shen +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Currently this only works using session evaluation as there is no +;; defined method for executing shen code outside of a session. + +;;; Requirements: + +;; - shen-mode and inf-shen will soon be available through the GNU +;; elpa, however in the interim they are available at +;; https://github.com/eschulte/shen-mode + +;;; Code: +(require 'ob) + +(declare-function shen-eval-defun "ext:inf-shen" (&optional and-go)) +(declare-function org-babel-ruby-var-to-ruby "ob-ruby" (var)) + +(defvar org-babel-default-header-args:shen '() + "Default header arguments for shen code blocks.") + +(defun org-babel-expand-body:shen (body params) + "Expand BODY according to PARAMS, return the expanded body." + (let ((vars (org-babel--get-vars params))) + (if (> (length vars) 0) + (concat "(let " + (mapconcat (lambda (var) + (format "%s %s" (car var) + (org-babel-shen-var-to-shen (cdr var)))) + vars " ") + body ")") + body))) + +(defun org-babel-shen-var-to-shen (var) + "Convert VAR into a shen variable." + (if (listp var) + (concat "[" (mapconcat #'org-babel-ruby-var-to-ruby var " ") "]") + (format "%S" var))) + +(defun org-babel-execute:shen (body params) + "Execute a block of Shen code with org-babel. +This function is called by `org-babel-execute-src-block'" + (require 'inf-shen) + (let* ((result-params (cdr (assq :result-params params))) + (full-body (org-babel-expand-body:shen body params))) + (let ((results + (with-temp-buffer + (insert full-body) + (call-interactively #'shen-eval-defun)))) + (org-babel-result-cond result-params + results + (condition-case nil (org-babel-script-escape results) + (error results)))))) + +(provide 'ob-shen) +;;; ob-shen.el ends here diff --git a/elpa/org-9.1.14/ob-sql.el b/elpa/org-9.1.14/ob-sql.el new file mode 100644 index 00000000..959ede3d --- /dev/null +++ b/elpa/org-9.1.14/ob-sql.el @@ -0,0 +1,332 @@ +;;; ob-sql.el --- Babel Functions for SQL -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating sql source code. +;; (see also ob-sqlite.el) +;; +;; SQL is somewhat unique in that there are many different engines for +;; the evaluation of sql (Mysql, PostgreSQL, etc...), so much of this +;; file will have to be implemented engine by engine. +;; +;; Also SQL evaluation generally takes place inside of a database. +;; +;; Header args used: +;; - engine +;; - cmdline +;; - dbhost +;; - dbport +;; - dbuser +;; - dbpassword +;; - database +;; - colnames (default, nil, means "yes") +;; - result-params +;; - out-file +;; +;; The following are used but not really implemented for SQL: +;; - colname-names +;; - rownames +;; - rowname-names +;; +;; Engines supported: +;; - mysql +;; - dbi +;; - mssql +;; - sqsh +;; - postgresql +;; - oracle +;; - vertica +;; +;; TODO: +;; +;; - support for sessions +;; - support for more engines +;; - what's a reasonable way to drop table data into SQL? +;; + +;;; Code: +(require 'ob) + +(declare-function org-table-import "org-table" (file arg)) +(declare-function orgtbl-to-csv "org-table" (table params)) +(declare-function org-table-to-lisp "org-table" (&optional txt)) +(declare-function cygwin-convert-file-name-to-windows "cygw32.c" (file &optional absolute-p)) + +(defvar org-babel-default-header-args:sql '()) + +(defconst org-babel-header-args:sql + '((engine . :any) + (out-file . :any) + (dbhost . :any) + (dbport . :any) + (dbuser . :any) + (dbpassword . :any) + (database . :any)) + "SQL-specific header arguments.") + +(defun org-babel-expand-body:sql (body params) + "Expand BODY according to the values of PARAMS." + (org-babel-sql-expand-vars + body (org-babel--get-vars params))) + +(defun org-babel-sql-dbstring-mysql (host port user password database) + "Make MySQL cmd line args for database connection. Pass nil to omit that arg." + (combine-and-quote-strings + (delq nil + (list (when host (concat "-h" host)) + (when port (format "-P%d" port)) + (when user (concat "-u" user)) + (when password (concat "-p" password)) + (when database (concat "-D" database)))))) + +(defun org-babel-sql-dbstring-postgresql (host port user database) + "Make PostgreSQL command line args for database connection. +Pass nil to omit that arg." + (combine-and-quote-strings + (delq nil + (list (when host (concat "-h" host)) + (when port (format "-p%d" port)) + (when user (concat "-U" user)) + (when database (concat "-d" database)))))) + +(defun org-babel-sql-dbstring-oracle (host port user password database) + "Make Oracle command line args for database connection." + (format "%s/%s@%s:%s/%s" user password host port database)) + +(defun org-babel-sql-dbstring-mssql (host user password database) + "Make sqlcmd command line args for database connection. +`sqlcmd' is the preferred command line tool to access Microsoft +SQL Server on Windows and Linux platform." + (mapconcat #'identity + (delq nil + (list (when host (format "-S \"%s\"" host)) + (when user (format "-U \"%s\"" user)) + (when password (format "-P \"%s\"" password)) + (when database (format "-d \"%s\"" database)))) + " ")) + +(defun org-babel-sql-dbstring-sqsh (host user password database) + "Make sqsh command line args for database connection. +\"sqsh\" is one method to access Sybase or MS SQL via Linux platform" + (mapconcat #'identity + (delq nil + (list (when host (format "-S \"%s\"" host)) + (when user (format "-U \"%s\"" user)) + (when password (format "-P \"%s\"" password)) + (when database (format "-D \"%s\"" database)))) + " ")) + +(defun org-babel-sql-dbstring-vertica (host port user password database) + "Make Vertica command line args for database connection. Pass nil to omit that arg." + (mapconcat #'identity + (delq nil + (list (when host (format "-h %s" host)) + (when port (format "-p %d" port)) + (when user (format "-U %s" user)) + (when password (format "-w %s" (shell-quote-argument password) )) + (when database (format "-d %s" database)))) + " ")) + +(defun org-babel-sql-convert-standard-filename (file) + "Convert FILE to OS standard file name. +If in Cygwin environment, uses Cygwin specific function to +convert the file name. In a Windows-NT environment, do nothing. +Otherwise, use Emacs' standard conversion function." + (cond ((fboundp 'cygwin-convert-file-name-to-windows) + (format "%S" (cygwin-convert-file-name-to-windows file))) + ((string= "windows-nt" system-type) file) + (t (format "%S" (convert-standard-filename file))))) + +(defun org-babel-execute:sql (body params) + "Execute a block of Sql code with Babel. +This function is called by `org-babel-execute-src-block'." + (let* ((result-params (cdr (assq :result-params params))) + (cmdline (cdr (assq :cmdline params))) + (dbhost (cdr (assq :dbhost params))) + (dbport (cdr (assq :dbport params))) + (dbuser (cdr (assq :dbuser params))) + (dbpassword (cdr (assq :dbpassword params))) + (database (cdr (assq :database params))) + (engine (cdr (assq :engine params))) + (colnames-p (not (equal "no" (cdr (assq :colnames params))))) + (in-file (org-babel-temp-file "sql-in-")) + (out-file (or (cdr (assq :out-file params)) + (org-babel-temp-file "sql-out-"))) + (header-delim "") + (command (pcase (intern engine) + (`dbi (format "dbish --batch %s < %s | sed '%s' > %s" + (or cmdline "") + (org-babel-process-file-name in-file) + "/^+/d;s/^|//;s/(NULL)/ /g;$d" + (org-babel-process-file-name out-file))) + (`monetdb (format "mclient -f tab %s < %s > %s" + (or cmdline "") + (org-babel-process-file-name in-file) + (org-babel-process-file-name out-file))) + (`mssql (format "sqlcmd %s -s \"\t\" %s -i %s -o %s" + (or cmdline "") + (org-babel-sql-dbstring-mssql + dbhost dbuser dbpassword database) + (org-babel-sql-convert-standard-filename + (org-babel-process-file-name in-file)) + (org-babel-sql-convert-standard-filename + (org-babel-process-file-name out-file)))) + (`mysql (format "mysql %s %s %s < %s > %s" + (org-babel-sql-dbstring-mysql + dbhost dbport dbuser dbpassword database) + (if colnames-p "" "-N") + (or cmdline "") + (org-babel-process-file-name in-file) + (org-babel-process-file-name out-file))) + (`postgresql (format + "%spsql --set=\"ON_ERROR_STOP=1\" %s -A -P \ +footer=off -F \"\t\" %s -f %s -o %s %s" + (if dbpassword + (format "PGPASSWORD=%s " dbpassword) + "") + (if colnames-p "" "-t") + (org-babel-sql-dbstring-postgresql + dbhost dbport dbuser database) + (org-babel-process-file-name in-file) + (org-babel-process-file-name out-file) + (or cmdline ""))) + (`sqsh (format "sqsh %s %s -i %s -o %s -m csv" + (or cmdline "") + (org-babel-sql-dbstring-sqsh + dbhost dbuser dbpassword database) + (org-babel-sql-convert-standard-filename + (org-babel-process-file-name in-file)) + (org-babel-sql-convert-standard-filename + (org-babel-process-file-name out-file)))) + (`vertica (format "vsql %s -f %s -o %s %s" + (org-babel-sql-dbstring-vertica + dbhost dbport dbuser dbpassword database) + (org-babel-process-file-name in-file) + (org-babel-process-file-name out-file) + (or cmdline ""))) + (`oracle (format + "sqlplus -s %s < %s > %s" + (org-babel-sql-dbstring-oracle + dbhost dbport dbuser dbpassword database) + (org-babel-process-file-name in-file) + (org-babel-process-file-name out-file))) + (_ (error "No support for the %s SQL engine" engine))))) + (with-temp-file in-file + (insert + (pcase (intern engine) + (`dbi "/format partbox\n") + (`oracle "SET PAGESIZE 50000 +SET NEWPAGE 0 +SET TAB OFF +SET SPACE 0 +SET LINESIZE 9999 +SET ECHO OFF +SET FEEDBACK OFF +SET VERIFY OFF +SET HEADING ON +SET MARKUP HTML OFF SPOOL OFF +SET COLSEP '|' + +") + ((or `mssql `sqsh) "SET NOCOUNT ON + +") + (`vertica "\\a\n") + (_ "")) + (org-babel-expand-body:sql body params) + ;; "sqsh" requires "go" inserted at EOF. + (if (string= engine "sqsh") "\ngo" ""))) + (org-babel-eval command "") + (org-babel-result-cond result-params + (with-temp-buffer + (progn (insert-file-contents-literally out-file) (buffer-string))) + (with-temp-buffer + (cond + ((memq (intern engine) '(dbi mysql postgresql sqsh vertica)) + ;; Add header row delimiter after column-names header in first line + (cond + (colnames-p + (with-temp-buffer + (insert-file-contents out-file) + (goto-char (point-min)) + (forward-line 1) + (insert "-\n") + (setq header-delim "-") + (write-file out-file))))) + (t + ;; Need to figure out the delimiter for the header row + (with-temp-buffer + (insert-file-contents out-file) + (goto-char (point-min)) + (when (re-search-forward "^\\(-+\\)[^-]" nil t) + (setq header-delim (match-string-no-properties 1))) + (goto-char (point-max)) + (forward-char -1) + (while (looking-at "\n") + (delete-char 1) + (goto-char (point-max)) + (forward-char -1)) + (write-file out-file)))) + (org-table-import out-file (if (string= engine "sqsh") '(4) '(16))) + (org-babel-reassemble-table + (mapcar (lambda (x) + (if (string= (car x) header-delim) + 'hline + x)) + (org-table-to-lisp)) + (org-babel-pick-name (cdr (assq :colname-names params)) + (cdr (assq :colnames params))) + (org-babel-pick-name (cdr (assq :rowname-names params)) + (cdr (assq :rownames params)))))))) + +(defun org-babel-sql-expand-vars (body vars) + "Expand the variables held in VARS in BODY." + (mapc + (lambda (pair) + (setq body + (replace-regexp-in-string + (format "$%s" (car pair)) + (let ((val (cdr pair))) + (if (listp val) + (let ((data-file (org-babel-temp-file "sql-data-"))) + (with-temp-file data-file + (insert (orgtbl-to-csv + val '(:fmt (lambda (el) (if (stringp el) + el + (format "%S" el))))))) + data-file) + (if (stringp val) val (format "%S" val)))) + body))) + vars) + body) + +(defun org-babel-prep-session:sql (_session _params) + "Raise an error because Sql sessions aren't implemented." + (error "SQL sessions not yet implemented")) + +(provide 'ob-sql) + + + +;;; ob-sql.el ends here diff --git a/elpa/org-9.1.14/ob-sqlite.el b/elpa/org-9.1.14/ob-sqlite.el new file mode 100644 index 00000000..42528a38 --- /dev/null +++ b/elpa/org-9.1.14/ob-sqlite.el @@ -0,0 +1,158 @@ +;;; ob-sqlite.el --- Babel Functions for SQLite Databases -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating sqlite source code. + +;;; Code: +(require 'ob) + +(declare-function org-fill-template "org" (template alist)) +(declare-function org-table-convert-region "org-table" + (beg0 end0 &optional separator)) +(declare-function orgtbl-to-csv "org-table" (table params)) +(declare-function org-table-to-lisp "org-table" (&optional txt)) + +(defvar org-babel-default-header-args:sqlite '()) + +(defvar org-babel-header-args:sqlite + '((db . :any) + (header . :any) + (echo . :any) + (bail . :any) + (csv . :any) + (column . :any) + (html . :any) + (line . :any) + (list . :any) + (separator . :any) + (nullvalue . :any)) + "Sqlite specific header args.") + +(defun org-babel-expand-body:sqlite (body params) + "Expand BODY according to the values of PARAMS." + (org-babel-sqlite-expand-vars + body (org-babel--get-vars params))) + +(defvar org-babel-sqlite3-command "sqlite3") + +(defun org-babel-execute:sqlite (body params) + "Execute a block of Sqlite code with Babel. +This function is called by `org-babel-execute-src-block'." + (let ((result-params (split-string (or (cdr (assq :results params)) ""))) + (db (cdr (assq :db params))) + (separator (cdr (assq :separator params))) + (nullvalue (cdr (assq :nullvalue params))) + (headers-p (equal "yes" (cdr (assq :colnames params)))) + (others (delq nil (mapcar + (lambda (arg) (car (assq arg params))) + (list :header :echo :bail :column + :csv :html :line :list))))) + (unless db (error "ob-sqlite: can't evaluate without a database")) + (with-temp-buffer + (insert + (org-babel-eval + (org-fill-template + "%cmd %header %separator %nullvalue %others %csv %db " + (list + (cons "cmd" org-babel-sqlite3-command) + (cons "header" (if headers-p "-header" "-noheader")) + (cons "separator" + (if separator (format "-separator %s" separator) "")) + (cons "nullvalue" + (if nullvalue (format "-nullvalue %s" nullvalue) "")) + (cons "others" + (mapconcat + (lambda (arg) (format "-%s" (substring (symbol-name arg) 1))) + others " ")) + ;; for easy table parsing, default header type should be -csv + (cons "csv" (if (or (member :csv others) (member :column others) + (member :line others) (member :list others) + (member :html others) separator) + "" + "-csv")) + (cons "db " db))) + ;; body of the code block + (org-babel-expand-body:sqlite body params))) + (org-babel-result-cond result-params + (buffer-string) + (if (equal (point-min) (point-max)) + "" + (org-table-convert-region (point-min) (point-max) + (if (or (member :csv others) + (member :column others) + (member :line others) + (member :list others) + (member :html others) separator) + nil + '(4))) + (org-babel-sqlite-table-or-scalar + (org-babel-sqlite-offset-colnames + (org-table-to-lisp) headers-p))))))) + +(defun org-babel-sqlite-expand-vars (body vars) + "Expand the variables held in VARS in BODY." + ;; FIXME: Redundancy with org-babel-sql-expand-vars! + (mapc + (lambda (pair) + (setq body + (replace-regexp-in-string + (format "$%s" (car pair)) + (let ((val (cdr pair))) + (if (listp val) + (let ((data-file (org-babel-temp-file "sqlite-data-"))) + (with-temp-file data-file + (insert (orgtbl-to-csv val nil))) + data-file) + (if (stringp val) val (format "%S" val)))) + body))) + vars) + body) + +(defun org-babel-sqlite-table-or-scalar (result) + "If RESULT looks like a trivial table, then unwrap it." + (if (and (equal 1 (length result)) + (equal 1 (length (car result)))) + (org-babel-read (caar result)) + (mapcar (lambda (row) + (if (eq 'hline row) + 'hline + (mapcar #'org-babel-string-read row))) result))) + +(defun org-babel-sqlite-offset-colnames (table headers-p) + "If HEADERS-P is non-nil then offset the first row as column names." + (if headers-p + (cons (car table) (cons 'hline (cdr table))) + table)) + +(defun org-babel-prep-session:sqlite (_session _params) + "Raise an error because support for SQLite sessions isn't implemented. +Prepare SESSION according to the header arguments specified in PARAMS." + (error "SQLite sessions not yet implemented")) + +(provide 'ob-sqlite) + + + +;;; ob-sqlite.el ends here diff --git a/elpa/org-9.1.14/ob-stan.el b/elpa/org-9.1.14/ob-stan.el new file mode 100644 index 00000000..ffc26818 --- /dev/null +++ b/elpa/org-9.1.14/ob-stan.el @@ -0,0 +1,85 @@ +;;; ob-stan.el --- Babel Functions for Stan -*- lexical-binding: t; -*- + +;; Copyright (C) 2015-2018 Free Software Foundation, Inc. + +;; Author: Kyle Meyer +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Org-Babel support for evaluating Stan [1] source code. +;; +;; Evaluating a Stan block can produce two different results. +;; +;; 1) Dump the source code contents to a file. +;; +;; This file can then be used as a variable in other blocks, which +;; allows interfaces like RStan to use the model. +;; +;; 2) Compile the contents to a model file. +;; +;; This provides access to the CmdStan interface. To use this, set +;; `org-babel-stan-cmdstan-directory' and provide a :file argument +;; that does not end in ".stan". +;; +;; For more information and usage examples, visit +;; https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-stan.html +;; +;; [1] http://mc-stan.org/ + +;;; Code: +(require 'ob) +(require 'org-compat) + +(defcustom org-babel-stan-cmdstan-directory nil + "CmdStan source directory. +Call \"make\" from this directory to compile the Stan block. +When nil, executing Stan blocks dumps the content to a file." + :group 'org-babel + :type '(choice + (directory :tag "Compilation directory") + (const :tag "Dump to a file" nil))) + +(defvar org-babel-default-header-args:stan + '((:results . "file"))) + +(defun org-babel-execute:stan (body params) + "Generate Stan file from BODY according to PARAMS. +A :file header argument must be given. If +`org-babel-stan-cmdstan-directory' is non-nil and the file name +does not have a \".stan\" extension, save an intermediate +\".stan\" file and compile the block to the named file. +Otherwise, write the Stan code directly to the named file." + (let ((file (expand-file-name + (or (cdr (assq :file params)) + (user-error "Set :file argument to execute Stan blocks"))))) + (if (or (not org-babel-stan-cmdstan-directory) + (string-match-p "\\.stan\\'" file)) + (with-temp-file file (insert body)) + (with-temp-file (concat file ".stan") (insert body)) + (let ((default-directory org-babel-stan-cmdstan-directory)) + (call-process-shell-command (concat "make " file)))) + nil)) ; Signal that output has been written to file. + +(defun org-babel-prep-session:stan (_session _params) + "Return an error because Stan does not support sessions." + (user-error "Stan does not support sessions")) + +(provide 'ob-stan) +;;; ob-stan.el ends here diff --git a/elpa/org-9.1.14/ob-table.el b/elpa/org-9.1.14/ob-table.el new file mode 100644 index 00000000..f6a5c88e --- /dev/null +++ b/elpa/org-9.1.14/ob-table.el @@ -0,0 +1,153 @@ +;;; ob-table.el --- Support for Calling Babel Functions from Tables -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Should allow calling functions from Org tables using the function +;; `org-sbe' as so... + +;; #+begin_src emacs-lisp :results silent +;; (defun fibbd (n) (if (< n 2) 1 (+ (fibbd (- n 1)) (fibbd (- n 2))))) +;; #+end_src + +;; #+name: fibbd +;; #+begin_src emacs-lisp :var n=2 :results silent +;; (fibbd n) +;; #+end_src + +;; | original | fibbd | +;; |----------+--------| +;; | 0 | | +;; | 1 | | +;; | 2 | | +;; | 3 | | +;; | 4 | | +;; | 5 | | +;; | 6 | | +;; | 7 | | +;; | 8 | | +;; | 9 | | +;; #+TBLFM: $2='(org-sbe "fibbd" (n $1)) + +;; NOTE: The quotation marks around the function name, 'fibbd' here, +;; are optional. + +;;; Code: +(require 'ob-core) + +(declare-function org-trim "org" (s &optional keep-lead)) + +(defun org-babel-table-truncate-at-newline (string) + "Replace newline character with ellipses. +If STRING ends in a newline character, then remove the newline +character and replace it with ellipses." + (if (and (stringp string) (string-match "[\n\r]\\(.\\)?" string)) + (concat (substring string 0 (match-beginning 0)) + (when (match-string 1 string) "...")) string)) + +(defmacro org-sbe (source-block &rest variables) + "Return the results of calling SOURCE-BLOCK with VARIABLES. + +Each element of VARIABLES should be a list of two elements: the +first element is the name of the variable and second element is a +string of its value. + +So this `org-sbe' construct + + (org-sbe \"source-block\" (n $2) (m 3)) + +is the equivalent of the following source code block: + + #+begin_src emacs-lisp :var results=source-block(n=val_at_col_2, m=3) :results silent + results + #+end_src + +NOTE: The quotation marks around the function name, +'source-block', are optional. + +NOTE: By default, string variable names are interpreted as +references to source-code blocks, to force interpretation of a +cell's value as a string, prefix the identifier a \"$\" (e.g., +\"$$2\" instead of \"$2\" or \"$@2$2\" instead of \"@2$2\"). + +NOTE: It is also possible to pass header arguments to the code +block. In this case a table cell should hold the string value of +the header argument which can then be passed before all variables +as shown in the example below. + +| 1 | 2 | :file nothing.png | nothing.png | +#+TBLFM: @1$4=\\='(org-sbe test-sbe $3 (x $1) (y $2))" + (declare (debug (form form))) + (let* ((header-args (if (stringp (car variables)) (car variables) "")) + (variables (if (stringp (car variables)) (cdr variables) variables))) + (let* (quote + (variables + (mapcar + (lambda (var) + ;; ensure that all cells prefixed with $'s are strings + (cons (car var) + (delq nil (mapcar + (lambda (el) + (if (eq '$ el) + (prog1 nil (setq quote t)) + (prog1 + (cond + (quote (format "\"%s\"" el)) + ((stringp el) (org-no-properties el)) + (t el)) + (setq quote nil)))) + (cdr var))))) + variables))) + (unless (stringp source-block) + (setq source-block (symbol-name source-block))) + (let ((result + (if (and source-block (> (length source-block) 0)) + (let ((params + ;; FIXME: Why `eval'?!?!? + (eval `(org-babel-parse-header-arguments + (concat + ":var results=" + ,source-block + "[" ,header-args "]" + "(" + (mapconcat + (lambda (var-spec) + (if (> (length (cdr var-spec)) 1) + (format "%S='%S" + (car var-spec) + (mapcar #'read (cdr var-spec))) + (format "%S=%s" + (car var-spec) (cadr var-spec)))) + ',variables ", ") + ")"))))) + (org-babel-execute-src-block + nil (list "emacs-lisp" "results" params) + '((:results . "silent")))) + ""))) + (org-trim (if (stringp result) result (format "%S" result))))))) + +(provide 'ob-table) + + + +;;; ob-table.el ends here diff --git a/elpa/org-9.1.14/ob-tangle.el b/elpa/org-9.1.14/ob-tangle.el new file mode 100644 index 00000000..48eddb73 --- /dev/null +++ b/elpa/org-9.1.14/ob-tangle.el @@ -0,0 +1,601 @@ +;;; ob-tangle.el --- Extract Source Code From Org Files -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Extract the code from source blocks out into raw source-code files. + +;;; Code: + +(require 'cl-lib) +(require 'org-src) +(require 'org-macs) + +(declare-function make-directory "files" (dir &optional parents)) +(declare-function org-at-heading-p "org" (&optional ignored)) +(declare-function org-babel-update-block-body "ob-core" (new-body)) +(declare-function org-back-to-heading "org" (&optional invisible-ok)) +(declare-function org-before-first-heading-p "org" ()) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-type "org-element" (element)) +(declare-function org-fill-template "org" (template alist)) +(declare-function org-heading-components "org" ()) +(declare-function org-in-commented-heading-p "org" (&optional no-inheritance)) +(declare-function org-link-escape "org" (text &optional table merge)) +(declare-function org-open-link-from-string "org" (s &optional arg reference-buffer)) +(declare-function org-remove-indentation "org" (code &optional n)) +(declare-function org-store-link "org" (arg)) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function outline-previous-heading "outline" ()) +(declare-function org-id-find "org-id" (id &optional markerp)) + +(defvar org-link-types-re) + +(defcustom org-babel-tangle-lang-exts + '(("emacs-lisp" . "el") + ("elisp" . "el")) + "Alist mapping languages to their file extensions. +The key is the language name, the value is the string that should +be inserted as the extension commonly used to identify files +written in this language. If no entry is found in this list, +then the name of the language is used." + :group 'org-babel-tangle + :version "24.1" + :type '(repeat + (cons + (string "Language name") + (string "File Extension")))) + +(defcustom org-babel-tangle-use-relative-file-links t + "Use relative path names in links from tangled source back the Org file." + :group 'org-babel-tangle + :type 'boolean) + +(defcustom org-babel-post-tangle-hook nil + "Hook run in code files tangled by `org-babel-tangle'." + :group 'org-babel + :version "24.1" + :type 'hook) + +(defcustom org-babel-pre-tangle-hook '(save-buffer) + "Hook run at the beginning of `org-babel-tangle'." + :group 'org-babel + :version "24.1" + :type 'hook) + +(defcustom org-babel-tangle-body-hook nil + "Hook run over the contents of each code block body." + :group 'org-babel + :version "24.1" + :type 'hook) + +(defcustom org-babel-tangle-comment-format-beg "[[%link][%source-name]]" + "Format of inserted comments in tangled code files. +The following format strings can be used to insert special +information into the output using `org-fill-template'. +%start-line --- the line number at the start of the code block +%file --------- the file from which the code block was tangled +%link --------- Org style link to the code block +%source-name -- name of the code block + +Upon insertion the formatted comment will be commented out, and +followed by a newline. To inhibit this post-insertion processing +set the `org-babel-tangle-uncomment-comments' variable to a +non-nil value. + +Whether or not comments are inserted during tangling is +controlled by the :comments header argument." + :group 'org-babel + :version "24.1" + :type 'string) + +(defcustom org-babel-tangle-comment-format-end "%source-name ends here" + "Format of inserted comments in tangled code files. +The following format strings can be used to insert special +information into the output using `org-fill-template'. +%start-line --- the line number at the start of the code block +%file --------- the file from which the code block was tangled +%link --------- Org style link to the code block +%source-name -- name of the code block + +Upon insertion the formatted comment will be commented out, and +followed by a newline. To inhibit this post-insertion processing +set the `org-babel-tangle-uncomment-comments' variable to a +non-nil value. + +Whether or not comments are inserted during tangling is +controlled by the :comments header argument." + :group 'org-babel + :version "24.1" + :type 'string) + +(defcustom org-babel-tangle-uncomment-comments nil + "Inhibits automatic commenting and addition of trailing newline +of tangle comments. Use `org-babel-tangle-comment-format-beg' +and `org-babel-tangle-comment-format-end' to customize the format +of tangled comments." + :group 'org-babel + :type 'boolean) + +(defcustom org-babel-process-comment-text 'org-remove-indentation + "Function called to process raw Org text collected to be +inserted as comments in tangled source-code files. The function +should take a single string argument and return a string +result. The default value is `org-remove-indentation'." + :group 'org-babel + :version "24.1" + :type 'function) + +(defun org-babel-find-file-noselect-refresh (file) + "Find file ensuring that the latest changes on disk are +represented in the file." + (find-file-noselect file 'nowarn) + (with-current-buffer (get-file-buffer file) + (revert-buffer t t t))) + +(defmacro org-babel-with-temp-filebuffer (file &rest body) + "Open FILE into a temporary buffer execute BODY there like +`progn', then kill the FILE buffer returning the result of +evaluating BODY." + (declare (indent 1)) + (let ((temp-path (make-symbol "temp-path")) + (temp-result (make-symbol "temp-result")) + (temp-file (make-symbol "temp-file")) + (visited-p (make-symbol "visited-p"))) + `(let* ((,temp-path ,file) + (,visited-p (get-file-buffer ,temp-path)) + ,temp-result ,temp-file) + (org-babel-find-file-noselect-refresh ,temp-path) + (setf ,temp-file (get-file-buffer ,temp-path)) + (with-current-buffer ,temp-file + (setf ,temp-result (progn ,@body))) + (unless ,visited-p (kill-buffer ,temp-file)) + ,temp-result))) +(def-edebug-spec org-babel-with-temp-filebuffer (form body)) + +;;;###autoload +(defun org-babel-tangle-file (file &optional target-file lang) + "Extract the bodies of source code blocks in FILE. +Source code blocks are extracted with `org-babel-tangle'. +Optional argument TARGET-FILE can be used to specify a default +export file for all source blocks. Optional argument LANG can be +used to limit the exported source code blocks by language. +Return a list whose CAR is the tangled file name." + (interactive "fFile to tangle: \nP") + (let ((visited-p (get-file-buffer (expand-file-name file))) + to-be-removed) + (prog1 + (save-window-excursion + (find-file file) + (setq to-be-removed (current-buffer)) + (mapcar #'expand-file-name (org-babel-tangle nil target-file lang))) + (unless visited-p + (kill-buffer to-be-removed))))) + +(defun org-babel-tangle-publish (_ filename pub-dir) + "Tangle FILENAME and place the results in PUB-DIR." + (unless (file-exists-p pub-dir) + (make-directory pub-dir t)) + (setq pub-dir (file-name-as-directory pub-dir)) + (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename))) + +;;;###autoload +(defun org-babel-tangle (&optional arg target-file lang) + "Write code blocks to source-specific files. +Extract the bodies of all source code blocks from the current +file into their own source-specific files. +With one universal prefix argument, only tangle the block at point. +When two universal prefix arguments, only tangle blocks for the +tangle file of the block at point. +Optional argument TARGET-FILE can be used to specify a default +export file for all source blocks. Optional argument LANG can be +used to limit the exported source code blocks by language." + (interactive "P") + (run-hooks 'org-babel-pre-tangle-hook) + ;; Possibly Restrict the buffer to the current code block + (save-restriction + (save-excursion + (when (equal arg '(4)) + (let ((head (org-babel-where-is-src-block-head))) + (if head + (goto-char head) + (user-error "Point is not in a source code block")))) + (let ((block-counter 0) + (org-babel-default-header-args + (if target-file + (org-babel-merge-params org-babel-default-header-args + (list (cons :tangle target-file))) + org-babel-default-header-args)) + (tangle-file + (when (equal arg '(16)) + (or (cdr (assq :tangle (nth 2 (org-babel-get-src-block-info 'light)))) + (user-error "Point is not in a source code block")))) + path-collector) + (mapc ;; map over all languages + (lambda (by-lang) + (let* ((lang (car by-lang)) + (specs (cdr by-lang)) + (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang)) + (lang-f (intern + (concat + (or (and (cdr (assoc lang org-src-lang-modes)) + (symbol-name + (cdr (assoc lang org-src-lang-modes)))) + lang) + "-mode"))) + she-banged) + (mapc + (lambda (spec) + (let ((get-spec (lambda (name) (cdr (assoc name (nth 4 spec)))))) + (let* ((tangle (funcall get-spec :tangle)) + (she-bang (let ((sheb (funcall get-spec :shebang))) + (when (> (length sheb) 0) sheb))) + (tangle-mode (funcall get-spec :tangle-mode)) + (base-name (cond + ((string= "yes" tangle) + (file-name-sans-extension + (nth 1 spec))) + ((string= "no" tangle) nil) + ((> (length tangle) 0) tangle))) + (file-name (when base-name + ;; decide if we want to add ext to base-name + (if (and ext (string= "yes" tangle)) + (concat base-name "." ext) base-name)))) + (when file-name + ;; Possibly create the parent directories for file. + (let ((m (funcall get-spec :mkdirp)) + (fnd (file-name-directory file-name))) + (and m fnd (not (string= m "no")) + (make-directory fnd 'parents))) + ;; delete any old versions of file + (and (file-exists-p file-name) + (not (member file-name (mapcar #'car path-collector))) + (delete-file file-name)) + ;; drop source-block to file + (with-temp-buffer + (when (fboundp lang-f) (ignore-errors (funcall lang-f))) + (when (and she-bang (not (member file-name she-banged))) + (insert (concat she-bang "\n")) + (setq she-banged (cons file-name she-banged))) + (org-babel-spec-to-string spec) + ;; We avoid append-to-file as it does not work with tramp. + (let ((content (buffer-string))) + (with-temp-buffer + (when (file-exists-p file-name) + (insert-file-contents file-name)) + (goto-char (point-max)) + ;; Handle :padlines unless first line in file + (unless (or (string= "no" (cdr (assq :padline (nth 4 spec)))) + (= (point) (point-min))) + (insert "\n")) + (insert content) + (write-region nil nil file-name)))) + ;; if files contain she-bangs, then make the executable + (when she-bang + (unless tangle-mode (setq tangle-mode #o755))) + ;; update counter + (setq block-counter (+ 1 block-counter)) + (unless (assoc file-name path-collector) + (push (cons file-name tangle-mode) path-collector)))))) + specs))) + (if (equal arg '(4)) + (org-babel-tangle-single-block 1 t) + (org-babel-tangle-collect-blocks lang tangle-file))) + (message "Tangled %d code block%s from %s" block-counter + (if (= block-counter 1) "" "s") + (file-name-nondirectory + (buffer-file-name + (or (buffer-base-buffer) (current-buffer))))) + ;; run `org-babel-post-tangle-hook' in all tangled files + (when org-babel-post-tangle-hook + (mapc + (lambda (file) + (org-babel-with-temp-filebuffer file + (run-hooks 'org-babel-post-tangle-hook))) + (mapcar #'car path-collector))) + ;; set permissions on tangled files + (mapc (lambda (pair) + (when (cdr pair) (set-file-modes (car pair) (cdr pair)))) + path-collector) + (mapcar #'car path-collector))))) + +(defun org-babel-tangle-clean () + "Remove comments inserted by `org-babel-tangle'. +Call this function inside of a source-code file generated by +`org-babel-tangle' to remove all comments inserted automatically +by `org-babel-tangle'. Warning, this comment removes any lines +containing constructs which resemble Org file links or noweb +references." + (interactive) + (goto-char (point-min)) + (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t) + (re-search-forward (org-babel-noweb-wrap) nil t)) + (delete-region (save-excursion (beginning-of-line 1) (point)) + (save-excursion (end-of-line 1) (forward-char 1) (point))))) + +(defvar org-stored-links) +(defvar org-bracket-link-regexp) +(defun org-babel-spec-to-string (spec) + "Insert SPEC into the current file. + +Insert the source-code specified by SPEC into the current source +code file. This function uses `comment-region' which assumes +that the appropriate major-mode is set. SPEC has the form: + + (start-line file link source-name params body comment)" + (pcase-let* + ((`(,start ,file ,link ,source ,info ,body ,comment) spec) + (comments (cdr (assq :comments info))) + (link? (or (string= comments "both") (string= comments "link") + (string= comments "yes") (string= comments "noweb"))) + (link-data `(("start-line" . ,(number-to-string start)) + ("file" . ,file) + ("link" . ,link) + ("source-name" . ,source))) + (insert-comment (lambda (text) + (when (and comments + (not (string= comments "no")) + (org-string-nw-p text)) + (if org-babel-tangle-uncomment-comments + ;; Plain comments: no processing. + (insert text) + ;; Ensure comments are made to be + ;; comments, and add a trailing newline. + ;; Also ignore invisible characters when + ;; commenting. + (comment-region + (point) + (progn (insert (org-no-properties text)) + (point))) + (end-of-line) + (insert "\n")))))) + (when comment (funcall insert-comment comment)) + (when link? + (funcall insert-comment + (org-fill-template + org-babel-tangle-comment-format-beg link-data))) + (insert body "\n") + (when link? + (funcall insert-comment + (org-fill-template + org-babel-tangle-comment-format-end link-data))))) + +(defun org-babel-tangle-collect-blocks (&optional language tangle-file) + "Collect source blocks in the current Org file. +Return an association list of source-code block specifications of +the form used by `org-babel-spec-to-string' grouped by language. +Optional argument LANGUAGE can be used to limit the collected +source code blocks by language. Optional argument TANGLE-FILE +can be used to limit the collected code blocks by target file." + (let ((counter 0) last-heading-pos blocks) + (org-babel-map-src-blocks (buffer-file-name) + (let ((current-heading-pos + (org-with-wide-buffer + (org-with-limited-levels (outline-previous-heading))))) + (if (eq last-heading-pos current-heading-pos) (cl-incf counter) + (setq counter 1) + (setq last-heading-pos current-heading-pos))) + (unless (org-in-commented-heading-p) + (let* ((info (org-babel-get-src-block-info 'light)) + (src-lang (nth 0 info)) + (src-tfile (cdr (assq :tangle (nth 2 info))))) + (unless (or (string= src-tfile "no") + (and tangle-file (not (equal tangle-file src-tfile))) + (and language (not (string= language src-lang)))) + ;; Add the spec for this block to blocks under its + ;; language. + (let ((by-lang (assoc src-lang blocks)) + (block (org-babel-tangle-single-block counter))) + (if by-lang (setcdr by-lang (cons block (cdr by-lang))) + (push (cons src-lang (list block)) blocks))))))) + ;; Ensure blocks are in the correct order. + (mapcar (lambda (b) (cons (car b) (nreverse (cdr b)))) blocks))) + +(defun org-babel-tangle-single-block (block-counter &optional only-this-block) + "Collect the tangled source for current block. +Return the list of block attributes needed by +`org-babel-tangle-collect-blocks'. When ONLY-THIS-BLOCK is +non-nil, return the full association list to be used by +`org-babel-tangle' directly." + (let* ((info (org-babel-get-src-block-info)) + (start-line + (save-restriction (widen) + (+ 1 (line-number-at-pos (point))))) + (file (buffer-file-name (buffer-base-buffer))) + (src-lang (nth 0 info)) + (params (nth 2 info)) + (extra (nth 3 info)) + (cref-fmt (or (and (string-match "-l \"\\(.+\\)\"" extra) + (match-string 1 extra)) + org-coderef-label-format)) + (link (let ((l (org-no-properties (org-store-link nil)))) + (and (string-match org-bracket-link-regexp l) + (match-string 1 l)))) + (source-name + (or (nth 4 info) + (format "%s:%d" + (or (ignore-errors (nth 4 (org-heading-components))) + "No heading") + block-counter))) + (expand-cmd (intern (concat "org-babel-expand-body:" src-lang))) + (assignments-cmd + (intern (concat "org-babel-variable-assignments:" src-lang))) + (body + ;; Run the tangle-body-hook. + (let ((body (if (org-babel-noweb-p params :tangle) + (org-babel-expand-noweb-references info) + (nth 1 info)))) + (with-temp-buffer + (insert + ;; Expand body in language specific manner. + (cond ((assq :no-expand params) body) + ((fboundp expand-cmd) (funcall expand-cmd body params)) + (t + (org-babel-expand-body:generic + body params (and (fboundp assignments-cmd) + (funcall assignments-cmd params)))))) + (when (string-match "-r" extra) + (goto-char (point-min)) + (while (re-search-forward + (replace-regexp-in-string "%s" ".+" cref-fmt) nil t) + (replace-match ""))) + (run-hooks 'org-babel-tangle-body-hook) + (buffer-string)))) + (comment + (when (or (string= "both" (cdr (assq :comments params))) + (string= "org" (cdr (assq :comments params)))) + ;; From the previous heading or code-block end + (funcall + org-babel-process-comment-text + (buffer-substring + (max (condition-case nil + (save-excursion + (org-back-to-heading t) ; Sets match data + (match-end 0)) + (error (point-min))) + (save-excursion + (if (re-search-backward + org-babel-src-block-regexp nil t) + (match-end 0) + (point-min)))) + (point))))) + (result + (list start-line + (if org-babel-tangle-use-relative-file-links + (file-relative-name file) + file) + (if (and org-babel-tangle-use-relative-file-links + (string-match org-link-types-re link) + (string= (match-string 0 link) "file")) + (concat "file:" + (file-relative-name (match-string 1 link) + (file-name-directory + (cdr (assq :tangle params))))) + link) + source-name + params + (if org-src-preserve-indentation + (org-trim body t) + (org-trim (org-remove-indentation body))) + comment))) + (if only-this-block + (list (cons src-lang (list result))) + result))) + +(defun org-babel-tangle-comment-links (&optional info) + "Return a list of begin and end link comments for the code block at point." + (let ((link-data + `(("start-line" . ,(number-to-string + (org-babel-where-is-src-block-head))) + ("file" . ,(buffer-file-name)) + ("link" . ,(org-link-escape + (progn + (call-interactively #'org-store-link) + (org-no-properties (car (pop org-stored-links)))))) + ("source-name" . + ,(nth 4 (or info (org-babel-get-src-block-info 'light))))))) + (list (org-fill-template org-babel-tangle-comment-format-beg link-data) + (org-fill-template org-babel-tangle-comment-format-end link-data)))) + +;; de-tangling functions +(defvar org-bracket-link-analytic-regexp) +(defun org-babel-detangle (&optional source-code-file) + "Propagate changes in source file back original to Org file. +This requires that code blocks were tangled with link comments +which enable the original code blocks to be found." + (interactive) + (save-excursion + (when source-code-file (find-file source-code-file)) + (goto-char (point-min)) + (let ((counter 0) new-body end) + (while (re-search-forward org-bracket-link-analytic-regexp nil t) + (when (re-search-forward + (concat " " (regexp-quote (match-string 5)) " ends here")) + (setq end (match-end 0)) + (forward-line -1) + (save-excursion + (when (setq new-body (org-babel-tangle-jump-to-org)) + (org-babel-update-block-body new-body))) + (setq counter (+ 1 counter))) + (goto-char end)) + (prog1 counter (message "Detangled %d code blocks" counter))))) + +(defun org-babel-tangle-jump-to-org () + "Jump from a tangled code file to the related Org mode file." + (interactive) + (let ((mid (point)) + start body-start end + target-buffer target-char link path block-name body) + (save-window-excursion + (save-excursion + (while (and (re-search-backward org-bracket-link-analytic-regexp nil t) + (not ; ever wider searches until matching block comments + (and (setq start (line-beginning-position)) + (setq body-start (line-beginning-position 2)) + (setq link (match-string 0)) + (setq path (match-string 3)) + (setq block-name (match-string 5)) + (save-excursion + (save-match-data + (re-search-forward + (concat " " (regexp-quote block-name) + " ends here") nil t) + (setq end (line-beginning-position)))))))) + (unless (and start (< start mid) (< mid end)) + (error "Not in tangled code")) + (setq body (buffer-substring body-start end))) + (when (string-match "::" path) + (setq path (substring path 0 (match-beginning 0)))) + (find-file (or (car (org-id-find path)) path)) + (setq target-buffer (current-buffer)) + ;; Go to the beginning of the relative block in Org file. + (org-open-link-from-string link) + (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name) + (let ((n (string-to-number (match-string 1 block-name)))) + (if (org-before-first-heading-p) (goto-char (point-min)) + (org-back-to-heading t)) + ;; Do not skip the first block if it begins at point min. + (cond ((or (org-at-heading-p) + (not (eq (org-element-type (org-element-at-point)) + 'src-block))) + (org-babel-next-src-block n)) + ((= n 1)) + (t (org-babel-next-src-block (1- n))))) + (org-babel-goto-named-src-block block-name)) + (goto-char (org-babel-where-is-src-block-head)) + ;; Preserve location of point within the source code in tangled + ;; code file. + (forward-line 1) + (forward-char (- mid body-start)) + (setq target-char (point))) + (org-src-switch-to-buffer target-buffer t) + (goto-char target-char) + body)) + +(provide 'ob-tangle) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; ob-tangle.el ends here diff --git a/elpa/org-9.1.14/ob-vala.el b/elpa/org-9.1.14/ob-vala.el new file mode 100644 index 00000000..96c37e3a --- /dev/null +++ b/elpa/org-9.1.14/ob-vala.el @@ -0,0 +1,117 @@ +;;; ob-vala.el --- Babel functions for Vala evaluation -*- lexical-binding: t; -*- + +;; Copyright (C) 2017-2018 Free Software Foundation, Inc. + +;; Author: Christian Garbs +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;;; License: + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; ob-vala.el provides Babel support for the Vala language +;; (see http://live.gnome.org/Vala for details) + +;;; Requirements: + +;; - Vala compiler binary (valac) +;; - Vala development environment (Vala libraries etc.) +;; +;; vala-mode.el is nice to have for code formatting, but is not needed +;; for ob-vala.el + +;;; Code: + +(require 'ob) + +(declare-function org-trim "org" (s &optional keep-lead)) + +;; File extension. +(add-to-list 'org-babel-tangle-lang-exts '("vala" . "vala")) + +;; Header arguments empty by default. +(defvar org-babel-default-header-args:vala '()) + +(defcustom org-babel-vala-compiler "valac" + "Command used to compile a C source code file into an executable. +May be either a command in the path, like \"valac\" +or an absolute path name, like \"/usr/local/bin/valac\". +Parameters may be used like this: \"valac -v\"" + :group 'org-babel + :version "26.1" + :package-version '(Org . "9.1") + :type 'string) + +;; This is the main function which is called to evaluate a code +;; block. +;; +;; - run Vala compiler and create a binary in a temporary file +;; - compiler/linker flags can be set via :flags header argument +;; - if compilation succeeded, run the binary +;; - commandline parameters to the binary can be set via :cmdline +;; header argument +;; - stdout will be parsed as RESULT (control via :result-params +;; header argument) +;; +;; There is no session support because Vala is a compiled language. +;; +;; This function is heavily based on ob-C.el +(defun org-babel-execute:vala (body params) + "Execute a block of Vala code with Babel. +This function is called by `org-babel-execute-src-block'." + (message "executing Vala source code block") + (let* ((tmp-src-file (org-babel-temp-file + "vala-src-" + ".vala")) + (tmp-bin-file (org-babel-temp-file "vala-bin-" org-babel-exeext)) + (cmdline (cdr (assq :cmdline params))) + (flags (cdr (assq :flags params)))) + (with-temp-file tmp-src-file (insert body)) + (org-babel-eval + (format "%s %s -o %s %s" + org-babel-vala-compiler + (mapconcat #'identity + (if (listp flags) flags (list flags)) " ") + (org-babel-process-file-name tmp-bin-file) + (org-babel-process-file-name tmp-src-file)) "") + (when (file-executable-p tmp-bin-file) + (let ((results + (org-trim + (org-babel-eval + (concat tmp-bin-file (if cmdline (concat " " cmdline) "")) "")))) + (org-babel-reassemble-table + (org-babel-result-cond (cdr (assq :result-params params)) + (org-babel-read results) + (let ((tmp-file (org-babel-temp-file "vala-"))) + (with-temp-file tmp-file (insert results)) + (org-babel-import-elisp-from-file tmp-file))) + (org-babel-pick-name + (cdr (assq :colname-names params)) (cdr (assq :colnames params))) + (org-babel-pick-name + (cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))))) + +(defun org-babel-prep-session:vala (_session _params) + "Prepare a session. +This function does nothing as Vala is a compiled language with no +support for sessions." + (error "Vala is a compiled language -- no support for sessions")) + +(provide 'ob-vala) + +;;; ob-vala.el ends here diff --git a/elpa/org-9.1.14/ob.el b/elpa/org-9.1.14/ob.el new file mode 100644 index 00000000..35f65ffa --- /dev/null +++ b/elpa/org-9.1.14/ob.el @@ -0,0 +1,43 @@ +;;; ob.el --- Working with Code Blocks in Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Authors: Eric Schulte +;; Keywords: literate programming, reproducible research +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Code: +(require 'org-macs) +(require 'org-compat) +(require 'ob-eval) +(require 'ob-core) +(require 'ob-comint) +(require 'ob-exp) +(require 'ob-keys) +(require 'ob-table) +(require 'ob-lob) +(require 'ob-ref) +(require 'ob-tangle) + +(provide 'ob) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; ob.el ends here diff --git a/elpa/org-9.1.14/org b/elpa/org-9.1.14/org new file mode 100644 index 00000000..636827d8 --- /dev/null +++ b/elpa/org-9.1.14/org @@ -0,0 +1,21818 @@ +This is org, produced by makeinfo version 6.3 from org.texi. + +This manual is for Org version 9.1.14 (release_9.1.14-1-g4931fc). + + Copyright © 2004–2018 Free Software Foundation, Inc. + + Permission is granted to copy, distribute and/or modify this + document under the terms of the GNU Free Documentation License, + Version 1.3 or any later version published by the Free Software + Foundation; with no Invariant Sections, with the Front-Cover Texts + being “A GNU Manual,” and with the Back-Cover Texts as in (a) + below. A copy of the license is included in the section entitled + “GNU Free Documentation License.” + + (a) The FSF’s Back-Cover Text is: “You have the freedom to copy and + modify this GNU manual.” +INFO-DIR-SECTION Emacs editing modes +START-INFO-DIR-ENTRY +* Org Mode: (org). Outline-based notes management and organizer +END-INFO-DIR-ENTRY + + +File: org, Node: Top, Next: Introduction, Prev: (dir), Up: (dir) + +Org Mode Manual +*************** + +This manual is for Org version 9.1.14 (release_9.1.14-1-g4931fc). + + Copyright © 2004–2018 Free Software Foundation, Inc. + + Permission is granted to copy, distribute and/or modify this + document under the terms of the GNU Free Documentation License, + Version 1.3 or any later version published by the Free Software + Foundation; with no Invariant Sections, with the Front-Cover Texts + being “A GNU Manual,” and with the Back-Cover Texts as in (a) + below. A copy of the license is included in the section entitled + “GNU Free Documentation License.” + + (a) The FSF’s Back-Cover Text is: “You have the freedom to copy and + modify this GNU manual.” + +* Menu: + +* Introduction:: Getting started +* Document structure:: A tree works like your brain +* Tables:: Pure magic for quick formatting +* Hyperlinks:: Notes in context +* TODO items:: Every tree branch can be a TODO item +* Tags:: Tagging headlines and matching sets of tags +* Properties and columns:: Storing information about an entry +* Dates and times:: Making items useful for planning +* Capture - Refile - Archive:: The ins and outs for projects +* Agenda views:: Collecting information into views +* Markup:: Prepare text for rich export +* Exporting:: Sharing and publishing notes +* Publishing:: Create a web site of linked Org files +* Working with source code:: Export, evaluate, and tangle code blocks +* Miscellaneous:: All the rest which did not fit elsewhere +* Hacking:: How to hack your way around +* MobileOrg:: Viewing and capture on a mobile device +* History and acknowledgments:: How Org came into being +* GNU Free Documentation License:: The license for this documentation. +* Main Index:: An index of Org’s concepts and features +* Key Index:: Key bindings and where they are described +* Command and Function Index:: Command names and some internal functions +* Variable Index:: Variables mentioned in the manual + + — The Detailed Node Listing — + +Introduction + +* Summary:: Brief summary of what Org does +* Installation:: Installing Org +* Activation:: How to activate Org for certain buffers +* Feedback:: Bug reports, ideas, patches etc. +* Conventions:: Typesetting conventions in the manual + +Document structure + +* Outlines:: Org is based on Outline mode +* Headlines:: How to typeset Org tree headlines +* Visibility cycling:: Show and hide, much simplified +* Motion:: Jumping to other headlines +* Structure editing:: Changing sequence and level of headlines +* Sparse trees:: Matches embedded in context +* Plain lists:: Additional structure within an entry +* Drawers:: Tucking stuff away +* Blocks:: Folding blocks +* Footnotes:: How footnotes are defined in Org’s syntax +* Orgstruct mode:: Structure editing outside Org +* Org syntax:: Formal description of Org’s syntax + +Visibility cycling + +* Global and local cycling:: Cycling through various visibility states +* Initial visibility:: Setting the initial visibility state +* Catching invisible edits:: Preventing mistakes when editing invisible parts + +Tables + +* Built-in table editor:: Simple tables +* Column width and alignment:: Overrule the automatic settings +* Column groups:: Grouping to trigger vertical lines +* Orgtbl mode:: The table editor as minor mode +* The spreadsheet:: The table editor has spreadsheet capabilities +* Org-Plot:: Plotting from org tables + +The spreadsheet + +* References:: How to refer to another field or range +* Formula syntax for Calc:: Using Calc to compute stuff +* Formula syntax for Lisp:: Writing formulas in Emacs Lisp +* Durations and time values:: How to compute durations and time values +* Field and range formulas:: Formula for specific (ranges of) fields +* Column formulas:: Formulas valid for an entire column +* Lookup functions:: Lookup functions for searching tables +* Editing and debugging formulas:: Fixing formulas +* Updating the table:: Recomputing all dependent fields +* Advanced features:: Field and column names, parameters and automatic recalc + +Hyperlinks + +* Link format:: How links in Org are formatted +* Internal links:: Links to other places in the current file +* External links:: URL-like links to the world +* Handling links:: Creating, inserting and following +* Using links outside Org:: Linking from my C source code? +* Link abbreviations:: Shortcuts for writing complex links +* Search options:: Linking to a specific location +* Custom searches:: When the default search is not enough + +Internal links + +* Radio targets:: Make targets trigger links in plain text + +TODO items + +* TODO basics:: Marking and displaying TODO entries +* TODO extensions:: Workflow and assignments +* Progress logging:: Dates and notes for progress +* Priorities:: Some things are more important than others +* Breaking down tasks:: Splitting a task into manageable pieces +* Checkboxes:: Tick-off lists + +Extended use of TODO keywords + +* Workflow states:: From TODO to DONE in steps +* TODO types:: I do this, Fred does the rest +* Multiple sets in one file:: Mixing it all, and still finding your way +* Fast access to TODO states:: Single letter selection of a state +* Per-file keywords:: Different files, different requirements +* Faces for TODO keywords:: Highlighting states +* TODO dependencies:: When one task needs to wait for others + +Progress logging + +* Closing items:: When was this entry marked DONE? +* Tracking TODO state changes:: When did the status change? +* Tracking your habits:: How consistent have you been? + +Tags + +* Tag inheritance:: Tags use the tree structure of the outline +* Setting tags:: How to assign tags to a headline +* Tag hierarchy:: Create a hierarchy of tags +* Tag searches:: Searching for combinations of tags + +Properties and columns + +* Property syntax:: How properties are spelled out +* Special properties:: Access to other Org mode features +* Property searches:: Matching property values +* Property inheritance:: Passing values down the tree +* Column view:: Tabular viewing and editing +* Property API:: Properties for Lisp programmers + +Column view + +* Defining columns:: The COLUMNS format property +* Using column view:: How to create and use column view +* Capturing column view:: A dynamic block for column view + +Defining columns + +* Scope of column definitions:: Where defined, where valid? +* Column attributes:: Appearance and content of a column + +Dates and times + +* Timestamps:: Assigning a time to a tree entry +* Creating timestamps:: Commands which insert timestamps +* Deadlines and scheduling:: Planning your work +* Clocking work time:: Tracking how long you spend on a task +* Effort estimates:: Planning work effort in advance +* Timers:: Notes with a running timer + +Creating timestamps + +* The date/time prompt:: How Org mode helps you entering date and time +* Custom time format:: Making dates look different + +Deadlines and scheduling + +* Inserting deadline/schedule:: Planning items +* Repeated tasks:: Items that show up again and again + +Clocking work time + +* Clocking commands:: Starting and stopping a clock +* The clock table:: Detailed reports +* Resolving idle time:: Resolving time when you’ve been idle + +Capture - Refile - Archive + +* Capture:: Capturing new stuff +* Attachments:: Add files to tasks +* RSS feeds:: Getting input from RSS feeds +* Protocols:: External (e.g., Browser) access to Emacs and Org +* Refile and copy:: Moving/copying a tree from one place to another +* Archiving:: What to do with finished projects + +Capture + +* Setting up capture:: Where notes will be stored +* Using capture:: Commands to invoke and terminate capture +* Capture templates:: Define the outline of different note types + +Capture templates + +* Template elements:: What is needed for a complete template entry +* Template expansion:: Filling in information about time and context +* Templates in contexts:: Only show a template in a specific context + +Protocols for external access + +* store-link protocol:: Store a link, push URL to kill-ring. +* capture protocol:: Fill a buffer with external information. +* open-source protocol:: Edit published contents. + +Archiving + +* Moving subtrees:: Moving a tree to an archive file +* Internal archiving:: Switch off a tree but keep it in the file + +Agenda views + +* Agenda files:: Files being searched for agenda information +* Agenda dispatcher:: Keyboard access to agenda views +* Built-in agenda views:: What is available out of the box? +* Presentation and sorting:: How agenda items are prepared for display +* Agenda commands:: Remote editing of Org trees +* Custom agenda views:: Defining special searches and views +* Exporting agenda views:: Writing a view to a file +* Agenda column view:: Using column view for collected entries + +The built-in agenda views + +* Weekly/daily agenda:: The calendar page with current tasks +* Global TODO list:: All unfinished action items +* Matching tags and properties:: Structured information with fine-tuned search +* Search view:: Find entries by searching for text +* Stuck projects:: Find projects you need to review + +Presentation and sorting + +* Categories:: Not all tasks are equal +* Time-of-day specifications:: How the agenda knows the time +* Sorting agenda items:: The order of things +* Filtering/limiting agenda items:: Dynamically narrow the agenda + +Custom agenda views + +* Storing searches:: Type once, use often +* Block agenda:: All the stuff you need in a single buffer +* Setting options:: Changing the rules + +Markup for rich export + +* Paragraphs:: The basic unit of text +* Emphasis and monospace:: Bold, italic, etc. +* Horizontal rules:: Make a line +* Images and tables:: Images, tables and caption mechanism +* Literal examples:: Source code examples with special formatting +* Special symbols:: Greek letters and other symbols +* Subscripts and superscripts:: Simple syntax for raising/lowering text +* Embedded LaTeX:: LaTeX can be freely used inside Org documents + +Embedded LaTeX + +* LaTeX fragments:: Complex formulas made easy +* Previewing LaTeX fragments:: What will this snippet look like? +* CDLaTeX mode:: Speed up entering of formulas + +Exporting + +* The export dispatcher:: The main interface +* Export settings:: Common export settings +* Table of contents:: The if and where of the table of contents +* Include files:: Include additional files into a document +* Macro replacement:: Use macros to create templates +* Comment lines:: What will not be exported +* ASCII/Latin-1/UTF-8 export:: Exporting to flat files with encoding +* Beamer export:: Exporting as a Beamer presentation +* HTML export:: Exporting to HTML +* LaTeX export:: Exporting to LaTeX, and processing to PDF +* Markdown export:: Exporting to Markdown +* OpenDocument Text export:: Exporting to OpenDocument Text +* Org export:: Exporting to Org +* Texinfo export:: Exporting to Texinfo +* iCalendar export:: Exporting to iCalendar +* Other built-in back-ends:: Exporting to a man page +* Advanced configuration:: Fine-tuning the export output +* Export in foreign buffers:: Author tables and lists in Org syntax + +Beamer export + +* Beamer export commands:: For creating Beamer documents. +* Beamer specific export settings:: For customizing Beamer export. +* Sectioning Frames and Blocks in Beamer:: For composing Beamer slides. +* Beamer specific syntax:: For using in Org documents. +* Editing support:: For using helper functions. +* A Beamer example:: A complete presentation. + +HTML export + +* HTML Export commands:: Invoking HTML export +* HTML Specific export settings:: Settings for HTML export +* HTML doctypes:: Exporting various (X)HTML flavors +* HTML preamble and postamble:: Inserting preamble and postamble +* Quoting HTML tags:: Using direct HTML in Org files +* Links in HTML export:: Interpreting and formatting links +* Tables in HTML export:: Formatting and modifying tables +* Images in HTML export:: Inserting figures with HTML output +* Math formatting in HTML export:: Handling math equations +* Text areas in HTML export:: Showing an alternate approach, an example +* CSS support:: Styling HTML output +* JavaScript support:: Folding scripting in the web browser + +LaTeX export + +* LaTeX export commands:: For producing LaTeX and PDF documents. +* LaTeX specific export settings:: Unique to this LaTeX back-end. +* LaTeX header and sectioning:: For file structure. +* Quoting LaTeX code:: Directly in the Org document. +* Tables in LaTeX export:: Attributes specific to tables. +* Images in LaTeX export:: Attributes specific to images. +* Plain lists in LaTeX export:: Attributes specific to lists. +* Source blocks in LaTeX export:: Attributes specific to source code blocks. +* Example blocks in LaTeX export:: Attributes specific to example blocks. +* Special blocks in LaTeX export:: Attributes specific to special blocks. +* Horizontal rules in LaTeX export:: Attributes specific to horizontal rules. + +OpenDocument Text export + +* Pre-requisites for ODT export:: Required packages. +* ODT export commands:: Invoking export. +* ODT specific export settings:: Configuration options. +* Extending ODT export:: Producing ‘.doc’, ‘.pdf’ files. +* Applying custom styles:: Styling the output. +* Links in ODT export:: Handling and formatting links. +* Tables in ODT export:: Org table conversions. +* Images in ODT export:: Inserting images. +* Math formatting in ODT export:: Formatting LaTeX fragments. +* Labels and captions in ODT export:: Rendering objects. +* Literal examples in ODT export:: For source code and example blocks. +* Advanced topics in ODT export:: For power users. + +Math formatting in ODT export + +* Working with LaTeX math snippets:: Embedding in LaTeX format. +* Working with MathML or OpenDocument formula files:: Embedding in native format. + +Advanced topics in ODT export + +* Configuring a document converter:: Registering a document converter. +* Working with OpenDocument style files:: Exploring internals. +* Creating one-off styles:: Customizing styles, highlighting. +* Customizing tables in ODT export:: Defining table templates. +* Validating OpenDocument XML:: Debugging corrupted OpenDocument files. + +Texinfo export + +* Texinfo export commands:: Invoking commands. +* Texinfo specific export settings:: Setting the environment. +* Texinfo file header:: Generating the header. +* Texinfo title and copyright page:: Creating preamble pages. +* Info directory file:: Installing a manual in Info file hierarchy. +* Headings and sectioning structure:: Building document structure. +* Indices:: Creating indices. +* Quoting Texinfo code:: Incorporating literal Texinfo code. +* Plain lists in Texinfo export:: List attributes. +* Tables in Texinfo export:: Table attributes. +* Images in Texinfo export:: Image attributes. +* Special blocks in Texinfo export:: Special block attributes. +* A Texinfo example:: Processing Org to Texinfo. + +Publishing + +* Configuration:: Defining projects +* Uploading files:: How to get files up on the server +* Sample configuration:: Example projects +* Triggering publication:: Publication commands + +Configuration + +* Project alist:: The central configuration variable +* Sources and destinations:: From here to there +* Selecting files:: What files are part of the project? +* Publishing action:: Setting the function doing the publishing +* Publishing options:: Tweaking HTML/LaTeX export +* Publishing links:: Which links keep working after publishing? +* Sitemap:: Generating a list of all pages +* Generating an index:: An index that reaches across pages + +Sample configuration + +* Simple example:: One-component publishing +* Complex example:: A multi-component publishing example + +Working with source code + +* Structure of code blocks:: Code block syntax described +* Editing source code:: Language major-mode editing +* Exporting code blocks:: Export contents and/or results +* Extracting source code:: Create pure source code files +* Evaluating code blocks:: Place results of evaluation in the Org mode buffer +* Library of Babel:: Use and contribute to a library of useful code blocks +* Languages:: List of supported code block languages +* Header arguments:: Configure code block functionality +* Results of evaluation:: How evaluation results are handled +* Noweb reference syntax:: Literate programming in Org mode +* Key bindings and useful functions:: Work quickly with code blocks +* Batch execution:: Call functions from the command line + +Header arguments + +* Using header arguments:: Different ways to set header arguments +* Specific header arguments:: List of header arguments + +Using header arguments + +* System-wide header arguments:: Set globally, language-specific +* Language-specific header arguments:: Set in the Org file’s headers +* Header arguments in Org mode properties:: Set in the Org file +* Language-specific mode properties:: +* Code block specific header arguments:: The most commonly used method +* Arguments in function calls:: The most specific level, takes highest priority + +Specific header arguments + +* var:: Pass arguments to ‘src’ code blocks +* results:: Specify results type; how to collect +* file:: Specify a path for output file +* file-desc:: Specify a description for file results +* file-ext:: Specify an extension for file output +* output-dir:: Specify a directory for output file +* dir:: Specify the default directory for code block execution +* exports:: Specify exporting code, results, both, none +* tangle:: Toggle tangling; or specify file name +* mkdirp:: Toggle for parent directory creation for target files during tangling +* comments:: Toggle insertion of comments in tangled code files +* padline:: Control insertion of padding lines in tangled code files +* no-expand:: Turn off variable assignment and noweb expansion during tangling +* session:: Preserve the state of code evaluation +* noweb:: Toggle expansion of noweb references +* noweb-ref:: Specify block’s noweb reference resolution target +* noweb-sep:: String to separate noweb references +* cache:: Avoid re-evaluating unchanged code blocks +* sep:: Delimiter for writing tabular results outside Org +* hlines:: Handle horizontal lines in tables +* colnames:: Handle column names in tables +* rownames:: Handle row names in tables +* shebang:: Make tangled files executable +* tangle-mode:: Set permission of tangled files +* eval:: Limit evaluation of specific code blocks +* wrap:: Mark source block evaluation results +* post:: Post processing of results of code block evaluation +* prologue:: Text to prepend to body of code block +* epilogue:: Text to append to body of code block + +Miscellaneous + +* Completion:: M- guesses completions +* Easy templates:: Quick insertion of structural elements +* Speed keys:: Electric commands at the beginning of a headline +* Code evaluation security:: Org mode files evaluate inline code +* Customization:: Adapting Org to changing tastes +* In-buffer settings:: Overview of the #+KEYWORDS +* The very busy C-c C-c key:: When in doubt, press C-c C-c +* Clean view:: Getting rid of leading stars in the outline +* TTY keys:: Using Org on a tty +* Interaction:: With other Emacs packages +* org-crypt:: Encrypting Org files + +Interaction with other packages + +* Cooperation:: Packages Org cooperates with +* Conflicts:: Packages that lead to conflicts + +Hacking + +* Hooks:: How to reach into Org’s internals +* Add-on packages:: Available extensions +* Adding hyperlink types:: New custom link types +* Adding export back-ends:: How to write new export back-ends +* Context-sensitive commands:: How to add functionality to such commands +* Tables in arbitrary syntax:: Orgtbl for LaTeX and other programs +* Dynamic blocks:: Automatically filled blocks +* Special agenda views:: Customized views +* Speeding up your agendas:: Tips on how to speed up your agendas +* Extracting agenda information:: Post-processing of agenda information +* Using the property API:: Writing programs that use entry properties +* Using the mapping API:: Mapping over all or selected entries + +Tables and lists in arbitrary syntax + +* Radio tables:: Sending and receiving radio tables +* A LaTeX example:: Step by step, almost a tutorial +* Translator functions:: Copy and modify +* Radio lists:: Sending and receiving lists + +MobileOrg + +* Setting up the staging area:: For the mobile device +* Pushing to MobileOrg:: Uploading Org files and agendas +* Pulling from MobileOrg:: Integrating captured and flagged items + + + +File: org, Node: Introduction, Next: Document structure, Up: Top + +1 Introduction +************** + +* Menu: + +* Summary:: Brief summary of what Org does +* Installation:: Installing Org +* Activation:: How to activate Org for certain buffers +* Feedback:: Bug reports, ideas, patches etc. +* Conventions:: Typesetting conventions in the manual + + +File: org, Node: Summary, Next: Installation, Up: Introduction + +1.1 Summary +=========== + +Org is a mode for keeping notes, maintaining TODO lists, and project +planning with a fast and effective plain-text system. It also is an +authoring system with unique support for literate programming and +reproducible research. + + Org is implemented on top of Outline mode, which makes it possible to +keep the content of large files well structured. Visibility cycling and +structure editing help to work with the tree. Tables are easily created +with a built-in table editor. Plain text URL-like links connect to +websites, emails, Usenet messages, BBDB entries, and any files related +to the projects. + + Org develops organizational tasks around notes files that contain +lists or information about projects as plain text. Project planning and +task management makes use of metadata which is part of an outline node. +Based on this data, specific entries can be extracted in queries and +create dynamic agenda views that also integrate the Emacs calendar and +diary. Org can be used to implement many different project planning +schemes, such as David Allen’s GTD system. + + Org files can serve as a single source authoring system with export +to many different formats such as HTML, LaTeX, Open Document, and +Markdown. New export backends can be derived from existing ones, or +defined from scratch. + + Org files can include source code blocks, which makes Org uniquely +suited for authoring technical documents with code examples. Org source +code blocks are fully functional; they can be evaluated in place and +their results can be captured in the file. This makes it possible to +create a single file reproducible research compendium. + + Org keeps simple things simple. When first fired up, it should feel +like a straightforward, easy to use outliner. Complexity is not +imposed, but a large amount of functionality is available when needed. +Org is a toolbox. Many users actually run only a (very personal) +fraction of Org’s capabilities, and know that there is more whenever +they need it. + + All of this is achieved with strictly plain text files, the most +portable and future-proof file format. Org runs in Emacs. Emacs is one +of the most widely ported programs, so that Org mode is available on +every major platform. + + There is a website for Org which provides links to the newest version +of Org, as well as additional information, frequently asked questions +(FAQ), links to tutorials, etc. This page is located at +. + + An earlier version (7.3) of this manual is available as a paperback +book from Network Theory Ltd. +(http://www.network-theory.co.uk/org/manual/) + + +File: org, Node: Installation, Next: Activation, Prev: Summary, Up: Introduction + +1.2 Installation +================ + +Org is part of recent distributions of GNU Emacs, so you normally don’t +need to install it. If, for one reason or another, you want to install +Org on top of this pre-packaged version, there are three ways to do it: + + • By using Emacs package system. + • By downloading Org as an archive. + • By using Org’s git repository. + + We strongly recommend to stick to a single installation method. + +Using Emacs packaging system +............................ + +Recent Emacs distributions include a packaging system which lets you +install Elisp libraries. You can install Org with ‘M-x package-install + org’. + +Important: you need to do this in a session where no ‘.org’ file has +been visited, i.e., where no Org built-in function have been loaded. +Otherwise autoload Org functions will mess up the installation. + + Then, to make sure your Org configuration is taken into account, +initialize the package system with ‘(package-initialize)’ in your Emacs +init file before setting any Org option. If you want to use Org’s +package repository, check out the Org ELPA page +(https://orgmode.org/elpa.html). + +Downloading Org as an archive +............................. + +You can download Org latest release from Org’s website +(https://orgmode.org/). In this case, make sure you set the load-path +correctly in your Emacs init file: + + (add-to-list 'load-path "~/path/to/orgdir/lisp") + + The downloaded archive contains contributed libraries that are not +included in Emacs. If you want to use them, add the ‘contrib’ directory +to your load-path: + + (add-to-list 'load-path "~/path/to/orgdir/contrib/lisp" t) + + Optionally, you can compile the files and/or install them in your +system. Run ‘make help’ to list compilation and installation options. + +Using Org’s git repository +.......................... + +You can clone Org’s repository and install Org like this: + + $ cd ~/src/ + $ git clone https://code.orgmode.org/bzg/org-mode.git + $ cd org-mode/ + $ make autoloads + + Note that in this case, ‘make autoloads’ is mandatory: it defines +Org’s version in ‘org-version.el’ and Org’s autoloads in +‘org-loaddefs.el’. + + Remember to add the correct load-path as described in the method +above. + + You can also compile with ‘make’, generate the documentation with +‘make doc’, create a local configuration with ‘make config’ and install +Org with ‘make install’. Please run ‘make help’ to get the list of +compilation/installation options. + + For more detailed explanations on Org’s build system, please check +the Org Build System page on Worg +(https://orgmode.org/worg/dev/org-build-system.html). + + +File: org, Node: Activation, Next: Feedback, Prev: Installation, Up: Introduction + +1.3 Activation +============== + +Org mode buffers need font-lock to be turned on: this is the default in +Emacs(1). + + There are compatibility issues between Org mode and some other Elisp +packages, please take the time to check the list (*note Conflicts::). + + The four Org commands ‘org-store-link’, ‘org-capture’, ‘org-agenda’, +and ‘org-switchb’ should be accessible through global keys (i.e., +anywhere in Emacs, not just in Org buffers). Here are suggested +bindings for these keys, please modify the keys to your own liking. + (global-set-key "\C-cl" 'org-store-link) + (global-set-key "\C-ca" 'org-agenda) + (global-set-key "\C-cc" 'org-capture) + (global-set-key "\C-cb" 'org-switchb) + + Files with the ‘.org’ extension use Org mode by default. To turn on +Org mode in a file that does not have the extension ‘.org’, make the +first line of a file look like this: + + MY PROJECTS -*- mode: org; -*- + +which will select Org mode for this buffer no matter what the file’s +name is. See also the variable ‘org-insert-mode-line-in-empty-file’. + + Many commands in Org work on the region if the region is active. To +make use of this, you need to have ‘transient-mark-mode’ turned on, +which is the default. If you do not like ‘transient-mark-mode’, you can +create an active region by using the mouse to select a region, or +pressing ‘C-’ twice before moving the cursor. + + ---------- Footnotes ---------- + + (1) If you don’t use font-lock globally, turn it on in Org buffer +with ‘(add-hook 'org-mode-hook 'turn-on-font-lock)’ + + +File: org, Node: Feedback, Next: Conventions, Prev: Activation, Up: Introduction + +1.4 Feedback +============ + +If you find problems with Org, or if you have questions, remarks, or +ideas about it, please mail to the Org mailing list +. You can subscribe to the list on this web page +(https://lists.gnu.org/mailman/listinfo/emacs-orgmode). If you are not +a member of the mailing list, your mail will be passed to the list after +a moderator has approved it(1). + + For bug reports, please first try to reproduce the bug with the +latest version of Org available—if you are running an outdated version, +it is quite possible that the bug has been fixed already. If the bug +persists, prepare a report and provide as much information as possible, +including the version information of Emacs (‘M-x emacs-version ’) +and Org (‘M-x org-version ’), as well as the Org related setup in +the Emacs init file. The easiest way to do this is to use the command + M-x org-submit-bug-report +which will put all this information into an Emacs mail buffer so that +you only need to add your description. If you are not sending the Email +from within Emacs, please copy and paste the content into your Email +program. + + Sometimes you might face a problem due to an error in your Emacs or +Org mode setup. Before reporting a bug, it is very helpful to start +Emacs with minimal customizations and reproduce the problem. Doing so +often helps you determine if the problem is with your customization or +with Org mode itself. You can start a typical minimal session with a +command like the example below. + + $ emacs -Q -l /path/to/minimal-org.el + + However if you are using Org mode as distributed with Emacs, a +minimal setup is not necessary. In that case it is sufficient to start +Emacs as ‘emacs -Q’. The ‘minimal-org.el’ setup file can have contents +as shown below. + + ;;; Minimal setup to load latest 'org-mode' + + ;; activate debugging + (setq debug-on-error t + debug-on-signal nil + debug-on-quit nil) + + ;; add latest org-mode to load path + (add-to-list 'load-path "/path/to/org-mode/lisp") + (add-to-list 'load-path "/path/to/org-mode/contrib/lisp" t) + + If an error occurs, a backtrace can be very useful (see below on how +to create one). Often a small example file helps, along with clear +information about: + + 1. What exactly did you do? + 2. What did you expect to happen? + 3. What happened instead? +Thank you for helping to improve this program. + +How to create a useful backtrace +................................ + +If working with Org produces an error with a message you don’t +understand, you may have hit a bug. The best way to report this is by +providing, in addition to what was mentioned above, a _backtrace_. This +is information from the built-in debugger about where and how the error +occurred. Here is how to produce a useful backtrace: + + 1. Reload uncompiled versions of all Org mode Lisp files. The + backtrace contains much more information if it is produced with + uncompiled code. To do this, use + C-u M-x org-reload + or select ‘Org -> Refresh/Reload -> Reload Org uncompiled’ from the + menu. + 2. Go to the ‘Options’ menu and select ‘Enter Debugger on Error’. + 3. Do whatever you have to do to hit the error. Don’t forget to + document the steps you take. + 4. When you hit the error, a ‘*Backtrace*’ buffer will appear on the + screen. Save this buffer to a file (for example using ‘C-x C-w’) + and attach it to your bug report. + + ---------- Footnotes ---------- + + (1) Please consider subscribing to the mailing list, in order to +minimize the work the mailing list moderators have to do. + + +File: org, Node: Conventions, Prev: Feedback, Up: Introduction + +1.5 Typesetting conventions used in this manual +=============================================== + +TODO keywords, tags, properties, etc. +..................................... + +Org mainly uses three types of keywords: TODO keywords, tags and +property names. In this manual we use the following conventions: + +‘TODO’ +‘WAITING’ + TODO keywords are written with all capitals, even if they are + user-defined. +‘boss’ +‘ARCHIVE’ + User-defined tags are written in lowercase; built-in tags with + special meaning are written with all capitals. +‘Release’ +‘PRIORITY’ + User-defined properties are capitalized; built-in properties with + special meaning are written with all capitals. + + Moreover, Org uses option keywords (like ‘#+TITLE’ to set the title) +and environment keywords (like ‘#+BEGIN_EXPORT html’ to start a ‘HTML’ +environment). They are written in uppercase in the manual to enhance +its readability, but you can use lowercase in your Org file. + +Key bindings and commands +......................... + +The manual suggests a few global key bindings, in particular ‘C-c a’ for +‘org-agenda’ and ‘C-c c’ for ‘org-capture’. These are only suggestions, +but the rest of the manual assumes that these key bindings are in place +in order to list commands by key access. + + Also, the manual lists both the keys and the corresponding commands +for accessing a functionality. Org mode often uses the same key for +different functions, depending on context. The command that is bound to +such keys has a generic name, like ‘org-metaright’. In the manual we +will, wherever possible, give the function that is internally called by +the generic command. For example, in the chapter on document structure, +‘M-’ will be listed to call ‘org-do-demote’, while in the chapter +on tables, it will be listed to call ‘org-table-move-column-right’. If +you prefer, you can compile the manual without the command names by +unsetting the flag ‘cmdnames’ in ‘org.texi’. + + +File: org, Node: Document structure, Next: Tables, Prev: Introduction, Up: Top + +2 Document structure +******************** + +Org is based on Outline mode and provides flexible commands to edit the +structure of the document. + +* Menu: + +* Outlines:: Org is based on Outline mode +* Headlines:: How to typeset Org tree headlines +* Visibility cycling:: Show and hide, much simplified +* Motion:: Jumping to other headlines +* Structure editing:: Changing sequence and level of headlines +* Sparse trees:: Matches embedded in context +* Plain lists:: Additional structure within an entry +* Drawers:: Tucking stuff away +* Blocks:: Folding blocks +* Footnotes:: How footnotes are defined in Org’s syntax +* Orgstruct mode:: Structure editing outside Org +* Org syntax:: Formal description of Org’s syntax + + +File: org, Node: Outlines, Next: Headlines, Up: Document structure + +2.1 Outlines +============ + +Org is implemented on top of Outline mode. Outlines allow a document to +be organized in a hierarchical structure, which (at least for me) is the +best representation of notes and thoughts. An overview of this +structure is achieved by folding (hiding) large parts of the document to +show only the general document structure and the parts currently being +worked on. Org greatly simplifies the use of outlines by compressing +the entire show/hide functionality into a single command, ‘org-cycle’, +which is bound to the key. + + +File: org, Node: Headlines, Next: Visibility cycling, Prev: Outlines, Up: Document structure + +2.2 Headlines +============= + +Headlines define the structure of an outline tree. The headlines in Org +start with one or more stars, on the left margin(1) (2). For example: + + * Top level headline + ** Second level + *** 3rd level + some text + *** 3rd level + more text + + * Another top level headline + +Note that a headline named after ‘org-footnote-section’, which defaults +to ‘Footnotes’, is considered as special. A subtree with this headline +will be silently ignored by exporting functions. + + Some people find the many stars too noisy and would prefer an outline +that has whitespace followed by a single star as headline starters. +*note Clean view::, describes a setup to realize this. + + An empty line after the end of a subtree is considered part of it and +will be hidden when the subtree is folded. However, if you leave at +least two empty lines, one empty line will remain visible after folding +the subtree, in order to structure the collapsed view. See the variable +‘org-cycle-separator-lines’ to modify this behavior. + + ---------- Footnotes ---------- + + (1) See the variables ‘org-special-ctrl-a/e’, ‘org-special-ctrl-k’, +and ‘org-ctrl-k-protect-subtree’ to configure special behavior of ‘C-a’, +‘C-e’, and ‘C-k’ in headlines. + + (2) Clocking only works with headings indented less than 30 stars. + + +File: org, Node: Visibility cycling, Next: Motion, Prev: Headlines, Up: Document structure + +2.3 Visibility cycling +====================== + +* Menu: + +* Global and local cycling:: Cycling through various visibility states +* Initial visibility:: Setting the initial visibility state +* Catching invisible edits:: Preventing mistakes when editing invisible parts + + +File: org, Node: Global and local cycling, Next: Initial visibility, Up: Visibility cycling + +2.3.1 Global and local cycling +------------------------------ + +Outlines make it possible to hide parts of the text in the buffer. Org +uses just two commands, bound to and ‘S-’ to change the +visibility in the buffer. + +‘’ (‘org-cycle’) + _Subtree cycling_: Rotate current subtree among the states + + ,-> FOLDED -> CHILDREN -> SUBTREE --. + '-----------------------------------' + + The cursor must be on a headline for this to work(1). + +‘S-’ (‘org-global-cycle’) +C-u + _Global cycling_: Rotate the entire buffer among the states + + ,-> OVERVIEW -> CONTENTS -> SHOW ALL --. + '--------------------------------------' + + When ‘S-’ is called with a numeric prefix argument N, the + CONTENTS view up to headlines of level N will be shown. Note that + inside tables, ‘S-’ jumps to the previous field. + + You can run global cycling using only if point is at the very + beginning of the buffer, but not on a headline, and + ‘org-cycle-global-at-bob’ is set to a non-‘nil’ value. + +‘C-u C-u ’ (‘org-set-startup-visibility’) + Switch back to the startup visibility of the buffer (*note Initial + visibility::). +‘C-u C-u C-u ’ (‘outline-show-all’) + Show all, including drawers. +‘C-c C-r’ (‘org-reveal’) + Reveal context around point, showing the current entry, the + following heading and the hierarchy above. Useful for working near + a location that has been exposed by a sparse tree command (*note + Sparse trees::) or an agenda command (*note Agenda commands::). + With a prefix argument show, on each level, all sibling headings. + With a double prefix argument, also show the entire subtree of the + parent. +‘C-c C-k’ (‘outline-show-branches’) + Expose all the headings of the subtree, CONTENTS view for just one + subtree. +‘C-c ’ (‘outline-show-children’) + Expose all direct children of the subtree. With a numeric prefix + argument N, expose all children down to level N. +‘C-c C-x b’ (‘org-tree-to-indirect-buffer’) + Show the current subtree in an indirect buffer(2). With a numeric + prefix argument N, go up to level N and then take that tree. If N + is negative then go up that many levels. With a ‘C-u’ prefix, do + not remove the previously used indirect buffer. +‘C-c C-x v’ (‘org-copy-visible’) + Copy the visible text in the region into the kill ring. + + ---------- Footnotes ---------- + + (1) see, however, the option ‘org-cycle-emulate-tab’. + + (2) The indirect buffer (*note (emacs)Indirect Buffers::) will +contain the entire buffer, but will be narrowed to the current tree. +Editing the indirect buffer will also change the original buffer, but +without affecting visibility in that buffer. + + +File: org, Node: Initial visibility, Next: Catching invisible edits, Prev: Global and local cycling, Up: Visibility cycling + +2.3.2 Initial visibility +------------------------ + +When Emacs first visits an Org file, the global state is set to +OVERVIEW, i.e., only the top level headlines are visible(1). This can +be configured through the variable ‘org-startup-folded’, or on a +per-file basis by adding one of the following lines anywhere in the +buffer: + + #+STARTUP: overview + #+STARTUP: content + #+STARTUP: showall + #+STARTUP: showeverything + +Furthermore, any entries with a ‘VISIBILITY’ property (*note Properties +and columns::) will get their visibility adapted accordingly. Allowed +values for this property are ‘folded’, ‘children’, ‘content’, and ‘all’. + +‘C-u C-u ’ (‘org-set-startup-visibility’) + Switch back to the startup visibility of the buffer, i.e., whatever + is requested by startup options and ‘VISIBILITY’ properties in + individual entries. + + ---------- Footnotes ---------- + + (1) When ‘org-agenda-inhibit-startup’ is non-‘nil’, Org will not +honor the default visibility state when first opening a file for the +agenda (*note Speeding up your agendas::). + + +File: org, Node: Catching invisible edits, Prev: Initial visibility, Up: Visibility cycling + +2.3.3 Catching invisible edits +------------------------------ + +Sometimes you may inadvertently edit an invisible part of the buffer and +be confused on what has been edited and how to undo the mistake. +Setting ‘org-catch-invisible-edits’ to non-‘nil’ will help prevent this. +See the docstring of this option on how Org should catch invisible edits +and process them. + + +File: org, Node: Motion, Next: Structure editing, Prev: Visibility cycling, Up: Document structure + +2.4 Motion +========== + +The following commands jump to other headlines in the buffer. + +‘C-c C-n’ (‘org-next-visible-heading’) + Next heading. +‘C-c C-p’ (‘org-previous-visible-heading’) + Previous heading. +‘C-c C-f’ (‘org-forward-same-level’) + Next heading same level. +‘C-c C-b’ (‘org-backward-same-level’) + Previous heading same level. +‘C-c C-u’ (‘outline-up-heading’) + Backward to higher level heading. +‘C-c C-j’ (‘org-goto’) + Jump to a different place without changing the current outline + visibility. Shows the document structure in a temporary buffer, + where you can use the following keys to find your destination: + Cycle visibility. + / Next/previous visible headline. + Select this location. + / Do a Sparse-tree search + The following keys work if you turn off ‘org-goto-auto-isearch’ + n / p Next/previous visible headline. + f / b Next/previous headline same level. + u One level up. + 0-9 Digit argument. + q Quit + See also the option ‘org-goto-interface’. + + +File: org, Node: Structure editing, Next: Sparse trees, Prev: Motion, Up: Document structure + +2.5 Structure editing +===================== + +‘M-’ (‘org-meta-return’) + Insert a new heading, item or row. + + If the command is used at the _beginning_ of a line, and if there + is a heading or a plain list item (*note Plain lists::) at point, + the new heading/item is created _before_ the current line. When + used at the beginning of a regular line of text, turn that line + into a heading. + + When this command is used in the middle of a line, the line is + split and the rest of the line becomes the new item or headline. + If you do not want the line to be split, customize + ‘org-M-RET-may-split-line’. + + Calling the command with a ‘C-u’ prefix unconditionally inserts a + new heading at the end of the current subtree, thus preserving its + contents. With a double ‘C-u C-u’ prefix, the new heading is + created at the end of the parent subtree instead. +‘C-’ (‘org-insert-heading-respect-content’) + Insert a new heading at the end of the current subtree. +‘M-S-’ (‘org-insert-todo-heading’) + Insert new TODO entry with same level as current heading. See also + the variable ‘org-treat-insert-todo-heading-as-state-change’. +‘C-S-’ (‘org-insert-todo-heading-respect-content’) + Insert new TODO entry with same level as current heading. Like + ‘C-’, the new headline will be inserted after the current + subtree. +‘’ (‘org-cycle’) + In a new entry with no text yet, the first demotes the entry + to become a child of the previous one. The next makes it a + parent, and so on, all the way to top level. Yet another , + and you are back to the initial level. +‘M-’ (‘org-do-promote’) + Promote current heading by one level. +‘M-’ (‘org-do-demote’) + Demote current heading by one level. +‘M-S-’ (‘org-promote-subtree’) + Promote the current subtree by one level. +‘M-S-’ (‘org-demote-subtree’) + Demote the current subtree by one level. +‘M-’ (‘org-move-subtree-up’) + Move subtree up (swap with previous subtree of same level). +‘M-’ (‘org-move-subtree-down’) + Move subtree down (swap with next subtree of same level). +‘M-h’ (‘org-mark-element’) + Mark the element at point. Hitting repeatedly will mark subsequent + elements of the one just marked. E.g., hitting ‘M-h’ on a + paragraph will mark it, hitting ‘M-h’ immediately again will mark + the next one. +‘C-c @’ (‘org-mark-subtree’) + Mark the subtree at point. Hitting repeatedly will mark subsequent + subtrees of the same level than the marked subtree. +‘C-c C-x C-w’ (‘org-cut-subtree’) + Kill subtree, i.e., remove it from buffer but save in kill ring. + With a numeric prefix argument N, kill N sequential subtrees. +‘C-c C-x M-w’ (‘org-copy-subtree’) + Copy subtree to kill ring. With a numeric prefix argument N, copy + the N sequential subtrees. +‘C-c C-x C-y’ (‘org-paste-subtree’) + Yank subtree from kill ring. This does modify the level of the + subtree to make sure the tree fits in nicely at the yank position. + The yank level can also be specified with a numeric prefix + argument, or by yanking after a headline marker like ‘****’. +‘C-y’ (‘org-yank’) + Depending on the options ‘org-yank-adjusted-subtrees’ and + ‘org-yank-folded-subtrees’, Org’s internal ‘yank’ command will + paste subtrees folded and in a clever way, using the same command + as ‘C-c C-x C-y’. With the default settings, no level adjustment + will take place, but the yanked tree will be folded unless doing so + would swallow text previously visible. Any prefix argument to this + command will force a normal ‘yank’ to be executed, with the prefix + passed along. A good way to force a normal yank is ‘C-u C-y’. If + you use ‘yank-pop’ after a yank, it will yank previous kill items + plainly, without adjustment and folding. +‘C-c C-x c’ (‘org-clone-subtree-with-time-shift’) + Clone a subtree by making a number of sibling copies of it. You + will be prompted for the number of copies to make, and you can also + specify if any timestamps in the entry should be shifted. This can + be useful, for example, to create a number of tasks related to a + series of lectures to prepare. For more details, see the docstring + of the command ‘org-clone-subtree-with-time-shift’. +‘C-c C-w’ (‘org-refile’) + Refile entry or region to a different location. *Note Refile and + copy::. +‘C-c ^’ (‘org-sort’) + Sort same-level entries. When there is an active region, all + entries in the region will be sorted. Otherwise the children of + the current headline are sorted. The command prompts for the + sorting method, which can be alphabetically, numerically, by time + (first timestamp with active preferred, creation time, scheduled + time, deadline time), by priority, by TODO keyword (in the sequence + the keywords have been defined in the setup) or by the value of a + property. Reverse sorting is possible as well. You can also + supply your own function to extract the sorting key. With a ‘C-u’ + prefix, sorting will be case-sensitive. +‘C-x n s’ (‘org-narrow-to-subtree’) + Narrow buffer to current subtree. +‘C-x n b’ (‘org-narrow-to-block’) + Narrow buffer to current block. +‘C-x n w’ (‘widen’) + Widen buffer to remove narrowing. +‘C-c *’ (‘org-toggle-heading’) + Turn a normal line or plain list item into a headline (so that it + becomes a subheading at its location). Also turn a headline into a + normal line by removing the stars. If there is an active region, + turn all lines in the region into headlines. If the first line in + the region was an item, turn only the item lines into headlines. + Finally, if the first line is a headline, remove the stars from all + headlines in the region. + + When there is an active region (Transient Mark mode), promotion and +demotion work on all headlines in the region. To select a region of +headlines, it is best to place both point and mark at the beginning of a +line, mark at the beginning of the first headline, and point at the line +just after the last headline to change. Note that when the cursor is +inside a table (*note Tables::), the Meta-Cursor keys have different +functionality. + + +File: org, Node: Sparse trees, Next: Plain lists, Prev: Structure editing, Up: Document structure + +2.6 Sparse trees +================ + +An important feature of Org mode is the ability to construct _sparse +trees_ for selected information in an outline tree, so that the entire +document is folded as much as possible, but the selected information is +made visible along with the headline structure above it(1). Just try it +out and you will see immediately how it works. + + Org mode contains several commands for creating such trees, all these +commands can be accessed through a dispatcher: + +‘C-c /’ (‘org-sparse-tree’) + This prompts for an extra key to select a sparse-tree creating + command. +‘C-c / r’ or ‘C-c / /’ (‘org-occur’) + Prompts for a regexp and shows a sparse tree with all matches. If + the match is in a headline, the headline is made visible. If the + match is in the body of an entry, headline and body are made + visible. In order to provide minimal context, also the full + hierarchy of headlines above the match is shown, as well as the + headline following the match. Each match is also highlighted; the + highlights disappear when the buffer is changed by an editing + command(2), or by pressing ‘C-c C-c’. When called with a ‘C-u’ + prefix argument, previous highlights are kept, so several calls to + this command can be stacked. +‘M-g n’ or ‘M-g M-n’ (‘next-error’) + Jump to the next sparse tree match in this buffer. +‘M-g p’ or ‘M-g M-p’ (‘previous-error’) + Jump to the previous sparse tree match in this buffer. + +For frequently used sparse trees of specific search strings, you can use +the option ‘org-agenda-custom-commands’ to define fast keyboard access +to specific sparse trees. These commands will then be accessible +through the agenda dispatcher (*note Agenda dispatcher::). For example: + + (setq org-agenda-custom-commands + '(("f" occur-tree "FIXME"))) + +will define the key ‘C-c a f’ as a shortcut for creating a sparse tree +matching the string ‘FIXME’. + + The other sparse tree commands select headings based on TODO +keywords, tags, or properties and will be discussed later in this +manual. + + To print a sparse tree, you can use the Emacs command +‘ps-print-buffer-with-faces’ which does not print invisible parts of the +document. Or you can use ‘C-c C-e C-v’ to export only the visible part +of the document and print the resulting file. + + ---------- Footnotes ---------- + + (1) See also the variable ‘org-show-context-detail’ to decide how +much context is shown around each match. + + (2) This depends on the option ‘org-remove-highlights-with-change’ + + +File: org, Node: Plain lists, Next: Drawers, Prev: Sparse trees, Up: Document structure + +2.7 Plain lists +=============== + +Within an entry of the outline tree, hand-formatted lists can provide +additional structure. They also provide a way to create lists of +checkboxes (*note Checkboxes::). Org supports editing such lists, and +every exporter (*note Exporting::) can parse and format them. + + Org knows ordered lists, unordered lists, and description lists. + • _Unordered_ list items start with ‘-’, ‘+’, or ‘*’(1) as bullets. + • _Ordered_ list items start with a numeral followed by either a + period or a right parenthesis(2), such as ‘1.’ or ‘1)’(3). If you + want a list to start with a different value (e.g., 20), start the + text of the item with ‘[@20]’(4). Those constructs can be used in + any item of the list in order to enforce a particular numbering. + • _Description_ list items are unordered list items, and contain the + separator ‘ :: ’ to distinguish the description _term_ from the + description. + + Items belonging to the same list must have the same indentation on +the first line. In particular, if an ordered list reaches number ‘10.’, +then the 2–digit numbers must be written left-aligned with the other +numbers in the list. An item ends before the next line that is less or +equally indented than its bullet/number. + + A list ends whenever every item has ended, which means before any +line less or equally indented than items at top level. It also ends +before two blank lines. In that case, all items are closed. Here is an +example: + + ** Lord of the Rings + My favorite scenes are (in this order) + 1. The attack of the Rohirrim + 2. Eowyn's fight with the witch king + + this was already my favorite scene in the book + + I really like Miranda Otto. + 3. Peter Jackson being shot by Legolas + - on DVD only + He makes a really funny face when it happens. + But in the end, no individual scenes matter but the film as a whole. + Important actors in this film are: + - Elijah Wood :: He plays Frodo + - Sean Astin :: He plays Sam, Frodo's friend. I still remember + him very well from his role as Mikey Walsh in The Goonies. + + Org supports these lists by tuning filling and wrapping commands to +deal with them correctly, and by exporting them properly (*note +Exporting::). Since indentation is what governs the structure of these +lists, many structural constructs like ‘#+BEGIN_...’ blocks can be +indented to signal that they belong to a particular item. + + If you find that using a different bullet for a sub-list (than that +used for the current list-level) improves readability, customize the +variable ‘org-list-demote-modify-bullet’. To get a greater difference +of indentation between items and their sub-items, customize +‘org-list-indent-offset’. + + The following commands act on items when the cursor is in the first +line of an item (the line with the bullet or number). Some of them +imply the application of automatic rules to keep list structure intact. +If some of these actions get in your way, configure +‘org-list-automatic-rules’ to disable them individually. + +‘’ (‘org-cycle’) + Items can be folded just like headline levels. Normally this works + only if the cursor is on a plain list item. For more details, see + the variable ‘org-cycle-include-plain-lists’. If this variable is + set to ‘integrate’, plain list items will be treated like low-level + headlines. The level of an item is then given by the indentation + of the bullet/number. Items are always subordinate to real + headlines, however; the hierarchies remain completely separated. + In a new item with no text yet, the first demotes the item to + become a child of the previous one. Subsequent s move the + item to meaningful levels in the list and eventually get it back to + its initial position. +‘M-’ (‘org-insert-heading’) + Insert new item at current level. With a prefix argument, force a + new heading (*note Structure editing::). If this command is used + in the middle of an item, that item is _split_ in two, and the + second part becomes the new item(5). If this command is executed + _before item’s body_, the new item is created _before_ the current + one. + +‘M-S-’ + Insert a new item with a checkbox (*note Checkboxes::). +‘S-up’ +‘S-down’ + Jump to the previous/next item in the current list(6), but only if + ‘org-support-shift-select’ is off. If not, you can still use + paragraph jumping commands like ‘C-’ and ‘C-’ to quite + similar effect. +‘M-up’ +‘M-down’ + Move the item including subitems up/down(7) (swap with + previous/next item of same indentation). If the list is ordered, + renumbering is automatic. +‘M-left’ +‘M-right’ + Decrease/increase the indentation of an item, leaving children + alone. +‘M-S-’ +‘M-S-’ + Decrease/increase the indentation of the item, including subitems. + Initially, the item tree is selected based on current indentation. + When these commands are executed several times in direct + succession, the initially selected region is used, even if the new + indentation would imply a different hierarchy. To use the new + hierarchy, break the command chain with a cursor motion or so. + + As a special case, using this command on the very first item of a + list will move the whole list. This behavior can be disabled by + configuring ‘org-list-automatic-rules’. The global indentation of + a list has no influence on the text _after_ the list. +‘C-c C-c’ + If there is a checkbox (*note Checkboxes::) in the item line, + toggle the state of the checkbox. In any case, verify bullets and + indentation consistency in the whole list. +‘C-c -’ + Cycle the entire list level through the different itemize/enumerate + bullets (‘-’, ‘+’, ‘*’, ‘1.’, ‘1)’) or a subset of them, depending + on ‘org-plain-list-ordered-item-terminator’, the type of list, and + its indentation. With a numeric prefix argument N, select the Nth + bullet from this list. If there is an active region when calling + this, all selected lines are converted to list items. With a + prefix argument, selected text is changed into a single item. If + the first line already was a list item, any item marker will be + removed from the list. Finally, even without an active region, a + normal line will be converted into a list item. +‘C-c *’ + Turn a plain list item into a headline (so that it becomes a + subheading at its location). *Note Structure editing::, for a + detailed explanation. +‘C-c C-*’ + Turn the whole plain list into a subtree of the current heading. + Checkboxes (*note Checkboxes::) will become TODO (resp. DONE) + keywords when unchecked (resp. checked). +‘S-/’ + This command also cycles bullet styles when the cursor in on the + bullet or anywhere in an item line, details depending on + ‘org-support-shift-select’. +‘C-c ^’ + Sort the plain list. You will be prompted for the sorting method: + numerically, alphabetically, by time, by checked status for check + lists, or by a custom function. + + ---------- Footnotes ---------- + + (1) When using ‘*’ as a bullet, lines must be indented or they will +be seen as top-level headlines. Also, when you are hiding leading stars +to get a clean outline view, plain list items starting with a star may +be hard to distinguish from true headlines. In short: even though ‘*’ +is supported, it may be better to not use it for plain list items. + + (2) You can filter out any of them by configuring +‘org-plain-list-ordered-item-terminator’. + + (3) You can also get ‘a.’, ‘A.’, ‘a)’ and ‘A)’ by configuring +‘org-list-allow-alphabetical’. To minimize confusion with normal text, +those are limited to one character only. Beyond that limit, bullets +will automatically fallback to numbers. + + (4) If there’s a checkbox in the item, the cookie must be put +_before_ the checkbox. If you have activated alphabetical lists, you +can also use counters like ‘[@b]’. + + (5) If you do not want the item to be split, customize the variable +‘org-M-RET-may-split-line’. + + (6) If you want to cycle around items that way, you may customize +‘org-list-use-circular-motion’. + + (7) See ‘org-list-use-circular-motion’ for a cyclic behavior. + + +File: org, Node: Drawers, Next: Blocks, Prev: Plain lists, Up: Document structure + +2.8 Drawers +=========== + +Sometimes you want to keep information associated with an entry, but you +normally don’t want to see it. For this, Org mode has _drawers_. They +can contain anything but a headline and another drawer. Drawers look +like this: + + ** This is a headline + Still outside the drawer + :DRAWERNAME: + This is inside the drawer. + :END: + After the drawer. + + You can interactively insert drawers at point by calling +‘org-insert-drawer’, which is bound to ‘C-c C-x d’. With an active +region, this command will put the region inside the drawer. With a +prefix argument, this command calls ‘org-insert-property-drawer’ and add +a property drawer right below the current headline. Completion over +drawer keywords is also possible using ‘M-’(1). + + Visibility cycling (*note Visibility cycling::) on the headline will +hide and show the entry, but keep the drawer collapsed to a single line. +In order to look inside the drawer, you need to move the cursor to the +drawer line and press there. Org mode uses the ‘PROPERTIES’ +drawer for storing properties (*note Properties and columns::), and you +can also arrange for state change notes (*note Tracking TODO state +changes::) and clock times (*note Clocking work time::) to be stored in +a drawer ‘LOGBOOK’. If you want to store a quick note in the LOGBOOK +drawer, in a similar way to state changes, use + +‘C-c C-z’ + Add a time-stamped note to the LOGBOOK drawer. + + You can select the name of the drawers which should be exported with +‘org-export-with-drawers’. In that case, drawer contents will appear in +export output. Property drawers are not affected by this variable: +configure ‘org-export-with-properties’ instead. + + ---------- Footnotes ---------- + + (1) Many desktops intercept ‘M-’ to switch windows. Use ‘C-M-i’ +or ‘ ’ instead for completion (*note Completion::). + + +File: org, Node: Blocks, Next: Footnotes, Prev: Drawers, Up: Document structure + +2.9 Blocks +========== + +Org mode uses begin...end blocks for various purposes from including +source code examples (*note Literal examples::) to capturing time +logging information (*note Clocking work time::). These blocks can be +folded and unfolded by pressing in the begin line. You can also +get all blocks folded at startup by configuring the option +‘org-hide-block-startup’ or on a per-file basis by using + + #+STARTUP: hideblocks + #+STARTUP: nohideblocks + + +File: org, Node: Footnotes, Next: Orgstruct mode, Prev: Blocks, Up: Document structure + +2.10 Footnotes +============== + +Org mode supports the creation of footnotes. + + A footnote is started by a footnote marker in square brackets in +column 0, no indentation allowed. It ends at the next footnote +definition, headline, or after two consecutive empty lines. The +footnote reference is simply the marker in square brackets, inside text. +Markers always start with ‘fn:’. For example: + + The Org homepage[fn:1] now looks a lot better than it used to. + ... + [fn:1] The link is: https://orgmode.org + + Org mode extends the number-based syntax to _named_ footnotes and +optional inline definition. Here are the valid references: + +‘[fn:name]’ + A named footnote reference, where ‘name’ is a unique label word, + or, for simplicity of automatic creation, a number. +‘[fn::This is the inline definition of this footnote]’ + A LaTeX-like anonymous footnote where the definition is given + directly at the reference point. +‘[fn:name:a definition]’ + An inline definition of a footnote, which also specifies a name for + the note. Since Org allows multiple references to the same note, + you can then use ‘[fn:name]’ to create additional references. + + Footnote labels can be created automatically, or you can create names +yourself. This is handled by the variable ‘org-footnote-auto-label’ and +its corresponding ‘#+STARTUP’ keywords. See the docstring of that +variable for details. + +The following command handles footnotes: + +‘C-c C-x f’ + The footnote action command. + + When the cursor is on a footnote reference, jump to the definition. + When it is at a definition, jump to the (first) reference. + + Otherwise, create a new footnote. Depending on the option + ‘org-footnote-define-inline’(1), the definition will be placed + right into the text as part of the reference, or separately into + the location determined by the option ‘org-footnote-section’. + + When this command is called with a prefix argument, a menu of + additional options is offered: + s Sort the footnote definitions by reference sequence. During editing, + Org makes no effort to sort footnote definitions into a particular + sequence. If you want them sorted, use this command, which will + also move entries according to ‘org-footnote-section’. Automatic + sorting after each insertion/deletion can be configured using the + option ‘org-footnote-auto-adjust’. + r Renumber the simple ‘fn:N’ footnotes. Automatic renumbering + after each insertion/deletion can be configured using the option + ‘org-footnote-auto-adjust’. + S Short for first ‘r’, then ‘s’ action. + n Normalize the footnotes by collecting all definitions (including + inline definitions) into a special section, and then numbering them + in sequence. The references will then also be numbers. + d Delete the footnote at point, and all definitions of and references + to it. + Depending on the variable ‘org-footnote-auto-adjust’(2), + renumbering and sorting footnotes can be automatic after each + insertion or deletion. + +‘C-c C-c’ + If the cursor is on a footnote reference, jump to the definition. + If it is a the definition, jump back to the reference. When called + at a footnote location with a prefix argument, offer the same menu + as ‘C-c C-x f’. +‘C-c C-o or mouse-1/2’ + Footnote labels are also links to the corresponding + definition/reference, and you can use the usual commands to follow + these links. + +‘C-c '’ +‘C-c '’ + Edit the footnote definition corresponding to the reference at + point in a separate window. The window can be closed by pressing + ‘C-c '’. + + ---------- Footnotes ---------- + + (1) The corresponding in-buffer setting is: ‘#+STARTUP: fninline’ or +‘#+STARTUP: nofninline’ + + (2) the corresponding in-buffer options are ‘fnadjust’ and +‘nofnadjust’. + + +File: org, Node: Orgstruct mode, Next: Org syntax, Prev: Footnotes, Up: Document structure + +2.11 The Orgstruct minor mode +============================= + +If you like the intuitive way the Org mode structure editing and list +formatting works, you might want to use these commands in other modes +like Text mode or Mail mode as well. The minor mode ‘orgstruct-mode’ +makes this possible. Toggle the mode with ‘M-x orgstruct-mode ’, +or turn it on by default, for example in Message mode, with one of: + + (add-hook 'message-mode-hook 'turn-on-orgstruct) + (add-hook 'message-mode-hook 'turn-on-orgstruct++) + + When this mode is active and the cursor is on a line that looks to +Org like a headline or the first line of a list item, most structure +editing commands will work, even if the same keys normally have +different functionality in the major mode you are using. If the cursor +is not in one of those special lines, Orgstruct mode lurks silently in +the shadows. + + When you use ‘orgstruct++-mode’, Org will also export indentation and +autofill settings into that mode, and detect item context after the +first line of an item. + + You can also use Org structure editing to fold and unfold headlines +in _any_ file, provided you defined ‘orgstruct-heading-prefix-regexp’: +the regular expression must match the local prefix to use before Org’s +headlines. For example, if you set this variable to ‘";; "’ in Emacs +Lisp files, you will be able to fold and unfold headlines in Emacs Lisp +commented lines. Some commands like ‘org-demote’ are disabled when the +prefix is set, but folding/unfolding will work correctly. + + +File: org, Node: Org syntax, Prev: Orgstruct mode, Up: Document structure + +2.12 Org syntax +=============== + +A reference document providing a formal description of Org’s syntax is +available as a draft on Worg +(https://orgmode.org/worg/dev/org-syntax.html), written and maintained +by Nicolas Goaziou. It defines Org’s core internal concepts such as +‘headlines’, ‘sections’, ‘affiliated keywords’, ‘(greater) elements’ and +‘objects’. Each part of an Org file falls into one of the categories +above. + + To explore the abstract structure of an Org buffer, run this in a +buffer: + + M-: (org-element-parse-buffer) + + It will output a list containing the buffer’s content represented as +an abstract structure. The export engine relies on the information +stored in this list. Most interactive commands (e.g., for structure +editing) also rely on the syntactic meaning of the surrounding context. + + You can check syntax in your documents using ‘org-lint’ command. + + +File: org, Node: Tables, Next: Hyperlinks, Prev: Document structure, Up: Top + +3 Tables +******** + +Org comes with a fast and intuitive table editor. Spreadsheet-like +calculations are supported using the Emacs ‘calc’ package (*note Calc: +(calc)Top.). + +* Menu: + +* Built-in table editor:: Simple tables +* Column width and alignment:: Overrule the automatic settings +* Column groups:: Grouping to trigger vertical lines +* Orgtbl mode:: The table editor as minor mode +* The spreadsheet:: The table editor has spreadsheet capabilities +* Org-Plot:: Plotting from org tables + + +File: org, Node: Built-in table editor, Next: Column width and alignment, Up: Tables + +3.1 The built-in table editor +============================= + +Org makes it easy to format tables in plain ASCII. Any line with ‘|’ as +the first non-whitespace character is considered part of a table. ‘|’ +is also the column separator(1). A table might look like this: + + | Name | Phone | Age | + |-------+-------+-----| + | Peter | 1234 | 17 | + | Anna | 4321 | 25 | + + A table is re-aligned automatically each time you press or + or ‘C-c C-c’ inside the table. also moves to the next field +( to the next row) and creates new table rows at the end of the +table or before horizontal lines. The indentation of the table is set +by the first line. Any line starting with ‘|-’ is considered as a +horizontal separator line and will be expanded on the next re-align to +span the whole table width. So, to create the above table, you would +only type + + |Name|Phone|Age| + |- + +and then press to align the table and start filling in fields. +Even faster would be to type ‘|Name|Phone|Age’ followed by ‘C-c ’. + + When typing text into a field, Org treats , , and all +character keys in a special way, so that inserting and deleting avoids +shifting other fields. Also, when typing _immediately after the cursor +was moved into a new field with ‘’, ‘S-’ or ‘’_, the +field is automatically made blank. If this behavior is too +unpredictable for you, configure the option +‘org-table-auto-blank-field’. + + Creation and conversion + ....................... + +‘C-c | (org-table-create-or-convert-from-region)’ + Convert the active region to a table. If every line contains at + least one TAB character, the function assumes that the material is + tab separated. If every line contains a comma, comma-separated + values (CSV) are assumed. If not, lines are split at whitespace + into fields. You can use a prefix argument to force a specific + separator: ‘C-u’ forces CSV, ‘C-u C-u’ forces TAB, ‘C-u C-u C-u’ + will prompt for a regular expression to match the separator, and a + numeric argument N indicates that at least N consecutive spaces, or + alternatively a TAB will be the separator. + If there is no active region, this command creates an empty Org + table. But it is easier just to start typing, like + ‘|Name|Phone|Age |- ’. + + Re-aligning and field motion + ............................ + +‘C-c C-c (org-table-align)’ + Re-align the table and don’t move to another field. +‘C-c (org-table-blank-field)’ + Blank the field at point. +‘ (org-table-next-field)’ + Re-align the table, move to the next field. Creates a new row if + necessary. +‘S- (org-table-previous-field)’ + Re-align, move to previous field. +‘ (org-table-next-row)’ + Re-align the table and move down to next row. Creates a new row if + necessary. At the beginning or end of a line, still does + NEWLINE, so it can be used to split a table. +‘M-a (org-table-beginning-of-field)’ + Move to beginning of the current table field, or on to the previous + field. +‘M-e (org-table-end-of-field)’ + Move to end of the current table field, or on to the next field. + + Column and row editing + ...................... + +‘M- (org-table-move-column-left)’ +‘M- (org-table-move-column-right)’ + Move the current column left/right. +‘M-S- (org-table-delete-column)’ + Kill the current column. +‘M-S- (org-table-insert-column)’ + Insert a new column to the left of the cursor position. +‘M- (org-table-move-row-up)’ +‘M- (org-table-move-row-down)’ + Move the current row up/down. +‘M-S- (org-table-kill-row)’ + Kill the current row or horizontal line. +‘M-S- (org-table-insert-row)’ + Insert a new row above the current row. With a prefix argument, + the line is created below the current one. +‘C-c - (org-table-insert-hline)’ + Insert a horizontal line below current row. With a prefix + argument, the line is created above the current line. +‘C-c (org-table-hline-and-move)’ + Insert a horizontal line below current row, and move the cursor + into the row below that line. +‘C-c ^ (org-table-sort-lines)’ + Sort the table lines in the region. The position of point + indicates the column to be used for sorting, and the range of lines + is the range between the nearest horizontal separator lines, or the + entire table. If point is before the first column, you will be + prompted for the sorting column. If there is an active region, the + mark specifies the first line and the sorting column, while point + should be in the last line to be included into the sorting. The + command prompts for the sorting type (alphabetically, numerically, + or by time). You can sort in normal or reverse order. You can + also supply your own key extraction and comparison functions. When + called with a prefix argument, alphabetic sorting will be + case-sensitive. + + Regions + ....... + +‘C-c C-x M-w (org-table-copy-region)’ + Copy a rectangular region from a table to a special clipboard. + Point and mark determine edge fields of the rectangle. If there is + no active region, copy just the current field. The process ignores + horizontal separator lines. +‘C-c C-x C-w (org-table-cut-region)’ + Copy a rectangular region from a table to a special clipboard, and + blank all fields in the rectangle. So this is the “cut” operation. +‘C-c C-x C-y (org-table-paste-rectangle)’ + Paste a rectangular region into a table. The upper left corner + ends up in the current field. All involved fields will be + overwritten. If the rectangle does not fit into the present table, + the table is enlarged as needed. The process ignores horizontal + separator lines. +‘M- (org-table-wrap-region)’ + Split the current field at the cursor position and move the rest to + the line below. If there is an active region, and both point and + mark are in the same column, the text in the column is wrapped to + minimum width for the given number of lines. A numeric prefix + argument may be used to change the number of desired lines. If + there is no region, but you specify a prefix argument, the current + field is made blank, and the content is appended to the field + above. + + Calculations + ............ + +‘C-c + (org-table-sum)’ + Sum the numbers in the current column, or in the rectangle defined + by the active region. The result is shown in the echo area and can + be inserted with ‘C-y’. +‘S- (org-table-copy-down)’ + When current field is empty, copy from first non-empty field above. + When not empty, copy current field down to next row and move cursor + along with it. Depending on the option ‘org-table-copy-increment’, + integer field values will be incremented during copy. Integers + that are too large will not be incremented. Also, a ‘0’ prefix + argument temporarily disables the increment. This key is also used + by shift-selection and related modes (*note Conflicts::). + + Miscellaneous + ............. + +‘C-c ` (org-table-edit-field)’ + Edit the current field in a separate window. This is useful for + fields that are not fully visible (*note Column width and + alignment::). When called with a ‘C-u’ prefix, just make the full + field visible, so that it can be edited in place. When called with + two ‘C-u’ prefixes, make the editor window follow the cursor + through the table and always show the current field. The follow + mode exits automatically when the cursor leaves the table, or when + you repeat this command with ‘C-u C-u C-c `’. +‘M-x org-table-import ’ + Import a file as a table. The table should be TAB or whitespace + separated. Use, for example, to import a spreadsheet table or data + from a database, because these programs generally can write + TAB-separated text files. This command works by inserting the file + into the buffer and then converting the region to a table. Any + prefix argument is passed on to the converter, which uses it to + determine the separator. +‘C-c | (org-table-create-or-convert-from-region)’ + Tables can also be imported by pasting tabular text into the Org + buffer, selecting the pasted text with ‘C-x C-x’ and then using the + ‘C-c |’ command (see above under Creation and conversion). +‘M-x org-table-export ’ + Export the table, by default as a TAB-separated file. Use for data + exchange with, for example, spreadsheet or database programs. The + format used to export the file can be configured in the option + ‘org-table-export-default-format’. You may also use properties + ‘TABLE_EXPORT_FILE’ and ‘TABLE_EXPORT_FORMAT’ to specify the file + name and the format for table export in a subtree. Org supports + quite general formats for exported tables. The exporter format is + the same as the format used by Orgtbl radio tables, see *note + Translator functions::, for a detailed description. + + ---------- Footnotes ---------- + + (1) To insert a vertical bar into a table field, use ‘\vert’ or, +inside a word ‘abc\vert{}def’. + + +File: org, Node: Column width and alignment, Next: Column groups, Prev: Built-in table editor, Up: Tables + +3.2 Column width and alignment +============================== + +The width of columns is automatically determined by the table editor. +And also the alignment of a column is determined automatically from the +fraction of number-like versus non-number fields in the column. + + Sometimes a single field or a few fields need to carry more text, +leading to inconveniently wide columns. Or maybe you want to make a +table with several columns having a fixed width, regardless of content. +To set the width of a column, one field anywhere in the column may +contain just the string ‘’ where ‘N’ is an integer specifying the +width of the column in characters. The next re-align will then set the +width of this column to this value. + + |---+------------------------------| |---+--------| + | | | | | <6> | + | 1 | one | | 1 | one | + | 2 | two | ----\ | 2 | two | + | 3 | This is a long chunk of text | ----/ | 3 | This=> | + | 4 | four | | 4 | four | + |---+------------------------------| |---+--------| + +Fields that are wider become clipped and end in the string ‘=>’. Note +that the full text is still in the buffer but is hidden. To see the +full text, hold the mouse over the field—a tool-tip window will show the +full content. To edit such a field, use the command ‘C-c `’ (that is +‘C-c’ followed by the grave accent). This will open a new window with +the full field. Edit it and finish with ‘C-c C-c’. + + When visiting a file containing a table with narrowed columns, the +necessary character hiding has not yet happened, and the table needs to +be aligned before it looks nice. Setting the option +‘org-startup-align-all-tables’ will realign all tables in a file upon +visiting, but also slow down startup. You can also set this option on a +per-file basis with: + + #+STARTUP: align + #+STARTUP: noalign + + If you would like to overrule the automatic alignment of number-rich +columns to the right and of string-rich columns to the left, you can use +‘’, ‘’(1) or ‘’ in a similar fashion. You may also combine +alignment and field width like this: ‘’. + + Lines which only contain these formatting cookies will be removed +automatically when exporting the document. + + ---------- Footnotes ---------- + + (1) Centering does not work inside Emacs, but it does have an effect +when exporting to HTML. + + +File: org, Node: Column groups, Next: Orgtbl mode, Prev: Column width and alignment, Up: Tables + +3.3 Column groups +================= + +When Org exports tables, it does so by default without vertical lines +because that is visually more satisfying in general. Occasionally +however, vertical lines can be useful to structure a table into groups +of columns, much like horizontal lines can do for groups of rows. In +order to specify column groups, you can use a special row where the +first field contains only ‘/’. The further fields can either contain +‘<’ to indicate that this column should start a group, ‘>’ to indicate +the end of a group, or ‘<>’ (no space between ‘<’ and ‘>’) to make a +column a group of its own. Boundaries between column groups will upon +export be marked with vertical lines. Here is an example: + + | N | N^2 | N^3 | N^4 | ~sqrt(n)~ | ~sqrt[4](N)~ | + |---+-----+-----+-----+-----------+--------------| + | / | < | | > | < | > | + | 1 | 1 | 1 | 1 | 1 | 1 | + | 2 | 4 | 8 | 16 | 1.4142 | 1.1892 | + | 3 | 9 | 27 | 81 | 1.7321 | 1.3161 | + |---+-----+-----+-----+-----------+--------------| + #+TBLFM: $2=$1^2::$3=$1^3::$4=$1^4::$5=sqrt($1)::$6=sqrt(sqrt(($1))) + + It is also sufficient to just insert the column group starters after +every vertical line you would like to have: + + | N | N^2 | N^3 | N^4 | sqrt(n) | sqrt[4](N) | + |----+-----+-----+-----+---------+------------| + | / | < | | | < | | + + +File: org, Node: Orgtbl mode, Next: The spreadsheet, Prev: Column groups, Up: Tables + +3.4 The Orgtbl minor mode +========================= + +If you like the intuitive way the Org table editor works, you might also +want to use it in other modes like Text mode or Mail mode. The minor +mode Orgtbl mode makes this possible. You can always toggle the mode +with ‘M-x orgtbl-mode ’. To turn it on by default, for example in +Message mode, use + + (add-hook 'message-mode-hook 'turn-on-orgtbl) + + Furthermore, with some special setup, it is possible to maintain +tables in arbitrary syntax with Orgtbl mode. For example, it is +possible to construct LaTeX tables with the underlying ease and power of +Orgtbl mode, including spreadsheet capabilities. For details, see *note +Tables in arbitrary syntax::. + + +File: org, Node: The spreadsheet, Next: Org-Plot, Prev: Orgtbl mode, Up: Tables + +3.5 The spreadsheet +=================== + +The table editor makes use of the Emacs ‘calc’ package to implement +spreadsheet-like capabilities. It can also evaluate Emacs Lisp forms to +derive fields from other fields. While fully featured, Org’s +implementation is not identical to other spreadsheets. For example, Org +knows the concept of a _column formula_ that will be applied to all +non-header fields in a column without having to copy the formula to each +relevant field. There is also a formula debugger, and a formula editor +with features for highlighting fields in the table corresponding to the +references at the point in the formula, moving these references by arrow +keys + +* Menu: + +* References:: How to refer to another field or range +* Formula syntax for Calc:: Using Calc to compute stuff +* Formula syntax for Lisp:: Writing formulas in Emacs Lisp +* Durations and time values:: How to compute durations and time values +* Field and range formulas:: Formula for specific (ranges of) fields +* Column formulas:: Formulas valid for an entire column +* Lookup functions:: Lookup functions for searching tables +* Editing and debugging formulas:: Fixing formulas +* Updating the table:: Recomputing all dependent fields +* Advanced features:: Field and column names, parameters and automatic recalc + + +File: org, Node: References, Next: Formula syntax for Calc, Up: The spreadsheet + +3.5.1 References +---------------- + +To compute fields in the table from other fields, formulas must +reference other fields or ranges. In Org, fields can be referenced by +name, by absolute coordinates, and by relative coordinates. To find out +what the coordinates of a field are, press ‘C-c ?’ in that field, or +press ‘C-c }’ to toggle the display of a grid. + +Field references +................ + +Formulas can reference the value of another field in two ways. Like in +any other spreadsheet, you may reference fields with a letter/number +combination like ‘B3’, meaning the 2nd field in the 3rd row. However, +Org prefers(1) to use another, more general representation that looks +like this: + @ROW$COLUMN + + Column specifications can be absolute like ‘$1’, ‘$2’,...‘$N’, or +relative to the current column (i.e., the column of the field which is +being computed) like ‘$+1’ or ‘$-2’. ‘$<’ and ‘$>’ are immutable +references to the first and last column, respectively, and you can use +‘$>>>’ to indicate the third column from the right. + + The row specification only counts data lines and ignores horizontal +separator lines (hlines). Like with columns, you can use absolute row +numbers ‘@1’, ‘@2’,...‘@N’, and row numbers relative to the current row +like ‘@+3’ or ‘@-1’. ‘@<’ and ‘@>’ are immutable references the first +and last(2) row in the table, respectively. You may also specify the +row relative to one of the hlines: ‘@I’ refers to the first hline, ‘@II’ +to the second, etc. ‘@-I’ refers to the first such line above the +current line, ‘@+I’ to the first such line below the current line. You +can also write ‘@III+2’ which is the second data line after the third +hline in the table. + + ‘@0’ and ‘$0’ refer to the current row and column, respectively, +i.e., to the row/column for the field being computed. Also, if you omit +either the column or the row part of the reference, the current +row/column is implied. + + Org’s references with _unsigned_ numbers are fixed references in the +sense that if you use the same reference in the formula for two +different fields, the same field will be referenced each time. Org’s +references with _signed_ numbers are floating references because the +same reference operator can reference different fields depending on the +field being calculated by the formula. + + Here are a few examples: + + @2$3 2nd row, 3rd column (same as ‘C2’) + $5 column 5 in the current row (same as ‘E&’) + @2 current column, row 2 + @-1$-3 the field one row up, three columns to the left + @-I$2 field just under hline above current row, column 2 + @>$5 field in the last row, in column 5 + +Range references +................ + +You may reference a rectangular range of fields by specifying two field +references connected by two dots ‘..’. If both fields are in the +current row, you may simply use ‘$2..$7’, but if at least one field is +in a different row, you need to use the general ‘@row$column’ format at +least for the first field (i.e the reference must start with ‘@’ in +order to be interpreted correctly). Examples: + + $1..$3 first three fields in the current row + $P..$Q range, using column names (see under Advanced) + $<<<..$>> start in third column, continue to the last but one + @2$1..@4$3 6 fields between these two fields (same as ‘A2..C4’) + @-1$-2..@-1 3 fields in the row above, starting from 2 columns on the left + @I..II between first and second hline, short for ‘@I..@II’ + +Range references return a vector of values that can be fed into Calc +vector functions. Empty fields in ranges are normally suppressed, so +that the vector contains only the non-empty fields. For other options +with the mode switches ‘E’, ‘N’ and examples *note Formula syntax for +Calc::. + +Field coordinates in formulas +............................. + +One of the very first actions during evaluation of Calc formulas and +Lisp formulas is to substitute ‘@#’ and ‘$#’ in the formula with the row +or column number of the field where the current result will go to. The +traditional Lisp formula equivalents are ‘org-table-current-dline’ and +‘org-table-current-column’. Examples: + +‘if(@# % 2, $#, string(""))’ + Insert column number on odd rows, set field to empty on even rows. +‘$2 = '(identity remote(FOO, @@#$1))’ + Copy text or values of each row of column 1 of the table named + ‘FOO’ into column 2 of the current table. +‘@3 = 2 * remote(FOO, @1$$#)’ + Insert the doubled value of each column of row 1 of the table named + ‘FOO’ into row 3 of the current table. + +For the second/third example, the table named ‘FOO’ must have at least +as many rows/columns as the current table. Note that this is +inefficient(3) for large number of rows/columns. + +Named references +................ + +‘$name’ is interpreted as the name of a column, parameter or constant. +Constants are defined globally through the option +‘org-table-formula-constants’, and locally (for the file) through a line +like + + #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6 + +Also properties (*note Properties and columns::) can be used as +constants in table formulas: for a property ‘:Xyz:’ use the name +‘$PROP_Xyz’, and the property will be searched in the current outline +entry and in the hierarchy above it. If you have the ‘constants.el’ +package, it will also be used to resolve constants, including natural +constants like ‘$h’ for Planck’s constant, and units like ‘$km’ for +kilometers(4). Column names and parameters can be specified in special +table lines. These are described below, see *note Advanced features::. +All names must start with a letter, and further consist of letters and +numbers. + +Remote references +................. + +You may also reference constants, fields and ranges from a different +table, either in the current file or even in a different file. The +syntax is + + remote(NAME-OR-ID,REF) + +where NAME can be the name of a table in the current file as set by a +‘#+NAME: Name’ line before the table. It can also be the ID of an +entry, even in a different file, and the reference then refers to the +first table in that entry. REF is an absolute field or range reference +as described above for example ‘@3$3’ or ‘$somename’, valid in the +referenced table. + + Indirection of NAME-OR-ID: When NAME-OR-ID has the format +‘@ROW$COLUMN’ it will be substituted with the name or ID found in this +field of the current table. For example ‘remote($1, @>$2)’ => +‘remote(year_2013, @>$1)’. The format ‘B3’ is not supported because it +can not be distinguished from a plain table name or ID. + + ---------- Footnotes ---------- + + (1) Org will understand references typed by the user as ‘B4’, but it +will not use this syntax when offering a formula for editing. You can +customize this behavior using the option +‘org-table-use-standard-references’. + + (2) For backward compatibility you can also use special names like +‘$LR5’ and ‘$LR12’ to refer in a stable way to the 5th and 12th field in +the last row of the table. However, this syntax is deprecated, it +should not be used for new documents. Use ‘@>$’ instead. + + (3) The computation time scales as O(N^2) because the table named +‘FOO’ is parsed for each field to be read. + + (4) ‘constants.el’ can supply the values of constants in two +different unit systems, ‘SI’ and ‘cgs’. Which one is used depends on +the value of the variable ‘constants-unit-system’. You can use the +‘#+STARTUP’ options ‘constSI’ and ‘constcgs’ to set this value for the +current buffer. + + +File: org, Node: Formula syntax for Calc, Next: Formula syntax for Lisp, Prev: References, Up: The spreadsheet + +3.5.2 Formula syntax for Calc +----------------------------- + +A formula can be any algebraic expression understood by the Emacs ‘Calc’ +package. Note that ‘calc’ has the non-standard convention that ‘/’ has +lower precedence than ‘*’, so that ‘a/b*c’ is interpreted as ‘a/(b*c)’. +Before evaluation by ‘calc-eval’ (*note calc-eval: (calc)Calling Calc +from Your Programs.), variable substitution takes place according to the +rules described above. The range vectors can be directly fed into the +Calc vector functions like ‘vmean’ and ‘vsum’. + + A formula can contain an optional mode string after a semicolon. +This string consists of flags to influence Calc and other modes during +execution. By default, Org uses the standard Calc modes (precision 12, +angular units degrees, fraction and symbolic modes off). The display +format, however, has been changed to ‘(float 8)’ to keep tables compact. +The default settings can be configured using the option +‘org-calc-default-modes’. + +List of modes: + +‘p20’ + Set the internal Calc calculation precision to 20 digits. +‘n3’, ‘s3’, ‘e2’, ‘f4’ + Normal, scientific, engineering or fixed format of the result of + Calc passed back to Org. Calc formatting is unlimited in precision + as long as the Calc calculation precision is greater. +‘D’, ‘R’ + Degree and radian angle modes of Calc. +‘F’, ‘S’ + Fraction and symbolic modes of Calc. +‘T’, ‘t’, ‘U’ + Duration computations in Calc or Lisp, *note Durations and time + values::. +‘E’ + If and how to consider empty fields. Without ‘E’ empty fields in + range references are suppressed so that the Calc vector or Lisp + list contains only the non-empty fields. With ‘E’ the empty fields + are kept. For empty fields in ranges or empty field references the + value ‘nan’ (not a number) is used in Calc formulas and the empty + string is used for Lisp formulas. Add ‘N’ to use 0 instead for + both formula types. For the value of a field the mode ‘N’ has + higher precedence than ‘E’. +‘N’ + Interpret all fields as numbers, use 0 for non-numbers. See the + next section to see how this is essential for computations with + Lisp formulas. In Calc formulas it is used only occasionally + because there number strings are already interpreted as numbers + without ‘N’. +‘L’ + Literal, for Lisp formulas only. See the next section. + +Unless you use large integer numbers or high-precision-calculation and +-display for floating point numbers you may alternatively provide a +‘printf’ format specifier to reformat the Calc result after it has been +passed back to Org instead of letting Calc already do the formatting(1). +A few examples: + + $1+$2 Sum of first and second field + $1+$2;%.2f Same, format result to two decimals + exp($2)+exp($1) Math functions can be used + $0;%.1f Reformat current cell to 1 decimal + ($3-32)*5/9 Degrees F -> C conversion + $c/$1/$cm Hz -> cm conversion, using ‘constants.el’ + tan($1);Dp3s1 Compute in degrees, precision 3, display SCI 1 + sin($1);Dp3%.1e Same, but use printf specifier for display + taylor($3,x=7,2) Taylor series of $3, at x=7, second degree + + Calc also contains a complete set of logical operations, (*note +Logical Operations: (calc)Logical Operations.). For example + +‘if($1 < 20, teen, string(""))’ + "teen" if age $1 is less than 20, else the Org table result field + is set to empty with the empty string. +‘if("$1" == "nan" || "$2" == "nan", string(""), $1 + $2); E f-1’ + Sum of the first two columns. When at least one of the input + fields is empty the Org table result field is set to empty. ‘E’ is + required to not convert empty fields to 0. ‘f-1’ is an optional + Calc format string similar to ‘%.1f’ but leaves empty results + empty. +‘if(typeof(vmean($1..$7)) == 12, string(""), vmean($1..$7); E’ + Mean value of a range unless there is any empty field. Every field + in the range that is empty is replaced by ‘nan’ which lets ‘vmean’ + result in ‘nan’. Then ‘typeof == 12’ detects the ‘nan’ from + ‘vmean’ and the Org table result field is set to empty. Use this + when the sample set is expected to never have missing values. +‘if("$1..$7" == "[]", string(""), vmean($1..$7))’ + Mean value of a range with empty fields skipped. Every field in + the range that is empty is skipped. When all fields in the range + are empty the mean value is not defined and the Org table result + field is set to empty. Use this when the sample set can have a + variable size. +‘vmean($1..$7); EN’ + To complete the example before: Mean value of a range with empty + fields counting as samples with value 0. Use this only when + incomplete sample sets should be padded with 0 to the full size. + + You can add your own Calc functions defined in Emacs Lisp with +‘defmath’ and use them in formula syntax for Calc. + + ---------- Footnotes ---------- + + (1) The ‘printf’ reformatting is limited in precision because the +value passed to it is converted into an ‘integer’ or ‘double’. The +‘integer’ is limited in size by truncating the signed value to 32 bits. +The ‘double’ is limited in precision to 64 bits overall which leaves +approximately 16 significant decimal digits. + + +File: org, Node: Formula syntax for Lisp, Next: Durations and time values, Prev: Formula syntax for Calc, Up: The spreadsheet + +3.5.3 Emacs Lisp forms as formulas +---------------------------------- + +It is also possible to write a formula in Emacs Lisp. This can be +useful for string manipulation and control structures, if Calc’s +functionality is not enough. + + If a formula starts with an apostrophe followed by an opening +parenthesis, then it is evaluated as a Lisp form. The evaluation should +return either a string or a number. Just as with ‘calc’ formulas, you +can specify modes and a printf format after a semicolon. + + With Emacs Lisp forms, you need to be conscious about the way field +references are interpolated into the form. By default, a reference will +be interpolated as a Lisp string (in double-quotes) containing the +field. If you provide the ‘N’ mode switch, all referenced elements will +be numbers (non-number fields will be zero) and interpolated as Lisp +numbers, without quotes. If you provide the ‘L’ flag, all fields will +be interpolated literally, without quotes. I.e., if you want a +reference to be interpreted as a string by the Lisp form, enclose the +reference operator itself in double-quotes, like ‘"$3"’. Ranges are +inserted as space-separated fields, so you can embed them in list or +vector syntax. + + Here are a few examples—note how the ‘N’ mode is used when we do +computations in Lisp: + +‘'(concat (substring $1 1 2) (substring $1 0 1) (substring $1 2))’ + Swap the first two characters of the content of column 1. +‘'(+ $1 $2);N’ + Add columns 1 and 2, equivalent to Calc’s ‘$1+$2’. +‘'(apply '+ '($1..$4));N’ + Compute the sum of columns 1 to 4, like Calc’s ‘vsum($1..$4)’. + + +File: org, Node: Durations and time values, Next: Field and range formulas, Prev: Formula syntax for Lisp, Up: The spreadsheet + +3.5.4 Durations and time values +------------------------------- + +If you want to compute time values use the ‘T’, ‘t’, or ‘U’ flag, either +in Calc formulas or Elisp formulas: + + | Task 1 | Task 2 | Total | + |---------+----------+----------| + | 2:12 | 1:47 | 03:59:00 | + | 2:12 | 1:47 | 03:59 | + | 3:02:20 | -2:07:00 | 0.92 | + #+TBLFM: @2$3=$1+$2;T::@3$3=$1+$2;U::@4$3=$1+$2;t + + Input duration values must be of the form ‘HH:MM[:SS]’, where seconds +are optional. With the ‘T’ flag, computed durations will be displayed +as ‘HH:MM:SS’ (see the first formula above). With the ‘U’ flag, seconds +will be omitted so that the result will be only ‘HH:MM’ (see second +formula above). Zero-padding of the hours field will depend upon the +value of the variable ‘org-table-duration-hour-zero-padding’. + + With the ‘t’ flag, computed durations will be displayed according to +the value of the option ‘org-table-duration-custom-format’, which +defaults to ‘'hours’ and will display the result as a fraction of hours +(see the third formula in the example above). + + Negative duration values can be manipulated as well, and integers +will be considered as seconds in addition and subtraction. + + +File: org, Node: Field and range formulas, Next: Column formulas, Prev: Durations and time values, Up: The spreadsheet + +3.5.5 Field and range formulas +------------------------------ + +To assign a formula to a particular field, type it directly into the +field, preceded by ‘:=’, for example ‘:=vsum(@II..III)’. When you press + or or ‘C-c C-c’ with the cursor still in the field, the +formula will be stored as the formula for this field, evaluated, and the +current field will be replaced with the result. + + Formulas are stored in a special line starting with ‘#+TBLFM:’ +directly below the table. If you type the equation in the 4th field of +the 3rd data line in the table, the formula will look like ‘@3$4=$1+$2’. +When inserting/deleting/swapping columns and rows with the appropriate +commands, absolute references (but not relative ones) in stored formulas +are modified in order to still reference the same field. To avoid this, +in particular in range references, anchor ranges at the table borders +(using ‘@<’, ‘@>’, ‘$<’, ‘$>’), or at hlines using the ‘@I’ notation. +Automatic adaptation of field references does of course not happen if +you edit the table structure with normal editing commands—then you must +fix the equations yourself. + + Instead of typing an equation into the field, you may also use the +following command + +‘C-u C-c = (org-table-eval-formula)’ + Install a new formula for the current field. The command prompts + for a formula with default taken from the ‘#+TBLFM:’ line, applies + it to the current field, and stores it. + + The left-hand side of a formula can also be a special expression in +order to assign the formula to a number of different fields. There is +no keyboard shortcut to enter such range formulas. To add them, use the +formula editor (*note Editing and debugging formulas::) or edit the +‘#+TBLFM:’ line directly. + +‘$2=’ + Column formula, valid for the entire column. This is so common + that Org treats these formulas in a special way, see *note Column + formulas::. +‘@3=’ + Row formula, applies to all fields in the specified row. ‘@>=’ + means the last row. +‘@1$2..@4$3=’ + Range formula, applies to all fields in the given rectangular + range. This can also be used to assign a formula to some but not + all fields in a row. +‘$name=’ + Named field, see *note Advanced features::. + + +File: org, Node: Column formulas, Next: Lookup functions, Prev: Field and range formulas, Up: The spreadsheet + +3.5.6 Column formulas +--------------------- + +When you assign a formula to a simple column reference like ‘$3=’, the +same formula will be used in all fields of that column, with the +following very convenient exceptions: (i) If the table contains +horizontal separator hlines with rows above and below, everything before +the first such hline is considered part of the table _header_ and will +not be modified by column formulas. Therefore a header is mandatory +when you use column formulas and want to add hlines to group rows, like +for example to separate a total row at the bottom from the summand rows +above. (ii) Fields that already get a value from a field/range formula +will be left alone by column formulas. These conditions make column +formulas very easy to use. + + To assign a formula to a column, type it directly into any field in +the column, preceded by an equal sign, like ‘=$1+$2’. When you press + or or ‘C-c C-c’ with the cursor still in the field, the +formula will be stored as the formula for the current column, evaluated +and the current field replaced with the result. If the field contains +only ‘=’, the previously stored formula for this column is used. For +each column, Org will only remember the most recently used formula. In +the ‘#+TBLFM:’ line, column formulas will look like ‘$4=$1+$2’. The +left-hand side of a column formula cannot be the name of column, it must +be the numeric column reference or ‘$>’. + + Instead of typing an equation into the field, you may also use the +following command: + +‘C-c = (org-table-eval-formula)’ + Install a new formula for the current column and replace current + field with the result of the formula. The command prompts for a + formula, with default taken from the ‘#+TBLFM’ line, applies it to + the current field and stores it. With a numeric prefix + argument(e.g., ‘C-5 C-c =’) the command will apply it to that many + consecutive fields in the current column. + + +File: org, Node: Lookup functions, Next: Editing and debugging formulas, Prev: Column formulas, Up: The spreadsheet + +3.5.7 Lookup functions +---------------------- + +Org has three predefined Emacs Lisp functions for lookups in tables. +‘(org-lookup-first VAL S-LIST R-LIST &optional PREDICATE)’ + Searches for the first element ‘S’ in list ‘S-LIST’ for which + (PREDICATE VAL S) + is ‘t’; returns the value from the corresponding position in list + ‘R-LIST’. The default ‘PREDICATE’ is ‘equal’. Note that the + parameters ‘VAL’ and ‘S’ are passed to ‘PREDICATE’ in the same + order as the corresponding parameters are in the call to + ‘org-lookup-first’, where ‘VAL’ precedes ‘S-LIST’. If ‘R-LIST’ is + ‘nil’, the matching element ‘S’ of ‘S-LIST’ is returned. +‘(org-lookup-last VAL S-LIST R-LIST &optional PREDICATE)’ + Similar to ‘org-lookup-first’ above, but searches for the last + element for which ‘PREDICATE’ is ‘t’. +‘(org-lookup-all VAL S-LIST R-LIST &optional PREDICATE)’ + Similar to ‘org-lookup-first’, but searches for all elements for + which ‘PREDICATE’ is ‘t’, and returns all corresponding values. + This function can not be used by itself in a formula, because it + returns a list of values. However, powerful lookups can be built + when this function is combined with other Emacs Lisp functions. + + If the ranges used in these functions contain empty fields, the ‘E’ +mode for the formula should usually be specified: otherwise empty fields +will not be included in ‘S-LIST’ and/or ‘R-LIST’ which can, for example, +result in an incorrect mapping from an element of ‘S-LIST’ to the +corresponding element of ‘R-LIST’. + + These three functions can be used to implement associative arrays, +count matching cells, rank results, group data etc. For practical +examples see this tutorial on Worg +(https://orgmode.org/worg/org-tutorials/org-lookups.html). + + +File: org, Node: Editing and debugging formulas, Next: Updating the table, Prev: Lookup functions, Up: The spreadsheet + +3.5.8 Editing and debugging formulas +------------------------------------ + +You can edit individual formulas in the minibuffer or directly in the +field. Org can also prepare a special buffer with all active formulas +of a table. When offering a formula for editing, Org converts +references to the standard format (like ‘B3’ or ‘D&’) if possible. If +you prefer to only work with the internal format (like ‘@3$2’ or ‘$4’), +configure the option ‘org-table-use-standard-references’. + +‘C-c = or C-u C-c = (org-table-eval-formula)’ + Edit the formula associated with the current column/field in the + minibuffer. See *note Column formulas::, and *note Field and range + formulas::. +‘C-u C-u C-c = (org-table-eval-formula)’ + Re-insert the active formula (either a field formula, or a column + formula) into the current field, so that you can edit it directly + in the field. The advantage over editing in the minibuffer is that + you can use the command ‘C-c ?’. +‘C-c ? (org-table-field-info)’ + While editing a formula in a table field, highlight the field(s) + referenced by the reference at the cursor position in the formula. +‘C-c }’ + Toggle the display of row and column numbers for a table, using + overlays (‘org-table-toggle-coordinate-overlays’). These are + updated each time the table is aligned; you can force it with ‘C-c + C-c’. +‘C-c {’ + Toggle the formula debugger on and off + (‘org-table-toggle-formula-debugger’). See below. +‘C-c ' (org-table-edit-formulas)’ + Edit all formulas for the current table in a special buffer, where + the formulas will be displayed one per line. If the current field + has an active formula, the cursor in the formula editor will mark + it. While inside the special buffer, Org will automatically + highlight any field or range reference at the cursor position. You + may edit, remove and add formulas, and use the following commands: + + ‘C-c C-c or C-x C-s (org-table-fedit-finish)’ + Exit the formula editor and store the modified formulas. With + ‘C-u’ prefix, also apply the new formulas to the entire table. + ‘C-c C-q (org-table-fedit-abort)’ + Exit the formula editor without installing changes. + ‘C-c C-r (org-table-fedit-toggle-ref-type)’ + Toggle all references in the formula editor between standard + (like ‘B3’) and internal (like ‘@3$2’). + ‘ (org-table-fedit-lisp-indent)’ + Pretty-print or indent Lisp formula at point. When in a line + containing a Lisp formula, format the formula according to + Emacs Lisp rules. Another collapses the formula back + again. In the open formula, re-indents just like in + Emacs Lisp mode. + ‘M- (lisp-complete-symbol)’ + Complete Lisp symbols, just like in Emacs Lisp mode.(1) + ‘S-///’ + Shift the reference at point. For example, if the reference + is ‘B3’ and you press ‘S-’, it will become ‘C3’. This + also works for relative references and for hline references. + ‘M-S- (org-table-fedit-line-up)’ + ‘M-S- (org-table-fedit-line-down)’ + Move the test line for column formulas in the Org buffer up + and down. + ‘M- (org-table-fedit-scroll-down)’ + ‘M- (org-table-fedit-scroll-up)’ + Scroll the window displaying the table. + ‘C-c }’ + Turn the coordinate grid in the table on and off. + + Making a table field blank does not remove the formula associated +with the field, because that is stored in a different line (the +‘#+TBLFM’ line)—during the next recalculation the field will be filled +again. To remove a formula from a field, you have to give an empty +reply when prompted for the formula, or to edit the ‘#+TBLFM’ line. + + You may edit the ‘#+TBLFM’ directly and re-apply the changed +equations with ‘C-c C-c’ in that line or with the normal recalculation +commands in the table. + +Using multiple ‘#+TBLFM’ lines +.............................. + +You may apply the formula temporarily. This is useful when you switch +the formula. Place multiple ‘#+TBLFM’ lines right after the table, and +then press ‘C-c C-c’ on the formula to apply. Here is an example: + + | x | y | + |---+---| + | 1 | | + | 2 | | + #+TBLFM: $2=$1*1 + #+TBLFM: $2=$1*2 + +Pressing ‘C-c C-c’ in the line of ‘#+TBLFM: $2=$1*2’ yields: + + | x | y | + |---+---| + | 1 | 2 | + | 2 | 4 | + #+TBLFM: $2=$1*1 + #+TBLFM: $2=$1*2 + +Note: If you recalculate this table (with ‘C-u C-c *’, for example), you +will get the following result of applying only the first ‘#+TBLFM’ line. + + | x | y | + |---+---| + | 1 | 1 | + | 2 | 2 | + #+TBLFM: $2=$1*1 + #+TBLFM: $2=$1*2 + +Debugging formulas +.................. + +When the evaluation of a formula leads to an error, the field content +becomes the string ‘#ERROR’. If you would like see what is going on +during variable substitution and calculation in order to find a bug, +turn on formula debugging in the ‘Tbl’ menu and repeat the calculation, +for example by pressing ‘C-u C-u C-c = ’ in a field. Detailed +information will be displayed. + + ---------- Footnotes ---------- + + (1) Many desktops intercept ‘M-’ to switch windows. Use ‘C-M-i’ +or ‘ ’ instead for completion (*note Completion::). + + +File: org, Node: Updating the table, Next: Advanced features, Prev: Editing and debugging formulas, Up: The spreadsheet + +3.5.9 Updating the table +------------------------ + +Recalculation of a table is normally not automatic, but needs to be +triggered by a command. See *note Advanced features::, for a way to +make recalculation at least semi-automatic. + + In order to recalculate a line of a table or the entire table, use +the following commands: + +‘C-c * (org-table-recalculate)’ + Recalculate the current row by first applying the stored column + formulas from left to right, and all field/range formulas in the + current row. +‘C-u C-c *’ +‘C-u C-c C-c’ + Recompute the entire table, line by line. Any lines before the + first hline are left alone, assuming that these are part of the + table header. +‘C-u C-u C-c * or C-u C-u C-c C-c (org-table-iterate)’ + Iterate the table by recomputing it until no further changes occur. + This may be necessary if some computed fields use the value of + other fields that are computed later in the calculation sequence. +‘M-x org-table-recalculate-buffer-tables ’ + Recompute all tables in the current buffer. +‘M-x org-table-iterate-buffer-tables ’ + Iterate all tables in the current buffer, in order to converge + table-to-table dependencies. + + +File: org, Node: Advanced features, Prev: Updating the table, Up: The spreadsheet + +3.5.10 Advanced features +------------------------ + +If you want the recalculation of fields to happen automatically, or if +you want to be able to assign names(1) to fields and columns, you need +to reserve the first column of the table for special marking characters. + +‘C-# (org-table-rotate-recalc-marks)’ + Rotate the calculation mark in first column through the states ‘ ’, + ‘#’, ‘*’, ‘!’, ‘$’. When there is an active region, change all + marks in the region. + + Here is an example of a table that collects exam results of students +and makes use of these features: + + |---+---------+--------+--------+--------+-------+------| + | | Student | Prob 1 | Prob 2 | Prob 3 | Total | Note | + |---+---------+--------+--------+--------+-------+------| + | ! | | P1 | P2 | P3 | Tot | | + | # | Maximum | 10 | 15 | 25 | 50 | 10.0 | + | ^ | | m1 | m2 | m3 | mt | | + |---+---------+--------+--------+--------+-------+------| + | # | Peter | 10 | 8 | 23 | 41 | 8.2 | + | # | Sam | 2 | 4 | 3 | 9 | 1.8 | + |---+---------+--------+--------+--------+-------+------| + | | Average | | | | 25.0 | | + | ^ | | | | | at | | + | $ | max=50 | | | | | | + |---+---------+--------+--------+--------+-------+------| + #+TBLFM: $6=vsum($P1..$P3)::$7=10*$Tot/$max;%.1f::$at=vmean(@-II..@-I);%.1f + +Important: please note that for these special tables, recalculating the +table with ‘C-u C-c *’ will only affect rows that are marked ‘#’ or ‘*’, +and fields that have a formula assigned to the field itself. The column +formulas are not applied in rows with empty first field. + + The marking characters have the following meaning: + +‘!’ + The fields in this line define names for the columns, so that you + may refer to a column as ‘$Tot’ instead of ‘$6’. +‘^’ + This row defines names for the fields _above_ the row. With such a + definition, any formula in the table may use ‘$m1’ to refer to the + value ‘10’. Also, if you assign a formula to a names field, it + will be stored as ‘$name=...’. +‘_’ + Similar to ‘^’, but defines names for the fields in the row + _below_. +‘$’ + Fields in this row can define _parameters_ for formulas. For + example, if a field in a ‘$’ row contains ‘max=50’, then formulas + in this table can refer to the value 50 using ‘$max’. Parameters + work exactly like constants, only that they can be defined on a + per-table basis. +‘#’ + Fields in this row are automatically recalculated when pressing + or or ‘S-’ in this row. Also, this row is + selected for a global recalculation with ‘C-u C-c *’. Unmarked + lines will be left alone by this command. +‘*’ + Selects this line for global recalculation with ‘C-u C-c *’, but + not for automatic recalculation. Use this when automatic + recalculation slows down editing too much. +‘ ’ + Unmarked lines are exempt from recalculation with ‘C-u C-c *’. All + lines that should be recalculated should be marked with ‘#’ or ‘*’. +‘/’ + Do not export this line. Useful for lines that contain the + narrowing ‘’ markers or column group markers. + + Finally, just to whet your appetite for what can be done with the +fantastic ‘calc.el’ package, here is a table that computes the Taylor +series of degree ‘n’ at location ‘x’ for a couple of functions. + + |---+-------------+---+-----+--------------------------------------| + | | Func | n | x | Result | + |---+-------------+---+-----+--------------------------------------| + | # | exp(x) | 1 | x | 1 + x | + | # | exp(x) | 2 | x | 1 + x + x^2 / 2 | + | # | exp(x) | 3 | x | 1 + x + x^2 / 2 + x^3 / 6 | + | # | x^2+sqrt(x) | 2 | x=0 | x*(0.5 / 0) + x^2 (2 - 0.25 / 0) / 2 | + | # | x^2+sqrt(x) | 2 | x=1 | 2 + 2.5 x - 2.5 + 0.875 (x - 1)^2 | + | * | tan(x) | 3 | x | 0.0175 x + 1.77e-6 x^3 | + |---+-------------+---+-----+--------------------------------------| + #+TBLFM: $5=taylor($2,$4,$3);n3 + + ---------- Footnotes ---------- + + (1) Such names must start by an alphabetic character and use only +alphanumeric/underscore characters. + + +File: org, Node: Org-Plot, Prev: The spreadsheet, Up: Tables + +3.6 Org-Plot +============ + +Org-Plot can produce graphs of information stored in org tables, either +graphically or in ASCII-art. + +Graphical plots using ‘Gnuplot’ +------------------------------- + +Org-Plot produces 2D and 3D graphs using ‘Gnuplot’ + and ‘gnuplot-mode’ +. To see this in action, ensure +that you have both Gnuplot and Gnuplot mode installed on your system, +then call ‘C-c " g’ or ‘M-x org-plot/gnuplot ’ on the following +table. + + #+PLOT: title:"Citas" ind:1 deps:(3) type:2d with:histograms set:"yrange [0:]" + | Sede | Max cites | H-index | + |-----------+-----------+---------| + | Chile | 257.72 | 21.39 | + | Leeds | 165.77 | 19.68 | + | Sao Paolo | 71.00 | 11.50 | + | Stockholm | 134.19 | 14.33 | + | Morelia | 257.56 | 17.67 | + + Notice that Org Plot is smart enough to apply the table’s headers as +labels. Further control over the labels, type, content, and appearance +of plots can be exercised through the ‘#+PLOT:’ lines preceding a table. +See below for a complete list of Org-plot options. The ‘#+PLOT:’ lines +are optional. For more information and examples see the Org-plot +tutorial at . + +Plot Options +............ + +‘set’ + Specify any ‘gnuplot’ option to be set when graphing. + +‘title’ + Specify the title of the plot. + +‘ind’ + Specify which column of the table to use as the ‘x’ axis. + +‘deps’ + Specify the columns to graph as a Lisp style list, surrounded by + parentheses and separated by spaces for example ‘dep:(3 4)’ to + graph the third and fourth columns (defaults to graphing all other + columns aside from the ‘ind’ column). + +‘type’ + Specify whether the plot will be ‘2d’, ‘3d’, or ‘grid’. + +‘with’ + Specify a ‘with’ option to be inserted for every col being plotted + (e.g., ‘lines’, ‘points’, ‘boxes’, ‘impulses’, etc...). Defaults + to ‘lines’. + +‘file’ + If you want to plot to a file, specify + ‘"PATH/TO/DESIRED/OUTPUT-FILE"’. + +‘labels’ + List of labels to be used for the ‘deps’ (defaults to the column + headers if they exist). + +‘line’ + Specify an entire line to be inserted in the Gnuplot script. + +‘map’ + When plotting ‘3d’ or ‘grid’ types, set this to ‘t’ to graph a flat + mapping rather than a ‘3d’ slope. + +‘timefmt’ + Specify format of Org mode timestamps as they will be parsed by + Gnuplot. Defaults to ‘%Y-%m-%d-%H:%M:%S’. + +‘script’ + If you want total control, you can specify a script file (place the + file name between double-quotes) which will be used to plot. + Before plotting, every instance of ‘$datafile’ in the specified + script will be replaced with the path to the generated data file. + Note: even if you set this option, you may still want to specify + the plot type, as that can impact the content of the data file. + +ASCII bar plots +--------------- + +While the cursor is on a column, typing ‘C-c " a’ or ‘M-x +orgtbl-ascii-plot ’ create a new column containing an ASCII-art +bars plot. The plot is implemented through a regular column formula. +When the source column changes, the bar plot may be updated by +refreshing the table, for example typing ‘C-u C-c *’. + + | Sede | Max cites | | + |---------------+-----------+--------------| + | Chile | 257.72 | WWWWWWWWWWWW | + | Leeds | 165.77 | WWWWWWWh | + | Sao Paolo | 71.00 | WWW; | + | Stockholm | 134.19 | WWWWWW: | + | Morelia | 257.56 | WWWWWWWWWWWH | + | Rochefourchat | 0.00 | | + #+TBLFM: $3='(orgtbl-ascii-draw $2 0.0 257.72 12) + + The formula is an elisp call: + (orgtbl-ascii-draw COLUMN MIN MAX WIDTH) + +‘COLUMN’ + is a reference to the source column. + +‘MIN MAX’ + are the minimal and maximal values displayed. Sources values + outside this range are displayed as ‘too small’ or ‘too large’. + +‘WIDTH’ + is the width in characters of the bar-plot. It defaults to ‘12’. + + +File: org, Node: Hyperlinks, Next: TODO items, Prev: Tables, Up: Top + +4 Hyperlinks +************ + +Like HTML, Org provides links inside a file, external links to other +files, Usenet articles, emails, and much more. + +* Menu: + +* Link format:: How links in Org are formatted +* Internal links:: Links to other places in the current file +* External links:: URL-like links to the world +* Handling links:: Creating, inserting and following +* Using links outside Org:: Linking from my C source code? +* Link abbreviations:: Shortcuts for writing complex links +* Search options:: Linking to a specific location +* Custom searches:: When the default search is not enough + + +File: org, Node: Link format, Next: Internal links, Up: Hyperlinks + +4.1 Link format +=============== + +Org will recognize plain URL-like links and activate them as clickable +links. The general link format, however, looks like this: + + [[link][description]] or alternatively [[link]] + +Once a link in the buffer is complete (all brackets present), Org will +change the display so that ‘description’ is displayed instead of +‘[[link][description]]’ and ‘link’ is displayed instead of ‘[[link]]’. +Links will be highlighted in the face ‘org-link’, which by default is an +underlined face. You can directly edit the visible part of a link. +Note that this can be either the ‘link’ part (if there is no +description) or the ‘description’ part. To edit also the invisible +‘link’ part, use ‘C-c C-l’ with the cursor on the link. + + If you place the cursor at the beginning or just behind the end of +the displayed text and press , you will remove the +(invisible) bracket at that location. This makes the link incomplete +and the internals are again displayed as plain text. Inserting the +missing bracket hides the link internals again. To show the internal +structure of all links, use the menu entry ‘Org->Hyperlinks->Literal +links’. + + +File: org, Node: Internal links, Next: External links, Prev: Link format, Up: Hyperlinks + +4.2 Internal links +================== + +If the link does not look like a URL, it is considered to be internal in +the current file. The most important case is a link like +‘[[#my-custom-id]]’ which will link to the entry with the ‘CUSTOM_ID’ +property ‘my-custom-id’. You are responsible yourself to make sure +these custom IDs are unique in a file. + + Links such as ‘[[My Target]]’ or ‘[[My Target][Find my target]]’ lead +to a text search in the current file. + + The link can be followed with ‘C-c C-o’ when the cursor is on the +link, or with a mouse click (*note Handling links::). Links to custom +IDs will point to the corresponding headline. The preferred match for a +text link is a dedicated target: the same string in double angular +brackets, like ‘<>’. + + If no dedicated target exists, the link will then try to match the +exact name of an element within the buffer. Naming is done with the +‘#+NAME’ keyword, which has to be put in the line before the element it +refers to, as in the following example + + #+NAME: My Target + | a | table | + |----+------------| + | of | four cells | + + If none of the above succeeds, Org will search for a headline that is +exactly the link text but may also include a TODO keyword and tags(1). + + During export, internal links will be used to mark objects and assign +them a number. Marked objects will then be referenced by links pointing +to them. In particular, links without a description will appear as the +number assigned to the marked object(2). In the following excerpt from +an Org buffer + + - one item + - <>another item + Here we refer to item [[target]]. + +The last sentence will appear as ‘Here we refer to item 2’ when +exported. + + In non-Org files, the search will look for the words in the link +text. In the above example the search would be for ‘my target’. + + Following a link pushes a mark onto Org’s own mark ring. You can +return to the previous position with ‘C-c &’. Using this command +several times in direct succession goes back to positions recorded +earlier. + +* Menu: + +* Radio targets:: Make targets trigger links in plain text + + ---------- Footnotes ---------- + + (1) To insert a link targeting a headline, in-buffer completion can +be used. Just type a star followed by a few optional letters into the +buffer and press ‘M-’. All headlines in the current buffer will be +offered as completions. + + (2) When targeting a ‘#+NAME’ keyword, ‘#+CAPTION’ keyword is +mandatory in order to get proper numbering (*note Images and tables::). + + +File: org, Node: Radio targets, Up: Internal links + +4.2.1 Radio targets +------------------- + +Org can automatically turn any occurrences of certain target names in +normal text into a link. So without explicitly creating a link, the +text connects to the target radioing its position. Radio targets are +enclosed by triple angular brackets. For example, a target ‘<<>>’ causes each occurrence of ‘my target’ in normal text to +become activated as a link. The Org file is scanned automatically for +radio targets only when the file is first loaded into Emacs. To update +the target list during editing, press ‘C-c C-c’ with the cursor on or at +a target. + + +File: org, Node: External links, Next: Handling links, Prev: Internal links, Up: Hyperlinks + +4.3 External links +================== + +Org supports links to files, websites, Usenet and email messages, BBDB +database entries and links to both IRC conversations and their logs. +External links are URL-like locators. They start with a short +identifying string followed by a colon. There can be no space after the +colon. The following list shows examples for each link type. + + http://www.astro.uva.nl/~dominik on the web + doi:10.1000/182 DOI for an electronic resource + file:/home/dominik/images/jupiter.jpg file, absolute path + /home/dominik/images/jupiter.jpg same as above + file:papers/last.pdf file, relative path + ./papers/last.pdf same as above + file:/ssh:myself@some.where:papers/last.pdf file, path on remote machine + /ssh:myself@some.where:papers/last.pdf same as above + file:sometextfile::NNN file, jump to line number + file:projects.org another Org file + file:projects.org::some words text search in Org file(1) + file:projects.org::*task title heading search in Org file(2) + docview:papers/last.pdf::NNN open in doc-view mode at page + id:B7423F4D-2E8A-471B-8810-C40F074717E9 Link to heading by ID + news:comp.emacs Usenet link + mailto:adent@galaxy.net Mail link + mhe:folder MH-E folder link + mhe:folder#id MH-E message link + rmail:folder RMAIL folder link + rmail:folder#id RMAIL message link + gnus:group Gnus group link + gnus:group#id Gnus article link + bbdb:R.*Stallman BBDB link (with regexp) + irc:/irc.com/#emacs/bob IRC link + info:org#External links Info node or index link + shell:ls *.org A shell command + elisp:org-agenda Interactive Elisp command + elisp:(find-file-other-frame "Elisp.org") Elisp form to evaluate + + On top of these built-in link types, some are available through the +‘contrib/’ directory (*note Installation::). For example, these links +to VM or Wanderlust messages are available when you load the +corresponding libraries from the ‘contrib/’ directory: + + vm:folder VM folder link + vm:folder#id VM message link + vm://myself@some.where.org/folder#id VM on remote machine + vm-imap:account:folder VM IMAP folder link + vm-imap:account:folder#id VM IMAP message link + wl:folder WANDERLUST folder link + wl:folder#id WANDERLUST message link + + For customizing Org to add new link types *note Adding hyperlink +types::. + + A link should be enclosed in double brackets and may contain a +descriptive text to be displayed instead of the URL (*note Link +format::), for example: + + [[https://www.gnu.org/software/emacs/][GNU Emacs]] + +If the description is a file name or URL that points to an image, HTML +export (*note HTML export::) will inline the image as a clickable +button. If there is no description at all and the link points to an +image, that image will be inlined into the exported HTML file. + + Org also finds external links in the normal text and activates them +as links. If spaces must be part of the link (for example in +‘bbdb:Richard Stallman’), or if you need to remove ambiguities about the +end of the link, enclose them in square brackets. + + ---------- Footnotes ---------- + + (1) The actual behavior of the search will depend on the value of the +option ‘org-link-search-must-match-exact-headline’. If its value is +‘nil’, then a fuzzy text search will be done. If it is ‘t’, then only +the exact headline will be matched, ignoring spaces and cookies. If the +value is ‘query-to-create’, then an exact headline will be searched; if +it is not found, then the user will be queried to create it. + + (2) Headline searches always match the exact headline, ignoring +spaces and cookies. If the headline is not found and the value of the +option ‘org-link-search-must-match-exact-headline’ is ‘query-to-create’, +then the user will be queried to create it. + + +File: org, Node: Handling links, Next: Using links outside Org, Prev: External links, Up: Hyperlinks + +4.4 Handling links +================== + +Org provides methods to create a link in the correct syntax, to insert +it into an Org file, and to follow the link. + +‘C-c l (org-store-link)’ + Store a link to the current location. This is a _global_ command + (you must create the key binding yourself) which can be used in any + buffer to create a link. The link will be stored for later + insertion into an Org buffer (see below). What kind of link will + be created depends on the current buffer: + + Org mode buffers + For Org files, if there is a ‘<>’ at the cursor, the link + points to the target. Otherwise it points to the current headline, + which will also be the description(1). + + If the headline has a ‘CUSTOM_ID’ property, a link to this custom + ID will be stored. In addition or alternatively (depending on the + value of ‘org-id-link-to-org-use-id’), a globally unique ‘ID’ + property will be created and/or used to construct a link(2). So + using this command in Org buffers will potentially create two + links: a human-readable from the custom ID, and one that is + globally unique and works even if the entry is moved from file to + file. Later, when inserting the link, you need to decide which one + to use. + + Email/News clients: VM, Rmail, Wanderlust, MH-E, Gnus + Pretty much all Emacs mail clients are supported. The link will + point to the current article, or, in some GNUS buffers, to the + group. The description is constructed from the author and the + subject. + + Web browsers: Eww, W3 and W3M + Here the link will be the current URL, with the page title as + description. + + Contacts: BBDB + Links created in a BBDB buffer will point to the current entry. + + Chat: IRC + For IRC links, if you set the option ‘org-irc-link-to-logs’ to ‘t’, + a ‘file:/’ style link to the relevant point in the logs for the + current conversation is created. Otherwise an ‘irc:/’ style link + to the user/channel/server under the point will be stored. + + Other files + For any other files, the link will point to the file, with a search + string (*note Search options::) pointing to the contents of the + current line. If there is an active region, the selected words + will form the basis of the search string. If the automatically + created link is not working correctly or accurately enough, you can + write custom functions to select the search string and to do the + search for particular file types—see *note Custom searches::. The + key binding ‘C-c l’ is only a suggestion—see *note Installation::. + + Agenda view + When the cursor is in an agenda view, the created link points to + the entry referenced by the current line. + +‘C-c C-l (org-insert-link)’ + Insert a link(3). This prompts for a link to be inserted into the + buffer. You can just type a link, using text for an internal link, + or one of the link type prefixes mentioned in the examples above. + The link will be inserted into the buffer(4), along with a + descriptive text. If some text was selected when this command is + called, the selected text becomes the default description. + + Inserting stored links + All links stored during the current session are part of the history + for this prompt, so you can access them with and (or + ‘M-p/n’). + + Completion support + Completion with will help you to insert valid link prefixes + like ‘https:’, including the prefixes defined through link + abbreviations (*note Link abbreviations::). If you press + after inserting only the PREFIX, Org will offer specific completion + support for some link types(5) For example, if you type ‘file + ’, file name completion (alternative access: ‘C-u C-c C-l’, + see below) will be offered, and after ‘bbdb ’ you can complete + contact names. +‘C-u C-c C-l’ + When ‘C-c C-l’ is called with a ‘C-u’ prefix argument, a link to a + file will be inserted and you may use file name completion to + select the name of the file. The path to the file is inserted + relative to the directory of the current Org file, if the linked + file is in the current directory or in a sub-directory of it, or if + the path is written relative to the current directory using ‘../’. + Otherwise an absolute path is used, if possible with ‘~/’ for your + home directory. You can force an absolute path with two ‘C-u’ + prefixes. +‘C-c C-l (with cursor on existing link)’ + When the cursor is on an existing link, ‘C-c C-l’ allows you to + edit the link and description parts of the link. +‘C-c C-o (org-open-at-point)’ + Open link at point. This will launch a web browser for URLs (using + ‘browse-url-at-point’), run VM/MH-E/Wanderlust/Rmail/Gnus/BBDB for + the corresponding links, and execute the command in a shell link. + When the cursor is on an internal link, this command runs the + corresponding search. When the cursor is on a TAG list in a + headline, it creates the corresponding TAGS view. If the cursor is + on a timestamp, it compiles the agenda for that date. Furthermore, + it will visit text and remote files in ‘file:’ links with Emacs and + select a suitable application for local non-text files. + Classification of files is based on file extension only. See + option ‘org-file-apps’. If you want to override the default + application and visit the file with Emacs, use a ‘C-u’ prefix. If + you want to avoid opening in Emacs, use a ‘C-u C-u’ prefix. + If the cursor is on a headline, but not on a link, offer all links + in the headline and entry text. If you want to setup the frame + configuration for following links, customize + ‘org-link-frame-setup’. + +‘’ + When ‘org-return-follows-link’ is set, ‘’ will also follow the + link at point. +‘mouse-2’ +‘mouse-1’ + On links, ‘mouse-1’ and ‘mouse-2’ will open the link just as ‘C-c + C-o’ would. +‘mouse-3’ + Like ‘mouse-2’, but force file links to be opened with Emacs, and + internal links to be displayed in another window(6). +‘C-c C-x C-v (org-toggle-inline-images)’ + Toggle the inline display of linked images. Normally this will + only inline images that have no description part in the link, i.e., + images that will also be inlined during export. When called with a + prefix argument, also display images that do have a link + description. You can ask for inline images to be displayed at + startup by configuring the variable + ‘org-startup-with-inline-images’(7). +‘C-c % (org-mark-ring-push)’ + Push the current position onto the mark ring, to be able to return + easily. Commands following an internal link do this automatically. +‘C-c & (org-mark-ring-goto)’ + Jump back to a recorded position. A position is recorded by the + commands following internal links, and by ‘C-c %’. Using this + command several times in direct succession moves through a ring of + previously recorded positions. +‘C-c C-x C-n (org-next-link)’ +‘C-c C-x C-p (org-previous-link)’ + Move forward/backward to the next link in the buffer. At the limit + of the buffer, the search fails once, and then wraps around. The + key bindings for this are really too long; you might want to bind + this also to ‘C-n’ and ‘C-p’ + (add-hook 'org-load-hook + (lambda () + (define-key org-mode-map "\C-n" 'org-next-link) + (define-key org-mode-map "\C-p" 'org-previous-link))) + + ---------- Footnotes ---------- + + (1) If the headline contains a timestamp, it will be removed from the +link and result in a wrong link—you should avoid putting timestamp in +the headline. + + (2) The library ‘org-id.el’ must first be loaded, either through +‘org-customize’ by enabling ‘org-id’ in ‘org-modules’, or by adding +‘(require 'org-id)’ in your Emacs init file. + + (3) Note that you don’t have to use this command to insert a link. +Links in Org are plain text, and you can type or paste them straight +into the buffer. By using this command, the links are automatically +enclosed in double brackets, and you will be asked for the optional +descriptive text. + + (4) After insertion of a stored link, the link will be removed from +the list of stored links. To keep it in the list later use, use a +triple ‘C-u’ prefix argument to ‘C-c C-l’, or configure the option +‘org-keep-stored-link-after-insertion’. + + (5) This works if a completion function is defined in the ‘:complete’ +property of a link in ‘org-link-parameters’. + + (6) See the option ‘org-display-internal-link-with-indirect-buffer’ + + (7) with corresponding ‘#+STARTUP’ keywords ‘inlineimages’ and +‘noinlineimages’ + + +File: org, Node: Using links outside Org, Next: Link abbreviations, Prev: Handling links, Up: Hyperlinks + +4.5 Using links outside Org +=========================== + +You can insert and follow links that have Org syntax not only in Org, +but in any Emacs buffer. For this, you should create two global +commands, like this (please select suitable global keys yourself): + + (global-set-key "\C-c L" 'org-insert-link-global) + (global-set-key "\C-c o" 'org-open-at-point-global) + + +File: org, Node: Link abbreviations, Next: Search options, Prev: Using links outside Org, Up: Hyperlinks + +4.6 Link abbreviations +====================== + +Long URLs can be cumbersome to type, and often many similar links are +needed in a document. For this you can use link abbreviations. An +abbreviated link looks like this + + [[linkword:tag][description]] + +where the tag is optional. The linkword must be a word, starting with a +letter, followed by letters, numbers, ‘-’, and ‘_’. Abbreviations are +resolved according to the information in the variable +‘org-link-abbrev-alist’ that relates the linkwords to replacement text. +Here is an example: + + (setq org-link-abbrev-alist + '(("bugzilla" . "http://10.1.2.9/bugzilla/show_bug.cgi?id=") + ("url-to-ja" . "http://translate.google.fr/translate?sl=en&tl=ja&u=%h") + ("google" . "http://www.google.com/search?q=") + ("gmap" . "http://maps.google.com/maps?q=%s") + ("omap" . "http://nominatim.openstreetmap.org/search?q=%s&polygon=1") + ("ads" . "http://adsabs.harvard.edu/cgi-bin/nph-abs_connect?author=%s&db_key=AST"))) + + If the replacement text contains the string ‘%s’, it will be replaced +with the tag. Using ‘%h’ instead of ‘%s’ will url-encode the tag (see +the example above, where we need to encode the URL parameter.) Using +‘%(my-function)’ will pass the tag to a custom function, and replace it +by the resulting string. + + If the replacement text doesn’t contain any specifier, the tag will +simply be appended in order to create the link. + + Instead of a string, you may also specify a function that will be +called with the tag as the only argument to create the link. + + With the above setting, you could link to a specific bug with +‘[[bugzilla:129]]’, search the web for ‘OrgMode’ with +‘[[google:OrgMode]]’, show the map location of the Free Software +Foundation ‘[[gmap:51 Franklin Street, Boston]]’ or of Carsten office +‘[[omap:Science Park 904, Amsterdam, The Netherlands]]’ and find out +what the Org author is doing besides Emacs hacking with +‘[[ads:Dominik,C]]’. + + If you need special abbreviations just for a single Org buffer, you +can define them in the file with + + #+LINK: bugzilla http://10.1.2.9/bugzilla/show_bug.cgi?id= + #+LINK: google http://www.google.com/search?q=%s + +In-buffer completion (*note Completion::) can be used after ‘[’ to +complete link abbreviations. You may also define a function that +implements special (e.g., completion) support for inserting such a link +with ‘C-c C-l’. Such a function should not accept any arguments, and +return the full link with prefix. You can add a completion function to +a link like this: + + (org-link-set-parameters ``type'' :complete #'some-function) + + +File: org, Node: Search options, Next: Custom searches, Prev: Link abbreviations, Up: Hyperlinks + +4.7 Search options in file links +================================ + +File links can contain additional information to make Emacs jump to a +particular location in the file when following a link. This can be a +line number or a search option after a double(1) colon. For example, +when the command ‘C-c l’ creates a link (*note Handling links::) to a +file, it encodes the words in the current line as a search string that +can be used to find this line back later when following the link with +‘C-c C-o’. + + Here is the syntax of the different ways to attach a search to a file +link, together with an explanation: + + [[file:~/code/main.c::255]] + [[file:~/xx.org::My Target]] + [[file:~/xx.org::*My Target]] + [[file:~/xx.org::#my-custom-id]] + [[file:~/xx.org::/regexp/]] + +‘255’ + Jump to line 255. +‘My Target’ + Search for a link target ‘<>’, or do a text search for + ‘my target’, similar to the search in internal links, see *note + Internal links::. In HTML export (*note HTML export::), such a + file link will become an HTML reference to the corresponding named + anchor in the linked file. +‘*My Target’ + In an Org file, restrict search to headlines. +‘#my-custom-id’ + Link to a heading with a ‘CUSTOM_ID’ property +‘/regexp/’ + Do a regular expression search for ‘regexp’. This uses the Emacs + command ‘occur’ to list all matches in a separate window. If the + target file is in Org mode, ‘org-occur’ is used to create a sparse + tree with the matches. + + As a degenerate case, a file link with an empty file name can be used +to search the current file. For example, ‘[[file:::find me]]’ does a +search for ‘find me’ in the current file, just as ‘[[find me]]’ would. + + ---------- Footnotes ---------- + + (1) For backward compatibility, line numbers can also follow a single +colon. + + +File: org, Node: Custom searches, Prev: Search options, Up: Hyperlinks + +4.8 Custom Searches +=================== + +The default mechanism for creating search strings and for doing the +actual search related to a file link may not work correctly in all +cases. For example, BibTeX database files have many entries like +‘year="1993"’ which would not result in good search strings, because the +only unique identification for a BibTeX entry is the citation key. + + If you come across such a problem, you can write custom functions to +set the right search string for a particular file type, and to do the +search for the string in the file. Using ‘add-hook’, these functions +need to be added to the hook variables +‘org-create-file-search-functions’ and +‘org-execute-file-search-functions’. See the docstring for these +variables for more information. Org actually uses this mechanism for +BibTeX database files, and you can use the corresponding code as an +implementation example. See the file ‘org-bibtex.el’. + + +File: org, Node: TODO items, Next: Tags, Prev: Hyperlinks, Up: Top + +5 TODO items +************ + +Org mode does not maintain TODO lists as separate documents(1). +Instead, TODO items are an integral part of the notes file, because TODO +items usually come up while taking notes! With Org mode, simply mark +any entry in a tree as being a TODO item. In this way, information is +not duplicated, and the entire context from which the TODO item emerged +is always present. + + Of course, this technique for managing TODO items scatters them +throughout your notes file. Org mode compensates for this by providing +methods to give you an overview of all the things that you have to do. + +* Menu: + +* TODO basics:: Marking and displaying TODO entries +* TODO extensions:: Workflow and assignments +* Progress logging:: Dates and notes for progress +* Priorities:: Some things are more important than others +* Breaking down tasks:: Splitting a task into manageable pieces +* Checkboxes:: Tick-off lists + + ---------- Footnotes ---------- + + (1) Of course, you can make a document that contains only long lists +of TODO items, but this is not required. + + +File: org, Node: TODO basics, Next: TODO extensions, Up: TODO items + +5.1 Basic TODO functionality +============================ + +Any headline becomes a TODO item when it starts with the word ‘TODO’, +for example: + + *** TODO Write letter to Sam Fortune + +The most important commands to work with TODO entries are: + +‘C-c C-t (org-todo)’ + + Rotate the TODO state of the current item among + + ,-> (unmarked) -> TODO -> DONE --. + '--------------------------------' + + If TODO keywords have fast access keys (see *note Fast access to + TODO states::), you will be prompted for a TODO keyword through the + fast selection interface; this is the default behavior when + ‘org-use-fast-todo-selection’ is non-‘nil’. + + The same rotation can also be done “remotely” from agenda buffers + with the ‘t’ command key (*note Agenda commands::). + +‘C-u C-c C-t’ + When TODO keywords have no selection keys, select a specific + keyword using completion; otherwise force cycling through TODO + states with no prompt. When ‘org-use-fast-todo-selection’ is set + to ‘prefix’, use the fast selection interface. + +‘S- / S-’ + Select the following/preceding TODO state, similar to cycling. + Useful mostly if more than two TODO states are possible (*note TODO + extensions::). See also *note Conflicts::, for a discussion of the + interaction with ‘shift-selection-mode’. See also the variable + ‘org-treat-S-cursor-todo-selection-as-state-change’. +‘C-c / t (org-show-todo-tree)’ + View TODO items in a _sparse tree_ (*note Sparse trees::). Folds + the entire buffer, but shows all TODO items (with not-DONE state) + and the headings hierarchy above them. With a prefix argument (or + by using ‘C-c / T’), search for a specific TODO. You will be + prompted for the keyword, and you can also give a list of keywords + like ‘KWD1|KWD2|...’ to list entries that match any one of these + keywords. With a numeric prefix argument N, show the tree for the + Nth keyword in the option ‘org-todo-keywords’. With two prefix + arguments, find all TODO states, both un-done and done. +‘C-c a t (org-todo-list)’ + Show the global TODO list. Collects the TODO items (with not-DONE + states) from all agenda files (*note Agenda views::) into a single + buffer. The new buffer will be in ‘agenda-mode’, which provides + commands to examine and manipulate the TODO entries from the new + buffer (*note Agenda commands::). *Note Global TODO list::, for + more information. +‘S-M- (org-insert-todo-heading)’ + Insert a new TODO entry below the current one. + +Changing a TODO state can also trigger tag changes. See the docstring +of the option ‘org-todo-state-tags-triggers’ for details. + + +File: org, Node: TODO extensions, Next: Progress logging, Prev: TODO basics, Up: TODO items + +5.2 Extended use of TODO keywords +================================= + +By default, marked TODO entries have one of only two states: TODO and +DONE. Org mode allows you to classify TODO items in more complex ways +with _TODO keywords_ (stored in ‘org-todo-keywords’). With special +setup, the TODO keyword system can work differently in different files. + + Note that tags are another way to classify headlines in general and +TODO items in particular (*note Tags::). + +* Menu: + +* Workflow states:: From TODO to DONE in steps +* TODO types:: I do this, Fred does the rest +* Multiple sets in one file:: Mixing it all, and still finding your way +* Fast access to TODO states:: Single letter selection of a state +* Per-file keywords:: Different files, different requirements +* Faces for TODO keywords:: Highlighting states +* TODO dependencies:: When one task needs to wait for others + + +File: org, Node: Workflow states, Next: TODO types, Up: TODO extensions + +5.2.1 TODO keywords as workflow states +-------------------------------------- + +You can use TODO keywords to indicate different _sequential_ states in +the process of working on an item, for example(1): + + (setq org-todo-keywords + '((sequence "TODO" "FEEDBACK" "VERIFY" "|" "DONE" "DELEGATED"))) + + The vertical bar separates the TODO keywords (states that _need +action_) from the DONE states (which need _no further action_). If you +don’t provide the separator bar, the last state is used as the DONE +state. With this setup, the command ‘C-c C-t’ will cycle an entry from +TODO to FEEDBACK, then to VERIFY, and finally to DONE and DELEGATED. +You may also use a numeric prefix argument to quickly select a specific +state. For example ‘C-3 C-c C-t’ will change the state immediately to +VERIFY. Or you can use ‘S-’ to go backward through the sequence. +If you define many keywords, you can use in-buffer completion (*note +Completion::) or even a special one-key selection scheme (*note Fast +access to TODO states::) to insert these words into the buffer. +Changing a TODO state can be logged with a timestamp, see *note Tracking +TODO state changes::, for more information. + + ---------- Footnotes ---------- + + (1) Changing this variable only becomes effective after restarting +Org mode in a buffer. + + +File: org, Node: TODO types, Next: Multiple sets in one file, Prev: Workflow states, Up: TODO extensions + +5.2.2 TODO keywords as types +---------------------------- + +The second possibility is to use TODO keywords to indicate different +_types_ of action items. For example, you might want to indicate that +items are for “work” or “home”. Or, when you work with several people +on a single project, you might want to assign action items directly to +persons, by using their names as TODO keywords. This would be set up +like this: + + (setq org-todo-keywords '((type "Fred" "Sara" "Lucy" "|" "DONE"))) + + In this case, different keywords do not indicate a sequence, but +rather different types. So the normal work flow would be to assign a +task to a person, and later to mark it DONE. Org mode supports this +style by adapting the workings of the command ‘C-c C-t’(1). When used +several times in succession, it will still cycle through all names, in +order to first select the right type for a task. But when you return to +the item after some time and execute ‘C-c C-t’ again, it will switch +from any name directly to DONE. Use prefix arguments or completion to +quickly select a specific name. You can also review the items of a +specific TODO type in a sparse tree by using a numeric prefix to ‘C-c / +t’. For example, to see all things Lucy has to do, you would use ‘C-3 +C-c / t’. To collect Lucy’s items from all agenda files into a single +buffer, you would use the numeric prefix argument as well when creating +the global TODO list: ‘C-3 C-c a t’. + + ---------- Footnotes ---------- + + (1) This is also true for the ‘t’ command in the agenda buffers. + + +File: org, Node: Multiple sets in one file, Next: Fast access to TODO states, Prev: TODO types, Up: TODO extensions + +5.2.3 Multiple keyword sets in one file +--------------------------------------- + +Sometimes you may want to use different sets of TODO keywords in +parallel. For example, you may want to have the basic ‘TODO’/‘DONE’, +but also a workflow for bug fixing, and a separate state indicating that +an item has been canceled (so it is not DONE, but also does not require +action). Your setup would then look like this: + + (setq org-todo-keywords + '((sequence "TODO" "|" "DONE") + (sequence "REPORT" "BUG" "KNOWNCAUSE" "|" "FIXED") + (sequence "|" "CANCELED"))) + + The keywords should all be different, this helps Org mode to keep +track of which subsequence should be used for a given entry. In this +setup, ‘C-c C-t’ only operates within a subsequence, so it switches from +‘DONE’ to (nothing) to ‘TODO’, and from ‘FIXED’ to (nothing) to +‘REPORT’. Therefore you need a mechanism to initially select the +correct sequence. Besides the obvious ways like typing a keyword or +using completion, you may also apply the following commands: + +‘C-u C-u C-c C-t’ +‘C-S-’ +‘C-S-’ + These keys jump from one TODO subset to the next. In the above + example, ‘C-u C-u C-c C-t’ or ‘C-S-’ would jump from ‘TODO’ + or ‘DONE’ to ‘REPORT’, and any of the words in the second row to + ‘CANCELED’. Note that the ‘C-S-’ key binding conflict with + ‘shift-selection-mode’ (*note Conflicts::). +‘S-’ +‘S-’ + ‘S-’ and ‘S-’ and walk through _all_ keywords from all + sets, so for example ‘S-’ would switch from ‘DONE’ to + ‘REPORT’ in the example above. See also *note Conflicts::, for a + discussion of the interaction with ‘shift-selection-mode’. + + +File: org, Node: Fast access to TODO states, Next: Per-file keywords, Prev: Multiple sets in one file, Up: TODO extensions + +5.2.4 Fast access to TODO states +-------------------------------- + +If you would like to quickly change an entry to an arbitrary TODO state +instead of cycling through the states, you can set up keys for +single-letter access to the states. This is done by adding the +selection character after each keyword, in parentheses(1). For example: + + (setq org-todo-keywords + '((sequence "TODO(t)" "|" "DONE(d)") + (sequence "REPORT(r)" "BUG(b)" "KNOWNCAUSE(k)" "|" "FIXED(f)") + (sequence "|" "CANCELED(c)"))) + + If you then press ‘C-c C-t’ followed by the selection key, the entry +will be switched to this state. ‘’ can be used to remove any TODO +keyword from an entry.(2) + + ---------- Footnotes ---------- + + (1) All characters are allowed except ‘@^!’, which have a special +meaning here. + + (2) Check also the option ‘org-fast-tag-selection-include-todo’, it +allows you to change the TODO state through the tags interface (*note +Setting tags::), in case you like to mingle the two concepts. Note that +this means you need to come up with unique keys across both sets of +keywords. + + +File: org, Node: Per-file keywords, Next: Faces for TODO keywords, Prev: Fast access to TODO states, Up: TODO extensions + +5.2.5 Setting up keywords for individual files +---------------------------------------------- + +It can be very useful to use different aspects of the TODO mechanism in +different files. For file-local settings, you need to add special lines +to the file which set the keywords and interpretation for that file +only. For example, to set one of the two examples discussed above, you +need one of the following lines anywhere in the file: + + #+TODO: TODO FEEDBACK VERIFY | DONE CANCELED +(you may also write ‘#+SEQ_TODO’ to be explicit about the +interpretation, but it means the same as ‘#+TODO’), or + #+TYP_TODO: Fred Sara Lucy Mike | DONE + + A setup for using several sets in parallel would be: + + #+TODO: TODO | DONE + #+TODO: REPORT BUG KNOWNCAUSE | FIXED + #+TODO: | CANCELED + +To make sure you are using the correct keyword, type ‘#+’ into the +buffer and then use ‘M-’ completion. + + Remember that the keywords after the vertical bar (or the last +keyword if no bar is there) must always mean that the item is DONE +(although you may use a different word). After changing one of these +lines, use ‘C-c C-c’ with the cursor still in the line to make the +changes known to Org mode(1). + + ---------- Footnotes ---------- + + (1) Org mode parses these lines only when Org mode is activated after +visiting a file. ‘C-c C-c’ with the cursor in a line starting with ‘#+’ +is simply restarting Org mode for the current buffer. + + +File: org, Node: Faces for TODO keywords, Next: TODO dependencies, Prev: Per-file keywords, Up: TODO extensions + +5.2.6 Faces for TODO keywords +----------------------------- + +Org mode highlights TODO keywords with special faces: ‘org-todo’ for +keywords indicating that an item still has to be acted upon, and +‘org-done’ for keywords indicating that an item is finished. If you are +using more than 2 different states, you might want to use special faces +for some of them. This can be done using the option +‘org-todo-keyword-faces’. For example: + + (setq org-todo-keyword-faces + '(("TODO" . org-warning) ("STARTED" . "yellow") + ("CANCELED" . (:foreground "blue" :weight bold)))) + + While using a list with face properties as shown for CANCELED +_should_ work, this does not always seem to be the case. If necessary, +define a special face and use that. A string is interpreted as a color. +The option ‘org-faces-easy-properties’ determines if that color is +interpreted as a foreground or a background color. + + +File: org, Node: TODO dependencies, Prev: Faces for TODO keywords, Up: TODO extensions + +5.2.7 TODO dependencies +----------------------- + +The structure of Org files (hierarchy and lists) makes it easy to define +TODO dependencies. Usually, a parent TODO task should not be marked +DONE until all subtasks (defined as children tasks) are marked as DONE. +And sometimes there is a logical sequence to a number of (sub)tasks, so +that one task cannot be acted upon before all siblings above it are +done. If you customize the option ‘org-enforce-todo-dependencies’, Org +will block entries from changing state to DONE while they have children +that are not DONE. Furthermore, if an entry has a property ‘ORDERED’, +each of its children will be blocked until all earlier siblings are +marked DONE. Here is an example: + + * TODO Blocked until (two) is done + ** DONE one + ** TODO two + + * Parent + :PROPERTIES: + :ORDERED: t + :END: + ** TODO a + ** TODO b, needs to wait for (a) + ** TODO c, needs to wait for (a) and (b) + + You can ensure an entry is never blocked by using the ‘NOBLOCKING’ +property: + + * This entry is never blocked + :PROPERTIES: + :NOBLOCKING: t + :END: + +‘C-c C-x o (org-toggle-ordered-property)’ + Toggle the ‘ORDERED’ property of the current entry. A property is + used for this behavior because this should be local to the current + entry, not inherited like a tag. However, if you would like to + track the value of this property with a tag for better visibility, + customize the option ‘org-track-ordered-property-with-tag’. +‘C-u C-u C-u C-c C-t’ + Change TODO state, circumventing any state blocking. + + If you set the option ‘org-agenda-dim-blocked-tasks’, TODO entries +that cannot be closed because of such dependencies will be shown in a +dimmed font or even made invisible in agenda views (*note Agenda +views::). + + You can also block changes of TODO states by looking at checkboxes +(*note Checkboxes::). If you set the option +‘org-enforce-todo-checkbox-dependencies’, an entry that has unchecked +checkboxes will be blocked from switching to DONE. + + If you need more complex dependency structures, for example +dependencies between entries in different trees or files, check out the +contributed module ‘org-depend.el’. + + +File: org, Node: Progress logging, Next: Priorities, Prev: TODO extensions, Up: TODO items + +5.3 Progress logging +==================== + +Org mode can automatically record a timestamp and possibly a note when +you mark a TODO item as DONE, or even each time you change the state of +a TODO item. This system is highly configurable; settings can be on a +per-keyword basis and can be localized to a file or even a subtree. For +information on how to clock working time for a task, see *note Clocking +work time::. + +* Menu: + +* Closing items:: When was this entry marked DONE? +* Tracking TODO state changes:: When did the status change? +* Tracking your habits:: How consistent have you been? + + +File: org, Node: Closing items, Next: Tracking TODO state changes, Up: Progress logging + +5.3.1 Closing items +------------------- + +The most basic logging is to keep track of _when_ a certain TODO item +was finished. This is achieved with(1) + + (setq org-log-done 'time) + +Then each time you turn an entry from a TODO (not-done) state into any +of the DONE states, a line ‘CLOSED: [timestamp]’ will be inserted just +after the headline. If you turn the entry back into a TODO item through +further state cycling, that line will be removed again. If you turn the +entry back to a non-TODO state (by pressing ‘C-c C-t ’ for +example), that line will also be removed, unless you set +‘org-closed-keep-when-no-todo’ to non-‘nil’. If you want to record a +note along with the timestamp, use(2) + + (setq org-log-done 'note) + +You will then be prompted for a note, and that note will be stored below +the entry with a ‘Closing Note’ heading. + + ---------- Footnotes ---------- + + (1) The corresponding in-buffer setting is: ‘#+STARTUP: logdone’ + + (2) The corresponding in-buffer setting is: ‘#+STARTUP: lognotedone’. + + +File: org, Node: Tracking TODO state changes, Next: Tracking your habits, Prev: Closing items, Up: Progress logging + +5.3.2 Tracking TODO state changes +--------------------------------- + +When TODO keywords are used as workflow states (*note Workflow +states::), you might want to keep track of when a state change occurred +and maybe take a note about this change. You can either record just a +timestamp, or a time-stamped note for a change. These records will be +inserted after the headline as an itemized list, newest first(1). When +taking a lot of notes, you might want to get the notes out of the way +into a drawer (*note Drawers::). Customize ‘org-log-into-drawer’ to get +this behavior—the recommended drawer for this is called ‘LOGBOOK’(2). +You can also overrule the setting of this variable for a subtree by +setting a ‘LOG_INTO_DRAWER’ property. + + Since it is normally too much to record a note for every state, Org +mode expects configuration on a per-keyword basis for this. This is +achieved by adding special markers ‘!’ (for a timestamp) or ‘@’ (for a +note with timestamp) in parentheses after each keyword. For example, +with the setting + + (setq org-todo-keywords + '((sequence "TODO(t)" "WAIT(w@/!)" "|" "DONE(d!)" "CANCELED(c@)"))) + + To record a timestamp without a note for TODO keywords configured +with ‘@’, just type ‘C-c C-c’ to enter a blank note when prompted. + +You not only define global TODO keywords and fast access keys, but also +request that a time is recorded when the entry is set to DONE(3), and +that a note is recorded when switching to WAIT or CANCELED. The setting +for WAIT is even more special: the ‘!’ after the slash means that in +addition to the note taken when entering the state, a timestamp should +be recorded when leaving the WAIT state, if and only if the target state +does not configure logging for entering it. So it has no effect when +switching from WAIT to DONE, because DONE is configured to record a +timestamp only. But when switching from WAIT back to TODO, the ‘/!’ in +the WAIT setting now triggers a timestamp even though TODO has no +logging configured. + + You can use the exact same syntax for setting logging preferences +local to a buffer: + #+TODO: TODO(t) WAIT(w@/!) | DONE(d!) CANCELED(c@) + + In order to define logging settings that are local to a subtree or a +single item, define a ‘LOGGING’ property in this entry. Any non-empty +‘LOGGING’ property resets all logging settings to ‘nil’. You may then +turn on logging for this specific tree using ‘#+STARTUP’ keywords like +‘lognotedone’ or ‘logrepeat’, as well as adding state specific settings +like ‘TODO(!)’. For example + + * TODO Log each state with only a time + :PROPERTIES: + :LOGGING: TODO(!) WAIT(!) DONE(!) CANCELED(!) + :END: + * TODO Only log when switching to WAIT, and when repeating + :PROPERTIES: + :LOGGING: WAIT(@) logrepeat + :END: + * TODO No logging at all + :PROPERTIES: + :LOGGING: nil + :END: + + ---------- Footnotes ---------- + + (1) See the option ‘org-log-states-order-reversed’ + + (2) Note that the ‘LOGBOOK’ drawer is unfolded when pressing ‘’ +in the agenda to show an entry—use ‘C-u ’ to keep it folded here + + (3) It is possible that Org mode will record two timestamps when you +are using both ‘org-log-done’ and state change logging. However, it +will never prompt for two notes—if you have configured both, the state +change recording note will take precedence and cancel the ‘Closing +Note’. + + +File: org, Node: Tracking your habits, Prev: Tracking TODO state changes, Up: Progress logging + +5.3.3 Tracking your habits +-------------------------- + +Org has the ability to track the consistency of a special category of +TODOs, called “habits”. A habit has the following properties: + + 1. You have enabled the ‘habits’ module by customizing ‘org-modules’. + 2. The habit is a TODO item, with a TODO keyword representing an open + state. + 3. The property ‘STYLE’ is set to the value ‘habit’. + 4. The TODO has a scheduled date, usually with a ‘.+’ style repeat + interval. A ‘++’ style may be appropriate for habits with time + constraints, e.g., must be done on weekends, or a ‘+’ style for an + unusual habit that can have a backlog, e.g., weekly reports. + 5. The TODO may also have minimum and maximum ranges specified by + using the syntax ‘.+2d/3d’, which says that you want to do the task + at least every three days, but at most every two days. + 6. You must also have state logging for the ‘DONE’ state enabled + (*note Tracking TODO state changes::), in order for historical data + to be represented in the consistency graph. If it is not enabled + it is not an error, but the consistency graphs will be largely + meaningless. + + To give you an idea of what the above rules look like in action, +here’s an actual habit with some history: + + ** TODO Shave + SCHEDULED: <2009-10-17 Sat .+2d/4d> + :PROPERTIES: + :STYLE: habit + :LAST_REPEAT: [2009-10-19 Mon 00:36] + :END: + - State "DONE" from "TODO" [2009-10-15 Thu] + - State "DONE" from "TODO" [2009-10-12 Mon] + - State "DONE" from "TODO" [2009-10-10 Sat] + - State "DONE" from "TODO" [2009-10-04 Sun] + - State "DONE" from "TODO" [2009-10-02 Fri] + - State "DONE" from "TODO" [2009-09-29 Tue] + - State "DONE" from "TODO" [2009-09-25 Fri] + - State "DONE" from "TODO" [2009-09-19 Sat] + - State "DONE" from "TODO" [2009-09-16 Wed] + - State "DONE" from "TODO" [2009-09-12 Sat] + + What this habit says is: I want to shave at most every 2 days (given +by the ‘SCHEDULED’ date and repeat interval) and at least every 4 days. +If today is the 15th, then the habit first appears in the agenda on Oct +17, after the minimum of 2 days has elapsed, and will appear overdue on +Oct 19, after four days have elapsed. + + What’s really useful about habits is that they are displayed along +with a consistency graph, to show how consistent you’ve been at getting +that task done in the past. This graph shows every day that the task +was done over the past three weeks, with colors for each day. The +colors used are: + +‘Blue’ + If the task wasn’t to be done yet on that day. +‘Green’ + If the task could have been done on that day. +‘Yellow’ + If the task was going to be overdue the next day. +‘Red’ + If the task was overdue on that day. + + In addition to coloring each day, the day is also marked with an +asterisk if the task was actually done that day, and an exclamation mark +to show where the current day falls in the graph. + + There are several configuration variables that can be used to change +the way habits are displayed in the agenda. + +‘org-habit-graph-column’ + The buffer column at which the consistency graph should be drawn. + This will overwrite any text in that column, so it is a good idea + to keep your habits’ titles brief and to the point. +‘org-habit-preceding-days’ + The amount of history, in days before today, to appear in + consistency graphs. +‘org-habit-following-days’ + The number of days after today that will appear in consistency + graphs. +‘org-habit-show-habits-only-for-today’ + If non-‘nil’, only show habits in today’s agenda view. This is set + to true by default. + + Lastly, pressing ‘K’ in the agenda buffer will cause habits to +temporarily be disabled and they won’t appear at all. Press ‘K’ again +to bring them back. They are also subject to tag filtering, if you have +habits which should only be done in certain contexts, for example. + + +File: org, Node: Priorities, Next: Breaking down tasks, Prev: Progress logging, Up: TODO items + +5.4 Priorities +============== + +If you use Org mode extensively, you may end up with enough TODO items +that it starts to make sense to prioritize them. Prioritizing can be +done by placing a _priority cookie_ into the headline of a TODO item, +like this + + *** TODO [#A] Write letter to Sam Fortune + +By default, Org mode supports three priorities: ‘A’, ‘B’, and ‘C’. ‘A’ +is the highest priority. An entry without a cookie is treated just like +priority ‘B’. Priorities make a difference only for sorting in the +agenda (*note Weekly/daily agenda::); outside the agenda, they have no +inherent meaning to Org mode. The cookies can be highlighted with +special faces by customizing ‘org-priority-faces’. + + Priorities can be attached to any outline node; they do not need to +be TODO items. + +‘C-c ,’ + Set the priority of the current headline (‘org-priority’). The + command prompts for a priority character ‘A’, ‘B’ or ‘C’. When you + press instead, the priority cookie is removed from the + headline. The priorities can also be changed “remotely” from the + agenda buffer with the ‘,’ command (*note Agenda commands::). +‘S- (org-priority-up)’ +‘S- (org-priority-down)’ + Increase/decrease priority of current headline(1). Note that these + keys are also used to modify timestamps (*note Creating + timestamps::). See also *note Conflicts::, for a discussion of the + interaction with ‘shift-selection-mode’. + + You can change the range of allowed priorities by setting the options +‘org-highest-priority’, ‘org-lowest-priority’, and +‘org-default-priority’. For an individual buffer, you may set these +values (highest, lowest, default) like this (please make sure that the +highest priority is earlier in the alphabet than the lowest priority): + + #+PRIORITIES: A C B + + ---------- Footnotes ---------- + + (1) See also the option ‘org-priority-start-cycle-with-default’. + + +File: org, Node: Breaking down tasks, Next: Checkboxes, Prev: Priorities, Up: TODO items + +5.5 Breaking tasks down into subtasks +===================================== + +It is often advisable to break down large tasks into smaller, manageable +subtasks. You can do this by creating an outline tree below a TODO +item, with detailed subtasks on the tree(1). To keep the overview over +the fraction of subtasks that are already completed, insert either ‘[/]’ +or ‘[%]’ anywhere in the headline. These cookies will be updated each +time the TODO status of a child changes, or when pressing ‘C-c C-c’ on +the cookie. For example: + + * Organize Party [33%] + ** TODO Call people [1/2] + *** TODO Peter + *** DONE Sarah + ** TODO Buy food + ** DONE Talk to neighbor + + If a heading has both checkboxes and TODO children below it, the +meaning of the statistics cookie become ambiguous. Set the property +‘COOKIE_DATA’ to either ‘checkbox’ or ‘todo’ to resolve this issue. + + If you would like to have the statistics cookie count any TODO +entries in the subtree (not just direct children), configure +‘org-hierarchical-todo-statistics’. To do this for a single subtree, +include the word ‘recursive’ into the value of the ‘COOKIE_DATA’ +property. + + * Parent capturing statistics [2/20] + :PROPERTIES: + :COOKIE_DATA: todo recursive + :END: + + If you would like a TODO entry to automatically change to DONE when +all children are done, you can use the following setup: + + (defun org-summary-todo (n-done n-not-done) + "Switch entry to DONE when all subentries are done, to TODO otherwise." + (let (org-log-done org-log-states) ; turn off logging + (org-todo (if (= n-not-done 0) "DONE" "TODO")))) + + (add-hook 'org-after-todo-statistics-hook 'org-summary-todo) + + Another possibility is the use of checkboxes to identify (a hierarchy +of) a large number of subtasks (*note Checkboxes::). + + ---------- Footnotes ---------- + + (1) To keep subtasks out of the global TODO list, see the +‘org-agenda-todo-list-sublevels’. + + +File: org, Node: Checkboxes, Prev: Breaking down tasks, Up: TODO items + +5.6 Checkboxes +============== + +Every item in a plain list(1) (*note Plain lists::) can be made into a +checkbox by starting it with the string ‘[ ]’. This feature is similar +to TODO items (*note TODO items::), but is more lightweight. Checkboxes +are not included in the global TODO list, so they are often great to +split a task into a number of simple steps. Or you can use them in a +shopping list. To toggle a checkbox, use ‘C-c C-c’, or use the mouse +(thanks to Piotr Zielinski’s ‘org-mouse.el’). + + Here is an example of a checkbox list. + + * TODO Organize party [2/4] + - [-] call people [1/3] + - [ ] Peter + - [X] Sarah + - [ ] Sam + - [X] order food + - [ ] think about what music to play + - [X] talk to the neighbors + + Checkboxes work hierarchically, so if a checkbox item has children +that are checkboxes, toggling one of the children checkboxes will make +the parent checkbox reflect if none, some, or all of the children are +checked. + + The ‘[2/4]’ and ‘[1/3]’ in the first and second line are cookies +indicating how many checkboxes present in this entry have been checked +off, and the total number of checkboxes present. This can give you an +idea on how many checkboxes remain, even without opening a folded entry. +The cookies can be placed into a headline or into (the first line of) a +plain list item. Each cookie covers checkboxes of direct children +structurally below the headline/item on which the cookie appears(2). +You have to insert the cookie yourself by typing either ‘[/]’ or ‘[%]’. +With ‘[/]’ you get an ‘n out of m’ result, as in the examples above. +With ‘[%]’ you get information about the percentage of checkboxes +checked (in the above example, this would be ‘[50%]’ and ‘[33%]’, +respectively). In a headline, a cookie can count either checkboxes +below the heading or TODO states of children, and it will display +whatever was changed last. Set the property ‘COOKIE_DATA’ to either +‘checkbox’ or ‘todo’ to resolve this issue. + + If the current outline node has an ‘ORDERED’ property, checkboxes +must be checked off in sequence, and an error will be thrown if you try +to check off a box while there are unchecked boxes above it. + +The following commands work with checkboxes: + +‘C-c C-c (org-toggle-checkbox)’ + Toggle checkbox status or (with prefix arg) checkbox presence at + point. With a single prefix argument, add an empty checkbox or + remove the current one(3). With a double prefix argument, set it + to ‘[-]’, which is considered to be an intermediate state. +‘C-c C-x C-b (org-toggle-checkbox)’ + Toggle checkbox status or (with prefix arg) checkbox presence at + point. With double prefix argument, set it to ‘[-]’, which is + considered to be an intermediate state. + − If there is an active region, toggle the first checkbox in the + region and set all remaining boxes to the same status as the + first. With a prefix arg, add or remove the checkbox for all + items in the region. + − If the cursor is in a headline, toggle the state of the first + checkbox in the region between this headline and the next—so + _not_ the entire subtree—and propagate this new state to all + other checkboxes in the same area. + − If there is no active region, just toggle the checkbox at + point. +‘M-S- (org-insert-todo-heading)’ + Insert a new item with a checkbox. This works only if the cursor + is already in a plain list item (*note Plain lists::). +‘C-c C-x o (org-toggle-ordered-property)’ + Toggle the ‘ORDERED’ property of the entry, to toggle if checkboxes + must be checked off in sequence. A property is used for this + behavior because this should be local to the current entry, not + inherited like a tag. However, if you would like to track the + value of this property with a tag for better visibility, customize + ‘org-track-ordered-property-with-tag’. +‘C-c # (org-update-statistics-cookies)’ + Update the statistics cookie in the current outline entry. When + called with a ‘C-u’ prefix, update the entire file. Checkbox + statistic cookies are updated automatically if you toggle + checkboxes with ‘C-c C-c’ and make new ones with ‘M-S-’. TODO + statistics cookies update when changing TODO states. If you delete + boxes/entries or add/change them by hand, use this command to get + things back into sync. + + ---------- Footnotes ---------- + + (1) With the exception of description lists. But you can allow it by +modifying ‘org-list-automatic-rules’ accordingly. + + (2) Set the option ‘org-checkbox-hierarchical-statistics’ if you want +such cookies to count all checkboxes below the cookie, not just those +belonging to direct children. + + (3) ‘C-u C-c C-c’ before the _first_ bullet in a list with no +checkbox will add checkboxes to the rest of the list. + + +File: org, Node: Tags, Next: Properties and columns, Prev: TODO items, Up: Top + +6 Tags +****** + +An excellent way to implement labels and contexts for cross-correlating +information is to assign tags to headlines. Org mode has extensive +support for tags. + + Every headline can contain a list of tags; they occur at the end of +the headline. Tags are normal words containing letters, numbers, ‘_’, +and ‘@’. Tags must be preceded and followed by a single colon, e.g., +‘:work:’. Several tags can be specified, as in ‘:work:urgent:’. Tags +will by default be in bold face with the same color as the headline. +You may specify special faces for specific tags using the option +‘org-tag-faces’, in much the same way as you can for TODO keywords +(*note Faces for TODO keywords::). + +* Menu: + +* Tag inheritance:: Tags use the tree structure of the outline +* Setting tags:: How to assign tags to a headline +* Tag hierarchy:: Create a hierarchy of tags +* Tag searches:: Searching for combinations of tags + + +File: org, Node: Tag inheritance, Next: Setting tags, Up: Tags + +6.1 Tag inheritance +=================== + +Tags make use of the hierarchical structure of outline trees. If a +heading has a certain tag, all subheadings will inherit the tag as well. +For example, in the list + + * Meeting with the French group :work: + ** Summary by Frank :boss:notes: + *** TODO Prepare slides for him :action: + +the final heading will have the tags ‘:work:’, ‘:boss:’, ‘:notes:’, and +‘:action:’ even though the final heading is not explicitly marked with +all those tags. You can also set tags that all entries in a file should +inherit just as if these tags were defined in a hypothetical level zero +that surrounds the entire file. Use a line like this(1): + + #+FILETAGS: :Peter:Boss:Secret: + +To limit tag inheritance to specific tags, use +‘org-tags-exclude-from-inheritance’. To turn it off entirely, use +‘org-use-tag-inheritance’. + + When a headline matches during a tags search while tag inheritance is +turned on, all the sublevels in the same tree will (for a simple match +form) match as well(2). The list of matches may then become very long. +If you only want to see the first tags match in a subtree, configure +‘org-tags-match-list-sublevels’ (not recommended). + + Tag inheritance is relevant when the agenda search tries to match a +tag, either in the ‘tags’ or ‘tags-todo’ agenda types. In other agenda +types, ‘org-use-tag-inheritance’ has no effect. Still, you may want to +have your tags correctly set in the agenda, so that tag filtering works +fine, with inherited tags. Set ‘org-agenda-use-tag-inheritance’ to +control this: the default value includes all agenda types, but setting +this to ‘nil’ can really speed up agenda generation. + + ---------- Footnotes ---------- + + (1) As with all these in-buffer settings, pressing ‘C-c C-c’ +activates any changes in the line. + + (2) This is only true if the search does not involve more complex +tests including properties (*note Property searches::). + + +File: org, Node: Setting tags, Next: Tag hierarchy, Prev: Tag inheritance, Up: Tags + +6.2 Setting tags +================ + +Tags can simply be typed into the buffer at the end of a headline. +After a colon, ‘M-’ offers completion on tags. There is also a +special command for inserting tags: + +‘C-c C-q (org-set-tags-command)’ + Enter new tags for the current headline. Org mode will either + offer completion or a special single-key interface for setting + tags, see below. After pressing , the tags will be inserted + and aligned to ‘org-tags-column’. When called with a ‘C-u’ prefix, + all tags in the current buffer will be aligned to that column, just + to make things look nice. TAGS are automatically realigned after + promotion, demotion, and TODO state changes (*note TODO basics::). + +‘C-c C-c (org-set-tags-command)’ + When the cursor is in a headline, this does the same as ‘C-c C-q’. + + Org supports tag insertion based on a _list of tags_. By default +this list is constructed dynamically, containing all tags currently used +in the buffer. You may also globally specify a hard list of tags with +the variable ‘org-tag-alist’. Finally you can set the default tags for +a given file with lines like + + #+TAGS: @work @home @tennisclub + #+TAGS: laptop car pc sailboat + + If you have globally defined your preferred set of tags using the +variable ‘org-tag-alist’, but would like to use a dynamic tag list in a +specific file, add an empty TAGS option line to that file: + + #+TAGS: + + If you have a preferred set of tags that you would like to use in +every file, in addition to those defined on a per-file basis by TAGS +option lines, then you may specify a list of tags with the variable +‘org-tag-persistent-alist’. You may turn this off on a per-file basis +by adding a ‘#+STARTUP’ option line to that file: + + #+STARTUP: noptag + + By default Org mode uses the standard minibuffer completion +facilities for entering tags. However, it also implements another, +quicker, tag selection method called _fast tag selection_. This allows +you to select and deselect tags with just a single key press. For this +to work well you should assign unique, case-sensitive, letters to most +of your commonly used tags. You can do this globally by configuring the +variable ‘org-tag-alist’ in your Emacs init file. For example, you may +find the need to tag many items in different files with ‘:@home:’. In +this case you can set something like: + + (setq org-tag-alist '(("@work" . ?w) ("@home" . ?h) ("laptop" . ?l))) + +If the tag is only relevant to the file you are working on, then you can +instead set the TAGS option line as: + + #+TAGS: @work(w) @home(h) @tennisclub(t) laptop(l) pc(p) + +The tags interface will show the available tags in a splash window. If +you want to start a new line after a specific tag, insert ‘\n’ into the +tag list + + #+TAGS: @work(w) @home(h) @tennisclub(t) \n laptop(l) pc(p) + +or write them in two lines: + + #+TAGS: @work(w) @home(h) @tennisclub(t) + #+TAGS: laptop(l) pc(p) + +You can also group together tags that are mutually exclusive by using +braces, as in: + + #+TAGS: { @work(w) @home(h) @tennisclub(t) } laptop(l) pc(p) + +you indicate that at most one of ‘@work’, ‘@home’, and ‘@tennisclub’ +should be selected. Multiple such groups are allowed. + +Don’t forget to press ‘C-c C-c’ with the cursor in one of these lines to +activate any changes. + +To set these mutually exclusive groups in the variable ‘org-tag-alist’, +you must use the dummy tags ‘:startgroup’ and ‘:endgroup’ instead of the +braces. Similarly, you can use ‘:newline’ to indicate a line break. +The previous example would be set globally by the following +configuration: + + (setq org-tag-alist '((:startgroup . nil) + ("@work" . ?w) ("@home" . ?h) + ("@tennisclub" . ?t) + (:endgroup . nil) + ("laptop" . ?l) ("pc" . ?p))) + + If at least one tag has a selection key then pressing ‘C-c C-c’ will +automatically present you with a special interface, listing inherited +tags, the tags of the current headline, and a list of all valid tags +with corresponding keys(1). + + Pressing keys assigned to tags will add or remove them from the list +of tags in the current line. Selecting a tag in a group of mutually +exclusive tags will turn off any other tags from that group. + + In this interface, you can also use the following special keys: + +‘’ + Enter a tag in the minibuffer, even if the tag is not in the + predefined list. You will be able to complete on all tags present + in the buffer. You can also add several tags: just separate them + with a comma. + +‘’ + Clear all tags for this line. + +‘’ + Accept the modified set. + +‘C-g’ + Abort without installing changes. + +‘q’ + If ‘q’ is not assigned to a tag, it aborts like ‘C-g’. + +‘!’ + Turn off groups of mutually exclusive tags. Use this to (as an + exception) assign several tags from such a group. + +‘C-c’ + Toggle auto-exit after the next change (see below). If you are + using expert mode, the first ‘C-c’ will display the selection + window. + +This method lets you assign tags to a headline with very few keys. With +the above setup, you could clear the current tags and set ‘@home’, +‘laptop’ and ‘pc’ tags with just the following keys: ‘C-c C-c h l +p ’. Switching from ‘@home’ to ‘@work’ would be done with ‘C-c C-c +w ’ or alternatively with ‘C-c C-c C-c w’. Adding the +non-predefined tag ‘Sarah’ could be done with ‘C-c C-c S a r a h + ’. + + If you find that most of the time you need only a single key press to +modify your list of tags, set ‘org-fast-tag-selection-single-key’. Then +you no longer have to press to exit fast tag selection—it will +immediately exit after the first change. If you then occasionally need +more keys, press ‘C-c’ to turn off auto-exit for the current tag +selection process (in effect: start selection with ‘C-c C-c C-c’ instead +of ‘C-c C-c’). If you set the variable to the value ‘expert’, the +special window is not even shown for single-key tag selection, it comes +up only when you press an extra ‘C-c’. + + ---------- Footnotes ---------- + + (1) Keys will automatically be assigned to tags which have no +configured keys. + + +File: org, Node: Tag hierarchy, Next: Tag searches, Prev: Setting tags, Up: Tags + +6.3 Tag hierarchy +================= + +Tags can be defined in hierarchies. A tag can be defined as a _group +tag_ for a set of other tags. The group tag can be seen as the “broader +term” for its set of tags. Defining multiple _group tags_ and nesting +them creates a tag hierarchy. + + One use-case is to create a taxonomy of terms (tags) that can be used +to classify nodes in a document or set of documents. + + When you search for a group tag, it will return matches for all +members in the group and its subgroups. In an agenda view, filtering by +a group tag will display or hide headlines tagged with at least one of +the members of the group or any of its subgroups. This makes tag +searches and filters even more flexible. + + You can set group tags by using brackets and inserting a colon +between the group tag and its related tags—beware that all whitespaces +are mandatory so that Org can parse this line correctly: + + #+TAGS: [ GTD : Control Persp ] + + In this example, ‘GTD’ is the _group tag_ and it is related to two +other tags: ‘Control’, ‘Persp’. Defining ‘Control’ and ‘Persp’ as group +tags creates a hierarchy of tags: + + #+TAGS: [ Control : Context Task ] + #+TAGS: [ Persp : Vision Goal AOF Project ] + + That can conceptually be seen as a hierarchy of tags: + + - GTD + - Persp + - Vision + - Goal + - AOF + - Project + - Control + - Context + - Task + + You can use the ‘:startgrouptag’, ‘:grouptags’ and ‘:endgrouptag’ +keyword directly when setting ‘org-tag-alist’ directly: + + (setq org-tag-alist '((:startgrouptag) + ("GTD") + (:grouptags) + ("Control") + ("Persp") + (:endgrouptag) + (:startgrouptag) + ("Control") + (:grouptags) + ("Context") + ("Task") + (:endgrouptag))) + + The tags in a group can be mutually exclusive if using the same group +syntax as is used for grouping mutually exclusive tags together; using +curly brackets. + + #+TAGS: { Context : @Home @Work @Call } + + When setting ‘org-tag-alist’ you can use ‘:startgroup’ & ‘:endgroup’ +instead of ‘:startgrouptag’ & ‘:endgrouptag’ to make the tags mutually +exclusive. + + Furthermore, the members of a _group tag_ can also be regular +expressions, creating the possibility of a more dynamic and rule-based +tag structure. The regular expressions in the group must be specified +within { }. Here is an expanded example: + + #+TAGS: [ Vision : {V@.+} ] + #+TAGS: [ Goal : {G@.+} ] + #+TAGS: [ AOF : {AOF@.+} ] + #+TAGS: [ Project : {P@.+} ] + + Searching for the tag ‘Project’ will now list all tags also including +regular expression matches for ‘P@.+’, and similarly for tag searches on +‘Vision’, ‘Goal’ and ‘AOF’. For example, this would work well for a +project tagged with a common project-identifier, e.g. ‘P@2014_OrgTags’. + + If you want to ignore group tags temporarily, toggle group tags +support with ‘org-toggle-tags-groups’, bound to ‘C-c C-x q’. If you +want to disable tag groups completely, set ‘org-group-tags’ to ‘nil’. + + +File: org, Node: Tag searches, Prev: Tag hierarchy, Up: Tags + +6.4 Tag searches +================ + +Once a system of tags has been set up, it can be used to collect related +information into special lists. + +‘C-c / m or C-c \ (org-match-sparse-tree)’ + Create a sparse tree with all headlines matching a + tags/property/TODO search. With a ‘C-u’ prefix argument, ignore + headlines that are not a TODO line. *Note Matching tags and + properties::. +‘C-c a m (org-tags-view)’ + Create a global list of tag matches from all agenda files. *Note + Matching tags and properties::. +‘C-c a M (org-tags-view)’ + Create a global list of tag matches from all agenda files, but + check only TODO items and force checking subitems (see the option + ‘org-tags-match-list-sublevels’). + + These commands all prompt for a match string which allows basic +Boolean logic like ‘+boss+urgent-project1’, to find entries with tags +‘boss’ and ‘urgent’, but not ‘project1’, or ‘Kathy|Sally’ to find +entries tagged as ‘Kathy’ or ‘Sally’. The full syntax of the search +string is rich and allows also matching against TODO keywords, entry +levels and properties. For a complete description with many examples, +see *note Matching tags and properties::. + + +File: org, Node: Properties and columns, Next: Dates and times, Prev: Tags, Up: Top + +7 Properties and columns +************************ + +A property is a key-value pair associated with an entry. Properties can +be set so they are associated with a single entry, with every entry in a +tree, or with every entry in an Org mode file. + + There are two main applications for properties in Org mode. First, +properties are like tags, but with a value. Imagine maintaining a file +where you document bugs and plan releases for a piece of software. +Instead of using tags like ‘:release_1:’, ‘:release_2:’, you can use a +property, say ‘:Release:’, that in different subtrees has different +values, such as ‘1.0’ or ‘2.0’. Second, you can use properties to +implement (very basic) database capabilities in an Org buffer. Imagine +keeping track of your music CDs, where properties could be things such +as the album, artist, date of release, number of tracks, and so on. + + Properties can be conveniently edited and viewed in column view +(*note Column view::). + +* Menu: + +* Property syntax:: How properties are spelled out +* Special properties:: Access to other Org mode features +* Property searches:: Matching property values +* Property inheritance:: Passing values down the tree +* Column view:: Tabular viewing and editing +* Property API:: Properties for Lisp programmers + + +File: org, Node: Property syntax, Next: Special properties, Up: Properties and columns + +7.1 Property syntax +=================== + +Properties are key-value pairs. When they are associated with a single +entry or with a tree they need to be inserted into a special drawer +(*note Drawers::) with the name ‘PROPERTIES’, which has to be located +right below a headline, and its planning line (*note Deadlines and +scheduling::) when applicable. Each property is specified on a single +line, with the key (surrounded by colons) first, and the value after it. +Keys are case-insensitive. Here is an example: + + * CD collection + ** Classic + *** Goldberg Variations + :PROPERTIES: + :Title: Goldberg Variations + :Composer: J.S. Bach + :Artist: Glen Gould + :Publisher: Deutsche Grammophon + :NDisks: 1 + :END: + + Depending on the value of ‘org-use-property-inheritance’, a property +set this way will either be associated with a single entry, or the +subtree defined by the entry, see *note Property inheritance::. + + You may define the allowed values for a particular property ‘:Xyz:’ +by setting a property ‘:Xyz_ALL:’. This special property is +_inherited_, so if you set it in a level 1 entry, it will apply to the +entire tree. When allowed values are defined, setting the corresponding +property becomes easier and is less prone to typing errors. For the +example with the CD collection, we can predefine publishers and the +number of disks in a box like this: + + * CD collection + :PROPERTIES: + :NDisks_ALL: 1 2 3 4 + :Publisher_ALL: "Deutsche Grammophon" Philips EMI + :END: + + If you want to set properties that can be inherited by any entry in a +file, use a line like + #+PROPERTY: NDisks_ALL 1 2 3 4 + + Contrary to properties set from a special drawer, you have to refresh +the buffer with ‘C-c C-c’ to activate this change. + + If you want to add to the value of an existing property, append a ‘+’ +to the property name. The following results in the property ‘var’ +having the value “foo=1 bar=2”. + #+PROPERTY: var foo=1 + #+PROPERTY: var+ bar=2 + + It is also possible to add to the values of inherited properties. +The following results in the ‘genres’ property having the value “Classic +Baroque” under the ‘Goldberg Variations’ subtree. + * CD collection + ** Classic + :PROPERTIES: + :GENRES: Classic + :END: + *** Goldberg Variations + :PROPERTIES: + :Title: Goldberg Variations + :Composer: J.S. Bach + :Artist: Glen Gould + :Publisher: Deutsche Grammophon + :NDisks: 1 + :GENRES+: Baroque + :END: + Note that a property can only have one entry per Drawer. + + Property values set with the global variable ‘org-global-properties’ +can be inherited by all entries in all Org files. + +The following commands help to work with properties: + +‘M- (pcomplete)’ + After an initial colon in a line, complete property keys. All keys + used in the current file will be offered as possible completions. +‘C-c C-x p (org-set-property)’ + Set a property. This prompts for a property name and a value. If + necessary, the property drawer is created as well. +‘C-u M-x org-insert-drawer ’ + Insert a property drawer into the current entry. The drawer will + be inserted early in the entry, but after the lines with planning + information like deadlines. +‘C-c C-c (org-property-action)’ + With the cursor in a property drawer, this executes property + commands. +‘C-c C-c s (org-set-property)’ + Set a property in the current entry. Both the property and the + value can be inserted using completion. +‘S- (org-property-next-allowed-value)’ +‘S- (org-property-previous-allowed-value)’ + Switch property at point to the next/previous allowed value. +‘C-c C-c d (org-delete-property)’ + Remove a property from the current entry. +‘C-c C-c D (org-delete-property-globally)’ + Globally remove a property, from all entries in the current file. +‘C-c C-c c (org-compute-property-at-point)’ + Compute the property at point, using the operator and scope from + the nearest column format definition. + + +File: org, Node: Special properties, Next: Property searches, Prev: Property syntax, Up: Properties and columns + +7.2 Special properties +====================== + +Special properties provide an alternative access method to Org mode +features, like the TODO state or the priority of an entry, discussed in +the previous chapters. This interface exists so that you can include +these states in a column view (*note Column view::), or to use them in +queries. The following property names are special and should not be +used as keys in the properties drawer: + + ALLTAGS All tags, including inherited ones. + BLOCKED "t" if task is currently blocked by children or siblings. + CLOCKSUM The sum of CLOCK intervals in the subtree. ‘org-clock-sum’ + must be run first to compute the values in the current buffer. + CLOCKSUM_T The sum of CLOCK intervals in the subtree for today. + ‘org-clock-sum-today’ must be run first to compute the + values in the current buffer. + CLOSED When was this entry closed? + DEADLINE The deadline time string, without the angular brackets. + FILE The filename the entry is located in. + ITEM The headline of the entry. + PRIORITY The priority of the entry, a string with a single letter. + SCHEDULED The scheduling timestamp, without the angular brackets. + TAGS The tags defined directly in the headline. + TIMESTAMP The first keyword-less timestamp in the entry. + TIMESTAMP_IA The first inactive timestamp in the entry. + TODO The TODO keyword of the entry. + + +File: org, Node: Property searches, Next: Property inheritance, Prev: Special properties, Up: Properties and columns + +7.3 Property searches +===================== + +To create sparse trees and special lists with selection based on +properties, the same commands are used as for tag searches (*note Tag +searches::). + +‘C-c / m or C-c \ (org-match-sparse-tree)’ + Create a sparse tree with all matching entries. With a ‘C-u’ + prefix argument, ignore headlines that are not a TODO line. +‘C-c a m (org-tags-view)’ + Create a global list of tag/property matches from all agenda files. + *Note Matching tags and properties::. +‘C-c a M (org-tags-view)’ + Create a global list of tag matches from all agenda files, but + check only TODO items and force checking of subitems (see the + option ‘org-tags-match-list-sublevels’). + + The syntax for the search string is described in *note Matching tags +and properties::. + + There is also a special command for creating sparse trees based on a +single property: + +‘C-c / p’ + Create a sparse tree based on the value of a property. This first + prompts for the name of a property, and then for a value. A sparse + tree is created with all entries that define this property with the + given value. If you enclose the value in curly braces, it is + interpreted as a regular expression and matched against the + property values. + + +File: org, Node: Property inheritance, Next: Column view, Prev: Property searches, Up: Properties and columns + +7.4 Property Inheritance +======================== + +The outline structure of Org mode documents lends itself to an +inheritance model of properties: if the parent in a tree has a certain +property, the children can inherit this property. Org mode does not +turn this on by default, because it can slow down property searches +significantly and is often not needed. However, if you find inheritance +useful, you can turn it on by setting the variable +‘org-use-property-inheritance’. It may be set to ‘t’ to make all +properties inherited from the parent, to a list of properties that +should be inherited, or to a regular expression that matches inherited +properties. If a property has the value ‘nil’, this is interpreted as +an explicit undefine of the property, so that inheritance search will +stop at this value and return ‘nil’. + + Org mode has a few properties for which inheritance is hard-coded, at +least for the special applications for which they are used: + +‘COLUMNS’ + The ‘:COLUMNS:’ property defines the format of column view (*note + Column view::). It is inherited in the sense that the level where + a ‘:COLUMNS:’ property is defined is used as the starting point for + a column view table, independently of the location in the subtree + from where columns view is turned on. +‘CATEGORY’ + For agenda view, a category set through a ‘:CATEGORY:’ property + applies to the entire subtree. +‘ARCHIVE’ + For archiving, the ‘:ARCHIVE:’ property may define the archive + location for the entire subtree (*note Moving subtrees::). +‘LOGGING’ + The ‘LOGGING’ property may define logging settings for an entry or + a subtree (*note Tracking TODO state changes::). + + +File: org, Node: Column view, Next: Property API, Prev: Property inheritance, Up: Properties and columns + +7.5 Column view +=============== + +A great way to view and edit properties in an outline tree is _column +view_. In column view, each outline node is turned into a table row. +Columns in this table provide access to properties of the entries. Org +mode implements columns by overlaying a tabular structure over the +headline of each item. While the headlines have been turned into a +table row, you can still change the visibility of the outline tree. For +example, you get a compact table by switching to CONTENTS view (‘S- +S-’, or simply ‘c’ while column view is active), but you can still +open, read, and edit the entry below each headline. Or, you can switch +to column view after executing a sparse tree command and in this way get +a table only for the selected items. Column view also works in agenda +buffers (*note Agenda views::) where queries have collected selected +items, possibly from a number of files. + +* Menu: + +* Defining columns:: The COLUMNS format property +* Using column view:: How to create and use column view +* Capturing column view:: A dynamic block for column view + + +File: org, Node: Defining columns, Next: Using column view, Up: Column view + +7.5.1 Defining columns +---------------------- + +Setting up a column view first requires defining the columns. This is +done by defining a column format line. + +* Menu: + +* Scope of column definitions:: Where defined, where valid? +* Column attributes:: Appearance and content of a column + + +File: org, Node: Scope of column definitions, Next: Column attributes, Up: Defining columns + +7.5.1.1 Scope of column definitions +................................... + +To define a column format for an entire file, use a line like + + #+COLUMNS: %25ITEM %TAGS %PRIORITY %TODO + + To specify a format that only applies to a specific tree, add a +‘:COLUMNS:’ property to the top node of that tree, for example: + + ** Top node for columns view + :PROPERTIES: + :COLUMNS: %25ITEM %TAGS %PRIORITY %TODO + :END: + + If a ‘:COLUMNS:’ property is present in an entry, it defines columns +for the entry itself, and for the entire subtree below it. Since the +column definition is part of the hierarchical structure of the document, +you can define columns on level 1 that are general enough for all +sublevels, and more specific columns further down, when you edit a +deeper part of the tree. + + +File: org, Node: Column attributes, Prev: Scope of column definitions, Up: Defining columns + +7.5.1.2 Column attributes +......................... + +A column definition sets the attributes of a column. The general +definition looks like this: + + %[WIDTH]PROPERTY[(TITLE)][{SUMMARY-TYPE}] + +Except for the percent sign and the property name, all items are +optional. The individual parts have the following meaning: + + WIDTH An integer specifying the width of the column in characters. + If omitted, the width will be determined automatically. + PROPERTY The property that should be edited in this column. + Special properties representing meta data are allowed here + as well (*note Special properties::) + TITLE The header text for the column. If omitted, the property + name is used. + {SUMMARY-TYPE} The summary type. If specified, the column values for + parent nodes are computed from the children(1). + Supported summary types are: + {+} Sum numbers in this column. + {+;%.1f} Like ‘+’, but format result with ‘%.1f’. + {$} Currency, short for ‘+;%.2f’. + {min} Smallest number in column. + {max} Largest number. + {mean} Arithmetic mean of numbers. + {X} Checkbox status, ‘[X]’ if all children are ‘[X]’. + {X/} Checkbox status, ‘[n/m]’. + {X%} Checkbox status, ‘[n%]’. + {:} Sum times, HH:MM, plain numbers are + hours(2). + {:min} Smallest time value in column. + {:max} Largest time value. + {:mean} Arithmetic mean of time values. + {@min} Minimum age(3) (in + days/hours/mins/seconds). + {@max} Maximum age (in days/hours/mins/seconds). + {@mean} Arithmetic mean of ages (in days/hours/mins/seconds). + {est+} Add ‘low-high’ estimates. + + The ‘est+’ summary type requires further explanation. It is used for +combining estimates, expressed as ‘low-high’ ranges or plain numbers. +For example, instead of estimating a particular task will take 5 days, +you might estimate it as 5–6 days if you’re fairly confident you know +how much work is required, or 1–10 days if you don’t really know what +needs to be done. Both ranges average at 5.5 days, but the first +represents a more predictable delivery. + + When combining a set of such estimates, simply adding the lows and +highs produces an unrealistically wide result. Instead, ‘est+’ adds the +statistical mean and variance of the sub-tasks, generating a final +estimate from the sum. For example, suppose you had ten tasks, each of +which was estimated at 0.5 to 2 days of work. Straight addition +produces an estimate of 5 to 20 days, representing what to expect if +everything goes either extremely well or extremely poorly. In contrast, +‘est+’ estimates the full job more realistically, at 10–15 days. + + Numbers are right-aligned when a format specifier with an explicit +width like ‘%5d’ or ‘%5.1f’ is used. + + You can also define custom summary types by setting +‘org-columns-summary-types’, which see. + + Here is an example for a complete columns definition, along with +allowed values. + + :COLUMNS: %25ITEM %9Approved(Approved?){X} %Owner %11Status \(4) + %10Time_Estimate{:} %CLOCKSUM %CLOCKSUM_T + :Owner_ALL: Tammy Mark Karl Lisa Don + :Status_ALL: "In progress" "Not started yet" "Finished" "" + :Approved_ALL: "[ ]" "[X]" + +The first column, ‘%25ITEM’, means the first 25 characters of the item +itself, i.e., of the headline. You probably always should start the +column definition with the ‘ITEM’ specifier. The other specifiers +create columns ‘Owner’ with a list of names as allowed values, for +‘Status’ with four different possible values, and for a checkbox field +‘Approved’. When no width is given after the ‘%’ character, the column +will be exactly as wide as it needs to be in order to fully display all +values. The ‘Approved’ column does have a modified title (‘Approved?’, +with a question mark). Summaries will be created for the +‘Time_Estimate’ column by adding time duration expressions like HH:MM, +and for the ‘Approved’ column, by providing an ‘[X]’ status if all +children have been checked. The ‘CLOCKSUM’ and ‘CLOCKSUM_T’ columns are +special, they lists the sums of CLOCK intervals in the subtree, either +for all clocks or just for today. + + ---------- Footnotes ---------- + + (1) If more than one summary type apply to the property, the parent +values are computed according to the first of them. + + (2) A time can also be a duration, using effort modifiers defined in +‘org-effort-durations’, e.g., ‘3d 1h’. If any value in the column is as +such, the summary will also be an effort duration. + + (3) An age is defined as a duration since a given time-stamp (*note +Timestamps::). It can also be expressed as days, hours, minutes and +seconds, identified by ‘d’, ‘h’, ‘m’ and ‘s’ suffixes, all mandatory, +e.g., ‘0d 13h 0m 10s’. + + (4) Please note that the COLUMNS definition must be on a single +line—it is wrapped here only because of formatting constraints. + + +File: org, Node: Using column view, Next: Capturing column view, Prev: Defining columns, Up: Column view + +7.5.2 Using column view +----------------------- + + Turning column view on and off + .............................. + +‘C-c C-x C-c (org-columns)’ + Turn on column view. If the cursor is before the first headline in + the file, or the function called with the universal prefix + argument, column view is turned on for the entire file, using the + ‘#+COLUMNS’ definition. If the cursor is somewhere inside the + outline, this command searches the hierarchy, up from point, for a + ‘:COLUMNS:’ property that defines a format. When one is found, the + column view table is established for the tree starting at the entry + that contains the ‘:COLUMNS:’ property. If no such property is + found, the format is taken from the ‘#+COLUMNS’ line or from the + variable ‘org-columns-default-format’, and column view is + established for the current entry and its subtree. +‘r (org-columns-redo)’ + Recreate the column view, to include recent changes made in the + buffer. +‘g (org-columns-redo)’ + Same as ‘r’. +‘q (org-columns-quit)’ + Exit column view. + + Editing values + .............. + +‘ ’ + Move through the column view from field to field. +‘S-/’ + Switch to the next/previous allowed value of the field. For this, + you have to have specified allowed values for a property. +‘1..9,0’ + Directly select the Nth allowed value, ‘0’ selects the 10th value. +‘n (org-columns-next-allowed-value)’ +‘p (org-columns-previous-allowed-value)’ + Same as ‘S-/’ +‘e (org-columns-edit-value)’ + Edit the property at point. For the special properties, this will + invoke the same interface that you normally use to change that + property. For example, when editing a TAGS property, the tag + completion or fast selection interface will pop up. +‘C-c C-c (org-columns-set-tags-or-toggle)’ + When there is a checkbox at point, toggle it. +‘v (org-columns-show-value)’ + View the full value of this property. This is useful if the width + of the column is smaller than that of the value. +‘a (org-columns-edit-allowed)’ + Edit the list of allowed values for this property. If the list is + found in the hierarchy, the modified value is stored there. If no + list is found, the new value is stored in the first entry that is + part of the current column view. + + Modifying the table structure + ............................. + +‘< (org-columns-narrow)’ +‘> (org-columns-widen)’ + Make the column narrower/wider by one character. +‘S-M- (org-columns-new)’ + Insert a new column, to the left of the current column. +‘S-M- (org-columns-delete)’ + Delete the current column. + + +File: org, Node: Capturing column view, Prev: Using column view, Up: Column view + +7.5.3 Capturing column view +--------------------------- + +Since column view is just an overlay over a buffer, it cannot be +exported or printed directly. If you want to capture a column view, use +a ‘columnview’ dynamic block (*note Dynamic blocks::). The frame of +this block looks like this: + + * The column view + #+BEGIN: columnview :hlines 1 :id "label" + + #+END: + +This dynamic block has the following parameters: + +‘:id’ + This is the most important parameter. Column view is a feature + that is often localized to a certain (sub)tree, and the capture + block might be at a different location in the file. To identify + the tree whose view to capture, you can use 4 values: + local use the tree in which the capture block is located + global make a global view, including all headings in the file + "file:PATH-TO-FILE" + run column view at the top of this file + "ID" call column view in the tree that has an ‘:ID:’ + property with the value label. You can use + ‘M-x org-id-copy ’ to create a globally unique ‘ID’ for + the current entry and copy it to the kill-ring. +‘:hlines’ + When ‘t’, insert an hline after every line. When a number N, + insert an hline before each headline with level ‘<= N’. +‘:vlines’ + When set to ‘t’, force column groups to get vertical lines. +‘:maxlevel’ + When set to a number, don’t capture entries below this level. +‘:skip-empty-rows’ + When set to ‘t’, skip rows where the only non-empty specifier of + the column view is ‘ITEM’. +‘:indent’ + When non-‘nil’, indent each ‘ITEM’ field according to its level. + +The following commands insert or update the dynamic block: + +‘C-c C-x i (org-insert-columns-dblock)’ + Insert a dynamic block capturing a column view. You will be + prompted for the scope or ‘ID’ of the view. +‘C-c C-c or C-c C-x C-u (org-dblock-update)’ + Update dynamic block at point. +‘C-u C-c C-x C-u (org-update-all-dblocks)’ + Update all dynamic blocks (*note Dynamic blocks::). This is useful + if you have several clock table blocks, column-capturing blocks or + other dynamic blocks in a buffer. + + You can add formulas to the column view table and you may add +plotting instructions in front of the table—these will survive an update +of the block. If there is a ‘#+TBLFM:’ after the table, the table will +actually be recalculated automatically after an update. + + An alternative way to capture and process property values into a +table is provided by Eric Schulte’s ‘org-collector.el’ which is a +contributed package(1). It provides a general API to collect properties +from entries in a certain scope, and arbitrary Lisp expressions to +process these values before inserting them into a table or a dynamic +block. + + ---------- Footnotes ---------- + + (1) Contributed packages are not part of Emacs, but are distributed +with the main distribution of Org (visit ). + + +File: org, Node: Property API, Prev: Column view, Up: Properties and columns + +7.6 The Property API +==================== + +There is a full API for accessing and changing properties. This API can +be used by Emacs Lisp programs to work with properties and to implement +features based on them. For more information see *note Using the +property API::. + + +File: org, Node: Dates and times, Next: Capture - Refile - Archive, Prev: Properties and columns, Up: Top + +8 Dates and times +***************** + +To assist project planning, TODO items can be labeled with a date and/or +a time. The specially formatted string carrying the date and time +information is called a _timestamp_ in Org mode. This may be a little +confusing because timestamp is often used to indicate when something was +created or last changed. However, in Org mode this term is used in a +much wider sense. + +* Menu: + +* Timestamps:: Assigning a time to a tree entry +* Creating timestamps:: Commands which insert timestamps +* Deadlines and scheduling:: Planning your work +* Clocking work time:: Tracking how long you spend on a task +* Effort estimates:: Planning work effort in advance +* Timers:: Notes with a running timer + + +File: org, Node: Timestamps, Next: Creating timestamps, Up: Dates and times + +8.1 Timestamps, deadlines, and scheduling +========================================= + +A timestamp is a specification of a date (possibly with a time or a +range of times) in a special format, either ‘<2003-09-16 Tue>’(1) or +‘<2003-09-16 Tue 09:39>’ or ‘<2003-09-16 Tue 12:00-12:30>’(2). A +timestamp can appear anywhere in the headline or body of an Org tree +entry. Its presence causes entries to be shown on specific dates in the +agenda (*note Weekly/daily agenda::). We distinguish: + +PLAIN TIMESTAMP; EVENT; APPOINTMENT + A simple timestamp just assigns a date/time to an item. This is + just like writing down an appointment or event in a paper agenda. + In the agenda display, the headline of an entry associated with a + plain timestamp will be shown exactly on that date. + + * Meet Peter at the movies + <2006-11-01 Wed 19:15> + * Discussion on climate change + <2006-11-02 Thu 20:00-22:00> + +TIMESTAMP WITH REPEATER INTERVAL + A timestamp may contain a _repeater interval_, indicating that it + applies not only on the given date, but again and again after a + certain interval of N days (d), weeks (w), months (m), or years + (y). The following will show up in the agenda every Wednesday: + + * Pick up Sam at school + <2007-05-16 Wed 12:30 +1w> + +DIARY-STYLE SEXP ENTRIES + For more complex date specifications, Org mode supports using the + special sexp diary entries implemented in the Emacs calendar/diary + package(3). For example with optional time + + * 22:00-23:00 The nerd meeting on every 2nd Thursday of the month + <%%(diary-float t 4 2)> + +TIME/DATE RANGE + Two timestamps connected by ‘--’ denote a range. The headline will + be shown on the first and last day of the range, and on any dates + that are displayed and fall in the range. Here is an example: + + ** Meeting in Amsterdam + <2004-08-23 Mon>--<2004-08-26 Thu> + +INACTIVE TIMESTAMP + Just like a plain timestamp, but with square brackets instead of + angular ones. These timestamps are inactive in the sense that they + do _not_ trigger an entry to show up in the agenda. + + * Gillian comes late for the fifth time + [2006-11-01 Wed] + + ---------- Footnotes ---------- + + (1) In this simplest form, the day name is optional when you type the +date yourself. However, any dates inserted or modified by Org will add +that day name, for reading convenience. + + (2) This is inspired by the standard ISO 8601 date/time format. To +use an alternative format, see *note Custom time format::. + + (3) When working with the standard diary sexp functions, you need to +be very careful with the order of the arguments. That order depends +evilly on the variable ‘calendar-date-style’ (or, for older Emacs +versions, ‘european-calendar-style’). For example, to specify a date +December 1, 2005, the call might look like ‘(diary-date 12 1 2005)’ or +‘(diary-date 1 12 2005)’ or ‘(diary-date 2005 12 1)’, depending on the +settings. This has been the source of much confusion. Org mode users +can resort to special versions of these functions like ‘org-date’ or +‘org-anniversary’. These work just like the corresponding ‘diary-’ +functions, but with stable ISO order of arguments (year, month, day) +wherever applicable, independent of the value of ‘calendar-date-style’. + + +File: org, Node: Creating timestamps, Next: Deadlines and scheduling, Prev: Timestamps, Up: Dates and times + +8.2 Creating timestamps +======================= + +For Org mode to recognize timestamps, they need to be in the specific +format. All commands listed below produce timestamps in the correct +format. + +‘C-c . (org-time-stamp)’ + Prompt for a date and insert a corresponding timestamp. When the + cursor is at an existing timestamp in the buffer, the command is + used to modify this timestamp instead of inserting a new one. When + this command is used twice in succession, a time range is inserted. +‘C-c ! (org-time-stamp-inactive)’ + Like ‘C-c .’, but insert an inactive timestamp that will not cause + an agenda entry. +‘C-u C-c .’ +‘C-u C-c !’ + Like ‘C-c .’ and ‘C-c !’, but use the alternative format which + contains date and time. The default time can be rounded to + multiples of 5 minutes, see the option + ‘org-time-stamp-rounding-minutes’. +‘C-c C-c’ + Normalize timestamp, insert/fix day name if missing or wrong. +‘C-c < (org-date-from-calendar)’ + Insert a timestamp corresponding to the cursor date in the + Calendar. +‘C-c > (org-goto-calendar)’ + Access the Emacs calendar for the current date. If there is a + timestamp in the current line, go to the corresponding date + instead. +‘C-c C-o (org-open-at-point)’ + Access the agenda for the date given by the timestamp or -range at + point (*note Weekly/daily agenda::). +‘S- (org-timestamp-down-day)’ +‘S- (org-timestamp-up-day)’ + Change date at cursor by one day. These key bindings conflict with + shift-selection and related modes (*note Conflicts::). +‘S- (org-timestamp-up)’ +‘S- (org-timestamp-down-down)’ + Change the item under the cursor in a timestamp. The cursor can be + on a year, month, day, hour or minute. When the timestamp contains + a time range like ‘15:30-16:30’, modifying the first time will also + shift the second, shifting the time block with constant length. To + change the length, modify the second time. Note that if the cursor + is in a headline and not at a timestamp, these same keys modify the + priority of an item. (*note Priorities::). The key bindings also + conflict with shift-selection and related modes (*note + Conflicts::). +‘C-c C-y (org-evaluate-time-range)’ + Evaluate a time range by computing the difference between start and + end. With a prefix argument, insert result after the time range + (in a table: into the following column). + +* Menu: + +* The date/time prompt:: How Org mode helps you entering date and time +* Custom time format:: Making dates look different + + +File: org, Node: The date/time prompt, Next: Custom time format, Up: Creating timestamps + +8.2.1 The date/time prompt +-------------------------- + +When Org mode prompts for a date/time, the default is shown in default +date/time format, and the prompt therefore seems to ask for a specific +format. But it will in fact accept date/time information in a variety +of formats. Generally, the information should start at the beginning of +the string. Org mode will find whatever information is in there and +derive anything you have not specified from the _default date and time_. +The default is usually the current date and time, but when modifying an +existing timestamp, or when entering the second stamp of a range, it is +taken from the stamp in the buffer. When filling in information, Org +mode assumes that most of the time you will want to enter a date in the +future: if you omit the month/year and the given day/month is before +today, it will assume that you mean a future date(1). If the date has +been automatically shifted into the future, the time prompt will show +this with ‘(=>F).’ + + For example, let’s assume that today is June 13, 2006. Here is how +various inputs will be interpreted, the items filled in by Org mode are +in bold. + + 3-2-5 ⇒ 2003-02-05 + 2/5/3 ⇒ 2003-02-05 + 14 ⇒ 2006-06-14 + 12 ⇒ 2006-07-12 + 2/5 ⇒ 2007-02-05 + Fri ⇒ nearest Friday after the default date + sep 15 ⇒ 2006-09-15 + feb 15 ⇒ 2007-02-15 + sep 12 9 ⇒ 2009-09-12 + 12:45 ⇒ 2006-06-13 12:45 + 22 sept 0:34 ⇒ 2006-09-22 00:34 + w4 ⇒ ISO week four of the current year 2006 + 2012 w4 fri ⇒ Friday of ISO week 4 in 2012 + 2012-w04-5 ⇒ Same as above + + Furthermore you can specify a relative date by giving, as the _first_ +thing in the input: a plus/minus sign, a number and a letter ([hdwmy]) +to indicate change in hours, days, weeks, months, or years. With a +single plus or minus, the date is always relative to today. With a +double plus or minus, it is relative to the default date. If instead of +a single letter, you use the abbreviation of day name, the date will be +the Nth such day, e.g.: + + +0 ⇒ today + . ⇒ today + +4d ⇒ four days from today + +4 ⇒ same as above + +2w ⇒ two weeks from today + ++5 ⇒ five days from default date + +2tue ⇒ second Tuesday from now + -wed ⇒ last Wednesday + + The function understands English month and weekday abbreviations. If +you want to use unabbreviated names and/or other languages, configure +the variables ‘parse-time-months’ and ‘parse-time-weekdays’. + + Not all dates can be represented in a given Emacs implementation. By +default Org mode forces dates into the compatibility range 1970–2037 +which works on all Emacs implementations. If you want to use dates +outside of this range, read the docstring of the variable +‘org-read-date-force-compatible-dates’. + + You can specify a time range by giving start and end times or by +giving a start time and a duration (in HH:MM format). Use one or two +dash(es) as the separator in the former case and use ’+’ as the +separator in the latter case, e.g.: + + 11am-1:15pm ⇒ 11:00-13:15 + 11am--1:15pm ⇒ same as above + 11am+2:15 ⇒ same as above + + Parallel to the minibuffer prompt, a calendar is popped up(2). When +you exit the date prompt, either by clicking on a date in the calendar, +or by pressing , the date selected in the calendar will be combined +with the information entered at the prompt. You can control the +calendar fully from the minibuffer: + + Choose date at cursor in calendar. + mouse-1 Select date by clicking on it. + S-/ One day forward/backward. + S-/ One week forward/backward. + M-S-/ One month forward/backward. + > / < Scroll calendar forward/backward by one month. + M-v / C-v Scroll calendar forward/backward by 3 months. + M-S-/ Scroll calendar forward/backward by one year. + + The actions of the date/time prompt may seem complex, but I assure +you they will grow on you, and you will start getting annoyed by pretty +much any other way of entering a date/time out there. To help you +understand what is going on, the current interpretation of your input +will be displayed live in the minibuffer(3). + + ---------- Footnotes ---------- + + (1) See the variable ‘org-read-date-prefer-future’. You may set that +variable to the symbol ‘time’ to even make a time before now shift the +date to tomorrow. + + (2) If you don’t need/want the calendar, configure the variable +‘org-popup-calendar-for-date-prompt’. + + (3) If you find this distracting, turn the display off with +‘org-read-date-display-live’. + + +File: org, Node: Custom time format, Prev: The date/time prompt, Up: Creating timestamps + +8.2.2 Custom time format +------------------------ + +Org mode uses the standard ISO notation for dates and times as it is +defined in ISO 8601. If you cannot get used to this and require another +representation of date and time to keep you happy, you can get it by +customizing the options ‘org-display-custom-times’ and +‘org-time-stamp-custom-formats’. + +‘C-c C-x C-t (org-toggle-time-stamp-overlays)’ + Toggle the display of custom formats for dates and times. + +Org mode needs the default format for scanning, so the custom date/time +format does not _replace_ the default format—instead it is put _over_ +the default format using text properties. This has the following +consequences: + • You cannot place the cursor onto a timestamp anymore, only before + or after. + • The ‘S-/’ keys can no longer be used to adjust each + component of a timestamp. If the cursor is at the beginning of the + stamp, ‘S-/’ will change the stamp by one day, just like + ‘S-/’. At the end of the stamp, the time will be + changed by one minute. + • If the timestamp contains a range of clock times or a repeater, + these will not be overlaid, but remain in the buffer as they were. + • When you delete a timestamp character-by-character, it will only + disappear from the buffer after _all_ (invisible) characters + belonging to the ISO timestamp have been removed. + • If the custom timestamp format is longer than the default and you + are using dates in tables, table alignment will be messed up. If + the custom format is shorter, things do work as expected. + + +File: org, Node: Deadlines and scheduling, Next: Clocking work time, Prev: Creating timestamps, Up: Dates and times + +8.3 Deadlines and scheduling +============================ + +A timestamp may be preceded by special keywords to facilitate planning. +Both the timestamp and the keyword have to be positioned immediately +after the task they refer to. + +DEADLINE + + Meaning: the task (most likely a TODO item, though not necessarily) + is supposed to be finished on that date. + + On the deadline date, the task will be listed in the agenda. In + addition, the agenda for _today_ will carry a warning about the + approaching or missed deadline, starting + ‘org-deadline-warning-days’ before the due date, and continuing + until the entry is marked DONE. An example: + + *** TODO write article about the Earth for the Guide + DEADLINE: <2004-02-29 Sun> + The editor in charge is [[bbdb:Ford Prefect]] + + You can specify a different lead time for warnings for a specific + deadline using the following syntax. Here is an example with a + warning period of 5 days ‘DEADLINE: <2004-02-29 Sun -5d>’. This + warning is deactivated if the task gets scheduled and you set + ‘org-agenda-skip-deadline-prewarning-if-scheduled’ to ‘t’. + +SCHEDULED + + Meaning: you are planning to start working on that task on the + given date. + + The headline will be listed under the given date(1). In addition, + a reminder that the scheduled date has passed will be present in + the compilation for _today_, until the entry is marked DONE, i.e., + the task will automatically be forwarded until completed. + + *** TODO Call Trillian for a date on New Years Eve. + SCHEDULED: <2004-12-25 Sat> + + If you want to _delay_ the display of this task in the agenda, use + ‘SCHEDULED: <2004-12-25 Sat -2d>’: the task is still scheduled on + the 25th but will appear two days later. In case the task contains + a repeater, the delay is considered to affect all occurrences; if + you want the delay to only affect the first scheduled occurrence of + the task, use ‘--2d’ instead. See ‘org-scheduled-delay-days’ and + ‘org-agenda-skip-scheduled-delay-if-deadline’ for details on how to + control this globally or per agenda. + + Important: Scheduling an item in Org mode should not be understood + in the same way that we understand scheduling a meeting. Setting a + date for a meeting is just a simple appointment, you should mark + this entry with a simple plain timestamp, to get this item shown on + the date where it applies. This is a frequent misunderstanding by + Org users. In Org mode, scheduling means setting a date when you + want to start working on an action item. + + You may use timestamps with repeaters in scheduling and deadline +entries. Org mode will issue early and late warnings based on the +assumption that the timestamp represents the nearest instance of the +repeater. However, the use of diary sexp entries like ‘<%%(diary-float +t 42)>’ in scheduling and deadline timestamps is limited. Org mode does +not know enough about the internals of each sexp function to issue early +and late warnings. However, it will show the item on each day where the +sexp entry matches. + +* Menu: + +* Inserting deadline/schedule:: Planning items +* Repeated tasks:: Items that show up again and again + + ---------- Footnotes ---------- + + (1) It will still be listed on that date after it has been marked +DONE. If you don’t like this, set the variable +‘org-agenda-skip-scheduled-if-done’. + + +File: org, Node: Inserting deadline/schedule, Next: Repeated tasks, Up: Deadlines and scheduling + +8.3.1 Inserting deadlines or schedules +-------------------------------------- + +The following commands allow you to quickly insert a deadline or to +schedule an item: + +‘C-c C-d (org-deadline)’ + Insert ‘DEADLINE’ keyword along with a stamp. Any CLOSED timestamp + will be removed. When called with a prefix arg, an existing + deadline will be removed from the entry. Depending on the variable + ‘org-log-redeadline’(1), a note will be taken when changing an + existing deadline. + +‘C-c C-s (org-schedule)’ + Insert ‘SCHEDULED’ keyword along with a stamp. Any CLOSED + timestamp will be removed. When called with a prefix argument, + remove the scheduling date from the entry. Depending on the + variable ‘org-log-reschedule’(2), a note will be taken when + changing an existing scheduling time. +‘C-c / d (org-check-deadlines)’ + Create a sparse tree with all deadlines that are either past-due, + or which will become due within ‘org-deadline-warning-days’. With + ‘C-u’ prefix, show all deadlines in the file. With a numeric + prefix, check that many days. For example, ‘C-1 C-c / d’ shows all + deadlines due tomorrow. +‘C-c / b (org-check-before-date)’ + Sparse tree for deadlines and scheduled items before a given date. +‘C-c / a (org-check-after-date)’ + Sparse tree for deadlines and scheduled items after a given date. + + Note that ‘org-schedule’ and ‘org-deadline’ supports setting the date +by indicating a relative time: e.g., +1d will set the date to the next +day after today, and –1w will set the date to the previous week before +any current timestamp. + + ---------- Footnotes ---------- + + (1) with corresponding ‘#+STARTUP’ keywords ‘logredeadline’, +‘lognoteredeadline’, and ‘nologredeadline’ + + (2) with corresponding ‘#+STARTUP’ keywords ‘logreschedule’, +‘lognotereschedule’, and ‘nologreschedule’ + + +File: org, Node: Repeated tasks, Prev: Inserting deadline/schedule, Up: Deadlines and scheduling + +8.3.2 Repeated tasks +-------------------- + +Some tasks need to be repeated again and again. Org mode helps to +organize such tasks using a so-called repeater in a ‘DEADLINE’, +‘SCHEDULED’, or plain timestamp. In the following example + ** TODO Pay the rent + DEADLINE: <2005-10-01 Sat +1m> +the ‘+1m’ is a repeater; the intended interpretation is that the task +has a deadline on <2005-10-01> and repeats itself every (one) month +starting from that time. You can use yearly, monthly, weekly, daily and +hourly repeat cookies by using the ‘y/w/m/d/h’ letters. If you need +both a repeater and a special warning period in a deadline entry, the +repeater should come first and the warning period last: ‘DEADLINE: +<2005-10-01 Sat +1m -3d>’. + + Deadlines and scheduled items produce entries in the agenda when they +are over-due, so it is important to be able to mark such an entry as +completed once you have done so. When you mark a ‘DEADLINE’ or a +‘SCHEDULED’ with the TODO keyword DONE, it will no longer produce +entries in the agenda. The problem with this is, however, that then +also the _next_ instance of the repeated entry will not be active. Org +mode deals with this in the following way: When you try to mark such an +entry DONE (using ‘C-c C-t’), it will shift the base date of the +repeating timestamp by the repeater interval, and immediately set the +entry state back to TODO(1). In the example above, setting the state to +DONE would actually switch the date like this: + + ** TODO Pay the rent + DEADLINE: <2005-11-01 Tue +1m> + + To mark a task with a repeater as ‘DONE’, use ‘C-- 1 C-c C-t’ (i.e., +‘org-todo’ with a numeric prefix argument of -1.) + + A timestamp(2) will be added under the deadline, to keep a record +that you actually acted on the previous instance of this deadline. + + As a consequence of shifting the base date, this entry will no longer +be visible in the agenda when checking past dates, but all future +instances will be visible. + + With the ‘+1m’ cookie, the date shift will always be exactly one +month. So if you have not paid the rent for three months, marking this +entry DONE will still keep it as an overdue deadline. Depending on the +task, this may not be the best way to handle it. For example, if you +forgot to call your father for 3 weeks, it does not make sense to call +him 3 times in a single day to make up for it. Finally, there are tasks +like changing batteries which should always repeat a certain time after +the last time you did it. For these tasks, Org mode has special +repeaters ‘++’ and ‘.+’. For example: + + ** TODO Call Father + DEADLINE: <2008-02-10 Sun ++1w> + Marking this DONE will shift the date by at least one week, + but also by as many weeks as it takes to get this date into + the future. However, it stays on a Sunday, even if you called + and marked it done on Saturday. + ** TODO Empty kitchen trash + DEADLINE: <2008-02-08 Fri 20:00 ++1d> + Marking this DONE will shift the date by at least one day, and + also by as many days as it takes to get the timestamp into the + future. Since there is a time in the timestamp, the next + deadline in the future will be on today's date if you + complete the task before 20:00. + ** TODO Check the batteries in the smoke detectors + DEADLINE: <2005-11-01 Tue .+1m> + Marking this DONE will shift the date to one month after + today. + + You may have both scheduling and deadline information for a specific +task. If the repeater is set for the scheduling information only, you +probably want the repeater to be ignored after the deadline. If so, set +the variable ‘org-agenda-skip-scheduled-if-deadline-is-shown’ to +‘repeated-after-deadline’. However, any scheduling information without +a repeater is no longer relevant once the task is done, and thus, +removed upon repeating the task. If you want both scheduling and +deadline information to repeat after the same interval, set the same +repeater for both timestamps. + + An alternative to using a repeater is to create a number of copies of +a task subtree, with dates shifted in each copy. The command ‘C-c C-x +c’ was created for this purpose, it is described in *note Structure +editing::. + + ---------- Footnotes ---------- + + (1) In fact, the target state is taken from, in this sequence, the +‘REPEAT_TO_STATE’ property or the variable ‘org-todo-repeat-to-state’. +If neither of these is specified, the target state defaults to the first +state of the TODO state sequence. + + (2) You can change this using the option ‘org-log-repeat’, or the +‘#+STARTUP’ options ‘logrepeat’, ‘lognoterepeat’, and ‘nologrepeat’. +With ‘lognoterepeat’, you will also be prompted for a note. + + +File: org, Node: Clocking work time, Next: Effort estimates, Prev: Deadlines and scheduling, Up: Dates and times + +8.4 Clocking work time +====================== + +Org mode allows you to clock the time you spend on specific tasks in a +project. When you start working on an item, you can start the clock. +When you stop working on that task, or when you mark the task done, the +clock is stopped and the corresponding time interval is recorded. It +also computes the total time spent on each subtree(1) of a project. And +it remembers a history or tasks recently clocked, so that you can jump +quickly between a number of tasks absorbing your time. + + To save the clock history across Emacs sessions, use + (setq org-clock-persist 'history) + (org-clock-persistence-insinuate) + When you clock into a new task after resuming Emacs, the incomplete +clock(2) will be found (*note Resolving idle time::) and you will be +prompted about what to do with it. + +* Menu: + +* Clocking commands:: Starting and stopping a clock +* The clock table:: Detailed reports +* Resolving idle time:: Resolving time when you’ve been idle + + ---------- Footnotes ---------- + + (1) Clocking only works if all headings are indented with less than +30 stars. This is a hardcoded limitation of ‘lmax’ in ‘org-clock-sum’. + + (2) To resume the clock under the assumption that you have worked on +this task while outside Emacs, use ‘(setq org-clock-persist t)’. + + +File: org, Node: Clocking commands, Next: The clock table, Up: Clocking work time + +8.4.1 Clocking commands +----------------------- + +‘C-c C-x C-i (org-clock-in)’ + !Start the clock on the current item (clock-in). This inserts the + ‘CLOCK’ keyword together with a timestamp. If this is not the + first clocking of this item, the multiple ‘CLOCK’ lines will be + wrapped into a ‘:LOGBOOK:’ drawer (see also the variable + ‘org-clock-into-drawer’). You can also overrule the setting of + this variable for a subtree by setting a ‘CLOCK_INTO_DRAWER’ or + ‘LOG_INTO_DRAWER’ property. When called with a ‘C-u’ prefix + argument, select the task from a list of recently clocked tasks. + With two ‘C-u C-u’ prefixes, clock into the task at point and mark + it as the default task; the default task will then always be + available with letter ‘d’ when selecting a clocking task. With + three ‘C-u C-u C-u’ prefixes, force continuous clocking by starting + the clock when the last clock stopped. + While the clock is running, the current clocking time is shown in + the mode line, along with the title of the task. The clock time + shown will be all time ever clocked for this task and its children. + If the task has an effort estimate (*note Effort estimates::), the + mode line displays the current clocking time against it(1) If the + task is a repeating one (*note Repeated tasks::), only the time + since the last reset of the task (2) will be shown. More control + over what time is shown can be exercised with the + ‘CLOCK_MODELINE_TOTAL’ property. It may have the values ‘current’ + to show only the current clocking instance, ‘today’ to show all + time clocked on this task today (see also the variable + ‘org-extend-today-until’), ‘all’ to include all time, or ‘auto’ + which is the default(3). + Clicking with ‘mouse-1’ onto the mode line entry will pop up a menu + with clocking options. +‘C-c C-x C-o (org-clock-out)’ + Stop the clock (clock-out). This inserts another timestamp at the + same location where the clock was last started. It also directly + computes the resulting time and inserts it after the time range as + ‘=> HH:MM’. See the variable ‘org-log-note-clock-out’ for the + possibility to record an additional note together with the + clock-out timestamp(4). +‘C-c C-x C-x (org-clock-in-last)’ + Reclock the last clocked task. With one ‘C-u’ prefix argument, + select the task from the clock history. With two ‘C-u’ prefixes, + force continuous clocking by starting the clock when the last clock + stopped. +‘C-c C-x C-e (org-clock-modify-effort-estimate)’ + Update the effort estimate for the current clock task. +‘C-c C-c or C-c C-y (org-evaluate-time-range)’ + Recompute the time interval after changing one of the timestamps. + This is only necessary if you edit the timestamps directly. If you + change them with ‘S-’ keys, the update is automatic. +‘C-S- (org-clock-timestamps-up/down)’ + On ‘CLOCK’ log lines, increase/decrease both timestamps so that the + clock duration keeps the same. +‘S-M- (org-timestamp-up/down)’ + On ‘CLOCK’ log lines, increase/decrease the timestamp at point and + the one of the previous (or the next clock) timestamp by the same + duration. For example, if you hit ‘S-M-’ to increase a + clocked-out timestamp by five minutes, then the clocked-in + timestamp of the next clock will be increased by five minutes. +‘C-c C-t (org-todo)’ + Changing the TODO state of an item to DONE automatically stops the + clock if it is running in this same item. +‘C-c C-x C-q (org-clock-cancel)’ + Cancel the current clock. This is useful if a clock was started by + mistake, or if you ended up working on something else. +‘C-c C-x C-j (org-clock-goto)’ + Jump to the headline of the currently clocked in task. With a + ‘C-u’ prefix arg, select the target task from a list of recently + clocked tasks. +‘C-c C-x C-d (org-clock-display)’ + Display time summaries for each subtree in the current buffer. + This puts overlays at the end of each headline, showing the total + time recorded under that heading, including the time of any + subheadings. You can use visibility cycling to study the tree, but + the overlays disappear when you change the buffer (see variable + ‘org-remove-highlights-with-change’) or press ‘C-c C-c’. + + The ‘l’ key may be used the agenda (*note Weekly/daily agenda::) to +show which tasks have been worked on or closed during a day. + + *Important:* note that both ‘org-clock-out’ and ‘org-clock-in-last’ +can have a global key binding and will not modify the window +disposition. + + ---------- Footnotes ---------- + + (1) To add an effort estimate “on the fly”, hook a function doing +this to ‘org-clock-in-prepare-hook’. + + (2) as recorded by the ‘LAST_REPEAT’ property + + (3) See also the variable ‘org-clock-modeline-total’. + + (4) The corresponding in-buffer setting is: ‘#+STARTUP: +lognoteclock-out’ + + +File: org, Node: The clock table, Next: Resolving idle time, Prev: Clocking commands, Up: Clocking work time + +8.4.2 The clock table +--------------------- + +Org mode can produce quite complex reports based on the time clocking +information. Such a report is called a _clock table_, because it is +formatted as one or several Org tables. + +‘C-c C-x C-r (org-clock-report)’ + Insert a dynamic block (*note Dynamic blocks::) containing a clock + report as an Org mode table into the current file. When the cursor + is at an existing clock table, just update it. When called with a + prefix argument, jump to the first clock report in the current + document and update it. The clock table always includes also trees + with ‘:ARCHIVE:’ tag. +‘C-c C-c or C-c C-x C-u (org-dblock-update)’ + Update dynamic block at point. +‘C-u C-c C-x C-u’ + Update all dynamic blocks (*note Dynamic blocks::). This is useful + if you have several clock table blocks in a buffer. +‘S-’ +‘S- (org-clocktable-try-shift)’ + Shift the current ‘:block’ interval and update the table. The + cursor needs to be in the ‘#+BEGIN: clocktable’ line for this + command. If ‘:block’ is ‘today’, it will be shifted to ‘today-1’ + etc. + + Here is an example of the frame for a clock table as it is inserted +into the buffer with the ‘C-c C-x C-r’ command: + + #+BEGIN: clocktable :maxlevel 2 :emphasize nil :scope file + #+END: clocktable +The ‘BEGIN’ line specifies a number of options to define the scope, +structure, and formatting of the report. Defaults for all these options +can be configured in the variable ‘org-clocktable-defaults’. + +First there are options that determine which clock entries are to be +selected: + :maxlevel Maximum level depth to which times are listed in the table. + Clocks at deeper levels will be summed into the upper level. + :scope The scope to consider. This can be any of the following: + nil the current buffer or narrowed region + file the full current buffer + subtree the subtree where the clocktable is located + treeN the surrounding level N tree, for example ‘tree3’ + tree the surrounding level 1 tree + agenda all agenda files + ("file"..) scan these files + function the list of files returned by a function of no argument + file-with-archives current file and its archives + agenda-with-archives all agenda files, including archives + :block The time block to consider. This block is specified either + absolutely, or relative to the current time and may be any of + these formats: + 2007-12-31 New year eve 2007 + 2007-12 December 2007 + 2007-W50 ISO-week 50 in 2007 + 2007-Q2 2nd quarter in 2007 + 2007 the year 2007 + today, yesterday, today-N a relative day + thisweek, lastweek, thisweek-N a relative week + thismonth, lastmonth, thismonth-N a relative month + thisyear, lastyear, thisyear-N a relative year + untilnow + Use ‘S-/’ keys to shift the time interval. + :tstart A time string specifying when to start considering times. + Relative times like ‘"<-2w>"’ can also be used. See + *note Matching tags and properties:: for relative time syntax. + :tend A time string specifying when to stop considering times. + Relative times like ‘""’ can also be used. See + *note Matching tags and properties:: for relative time syntax. + :wstart The starting day of the week. The default is 1 for monday. + :mstart The starting day of the month. The default 1 is for the first + day of the month. + :step ‘week’ or ‘day’, to split the table into chunks. + To use this, ‘:block’ or ‘:tstart’, ‘:tend’ are needed. + :stepskip0 Do not show steps that have zero time. + :fileskip0 Do not show table sections from files which did not contribute. + :tags A tags match to select entries that should contribute. See + *note Matching tags and properties:: for the match syntax. + + Then there are options which determine the formatting of the table. +These options are interpreted by the function +‘org-clocktable-write-default’, but you can specify your own function +using the ‘:formatter’ parameter. + :emphasize When ‘t’, emphasize level one and level two items. + :lang Language(1) to use for descriptive cells like "Task". + :link Link the item headlines in the table to their origins. + :narrow An integer to limit the width of the headline column in + the org table. If you write it like ‘50!’, then the + headline will also be shortened in export. + :indent Indent each headline field according to its level. + :tcolumns Number of columns to be used for times. If this is smaller + than ‘:maxlevel’, lower levels will be lumped into one column. + :level Should a level number column be included? + :sort A cons cell like containing the column to sort and a sorting type. + E.g., ‘:sort (1 . ?a)’ sorts the first column alphabetically. + :compact Abbreviation for ‘:level nil :indent t :narrow 40! :tcolumns 1’ + All are overwritten except if there is an explicit ‘:narrow’ + :timestamp A timestamp for the entry, when available. Look for ‘SCHEDULED’, + ‘DEADLINE’, ‘TIMESTAMP’ and ‘TIMESTAMP_IA’, in this order. + :properties List of properties that should be shown in the table. Each + property will get its own column. + :inherit-props When this flag is ‘t’, the values for ‘:properties’ will be inherited. + :formula Content of a ‘#+TBLFM’ line to be added and evaluated. + As a special case, ‘:formula %’ adds a column with % time. + If you do not specify a formula here, any existing formula + below the clock table will survive updates and be evaluated. + :formatter A function to format clock data and insert it into the buffer. + To get a clock summary of the current level 1 tree, for the current +day, you could write + #+BEGIN: clocktable :maxlevel 2 :block today :scope tree1 :link t + #+END: clocktable +and to use a specific time range you could write(2) + #+BEGIN: clocktable :tstart "<2006-08-10 Thu 10:00>" + :tend "<2006-08-10 Thu 12:00>" + #+END: clocktable + A range starting a week ago and ending right now could be written as + #+BEGIN: clocktable :tstart "<-1w>" :tend "" + #+END: clocktable + A summary of the current subtree with % times would be + #+BEGIN: clocktable :scope subtree :link t :formula % + #+END: clocktable + A horizontally compact representation of everything clocked during +last week would be + #+BEGIN: clocktable :scope agenda :block lastweek :compact t + #+END: clocktable + + ---------- Footnotes ---------- + + (1) Language terms can be set through the variable +‘org-clock-clocktable-language-setup’. + + (2) Note that all parameters must be specified in a single line—the +line is broken here only to fit it into the manual. + + +File: org, Node: Resolving idle time, Prev: The clock table, Up: Clocking work time + +8.4.3 Resolving idle time and continuous clocking +------------------------------------------------- + +Resolving idle time +................... + +If you clock in on a work item, and then walk away from your +computer—perhaps to take a phone call—you often need to “resolve” the +time you were away by either subtracting it from the current clock, or +applying it to another one. + + By customizing the variable ‘org-clock-idle-time’ to some integer, +such as 10 or 15, Emacs can alert you when you get back to your computer +after being idle for that many minutes(1), and ask what you want to do +with the idle time. There will be a question waiting for you when you +get back, indicating how much idle time has passed (constantly updated +with the current amount), as well as a set of choices to correct the +discrepancy: + +‘k’ + To keep some or all of the minutes and stay clocked in, press ‘k’. + Org will ask how many of the minutes to keep. Press to keep + them all, effectively changing nothing, or enter a number to keep + that many minutes. +‘K’ + If you use the shift key and press ‘K’, it will keep however many + minutes you request and then immediately clock out of that task. + If you keep all of the minutes, this is the same as just clocking + out of the current task. +‘s’ + To keep none of the minutes, use ‘s’ to subtract all the away time + from the clock, and then check back in from the moment you + returned. +‘S’ + To keep none of the minutes and just clock out at the start of the + away time, use the shift key and press ‘S’. Remember that using + shift will always leave you clocked out, no matter which option you + choose. +‘C’ + To cancel the clock altogether, use ‘C’. Note that if instead of + canceling you subtract the away time, and the resulting clock + amount is less than a minute, the clock will still be canceled + rather than clutter up the log with an empty entry. + + What if you subtracted those away minutes from the current clock, and +now want to apply them to a new clock? Simply clock in to any task +immediately after the subtraction. Org will notice that you have +subtracted time “on the books”, so to speak, and will ask if you want to +apply those minutes to the next task you clock in on. + + There is one other instance when this clock resolution magic occurs. +Say you were clocked in and hacking away, and suddenly your cat chased a +mouse who scared a hamster that crashed into your UPS’s power button! +You suddenly lose all your buffers, but thanks to auto-save you still +have your recent Org mode changes, including your last clock in. + + If you restart Emacs and clock into any task, Org will notice that +you have a dangling clock which was never clocked out from your last +session. Using that clock’s starting time as the beginning of the +unaccounted-for period, Org will ask how you want to resolve that time. +The logic and behavior is identical to dealing with away time due to +idleness; it is just happening due to a recovery event rather than a set +amount of idle time. + + You can also check all the files visited by your Org agenda for +dangling clocks at any time using ‘M-x org-resolve-clocks ’ (or +‘C-c C-x C-z’). + +Continuous clocking +................... + +You may want to start clocking from the time when you clocked out the +previous task. To enable this systematically, set +‘org-clock-continuously’ to ‘t’. Each time you clock in, Org retrieves +the clock-out time of the last clocked entry for this session, and start +the new clock from there. + + If you only want this from time to time, use three universal prefix +arguments with ‘org-clock-in’ and two ‘C-u C-u’ with +‘org-clock-in-last’. + + ---------- Footnotes ---------- + + (1) On computers using macOS, idleness is based on actual user +idleness, not just Emacs’ idle time. For X11, you can install a utility +program ‘x11idle.c’, available in the ‘contrib/scripts’ directory of the +Org git distribution, or install the ‘xprintidle’ package and set it to +the variable ‘org-clock-x11idle-program-name’ if you are running Debian, +to get the same general treatment of idleness. On other systems, idle +time refers to Emacs idle time only. + + +File: org, Node: Effort estimates, Next: Timers, Prev: Clocking work time, Up: Dates and times + +8.5 Effort estimates +==================== + +If you want to plan your work in a very detailed way, or if you need to +produce offers with quotations of the estimated work effort, you may +want to assign effort estimates to entries. If you are also clocking +your work, you may later want to compare the planned effort with the +actual working time, a great way to improve planning estimates. Effort +estimates are stored in a special property ‘EFFORT’. You can set the +effort for an entry with the following commands: + +‘C-c C-x e (org-set-effort)’ + Set the effort estimate for the current entry. With a numeric + prefix argument, set it to the Nth allowed value (see below). This + command is also accessible from the agenda with the ‘e’ key. +‘C-c C-x C-e (org-clock-modify-effort-estimate)’ + Modify the effort estimate of the item currently being clocked. + + Clearly the best way to work with effort estimates is through column +view (*note Column view::). You should start by setting up discrete +values for effort estimates, and a ‘COLUMNS’ format that displays these +values together with clock sums (if you want to clock your time). For a +specific buffer you can use + + #+PROPERTY: Effort_ALL 0 0:10 0:30 1:00 2:00 3:00 4:00 5:00 6:00 7:00 + #+COLUMNS: %40ITEM(Task) %17Effort(Estimated Effort){:} %CLOCKSUM + +or, even better, you can set up these values globally by customizing the +variables ‘org-global-properties’ and ‘org-columns-default-format’. In +particular if you want to use this setup also in the agenda, a global +setup may be advised. + + The way to assign estimates to individual items is then to switch to +column mode, and to use ‘S-’ and ‘S-’ to change the value. +The values you enter will immediately be summed up in the hierarchy. In +the column next to it, any clocked time will be displayed. + + If you switch to column view in the daily/weekly agenda, the effort +column will summarize the estimated work effort for each day(1), and you +can use this to find space in your schedule. To get an overview of the +entire part of the day that is committed, you can set the option +‘org-agenda-columns-add-appointments-to-effort-sum’. The appointments +on a day that take place over a specified time interval will then also +be added to the load estimate of the day. + + Effort estimates can be used in secondary agenda filtering that is +triggered with the ‘/’ key in the agenda (*note Agenda commands::). If +you have these estimates defined consistently, two or three key presses +will narrow down the list to stuff that fits into an available time +slot. + + ---------- Footnotes ---------- + + (1) Please note the pitfalls of summing hierarchical data in a flat +list (*note Agenda column view::). + + +File: org, Node: Timers, Prev: Effort estimates, Up: Dates and times + +8.6 Taking notes with a timer +============================= + +Org provides two types of timers. There is a relative timer that counts +up, which can be useful when taking notes during, for example, a meeting +or a video viewing. There is also a countdown timer. + + The relative and countdown are started with separate commands. + +‘C-c C-x 0 (org-timer-start)’ + Start or reset the relative timer. By default, the timer is set to + 0. When called with a ‘C-u’ prefix, prompt the user for a starting + offset. If there is a timer string at point, this is taken as the + default, providing a convenient way to restart taking notes after a + break in the process. When called with a double prefix argument + ‘C-u C-u’, change all timer strings in the active region by a + certain amount. This can be used to fix timer strings if the timer + was not started at exactly the right moment. +‘C-c C-x ; (org-timer-set-timer)’ + Start a countdown timer. The user is prompted for a duration. + ‘org-timer-default-timer’ sets the default countdown value. Giving + a numeric prefix argument overrides this default value. This + command is available as ‘;’ in agenda buffers. + + Once started, relative and countdown timers are controlled with the +same commands. + +‘C-c C-x . (org-timer)’ + Insert the value of the current relative or countdown timer into + the buffer. If no timer is running, the relative timer will be + started. When called with a prefix argument, the relative timer is + restarted. +‘C-c C-x - (org-timer-item)’ + Insert a description list item with the value of the current + relative or countdown timer. With a prefix argument, first reset + the relative timer to 0. +‘M- (org-insert-heading)’ + Once the timer list is started, you can also use ‘M-’ to + insert new timer items. +‘C-c C-x , (org-timer-pause-or-continue)’ + Pause the timer, or continue it if it is already paused. +‘C-c C-x _ (org-timer-stop)’ + Stop the timer. After this, you can only start a new timer, not + continue the old one. This command also removes the timer from the + mode line. + + +File: org, Node: Capture - Refile - Archive, Next: Agenda views, Prev: Dates and times, Up: Top + +9 Capture - Refile - Archive +**************************** + +An important part of any organization system is the ability to quickly +capture new ideas and tasks, and to associate reference material with +them. Org does this using a process called capture. It also can store +files related to a task (attachments) in a special directory. Once in +the system, tasks and projects need to be moved around. Moving +completed project trees to an archive file keeps the system compact and +fast. + +* Menu: + +* Capture:: Capturing new stuff +* Attachments:: Add files to tasks +* RSS feeds:: Getting input from RSS feeds +* Protocols:: External (e.g., Browser) access to Emacs and Org +* Refile and copy:: Moving/copying a tree from one place to another +* Archiving:: What to do with finished projects + + +File: org, Node: Capture, Next: Attachments, Up: Capture - Refile - Archive + +9.1 Capture +=========== + +Capture lets you quickly store notes with little interruption of your +work flow. Org’s method for capturing new items is heavily inspired by +John Wiegley excellent ‘remember.el’ package. Up to version 6.36, Org +used a special setup for ‘remember.el’, then replaced it with +‘org-remember.el’. As of version 8.0, ‘org-remember.el’ has been +completely replaced by ‘org-capture.el’. + + If your configuration depends on ‘org-remember.el’, you need to +update it and use the setup described below. To convert your +‘org-remember-templates’, run the command + M-x org-capture-import-remember-templates +and then customize the new variable with ‘M-x customize-variable +org-capture-templates’, check the result, and save the customization. + +* Menu: + +* Setting up capture:: Where notes will be stored +* Using capture:: Commands to invoke and terminate capture +* Capture templates:: Define the outline of different note types + + +File: org, Node: Setting up capture, Next: Using capture, Up: Capture + +9.1.1 Setting up capture +------------------------ + +The following customization sets a default target file for notes, and +defines a global key(1) for capturing new material. + + (setq org-default-notes-file (concat org-directory "/notes.org")) + (define-key global-map "\C-cc" 'org-capture) + + ---------- Footnotes ---------- + + (1) Please select your own key, ‘C-c c’ is only a suggestion. + + +File: org, Node: Using capture, Next: Capture templates, Prev: Setting up capture, Up: Capture + +9.1.2 Using capture +------------------- + +‘C-c c (org-capture)’ + Call the command ‘org-capture’. Note that this key binding is + global and not active by default: you need to install it. If you + have templates defined *note Capture templates::, it will offer + these templates for selection or use a new Org outline node as the + default template. It will insert the template into the target file + and switch to an indirect buffer narrowed to this new node. You + may then insert the information you want. + +‘C-c C-c (org-capture-finalize)’ + Once you have finished entering information into the capture + buffer, ‘C-c C-c’ will return you to the window configuration + before the capture process, so that you can resume your work + without further distraction. When called with a prefix arg, + finalize and then jump to the captured item. + +‘C-c C-w (org-capture-refile)’ + Finalize the capture process by refiling (*note Refile and copy::) + the note to a different place. Please realize that this is a + normal refiling command that will be executed—so the cursor + position at the moment you run this command is important. If you + have inserted a tree with a parent and children, first move the + cursor back to the parent. Any prefix argument given to this + command will be passed on to the ‘org-refile’ command. + +‘C-c C-k (org-capture-kill)’ + Abort the capture process and return to the previous state. + + You can also call ‘org-capture’ in a special way from the agenda, +using the ‘k c’ key combination. With this access, any timestamps +inserted by the selected capture template will default to the cursor +date in the agenda, rather than to the current date. + + To find the locations of the last stored capture, use ‘org-capture’ +with prefix commands: + +‘C-u C-c c’ + Visit the target location of a capture template. You get to select + the template in the usual way. +‘C-u C-u C-c c’ + Visit the last stored capture item in its buffer. + + You can also jump to the bookmark ‘org-capture-last-stored’, which +will automatically be created unless you set ‘org-capture-bookmark’ to +‘nil’. + + To insert the capture at point in an Org buffer, call ‘org-capture’ +with a ‘C-0’ prefix argument. + + +File: org, Node: Capture templates, Prev: Using capture, Up: Capture + +9.1.3 Capture templates +----------------------- + +You can use templates for different types of capture items, and for +different target locations. The easiest way to create such templates is +through the customize interface. + +‘C-c c C’ + Customize the variable ‘org-capture-templates’. + + Before we give the formal description of template definitions, let’s +look at an example. Say you would like to use one template to create +general TODO entries, and you want to put these entries under the +heading ‘Tasks’ in your file ‘~/org/gtd.org’. Also, a date tree in the +file ‘journal.org’ should capture journal entries. A possible +configuration would look like: + + (setq org-capture-templates + '(("t" "Todo" entry (file+headline "~/org/gtd.org" "Tasks") + "* TODO %?\n %i\n %a") + ("j" "Journal" entry (file+olp+datetree "~/org/journal.org") + "* %?\nEntered on %U\n %i\n %a"))) + +If you then press ‘C-c c t’, Org will prepare the template for you like +this: + * TODO + [[file:LINK TO WHERE YOU INITIATED CAPTURE]] + +During expansion of the template, ‘%a’ has been replaced by a link to +the location from where you called the capture command. This can be +extremely useful for deriving tasks from emails, for example. You fill +in the task definition, press ‘C-c C-c’ and Org returns you to the same +place where you started the capture process. + + To define special keys to capture to a particular template without +going through the interactive template selection, you can create your +key binding like this: + + (define-key global-map "\C-cx" + (lambda () (interactive) (org-capture nil "x"))) + +* Menu: + +* Template elements:: What is needed for a complete template entry +* Template expansion:: Filling in information about time and context +* Templates in contexts:: Only show a template in a specific context + + +File: org, Node: Template elements, Next: Template expansion, Up: Capture templates + +9.1.3.1 Template elements +......................... + +Now lets look at the elements of a template definition. Each entry in +‘org-capture-templates’ is a list with the following items: + +KEYS + The keys that will select the template, as a string, characters + only, for example ‘"a"’ for a template to be selected with a single + key, or ‘"bt"’ for selection with two keys. When using several + keys, keys using the same prefix key must be sequential in the list + and preceded by a 2-element entry explaining the prefix key, for + example + ("b" "Templates for marking stuff to buy") + If you do not define a template for the ‘C’ key, this key will be + used to open the customize buffer for this complex variable. + +DESCRIPTION + A short string describing the template, which will be shown during + selection. + +TYPE + The type of entry, a symbol. Valid values are: + + ‘entry’ + An Org mode node, with a headline. Will be filed as the child + of the target entry or as a top-level entry. The target file + should be an Org mode file. + ‘item’ + A plain list item, placed in the first plain list at the + target location. Again the target file should be an Org file. + ‘checkitem’ + A checkbox item. This only differs from the plain list item + by the default template. + ‘table-line’ + a new line in the first table at the target location. Where + exactly the line will be inserted depends on the properties + ‘:prepend’ and ‘:table-line-pos’ (see below). + ‘plain’ + Text to be inserted as it is. + +TARGET + Specification of where the captured item should be placed. In Org + mode files, targets usually define a node. Entries will become + children of this node. Other types will be added to the table or + list in the body of this node. Most target specifications contain + a file name. If that file name is the empty string, it defaults to + ‘org-default-notes-file’. A file can also be given as a variable + or as a function called with no argument. When an absolute path is + not specified for a target, it is taken as relative to + ‘org-directory’. + + Valid values are: + + ‘(file "path/to/file")’ + Text will be placed at the beginning or end of that file. + + ‘(id "id of existing org entry")’ + Filing as child of this entry, or in the body of the entry. + + ‘(file+headline "path/to/file" "node headline")’ + Fast configuration if the target heading is unique in the + file. + + ‘(file+olp "path/to/file" "Level 1 heading" "Level 2" ...)’ + For non-unique headings, the full path is safer. + + ‘(file+regexp "path/to/file" "regexp to find location")’ + Use a regular expression to position the cursor. + + ‘(file+olp+datetree "path/to/file" [ "Level 1 heading" ....])’ + This target(1) will create a heading in a date tree(2) for + today’s date. If the optional outline path is given, the tree + will be built under the node it is pointing to, instead of at + top level. Check out the ‘:time-prompt’ and ‘:tree-type’ + properties below for additional options. + + ‘(file+function "path/to/file" function-finding-location)’ + A function to find the right location in the file. + + ‘(clock)’ + File to the entry that is currently being clocked. + + ‘(function function-finding-location)’ + Most general way: write your own function which both visits + the file and moves point to the right location. + +TEMPLATE + The template for creating the capture item. If you leave this + empty, an appropriate default template will be used. Otherwise + this is a string with escape codes, which will be replaced + depending on time and context of the capture call. The string with + escapes may be loaded from a template file, using the special + syntax ‘(file "path/to/template")’. See below for more details. + +PROPERTIES + The rest of the entry is a property list of additional options. + Recognized properties are: + + ‘:prepend’ + Normally new captured information will be appended at the + target location (last child, last table line, last list + item...). Setting this property will change that. + + ‘:immediate-finish’ + When set, do not offer to edit the information, just file it + away immediately. This makes sense if the template only needs + information that can be added automatically. + + ‘:empty-lines’ + Set this to the number of lines to insert before and after the + new item. Default 0, only common other value is 1. + + ‘:clock-in’ + Start the clock in this item. + + ‘:clock-keep’ + Keep the clock running when filing the captured entry. + + ‘:clock-resume’ + If starting the capture interrupted a clock, restart that + clock when finished with the capture. Note that ‘:clock-keep’ + has precedence over ‘:clock-resume’. When setting both to + ‘t’, the current clock will run and the previous one will not + be resumed. + + ‘:time-prompt’ + Prompt for a date/time to be used for date/week trees and when + filling the template. Without this property, capture uses the + current date and time. Even if this property has not been + set, you can force the same behavior by calling ‘org-capture’ + with a ‘C-1’ prefix argument. + + ‘:tree-type’ + When ‘week’, make a week tree instead of the month tree, i.e. + place the headings for each day under a heading with the + current iso week. + + ‘:unnarrowed’ + Do not narrow the target buffer, simply show the full buffer. + Default is to narrow it so that you only see the new material. + + ‘:table-line-pos’ + Specification of the location in the table where the new line + should be inserted. It can be a string, a variable holding a + string or a function returning a string. The string should + look like ‘"II-3"’ meaning that the new line should become the + third line before the second horizontal separator line. + + ‘:kill-buffer’ + If the target file was not yet visited when capture was + invoked, kill the buffer again after capture is completed. + + ---------- Footnotes ---------- + + (1) Org used to offer four different targets for date/week tree +capture. Now, Org automatically translates these to use +‘file+olp+datetree’, applying the ‘:time-prompt’ and ‘:tree-type’ +properties. Please rewrite your date/week-tree targets using +‘file+olp+datetree’ since the older targets are now deprecated. + + (2) A date tree is an outline structure with years on the highest +level, months or ISO-weeks as sublevels and then dates on the lowest +level. Tags are allowed in the tree structure. + + +File: org, Node: Template expansion, Next: Templates in contexts, Prev: Template elements, Up: Capture templates + +9.1.3.2 Template expansion +.......................... + +In the template itself, special ‘%’-escapes(1) allow dynamic insertion +of content. The templates are expanded in the order given here: + + %[FILE] Insert the contents of the file given by FILE. + %(SEXP) Evaluate Elisp SEXP and replace with the result. + For convenience, %:keyword (see below) placeholders + within the expression will be expanded prior to this. + The sexp must return a string. + %<...> The result of format-time-string on the ... format specification. + %t Timestamp, date only. + %T Timestamp, with date and time. + %u, %U Like the above, but inactive timestamps. + %i Initial content, the region when capture is called while the + region is active. + The entire text will be indented like ‘%i’ itself. + %a Annotation, normally the link created with ‘org-store-link’. + %A Like ‘%a’, but prompt for the description part. + %l Like %a, but only insert the literal link. + %c Current kill ring head. + %x Content of the X clipboard. + %k Title of the currently clocked task. + %K Link to the currently clocked task. + %n User name (taken from ‘user-full-name’). + %f File visited by current buffer when org-capture was called. + %F Full path of the file or directory visited by current buffer. + %:keyword Specific information for certain link types, see below. + %^g Prompt for tags, with completion on tags in target file. + %^G Prompt for tags, with completion all tags in all agenda files. + %^t Like ‘%t’, but prompt for date. Similarly ‘%^T’, ‘%^u’, ‘%^U’. + You may define a prompt like ‘%^{Birthday}t’. + %^C Interactive selection of which kill or clip to use. + %^L Like ‘%^C’, but insert as link. + %^{PROP}p Prompt the user for a value for property PROP. + %^{PROMPT} prompt the user for a string and replace this sequence with it. + You may specify a default value and a completion table with + %^{prompt|default|completion2|completion3...}. + The arrow keys access a prompt-specific history. + %\1 ... %\N Insert the text entered at the Nth %^{PROMPT}, where ‘N’ is + a number, starting from 1.(2) + %? After completing the template, position cursor here. + +For specific link types, the following keywords will be defined(3): + + Link type | Available keywords + ---------------------------------+---------------------------------------------- + bbdb | %:name %:company + irc | %:server %:port %:nick + vm, vm-imap, wl, mh, mew, rmail, | %:type %:subject %:message-id + gnus, notmuch | %:from %:fromname %:fromaddress + | %:to %:toname %:toaddress + | %:date (message date header field) + | %:date-timestamp (date as active timestamp) + | %:date-timestamp-inactive (date as inactive timestamp) + | %:fromto (either "to NAME" or "from NAME")(4) + gnus | %:group, for messages also all email fields + eww, w3, w3m | %:url + info | %:file %:node + calendar | %:date + org-protocol | %:link %:description %:annotation + +To place the cursor after template expansion use: + + %? After completing the template, position cursor here. + + ---------- Footnotes ---------- + + (1) If you need one of these sequences literally, escape the ‘%’ with +a backslash. + + (2) As required in Emacs Lisp, it is necessary to escape any +backslash character in a string with another backslash. So, in order to +use ‘%\1’ placeholder, you need to write ‘%\\1’ in the template. + + (3) If you define your own link types (*note Adding hyperlink +types::), any property you store with ‘org-store-link-props’ can be +accessed in capture templates in a similar way. + + (4) This will always be the other, not the user. See the variable +‘org-from-is-user-regexp’. + + +File: org, Node: Templates in contexts, Prev: Template expansion, Up: Capture templates + +9.1.3.3 Templates in contexts +............................. + +To control whether a capture template should be accessible from a +specific context, you can customize ‘org-capture-templates-contexts’. +Let’s say for example that you have a capture template ‘"p"’ for storing +Gnus emails containing patches. Then you would configure this option +like this: + + (setq org-capture-templates-contexts + '(("p" (in-mode . "message-mode")))) + + You can also tell that the command key ‘"p"’ should refer to another +template. In that case, add this command key like this: + + (setq org-capture-templates-contexts + '(("p" "q" (in-mode . "message-mode")))) + + See the docstring of the variable for more information. + + +File: org, Node: Attachments, Next: RSS feeds, Prev: Capture, Up: Capture - Refile - Archive + +9.2 Attachments +=============== + +It is often useful to associate reference material with an outline +node/task. Small chunks of plain text can simply be stored in the +subtree of a project. Hyperlinks (*note Hyperlinks::) can establish +associations with files that live elsewhere on your computer or in the +cloud, like emails or source code files belonging to a project. Another +method is attachments, which are files located in a directory belonging +to an outline node. Org uses directories named by the unique ID of each +entry. These directories are located in the ‘data’ directory which +lives in the same directory where your Org file lives(1). If you +initialize this directory with ‘git init’, Org will automatically commit +changes when it sees them. The attachment system has been contributed +to Org by John Wiegley. + + In cases where it seems better to do so, you can also attach a +directory of your choice to an entry. You can also make children +inherit the attachment directory from a parent, so that an entire +subtree uses the same attached directory. + +The following commands deal with attachments: + +‘C-c C-a (org-attach)’ + The dispatcher for commands related to the attachment system. + After these keys, a list of commands is displayed and you must + press an additional key to select a command: + + ‘a (org-attach-attach)’ + Select a file and move it into the task’s attachment + directory. The file will be copied, moved, or linked, + depending on ‘org-attach-method’. Note that hard links are + not supported on all systems. + + ‘c/m/l’ + Attach a file using the copy/move/link method. Note that hard + links are not supported on all systems. + + ‘u (org-attach-url)’ + Attach a file from URL + + ‘n (org-attach-new)’ + Create a new attachment as an Emacs buffer. + + ‘z (org-attach-sync)’ + Synchronize the current task with its attachment directory, in + case you added attachments yourself. + + ‘o (org-attach-open)’ + Open current task’s attachment. If there is more than one, + prompt for a file name first. Opening will follow the rules + set by ‘org-file-apps’. For more details, see the information + on following hyperlinks (*note Handling links::). + + ‘O (org-attach-open-in-emacs)’ + Also open the attachment, but force opening the file in Emacs. + + ‘f (org-attach-reveal)’ + Open the current task’s attachment directory. + + ‘F (org-attach-reveal-in-emacs)’ + Also open the directory, but force using ‘dired’ in Emacs. + + ‘d (org-attach-delete-one)’ + Select and delete a single attachment. + + ‘D (org-attach-delete-all)’ + Delete all of a task’s attachments. A safer way is to open + the directory in ‘dired’ and delete from there. + + ‘s (org-attach-set-directory)’ + Set a specific directory as the entry’s attachment directory. + This works by putting the directory path into the ‘ATTACH_DIR’ + property. + + ‘i (org-attach-set-inherit)’ + Set the ‘ATTACH_DIR_INHERIT’ property, so that children will + use the same directory for attachments as the parent does. + + ---------- Footnotes ---------- + + (1) If you move entries or Org files from one directory to another, +you may want to configure ‘org-attach-directory’ to contain an absolute +path. + + +File: org, Node: RSS feeds, Next: Protocols, Prev: Attachments, Up: Capture - Refile - Archive + +9.3 RSS feeds +============= + +Org can add and change entries based on information found in RSS feeds +and Atom feeds. You could use this to make a task out of each new +podcast in a podcast feed. Or you could use a phone-based note-creating +service on the web to import tasks into Org. To access feeds, configure +the variable ‘org-feed-alist’. The docstring of this variable has +detailed information. Here is just an example: + + (setq org-feed-alist + '(("Slashdot" + "http://rss.slashdot.org/Slashdot/slashdot" + "~/txt/org/feeds.org" "Slashdot Entries"))) + +will configure that new items from the feed provided by +‘rss.slashdot.org’ will result in new entries in the file +‘~/org/feeds.org’ under the heading ‘Slashdot Entries’, whenever the +following command is used: + +‘C-c C-x g (org-feed-update-all)’ +‘C-c C-x g’ + Collect items from the feeds configured in ‘org-feed-alist’ and act + upon them. +‘C-c C-x G (org-feed-goto-inbox)’ + Prompt for a feed name and go to the inbox configured for this + feed. + + Under the same headline, Org will create a drawer ‘FEEDSTATUS’ in +which it will store information about the status of items in the feed, +to avoid adding the same item several times. + + For more information, including how to read atom feeds, see +‘org-feed.el’ and the docstring of ‘org-feed-alist’. + + +File: org, Node: Protocols, Next: Refile and copy, Prev: RSS feeds, Up: Capture - Refile - Archive + +9.4 Protocols for external access +================================= + +Org protocol is a mean to trigger custom actions in Emacs from external +applications. Any application that supports calling external programs +with an URL as argument may be used with this functionality. For +example, you can configure bookmarks in your web browser to send a link +to the current page to Org and create a note from it using capture +(*note Capture::). You can also create a bookmark that tells Emacs to +open the local source file of a remote website you are browsing. + + In order to use Org protocol from an application, you need to +register ‘org-protocol://’ as a valid scheme-handler. External calls +are passed to Emacs through the ‘emacsclient’ command, so you also need +to ensure an Emacs server is running. More precisely, when the +application calls + + emacsclient org-protocol://PROTOCOL?key1=val1&key2=val2 + +Emacs calls the handler associated to ‘PROTOCOL’ with argument ‘(:key1 +val1 :key2 val2)’. + + Org protocol comes with three predefined protocols, detailed in the +following sections. Configure ‘org-protocol-protocol-alist’ to define +your own. + +* Menu: + +* store-link protocol:: Store a link, push URL to kill-ring. +* capture protocol:: Fill a buffer with external information. +* open-source protocol:: Edit published contents. + + +File: org, Node: store-link protocol, Next: capture protocol, Up: Protocols + +9.4.1 ‘store-link’ protocol +--------------------------- + +Using ‘store-link’ handler, you can copy links, insertable through ‘M-x +org-insert-link’ or yanking thereafter. More precisely, the command + + emacsclient org-protocol://store-link?url=URL&title=TITLE + +stores the following link: + + [[URL][TITLE]] + + In addition, ‘URL’ is pushed on the kill-ring for yanking. You need +to encode ‘URL’ and ‘TITLE’ if they contain slashes, and probably quote +those for the shell. + + To use this feature from a browser, add a bookmark with an arbitrary +name, e.g., ‘Org: store-link’ and enter this as _Location_: + + javascript:location.href='org-protocol://store-link?url='+ + encodeURIComponent(location.href); + + +File: org, Node: capture protocol, Next: open-source protocol, Prev: store-link protocol, Up: Protocols + +9.4.2 ‘capture’ protocol +------------------------ + +Activating ‘capture’ handler pops up a ‘Capture’ buffer and fills the +capture template associated to the ‘X’ key with them. + + emacsclient org-protocol://capture?template=X?url=URL?title=TITLE?body=BODY + + To use this feature, add a bookmark with an arbitrary name, e.g. +‘Org: capture’ and enter this as ‘Location’: + + javascript:location.href='org-protocol://capture?template=x'+ + '&url='+encodeURIComponent(window.location.href)+ + '&title='+encodeURIComponent(document.title)+ + '&body='+encodeURIComponent(window.getSelection()); + + The result depends on the capture template used, which is set in the +bookmark itself, as in the example above, or in +‘org-protocol-default-template-key’. + + The following template placeholders are available: + + %:link The URL + %:description The webpage title + %:annotation Equivalent to [[%:link][%:description]] + %i The selected text + + +File: org, Node: open-source protocol, Prev: capture protocol, Up: Protocols + +9.4.3 ‘open-source’ protocol +---------------------------- + +The ‘open-source’ handler is designed to help with editing local sources +when reading a document. To that effect, you can use a bookmark with +the following location: + + javascript:location.href='org-protocol://open-source?&url='+ + encodeURIComponent(location.href) + + The variable ‘org-protocol-project-alist’ maps URLs to local file +names, by stripping URL parameters from the end and replacing the +‘:base-url’ with ‘:working-directory’ and ‘:online-suffix’ with +‘:working-suffix’. For example, assuming you own a local copy of + contents at ‘/home/user/worg’, you can set +‘org-protocol-project-alist’ to the following + + (setq org-protocol-project-alist + '(("Worg" + :base-url "https://orgmode.org/worg/" + :working-directory "/home/user/worg/" + :online-suffix ".html" + :working-suffix ".org"))) + +If you are now browsing + and find a typo +or have an idea about how to enhance the documentation, simply click the +bookmark and start editing. + + However, such mapping may not yield the desired results. Suppose you +maintain an online store located at . The local +sources reside in ‘/home/user/example/’. It is common practice to serve +all products in such a store through one file and rewrite URLs that do +not match an existing file on the server. That way, a request to + might be rewritten on the server +to something like +. The +‘open-source’ handler probably cannot find a file named +‘/home/user/example/print/posters.html.php’ and fails. + + Such an entry in ‘org-protocol-project-alist’ may hold an additional +property ‘:rewrites’. This property is a list of cons cells, each of +which maps a regular expression to a path relative to the +‘:working-directory’. + + Now map the URL to the path ‘/home/user/example/products.php’ by +adding ‘:rewrites’ rules like this: + + (setq org-protocol-project-alist + '(("example.com" + :base-url "http://example.com/" + :working-directory "/home/user/example/" + :online-suffix ".php" + :working-suffix ".php" + :rewrites (("example.com/print/" . "products.php") + ("example.com/$" . "index.php"))))) + +Since ‘example.com/$’ is used as a regular expression, it maps +, , +and similar to ‘/home/user/example/index.php’. + + The ‘:rewrites’ rules are searched as a last resort if and only if no +existing file name is matched. + + Two functions can help you filling ‘org-protocol-project-alist’ with +valid contents: ‘org-protocol-create’ and ‘org-protocol-create-for-org’. +The latter is of use if you’re editing an Org file that is part of a +publishing project. + + +File: org, Node: Refile and copy, Next: Archiving, Prev: Protocols, Up: Capture - Refile - Archive + +9.5 Refile and copy +=================== + +When reviewing the captured data, you may want to refile or to copy some +of the entries into a different list, for example into a project. +Cutting, finding the right location, and then pasting the note is +cumbersome. To simplify this process, you can use the following special +command: + +‘C-c M-w (org-copy)’ + Copying works like refiling, except that the original note is not + deleted. +‘C-c C-w (org-refile)’ + Refile the entry or region at point. This command offers possible + locations for refiling the entry and lets you select one with + completion. The item (or all items in the region) is filed below + the target heading as a subitem. Depending on + ‘org-reverse-note-order’, it will be either the first or last + subitem. + By default, all level 1 headlines in the current buffer are + considered to be targets, but you can have more complex definitions + across a number of files. See the variable ‘org-refile-targets’ + for details. If you would like to select a location via a + file-path-like completion along the outline path, see the variables + ‘org-refile-use-outline-path’ and + ‘org-outline-path-complete-in-steps’. If you would like to be able + to create new nodes as new parents for refiling on the fly, check + the variable ‘org-refile-allow-creating-parent-nodes’. When the + variable ‘org-log-refile’(1) is set, a timestamp or a note will be + recorded when an entry has been refiled. +‘C-u C-c C-w’ + Use the refile interface to jump to a heading. +‘C-u C-u C-c C-w (org-refile-goto-last-stored)’ + Jump to the location where ‘org-refile’ last moved a tree to. +‘C-2 C-c C-w’ + Refile as the child of the item currently being clocked. +‘C-3 C-c C-w’ + Refile and keep the entry in place. Also see ‘org-refile-keep’ to + make this the default behavior, and beware that this may result in + duplicated ‘ID’ properties. +‘C-0 C-c C-w or C-u C-u C-u C-c C-w (org-refile-cache-clear)’ + Clear the target cache. Caching of refile targets can be turned on + by setting ‘org-refile-use-cache’. To make the command see new + possible targets, you have to clear the cache with this command. + + ---------- Footnotes ---------- + + (1) with corresponding ‘#+STARTUP’ keywords ‘logrefile’, +‘lognoterefile’, and ‘nologrefile’ + + +File: org, Node: Archiving, Prev: Refile and copy, Up: Capture - Refile - Archive + +9.6 Archiving +============= + +When a project represented by a (sub)tree is finished, you may want to +move the tree out of the way and to stop it from contributing to the +agenda. Archiving is important to keep your working files compact and +global searches like the construction of agenda views fast. + +‘C-c C-x C-a (org-archive-subtree-default)’ + Archive the current entry using the command specified in the + variable ‘org-archive-default-command’. + +* Menu: + +* Moving subtrees:: Moving a tree to an archive file +* Internal archiving:: Switch off a tree but keep it in the file + + +File: org, Node: Moving subtrees, Next: Internal archiving, Up: Archiving + +9.6.1 Moving a tree to the archive file +--------------------------------------- + +The most common archiving action is to move a project tree to another +file, the archive file. + +‘C-c C-x C-s or short C-c $ (org-archive-subtree)’ + Archive the subtree starting at the cursor position to the location + given by ‘org-archive-location’. +‘C-u C-c C-x C-s’ + Check if any direct children of the current headline could be moved + to the archive. To do this, each subtree is checked for open TODO + entries. If none are found, the command offers to move it to the + archive location. If the cursor is _not_ on a headline when this + command is invoked, the level 1 trees will be checked. +‘C-u C-u C-c C-x C-s’ + As above, but check subtree for timestamps instead of TODO entries. + The command will offer to archive the subtree if it _does_ contain + a timestamp, and that timestamp is in the past. + + The default archive location is a file in the same directory as the +current file, with the name derived by appending ‘_archive’ to the +current file name. You can also choose what heading to file archived +items under, with the possibility to add them to a datetree in a file. +For information and examples on how to specify the file and the heading, +see the documentation string of the variable ‘org-archive-location’. + + There is also an in-buffer option for setting this variable, for +example: + + #+ARCHIVE: %s_done:: + +If you would like to have a special ARCHIVE location for a single entry +or a (sub)tree, give the entry an ‘:ARCHIVE:’ property with the location +as the value (*note Properties and columns::). + + When a subtree is moved, it receives a number of special properties +that record context information like the file from where the entry came, +its outline path the archiving time etc. Configure the variable +‘org-archive-save-context-info’ to adjust the amount of information +added. + + +File: org, Node: Internal archiving, Prev: Moving subtrees, Up: Archiving + +9.6.2 Internal archiving +------------------------ + +If you want to just switch off—for agenda views—certain subtrees without +moving them to a different file, you can use the archive tag. + + A headline that is marked with the ‘:ARCHIVE:’ tag (*note Tags::) +stays at its location in the outline tree, but behaves in the following +way: + − It does not open when you attempt to do so with a visibility + cycling command (*note Visibility cycling::). You can force + cycling archived subtrees with ‘C-’, or by setting the option + ‘org-cycle-open-archived-trees’. Also normal outline commands like + ‘show-all’ will open archived subtrees. + − During sparse tree construction (*note Sparse trees::), matches in + archived subtrees are not exposed, unless you configure the option + ‘org-sparse-tree-open-archived-trees’. + − During agenda view construction (*note Agenda views::), the content + of archived trees is ignored unless you configure the option + ‘org-agenda-skip-archived-trees’, in which case these trees will + always be included. In the agenda you can press ‘v a’ to get + archives temporarily included. + − Archived trees are not exported (*note Exporting::), only the + headline is. Configure the details using the variable + ‘org-export-with-archived-trees’. + − Archived trees are excluded from column view unless the variable + ‘org-columns-skip-archived-trees’ is configured to ‘nil’. + + The following commands help manage the ARCHIVE tag: + +‘C-c C-x a (org-toggle-archive-tag)’ + Toggle the ARCHIVE tag for the current headline. When the tag is + set, the headline changes to a shadowed face, and the subtree below + it is hidden. +‘C-u C-c C-x a’ + Check if any direct children of the current headline should be + archived. To do this, each subtree is checked for open TODO + entries. If none are found, the command offers to set the ARCHIVE + tag for the child. If the cursor is _not_ on a headline when this + command is invoked, the level 1 trees will be checked. +‘C- (org-force-cycle-archived)’ + Cycle a tree even if it is tagged with ARCHIVE. +‘C-c C-x A (org-archive-to-archive-sibling)’ + Move the current entry to the _Archive Sibling_. This is a sibling + of the entry with the heading ‘Archive’ and the tag ‘ARCHIVE’. The + entry becomes a child of that sibling and in this way retains a lot + of its original context, including inherited tags and approximate + position in the outline. + + +File: org, Node: Agenda views, Next: Markup, Prev: Capture - Refile - Archive, Up: Top + +10 Agenda views +*************** + +Due to the way Org works, TODO items, time-stamped items, and tagged +headlines can be scattered throughout a file or even a number of files. +To get an overview of open action items, or of events that are important +for a particular date, this information must be collected, sorted and +displayed in an organized way. + + Org can select items based on various criteria and display them in a +separate buffer. Six different view types are provided: + + • an _agenda_ that is like a calendar and shows information for + specific dates, + • a _TODO list_ that covers all unfinished action items, + • a _match view_, showings headlines based on the tags, properties, + and TODO state associated with them, + • a _text search view_ that shows all entries from multiple files + that contain specified keywords, + • a _stuck projects view_ showing projects that currently don’t move + along, and + • _custom views_ that are special searches and combinations of + different views. + +The extracted information is displayed in a special _agenda buffer_. +This buffer is read-only, but provides commands to visit the +corresponding locations in the original Org files, and even to edit +these files remotely. + + By default, the report ignores commented (*note Comment lines::) and +archived (*note Internal archiving::) entries. You can override this by +setting ‘org-agenda-skip-comment-trees’ and +‘org-agenda-skip-archived-trees’ to ‘nil’. + + Two variables control how the agenda buffer is displayed and whether +the window configuration is restored when the agenda exits: +‘org-agenda-window-setup’ and ‘org-agenda-restore-windows-after-quit’. + +* Menu: + +* Agenda files:: Files being searched for agenda information +* Agenda dispatcher:: Keyboard access to agenda views +* Built-in agenda views:: What is available out of the box? +* Presentation and sorting:: How agenda items are prepared for display +* Agenda commands:: Remote editing of Org trees +* Custom agenda views:: Defining special searches and views +* Exporting agenda views:: Writing a view to a file +* Agenda column view:: Using column view for collected entries + + +File: org, Node: Agenda files, Next: Agenda dispatcher, Up: Agenda views + +10.1 Agenda files +================= + +The information to be shown is normally collected from all _agenda +files_, the files listed in the variable ‘org-agenda-files’(1). If a +directory is part of this list, all files with the extension ‘.org’ in +this directory will be part of the list. + + Thus, even if you only work with a single Org file, that file should +be put into the list(2). You can customize ‘org-agenda-files’, but the +easiest way to maintain it is through the following commands + +‘C-c [ (org-agenda-file-to-front)’ + Add current file to the list of agenda files. The file is added to + the front of the list. If it was already in the list, it is moved + to the front. With a prefix argument, file is added/moved to the + end. +‘C-c ] (org-remove-file)’ + Remove current file from the list of agenda files. +‘C-' (org-cycle-agenda-files)’ +‘C-,’ + Cycle through agenda file list, visiting one file after the other. +‘M-x org-switchb ’ + Command to use an ‘iswitchb’-like interface to switch to and + between Org buffers. + +The Org menu contains the current list of files and can be used to visit +any of them. + + If you would like to focus the agenda temporarily on a file not in +this list, or on just one file in the list, or even on only a subtree in +a file, then this can be done in different ways. For a single agenda +command, you may press ‘<’ once or several times in the dispatcher +(*note Agenda dispatcher::). To restrict the agenda scope for an +extended period, use the following commands: + +‘C-c C-x < (org-agenda-set-restriction-lock)’ + Permanently restrict the agenda to the current subtree. When with + a prefix argument, or with the cursor before the first headline in + a file, the agenda scope is set to the entire file. This + restriction remains in effect until removed with ‘C-c C-x >’, or by + typing either ‘<’ or ‘>’ in the agenda dispatcher. If there is a + window displaying an agenda view, the new restriction takes effect + immediately. +‘C-c C-x > (org-agenda-remove-restriction-lock)’ + Remove the permanent restriction created by ‘C-c C-x <’. + +When working with ‘speedbar.el’, you can use the following commands in +the Speedbar frame: + +‘< in the speedbar frame (org-speedbar-set-agenda-restriction)’ + Permanently restrict the agenda to the item—either an Org file or a + subtree in such a file—at the cursor in the Speedbar frame. If + there is a window displaying an agenda view, the new restriction + takes effect immediately. +‘> in the speedbar frame (org-agenda-remove-restriction-lock)’ + Lift the restriction. + + ---------- Footnotes ---------- + + (1) If the value of that variable is not a list, but a single file +name, then the list of agenda files will be maintained in that external +file. + + (2) When using the dispatcher, pressing ‘<’ before selecting a +command will actually limit the command to the current file, and ignore +‘org-agenda-files’ until the next dispatcher command. + + +File: org, Node: Agenda dispatcher, Next: Built-in agenda views, Prev: Agenda files, Up: Agenda views + +10.2 The agenda dispatcher +========================== + +The views are created through a dispatcher, which should be bound to a +global key—for example ‘C-c a’ (*note Activation::). In the following +we will assume that ‘C-c a’ is indeed how the dispatcher is accessed and +list keyboard access to commands accordingly. After pressing ‘C-c a’, +an additional letter is required to execute a command. The dispatcher +offers the following default commands: + +‘a’ + Create the calendar-like agenda (*note Weekly/daily agenda::). +‘t / T’ + Create a list of all TODO items (*note Global TODO list::). +‘m / M’ + Create a list of headlines matching a TAGS expression (*note + Matching tags and properties::). +‘s’ + Create a list of entries selected by a boolean expression of + keywords and/or regular expressions that must or must not occur in + the entry. +‘/’ + Search for a regular expression in all agenda files and + additionally in the files listed in + ‘org-agenda-text-search-extra-files’. This uses the Emacs command + ‘multi-occur’. A prefix argument can be used to specify the number + of context lines for each match, default is 1. +‘# / !’ + Create a list of stuck projects (*note Stuck projects::). +‘<’ + Restrict an agenda command to the current buffer(1). After + pressing ‘<’, you still need to press the character selecting the + command. +‘< <’ + If there is an active region, restrict the following agenda command + to the region. Otherwise, restrict it to the current subtree(2). + After pressing ‘< <’, you still need to press the character + selecting the command. + +‘*’ + Toggle sticky agenda views. By default, Org maintains only a + single agenda buffer and rebuilds it each time you change the view, + to make sure everything is always up to date. If you often switch + between agenda views and the build time bothers you, you can turn + on sticky agenda buffers or make this the default by customizing + the variable ‘org-agenda-sticky’. With sticky agendas, the agenda + dispatcher will not recreate agenda views from scratch, it will + only switch to the selected one, and you need to update the agenda + by hand with ‘r’ or ‘g’ when needed. You can toggle sticky agenda + view any time with ‘org-toggle-sticky-agenda’. + + You can also define custom commands that will be accessible through +the dispatcher, just like the default commands. This includes the +possibility to create extended agenda buffers that contain several +blocks together, for example the weekly agenda, the global TODO list and +a number of special tags matches. *Note Custom agenda views::. + + ---------- Footnotes ---------- + + (1) For backward compatibility, you can also press ‘1’ to restrict to +the current buffer. + + (2) For backward compatibility, you can also press ‘0’ to restrict to +the current region/subtree. + + +File: org, Node: Built-in agenda views, Next: Presentation and sorting, Prev: Agenda dispatcher, Up: Agenda views + +10.3 The built-in agenda views +============================== + +In this section we describe the built-in views. + +* Menu: + +* Weekly/daily agenda:: The calendar page with current tasks +* Global TODO list:: All unfinished action items +* Matching tags and properties:: Structured information with fine-tuned search +* Search view:: Find entries by searching for text +* Stuck projects:: Find projects you need to review + + +File: org, Node: Weekly/daily agenda, Next: Global TODO list, Up: Built-in agenda views + +10.3.1 The weekly/daily agenda +------------------------------ + +The purpose of the weekly/daily _agenda_ is to act like a page of a +paper agenda, showing all the tasks for the current week or day. + +‘C-c a a (org-agenda-list)’ + Compile an agenda for the current week from a list of Org files. + The agenda shows the entries for each day. With a numeric + prefix(1) (like ‘C-u 2 1 C-c a a’) you may set the number of days + to be displayed. + + The default number of days displayed in the agenda is set by the +variable ‘org-agenda-span’ (or the obsolete ‘org-agenda-ndays’). This +variable can be set to any number of days you want to see by default in +the agenda, or to a span name, such as ‘day’, ‘week’, ‘month’ or ‘year’. +For weekly agendas, the default is to start on the previous monday (see +‘org-agenda-start-on-weekday’). You can also set the start date using a +date shift: ‘(setq org-agenda-start-day "+10d")’ will start the agenda +ten days from today in the future. + + Remote editing from the agenda buffer means, for example, that you +can change the dates of deadlines and appointments from the agenda +buffer. The commands available in the Agenda buffer are listed in *note +Agenda commands::. + +Calendar/Diary integration +.......................... + +Emacs contains the calendar and diary by Edward M. Reingold. The +calendar displays a three-month calendar with holidays from different +countries and cultures. The diary allows you to keep track of +anniversaries, lunar phases, sunrise/set, recurrent appointments +(weekly, monthly) and more. In this way, it is quite complementary to +Org. It can be very useful to combine output from Org with the diary. + + In order to include entries from the Emacs diary into Org mode’s +agenda, you only need to customize the variable + + (setq org-agenda-include-diary t) + +After that, everything will happen automatically. All diary entries +including holidays, anniversaries, etc., will be included in the agenda +buffer created by Org mode. , , and can be used from +the agenda buffer to jump to the diary file in order to edit existing +diary entries. The ‘i’ command to insert new entries for the current +date works in the agenda buffer, as well as the commands ‘S’, ‘M’, and +‘C’ to display Sunrise/Sunset times, show lunar phases and to convert to +other calendars, respectively. ‘c’ can be used to switch back and forth +between calendar and agenda. + + If you are using the diary only for sexp entries and holidays, it is +faster to not use the above setting, but instead to copy or even move +the entries into an Org file. Org mode evaluates diary-style sexp +entries, and does it faster because there is no overhead for first +creating the diary display. Note that the sexp entries must start at +the left margin, no whitespace is allowed before them. For example, the +following segment of an Org file will be processed and entries will be +made in the agenda: + + * Holidays + :PROPERTIES: + :CATEGORY: Holiday + :END: + %%(org-calendar-holiday) ; special function for holiday names + + * Birthdays + :PROPERTIES: + :CATEGORY: Ann + :END: + %%(org-anniversary 1956 5 14)(2) Arthur Dent is %d years old + %%(org-anniversary 1869 10 2) Mahatma Gandhi would be %d years old + +Anniversaries from BBDB +....................... + +If you are using the Big Brothers Database to store your contacts, you +will very likely prefer to store anniversaries in BBDB rather than in a +separate Org or diary file. Org supports this and will show BBDB +anniversaries as part of the agenda. All you need to do is to add the +following to one of your agenda files: + + * Anniversaries + :PROPERTIES: + :CATEGORY: Anniv + :END: + %%(org-bbdb-anniversaries) + + You can then go ahead and define anniversaries for a BBDB record. +Basically, you need to press ‘C-o anniversary ’ with the cursor in +a BBDB record and then add the date in the format ‘YYYY-MM-DD’ or +‘MM-DD’, followed by a space and the class of the anniversary +(‘birthday’ or ‘wedding’, or a format string). If you omit the class, +it will default to ‘birthday’. Here are a few examples, the header for +the file ‘org-bbdb.el’ contains more detailed information. + + 1973-06-22 + 06-22 + 1955-08-02 wedding + 2008-04-14 %s released version 6.01 of org mode, %d years ago + + After a change to BBDB, or for the first agenda display during an +Emacs session, the agenda display will suffer a short delay as Org +updates its hash with anniversaries. However, from then on things will +be very fast—much faster in fact than a long list of +‘%%(diary-anniversary)’ entries in an Org or Diary file. + + If you would like to see upcoming anniversaries with a bit of +forewarning, you can use the following instead: + + * Anniversaries + :PROPERTIES: + :CATEGORY: Anniv + :END: + %%(org-bbdb-anniversaries-future 3) + + That will give you three days’ warning: on the anniversary date +itself and the two days prior. The argument is optional: if omitted, it +defaults to 7. + +Appointment reminders +..................... + +Org can interact with Emacs appointments notification facility. To add +the appointments of your agenda files, use the command +‘org-agenda-to-appt’. This command lets you filter through the list of +your appointments and add only those belonging to a specific category or +matching a regular expression. It also reads a ‘APPT_WARNTIME’ property +which will then override the value of ‘appt-message-warning-time’ for +this appointment. See the docstring for details. + + ---------- Footnotes ---------- + + (1) For backward compatibility, the universal prefix ‘C-u’ causes all +TODO entries to be listed before the agenda. This feature is +deprecated, use the dedicated TODO list, or a block agenda instead +(*note Block agenda::). + + (2) ‘org-anniversary’ is just like ‘diary-anniversary’, but the +argument order is always according to ISO and therefore independent of +the value of ‘calendar-date-style’. + + +File: org, Node: Global TODO list, Next: Matching tags and properties, Prev: Weekly/daily agenda, Up: Built-in agenda views + +10.3.2 The global TODO list +--------------------------- + +The global TODO list contains all unfinished TODO items formatted and +collected into a single place. + +‘C-c a t (org-todo-list)’ + Show the global TODO list. This collects the TODO items from all + agenda files (*note Agenda views::) into a single buffer. By + default, this lists items with a state the is not a DONE state. + The buffer is in ‘agenda-mode’, so there are commands to examine + and manipulate the TODO entries directly from that buffer (*note + Agenda commands::). +‘C-c a T (org-todo-list)’ + Like the above, but allows selection of a specific TODO keyword. + You can also do this by specifying a prefix argument to ‘C-c a t’. + You are prompted for a keyword, and you may also specify several + keywords by separating them with ‘|’ as the boolean OR operator. + With a numeric prefix, the Nth keyword in ‘org-todo-keywords’ is + selected. The ‘r’ key in the agenda buffer regenerates it, and you + can give a prefix argument to this command to change the selected + TODO keyword, for example ‘3 r’. If you often need a search for a + specific keyword, define a custom command for it (*note Agenda + dispatcher::). + Matching specific TODO keywords can also be done as part of a tags + search (*note Tag searches::). + + Remote editing of TODO items means that you can change the state of a +TODO entry with a single key press. The commands available in the TODO +list are described in *note Agenda commands::. + + Normally the global TODO list simply shows all headlines with TODO +keywords. This list can become very long. There are two ways to keep +it more compact: + − Some people view a TODO item that has been _scheduled_ for + execution or have a _deadline_ (*note Timestamps::) as no longer + _open_. Configure the variables + ‘org-agenda-todo-ignore-scheduled’, + ‘org-agenda-todo-ignore-deadlines’, + ‘org-agenda-todo-ignore-timestamp’ and/or + ‘org-agenda-todo-ignore-with-date’ to exclude such items from the + global TODO list. + − TODO items may have sublevels to break up the task into subtasks. + In such cases it may be enough to list only the highest level TODO + headline and omit the sublevels from the global list. Configure + the variable ‘org-agenda-todo-list-sublevels’ to get this behavior. + + +File: org, Node: Matching tags and properties, Next: Search view, Prev: Global TODO list, Up: Built-in agenda views + +10.3.3 Matching tags and properties +----------------------------------- + +If headlines in the agenda files are marked with _tags_ (*note Tags::), +or have properties (*note Properties and columns::), you can select +headlines based on this metadata and collect them into an agenda buffer. +The match syntax described here also applies when creating sparse trees +with ‘C-c / m’. + +‘C-c a m (org-tags-view)’ + Produce a list of all headlines that match a given set of tags. + The command prompts for a selection criterion, which is a boolean + logic expression with tags, like ‘+work+urgent-withboss’ or + ‘work|home’ (*note Tags::). If you often need a specific search, + define a custom command for it (*note Agenda dispatcher::). +‘C-c a M (org-tags-view)’ + Like ‘C-c a m’, but only select headlines that are also TODO items + in a not-DONE state and force checking subitems (see variable + ‘org-tags-match-list-sublevels’). To exclude scheduled/deadline + items, see the variable + ‘org-agenda-tags-todo-honor-ignore-options’. Matching specific + TODO keywords together with a tags match is also possible, see + *note Tag searches::. + + The commands available in the tags list are described in *note Agenda +commands::. + +Match syntax +............ + +A search string can use Boolean operators ‘&’ for ‘AND’ and ‘|’ for +‘OR’. ‘&’ binds more strongly than ‘|’. Parentheses are not +implemented. Each element in the search is either a tag, a regular +expression matching tags, or an expression like ‘PROPERTY OPERATOR +VALUE’ with a comparison operator, accessing a property value. Each +element may be preceded by ‘-’, to select against it, and ‘+’ is +syntactic sugar for positive selection. The ‘AND’ operator ‘&’ is +optional when ‘+’ or ‘-’ is present. Here are some examples, using only +tags. + +‘work’ + Select headlines tagged ‘:work:’. +‘work&boss’ + Select headlines tagged ‘:work:’ and ‘:boss:’. +‘+work-boss’ + Select headlines tagged ‘:work:’, but discard those also tagged + ‘:boss:’. +‘work|laptop’ + Selects lines tagged ‘:work:’ or ‘:laptop:’. +‘work|laptop+night’ + Like before, but require the ‘:laptop:’ lines to be tagged also + ‘:night:’. + + Instead of a tag, you may also specify a regular expression enclosed +in curly braces. For example, ‘work+{^boss.*}’ matches headlines that +contain the tag ‘:work:’ and any tag starting with ‘boss’. + + Group tags (*note Tag hierarchy::) are expanded as regular +expressions. E.g., if ‘:work:’ is a group tag for the group +‘:work:lab:conf:’, then searching for ‘work’ will search for +‘{\(?:work\|lab\|conf\)}’ and searching for ‘-work’ will search for all +headlines but those with one of the tags in the group (i.e., +‘-{\(?:work\|lab\|conf\)}’). + + You may also test for properties (*note Properties and columns::) at +the same time as matching tags. The properties may be real properties, +or special properties that represent other metadata (*note Special +properties::). For example, the “property” ‘TODO’ represents the TODO +keyword of the entry and the “property” ‘PRIORITY’ represents the +PRIORITY keyword of the entry. + + In addition to the properties mentioned above, ‘LEVEL’ represents the +level of an entry. So a search ‘+LEVEL=3+boss-TODO="DONE"’ lists all +level three headlines that have the tag ‘boss’ and are _not_ marked with +the TODO keyword DONE. In buffers with ‘org-odd-levels-only’ set, +‘LEVEL’ does not count the number of stars, but ‘LEVEL=2’ will +correspond to 3 stars etc. + + Here are more examples: + +‘work+TODO="WAITING"’ + Select ‘:work:’-tagged TODO lines with the specific TODO keyword + ‘WAITING’. +‘work+TODO="WAITING"|home+TODO="WAITING"’ + Waiting tasks both at work and at home. + + When matching properties, a number of different operators can be used +to test the value of a property. Here is a complex example: + + +work-boss+PRIORITY="A"+Coffee="unlimited"+Effort<2 \ + +With={Sarah\|Denny}+SCHEDULED>="<2008-10-11>" + +The type of comparison will depend on how the comparison value is +written: + − If the comparison value is a plain number, a numerical comparison + is done, and the allowed operators are ‘<’, ‘=’, ‘>’, ‘<=’, ‘>=’, + and ‘<>’. + − If the comparison value is enclosed in double-quotes, a string + comparison is done, and the same operators are allowed. + − If the comparison value is enclosed in double-quotes _and_ angular + brackets (like ‘DEADLINE<="<2008-12-24 18:30>"’), both values are + assumed to be date/time specifications in the standard Org way, and + the comparison will be done accordingly. Special values that will + be recognized are ‘""’ for now (including time), and + ‘""’, and ‘""’ for these days at 00:00 hours, + i.e., without a time specification. Also strings like ‘"<+5d>"’ or + ‘"<-2m>"’ with units ‘d’, ‘w’, ‘m’, and ‘y’ for day, week, month, + and year, respectively, can be used. + − If the comparison value is enclosed in curly braces, a regexp match + is performed, with ‘=’ meaning that the regexp matches the property + value, and ‘<>’ meaning that it does not match. + + So the search string in the example finds entries tagged ‘:work:’ but +not ‘:boss:’, which also have a priority value ‘A’, a ‘:Coffee:’ +property with the value ‘unlimited’, an ‘Effort’ property that is +numerically smaller than 2, a ‘:With:’ property that is matched by the +regular expression ‘Sarah\|Denny’, and that are scheduled on or after +October 11, 2008. + + You can configure Org mode to use property inheritance during a +search, but beware that this can slow down searches considerably. See +*note Property inheritance::, for details. + + For backward compatibility, and also for typing speed, there is also +a different way to test TODO states in a search. For this, terminate +the tags/property part of the search string (which may include several +terms connected with ‘|’) with a ‘/’ and then specify a Boolean +expression just for TODO keywords. The syntax is then similar to that +for tags, but should be applied with care: for example, a positive +selection on several TODO keywords cannot meaningfully be combined with +boolean AND. However, _negative selection_ combined with AND can be +meaningful. To make sure that only lines are checked that actually have +any TODO keyword (resulting in a speed-up), use ‘C-c a M’, or +equivalently start the TODO part after the slash with ‘!’. Using ‘C-c a +M’ or ‘/!’ will not match TODO keywords in a DONE state. Examples: + +‘work/WAITING’ + Same as ‘work+TODO="WAITING"’ +‘work/!-WAITING-NEXT’ + Select ‘:work:’-tagged TODO lines that are neither ‘WAITING’ nor + ‘NEXT’ +‘work/!+WAITING|+NEXT’ + Select ‘:work:’-tagged TODO lines that are either ‘WAITING’ or + ‘NEXT’. + + +File: org, Node: Search view, Next: Stuck projects, Prev: Matching tags and properties, Up: Built-in agenda views + +10.3.4 Search view +------------------ + +This agenda view is a general text search facility for Org mode entries. +It is particularly useful to find notes. + +‘C-c a s (org-search-view)’ + This is a special search that lets you select entries by matching a + substring or specific words using a boolean logic. + For example, the search string ‘computer equipment’ will find entries +that contain ‘computer equipment’ as a substring. If the two words are +separated by more space or a line break, the search will still match. +Search view can also search for specific keywords in the entry, using +Boolean logic. The search string ‘+computer +wifi -ethernet +-{8\.11[bg]}’ will search for note entries that contain the keywords +‘computer’ and ‘wifi’, but not the keyword ‘ethernet’, and which are +also not matched by the regular expression ‘8\.11[bg]’, meaning to +exclude both 8.11b and 8.11g. The first ‘+’ is necessary to turn on +word search, other ‘+’ characters are optional. For more details, see +the docstring of the command ‘org-search-view’. + + Note that in addition to the agenda files, this command will also +search the files listed in ‘org-agenda-text-search-extra-files’. + + +File: org, Node: Stuck projects, Prev: Search view, Up: Built-in agenda views + +10.3.5 Stuck projects +--------------------- + +If you are following a system like David Allen’s GTD to organize your +work, one of the “duties” you have is a regular review to make sure that +all projects move along. A _stuck_ project is a project that has no +defined next actions, so it will never show up in the TODO lists Org +mode produces. During the review, you need to identify such projects +and define next actions for them. + +‘C-c a # (org-agenda-list-stuck-projects)’ + List projects that are stuck. +‘C-c a !’ + Customize the variable ‘org-stuck-projects’ to define what a stuck + project is and how to find it. + + You almost certainly will have to configure this view before it will +work for you. The built-in default assumes that all your projects are +level-2 headlines, and that a project is not stuck if it has at least +one entry marked with a TODO keyword TODO or NEXT or NEXTACTION. + + Let’s assume that you, in your own way of using Org mode, identify +projects with a tag PROJECT, and that you use a TODO keyword MAYBE to +indicate a project that should not be considered yet. Let’s further +assume that the TODO keyword DONE marks finished projects, and that NEXT +and TODO indicate next actions. The tag @SHOP indicates shopping and is +a next action even without the NEXT tag. Finally, if the project +contains the special word IGNORE anywhere, it should not be listed +either. In this case you would start by identifying eligible projects +with a tags/todo match(1) ‘+PROJECT/-MAYBE-DONE’, and then check for +TODO, NEXT, @SHOP, and IGNORE in the subtree to identify projects that +are not stuck. The correct customization for this is + + (setq org-stuck-projects + '("+PROJECT/-MAYBE-DONE" ("NEXT" "TODO") ("@SHOP") + "\\")) + + Note that if a project is identified as non-stuck, the subtree of +this entry will still be searched for stuck projects. + + ---------- Footnotes ---------- + + (1) *Note Tag searches::. + + +File: org, Node: Presentation and sorting, Next: Agenda commands, Prev: Built-in agenda views, Up: Agenda views + +10.4 Presentation and sorting +============================= + +Before displaying items in an agenda view, Org mode visually prepares +the items and sorts them. Each item occupies a single line. The line +starts with a _prefix_ that contains the _category_ (*note Categories::) +of the item and other important information. You can customize in which +column tags will be displayed through ‘org-agenda-tags-column’. You can +also customize the prefix using the option ‘org-agenda-prefix-format’. +This prefix is followed by a cleaned-up version of the outline headline +associated with the item. + +* Menu: + +* Categories:: Not all tasks are equal +* Time-of-day specifications:: How the agenda knows the time +* Sorting agenda items:: The order of things +* Filtering/limiting agenda items:: Dynamically narrow the agenda + + +File: org, Node: Categories, Next: Time-of-day specifications, Up: Presentation and sorting + +10.4.1 Categories +----------------- + +The category is a broad label assigned to each agenda item. By default, +the category is simply derived from the file name, but you can also +specify it with a special line in the buffer, like this: + + #+CATEGORY: Thesis + +If you would like to have a special ‘CATEGORY’ for a single entry or a +(sub)tree, give the entry a ‘:CATEGORY:’ property with the special +category you want to apply as the value. + +The display in the agenda buffer looks best if the category is not +longer than 10 characters. + +You can set up icons for category by customizing the +‘org-agenda-category-icon-alist’ variable. + + +File: org, Node: Time-of-day specifications, Next: Sorting agenda items, Prev: Categories, Up: Presentation and sorting + +10.4.2 Time-of-day specifications +--------------------------------- + +Org mode checks each agenda item for a time-of-day specification. The +time can be part of the timestamp that triggered inclusion into the +agenda, for example as in ‘<2005-05-10 Tue 19:00>’. Time ranges can be +specified with two timestamps, like +‘<2005-05-10 Tue 20:30>--<2005-05-10 Tue 22:15>’. + + In the headline of the entry itself, a time(range) may also appear as +plain text (like ‘12:45’ or a ‘8:30-1pm’)(1). + + If the agenda integrates the Emacs diary (*note Weekly/daily +agenda::), time specifications in diary entries are recognized as well. + + For agenda display, Org mode extracts the time and displays it in a +standard 24 hour format as part of the prefix. The example times in the +previous paragraphs would end up in the agenda like this: + + 8:30-13:00 Arthur Dent lies in front of the bulldozer + 12:45...... Ford Prefect arrives and takes Arthur to the pub + 19:00...... The Vogon reads his poem + 20:30-22:15 Marvin escorts the Hitchhikers to the bridge + + If the agenda is in single-day mode, or for the display of today, the +timed entries are embedded in a time grid, like + + 8:00...... ------------------ + 8:30-13:00 Arthur Dent lies in front of the bulldozer + 10:00...... ------------------ + 12:00...... ------------------ + 12:45...... Ford Prefect arrives and takes Arthur to the pub + 14:00...... ------------------ + 16:00...... ------------------ + 18:00...... ------------------ + 19:00...... The Vogon reads his poem + 20:00...... ------------------ + 20:30-22:15 Marvin escorts the Hitchhikers to the bridge + + The time grid can be turned on and off with the variable +‘org-agenda-use-time-grid’, and can be configured with +‘org-agenda-time-grid’. + + ---------- Footnotes ---------- + + (1) You can, however, disable this by setting +‘org-agenda-search-headline-for-time’ variable to a ‘nil’ value. + + +File: org, Node: Sorting agenda items, Next: Filtering/limiting agenda items, Prev: Time-of-day specifications, Up: Presentation and sorting + +10.4.3 Sorting agenda items +--------------------------- + +Before being inserted into a view, the items are sorted. How this is +done depends on the type of view. + • For the daily/weekly agenda, the items for each day are sorted. + The default order is to first collect all items containing an + explicit time-of-day specification. These entries will be shown at + the beginning of the list, as a _schedule_ for the day. After + that, items remain grouped in categories, in the sequence given by + ‘org-agenda-files’. Within each category, items are sorted by + priority (*note Priorities::), which is composed of the base + priority (2000 for priority ‘A’, 1000 for ‘B’, and 0 for ‘C’), plus + additional increments for overdue scheduled or deadline items. + • For the TODO list, items remain in the order of categories, but + within each category, sorting takes place according to priority + (*note Priorities::). The priority used for sorting derives from + the priority cookie, with additions depending on how close an item + is to its due or scheduled date. + • For tags matches, items are not sorted at all, but just appear in + the sequence in which they are found in the agenda files. + + Sorting can be customized using the variable +‘org-agenda-sorting-strategy’, and may also include criteria based on +the estimated effort of an entry (*note Effort estimates::). + + +File: org, Node: Filtering/limiting agenda items, Prev: Sorting agenda items, Up: Presentation and sorting + +10.4.4 Filtering/limiting agenda items +-------------------------------------- + +Agenda built-in or customized commands are statically defined. Agenda +filters and limits provide two ways of dynamically narrowing down the +list of agenda entries: _filters_ and _limits_. Filters only act on the +display of the items, while limits take effect before the list of agenda +entries is built. Filters are more often used interactively, while +limits are mostly useful when defined as local variables within custom +agenda commands. + +Filtering in the agenda +....................... + +‘/ (org-agenda-filter-by-tag)’ + Filter the agenda view with respect to a tag and/or effort + estimates. The difference between this and a custom agenda command + is that filtering is very fast, so that you can switch quickly + between different filters without having to recreate the agenda.(1) + + You will be prompted for a tag selection letter; will mean + any tag at all. Pressing at that prompt will offer use + completion to select a tag (including any tags that do not have a + selection character). The command then hides all entries that do + not contain or inherit this tag. When called with prefix arg, + remove the entries that _do_ have the tag. A second ‘/’ at the + prompt will turn off the filter and unhide any hidden entries. + Pressing ‘+’ or ‘-’ switches between filtering and excluding the + next tag. + + Org also supports automatic, context-aware tag filtering. If the + variable ‘org-agenda-auto-exclude-function’ is set to a + user-defined function, that function can decide which tags should + be excluded from the agenda automatically. Once this is set, the + ‘/’ command then accepts ‘’ as a sub-option key and runs the + auto exclusion logic. For example, let’s say you use a ‘Net’ tag + to identify tasks which need network access, an ‘Errand’ tag for + errands in town, and a ‘Call’ tag for making phone calls. You + could auto-exclude these tags based on the availability of the + Internet, and outside of business hours, with something like this: + + (defun org-my-auto-exclude-function (tag) + (and (cond + ((string= tag "Net") + (/= 0 (call-process "/sbin/ping" nil nil nil + "-c1" "-q" "-t1" "mail.gnu.org"))) + ((or (string= tag "Errand") (string= tag "Call")) + (let ((hour (nth 2 (decode-time)))) + (or (< hour 8) (> hour 21))))) + (concat "-" tag))) + + (setq org-agenda-auto-exclude-function 'org-my-auto-exclude-function) + +‘[ ] { }’ + in search view + add new search words (‘[’ and ‘]’) or new regular expressions + (‘{’ and ‘}’) to the query string. The opening bracket/brace + will add a positive search term prefixed by ‘+’, indicating + that this search term must occur/match in the entry. The + closing bracket/brace will add a negative search term which + must not occur/match in the entry for it to be selected. + +‘< (org-agenda-filter-by-category)’ + + Filter the current agenda view with respect to the category of the + item at point. Pressing ‘<’ another time will remove this filter. + When called with a prefix argument exclude the category of the item + at point from the agenda. + + You can add a filter preset in custom agenda commands through the + option ‘org-agenda-category-filter-preset’. *Note Setting + options::. + +‘^ (org-agenda-filter-by-top-headline)’ + Filter the current agenda view and only display the siblings and + the parent headline of the one at point. + +‘= (org-agenda-filter-by-regexp)’ + + Filter the agenda view by a regular expression: only show agenda + entries matching the regular expression the user entered. When + called with a prefix argument, it will filter _out_ entries + matching the regexp. With two universal prefix arguments, it will + remove all the regexp filters, which can be accumulated. + + You can add a filter preset in custom agenda commands through the + option ‘org-agenda-regexp-filter-preset’. *Note Setting options::. + +‘_ (org-agenda-filter-by-effort)’ + Filter the agenda view with respect to effort estimates. You first + need to set up allowed efforts globally, for example + (setq org-global-properties + '(("Effort_ALL". "0 0:10 0:30 1:00 2:00 3:00 4:00"))) + You can then filter for an effort by first typing an operator, one + of ‘<’, ‘>’, and ‘=’, and then the one-digit index of an effort + estimate in your array of allowed values, where ‘0’ means the 10th + value. The filter will then restrict to entries with effort + smaller-or-equal, equal, or larger-or-equal than the selected + value. For application of the operator, entries without a defined + effort will be treated according to the value of + ‘org-sort-agenda-noeffort-is-high’. + + When called with a prefix argument, it will remove entries matching + the condition. With two universal prefix arguments, it will clear + effort filters, which can be accumulated. + + You can add a filter preset in custom agenda commands through the + option ‘org-agenda-effort-filter-preset’. *Note Setting options::. + +‘| (org-agenda-filter-remove-all)’ + Remove all filters in the current agenda view. + +Setting limits for the agenda +............................. + +Here is a list of options that you can set, either globally, or locally +in your custom agenda views (*note Custom agenda views::). + +‘org-agenda-max-entries’ + Limit the number of entries. +‘org-agenda-max-effort’ + Limit the duration of accumulated efforts (as minutes). +‘org-agenda-max-todos’ + Limit the number of entries with TODO keywords. +‘org-agenda-max-tags’ + Limit the number of tagged entries. + + When set to a positive integer, each option will exclude entries from +other categories: for example, ‘(setq org-agenda-max-effort 100)’ will +limit the agenda to 100 minutes of effort and exclude any entry that has +no effort property. If you want to include entries with no effort +property, use a negative value for ‘org-agenda-max-effort’. + + One useful setup is to use ‘org-agenda-max-entries’ locally in a +custom command. For example, this custom command will display the next +five entries with a ‘NEXT’ TODO keyword. + + (setq org-agenda-custom-commands + '(("n" todo "NEXT" + ((org-agenda-max-entries 5))))) + + Once you mark one of these five entry as ‘DONE’, rebuilding the +agenda will again the next five entries again, including the first entry +that was excluded so far. + + You can also dynamically set temporary limits, which will be lost +when rebuilding the agenda: + +‘~ (org-agenda-limit-interactively)’ + This prompts for the type of limit to apply and its value. + + ---------- Footnotes ---------- + + (1) Custom commands can preset a filter by binding the variable +‘org-agenda-tag-filter-preset’ as an option. This filter will then be +applied to the view and persist as a basic filter through refreshes and +more secondary filtering. The filter is a global property of the entire +agenda view—in a block agenda, you should only set this in the global +options section, not in the section of an individual block. + + +File: org, Node: Agenda commands, Next: Custom agenda views, Prev: Presentation and sorting, Up: Agenda views + +10.5 Commands in the agenda buffer +================================== + +Entries in the agenda buffer are linked back to the Org file or diary +file where they originate. You are not allowed to edit the agenda +buffer itself, but commands are provided to show and jump to the +original entry location, and to edit the Org files “remotely” from the +agenda buffer. In this way, all information is stored only once, +removing the risk that your agenda and note files may diverge. + + Some commands can be executed with mouse clicks on agenda lines. For +the other commands, the cursor needs to be in the desired line. + + Motion + ...... + +‘n (org-agenda-next-line)’ + Next line (same as and ‘C-n’). +‘p (org-agenda-previous-line)’ + Previous line (same as and ‘C-p’). +‘N (org-agenda-next-item)’ + Next item: same as next line, but only consider items. +‘P (org-agenda-previous-item)’ + Previous item: same as previous line, but only consider items. + + View/Go to Org file + ................... + +‘ or mouse-3 (org-agenda-show-and-scroll-up)’ + Display the original location of the item in another window. With + prefix arg, make sure that drawers stay folded. +‘L (org-agenda-recenter)’ + Display original location and recenter that window. +‘ or mouse-2 (org-agenda-goto)’ + Go to the original location of the item in another window. +‘ (org-agenda-switch-to)’ + Go to the original location of the item and delete other windows. +‘F (org-agenda-follow-mode)’ + Toggle Follow mode. In Follow mode, as you move the cursor through + the agenda buffer, the other window always shows the corresponding + location in the Org file. The initial setting for this mode in new + agenda buffers can be set with the variable + ‘org-agenda-start-with-follow-mode’. +‘C-c C-x b (org-agenda-tree-to-indirect-buffer)’ + Display the entire subtree of the current item in an indirect + buffer. With a numeric prefix argument N, go up to level N and + then take that tree. If N is negative, go up that many levels. + With a ‘C-u’ prefix, do not remove the previously used indirect + buffer. + +‘C-c C-o (org-agenda-open-link)’ + Follow a link in the entry. This will offer a selection of any + links in the text belonging to the referenced Org node. If there + is only one link, it will be followed without a selection prompt. + + Change display + .............. + +‘A’ + Interactively select another agenda view and append it to the + current view. +‘o’ + Delete other windows. +‘v d or short d (org-agenda-day-view)’ +‘v w or short w (org-agenda-week-view)’ +‘v t (org-agenda-fortnight-view)’ +‘v m (org-agenda-month-view)’ +‘v y (org-agenda-year-view)’ +‘v (org-agenda-reset-view)’ + Switch to day/week/month/year view. When switching to day or week + view, this setting becomes the default for subsequent agenda + refreshes. Since month and year views are slow to create, they do + not become the default. A numeric prefix argument may be used to + jump directly to a specific day of the year, ISO week, month, or + year, respectively. For example, ‘32 d’ jumps to February 1st, ‘9 + w’ to ISO week number 9. When setting day, week, or month view, a + year may be encoded in the prefix argument as well. For example, + ‘200712 w’ will jump to week 12 in 2007. If such a year + specification has only one or two digits, it will be mapped to the + interval 1938–2037. ‘v ’ will reset to what is set in + ‘org-agenda-span’. +‘f (org-agenda-later)’ + Go forward in time to display the following + ‘org-agenda-current-span’ days. For example, if the display covers + a week, switch to the following week. With prefix arg, go forward + that many times ‘org-agenda-current-span’ days. +‘b (org-agenda-earlier)’ + Go backward in time to display earlier dates. +‘. (org-agenda-goto-today)’ + Go to today. +‘j (org-agenda-goto-date)’ + Prompt for a date and go there. +‘J (org-agenda-clock-goto)’ + Go to the currently clocked-in task in the agenda buffer. +‘D (org-agenda-toggle-diary)’ + Toggle the inclusion of diary entries. See *note Weekly/daily + agenda::. +‘v l or short l (org-agenda-log-mode)’ + Toggle Logbook mode. In Logbook mode, entries that were marked + DONE while logging was on (variable ‘org-log-done’) are shown in + the agenda, as are entries that have been clocked on that day. You + can configure the entry types that should be included in log mode + using the variable ‘org-agenda-log-mode-items’. When called with a + ‘C-u’ prefix, show all possible logbook entries, including state + changes. When called with two prefix arguments ‘C-u C-u’, show + only logging information, nothing else. ‘v L’ is equivalent to + ‘C-u v l’. +‘v [ or short [ (org-agenda-manipulate-query-add)’ + Include inactive timestamps into the current view. Only for + weekly/daily agenda. +‘v a (org-agenda-archives-mode)’ +‘v A (org-agenda-archives-mode 'files)’ + Toggle Archives mode. In Archives mode, trees that are marked + ‘ARCHIVED’ are also scanned when producing the agenda. When you + use the capital ‘A’, even all archive files are included. To exit + archives mode, press ‘v a’ again. +‘v R or short R (org-agenda-clockreport-mode)’ + Toggle Clockreport mode. In Clockreport mode, the daily/weekly + agenda will always show a table with the clocked times for the time + span and file scope covered by the current agenda view. The + initial setting for this mode in new agenda buffers can be set with + the variable ‘org-agenda-start-with-clockreport-mode’. By using a + prefix argument when toggling this mode (i.e., ‘C-u R’), the clock + table will not show contributions from entries that are hidden by + agenda filtering(1). See also the variable + ‘org-clock-report-include-clocking-task’. +‘v c’ + Show overlapping clock entries, clocking gaps, and other clocking + problems in the current agenda range. You can then visit clocking + lines and fix them manually. See the variable + ‘org-agenda-clock-consistency-checks’ for information on how to + customize the definition of what constituted a clocking problem. + To return to normal agenda display, press ‘l’ to exit Logbook mode. +‘v E or short E (org-agenda-entry-text-mode)’ + Toggle entry text mode. In entry text mode, a number of lines from + the Org outline node referenced by an agenda line will be displayed + below the line. The maximum number of lines is given by the + variable ‘org-agenda-entry-text-maxlines’. Calling this command + with a numeric prefix argument will temporarily modify that number + to the prefix value. +‘G (org-agenda-toggle-time-grid)’ + Toggle the time grid on and off. See also the variables + ‘org-agenda-use-time-grid’ and ‘org-agenda-time-grid’. +‘r (org-agenda-redo)’ + Recreate the agenda buffer, for example to reflect the changes + after modification of the timestamps of items with ‘S-’ and + ‘S-’. When the buffer is the global TODO list, a prefix + argument is interpreted to create a selective list for a specific + TODO keyword. +‘g (org-agenda-redo)’ + Same as ‘r’. +‘C-x C-s or short s (org-save-all-org-buffers)’ + Save all Org buffers in the current Emacs session, and also the + locations of IDs. +‘C-c C-x C-c (org-agenda-columns)’ + Invoke column view (*note Column view::) in the agenda buffer. The + column view format is taken from the entry at point, or (if there + is no entry at point), from the first entry in the agenda view. So + whatever the format for that entry would be in the original buffer + (taken from a property, from a ‘#+COLUMNS’ line, or from the + default variable ‘org-columns-default-format’), will be used in the + agenda. + +‘C-c C-x > (org-agenda-remove-restriction-lock)’ + Remove the restriction lock on the agenda, if it is currently + restricted to a file or subtree (*note Agenda files::). + + Secondary filtering and query editing + ..................................... + + For a detailed description of these commands, *note + Filtering/limiting agenda items::. + +‘/ (org-agenda-filter-by-tag)’ + Filter the agenda view with respect to a tag and/or effort + estimates. + +‘< (org-agenda-filter-by-category)’ + Filter the current agenda view with respect to the category of the + item at point. + +‘^ (org-agenda-filter-by-top-headline)’ + Filter the current agenda view and only display the siblings and + the parent headline of the one at point. + +‘= (org-agenda-filter-by-regexp)’ + Filter the agenda view by a regular expression. + +‘_ (org-agenda-filter-by-effort)’ + Filter the agenda view with respect to effort estimates. + +‘| (org-agenda-filter-remove-all)’ + Remove all filters in the current agenda view. + + Remote editing + .............. + +‘0--9’ + Digit argument. +‘C-_ (org-agenda-undo)’ + Undo a change due to a remote editing command. The change is + undone both in the agenda buffer and in the remote buffer. +‘t (org-agenda-todo)’ + Change the TODO state of the item, both in the agenda and in the + original org file. +‘C-S- (org-agenda-todo-nextset)’ +‘C-S- (org-agenda-todo-previousset)’ + Switch to the next/previous set of TODO keywords. +‘C-k (org-agenda-kill)’ + Delete the current agenda item along with the entire subtree + belonging to it in the original Org file. If the text to be + deleted remotely is longer than one line, the kill needs to be + confirmed by the user. See variable ‘org-agenda-confirm-kill’. +‘C-c C-w (org-agenda-refile)’ + Refile the entry at point. +‘C-c C-x C-a or short a (org-agenda-archive-default-with-confirmation)’ + Archive the subtree corresponding to the entry at point using the + default archiving command set in ‘org-archive-default-command’. + When using the ‘a’ key, confirmation will be required. +‘C-c C-x a (org-agenda-toggle-archive-tag)’ + Toggle the ARCHIVE tag for the current headline. +‘C-c C-x A (org-agenda-archive-to-archive-sibling)’ + Move the subtree corresponding to the current entry to its _archive + sibling_. +‘C-c C-x C-s or short $ (org-agenda-archive)’ + Archive the subtree corresponding to the current headline. This + means the entry will be moved to the configured archive location, + most likely a different file. +‘T (org-agenda-show-tags)’ + Show all tags associated with the current item. This is useful if + you have turned off ‘org-agenda-show-inherited-tags’, but still + want to see all tags of a headline occasionally. +‘: (org-agenda-set-tags)’ + Set tags for the current headline. If there is an active region in + the agenda, change a tag for all headings in the region. +‘,’ + Set the priority for the current item (‘org-agenda-priority’). Org + mode prompts for the priority character. If you reply with , + the priority cookie is removed from the entry. +‘P (org-agenda-show-priority)’ + Display weighted priority of current item. +‘+ or S- (org-agenda-priority-up)’ + Increase the priority of the current item. The priority is changed + in the original buffer, but the agenda is not resorted. Use the + ‘r’ key for this. +‘- or S- (org-agenda-priority-down)’ + Decrease the priority of the current item. +‘z or C-c C-z (org-agenda-add-note)’ + Add a note to the entry. This note will be recorded, and then + filed to the same location where state change notes are put. + Depending on ‘org-log-into-drawer’, this may be inside a drawer. +‘C-c C-a (org-attach)’ + Dispatcher for all command related to attachments. +‘C-c C-s (org-agenda-schedule)’ + Schedule this item. With prefix arg remove the scheduling + timestamp +‘C-c C-d (org-agenda-deadline)’ + Set a deadline for this item. With prefix arg remove the deadline. +‘S- (org-agenda-do-date-later)’ + Change the timestamp associated with the current line by one day + into the future. If the date is in the past, the first call to + this command will move it to today. + With a numeric prefix argument, change it by that many days. For + example, ‘3 6 5 S-’ will change it by a year. With a ‘C-u’ + prefix, change the time by one hour. If you immediately repeat the + command, it will continue to change hours even without the prefix + arg. With a double ‘C-u C-u’ prefix, do the same for changing + minutes. + The stamp is changed in the original Org file, but the change is + not directly reflected in the agenda buffer. Use ‘r’ or ‘g’ to + update the buffer. +‘S- (org-agenda-do-date-earlier)’ + Change the timestamp associated with the current line by one day + into the past. +‘> (org-agenda-date-prompt)’ + Change the timestamp associated with the current line. The key ‘>’ + has been chosen, because it is the same as ‘S-.’ on my keyboard. +‘I (org-agenda-clock-in)’ + Start the clock on the current item. If a clock is running + already, it is stopped first. +‘O (org-agenda-clock-out)’ + Stop the previously started clock. +‘X (org-agenda-clock-cancel)’ + Cancel the currently running clock. +‘J (org-agenda-clock-goto)’ + Jump to the running clock in another window. +‘k (org-agenda-capture)’ + Like ‘org-capture’, but use the date at point as the default date + for the capture template. See ‘org-capture-use-agenda-date’ to + make this the default behavior of ‘org-capture’. + + Dragging agenda lines forward/backward + ...................................... + +‘M- (org-agenda-drag-line-backward)’ + Drag the line at point backward one line(2). With a numeric prefix + argument, drag backward by that many lines. + +‘M- (org-agenda-drag-line-forward)’ + Drag the line at point forward one line. With a numeric prefix + argument, drag forward by that many lines. + + Bulk remote editing selected entries + .................................... + +‘m (org-agenda-bulk-mark)’ + Mark the entry at point for bulk action. With numeric prefix + argument, mark that many successive entries. +‘* (org-agenda-bulk-mark-all)’ + Mark all visible agenda entries for bulk action. +‘u (org-agenda-bulk-unmark)’ + Unmark entry at point for bulk action. +‘U (org-agenda-bulk-remove-all-marks)’ + Unmark all marked entries for bulk action. +‘M-m (org-agenda-bulk-toggle)’ + Toggle mark of the entry at point for bulk action. +‘M-* (org-agenda-bulk-toggle-all)’ + Toggle marks of all visible entries for bulk action. +‘% (org-agenda-bulk-mark-regexp)’ + Mark entries matching a regular expression for bulk action. +‘B (org-agenda-bulk-action)’ + Bulk action: act on all marked entries in the agenda. This will + prompt for another key to select the action to be applied. The + prefix arg to ‘B’ will be passed through to the ‘s’ and ‘d’ + commands, to bulk-remove these special timestamps. By default, + marks are removed after the bulk. If you want them to persist, set + ‘org-agenda-persistent-marks’ to ‘t’ or hit ‘p’ at the prompt. + + ‘*’ + Toggle persistent marks. + ‘$’ + Archive all selected entries. + ‘A’ + Archive entries by moving them to their respective archive + siblings. + ‘t’ + Change TODO state. This prompts for a single TODO keyword and + changes the state of all selected entries, bypassing blocking + and suppressing logging notes (but not timestamps). + ‘+’ + Add a tag to all selected entries. + ‘-’ + Remove a tag from all selected entries. + ‘s’ + Schedule all items to a new date. To shift existing schedule + dates by a fixed number of days, use something starting with + double plus at the prompt, for example ‘++8d’ or ‘++2w’. + ‘d’ + Set deadline to a specific date. + ‘r’ + Prompt for a single refile target and move all entries. The + entries will no longer be in the agenda; refresh (‘g’) to + bring them back. + ‘S’ + Reschedule randomly into the coming N days. N will be + prompted for. With prefix arg (‘C-u B S’), scatter only + across weekdays. + ‘f’ + Apply a function(3) to marked entries. For example, the + function below sets the CATEGORY property of the entries to + web. + + (defun set-category () + (interactive "P") + (let* ((marker (or (org-get-at-bol 'org-hd-marker) + (org-agenda-error))) + (buffer (marker-buffer marker))) + (with-current-buffer buffer + (save-excursion + (save-restriction + (widen) + (goto-char marker) + (org-back-to-heading t) + (org-set-property "CATEGORY" "web")))))) + + Calendar commands + ................. + +‘c (org-agenda-goto-calendar)’ + Open the Emacs calendar and move to the date at the agenda cursor. +‘c (org-calendar-goto-agenda)’ + When in the calendar, compute and show the Org mode agenda for the + date at the cursor. +‘i (org-agenda-diary-entry)’ + Insert a new entry into the diary, using the date at the cursor and + (for block entries) the date at the mark. This will add to the + Emacs diary file(4), in a way similar to the ‘i’ command in the + calendar. The diary file will pop up in another window, where you + can add the entry. + + If you configure ‘org-agenda-diary-file’ to point to an Org mode + file, Org will create entries (in Org mode syntax) in that file + instead. Most entries will be stored in a date-based outline tree + that will later make it easy to archive appointments from previous + months/years. The tree will be built under an entry with a + ‘DATE_TREE’ property, or else with years as top-level entries. + Emacs will prompt you for the entry text—if you specify it, the + entry will be created in ‘org-agenda-diary-file’ without further + interaction. If you directly press at the prompt without + typing text, the target file will be shown in another window for + you to finish the entry there. See also the ‘k r’ command. +‘M (org-agenda-phases-of-moon)’ + Show the phases of the moon for the three months around current + date. +‘S (org-agenda-sunrise-sunset)’ + Show sunrise and sunset times. The geographical location must be + set with calendar variables, see the documentation for the Emacs + calendar. +‘C (org-agenda-convert-date)’ + Convert the date at cursor into many other cultural and historic + calendars. +‘H (org-agenda-holidays)’ + Show holidays for three months around the cursor date. + +‘M-x org-icalendar-combine-agenda-files ’ + Export a single iCalendar file containing entries from all agenda + files. This is a globally available command, and also available in + the agenda menu. + + Exporting to a file + ................... + +‘C-x C-w (org-agenda-write)’ + Write the agenda view to a file. Depending on the extension of the + selected file name, the view will be exported as HTML (‘.html’ or + ‘.htm’), Postscript (‘.ps’), PDF (‘.pdf’), Org (‘.org’) and plain + text (any other extension). When exporting to Org, only the body + of original headlines are exported, not subtrees or inherited tags. + When called with a ‘C-u’ prefix argument, immediately open the + newly created file. Use the variable + ‘org-agenda-exporter-settings’ to set options for ‘ps-print’ and + for ‘htmlize’ to be used during export. + + Quit and Exit + ............. + +‘q (org-agenda-quit)’ + Quit agenda, remove the agenda buffer. +‘x (org-agenda-exit)’ + Exit agenda, remove the agenda buffer and all buffers loaded by + Emacs for the compilation of the agenda. Buffers created by the + user to visit Org files will not be removed. + + ---------- Footnotes ---------- + + (1) Only tags filtering will be respected here, effort filtering is +ignored. + + (2) Moving agenda lines does not persist after an agenda refresh and +does not modify the contributing ‘.org’ files + + (3) You can also create persistent custom functions through +‘org-agenda-bulk-custom-functions’. + + (4) This file is parsed for the agenda when +‘org-agenda-include-diary’ is set. + + +File: org, Node: Custom agenda views, Next: Exporting agenda views, Prev: Agenda commands, Up: Agenda views + +10.6 Custom agenda views +======================== + +Custom agenda commands serve two purposes: to store and quickly access +frequently used TODO and tags searches, and to create special composite +agenda buffers. Custom agenda commands will be accessible through the +dispatcher (*note Agenda dispatcher::), just like the default commands. + +* Menu: + +* Storing searches:: Type once, use often +* Block agenda:: All the stuff you need in a single buffer +* Setting options:: Changing the rules + + +File: org, Node: Storing searches, Next: Block agenda, Up: Custom agenda views + +10.6.1 Storing searches +----------------------- + +The first application of custom searches is the definition of keyboard +shortcuts for frequently used searches, either creating an agenda +buffer, or a sparse tree (the latter covering of course only the current +buffer). + + Custom commands are configured in the variable +‘org-agenda-custom-commands’. You can customize this variable, for +example by pressing ‘C-c a C’. You can also directly set it with Emacs +Lisp in the Emacs init file. The following example contains all valid +agenda views: + + (setq org-agenda-custom-commands + '(("x" agenda) + ("y" agenda*) + ("w" todo "WAITING") + ("W" todo-tree "WAITING") + ("u" tags "+boss-urgent") + ("v" tags-todo "+boss-urgent") + ("U" tags-tree "+boss-urgent") + ("f" occur-tree "\\") + ("h" . "HOME+Name tags searches") ; description for "h" prefix + ("hl" tags "+home+Lisa") + ("hp" tags "+home+Peter") + ("hk" tags "+home+Kim"))) + +The initial string in each entry defines the keys you have to press +after the dispatcher command ‘C-c a’ in order to access the command. +Usually this will be just a single character, but if you have many +similar commands, you can also define two-letter combinations where the +first character is the same in several combinations and serves as a +prefix key(1). The second parameter is the search type, followed by the +string or regular expression to be used for the matching. The example +above will therefore define: + +‘C-c a x’ + as a global search for agenda entries planned(2) this week/day. +‘C-c a y’ + as a global search for agenda entries planned this week/day, but + only those with an hour specification like ‘[h]h:mm’—think of them + as appointments. +‘C-c a w’ + as a global search for TODO entries with ‘WAITING’ as the TODO + keyword +‘C-c a W’ + as the same search, but only in the current buffer and displaying + the results as a sparse tree +‘C-c a u’ + as a global tags search for headlines marked ‘:boss:’ but not + ‘:urgent:’ +‘C-c a v’ + as the same search as ‘C-c a u’, but limiting the search to + headlines that are also TODO items +‘C-c a U’ + as the same search as ‘C-c a u’, but only in the current buffer and + displaying the result as a sparse tree +‘C-c a f’ + to create a sparse tree (again: current buffer only) with all + entries containing the word ‘FIXME’ +‘C-c a h’ + as a prefix command for a HOME tags search where you have to press + an additional key (‘l’, ‘p’ or ‘k’) to select a name (Lisa, Peter, + or Kim) as additional tag to match. + + Note that the ‘*-tree’ agenda views need to be called from an Org +buffer as they operate on the current buffer only. + + ---------- Footnotes ---------- + + (1) You can provide a description for a prefix key by inserting a +cons cell with the prefix and the description. + + (2) _Planned_ means here that these entries have some planning +information attached to them, like a time-stamp, a scheduled or a +deadline string. See ‘org-agenda-entry-types’ on how to set what +planning information will be taken into account. + + +File: org, Node: Block agenda, Next: Setting options, Prev: Storing searches, Up: Custom agenda views + +10.6.2 Block agenda +------------------- + +Another possibility is the construction of agenda views that comprise +the results of _several_ commands, each of which creates a block in the +agenda buffer. The available commands include ‘agenda’ for the daily or +weekly agenda (as created with ‘C-c a a’), ‘alltodo’ for the global TODO +list (as constructed with ‘C-c a t’), and the matching commands +discussed above: ‘todo’, ‘tags’, and ‘tags-todo’. Here are two +examples: + + (setq org-agenda-custom-commands + '(("h" "Agenda and Home-related tasks" + ((agenda "") + (tags-todo "home") + (tags "garden"))) + ("o" "Agenda and Office-related tasks" + ((agenda "") + (tags-todo "work") + (tags "office"))))) + +This will define ‘C-c a h’ to create a multi-block view for stuff you +need to attend to at home. The resulting agenda buffer will contain +your agenda for the current week, all TODO items that carry the tag +‘home’, and also all lines tagged with ‘garden’. Finally the command +‘C-c a o’ provides a similar view for office tasks. + + +File: org, Node: Setting options, Prev: Block agenda, Up: Custom agenda views + +10.6.3 Setting options for custom commands +------------------------------------------ + +Org mode contains a number of variables regulating agenda construction +and display. The global variables define the behavior for all agenda +commands, including the custom commands. However, if you want to change +some settings just for a single custom view, you can do so. Setting +options requires inserting a list of variable names and values at the +right spot in ‘org-agenda-custom-commands’. For example: + + (setq org-agenda-custom-commands + '(("w" todo "WAITING" + ((org-agenda-sorting-strategy '(priority-down)) + (org-agenda-prefix-format " Mixed: "))) + ("U" tags-tree "+boss-urgent" + ((org-show-context-detail 'minimal))) + ("N" search "" + ((org-agenda-files '("~org/notes.org")) + (org-agenda-text-search-extra-files nil))))) + +Now the ‘C-c a w’ command will sort the collected entries only by +priority, and the prefix format is modified to just say ‘ Mixed: ’ +instead of giving the category of the entry. The sparse tags tree of +‘C-c a U’ will now turn out ultra-compact, because neither the headline +hierarchy above the match, nor the headline following the match will be +shown. The command ‘C-c a N’ will do a text search limited to only a +single file. + + For command sets creating a block agenda, +‘org-agenda-custom-commands’ has two separate spots for setting options. +You can add options that should be valid for just a single command in +the set, and options that should be valid for all commands in the set. +The former are just added to the command entry; the latter must come +after the list of command entries. Going back to the block agenda +example (*note Block agenda::), let’s change the sorting strategy for +the ‘C-c a h’ commands to ‘priority-down’, but let’s sort the results +for GARDEN tags query in the opposite order, ‘priority-up’. This would +look like this: + + (setq org-agenda-custom-commands + '(("h" "Agenda and Home-related tasks" + ((agenda) + (tags-todo "home") + (tags "garden" + ((org-agenda-sorting-strategy '(priority-up))))) + ((org-agenda-sorting-strategy '(priority-down)))) + ("o" "Agenda and Office-related tasks" + ((agenda) + (tags-todo "work") + (tags "office"))))) + + As you see, the values and parentheses setting is a little complex. +When in doubt, use the customize interface to set this variable—it fully +supports its structure. Just one caveat: when setting options in this +interface, the _values_ are just Lisp expressions. So if the value is a +string, you need to add the double-quotes around the value yourself. + + To control whether an agenda command should be accessible from a +specific context, you can customize +‘org-agenda-custom-commands-contexts’. Let’s say for example that you +have an agenda command ‘"o"’ displaying a view that you only need when +reading emails. Then you would configure this option like this: + + (setq org-agenda-custom-commands-contexts + '(("o" (in-mode . "message-mode")))) + + You can also tell that the command key ‘"o"’ should refer to another +command key ‘"r"’. In that case, add this command key like this: + + (setq org-agenda-custom-commands-contexts + '(("o" "r" (in-mode . "message-mode")))) + + See the docstring of the variable for more information. + + +File: org, Node: Exporting agenda views, Next: Agenda column view, Prev: Custom agenda views, Up: Agenda views + +10.7 Exporting agenda views +=========================== + +If you are away from your computer, it can be very useful to have a +printed version of some agenda views to carry around. Org mode can +export custom agenda views as plain text, HTML(1), Postscript, PDF(2), +and iCalendar files. If you want to do this only occasionally, use the +command + +‘C-x C-w (org-agenda-write)’ + Write the agenda view to a file. Depending on the extension of the + selected file name, the view will be exported as HTML (extension + ‘.html’ or ‘.htm’), Postscript (extension ‘.ps’), iCalendar + (extension ‘.ics’), or plain text (any other extension). Use the + variable ‘org-agenda-exporter-settings’ to set options for + ‘ps-print’ and for ‘htmlize’ to be used during export, for example + + (setq org-agenda-exporter-settings + '((ps-number-of-columns 2) + (ps-landscape-mode t) + (org-agenda-add-entry-text-maxlines 5) + (htmlize-output-type 'css))) + + If you need to export certain agenda views frequently, you can +associate any custom agenda command with a list of output file names +(3). Here is an example that first defines custom commands for the +agenda and the global TODO list, together with a number of files to +which to export them. Then we define two block agenda commands and +specify file names for them as well. File names can be relative to the +current working directory, or absolute. + + (setq org-agenda-custom-commands + '(("X" agenda "" nil ("agenda.html" "agenda.ps")) + ("Y" alltodo "" nil ("todo.html" "todo.txt" "todo.ps")) + ("h" "Agenda and Home-related tasks" + ((agenda "") + (tags-todo "home") + (tags "garden")) + nil + ("~/views/home.html")) + ("o" "Agenda and Office-related tasks" + ((agenda) + (tags-todo "work") + (tags "office")) + nil + ("~/views/office.ps" "~/calendars/office.ics")))) + + The extension of the file name determines the type of export. If it +is ‘.html’, Org mode will try to use the ‘htmlize.el’ package to convert +the buffer to HTML and save it to this file name. If the extension is +‘.ps’, ‘ps-print-buffer-with-faces’ is used to produce Postscript +output. If the extension is ‘.ics’, iCalendar export is run export over +all files that were used to construct the agenda, and limit the export +to entries listed in the agenda. Any other extension produces a plain +ASCII file. + + The export files are _not_ created when you use one of those commands +interactively because this might use too much overhead. Instead, there +is a special command to produce _all_ specified files in one step: + +‘C-c a e (org-store-agenda-views)’ + Export all agenda views that have export file names associated with + them. + + You can use the options section of the custom agenda commands to also +set options for the export commands. For example: + + (setq org-agenda-custom-commands + '(("X" agenda "" + ((ps-number-of-columns 2) + (ps-landscape-mode t) + (org-agenda-prefix-format " [ ] ") + (org-agenda-with-colors nil) + (org-agenda-remove-tags t)) + ("theagenda.ps")))) + +This command sets two options for the Postscript exporter, to make it +print in two columns in landscape format—the resulting page can be cut +in two and then used in a paper agenda. The remaining settings modify +the agenda prefix to omit category and scheduling information, and +instead include a checkbox to check off items. We also remove the tags +to make the lines compact, and we don’t want to use colors for the +black-and-white printer. Settings specified in +‘org-agenda-exporter-settings’ will also apply, but the settings in +‘org-agenda-custom-commands’ take precedence. + +From the command line you may also use + emacs -eval (org-batch-store-agenda-views) -kill +or, if you need to modify some parameters(4) + emacs -eval '(org-batch-store-agenda-views \ + org-agenda-span (quote month) \ + org-agenda-start-day "2007-11-01" \ + org-agenda-include-diary nil \ + org-agenda-files (quote ("~/org/project.org")))' \ + -kill +which will create the agenda views restricted to the file +‘~/org/project.org’, without diary entries and with a 30-day extent. + + You can also extract agenda information in a way that allows further +processing by other programs. See *note Extracting agenda +information::, for more information. + + ---------- Footnotes ---------- + + (1) You need to install ‘htmlize.el’ from Hrvoje Niksic’s repository. +(https://github.com/hniksic/emacs-htmlize) + + (2) To create PDF output, the ghostscript ‘ps2pdf’ utility must be +installed on the system. Selecting a PDF file will also create the +postscript file. + + (3) If you want to store standard views like the weekly agenda or the +global TODO list as well, you need to define custom commands for them in +order to be able to specify file names. + + (4) Quoting depends on the system you use, please check the FAQ for +examples. + + +File: org, Node: Agenda column view, Prev: Exporting agenda views, Up: Agenda views + +10.8 Using column view in the agenda +==================================== + +Column view (*note Column view::) is normally used to view and edit +properties embedded in the hierarchical structure of an Org file. It +can be quite useful to use column view also from the agenda, where +entries are collected by certain criteria. + +‘C-c C-x C-c (org-agenda-columns)’ + Turn on column view in the agenda. + + To understand how to use this properly, it is important to realize +that the entries in the agenda are no longer in their proper outline +environment. This causes the following issues: + + 1. Org needs to make a decision which ‘COLUMNS’ format to use. Since + the entries in the agenda are collected from different files, and + different files may have different ‘COLUMNS’ formats, this is a + non-trivial problem. Org first checks if the variable + ‘org-agenda-overriding-columns-format’ is currently set, and if so, + takes the format from there. Otherwise it takes the format + associated with the first item in the agenda, or, if that item does + not have a specific format—defined in a property, or in its file—it + uses ‘org-columns-default-format’. + + 2. If any of the columns has a summary type defined (*note Column + attributes::), turning on column view in the agenda will visit all + relevant agenda files and make sure that the computations of this + property are up to date. This is also true for the special + ‘CLOCKSUM’ property. Org will then sum the values displayed in the + agenda. In the daily/weekly agenda, the sums will cover a single + day; in all other views they cover the entire block. It is vital + to realize that the agenda may show the same entry _twice_—for + example as scheduled and as a deadline—and it may show two entries + from the same hierarchy—for example a _parent_ and its _child_. In + these cases, the summation in the agenda will lead to incorrect + results because some values will count double. + + 3. When the column view in the agenda shows the ‘CLOCKSUM’, that is + always the entire clocked time for this item. So even in the + daily/weekly agenda, the clocksum listed in column view may + originate from times outside the current view. This has the + advantage that you can compare these values with a column listing + the planned total effort for a task—one of the major applications + for column view in the agenda. If you want information about + clocked time in the displayed period use clock table mode (press + ‘R’ in the agenda). + + 4. When the column view in the agenda shows the ‘CLOCKSUM_T’, that is + always today’s clocked time for this item. So even in the weekly + agenda, the clocksum listed in column view only originates from + today. This lets you compare the time you spent on a task for + today, with the time already spent —via ‘CLOCKSUM’—and with the + planned total effort for it. + + +File: org, Node: Markup, Next: Exporting, Prev: Agenda views, Up: Top + +11 Markup for rich export +************************* + +When exporting Org mode documents, the exporter tries to reflect the +structure of the document as accurately as possible in the back-end. +Since export targets like HTML and LaTeX allow much richer formatting, +Org mode has rules on how to prepare text for rich export. This section +summarizes the markup rules used in an Org mode buffer. + +* Menu: + +* Paragraphs:: The basic unit of text +* Emphasis and monospace:: Bold, italic, etc. +* Horizontal rules:: Make a line +* Images and tables:: Images, tables and caption mechanism +* Literal examples:: Source code examples with special formatting +* Special symbols:: Greek letters and other symbols +* Subscripts and superscripts:: Simple syntax for raising/lowering text +* Embedded LaTeX:: LaTeX can be freely used inside Org documents + + +File: org, Node: Paragraphs, Next: Emphasis and monospace, Up: Markup + +11.1 Paragraphs, line breaks, and quoting +========================================= + +Paragraphs are separated by at least one empty line. If you need to +enforce a line break within a paragraph, use ‘\\’ at the end of a line. + + To preserve the line breaks, indentation and blank lines in a region, +but otherwise use normal formatting, you can use this construct, which +can also be used to format poetry. + + #+BEGIN_VERSE + Great clouds overhead + Tiny black birds rise and fall + Snow covers Emacs + + -- AlexSchroeder + #+END_VERSE + + When quoting a passage from another document, it is customary to +format this as a paragraph that is indented on both the left and the +right margin. You can include quotations in Org mode documents like +this: + + #+BEGIN_QUOTE + Everything should be made as simple as possible, + but not any simpler -- Albert Einstein + #+END_QUOTE + + If you would like to center some text, do it like this: + #+BEGIN_CENTER + Everything should be made as simple as possible, \\ + but not any simpler + #+END_CENTER + + +File: org, Node: Emphasis and monospace, Next: Horizontal rules, Prev: Paragraphs, Up: Markup + +11.2 Emphasis and monospace +=========================== + +You can make words *bold*, /italic/, _underlined_, ‘=verbatim=’ and +‘~code~’, and, if you must, ‘+strike-through+’. Text in the code and +verbatim string is not processed for Org mode specific syntax, it is +exported verbatim. + + To turn off fontification for marked up text, you can set +‘org-fontify-emphasized-text’ to ‘nil’. To narrow down the list of +available markup syntax, you can customize ‘org-emphasis-alist’. To +fine tune what characters are allowed before and after the markup +characters, you can tweak ‘org-emphasis-regexp-components’. Beware that +changing one of the above variables will not take effect until you +reload Org, for which you may need to restart Emacs. + + +File: org, Node: Horizontal rules, Next: Images and tables, Prev: Emphasis and monospace, Up: Markup + +11.3 Horizontal rules +===================== + +A line consisting of only dashes, and at least 5 of them, will be +exported as a horizontal line. + + +File: org, Node: Images and tables, Next: Literal examples, Prev: Horizontal rules, Up: Markup + +11.4 Images and Tables +====================== + +Both the native Org mode tables (*note Tables::) and tables formatted +with the ‘table.el’ package will be exported properly. For Org mode +tables, the lines before the first horizontal separator line will become +table header lines. You can use the following lines somewhere before +the table to assign a caption and a label for cross references, and in +the text you can refer to the object with ‘[[tab:basic-data]]’ (*note +Internal links::): + + #+CAPTION: This is the caption for the next table (or link) + #+NAME: tab:basic-data + | ... | ...| + |-----|----| + + Optionally, the caption can take the form: + #+CAPTION[Caption for list of tables]: Caption for table. + + Some back-ends allow you to directly include images into the exported +document. Org does this, if a link to an image files does not have a +description part, for example ‘[[./img/a.jpg]]’. If you wish to define +a caption for the image and maybe a label for internal cross references, +make sure that the link is on a line by itself and precede it with +‘#+CAPTION’ and ‘#+NAME’ as follows: + + #+CAPTION: This is the caption for the next figure link (or table) + #+NAME: fig:SED-HR4049 + [[./img/a.jpg]] + +Such images can be displayed within the buffer. *Note the discussion of +image links: Handling links. + + Even though images and tables are prominent examples of captioned +structures, the same caption mechanism can apply to many others (e.g., +LaTeX equations, source code blocks). Depending on the export back-end, +those may or may not be handled. + + +File: org, Node: Literal examples, Next: Special symbols, Prev: Images and tables, Up: Markup + +11.5 Literal examples +===================== + +You can include literal examples that should not be subjected to markup. +Such examples will be typeset in monospace, so this is well suited for +source code and similar examples. + + #+BEGIN_EXAMPLE + Some example from a text file. + #+END_EXAMPLE + + Note that such blocks may be indented in order to align nicely with +indented text and in particular with plain list structure (*note Plain +lists::). For simplicity when using small examples, you can also start +the example lines with a colon followed by a space. There may also be +additional whitespace before the colon: + + Here is an example + : Some example from a text file. + + If the example is source code from a programming language, or any +other text that can be marked up by font-lock in Emacs, you can ask for +the example to look like the fontified Emacs buffer(1). This is done +with the ‘src’ block, where you also need to specify the name of the +major mode that should be used to fontify the example(2), see *note Easy +templates:: for shortcuts to easily insert code blocks. + + #+BEGIN_SRC emacs-lisp + (defun org-xor (a b) + "Exclusive or." + (if a (not b) b)) + #+END_SRC + + Both in ‘example’ and in ‘src’ snippets, you can add a ‘-n’ switch to +the end of the ‘BEGIN’ line, to get the lines of the example numbered. +The ‘-n’ takes an optional numeric argument specifying the starting line +number of the block. If you use a ‘+n’ switch, the numbering from the +previous numbered snippet will be continued in the current one. The +‘+n’ can also take a numeric argument. The value of the argument will +be added to the last line of the previous block to determine the +starting line number. + + #+BEGIN_SRC emacs-lisp -n 20 + ;; this will export with line number 20 + (message "This is line 21") + #+END_SRC + #+BEGIN_SRC emacs-lisp +n 10 + ;; This will be listed as line 31 + (message "This is line 32") + #+END_SRC + + In literal examples, Org will interpret strings like ‘(ref:name)’ as +labels, and use them as targets for special hyperlinks like ‘[[(name)]]’ +(i.e., the reference name enclosed in single parenthesis). In HTML, +hovering the mouse over such a link will remote-highlight the +corresponding code line, which is kind of cool. + + You can also add a ‘-r’ switch which removes the labels from the +source code(3). With the ‘-n’ switch, links to these references will be +labeled by the line numbers from the code listing, otherwise links will +use the labels with no parentheses. Here is an example: + + #+BEGIN_SRC emacs-lisp -n -r + (save-excursion (ref:sc) + (goto-char (point-min))) (ref:jump) + #+END_SRC + In line [[(sc)]] we remember the current position. [[(jump)][Line (jump)]] + jumps to point-min. + + Finally, you can use ‘-i’ to preserve the indentation of a specific +code block (*note Editing source code::). + + If the syntax for the label format conflicts with the language +syntax, use a ‘-l’ switch to change the format, for example ‘#+BEGIN_SRC +pascal -n -r -l "((%s))"’. See also the variable +‘org-coderef-label-format’. + + HTML export also allows examples to be published as text areas (*note +Text areas in HTML export::). + + Because the ‘#+BEGIN_...’ and ‘#+END_...’ patterns need to be added +so often, shortcuts are provided using the Easy templates facility +(*note Easy templates::). + +‘C-c '’ + Edit the source code example at point in its native mode. This + works by switching to a temporary buffer with the source code. You + need to exit by pressing ‘C-c '’ again(4). The edited version will + then replace the old version in the Org buffer. Fixed-width + regions (where each line starts with a colon followed by a space) + will be edited using ‘artist-mode’(5) to allow creating ASCII + drawings easily. Using this command in an empty line will create a + new fixed-width region. +‘C-c l’ + Calling ‘org-store-link’ while editing a source code example in a + temporary buffer created with ‘C-c '’ will prompt for a label. + Make sure that it is unique in the current buffer, and insert it + with the proper formatting like ‘(ref:label)’ at the end of the + current line. Then the label is stored as a link ‘(label)’, for + retrieval with ‘C-c C-l’. + + ---------- Footnotes ---------- + + (1) This works automatically for the HTML back-end (it requires +version 1.34 of the ‘htmlize.el’ package, which you need to install). +Fontified code chunks in LaTeX can be achieved using either the + +or the package. If you use minted or +listing, you must load the packages manually, for example by adding the +desired package to ‘org-latex-packages-alist’. Refer to +‘org-latex-listings’ for details. + + (2) Code in ‘src’ blocks may also be evaluated either interactively +or on export. *Note Working with source code::, for more information on +evaluating code blocks. + + (3) Adding ‘-k’ to ‘-n -r’ will keep the labels in the source code +while using line numbers for the links, which might be useful to explain +those in an Org mode example code. + + (4) Upon exit, lines starting with ‘*’, ‘,*’, ‘#+’ and ‘,#+’ will get +a comma prepended, to keep them from being interpreted by Org as outline +nodes or special syntax. These commas will be stripped for editing with +‘C-c '’, and also for export. + + (5) You may select a different-mode with the variable +‘org-edit-fixed-width-region-mode’. + + +File: org, Node: Special symbols, Next: Subscripts and superscripts, Prev: Literal examples, Up: Markup + +11.6 Special symbols +==================== + +You can use LaTeX-like syntax to insert special symbols—named +entities—like ‘\alpha’ to indicate the Greek letter, or ‘\to’ to +indicate an arrow. Completion for these symbols is available, just type +‘\’ and maybe a few letters, and press ‘M-’ to see possible +completions. If you need such a symbol inside a word, terminate it with +a pair of curly brackets. For example + + Pro tip: Given a circle \Gamma of diameter d, the length of its circumference + is \pi{}d. + + A large number of entities is provided, with names taken from both +HTML and LaTeX; you can comfortably browse the complete list from a +dedicated buffer using the command ‘org-entities-help’. It is also +possible to provide your own special symbols in the variable +‘org-entities-user’. + + During export, these symbols are transformed into the native format +of the exporter back-end. Strings like ‘\alpha’ are exported as +‘α’ in the HTML output, and as ‘\(\alpha\)’ in the LaTeX output. +Similarly, ‘\nbsp’ becomes ‘ â€™ in HTML and ‘~’ in LaTeX. + + Entities may also be used as a may to escape markup in an Org +document, e.g., ‘\under{}not underlined\under’ exports as ‘_not +underlined_’. + + If you would like to see entities displayed as UTF-8 characters, use +the following command(1): + +‘C-c C-x \’ + Toggle display of entities as UTF-8 characters. This does not + change the buffer content which remains plain ASCII, but it + overlays the UTF-8 character for display purposes only. + + In addition to regular entities defined above, Org exports in a +special way(2) the following commonly used character combinations: ‘\-’ +is treated as a shy hyphen, ‘--’ and ‘---’ are converted into dashes, +and ‘...’ becomes a compact set of dots. + + ---------- Footnotes ---------- + + (1) You can turn this on by default by setting the variable +‘org-pretty-entities’, or on a per-file base with the ‘#+STARTUP’ option +‘entitiespretty’. + + (2) This behavior can be disabled with ‘-’ export setting (*note +Export settings::). + + +File: org, Node: Subscripts and superscripts, Next: Embedded LaTeX, Prev: Special symbols, Up: Markup + +11.7 Subscripts and superscripts +================================ + +‘^’ and ‘_’ are used to indicate super- and subscripts. To increase the +readability of ASCII text, it is not necessary—but OK—to surround +multi-character sub- and superscripts with curly braces. Those are, +however, mandatory, when more than one word is involved. For example + + The radius of the sun is R_sun = 6.96 x 10^8 m. On the other hand, the + radius of Alpha Centauri is R_{Alpha Centauri} = 1.28 x R_{sun}. + + If you write a text where the underscore is often used in a different +context, Org’s convention to always interpret these as subscripts can +get in your way. Configure the variable ‘org-use-sub-superscripts’ to +change this convention. For example, when setting this variable to +‘{}’, ‘a_b’ will not be interpreted as a subscript, but ‘a_{b}’ will. + +‘C-c C-x \’ + In addition to showing entities as UTF-8 characters, this command + will also format sub- and superscripts in a WYSIWYM way. + + +File: org, Node: Embedded LaTeX, Prev: Subscripts and superscripts, Up: Markup + +11.8 Embedded LaTeX +=================== + +Plain ASCII is normally sufficient for almost all note taking. +Exceptions include scientific notes, which often require mathematical +symbols and the occasional formula. LaTeX(1) is widely used to typeset +scientific documents. Org mode supports embedding LaTeX code into its +files, because many academics are used to writing and reading LaTeX +source code, and because it can be readily processed to produce pretty +output for a number of export back-ends. + +* Menu: + +* LaTeX fragments:: Complex formulas made easy +* Previewing LaTeX fragments:: What will this snippet look like? +* CDLaTeX mode:: Speed up entering of formulas + + ---------- Footnotes ---------- + + (1) LaTeX is a macro system based on Donald E. Knuth’s TeX system. +Many of the features described here as “LaTeX” are really from TeX, but +for simplicity I am blurring this distinction. + + +File: org, Node: LaTeX fragments, Next: Previewing LaTeX fragments, Up: Embedded LaTeX + +11.8.1 LaTeX fragments +---------------------- + +Org mode can contain LaTeX math fragments, and it supports ways to +process these for several export back-ends. When exporting to LaTeX, +the code is left as it is. When exporting to HTML, Org can use either +MathJax (http://www.mathjax.org) (*note Math formatting in HTML +export::) or transcode the math into images (see *note Previewing LaTeX +fragments::). + + LaTeX fragments don’t need any special marking at all. The following +snippets will be identified as LaTeX source code: + • Environments of any kind(1). The only requirement is that the + ‘\begin’ statement appears on a new line, at the beginning of the + line or after whitespaces only. + • Text within the usual LaTeX math delimiters. To avoid conflicts + with currency specifications, single ‘$’ characters are only + recognized as math delimiters if the enclosed text contains at most + two line breaks, is directly attached to the ‘$’ characters with no + whitespace in between, and if the closing ‘$’ is followed by + whitespace or punctuation (parentheses and quotes are considered to + be punctuation in this context). For the other delimiters, there + is no such restriction, so when in doubt, use ‘\(...\)’ as inline + math delimiters. + +For example: + + \begin{equation} + x=\sqrt{b} + \end{equation} + + If $a^2=b$ and \( b=2 \), then the solution must be + either $$ a=+\sqrt{2} $$ or \[ a=-\sqrt{2} \]. + + LaTeX processing can be configured with the variable +‘org-export-with-latex’. The default setting is ‘t’ which means MathJax +for HTML, and no processing for ASCII and LaTeX back-ends. You can also +set this variable on a per-file basis using one of these lines: + + #+OPTIONS: tex:t Do the right thing automatically (MathJax) + #+OPTIONS: tex:nil Do not process LaTeX fragments at all + #+OPTIONS: tex:verbatim Verbatim export, for jsMath or so + + ---------- Footnotes ---------- + + (1) When MathJax is used, only the environments recognized by MathJax +will be processed. When ‘dvipng’ program, ‘dvisvgm’ program or +‘imagemagick’ suite is used to create images, any LaTeX environment will +be handled. + + +File: org, Node: Previewing LaTeX fragments, Next: CDLaTeX mode, Prev: LaTeX fragments, Up: Embedded LaTeX + +11.8.2 Previewing LaTeX fragments +--------------------------------- + +If you have a working LaTeX installation and ‘dvipng’, ‘dvisvgm’ or +‘convert’ installed(1), LaTeX fragments can be processed to produce +images of the typeset expressions to be used for inclusion while +exporting to HTML (see *note LaTeX fragments::), or for inline +previewing within Org mode. + + You can customize the variables ‘org-format-latex-options’ and +‘org-format-latex-header’ to influence some aspects of the preview. In +particular, the ‘:scale’ (and for HTML export, ‘:html-scale’) property +of the former can be used to adjust the size of the preview images. + +‘C-c C-x C-l’ + Produce a preview image of the LaTeX fragment at point and overlay + it over the source code. If there is no fragment at point, process + all fragments in the current entry (between two headlines). When + called with a prefix argument, process the entire subtree. When + called with two prefix arguments, or when the cursor is before the + first headline, process the entire buffer. +‘C-c C-c’ + Remove the overlay preview images. + + You can turn on the previewing of all LaTeX fragments in a file with + + #+STARTUP: latexpreview + + To disable it, simply use + + #+STARTUP: nolatexpreview + + ---------- Footnotes ---------- + + (1) These are respectively available at +, +and from the ‘imagemagick’ suite. Choose the converter by setting the +variable ‘org-preview-latex-default-process’ accordingly. + + +File: org, Node: CDLaTeX mode, Prev: Previewing LaTeX fragments, Up: Embedded LaTeX + +11.8.3 Using CDLaTeX to enter math +---------------------------------- + +CDLaTeX mode is a minor mode that is normally used in combination with a +major LaTeX mode like AUCTeX in order to speed-up insertion of +environments and math templates. Inside Org mode, you can make use of +some of the features of CDLaTeX mode. You need to install ‘cdlatex.el’ +and ‘texmathp.el’ (the latter comes also with AUCTeX) from +. Don’t use CDLaTeX +mode itself under Org mode, but use the light version ‘org-cdlatex-mode’ +that comes as part of Org mode. Turn it on for the current buffer with +‘M-x org-cdlatex-mode ’, or for all Org files with + + (add-hook 'org-mode-hook 'turn-on-org-cdlatex) + + When this mode is enabled, the following features are present (for +more details see the documentation of CDLaTeX mode): + • Environment templates can be inserted with ‘C-c {’. + • The key will do template expansion if the cursor is inside a + LaTeX fragment(1). For example, will expand ‘fr’ to + ‘\frac{}{}’ and position the cursor correctly inside the first + brace. Another will get you into the second brace. Even + outside fragments, will expand environment abbreviations at + the beginning of a line. For example, if you write ‘equ’ at the + beginning of a line and press , this abbreviation will be + expanded to an ‘equation’ environment. To get a list of all + abbreviations, type ‘M-x cdlatex-command-help ’. + • Pressing ‘_’ and ‘^’ inside a LaTeX fragment will insert these + characters together with a pair of braces. If you use to + move out of the braces, and if the braces surround only a single + character or macro, they are removed again (depending on the + variable ‘cdlatex-simplify-sub-super-scripts’). + • Pressing the grave accent ‘`’ followed by a character inserts math + macros, also outside LaTeX fragments. If you wait more than 1.5 + seconds after the grave accent, a help window will pop up. + • Pressing the apostrophe ‘'’ followed by another character modifies + the symbol before point with an accent or a font. If you wait more + than 1.5 seconds after the apostrophe, a help window will pop up. + Character modification will work only inside LaTeX fragments; + outside the quote is normal. + + ---------- Footnotes ---------- + + (1) Org mode has a method to test if the cursor is inside such a +fragment, see the documentation of the function +‘org-inside-LaTeX-fragment-p’. + + +File: org, Node: Exporting, Next: Publishing, Prev: Markup, Up: Top + +12 Exporting +************ + +Sometimes, you may want to pretty print your notes, publish them on the +web or even share them with people not using Org. In these cases, the +Org export facilities can be used to convert your documents to a variety +of other formats, while retaining as much structure (*note Document +structure::) and markup (*note Markup::) as possible. + + Libraries responsible for such translation are called back-ends. Org +ships with the following ones + + • ascii (ASCII format) + • beamer (LaTeX Beamer format) + • html (HTML format) + • icalendar (iCalendar format) + • latex (LaTeX format) + • md (Markdown format) + • odt (OpenDocument Text format) + • org (Org format) + • texinfo (Texinfo format) + • man (Man page format) + +Org also uses additional libraries located in ‘contrib/’ directory +(*note Installation::). Users can install additional export libraries +for additional formats from the Emacs packaging system. For easy +discovery, these packages have a common naming scheme: ‘ox-NAME’, where +NAME is one of the formats. For example, ‘ox-koma-letter’ for +‘koma-letter’ back-end. + + Org loads back-ends for the following formats by default: ‘ascii’, +‘html’, ‘icalendar’, ‘latex’ and ‘odt’. + + Org can load additional back-ends either of two ways: through the +‘org-export-backends’ variable configuration; or, by requiring the +library in the Emacs init file like this: + + (require 'ox-md) + +* Menu: + +* The export dispatcher:: The main interface +* Export settings:: Common export settings +* Table of contents:: The if and where of the table of contents +* Include files:: Include additional files into a document +* Macro replacement:: Use macros to create templates +* Comment lines:: What will not be exported +* ASCII/Latin-1/UTF-8 export:: Exporting to flat files with encoding +* Beamer export:: Exporting as a Beamer presentation +* HTML export:: Exporting to HTML +* LaTeX export:: Exporting to LaTeX, and processing to PDF +* Markdown export:: Exporting to Markdown +* OpenDocument Text export:: Exporting to OpenDocument Text +* Org export:: Exporting to Org +* Texinfo export:: Exporting to Texinfo +* iCalendar export:: Exporting to iCalendar +* Other built-in back-ends:: Exporting to a man page +* Advanced configuration:: Fine-tuning the export output +* Export in foreign buffers:: Author tables and lists in Org syntax + + +File: org, Node: The export dispatcher, Next: Export settings, Up: Exporting + +12.1 The export dispatcher +========================== + +The export dispatcher is the main interface for Org’s exports. A +hierarchical menu presents the currently configured export formats. +Options are shown as easy toggle switches on the same screen. + + Org also has a minimal prompt interface for the export dispatcher. +When the variable ‘org-export-dispatch-use-expert-ui’ is set to a +non-‘nil’ value, Org prompts in the minibuffer. To switch back to the +hierarchical menu, press . + +‘C-c C-e’ (‘org-export-dispatch’) + + Invokes the export dispatcher interface. The options show default + settings. The ‘C-u’ prefix argument preserves options from the + previous export, including any sub-tree selections. + + Org exports the entire buffer by default. If the Org buffer has an +active region, then Org exports just that region. + + These are the export options, the key combinations that toggle them +(*note Export settings::): + +‘C-a’ + Toggles asynchronous export. Asynchronous export uses an external + Emacs process with a specially configured initialization file to + complete the exporting process in the background thereby releasing + the current interface. This is particularly useful when exporting + long documents. + + Output from an asynchronous export is saved on the “the export + stack”. To view this stack, call the export dispatcher with a + double ‘C-u’ prefix argument. If already in the export dispatcher + menu, ‘&’ displays the stack. + + To make the background export process the default, customize the + variable, ‘org-export-in-background’. + +‘C-b’ + Toggle body-only export. Useful for excluding headers and footers + in the export. Affects only those back-end formats that have such + sections—like ‘...’ in HTML. + +‘C-s’ + Toggle sub-tree export. When turned on, Org exports only the + sub-tree starting from the cursor position at the time the export + dispatcher was invoked. Org uses the top heading of this sub-tree + as the document’s title. If the cursor is not on a heading, Org + uses the nearest enclosing header. If the cursor is in the + document preamble, Org signals an error and aborts export. + + To make the sub-tree export the default, customize the variable, + ‘org-export-initial-scope’. + +‘C-v’ + Toggle visible-only export. Useful for exporting only visible + parts of an Org document by adjusting outline visibility settings. + + +File: org, Node: Export settings, Next: Table of contents, Prev: The export dispatcher, Up: Exporting + +12.2 Export settings +==================== + +Export options can be set: globally with variables; for an individual +file by making variables buffer-local with in-buffer settings (*note +In-buffer settings::), by setting individual keywords, or by specifying +them in a compact form with the ‘#+OPTIONS’ keyword; or for a tree by +setting properties (*note Properties and columns::). Options set at a +specific level override options set at a more general level. + + In-buffer settings may appear anywhere in the file, either directly +or indirectly through a file included using ‘#+SETUPFILE: filename or +URL’ syntax. Option keyword sets tailored to a particular back-end can +be inserted from the export dispatcher (*note The export dispatcher::) +using the ‘Insert template’ command by pressing ‘#’. To insert keywords +individually, a good way to make sure the keyword is correct is to type +‘#+’ and then to use ‘M-’(1) for completion. + + The export keywords available for every back-end, and their +equivalent global variables, include: + +‘AUTHOR’ + The document author (‘user-full-name’). + +‘CREATOR’ + Entity responsible for output generation + (‘org-export-creator-string’). + +‘DATE’ + A date or a time-stamp(2). + +‘EMAIL’ + The email address (‘user-mail-address’). + +‘LANGUAGE’ + Language to use for translating certain strings + (‘org-export-default-language’). With ‘#+LANGUAGE: fr’, for + example, Org translates _Table of contents_ to the French _Table + des matières_. + +‘SELECT_TAGS’ + The default value is ‘:export:’. When a tree is tagged with + ‘:export:’ (‘org-export-select-tags’), Org selects that tree and + its sub-trees for export. Org excludes trees with ‘:noexport:’ + tags, see below. When selectively exporting files with ‘:export:’ + tags set, Org does not export any text that appears before the + first headline. + +‘EXCLUDE_TAGS’ + The default value is ‘:noexport:’. When a tree is tagged with + ‘:noexport:’ (‘org-export-exclude-tags’), Org excludes that tree + and its sub-trees from export. Entries tagged with ‘:noexport:’ + will be unconditionally excluded from the export, even if they have + an ‘:export:’ tag. Even if a sub-tree is not exported, Org will + execute any code blocks contained in them. + +‘TITLE’ + Org displays this title. For long titles, use multiple ‘#+TITLE’ + lines. + +‘EXPORT_FILE_NAME’ + The name of the output file to be generated. Otherwise, Org + generates the file name based on the buffer name and the extension + based on the back-end format. + + The ‘#+OPTIONS’ keyword is a compact form. To configure multiple +options, use several ‘#+OPTIONS’ lines. ‘#+OPTIONS’ recognizes the +following arguments. + +‘':’ + Toggle smart quotes (‘org-export-with-smart-quotes’). Depending on + the language used, when activated, Org treats pairs of double + quotes as primary quotes, pairs of single quotes as secondary + quotes, and single quote marks as apostrophes. + +‘*:’ + Toggle emphasized text (‘org-export-with-emphasize’). + +‘-:’ + Toggle conversion of special strings + (‘org-export-with-special-strings’). + +‘::’ + Toggle fixed-width sections (‘org-export-with-fixed-width’). + +‘<:’ + Toggle inclusion of time/date active/inactive stamps + (‘org-export-with-timestamps’). + +‘\n:’ + Toggles whether to preserve line breaks + (‘org-export-preserve-breaks’). + +‘^:’ + Toggle TeX-like syntax for sub- and superscripts. If you write + "^:{}", ‘a_{b}’ will be interpreted, but the simple ‘a_b’ will be + left as it is (‘org-export-with-sub-superscripts’). + +‘arch:’ + Configure how archived trees are exported. When set to ‘headline’, + the export process skips the contents and processes only the + headlines (‘org-export-with-archived-trees’). + +‘author:’ + Toggle inclusion of author name into exported file + (‘org-export-with-author’). + +‘broken-links:’ + Toggles if Org should continue exporting upon finding a broken + internal link. When set to ‘mark’, Org clearly marks the problem + link in the output (‘org-export-with-broken-links’). + +‘c:’ + Toggle inclusion of CLOCK keywords (‘org-export-with-clocks’). + +‘creator:’ + Toggle inclusion of creator information in the exported file + (‘org-export-with-creator’). + +‘d:’ + Toggles inclusion of drawers, or list of drawers to include, or + list of drawers to exclude (‘org-export-with-drawers’). + +‘date:’ + Toggle inclusion of a date into exported file + (‘org-export-with-date’). + +‘e:’ + Toggle inclusion of entities (‘org-export-with-entities’). + +‘email:’ + Toggle inclusion of the author’s e-mail into exported file + (‘org-export-with-email’). + +‘f:’ + Toggle the inclusion of footnotes (‘org-export-with-footnotes’). + +‘H:’ + Set the number of headline levels for export + (‘org-export-headline-levels’). Below that level, headlines are + treated differently. In most back-ends, they become list items. + +‘inline:’ + Toggle inclusion of inlinetasks (‘org-export-with-inlinetasks’). + +‘num:’ + Toggle section-numbers (‘org-export-with-section-numbers’). When + set to number ‘n’, Org numbers only those headlines at level ‘n’ or + above. Setting ‘UNNUMBERED’ property to non-‘nil’ disables + numbering of a heading. Since subheadings inherit from this + property, it affects their numbering, too. + +‘p:’ + Toggle export of planning information (‘org-export-with-planning’). + “Planning information” comes from lines located right after the + headline and contain any combination of these cookies: + ‘SCHEDULED:’, ‘DEADLINE:’, or ‘CLOSED:’. + +‘pri:’ + Toggle inclusion of priority cookies (‘org-export-with-priority’). + +‘prop:’ + Toggle inclusion of property drawers, or list the properties to + include (‘org-export-with-properties’). + +‘stat:’ + Toggle inclusion of statistics cookies + (‘org-export-with-statistics-cookies’). + +‘tags:’ + Toggle inclusion of tags, may also be ‘not-in-toc’ + (‘org-export-with-tags’). + +‘tasks:’ + Toggle inclusion of tasks (TODO items); or ‘nil’ to remove all + tasks; or ‘todo’ to remove DONE tasks; or list the keywords to keep + (‘org-export-with-tasks’). + +‘tex:’ + ‘nil’ does not export; ‘t’ exports; ‘verbatim’ keeps everything in + verbatim (‘org-export-with-latex’). + +‘timestamp:’ + Toggle inclusion of the creation time in the exported file + (‘org-export-time-stamp-file’). + +‘title:’ + Toggle inclusion of title (‘org-export-with-title’). + +‘toc:’ + Toggle inclusion of the table of contents, or set the level limit + (‘org-export-with-toc’). + +‘todo:’ + Toggle inclusion of TODO keywords into exported text + (‘org-export-with-todo-keywords’). + +‘|:’ + Toggle inclusion of tables (‘org-export-with-tables’). + + When exporting sub-trees, special node properties in them can +override the above keywords. They are special because they have an +‘EXPORT_’ prefix. For example, ‘DATE’ and ‘EXPORT_FILE_NAME’ keywords +become, respectively, ‘EXPORT_DATE’ and ‘EXPORT_FILE_NAME’. Except for +‘SETUPFILE’, all other keywords listed above have an ‘EXPORT_’ +equivalent. + + If ‘org-export-allow-bind-keywords’ is non-‘nil’, Emacs variables can +become buffer-local during export by using the BIND keyword. Its syntax +is ‘#+BIND: variable value’. This is particularly useful for in-buffer +settings that cannot be changed using keywords. + + ---------- Footnotes ---------- + + (1) Many desktops intercept ‘M-’ to switch windows. Use ‘C-M-i’ +or ‘ ’ instead. + + (2) The variable ‘org-export-date-timestamp-format’ defines how this +time-stamp will be exported. + + +File: org, Node: Table of contents, Next: Include files, Prev: Export settings, Up: Exporting + +12.3 Table of contents +====================== + +Org normally inserts the table of contents directly before the first +headline of the file. Org sets the TOC depth the same as the headline +levels in the file. Use a lower number for lower TOC depth. To turn +off TOC entirely, use ‘nil’. This is configured in the +‘org-export-with-toc’ variable or as keywords in an Org file as: + + #+OPTIONS: toc:2 only include two levels in TOC + #+OPTIONS: toc:nil no default TOC at all + + To move the table of contents to a different location, first turn off +the default with ‘org-export-with-toc’ variable or with ‘#+OPTIONS: +toc:nil’. Then insert ‘#+TOC: headlines N’ at the desired location(s). + + #+OPTIONS: toc:nil no default TOC + ... + #+TOC: headlines 2 insert TOC here, with two headline levels + + To adjust the TOC depth for a specific section of the Org document, +append an additional ‘local’ parameter. This parameter becomes a +relative depth for the current level. + + Note that for this feature to work properly in LaTeX export, the Org +file requires the inclusion of the ‘titletoc’ package. Because of +compatibility issues, ‘titletoc’ has to be loaded _before_ ‘hyperref’. +Customize the ‘org-latex-default-packages-alist’ variable. + + * Section #+TOC: headlines 1 local insert local TOC, with direct children + only + + Use the ‘TOC’ keyword to generate list of tables (resp. all listings) +with captions. + + #+TOC: listings build a list of listings + #+TOC: tables build a list of tables + + Normally Org uses the headline for its entry in the table of +contents. But with ‘ALT_TITLE’ property, a different entry can be +specified for the table of contents. + + +File: org, Node: Include files, Next: Macro replacement, Prev: Table of contents, Up: Exporting + +12.4 Include files +================== + +Include other files during export. For example, to include your +‘.emacs’ file, you could use: + + #+INCLUDE: "~/.emacs" src emacs-lisp + +The first parameter is the file name to include. The optional second +parameter specifies the block type: ‘example’, ‘export’ or ‘src’. The +optional third parameter specifies the source code language to use for +formatting the contents. This is relevant to both ‘export’ and ‘src’ +block types. + + If an include file is specified as having a markup language, Org +neither checks for valid syntax nor changes the contents in any way. +For ‘example’ and ‘src’ blocks, Org code-escapes the contents before +inclusion. + + If an include file is not specified as having any markup language, +Org assumes it be in Org format and proceeds as usual with a few +exceptions. Org makes the footnote labels (*note Footnotes::) in the +included file local to that file. The contents of the included file +will belong to the same structure—headline, item—containing the +‘INCLUDE’ keyword. In particular, headlines within the file will become +children of the current section. That behavior can be changed by +providing an additional keyword parameter, ‘:minlevel’. It shifts the +headlines in the included file to become the lowest level. For example, +this syntax makes the included file a sibling of the current top-level +headline: + + #+INCLUDE: "~/my-book/chapter2.org" :minlevel 1 + + Inclusion of only portions of files are specified using ranges +parameter with ‘:lines’ keyword. The line at the upper end of the range +will not be included. The start and/or the end of the range may be +omitted to use the obvious defaults. + + #+INCLUDE: "~/.emacs" :lines "5-10" Include lines 5 to 10, 10 excluded + #+INCLUDE: "~/.emacs" :lines "-10" Include lines 1 to 10, 10 excluded + #+INCLUDE: "~/.emacs" :lines "10-" Include lines from 10 to EOF + + Inclusions may specify a file-link to extract an object matched by +‘org-link-search’(1) (*note Search options::). + + To extract only the contents of the matched object, set +‘:only-contents’ property to non-‘nil’. This will omit any planning +lines or property drawers. The ranges for ‘:lines’ keyword are relative +to the requested element. Some examples: + + #+INCLUDE: "./paper.org::#theory" :only-contents t + Include the body of the heading with the custom id ‘theory’ + #+INCLUDE: "./paper.org::mytable" Include named element. + #+INCLUDE: "./paper.org::*conclusion" :lines 1-20 + Include the first 20 lines of the headline named ‘conclusion’. + +‘C-c '’ + Visit the include file at point. + + ---------- Footnotes ---------- + + (1) Note that ‘org-link-search-must-match-exact-headline’ is locally +bound to non-‘nil’. Therefore, ‘org-link-search’ only matches headlines +and named elements. + + +File: org, Node: Macro replacement, Next: Comment lines, Prev: Include files, Up: Exporting + +12.5 Macro replacement +====================== + +Macros replace text snippets during export. Macros are defined globally +in ‘org-export-global-macros’, or document-wise with the following +syntax: + + #+MACRO: name replacement text $1, $2 are arguments + +which can be referenced using ‘{{{name(arg1, arg2)}}}’(1). + + Org recognizes macro references in following Org markup areas: +paragraphs, headlines, verse blocks, tables cells and lists. Org also +recognizes macro references in keywords, such as ‘#+CAPTION’, ‘#+TITLE’, +‘#+AUTHOR’, ‘#+DATE’, and for some back-end specific export options. + + Org comes with following pre-defined macros: + +‘{{{title}}}’ +‘{{{author}}}’ +‘{{{email}}}’ + Org replaces these macro references with available information at + the time of export. + +‘{{{date}}}’ +‘{{{date(FORMAT)}}}’ + This macro refers to the ‘#+DATE’ keyword. FORMAT is an optional + argument to the ‘{{{date}}}’ macro that will be used only if + ‘#+DATE’ is a single timestamp. FORMAT should be a format string + understood by ‘format-time-string’. + +‘{{{time(FORMAT)}}}’ +‘{{{modification-time(FORMAT, VC)}}}’ + These macros refer to the document’s date and time of export and + date and time of modification. FORMAT is a string understood by + ‘format-time-string’. If the second argument to the + ‘modification-time’ macro is non-‘nil’, Org uses ‘vc.el’ to + retrieve the document’s modification time from the version control + system. Otherwise Org reads the file attributes. + +‘{{{input-file}}}’ + This macro refers to the filename of the exported file. + +‘{{{property(PROPERTY-NAME)}}}’ +‘{{{property(PROPERTY-NAME,SEARCH-OPTION)}}}’ + This macro returns the value of property PROPERTY-NAME in the + current entry. If SEARCH-OPTION (*note Search options::) refers to + a remote entry, that will be used instead. + +‘{{{n}}}’ +‘{{{n(NAME)}}}’ +‘{{{n(NAME,ACTION)}}}’ + This macro implements custom counters by returning the number of + times the macro has been expanded so far while exporting the + buffer. You can create more than one counter using different NAME + values. If ACTION is ‘-’, previous value of the counter is held, + i.e. the specified counter is not incremented. If the value is a + number, the specified counter is set to that value. If it is any + other non-empty string, the specified counter is reset to 1. You + may leave NAME empty to reset the default counter. + + The surrounding brackets can be made invisible by setting +‘org-hide-macro-markers’ non-‘nil’. + + Org expands macros at the very beginning of the export process. + + ---------- Footnotes ---------- + + (1) Since commas separate the arguments, commas within arguments have +to be escaped with the backslash character. So only those backslash +characters before a comma need escaping with another backslash +character. + + +File: org, Node: Comment lines, Next: ASCII/Latin-1/UTF-8 export, Prev: Macro replacement, Up: Exporting + +12.6 Comment lines +================== + +Lines starting with zero or more whitespace characters followed by one +‘#’ and a whitespace are treated as comments and, as such, are not +exported. + + Likewise, regions surrounded by ‘#+BEGIN_COMMENT’ ... +‘#+END_COMMENT’ are not exported. + + Finally, a ‘COMMENT’ keyword at the beginning of an entry, but after +any other keyword or priority cookie, comments out the entire subtree. +In this case, the subtree is not exported and no code block within it is +executed either(1). The command below helps changing the comment status +of a headline. + +‘C-c ;’ + Toggle the ‘COMMENT’ keyword at the beginning of an entry. + + ---------- Footnotes ---------- + + (1) For a less drastic behavior, consider using a select tag (*note +Export settings::) instead. + + +File: org, Node: ASCII/Latin-1/UTF-8 export, Next: Beamer export, Prev: Comment lines, Up: Exporting + +12.7 ASCII/Latin-1/UTF-8 export +=============================== + +ASCII export produces an output file containing only plain ASCII +characters. This is the most simplest and direct text output. It does +not contain any Org markup either. Latin-1 and UTF-8 export use +additional characters and symbols available in these encoding standards. +All three of these export formats offer the most basic of text output +for maximum portability. + + On export, Org fills and justifies text according to the text width +set in ‘org-ascii-text-width’. + + Org exports links using a footnote-like style where the descriptive +part is in the text and the link is in a note before the next heading. +See the variable ‘org-ascii-links-to-notes’ for details. + +ASCII export commands +--------------------- + +‘C-c C-e t a/l/u (org-ascii-export-to-ascii)’ + Export as an ASCII file with a ‘.txt’ extension. For ‘myfile.org’, + Org exports to ‘myfile.txt’, overwriting without warning. For + ‘myfile.txt’, Org exports to ‘myfile.txt.txt’ in order to prevent + data loss. +‘C-c C-e t A/L/U (org-ascii-export-as-ascii)’ + Export to a temporary buffer. Does not create a file. + +ASCII specific export settings +------------------------------ + +The ASCII export back-end has one extra keyword for customizing ASCII +output. Setting this keyword works similar to the general options +(*note Export settings::). + +‘SUBTITLE’ + The document subtitle. For long subtitles, use multiple + ‘#+SUBTITLE’ lines in the Org file. Org prints them on one + continuous line, wrapping into multiple lines if necessary. + +Header and sectioning structure +------------------------------- + +Org converts the first three outline levels into headlines for ASCII +export. The remaining levels are turned into lists. To change this +cut-off point where levels become lists, *note Export settings::. + +Quoting ASCII text +------------------ + +To insert text within the Org file by the ASCII back-end, use one the +following constructs, inline, keyword, or export block: + + Inline text @@ascii:and additional text@@ within a paragraph. + + #+ASCII: Some text + + #+BEGIN_EXPORT ascii + Org exports text in this block only when using ASCII back-end. + #+END_EXPORT + +ASCII specific attributes +------------------------- + +ASCII back-end recognizes only one attribute, ‘:width’, which specifies +the width of a horizontal rule in number of characters. The keyword and +syntax for specifying widths is: + + #+ATTR_ASCII: :width 10 + ----- + +ASCII special blocks +-------------------- + +Besides ‘#+BEGIN_CENTER’ blocks (*note Paragraphs::), ASCII back-end has +these two left and right justification blocks: + + #+BEGIN_JUSTIFYLEFT + It's just a jump to the left... + #+END_JUSTIFYLEFT + + #+BEGIN_JUSTIFYRIGHT + ...and then a step to the right. + #+END_JUSTIFYRIGHT + + +File: org, Node: Beamer export, Next: HTML export, Prev: ASCII/Latin-1/UTF-8 export, Up: Exporting + +12.8 Beamer export +================== + +Org uses _Beamer_ export to convert an Org file tree structure into a +high-quality interactive slides for presentations. _Beamer_ is a LaTeX +document class for creating presentations in PDF, HTML, and other +popular display formats. + +* Menu: + +* Beamer export commands:: For creating Beamer documents. +* Beamer specific export settings:: For customizing Beamer export. +* Sectioning Frames and Blocks in Beamer:: For composing Beamer slides. +* Beamer specific syntax:: For using in Org documents. +* Editing support:: For using helper functions. +* A Beamer example:: A complete presentation. + + +File: org, Node: Beamer export commands, Next: Beamer specific export settings, Up: Beamer export + +12.8.1 Beamer export commands +----------------------------- + +‘C-c C-e l b (org-beamer-export-to-latex)’ + Export as LaTeX file with a ‘.tex’ extension. For ‘myfile.org’, + Org exports to ‘myfile.tex’, overwriting without warning. +‘C-c C-e l B (org-beamer-export-as-latex)’ + Export to a temporary buffer. Does not create a file. +‘C-c C-e l P (org-beamer-export-to-pdf)’ + Export as LaTeX file and then convert it to PDF format. +‘C-c C-e l O’ + Export as LaTeX file, convert it to PDF format, and then open the + PDF file. + + +File: org, Node: Beamer specific export settings, Next: Sectioning Frames and Blocks in Beamer, Prev: Beamer export commands, Up: Beamer export + +12.8.2 Beamer specific export settings +-------------------------------------- + +Beamer export back-end has several additional keywords for customizing +Beamer output. These keywords work similar to the general options +settings (*note Export settings::). + +‘BEAMER_THEME’ + The Beamer layout theme (‘org-beamer-theme’). Use square brackets + for options. For example: + #+BEAMER_THEME: Rochester [height=20pt] + +‘BEAMER_FONT_THEME’ + The Beamer font theme. + +‘BEAMER_INNER_THEME’ + The Beamer inner theme. + +‘BEAMER_OUTER_THEME’ + The Beamer outer theme. + +‘BEAMER_HEADER’ + Arbitrary lines inserted in the preamble, just before the + ‘hyperref’ settings. + +‘DESCRIPTION’ + The document description. For long descriptions, use multiple + ‘#+DESCRIPTION’ keywords. By default, ‘hyperref’ inserts + ‘#+DESCRIPTION’ as metadata. Use ‘org-latex-hyperref-template’ to + configure document metadata. Use ‘org-latex-title-command’ to + configure typesetting of description as part of front matter. + +‘KEYWORDS’ + The keywords for defining the contents of the document. Use + multiple ‘#+KEYWORDS’ lines if necessary. By default, ‘hyperref’ + inserts ‘#+KEYWORDS’ as metadata. Use + ‘org-latex-hyperref-template’ to configure document metadata. Use + ‘org-latex-title-command’ to configure typesetting of keywords as + part of front matter. + +‘SUBTITLE’ + Document’s subtitle. For typesetting, use + ‘org-beamer-subtitle-format’ string. Use + ‘org-latex-hyperref-template’ to configure document metadata. Use + ‘org-latex-title-command’ to configure typesetting of subtitle as + part of front matter. + + +File: org, Node: Sectioning Frames and Blocks in Beamer, Next: Beamer specific syntax, Prev: Beamer specific export settings, Up: Beamer export + +12.8.3 Sectioning, Frames and Blocks in Beamer +---------------------------------------------- + +Org transforms heading levels into Beamer’s sectioning elements, frames +and blocks. Any Org tree with a not-too-deep-level nesting should in +principle be exportable as a Beamer presentation. + + − Org headlines become Beamer frames when the heading level in Org is + equal to ‘org-beamer-frame-level’ or ‘H’ value in an ‘OPTIONS’ line + (*note Export settings::). + + Org overrides headlines to frames conversion for the current tree + of an Org file if it encounters the ‘BEAMER_ENV’ property set to + ‘frame’ or ‘fullframe’. Org ignores whatever + ‘org-beamer-frame-level’ happens to be for that headline level in + the Org tree. In Beamer terminology, a ‘fullframe’ is a frame + without its title. + + − Org exports a Beamer frame’s objects as ‘block’ environments. Org + can enforce wrapping in special block types when ‘BEAMER_ENV’ + property is set(1). For valid values see + ‘org-beamer-environments-default’. To add more values, see + ‘org-beamer-environments-extra’. + + − If ‘BEAMER_ENV’ is set to ‘appendix’, Org exports the entry as an + appendix. When set to ‘note’, Org exports the entry as a note + within the frame or between frames, depending on the entry’s + heading level. When set to ‘noteNH’, Org exports the entry as a + note without its title. When set to ‘againframe’, Org exports the + entry with ‘\againframe’ command, which makes setting the + ‘BEAMER_REF’ property mandatory because ‘\againframe’ needs frame + to resume. + + When ‘ignoreheading’ is set, Org export ignores the entry’s + headline but not its content. This is useful for inserting content + between frames. It is also useful for properly closing a ‘column’ + environment. + + When ‘BEAMER_ACT’ is set for a headline, Org export translates that +headline as an overlay or action specification. When enclosed in square +brackets, Org export makes the overlay specification a default. Use +‘BEAMER_OPT’ to set any options applicable to the current Beamer frame +or block. The Beamer export back-end wraps with appropriate angular or +square brackets. It also adds the ‘fragile’ option for any code that +may require a verbatim block. + + To create a column on the Beamer slide, use the ‘BEAMER_COL’ property +for its headline in the Org file. Set the value of ‘BEAMER_COL’ to a +decimal number representing the fraction of the total text width. +Beamer export uses this value to set the column’s width and fills the +column with the contents of the Org entry. If the Org entry has no +specific environment defined, Beamer export ignores the heading. If the +Org entry has a defined environment, Beamer export uses the heading as +title. Behind the scenes, Beamer export automatically handles LaTeX +column separations for contiguous headlines. To manually adjust them +for any unique configurations needs, use the ‘BEAMER_ENV’ property. + + ---------- Footnotes ---------- + + (1) If ‘BEAMER_ENV’ is set, Org export adds ‘:B_environment:’ tag to +make it visible. The tag serves as a visual aid and has no semantic +relevance. + + +File: org, Node: Beamer specific syntax, Next: Editing support, Prev: Sectioning Frames and Blocks in Beamer, Up: Beamer export + +12.8.4 Beamer specific syntax +----------------------------- + +Since Org’s Beamer export back-end is an extension of the LaTeX +back-end, it recognizes other LaTeX specific syntax—for example, +‘#+LATEX:’ or ‘#+ATTR_LATEX:’. *Note LaTeX export::, for details. + + Beamer export wraps the table of contents generated with ‘toc:t’ +‘OPTION’ keyword in a ‘frame’ environment. Beamer export does not wrap +the table of contents generated with ‘TOC’ keyword (*note Table of +contents::). Use square brackets for specifying options. + + #+TOC: headlines [currentsection] + + Insert Beamer-specific code using the following constructs: + + #+BEAMER: \pause + + #+BEGIN_EXPORT beamer + Only Beamer export back-end will export this line. + #+END_BEAMER + + Text @@beamer:some code@@ within a paragraph. + + Inline constructs, such as the last one above, are useful for adding +overlay specifications to objects with ‘bold’, ‘item’, ‘link’, +‘radio-target’ and ‘target’ types. Enclose the value in angular +brackets and place the specification at the beginning the object as +shown in this example: + + A *@@beamer:<2->@@useful* feature + + Beamer export recognizes the ‘ATTR_BEAMER’ keyword with the following +attributes from Beamer configurations: ‘:environment’ for changing local +Beamer environment, ‘:overlay’ for specifying Beamer overlays in angular +or square brackets, and ‘:options’ for inserting optional arguments. + + #+ATTR_BEAMER: :environment nonindentlist + - item 1, not indented + - item 2, not indented + - item 3, not indented + + #+ATTR_BEAMER: :overlay <+-> + - item 1 + - item 2 + + #+ATTR_BEAMER: :options [Lagrange] + Let $G$ be a finite group, and let $H$ be + a subgroup of $G$. Then the order of $H$ divides the order of $G$. + + +File: org, Node: Editing support, Next: A Beamer example, Prev: Beamer specific syntax, Up: Beamer export + +12.8.5 Editing support +---------------------- + +The ‘org-beamer-mode’ is a special minor mode for faster editing of +Beamer documents. + + #+STARTUP: beamer + +‘C-c C-b (org-beamer-select-environment)’ + The ‘org-beamer-mode’ provides this key for quicker selections in + Beamer normal environments, and for selecting the ‘BEAMER_COL’ + property. + + +File: org, Node: A Beamer example, Prev: Editing support, Up: Beamer export + +12.8.6 A Beamer example +----------------------- + +Here is an example of an Org document ready for Beamer export. + + #+TITLE: Example Presentation + #+AUTHOR: Carsten Dominik + #+OPTIONS: H:2 toc:t num:t + #+LATEX_CLASS: beamer + #+LATEX_CLASS_OPTIONS: [presentation] + #+BEAMER_THEME: Madrid + #+COLUMNS: %45ITEM %10BEAMER_ENV(Env) %10BEAMER_ACT(Act) %4BEAMER_COL(Col) %8BEAMER_OPT(Opt) + + * This is the first structural section + + ** Frame 1 + *** Thanks to Eric Fraga :B_block: + :PROPERTIES: + :BEAMER_COL: 0.48 + :BEAMER_ENV: block + :END: + for the first viable Beamer setup in Org + *** Thanks to everyone else :B_block: + :PROPERTIES: + :BEAMER_COL: 0.48 + :BEAMER_ACT: <2-> + :BEAMER_ENV: block + :END: + for contributing to the discussion + **** This will be formatted as a beamer note :B_note: + :PROPERTIES: + :BEAMER_env: note + :END: + ** Frame 2 (where we will not use columns) + *** Request + Please test this stuff! + + +File: org, Node: HTML export, Next: LaTeX export, Prev: Beamer export, Up: Exporting + +12.9 HTML export +================ + +Org mode contains an HTML exporter with extensive HTML formatting +compatible with XHTML 1.0 strict standard. + +* Menu: + +* HTML Export commands:: Invoking HTML export +* HTML Specific export settings:: Settings for HTML export +* HTML doctypes:: Exporting various (X)HTML flavors +* HTML preamble and postamble:: Inserting preamble and postamble +* Quoting HTML tags:: Using direct HTML in Org files +* Links in HTML export:: Interpreting and formatting links +* Tables in HTML export:: Formatting and modifying tables +* Images in HTML export:: Inserting figures with HTML output +* Math formatting in HTML export:: Handling math equations +* Text areas in HTML export:: Showing an alternate approach, an example +* CSS support:: Styling HTML output +* JavaScript support:: Folding scripting in the web browser + + +File: org, Node: HTML Export commands, Next: HTML Specific export settings, Up: HTML export + +12.9.1 HTML export commands +--------------------------- + +‘C-c C-e h h (org-html-export-to-html)’ + Export as HTML file with a ‘.html’ extension. For ‘myfile.org’, + Org exports to ‘myfile.html’, overwriting without warning. ‘C-c + C-e h o’ Exports to HTML and opens it in a web browser. + +‘C-c C-e h H (org-html-export-as-html)’ + Exports to a temporary buffer. Does not create a file. + + +File: org, Node: HTML Specific export settings, Next: HTML doctypes, Prev: HTML Export commands, Up: HTML export + +12.9.2 HTML Specific export settings +------------------------------------ + +HTML export has a number of keywords, similar to the general options +settings described in *note Export settings::. + +‘DESCRIPTION’ + This is the document’s description, which the HTML exporter inserts + it as a HTML meta tag in the HTML file. For long descriptions, use + multiple ‘#+DESCRIPTION’ lines. The exporter takes care of + wrapping the lines properly. + +‘HTML_DOCTYPE’ + Specify the document type, for example: HTML5 (‘org-html-doctype’). + +‘HTML_CONTAINER’ + Specify the HTML container, such as ‘div’, for wrapping sections + and elements (‘org-html-container-element’). + +‘HTML_LINK_HOME’ + The URL for home link (‘org-html-link-home’). + +‘HTML_LINK_UP’ + The URL for the up link of exported HTML pages + (‘org-html-link-up’). + +‘HTML_MATHJAX’ + Options for MathJax (‘org-html-mathjax-options’). MathJax is used + to typeset LaTeX math in HTML documents. *Note Math formatting in + HTML export::, for an example. + +‘HTML_HEAD’ + Arbitrary lines for appending to the HTML document’s head + (‘org-html-head’). + +‘HTML_HEAD_EXTRA’ + More arbitrary lines for appending to the HTML document’s head + (‘org-html-head-extra’). + +‘KEYWORDS’ + Keywords to describe the document’s content. HTML exporter inserts + these keywords as HTML meta tags. For long keywords, use multiple + ‘#+KEYWORDS’ lines. + +‘LATEX_HEADER’ + Arbitrary lines for appending to the preamble; HTML exporter + appends when transcoding LaTeX fragments to images (*note Math + formatting in HTML export::). + +‘SUBTITLE’ + The document’s subtitle. HTML exporter formats subtitle if + document type is ‘HTML5’ and the CSS has a ‘subtitle’ class. + + Some of these keywords are explained in more detail in the following +sections of the manual. + + +File: org, Node: HTML doctypes, Next: HTML preamble and postamble, Prev: HTML Specific export settings, Up: HTML export + +12.9.3 HTML doctypes +-------------------- + +Org can export to various (X)HTML flavors. + + Set the ‘org-html-doctype’ variable for different (X)HTML variants. +Depending on the variant, the HTML exporter adjusts the syntax of HTML +conversion accordingly. Org includes the following ready-made variants: + + • “html4-strict” + • “html4-transitional” + • “html4-frameset” + • “xhtml-strict” + • “xhtml-transitional” + • “xhtml-frameset” + • “xhtml-11” + • “html5” + • “xhtml5” + +See the variable ‘org-html-doctype-alist’ for details. The default is +“xhtml-strict”. + + Org’s HTML exporter does not by default enable new block elements +introduced with the HTML5 standard. To enable them, set +‘org-html-html5-fancy’ to non-‘nil’. Or use an ‘OPTIONS’ line in the +file to set ‘html5-fancy’. HTML5 documents can now have arbitrary +‘#+BEGIN’ and ‘#+END’ blocks. For example: + + #+BEGIN_aside + Lorem ipsum + #+END_aside + + Will export to: + + + + While this: + + #+ATTR_HTML: :controls controls :width 350 + #+BEGIN_video + #+HTML: + #+HTML: + Your browser does not support the video tag. + #+END_video + + Exports to: + + + + When special blocks do not have a corresponding HTML5 element, the +HTML exporter reverts to standard translation (see +‘org-html-html5-elements’). For example, ‘#+BEGIN_lederhosen’ exports +to ‘
’. + + Special blocks cannot have headlines. For the HTML exporter to wrap +the headline and its contents in ‘
’ or ‘
’ tags, set +the ‘HTML_CONTAINER’ property for the headline. + + +File: org, Node: HTML preamble and postamble, Next: Quoting HTML tags, Prev: HTML doctypes, Up: HTML export + +12.9.4 HTML preamble and postamble +---------------------------------- + +The HTML exporter has delineations for preamble and postamble. The +default value for ‘org-html-preamble’ is ‘t’, which makes the HTML +exporter insert the preamble. See the variable +‘org-html-preamble-format’ for the format string. + + Set ‘org-html-preamble’ to a string to override the default format +string. If the string is a function, the HTML exporter expects the +function to return a string upon execution. The HTML exporter inserts +this string in the preamble. The HTML exporter will not insert a +preamble if ‘org-html-preamble’ is set ‘nil’. + + The default value for ‘org-html-postamble’ is ‘auto’, which makes the +HTML exporter build a postamble from looking up author’s name, email +address, creator’s name, and date. Set ‘org-html-postamble’ to ‘t’ to +insert the postamble in the format specified in the +‘org-html-postamble-format’ variable. The HTML exporter will not insert +a postamble if ‘org-html-postamble’ is set to ‘nil’. + + +File: org, Node: Quoting HTML tags, Next: Links in HTML export, Prev: HTML preamble and postamble, Up: HTML export + +12.9.5 Quoting HTML tags +------------------------ + +The HTML export back-end transforms ‘<’ and ‘>’ to ‘<’ and ‘>’. +To include raw HTML code in the Org file so the HTML export back-end can +insert that HTML code in the output, use this inline syntax: ‘@@html:’. +For example: ‘@@html:@@bold text@@html:@@’. For larger raw HTML +code blocks, use these HTML export code blocks: + + #+HTML: Literal HTML code for export + +or + + #+BEGIN_EXPORT html + All lines between these markers are exported literally + #+END_EXPORT + + +File: org, Node: Links in HTML export, Next: Tables in HTML export, Prev: Quoting HTML tags, Up: HTML export + +12.9.6 Links in HTML export +--------------------------- + +The HTML export back-end transforms Org’s internal links (*note Internal +links::) to equivalent HTML links in the output. The back-end similarly +handles Org’s automatic links created by radio targets (*note Radio +targets::) similarly. For Org links to external files, the back-end +transforms the links to _relative_ paths. + + For Org links to other ‘.org’ files, the back-end automatically +changes the file extension to ‘.html’ and makes file paths relative. If +the ‘.org’ files have an equivalent ‘.html’ version at the same +location, then the converted links should work without any further +manual intervention. However, to disable this automatic path +translation, set ‘org-html-link-org-files-as-html’ to ‘nil’. When +disabled, the HTML export back-end substitutes the ‘id:’-based links in +the HTML output. For more about linking files when publishing to a +directory, *note Publishing links::. + + Org files can also have special directives to the HTML export +back-end. For example, by using ‘#+ATTR_HTML’ lines to specify new +format attributes to ‘’ or ‘’ tags. This example shows changing +the link’s ‘title’ and ‘style’: + + #+ATTR_HTML: :title The Org mode homepage :style color:red; + [[https://orgmode.org]] + + +File: org, Node: Tables in HTML export, Next: Images in HTML export, Prev: Links in HTML export, Up: HTML export + +12.9.7 Tables in HTML export +---------------------------- + +The HTML export back-end uses ‘org-html-table-default-attributes’ when +exporting Org tables to HTML. By default, the exporter does not draw +frames and cell borders. To change for this for a table, use the +following lines before the table in the Org file: + + #+CAPTION: This is a table with lines around and between cells + #+ATTR_HTML: :border 2 :rules all :frame border + + The HTML export back-end preserves column groupings in Org tables +(*note Column groups::) when exporting to HTML. + + Additional options for customizing tables for HTML export. + +‘org-html-table-align-individual-fields’ + Non-‘nil’ attaches style attributes for alignment to each table + field. + +‘org-html-table-caption-above’ + Non-‘nil’ places caption string at the beginning of the table. + +‘org-html-table-data-tags’ + Opening and ending tags for table data fields. + +‘org-html-table-default-attributes’ + Default attributes and values for table tags. + +‘org-html-table-header-tags’ + Opening and ending tags for table’s header fields. + +‘org-html-table-row-tags’ + Opening and ending tags for table rows. + +‘org-html-table-use-header-tags-for-first-column’ + Non-‘nil’ formats column one in tables with header tags. + + +File: org, Node: Images in HTML export, Next: Math formatting in HTML export, Prev: Tables in HTML export, Up: HTML export + +12.9.8 Images in HTML export +---------------------------- + +The HTML export back-end has features to convert Org image links to HTML +inline images and HTML clickable image links. + + When the link in the Org file has no description, the HTML export +back-end by default in-lines that image. For example: +‘[[file:myimg.jpg]]’ is in-lined, while ‘[[file:myimg.jpg][the image]]’ +links to the text, ‘the image’. + + For more details, see the variable ‘org-html-inline-images’. + + On the other hand, if the description part of the Org link is itself +another link, such as ‘file:’ or ‘http:’ URL pointing to an image, the +HTML export back-end in-lines this image and links to the main image. +This Org syntax enables the back-end to link low-resolution thumbnail to +the high-resolution version of the image, as shown in this example: + + [[file:highres.jpg][file:thumb.jpg]] + + To change attributes of in-lined images, use ‘#+ATTR_HTML’ lines in +the Org file. This example shows realignment to right, and adds ‘alt’ +and ‘title’ attributes in support of text viewers and modern web +accessibility standards. + + #+CAPTION: A black cat stalking a spider + #+ATTR_HTML: :alt cat/spider image :title Action! :align right + [[./img/a.jpg]] + +The HTML export back-end copies the ‘http’ links from the Org file as +is. + + +File: org, Node: Math formatting in HTML export, Next: Text areas in HTML export, Prev: Images in HTML export, Up: HTML export + +12.9.9 Math formatting in HTML export +------------------------------------- + +LaTeX math snippets (*note LaTeX fragments::) can be displayed in two +different ways on HTML pages. The default is to use MathJax +(http://www.mathjax.org) which should work out of the box with Org(1). +Some MathJax display options can be configured via +‘org-html-mathjax-options’, or in the buffer. For example, with the +following settings, + #+HTML_MATHJAX: align: left indent: 5em tagside: left font: Neo-Euler + equation labels will be displayed on the left margin and equations +will be five ems from the left margin. + +See the docstring of ‘org-html-mathjax-options’ for all supported +variables. The MathJax template can be configure via +‘org-html-mathjax-template’. + + If you prefer, you can also request that LaTeX fragments are +processed into small images that will be inserted into the browser page. +Before the availability of MathJax, this was the default method for Org +files. This method requires that the ‘dvipng’ program, ‘dvisvgm’ or +‘imagemagick’ suite is available on your system. You can still get this +processing with + + #+OPTIONS: tex:dvipng + + #+OPTIONS: tex:dvisvgm + + or: + + #+OPTIONS: tex:imagemagick + + ---------- Footnotes ---------- + + (1) By default Org loads MathJax from cdnjs.com (https://cdnjs.com) +as recommended by MathJax (http://www.mathjax.org). + + +File: org, Node: Text areas in HTML export, Next: CSS support, Prev: Math formatting in HTML export, Up: HTML export + +12.9.10 Text areas in HTML export +--------------------------------- + +Before Org mode’s Babel, one popular approach to publishing code in HTML +was by using ‘:textarea’. The advantage of this approach was that +copying and pasting was built into browsers with simple JavaScript +commands. Even editing before pasting was made simple. + + The HTML export back-end can create such text areas. It requires an +‘#+ATTR_HTML:’ line as shown in the example below with the ‘:textarea’ +option. This must be followed by either an ‘example’ or a ‘src’ code +block. Other Org block types will not honor the ‘:textarea’ option. + + By default, the HTML export back-end creates a text area 80 +characters wide and height just enough to fit the content. Override +these defaults with ‘:width’ and ‘:height’ options on the ‘#+ATTR_HTML:’ +line. + + #+ATTR_HTML: :textarea t :width 40 + #+BEGIN_EXAMPLE + (defun org-xor (a b) + "Exclusive or." + (if a (not b) b)) + #+END_EXAMPLE + + +File: org, Node: CSS support, Next: JavaScript support, Prev: Text areas in HTML export, Up: HTML export + +12.9.11 CSS support +------------------- + +You can modify the CSS style definitions for the exported file. The +HTML exporter assigns the following special CSS classes(1) to +appropriate parts of the document—your style specifications may change +these, in addition to any of the standard classes like for headlines, +tables, etc. + p.author author information, including email + p.date publishing date + p.creator creator info, about org mode version + .title document title + .subtitle document subtitle + .todo TODO keywords, all not-done states + .done the DONE keywords, all states that count as done + .WAITING each TODO keyword also uses a class named after itself + .timestamp timestamp + .timestamp-kwd keyword associated with a timestamp, like ‘SCHEDULED’ + .timestamp-wrapper span around keyword plus timestamp + .tag tag in a headline + ._HOME each tag uses itself as a class, "@" replaced by "_" + .target target for links + .linenr the line number in a code example + .code-highlighted for highlighting referenced code lines + div.outline-N div for outline level N (headline plus text)) + div.outline-text-N extra div for text at outline level N + .section-number-N section number in headlines, different for each level + .figure-number label like "Figure 1:" + .table-number label like "Table 1:" + .listing-number label like "Listing 1:" + div.figure how to format an in-lined image + pre.src formatted source code + pre.example normal example + p.verse verse paragraph + div.footnotes footnote section headline + p.footnote footnote definition paragraph, containing a footnote + .footref a footnote reference number (always a ) + .footnum footnote number in footnote definition (always ) + .org-svg default class for a linked ‘.svg’ image + + The HTML export back-end includes a compact default style in each +exported HTML file. To override the default style with another style, +use these keywords in the Org file. They will replace the global +defaults the HTML exporter uses. + + #+HTML_HEAD: + #+HTML_HEAD_EXTRA: + + To just turn off the default style, customize +‘org-html-head-include-default-style’ variable, or use this option line +in the Org file. + + #+OPTIONS: html-style:nil + +For longer style definitions, either use several ‘#+HTML_HEAD’ and +‘#+HTML_HEAD_EXTRA’ lines, or use ‘’ blocks around +them. Both of these approaches can avoid referring to an external file. + + In order to add styles to a sub-tree, use the +‘:HTML_CONTAINER_CLASS:’ property to assign a class to the tree. In +order to specify CSS styles for a particular headline, you can use the +id specified in a ‘:CUSTOM_ID:’ property. + + Never change the ‘org-html-style-default’ constant. Instead use +other simpler ways of customizing as described above. + + ---------- Footnotes ---------- + + (1) If the classes on TODO keywords and tags lead to conflicts, use +the variables ‘org-html-todo-kwd-class-prefix’ and +‘org-html-tag-class-prefix’ to make them unique. + + +File: org, Node: JavaScript support, Prev: CSS support, Up: HTML export + +12.9.12 JavaScript supported display of web pages +------------------------------------------------- + +Sebastian Rose has written a JavaScript program especially designed to +enhance the web viewing experience of HTML files created with Org. This +program enhances large files in two different ways of viewing. One is +an _Info_-like mode where each section is displayed separately and +navigation can be done with the ‘n’ and ‘p’ keys (and some other keys as +well, press ‘?’ for an overview of the available keys). The second one +has a _folding_ view, much like Org provides inside Emacs. The script +is available at and the documentation +at . The script is hosted +on , but for reliability, prefer installing it on +your own web server. + + To use this program, just add this line to the Org file: + + #+INFOJS_OPT: view:info toc:nil + +The HTML header now has the code needed to automatically invoke the +script. For setting options, use the syntax from the above line for +options described below: + + path: The path to the script. The default grabs the script from + , but you might want to have + a local copy and use a path like ‘../scripts/org-info.js’. + view: Initial view when the website is first shown. Possible values are: + info Info-like interface with one section per page. + overview Folding interface, initially showing only top-level. + content Folding interface, starting with all headlines visible. + showall Folding interface, all headlines and text visible. + sdepth: Maximum headline level that will still become an independent + section for info and folding modes. The default is taken from + ‘org-export-headline-levels’ (= the ‘H’ switch in ‘#+OPTIONS’). + If this is smaller than in ‘org-export-headline-levels’, each + info/folding section can still contain child headlines. + toc: Should the table of contents _initially_ be visible? + Even when ‘nil’, you can always get to the "toc" with ‘i’. + tdepth: The depth of the table of contents. The defaults are taken from + the variables ‘org-export-headline-levels’ and ‘org-export-with-toc’. + ftoc: Does the CSS of the page specify a fixed position for the "toc"? + If yes, the toc will never be displayed as a section. + ltoc: Should there be short contents (children) in each section? + Make this ‘above’ if the section should be above initial text. + mouse: Headings are highlighted when the mouse is over them. Should be + ‘underline’ (default) or a background color like ‘#cccccc’. + buttons: Should view-toggle buttons be everywhere? When ‘nil’ (the + default), only one such button will be present. +You can choose default values for these options by customizing the +variable ‘org-html-infojs-options’. If you want the script to always +apply to your pages, configure the variable ‘org-html-use-infojs’. + + +File: org, Node: LaTeX export, Next: Markdown export, Prev: HTML export, Up: Exporting + +12.10 LaTeX export +================== + +The LaTeX export back-end can handle complex documents, incorporate +standard or custom LaTeX document classes, generate documents using +alternate LaTeX engines, and produce fully linked PDF files with +indexes, bibliographies, and tables of contents, destined for +interactive online viewing or high-quality print publication. + + While the details are covered in-depth in this section, here are some +quick references to variables for the impatient: for engines, see +‘org-latex-compiler’; for build sequences, see ‘org-latex-pdf-process’; +for packages, see ‘org-latex-default-packages-alist’ and +‘org-latex-packages-alist’. + + An important note about the LaTeX export back-end: it is sensitive to +blank lines in the Org document. That’s because LaTeX itself depends on +blank lines to tell apart syntactical elements, such as paragraphs. + +* Menu: + +* LaTeX export commands:: For producing LaTeX and PDF documents. +* LaTeX specific export settings:: Unique to this LaTeX back-end. +* LaTeX header and sectioning:: For file structure. +* Quoting LaTeX code:: Directly in the Org document. +* Tables in LaTeX export:: Attributes specific to tables. +* Images in LaTeX export:: Attributes specific to images. +* Plain lists in LaTeX export:: Attributes specific to lists. +* Source blocks in LaTeX export:: Attributes specific to source code blocks. +* Example blocks in LaTeX export:: Attributes specific to example blocks. +* Special blocks in LaTeX export:: Attributes specific to special blocks. +* Horizontal rules in LaTeX export:: Attributes specific to horizontal rules. + + +File: org, Node: LaTeX export commands, Next: LaTeX specific export settings, Up: LaTeX export + +12.10.1 LaTeX export commands +----------------------------- + +‘C-c C-e l l (org-latex-export-to-latex)’ + Export as LaTeX file with a ‘.tex’ extension. For ‘myfile.org’, + Org exports to ‘myfile.tex’, overwriting without warning. ‘C-c C-e + l l’ Exports to LaTeX file. + +‘C-c C-e l L (org-latex-export-as-latex)’ + Export to a temporary buffer. Do not create a file. +‘C-c C-e l p (org-latex-export-to-pdf)’ + Export as LaTeX file and convert it to PDF file. +‘C-c C-e l o’ + Export as LaTeX file and convert it to PDF, then open the PDF using + the default viewer. + + The LaTeX export back-end can use any of these LaTeX engines: +‘pdflatex’, ‘xelatex’, and ‘lualatex’. These engines compile LaTeX +files with different compilers, packages, and output options. The LaTeX +export back-end finds the compiler version to use from +‘org-latex-compiler’ variable or the ‘#+LATEX_COMPILER’ keyword in the +Org file. See the docstring for the ‘org-latex-default-packages-alist’ +for loading packages with certain compilers. Also see +‘org-latex-bibtex-compiler’ to set the bibliography compiler(1). + + ---------- Footnotes ---------- + + (1) This does not allow setting different bibliography compilers for +different files. However, “smart” LaTeX compilation systems, such as +‘latexmk’, can select the correct bibliography compiler. + + +File: org, Node: LaTeX specific export settings, Next: LaTeX header and sectioning, Prev: LaTeX export commands, Up: LaTeX export + +12.10.2 LaTeX specific export settings +-------------------------------------- + +The LaTeX export back-end has several additional keywords for +customizing LaTeX output. Setting these keywords works similar to the +general options (*note Export settings::). + +‘DESCRIPTION’ + The document’s description. The description along with author + name, keywords, and related file metadata are inserted in the + output file by the ‘hyperref’ package. See + ‘org-latex-hyperref-template’ for customizing metadata items. See + ‘org-latex-title-command’ for typesetting description into the + document’s front matter. Use multiple ‘#+DESCRIPTION’ lines for + long descriptions. + +‘LATEX_CLASS’ + This is LaTeX document class, such as ‘article’, ‘report’, ‘book’, + and so on, which contain predefined preamble and headline level + mapping that the LaTeX export back-end needs. The back-end reads + the default class name from the ‘org-latex-default-class’ variable. + Org has ‘article’ as the default class. A valid default class must + be an element of ‘org-latex-classes’. + +‘LATEX_CLASS_OPTIONS’ + Options the LaTeX export back-end uses when calling the LaTeX + document class. + +‘LATEX_COMPILER’ + The compiler, such as ‘pdflatex’, ‘xelatex’, ‘lualatex’, for + producing the PDF (‘org-latex-compiler’). + +‘LATEX_HEADER’ + Arbitrary lines to add to the document’s preamble, before the + ‘hyperref’ settings. See ‘org-latex-classes’ for adjusting the + structure and order of the LaTeX headers. + +‘LATEX_HEADER_EXTRA’ + Arbitrary lines to add to the document’s preamble, before the + ‘hyperref’ settings. See ‘org-latex-classes’ for adjusting the + structure and order of the LaTeX headers. + +‘KEYWORDS’ + The keywords for the document. The description along with author + name, keywords, and related file metadata are inserted in the + output file by the ‘hyperref’ package. See + ‘org-latex-hyperref-template’ for customizing metadata items. See + ‘org-latex-title-command’ for typesetting description into the + document’s front matter. Use multiple ‘#+KEYWORDS’ lines if + necessary. + +‘SUBTITLE’ + The document’s subtitle. It is typeset as per + ‘org-latex-subtitle-format’. If ‘org-latex-subtitle-separate’ is + non-‘nil’, it is typed as part of the ‘\title’-macro. See + ‘org-latex-hyperref-template’ for customizing metadata items. See + ‘org-latex-title-command’ for typesetting description into the + document’s front matter. + + The following sections have further details. + + +File: org, Node: LaTeX header and sectioning, Next: Quoting LaTeX code, Prev: LaTeX specific export settings, Up: LaTeX export + +12.10.3 LaTeX header and sectioning structure +--------------------------------------------- + +The LaTeX export back-end converts the first three of Org’s outline +levels into LaTeX headlines. The remaining Org levels are exported as +‘itemize’ or ‘enumerate’ lists. To change this globally for the cut-off +point between levels and lists, (*note Export settings::). + + By default, the LaTeX export back-end uses the ‘article’ class. + + To change the default class globally, edit ‘org-latex-default-class’. +To change the default class locally in an Org file, add option lines +‘#+LATEX_CLASS: myclass’. To change the default class for just a part +of the Org file, set a sub-tree property, ‘EXPORT_LATEX_CLASS’. The +class name entered here must be valid member of ‘org-latex-classes’. +This variable defines a header template for each class into which the +exporter splices the values of ‘org-latex-default-packages-alist’ and +‘org-latex-packages-alist’. Use the same three variables to define +custom sectioning or custom classes. + + The LaTeX export back-end sends the ‘LATEX_CLASS_OPTIONS’ keyword and +‘EXPORT_LATEX_CLASS_OPTIONS’ property as options to the LaTeX +‘\documentclass’ macro. The options and the syntax for specifying them, +including enclosing them in square brackets, follow LaTeX conventions. + + #+LATEX_CLASS_OPTIONS: [a4paper,11pt,twoside,twocolumn] + + The LaTeX export back-end appends values from ‘LATEX_HEADER’ and +‘LATEX_HEADER_EXTRA’ keywords to the LaTeX header. The docstring for +‘org-latex-classes’ explains in more detail. Also note that LaTeX +export back-end does not append ‘LATEX_HEADER_EXTRA’ to the header when +previewing LaTeX snippets (*note Previewing LaTeX fragments::). + + A sample Org file with the above headers: + + #+LATEX_CLASS: article + #+LATEX_CLASS_OPTIONS: [a4paper] + #+LATEX_HEADER: \usepackage{xyz} + + * Headline 1 + some text + * Headline 2 + some more text + + +File: org, Node: Quoting LaTeX code, Next: Tables in LaTeX export, Prev: LaTeX header and sectioning, Up: LaTeX export + +12.10.4 Quoting LaTeX code +-------------------------- + +The LaTeX export back-end can insert any arbitrary LaTeX code, *note +Embedded LaTeX::. There are three ways to embed such code in the Org +file and they all use different quoting syntax. + + Inserting in-line quoted with symbols: + Code embedded in-line @@latex:any arbitrary LaTeX code@@ in a paragraph. + + Inserting as one or more keyword lines in the Org file: + #+LATEX: any arbitrary LaTeX code + + Inserting as an export block in the Org file, where the back-end +exports any code between begin and end markers: + #+BEGIN_EXPORT latex + any arbitrary LaTeX code + #+END_EXPORT + + +File: org, Node: Tables in LaTeX export, Next: Images in LaTeX export, Prev: Quoting LaTeX code, Up: LaTeX export + +12.10.5 Tables in LaTeX export +------------------------------ + +The LaTeX export back-end can pass several LaTeX attributes for table +contents and layout. Besides specifying label and caption (*note Images +and tables::), the other valid LaTeX attributes include: + +‘:mode’ + The LaTeX export back-end wraps the table differently depending on + the mode for accurate rendering of math symbols. Mode is either + ‘table’, ‘math’, ‘inline-math’ or ‘verbatim’. For ‘math’ or + ‘inline-math’ mode, LaTeX export back-end wraps the table in a math + environment, but every cell in it is exported as-is. The LaTeX + export back-end determines the default mode from + ‘org-latex-default-table-mode’. For , The LaTeX export back-end + merges contiguous tables in the same mode into a single + environment. +‘:environment’ + Set the default LaTeX table environment for the LaTeX export + back-end to use when exporting Org tables. Common LaTeX table + environments are provided by these packages: ‘tabularx’, + ‘longtable’, ‘array’, ‘tabu’, and ‘bmatrix’. For packages, such as + ‘tabularx’ and ‘tabu’, or any newer replacements, include them in + the ‘org-latex-packages-alist’ variable so the LaTeX export + back-end can insert the appropriate load package headers in the + converted LaTeX file. Look in the docstring for the + ‘org-latex-packages-alist’ variable for configuring these packages + for LaTeX snippet previews, if any. +‘:caption’ + Use ‘#+CAPTION’ keyword to set a simple caption for a table (*note + Images and tables::). For custom captions, use ‘:caption’ + attribute, which accepts raw LaTeX code. ‘:caption’ value + overrides ‘#+CAPTION’ value. +‘:float’ +‘:placement’ + The table environments by default are not floats in LaTeX. To make + them floating objects use ‘:float’ with one of the following + options: ‘sideways’, ‘multicolumn’, ‘t’, and ‘nil’. Note that + ‘sidewaystable’ has been deprecated since Org 8.3. LaTeX floats + can also have additional layout ‘:placement’ attributes. These are + the usual ‘[h t b p ! H]’ permissions specified in square brackets. + Note that for ‘:float sideways’ tables, the LaTeX export back-end + ignores ‘:placement’ attributes. +‘:align’ +‘:font’ +‘:width’ + The LaTeX export back-end uses these attributes for regular tables + to set their alignments, fonts, and widths. +‘:spread’ + When ‘:spread’ is non-‘nil’, the LaTeX export back-end spreads or + shrinks the table by the ‘:width’ for ‘tabu’ and ‘longtabu’ + environments. ‘:spread’ has no effect if ‘:width’ is not set. +‘:booktabs’ +‘:center’ +‘:rmlines’ + All three commands are toggles. ‘:booktabs’ brings in modern + typesetting enhancements to regular tables. The ‘booktabs’ package + has to be loaded through ‘org-latex-packages-alist’. ‘:center’ is + for centering the table. ‘:rmlines’ removes all but the very first + horizontal line made of ASCII characters from "table.el" tables + only. +‘:math-prefix’ +‘:math-suffix’ +‘:math-arguments’ + The LaTeX export back-end inserts ‘:math-prefix’ string value in a + math environment before the table. The LaTeX export back-end + inserts ‘:math-suffix’ string value in a math environment after the + table. The LaTeX export back-end inserts ‘:math-arguments’ string + value between the macro name and the table’s contents. + ‘:math-arguments’ comes in use for matrix macros that require more + than one argument, such as ‘qbordermatrix’. + + LaTeX table attributes help formatting tables for a wide range of +situations, such as matrix product or spanning multiple pages: + + #+ATTR_LATEX: :environment longtable :align l|lp{3cm}r|l + | ..... | ..... | + | ..... | ..... | + + #+ATTR_LATEX: :mode math :environment bmatrix :math-suffix \times + | a | b | + | c | d | + #+ATTR_LATEX: :mode math :environment bmatrix + | 1 | 2 | + | 3 | 4 | + + Set the caption with the LaTeX command +‘\bicaption{HeadingA}{HeadingB}’: + + #+ATTR_LATEX: :caption \bicaption{HeadingA}{HeadingB} + | ..... | ..... | + | ..... | ..... | + + +File: org, Node: Images in LaTeX export, Next: Plain lists in LaTeX export, Prev: Tables in LaTeX export, Up: LaTeX export + +12.10.6 Images in LaTeX export +------------------------------ + +The LaTeX export back-end processes image links in Org files that do not +have descriptions, such as these links ‘[[file:img.jpg]]’ or +‘[[./img.jpg]]’, as direct image insertions in the final PDF output. In +the PDF, they are no longer links but actual images embedded on the +page. The LaTeX export back-end uses ‘\includegraphics’ macro to insert +the image. But for TikZ(1) images, the back-end uses an ‘\input’ macro +wrapped within a ‘tikzpicture’ environment. + + For specifying image ‘:width’, ‘:height’, and other ‘:options’, use +this syntax: + + #+ATTR_LATEX: :width 5cm :options angle=90 + [[./img/sed-hr4049.pdf]] + + For custom commands for captions, use the ‘:caption’ attribute. It +will override the default ‘#+CAPTION’ value: + + #+ATTR_LATEX: :caption \bicaption{HeadingA}{HeadingB} + [[./img/sed-hr4049.pdf]] + + When captions follow the method as described in *note Images and +tables::, the LaTeX export back-end wraps the picture in a floating +‘figure’ environment. To float an image without specifying a caption, +set the ‘:float’ attribute to one of the following: + − ‘t’: for a standard ‘figure’ environment; used by default whenever + an image has a caption. + − ‘multicolumn’: to span the image across multiple columns of a page; + the back-end wraps the image in a ‘figure*’ environment. + − ‘wrap’: for text to flow around the image on the right; the figure + occupies the left half of the page. + − ‘sideways’: for a new page with the image sideways, rotated ninety + degrees, in a ‘sidewaysfigure’ environment; overrides ‘:placement’ + setting. + − ‘nil’: to avoid a ‘:float’ even if using a caption. +Use the ‘placement’ attribute to modify a floating environment’s +placement. + + #+ATTR_LATEX: :float wrap :width 0.38\textwidth :placement + {r}{0.4\textwidth} [[./img/hst.png]] + + The LaTeX export back-end centers all images by default. Setting +‘:center’ attribute to ‘nil’ disables centering. To disable centering +globally, set ‘org-latex-images-centered’ to ‘t’. + + Set the ‘:comment-include’ attribute to non-‘nil’ value for the LaTeX +export back-end to comment out the ‘\includegraphics’ macro. + + ---------- Footnotes ---------- + + (1) + + +File: org, Node: Plain lists in LaTeX export, Next: Source blocks in LaTeX export, Prev: Images in LaTeX export, Up: LaTeX export + +12.10.7 Plain lists in LaTeX export +----------------------------------- + +The LaTeX export back-end accepts the ‘:environment’ and ‘:options’ +attributes for plain lists. Both attributes work together for +customizing lists, as shown in the examples: + + #+LATEX_HEADER: \usepackage[inline]{enumitem} + Some ways to say "Hello": + #+ATTR_LATEX: :environment itemize* + #+ATTR_LATEX: :options [label={}, itemjoin={,}, itemjoin*={, and}] + - Hola + - Bonjour + - Guten Tag. + + Since LaTeX supports only four levels of nesting for lists, use an +external package, such as ‘enumitem’ in LaTeX, for levels deeper than +four: + + #+LATEX_HEADER: \usepackage{enumitem} + #+LATEX_HEADER: \renewlist{itemize}{itemize}{9} + #+LATEX_HEADER: \setlist[itemize]{label=$\circ$} + - One + - Two + - Three + - Four + - Five + + +File: org, Node: Source blocks in LaTeX export, Next: Example blocks in LaTeX export, Prev: Plain lists in LaTeX export, Up: LaTeX export + +12.10.8 Source blocks in LaTeX export +------------------------------------- + +The LaTeX export back-end can make source code blocks into floating +objects through the attributes ‘:float’ and ‘:options’. For ‘:float’: + + − ‘t’: makes a source block float; by default floats any source block + with a caption. + − ‘multicolumn’: spans the source block across multiple columns of a + page. + − ‘nil’: avoids a ‘:float’ even if using a caption; useful for source + code blocks that may not fit on a page. + + #+ATTR_LATEX: :float nil + #+BEGIN_SRC emacs-lisp + Lisp code that may not fit in a single page. + #+END_SRC + + The LaTeX export back-end passes string values in ‘:options’ to LaTeX +packages for customization of that specific source block. In the +example below, the ‘:options’ are set for Minted. Minted is a source +code highlighting LaTeXpackage with many configurable options. + + #+ATTR_LATEX: :options commentstyle=\bfseries + #+BEGIN_SRC emacs-lisp + (defun Fib (n) + (if (< n 2) n (+ (Fib (- n 1)) (Fib (- n 2))))) + #+END_SRC + + To apply similar configuration options for all source blocks in a +file, use the ‘org-latex-listings-options’ and +‘org-latex-minted-options’ variables. + + +File: org, Node: Example blocks in LaTeX export, Next: Special blocks in LaTeX export, Prev: Source blocks in LaTeX export, Up: LaTeX export + +12.10.9 Example blocks in LaTeX export +-------------------------------------- + +The LaTeX export back-end wraps the contents of example blocks in a +‘verbatim’ environment. To change this behavior to use another +environment globally, specify an appropriate export filter (*note +Advanced configuration::). To change this behavior to use another +environment for each block, use the ‘:environment’ parameter to specify +a custom environment. + + #+ATTR_LATEX: :environment myverbatim + #+BEGIN_EXAMPLE + This sentence is false. + #+END_EXAMPLE + + +File: org, Node: Special blocks in LaTeX export, Next: Horizontal rules in LaTeX export, Prev: Example blocks in LaTeX export, Up: LaTeX export + +12.10.10 Special blocks in LaTeX export +--------------------------------------- + +For other special blocks in the Org file, the LaTeX export back-end +makes a special environment of the same name. The back-end also takes +‘:options’, if any, and appends as-is to that environment’s opening +string. For example: + + #+BEGIN_abstract + We demonstrate how to solve the Syracuse problem. + #+END_abstract + + #+ATTR_LATEX: :options [Proof of important theorem] + #+BEGIN_proof + ... + Therefore, any even number greater than 2 is the sum of two primes. + #+END_proof + +exports to + + \begin{abstract} + We demonstrate how to solve the Syracuse problem. + \end{abstract} + + \begin{proof}[Proof of important theorem] + ... + Therefore, any even number greater than 2 is the sum of two primes. + \end{proof} + + If you need to insert a specific caption command, use ‘:caption’ +attribute. It will override standard ‘#+CAPTION’ value, if any. For +example: + + #+ATTR_LATEX: :caption \MyCaption{HeadingA} + #+BEGIN_proof + ... + #+END_proof + + +File: org, Node: Horizontal rules in LaTeX export, Prev: Special blocks in LaTeX export, Up: LaTeX export + +12.10.11 Horizontal rules in LaTeX export +----------------------------------------- + +The LaTeX export back-end converts horizontal rules by the specified +‘:width’ and ‘:thickness’ attributes. For example: + + #+ATTR_LATEX: :width .6\textwidth :thickness 0.8pt + ----- + + +File: org, Node: Markdown export, Next: OpenDocument Text export, Prev: LaTeX export, Up: Exporting + +12.11 Markdown export +===================== + +The Markdown export back-end, ‘md’, converts an Org file to Markdown +format, as defined at . + + The ‘md’ back-end is built on top of the HTML back-end (*note HTML +export::). As a consequence, it converts every Org construct not +supported by Markdown syntax, such as tables, to HTML. + +Markdown export commands +------------------------ + +‘C-c C-e m m (org-md-export-to-markdown)’ + Export to a text file with Markdown syntax. For ‘myfile.org’, Org + exports to ‘myfile.md’, overwritten without warning. +‘C-c C-e m M (org-md-export-as-markdown)’ + Export to a temporary buffer. Does not create a file. +‘C-c C-e m o’ + Export as a text file with Markdown syntax, then open it. + +Header and sectioning structure +------------------------------- + +Based on ‘org-md-headline-style’, markdown export can generate headlines +of both ‘atx’ and ‘setext’ types. ‘atx’ limits headline levels to two. +‘setext’ limits headline levels to six. Beyond these limits, the export +back-end converts headlines to lists. To set a limit to a level before +the absolute limit (*note Export settings::). + + +File: org, Node: OpenDocument Text export, Next: Org export, Prev: Markdown export, Up: Exporting + +12.12 OpenDocument Text export +============================== + +The ODT export back-end handles creating of OpenDocument Text (ODT) +format files. The format complies with ‘OpenDocument-v1.2 +specification’(1) and is compatible with LibreOffice 3.4. + +* Menu: + +* Pre-requisites for ODT export:: Required packages. +* ODT export commands:: Invoking export. +* ODT specific export settings:: Configuration options. +* Extending ODT export:: Producing ‘.doc’, ‘.pdf’ files. +* Applying custom styles:: Styling the output. +* Links in ODT export:: Handling and formatting links. +* Tables in ODT export:: Org table conversions. +* Images in ODT export:: Inserting images. +* Math formatting in ODT export:: Formatting LaTeX fragments. +* Labels and captions in ODT export:: Rendering objects. +* Literal examples in ODT export:: For source code and example blocks. +* Advanced topics in ODT export:: For power users. + + ---------- Footnotes ---------- + + (1) Open Document Format for Office Applications (OpenDocument) +Version 1.2 +(http://docs.oasis-open.org/office/v1.2/OpenDocument-v1.2.html) + + +File: org, Node: Pre-requisites for ODT export, Next: ODT export commands, Up: OpenDocument Text export + +12.12.1 Pre-requisites for ODT export +------------------------------------- + +The ODT export back-end relies on the ‘zip’ program to create the final +compressed ODT output. Check if ‘zip’ is locally available and +executable. Without ‘zip’, export cannot finish. + + +File: org, Node: ODT export commands, Next: ODT specific export settings, Prev: Pre-requisites for ODT export, Up: OpenDocument Text export + +12.12.2 ODT export commands +--------------------------- + +‘C-c C-e o o (org-odt-export-to-odt)’ + + Export as OpenDocument Text file. + + If ‘org-odt-preferred-output-format’ is specified, the ODT export + back-end automatically converts the exported file to that format. + *Note Automatically exporting to other formats: + x-export-to-other-formats. + + For ‘myfile.org’, Org exports to ‘myfile.odt’, overwriting without + warning. The ODT export back-end exports a region only if a region + was active. Note for exporting active regions, the + ‘transient-mark-mode’ has to be turned on. + + If the selected region is a single tree, the ODT export back-end + makes the tree head the document title. Incidentally, ‘C-c @’ + selects the current sub-tree. If the tree head entry has, or + inherits, an ‘EXPORT_FILE_NAME’ property, the ODT export back-end + uses that for file name. + + ‘C-c C-e o O’ Export to an OpenDocument Text file format and open + it. + + When ‘org-odt-preferred-output-format’ is specified, open the + converted file instead. *Note Automatically exporting to other + formats: x-export-to-other-formats. + + +File: org, Node: ODT specific export settings, Next: Extending ODT export, Prev: ODT export commands, Up: OpenDocument Text export + +12.12.3 ODT specific export settings +------------------------------------ + +The ODT export back-end has several additional keywords for customizing +ODT output. Setting these keywords works similar to the general options +(*note Export settings::). + +‘DESCRIPTION’ + This is the document’s description, which the ODT export back-end + inserts as document metadata. For long descriptions, use multiple + ‘#+DESCRIPTION’ lines. + +‘KEYWORDS’ + The keywords for the document. The ODT export back-end inserts the + description along with author name, keywords, and related file + metadata as metadata in the output file. Use multiple ‘#+KEYWORDS’ + lines if necessary. + +‘ODT_STYLES_FILE’ + The ODT export back-end uses the ‘org-odt-styles-file’ by default. + See *note Applying custom styles:: for details. + +‘SUBTITLE’ + The document subtitle. + + +File: org, Node: Extending ODT export, Next: Applying custom styles, Prev: ODT specific export settings, Up: OpenDocument Text export + +12.12.4 Extending ODT export +---------------------------- + +The ODT export back-end can produce documents in other formats besides +ODT using a specialized ODT converter process. Its common interface +works with popular converters to produce formats such as ‘doc’, or +convert a document from one format, say ‘csv’, to another format, say +‘xls’. + + Customize ‘org-odt-convert-process’ variable to point to ‘unoconv’, +which is the ODT’s preferred converter. Working installations of +LibreOffice would already have ‘unoconv’ installed. Alternatively, +other converters may be substituted here. *Note Configuring a document +converter::. + +Automatically exporting to other formats +........................................ + +If ODT format is just an intermediate step to get to other formats, such +as ‘doc’, ‘docx’, ‘rtf’, or ‘pdf’, etc., then extend the ODT export +back-end to directly produce that format. Specify the final format in +the ‘org-odt-preferred-output-format’ variable. This is one way to +extend (*note Exporting to ODT: x-export-to-odt.). + +Converting between document formats +................................... + +The Org export back-end is made to be inter-operable with a wide range +of text document format converters. Newer generation converters, such +as LibreOffice and Pandoc, can handle hundreds of formats at once. Org +provides a consistent interaction with whatever converter is installed. +Here are some generic commands: + +‘M-x org-odt-convert ’ + Convert an existing document from one format to another. With a + prefix argument, opens the newly produced file. + + +File: org, Node: Applying custom styles, Next: Links in ODT export, Prev: Extending ODT export, Up: OpenDocument Text export + +12.12.5 Applying custom styles +------------------------------ + +The ODT export back-end comes with many OpenDocument styles (*note +Working with OpenDocument style files::). To expand or further +customize these built-in style sheets, either edit the style sheets +directly or generate them using an application such as LibreOffice. The +example here shows creating a style using LibreOffice. + +Applying custom styles: the easy way +.................................... + + 1. Create a sample ‘example.org’ file with settings as shown below, + and export it to ODT format. + + #+OPTIONS: H:10 num:t + + 2. Open the above ‘example.odt’ using LibreOffice. Use the ‘Stylist’ + to locate the target styles, which typically have the ‘Org’ prefix. + Open one, modify, and save as either OpenDocument Text (‘.odt’) or + OpenDocument Template (‘.ott’) file. + + 3. Customize the variable ‘org-odt-styles-file’ and point it to the + newly created file. For additional configuration options *note + Overriding factory styles: x-overriding-factory-styles. + + To apply and ODT style to a particular file, use the + ‘#+ODT_STYLES_FILE’ option as shown in the example below: + + #+ODT_STYLES_FILE: "/path/to/example.ott" + + or + + #+ODT_STYLES_FILE: ("/path/to/file.ott" ("styles.xml" "image/hdr.png")) + +Using third-party styles and templates +...................................... + +The ODT export back-end relies on many templates and style names. Using +third-party styles and templates can lead to mismatches. Templates +derived from built in ODT templates and styles seem to have fewer +problems. + + +File: org, Node: Links in ODT export, Next: Tables in ODT export, Prev: Applying custom styles, Up: OpenDocument Text export + +12.12.6 Links in ODT export +--------------------------- + +ODT export back-end creates native cross-references for internal links +and Internet-style links for all other link types. + + A link with no description and pointing to a +regular—un-itemized—outline heading is replaced with a cross-reference +and section number of the heading. + + A ‘\ref{label}’-style reference to an image, table etc. is replaced +with a cross-reference and sequence number of the labeled entity. *Note +Labels and captions in ODT export::. + + +File: org, Node: Tables in ODT export, Next: Images in ODT export, Prev: Links in ODT export, Up: OpenDocument Text export + +12.12.7 Tables in ODT export +---------------------------- + +The ODT export back-end handles native Org mode tables (*note Tables::) +and simple ‘table.el’ tables. Complex ‘table.el’ tables having column +or row spans are not supported. Such tables are stripped from the +exported document. + + By default, the ODT export back-end exports a table with top and +bottom frames and with ruled lines separating row and column groups +(*note Column groups::). All tables are typeset to occupy the same +width. The ODT export back-end honors any table alignments and relative +widths for columns (*note Column width and alignment::). + + Note that the ODT export back-end interprets column widths as +weighted ratios, the default weight being 1. + + Specifying ‘:rel-width’ property on an ‘#+ATTR_ODT’ line controls the +width of the table. For example: + + #+ATTR_ODT: :rel-width 50 + | Area/Month | Jan | Feb | Mar | Sum | + |---------------+-------+-------+-------+-------| + | / | < | | | < | + | | | | | | + | North America | 1 | 21 | 926 | 948 | + | Middle East | 6 | 75 | 844 | 925 | + | Asia Pacific | 9 | 27 | 790 | 826 | + |---------------+-------+-------+-------+-------| + | Sum | 16 | 123 | 2560 | 2699 | + + On export, the above table takes 50% of text width area. The +exporter sizes the columns in the ratio: 13:5:5:5:6. The first column +is left-aligned and rest of the columns, right-aligned. Vertical rules +separate the header and the last column. Horizontal rules separate the +header and the last row. + + For even more customization, create custom table styles and associate +them with a table using the ‘#+ATTR_ODT’ line. *Note Customizing tables +in ODT export::. + + +File: org, Node: Images in ODT export, Next: Math formatting in ODT export, Prev: Tables in ODT export, Up: OpenDocument Text export + +12.12.8 Images in ODT export +---------------------------- + +Embedding images +................ + +The ODT export back-end processes image links in Org files that do not +have descriptions, such as these links ‘[[file:img.jpg]]’ or +‘[[./img.jpg]]’, as direct image insertions in the final output. Either +of these examples works: + + [[file:img.png]] + + [[./img.png]] + +Embedding clickable images +.......................... + +For clickable images, provide a link whose description is another link +to an image file. For example, to embed an image ‘org-mode-unicorn.png’ +which when clicked jumps to website, do the +following + + [[https://orgmode.org][./org-mode-unicorn.png]] + +Sizing and scaling of embedded images +..................................... + +Control the size and scale of the embedded images with the ‘#+ATTR_ODT’ +attribute. + + The ODT export back-end starts with establishing the size of the +image in the final document. The dimensions of this size is measured in +centimeters. The back-end then queries the image file for its +dimensions measured in pixels. For this measurement, the back-end +relies on ImageMagick’s ‘identify’ program or Emacs ‘create-image’ and +‘image-size’ API. ImageMagick is the preferred choice for large file +sizes or frequent batch operations. The back-end then converts the +pixel dimensions using ‘org-odt-pixels-per-inch’ into the familiar 72 +dpi or 96 dpi. The default value for this is in +‘display-pixels-per-inch’, which can be tweaked for better results based +on the capabilities of the output device. Here are some common image +scaling operations: + +Explicitly size the image + To embed ‘img.png’ as a 10 cm x 10 cm image, do the following: + + #+ATTR_ODT: :width 10 :height 10 + [[./img.png]] + +Scale the image + To embed ‘img.png’ at half its size, do the following: + + #+ATTR_ODT: :scale 0.5 + [[./img.png]] + +Scale the image to a specific width + To embed ‘img.png’ with a width of 10 cm while retaining the + original height:width ratio, do the following: + + #+ATTR_ODT: :width 10 + [[./img.png]] + +Scale the image to a specific height + To embed ‘img.png’ with a height of 10 cm while retaining the + original height:width ratio, do the following + + #+ATTR_ODT: :height 10 + [[./img.png]] + +Anchoring of images +................... + +The ODT export back-end can anchor images to ‘"as-char"’, ‘"paragraph"’, +or ‘"page"’. Set the preferred anchor using the ‘:anchor’ property of +the ‘#+ATTR_ODT’ line. + + To create an image that is anchored to a page: + #+ATTR_ODT: :anchor "page" + [[./img.png]] + + +File: org, Node: Math formatting in ODT export, Next: Labels and captions in ODT export, Prev: Images in ODT export, Up: OpenDocument Text export + +12.12.9 Math formatting in ODT export +------------------------------------- + +The ODT export back-end has special support built-in for handling math. + +* Menu: + +* Working with LaTeX math snippets:: Embedding in LaTeX format. +* Working with MathML or OpenDocument formula files:: Embedding in native format. + + +File: org, Node: Working with LaTeX math snippets, Next: Working with MathML or OpenDocument formula files, Up: Math formatting in ODT export + +Working with LaTeX math snippets +................................ + +LaTeX math snippets (*note LaTeX fragments::) can be embedded in an ODT +document in one of the following ways: + + 1. MathML + + Add this line to the Org file. This option is activated on a + per-file basis. + + #+OPTIONS: LaTeX:t + + With this option, LaTeX fragments are first converted into MathML + fragments using an external LaTeX-to-MathML converter program. The + resulting MathML fragments are then embedded as an OpenDocument + Formula in the exported document. + + To specify the LaTeX-to-MathML converter, customize the variables + ‘org-latex-to-mathml-convert-command’ and + ‘org-latex-to-mathml-jar-file’. + + To use MathToWeb(1) as the preferred converter, configure the above + variables as + + (setq org-latex-to-mathml-convert-command + "java -jar %j -unicode -force -df %o %I" + org-latex-to-mathml-jar-file + "/path/to/mathtoweb.jar") + To use LaTeXML(2) use + (setq org-latex-to-mathml-convert-command + "latexmlmath \"%i\" --presentationmathml=%o") + + To quickly verify the reliability of the LaTeX-to-MathML converter, + use the following commands: + + ‘M-x org-odt-export-as-odf ’ + Convert a LaTeX math snippet to an OpenDocument formula + (‘.odf’) file. + + ‘M-x org-odt-export-as-odf-and-open ’ + Convert a LaTeX math snippet to an OpenDocument formula + (‘.odf’) file and open the formula file with the + system-registered application. + + 2. PNG images + + Add this line to the Org file. This option is activated on a + per-file basis. + + #+OPTIONS: tex:dvipng + + #+OPTIONS: tex:dvisvgm + + or: + + #+OPTIONS: tex:imagemagick + + Under this option, LaTeX fragments are processed into PNG or SVG + images and the resulting images are embedded in the exported + document. This method requires ‘dvipng’ program, ‘dvisvgm’ or + ‘imagemagick’ programs. + + ---------- Footnotes ---------- + + (1) See MathToWeb +(http://www.mathtoweb.com/cgi-bin/mathtoweb_home.pl). + + (2) See . + + +File: org, Node: Working with MathML or OpenDocument formula files, Prev: Working with LaTeX math snippets, Up: Math formatting in ODT export + +Working with MathML or OpenDocument formula files +................................................. + +When embedding LaTeX math snippets in ODT documents is not reliable, +there is one more option to try. Embed an equation by linking to its +MathML (‘.mml’) source or its OpenDocument formula (‘.odf’) file as +shown below: + + [[./equation.mml]] + + or + + [[./equation.odf]] + + +File: org, Node: Labels and captions in ODT export, Next: Literal examples in ODT export, Prev: Math formatting in ODT export, Up: OpenDocument Text export + +12.12.10 Labels and captions in ODT export +------------------------------------------ + +ODT format handles labeling and captioning of objects based on their +types. Inline images, tables, LaTeX fragments, and Math formulas are +numbered and captioned separately. Each object also gets a unique +sequence number based on its order of first appearance in the Org file. +Each category has its own sequence. A caption is just a label applied +to these objects. + + #+CAPTION: Bell curve + #+LABEL: fig:SED-HR4049 + [[./img/a.png]] + + When rendered, it may show as follows in the exported document: + + Figure 2: Bell curve + + To modify the category component of the caption, customize the option +‘org-odt-category-map-alist’. For example, to tag embedded images with +the string ‘Illustration’ instead of the default string ‘Figure’, use +the following setting: + + (setq org-odt-category-map-alist + '(("__Figure__" "Illustration" "value" "Figure" org-odt--enumerable-image-p))) + + With the above modification, the previous example changes to: + + Illustration 2: Bell curve + + +File: org, Node: Literal examples in ODT export, Next: Advanced topics in ODT export, Prev: Labels and captions in ODT export, Up: OpenDocument Text export + +12.12.11 Literal examples in ODT export +--------------------------------------- + +The ODT export back-end supports literal examples (*note Literal +examples::) with full fontification. Internally, the ODT export +back-end relies on ‘htmlfontify.el’ to generate the style definitions +needed for fancy listings. The auto-generated styles get ‘OrgSrc’ +prefix and inherit colors from the faces used by Emacs ‘font-lock’ +library for that source language. + + For custom fontification styles, customize the +‘org-odt-create-custom-styles-for-srcblocks’ option. + + To turn off fontification of literal examples, customize the +‘org-odt-fontify-srcblocks’ option. + + +File: org, Node: Advanced topics in ODT export, Prev: Literal examples in ODT export, Up: OpenDocument Text export + +12.12.12 Advanced topics in ODT export +-------------------------------------- + +The ODT export back-end has extensive features useful for power users +and frequent uses of ODT formats. + +* Menu: + +* Configuring a document converter:: Registering a document converter. +* Working with OpenDocument style files:: Exploring internals. +* Creating one-off styles:: Customizing styles, highlighting. +* Customizing tables in ODT export:: Defining table templates. +* Validating OpenDocument XML:: Debugging corrupted OpenDocument files. + + +File: org, Node: Configuring a document converter, Next: Working with OpenDocument style files, Up: Advanced topics in ODT export + +Configuring a document converter +................................ + +The ODT export back-end works with popular converters with little or no +extra configuration. *Note Extending ODT export::. The following is +for unsupported converters or tweaking existing defaults. + + 1. Register the converter + + Add the name of the converter to the ‘org-odt-convert-processes’ + variable. Note that it also requires how the converter is invoked + on the command line. See the variable’s docstring for details. + + 2. Configure its capabilities + + Specify which formats the converter can handle by customizing the + variable ‘org-odt-convert-capabilities’. Use the entry for the + default values in this variable for configuring the new converter. + Also see its docstring for details. + + 3. Choose the converter + + Select the newly added converter as the preferred one by + customizing the option ‘org-odt-convert-process’. + + +File: org, Node: Working with OpenDocument style files, Next: Creating one-off styles, Prev: Configuring a document converter, Up: Advanced topics in ODT export + +Working with OpenDocument style files +..................................... + +This section explores the internals of the ODT exporter; the means by +which it produces styled documents; the use of automatic and custom +OpenDocument styles. + +a) Factory styles +................. + +The ODT exporter relies on two files for generating its output. These +files are bundled with the distribution under the directory pointed to +by the variable ‘org-odt-styles-dir’. The two files are: + + • ‘OrgOdtStyles.xml’ + + This file contributes to the ‘styles.xml’ file of the final ‘ODT’ + document. This file gets modified for the following purposes: + + 1. To control outline numbering based on user settings. + + 2. To add styles generated by ‘htmlfontify.el’ for fontification + of code blocks. + + • ‘OrgOdtContentTemplate.xml’ + + This file contributes to the ‘content.xml’ file of the final ‘ODT’ + document. The contents of the Org outline are inserted between the + ‘’...‘’ elements of this file. + + Apart from serving as a template file for the final ‘content.xml’, + the file serves the following purposes: + + 1. It contains automatic styles for formatting of tables which + are referenced by the exporter. + + 2. It contains ‘’...‘’ + elements that control numbering of tables, images, equations, + and similar entities. + +b) Overriding factory styles +............................ + +The following two variables control the location from where the ODT +exporter picks up the custom styles and content template files. +Customize these variables to override the factory styles used by the +exporter. + + • ‘org-odt-styles-file’ + + The ODT export back-end uses the file pointed to by this variable, + such as ‘styles.xml’, for the final output. It can take one of the + following values: + + 1. A ‘styles.xml’ file + + Use this file instead of the default ‘styles.xml’ + + 2. A ‘.odt’ or ‘.ott’ file + + Use the ‘styles.xml’ contained in the specified OpenDocument + Text or Template file + + 3. A ‘.odt’ or ‘.ott’ file and a subset of files contained within + them + + Use the ‘styles.xml’ contained in the specified OpenDocument + Text or Template file. Additionally extract the specified + member files and embed those within the final ‘ODT’ document. + + Use this option if the ‘styles.xml’ file references additional + files like header and footer images. + + 4. ‘nil’ + + Use the default ‘styles.xml’ + + • ‘org-odt-content-template-file’ + + Use this variable to specify the blank ‘content.xml’ that will be + used in the final output. + + +File: org, Node: Creating one-off styles, Next: Customizing tables in ODT export, Prev: Working with OpenDocument style files, Up: Advanced topics in ODT export + +Creating one-off styles +....................... + +The ODT export back-end can read embedded raw OpenDocument XML from the +Org file. Such direct formatting are useful for one-off instances. + + 1. Embedding ODT tags as part of regular text + + Enclose OpenDocument syntax in ‘@@odt:...@@’ for inline markup. + For example, to highlight a region of text do the following: + + @@odt:This is highlighted + text@@. But this is regular text. + + *Hint:* To see the above example in action, edit the ‘styles.xml’ + (*note Factory styles: x-orgodtstyles-xml.) and add a custom + ‘Highlight’ style as shown below: + + + + + + 2. Embedding a one-line OpenDocument XML + + The ODT export back-end can read one-liner options with ‘#+ODT:’ in + the Org file. For example, to force a page break: + + #+ODT: + + *Hint:* To see the above example in action, edit your ‘styles.xml’ + (*note Factory styles: x-orgodtstyles-xml.) and add a custom + ‘PageBreak’ style as shown below. + + + + + + 3. Embedding a block of OpenDocument XML + + The ODT export back-end can also read ODT export blocks for + OpenDocument XML. Such blocks use the ‘#+BEGIN_EXPORT + odt’...‘#+END_EXPORT’ constructs. + + For example, to create a one-off paragraph that uses bold text, do + the following: + + #+BEGIN_EXPORT odt + + This paragraph is specially formatted and uses bold text. + + #+END_EXPORT + + +File: org, Node: Customizing tables in ODT export, Next: Validating OpenDocument XML, Prev: Creating one-off styles, Up: Advanced topics in ODT export + +Customizing tables in ODT export +................................ + +Override the default table format by specifying a custom table style +with the ‘#+ATTR_ODT’ line. For a discussion on default formatting of +tables *note Tables in ODT export::. + + This feature closely mimics the way table templates are defined in +the OpenDocument-v1.2 specification.(1) + + For quick preview of this feature, install the settings below and +export the table that follows: + + (setq org-odt-table-styles + (append org-odt-table-styles + '(("TableWithHeaderRowAndColumn" "Custom" + ((use-first-row-styles . t) + (use-first-column-styles . t))) + ("TableWithFirstRowandLastRow" "Custom" + ((use-first-row-styles . t) + (use-last-row-styles . t)))))) + + #+ATTR_ODT: :style TableWithHeaderRowAndColumn + | Name | Phone | Age | + | Peter | 1234 | 17 | + | Anna | 4321 | 25 | + + The example above used ‘Custom’ template and installed two table +styles ‘TableWithHeaderRowAndColumn’ and ‘TableWithFirstRowandLastRow’. +*Important:* The OpenDocument styles needed for producing the above +template were pre-defined. They are available in the section marked +‘Custom Table Template’ in ‘OrgOdtContentTemplate.xml’ (*note Factory +styles: x-orgodtcontenttemplate-xml. For adding new templates, define +new styles here. + + To use this feature proceed as follows: + + 1. Create a table template(2) + + A table template is set of ‘table-cell’ and ‘paragraph’ styles for + each of the following table cell categories: + + − Body + − First column + − Last column + − First row + − Last row + − Even row + − Odd row + − Even column + − Odd Column + + The names for the above styles must be chosen based on the name of + the table template using a well-defined convention. + + The naming convention is better illustrated with an example. For a + table template with the name ‘Custom’, the needed style names are + listed in the following table. + + Table cell type ‘table-cell’ style ‘paragraph’ style + ------------------------------------------------------------------------------- + Body ‘CustomTableCell’ ‘CustomTableParagraph’ + First column ‘CustomFirstColumnTableCell’‘CustomFirstColumnTableParagraph’ + Last column ‘CustomLastColumnTableCell’ ‘CustomLastColumnTableParagraph’ + First row ‘CustomFirstRowTableCell’ ‘CustomFirstRowTableParagraph’ + Last row ‘CustomLastRowTableCell’ ‘CustomLastRowTableParagraph’ + Even row ‘CustomEvenRowTableCell’ ‘CustomEvenRowTableParagraph’ + Odd row ‘CustomOddRowTableCell’ ‘CustomOddRowTableParagraph’ + Even column ‘CustomEvenColumnTableCell’ ‘CustomEvenColumnTableParagraph’ + Odd column ‘CustomOddColumnTableCell’ ‘CustomOddColumnTableParagraph’ + + To create a table template with the name ‘Custom’, define the above + styles in the + ‘’...‘’ element + of the content template file (*note Factory styles: + x-orgodtcontenttemplate-xml.). + + 2. Define a table style(3) + + To define a table style, create an entry for the style in the + variable ‘org-odt-table-styles’ and specify the following: + + − the name of the table template created in step (1) + − the set of cell styles in that template that are to be + activated + + For example, the entry below defines two different table styles + ‘TableWithHeaderRowAndColumn’ and ‘TableWithFirstRowandLastRow’ + based on the same template ‘Custom’. The styles achieve their + intended effect by selectively activating the individual cell + styles in that template. + + (setq org-odt-table-styles + (append org-odt-table-styles + '(("TableWithHeaderRowAndColumn" "Custom" + ((use-first-row-styles . t) + (use-first-column-styles . t))) + ("TableWithFirstRowandLastRow" "Custom" + ((use-first-row-styles . t) + (use-last-row-styles . t)))))) + + 3. Associate a table with the table style + + To do this, specify the table style created in step (2) as part of + the ‘ATTR_ODT’ line as shown below. + + #+ATTR_ODT: :style "TableWithHeaderRowAndColumn" + | Name | Phone | Age | + | Peter | 1234 | 17 | + | Anna | 4321 | 25 | + + ---------- Footnotes ---------- + + (1) OpenDocument-v1.2 Specification +(http://docs.oasis-open.org/office/v1.2/OpenDocument-v1.2.html) + + (2) See the ‘’ element of the OpenDocument-v1.2 +specification + + (3) See the attributes ‘table:template-name’, +‘table:use-first-row-styles’, ‘table:use-last-row-styles’, +‘table:use-first-column-styles’, ‘table:use-last-column-styles’, +‘table:use-banding-rows-styles’, and ‘table:use-banding-column-styles’ +of the ‘’ element in the OpenDocument-v1.2 specification + + +File: org, Node: Validating OpenDocument XML, Prev: Customizing tables in ODT export, Up: Advanced topics in ODT export + +Validating OpenDocument XML +........................... + +Sometimes ODT format files may not open due to ‘.odt’ file corruption. +To verify if the ‘.odt’ file is corrupt, validate it against the +OpenDocument RELAX NG Compact Syntax—RNC—schema. But first the ‘.odt’ +files have to be decompressed using ‘zip’. Note that ‘.odt’ files are +‘zip’ archives: *note (emacs)File Archives::. The contents of ‘.odt’ +files are in ‘.xml’. For general help with validation—and +schema-sensitive editing—of XML files: *note (nxml-mode)Introduction::. + + Customize ‘org-odt-schema-dir’ to point to a directory with +OpenDocument ‘.rnc’ files and the needed schema-locating rules. The ODT +export back-end takes care of updating the ‘rng-schema-locating-files’. + + +File: org, Node: Org export, Next: Texinfo export, Prev: OpenDocument Text export, Up: Exporting + +12.13 Org export +================ + +‘org’ export back-end creates a normalized version of the Org document +in current buffer. The exporter evaluates Babel code (*note Evaluating +code blocks::) and removes content specific to other back-ends. + +Org export commands +------------------- + +‘C-c C-e O o (org-org-export-to-org)’ + Export as an Org file with a ‘.org’ extension. For ‘myfile.org’, + Org exports to ‘myfile.org.org’, overwriting without warning. + +‘C-c C-e O O (org-org-export-as-org)’ + Export to a temporary buffer. Does not create a file. +‘C-c C-e O v’ + Export to an Org file, then open it. + + +File: org, Node: Texinfo export, Next: iCalendar export, Prev: Org export, Up: Exporting + +12.14 Texinfo export +==================== + +The ‘texinfo’ export back-end generates documents with Texinfo code that +can compile to Info format. + +* Menu: + +* Texinfo export commands:: Invoking commands. +* Texinfo specific export settings:: Setting the environment. +* Texinfo file header:: Generating the header. +* Texinfo title and copyright page:: Creating preamble pages. +* Info directory file:: Installing a manual in Info file hierarchy. +* Headings and sectioning structure:: Building document structure. +* Indices:: Creating indices. +* Quoting Texinfo code:: Incorporating literal Texinfo code. +* Plain lists in Texinfo export:: List attributes. +* Tables in Texinfo export:: Table attributes. +* Images in Texinfo export:: Image attributes. +* Special blocks in Texinfo export:: Special block attributes. +* A Texinfo example:: Processing Org to Texinfo. + + +File: org, Node: Texinfo export commands, Next: Texinfo specific export settings, Up: Texinfo export + +12.14.1 Texinfo export commands +------------------------------- + +‘C-c C-e i t (org-texinfo-export-to-texinfo)’ + Export as a Texinfo file with ‘.texi’ extension. For ‘myfile.org’, + Org exports to ‘myfile.texi’, overwriting without warning. +‘C-c C-e i i (org-texinfo-export-to-info)’ + Export to Texinfo format first and then process it to make an Info + file. To generate other formats, such as DocBook, customize the + ‘org-texinfo-info-process’ variable. + + +File: org, Node: Texinfo specific export settings, Next: Texinfo file header, Prev: Texinfo export commands, Up: Texinfo export + +12.14.2 Texinfo specific export settings +---------------------------------------- + +The Texinfo export back-end has several additional keywords for +customizing Texinfo output. Setting these keywords works similar to the +general options (*note Export settings::). + +‘SUBTITLE’ + The document subtitle. + +‘SUBAUTHOR’ + The document subauthor. + +‘TEXINFO_FILENAME’ + The Texinfo filename. + +‘TEXINFO_CLASS’ + The default document class (‘org-texinfo-default-class’), which + must be a member of ‘org-texinfo-classes’. + +‘TEXINFO_HEADER’ + Arbitrary lines inserted at the end of the header. + +‘TEXINFO_POST_HEADER’ + Arbitrary lines inserted after the end of the header. + +‘TEXINFO_DIR_CATEGORY’ + The directory category of the document. + +‘TEXINFO_DIR_TITLE’ + The directory title of the document. + +‘TEXINFO_DIR_DESC’ + The directory description of the document. + +‘TEXINFO_PRINTED_TITLE’ + The printed title of the document. + + +File: org, Node: Texinfo file header, Next: Texinfo title and copyright page, Prev: Texinfo specific export settings, Up: Texinfo export + +12.14.3 Texinfo file header +--------------------------- + +After creating the header for a Texinfo file, the Texinfo back-end +automatically generates a name and destination path for the Info file. +To override this default with a more sensible path and name, specify the +‘#+TEXINFO_FILENAME’ keyword. + + Along with the output’s file name, the Texinfo header also contains +language details (*note Export settings::) and encoding system as set in +the ‘org-texinfo-coding-system’ variable. Insert ‘#+TEXINFO_HEADER’ +keywords for each additional command in the header, for example: +@code{@synindex}. + + Instead of repeatedly installing the same set of commands, define a +class in ‘org-texinfo-classes’ once, and then activate it in the +document by setting the ‘#+TEXINFO_CLASS’ keyword to that class. + + +File: org, Node: Texinfo title and copyright page, Next: Info directory file, Prev: Texinfo file header, Up: Texinfo export + +12.14.4 Texinfo title and copyright page +---------------------------------------- + +The default template for hard copy output has a title page with +‘#+TITLE’ and ‘#+AUTHOR’ (*note Export settings::). To replace the +regular ‘#+TITLE’ with something different for the printed version, use +the ‘#+TEXINFO_PRINTED_TITLE’ and ‘#+SUBTITLE’ keywords. Both expect +raw Texinfo code for setting their values. + + If one ‘#+AUTHOR’ is not sufficient, add multiple ‘#+SUBAUTHOR’ +keywords. They have to be set in raw Texinfo code. + + #+AUTHOR: Jane Smith + #+SUBAUTHOR: John Doe + #+TEXINFO_PRINTED_TITLE: This Long Title@inlinefmt{tex,@*} Is Broken in @TeX{} + + Copying material is defined in a dedicated headline with a non-‘nil’ +‘:COPYING:’ property. The back-end inserts the contents within a +‘@copying’ command at the beginning of the document. The heading itself +does not appear in the structure of the document. + + Copyright information is printed on the back of the title page. + + * Legalese + :PROPERTIES: + :COPYING: t + :END: + + This is a short example of a complete Texinfo file, version 1.0. + + Copyright \copy 2018 Free Software Foundation, Inc. + + +File: org, Node: Info directory file, Next: Headings and sectioning structure, Prev: Texinfo title and copyright page, Up: Texinfo export + +12.14.5 Info directory file +--------------------------- + +The end result of the Texinfo export process is the creation of an Info +file. This Info file’s metadata has variables for category, title, and +description: ‘#+TEXINFO_DIR_CATEGORY’, ‘#+TEXINFO_DIR_TITLE’, and +‘#+TEXINFO_DIR_DESC’ that establish where in the Info hierarchy the file +fits. + + Here is an example that writes to the Info directory file: + + #+TEXINFO_DIR_CATEGORY: Emacs + #+TEXINFO_DIR_TITLE: Org Mode: (org) + #+TEXINFO_DIR_DESC: Outline-based notes management and organizer + + +File: org, Node: Headings and sectioning structure, Next: Indices, Prev: Info directory file, Up: Texinfo export + +12.14.6 Headings and sectioning structure +----------------------------------------- + +The Texinfo export back-end uses a pre-defined scheme to convert Org +headlines to an equivalent Texinfo structuring commands. A scheme like +this maps top-level headlines to numbered chapters tagged as ‘@chapter’ +and lower-level headlines to unnumbered chapters tagged as +‘@unnumbered’. To override such mappings to introduce ‘@part’ or other +Texinfo structuring commands, define a new class in +‘org-texinfo-classes’. Activate the new class with the +‘#+TEXINFO_CLASS’ keyword. When no new class is defined and activated, +the Texinfo export back-end defaults to the ‘org-texinfo-default-class’. + + If an Org headline’s level has no associated Texinfo structuring +command, or is below a certain threshold (*note Export settings::), then +the Texinfo export back-end makes it into a list item. + + The Texinfo export back-end makes any headline with a non-‘nil’ +‘:APPENDIX:’ property into an appendix. This happens independent of the +Org headline level or the ‘#+TEXINFO_CLASS’. + + The Texinfo export back-end creates a menu entry after the Org +headline for each regular sectioning structure. To override this with a +shorter menu entry, use the ‘:ALT_TITLE:’ property (*note Table of +contents::). Texinfo menu entries also have an option for a longer +‘:DESCRIPTION:’ property. Here’s an example that uses both to override +the default menu entry: + + * Controlling Screen Display + :PROPERTIES: + :ALT_TITLE: Display + :DESCRIPTION: Controlling Screen Display + :END: + + The text before the first headline belongs to the ‘Top’ node, i.e., +the node in which a reader enters an Info manual. As such, it is +expected not to appear in printed output generated from the ‘.texi’ +file. *note (texinfo)The Top Node::, for more information. + + +File: org, Node: Indices, Next: Quoting Texinfo code, Prev: Headings and sectioning structure, Up: Texinfo export + +12.14.7 Indices +--------------- + +The Texinfo export back-end recognizes these indexing keywords if used +in the Org file: ‘#+CINDEX’, ‘#+FINDEX’, ‘#+KINDEX’, ‘#+PINDEX’, +‘#+TINDEX’, and ‘#+VINDEX’. Write their value as verbatim Texinfo code; +in particular, ‘{’, ‘}’ and ‘@’ characters need to be escaped with ‘@’ +if they not belong to a Texinfo command. + + #+CINDEX: Defining indexing entries + + For the back-end to generate an index entry for a headline, set the +‘:INDEX:’ property to ‘cp’ or ‘vr’. These abbreviations come from +Texinfo that stand for concept index and variable index. The Texinfo +manual has abbreviations for all other kinds of indexes. The back-end +exports the headline as an unnumbered chapter or section command, and +then inserts the index after its contents. + + * Concept Index + :PROPERTIES: + :INDEX: cp + :END: + + +File: org, Node: Quoting Texinfo code, Next: Plain lists in Texinfo export, Prev: Indices, Up: Texinfo export + +12.14.8 Quoting Texinfo code +---------------------------- + +Use any of the following three methods to insert or escape raw Texinfo +code: + + Richard @@texinfo:@sc{@@Stallman@@texinfo:}@@ commence' GNU. + + #+TEXINFO: @need800 + This paragraph is preceded by... + + #+BEGIN_EXPORT texinfo + @auindex Johnson, Mark + @auindex Lakoff, George + #+END_EXPORT + + +File: org, Node: Plain lists in Texinfo export, Next: Tables in Texinfo export, Prev: Quoting Texinfo code, Up: Texinfo export + +12.14.9 Plain lists in Texinfo export +------------------------------------- + +The Texinfo export back-end by default converts description lists in the +Org file using the default command ‘@table’, which results in a table +with two columns. To change this behavior, specify ‘:table-type’ with +‘ftable’ or ‘vtable’ attributes. For more information, *note +(texinfo)Two-column Tables::. + + The Texinfo export back-end by default also applies a text highlight +based on the defaults stored in ‘org-texinfo-table-default-markup’. To +override the default highlight command, specify another one with the +‘:indic’ attribute. + + Org syntax is limited to one entry per list item. Nevertheless, the +Texinfo export back-end can split that entry according to any text +provided through the ‘:sep’ attribute. Each part then becomes a new +entry in the first column of the table. + + The following example illustrates all the attributes above: + + #+ATTR_TEXINFO: :table-type vtable :sep , :indic asis + - foo, bar :: This is the common text for variables foo and bar. + +becomes + + @vtable @asis + @item foo + @itemx bar + This is the common text for variables foo and bar. + @end table + + +File: org, Node: Tables in Texinfo export, Next: Images in Texinfo export, Prev: Plain lists in Texinfo export, Up: Texinfo export + +12.14.10 Tables in Texinfo export +--------------------------------- + +When exporting tables, the Texinfo export back-end uses the widest cell +width in each column. To override this and instead specify as fractions +of line length, use the ‘:columns’ attribute. See example below. + + #+ATTR_TEXINFO: :columns .5 .5 + | a cell | another cell | + + +File: org, Node: Images in Texinfo export, Next: Special blocks in Texinfo export, Prev: Tables in Texinfo export, Up: Texinfo export + +12.14.11 Images in Texinfo export +--------------------------------- + +Insert a file link to the image in the Org file, and the Texinfo export +back-end inserts the image. These links must have the usual supported +image extensions and no descriptions. To scale the image, use ‘:width’ +and ‘:height’ attributes. For alternate text, use ‘:alt’ and specify +the text using Texinfo code, as shown in the example: + + #+ATTR_TEXINFO: :width 1in :alt Alternate @i{text} + [[ridt.pdf]] + + +File: org, Node: Special blocks in Texinfo export, Next: A Texinfo example, Prev: Images in Texinfo export, Up: Texinfo export + +12.14.12 Special blocks +----------------------- + +The Texinfo export back-end converts special blocks to commands with the +same name. It also adds any ‘:options’ attributes to the end of the +command, as shown in this example: + + #+ATTR_TEXINFO: :options org-org-export-to-org ... + #+begin_defun + A somewhat obsessive function. + #+end_defun + +becomes + + @defun org-org-export-to-org ... + A somewhat obsessive function. + @end defun + + +File: org, Node: A Texinfo example, Prev: Special blocks in Texinfo export, Up: Texinfo export + +12.14.13 A Texinfo example +-------------------------- + +Here is a more detailed example Org file. See *note (texinfo)GNU Sample +Texts:: for an equivalent example using Texinfo code. + + #+TITLE: GNU Sample {{{version}}} + #+SUBTITLE: for version {{{version}}}, {{{updated}}} + #+AUTHOR: A.U. Thor + #+EMAIL: bug-sample@gnu.org + + #+OPTIONS: ':t toc:t author:t email:t + #+LANGUAGE: en + + #+MACRO: version 2.0 + #+MACRO: updated last updated 4 March 2014 + + #+TEXINFO_FILENAME: sample.info + #+TEXINFO_HEADER: @syncodeindex pg cp + + #+TEXINFO_DIR_CATEGORY: Texinfo documentation system + #+TEXINFO_DIR_TITLE: sample: (sample) + #+TEXINFO_DIR_DESC: Invoking sample + + #+TEXINFO_PRINTED_TITLE: GNU Sample + + This manual is for GNU Sample (version {{{version}}}, + {{{updated}}}). + + * Copying + :PROPERTIES: + :COPYING: t + :END: + + This manual is for GNU Sample (version {{{version}}}, + {{{updated}}}), which is an example in the Texinfo documentation. + + Copyright \copy 2018 Free Software Foundation, Inc. + + #+BEGIN_QUOTE + Permission is granted to copy, distribute and/or modify this + document under the terms of the GNU Free Documentation License, + Version 1.3 or any later version published by the Free Software + Foundation; with no Invariant Sections, with no Front-Cover Texts, + and with no Back-Cover Texts. A copy of the license is included in + the section entitled "GNU Free Documentation License". + #+END_QUOTE + + * Invoking sample + + #+PINDEX: sample + #+CINDEX: invoking @command{sample} + + This is a sample manual. There is no sample program to invoke, but + if there were, you could see its basic usage and command line + options here. + + * GNU Free Documentation License + :PROPERTIES: + :APPENDIX: t + :END: + + #+TEXINFO: @include fdl.texi + + * Index + :PROPERTIES: + :INDEX: cp + :END: + + +File: org, Node: iCalendar export, Next: Other built-in back-ends, Prev: Texinfo export, Up: Exporting + +12.15 iCalendar export +====================== + +A large part of Org mode’s inter-operability success is its ability to +easily export to or import from external applications. The iCalendar +export back-end takes calendar data from Org files and exports to the +standard iCalendar format. + + The iCalendar export back-end can also incorporate TODO entries based +on the configuration of the ‘org-icalendar-include-todo’ variable. The +back-end exports plain timestamps as VEVENT, TODO items as VTODO, and +also create events from deadlines that are in non-TODO items. The +back-end uses the deadlines and scheduling dates in Org TODO items for +setting the start and due dates for the iCalendar TODO entry. Consult +the ‘org-icalendar-use-deadline’ and ‘org-icalendar-use-scheduled’ +variables for more details. + + For tags on the headline, the iCalendar export back-end makes them +into iCalendar categories. To tweak the inheritance of tags and TODO +states, configure the variable ‘org-icalendar-categories’. To assign +clock alarms based on time, configure the ‘org-icalendar-alarm-time’ +variable. + + The iCalendar format standard requires globally unique +identifier—UID—for each entry. The iCalendar export back-end creates +UIDs during export. To save a copy of the UID in the Org file set the +variable ‘org-icalendar-store-UID’. The back-end looks for the ‘:ID:’ +property of the entry for re-using the same UID for subsequent exports. + + Since a single Org entry can result in multiple iCalendar entries—as +timestamp, deadline, scheduled item, or TODO item—Org adds prefixes to +the UID, depending on which part of the Org entry triggered the creation +of the iCalendar entry. Prefixing ensures UIDs remains unique, yet +enable synchronization programs trace the connections. + +‘C-c C-e c f (org-icalendar-export-to-ics)’ + Create iCalendar entries from the current Org buffer and store them + in the same directory, using a file extension ‘.ics’. +‘C-c C-e c a (org-icalendar-export-agenda-files)’ + Create iCalendar entries from Org files in ‘org-agenda-files’ and + store in a separate iCalendar file for each Org file. +‘C-c C-e c c (org-icalendar-combine-agenda-files)’ + Create a combined iCalendar file from Org files in + ‘org-agenda-files’ and write it to + ‘org-icalendar-combined-agenda-file’ file name. + + The iCalendar export back-end includes ‘SUMMARY’, ‘DESCRIPTION’, +‘LOCATION’ and ‘TIMEZONE’ properties from the Org entries when +exporting. To force the back-end to inherit the ‘LOCATION’ and +‘TIMEZONE’ properties, configure the ‘org-use-property-inheritance’ +variable. + + When Org entries do not have ‘SUMMARY’, ‘DESCRIPTION’ and ‘LOCATION’ +properties, the iCalendar export back-end derives the summary from the +headline, and derives the description from the body of the Org item. +The ‘org-icalendar-include-body’ variable limits the maximum number of +characters of the content are turned into its description. + + The ‘TIMEZONE’ property can be used to specify a per-entry time zone, +and will be applied to any entry with timestamp information. Time zones +should be specified as per the IANA time zone database format, e.g. +“Asia/Almaty”. Alternately, the property value can be “UTC”, to force +UTC time for this entry only. + + Exporting to iCalendar format depends in large part on the +capabilities of the destination application. Some are more lenient than +others. Consult the Org mode FAQ for advice on specific applications. + + +File: org, Node: Other built-in back-ends, Next: Advanced configuration, Prev: iCalendar export, Up: Exporting + +12.16 Other built-in back-ends +============================== + +Other export back-ends included with Org are: + + • ‘ox-man.el’: export to a man page. + + To activate such back-ends, either customize ‘org-export-backends’ or +load directly with ‘(require 'ox-man)’. On successful load, the +back-end adds new keys in the export dispatcher (*note The export +dispatcher::). + + Follow the comment section of such files, for example, ‘ox-man.el’, +for usage and configuration details. + + +File: org, Node: Advanced configuration, Next: Export in foreign buffers, Prev: Other built-in back-ends, Up: Exporting + +12.17 Advanced configuration +============================ + +Hooks +----- + +The export process executes two hooks before the actual exporting +begins. The first hook, ‘org-export-before-processing-hook’, runs +before any expansions of macros, Babel code, and include keywords in the +buffer. The second hook, ‘org-export-before-parsing-hook’, runs before +the buffer is parsed. Both hooks are specified as functions, see +example below. Their main use is for heavy duty structural +modifications of the Org content. For example, removing every headline +in the buffer during export: + + (defun my-headline-removal (backend) + "Remove all headlines in the current buffer. + BACKEND is the export back-end being used, as a symbol." + (org-map-entries + (lambda () (delete-region (point) (progn (forward-line) (point)))))) + + (add-hook 'org-export-before-parsing-hook 'my-headline-removal) + + Note that the hook function must have a mandatory argument that is a +symbol for the back-end. + +Filters +------- + +The Org export process relies on filters to process specific parts of +conversion process. Filters are just lists of functions to be applied +to certain parts for a given back-end. The output from the first +function in the filter is passed on to the next function in the filter. +The final output is the output from the final function in the filter. + + The Org export process has many filter sets applicable to different +types of objects, plain text, parse trees, export options, and final +output formats. The filters are named after the element type or object +type: ‘org-export-filter-TYPE-functions’, where ‘TYPE’ is the type +targeted by the filter. Valid types are: + +body bold babel-call +center-block clock code +diary-sexp drawer dynamic-block +entity example-block export-block +export-snippet final-output fixed-width +footnote-definition footnote-reference headline +horizontal-rule inline-babel-call inline-src-block +inlinetask italic item +keyword latex-environment latex-fragment +line-break link node-property +options paragraph parse-tree +plain-list plain-text planning +property-drawer quote-block radio-target +section special-block src-block +statistics-cookie strike-through subscript +superscript table table-cell +table-row target timestamp +underline verbatim verse-block + + Here is an example filter that replaces non-breaking spaces ‘~’ in +the Org buffer with ‘_’ for the LaTeX back-end. + + (defun my-latex-filter-nobreaks (text backend info) + "Ensure \"_\" are properly handled in LaTeX export." + (when (org-export-derived-backend-p backend 'latex) + (replace-regexp-in-string "_" "~" text))) + + (add-to-list 'org-export-filter-plain-text-functions + 'my-latex-filter-nobreaks) + + A filter requires three arguments: the code to be transformed, the +name of the back-end, and some optional information about the export +process. The third argument can be safely ignored. Note the use of +‘org-export-derived-backend-p’ predicate that tests for ‘latex’ back-end +or any other back-end, such as ‘beamer’, derived from ‘latex’. + +Defining filters for individual files +------------------------------------- + +The Org export can filter not just for back-ends, but also for specific +files through the ‘#+BIND’ keyword. Here is an example with two +filters; one removes brackets from time stamps, and the other removes +strike-through text. The filter functions are defined in a ‘src’ code +block in the same Org file, which is a handy location for debugging. + + #+BIND: org-export-filter-timestamp-functions (tmp-f-timestamp) + #+BIND: org-export-filter-strike-through-functions (tmp-f-strike-through) + #+begin_src emacs-lisp :exports results :results none + (defun tmp-f-timestamp (s backend info) + (replace-regexp-in-string "&[lg]t;\\|[][]" "" s)) + (defun tmp-f-strike-through (s backend info) "") + #+end_src + +Extending an existing back-end +------------------------------ + +Some parts of the conversion process can be extended for certain +elements so as to introduce a new or revised translation. That is how +the HTML export back-end was extended to handle Markdown format. The +extensions work seamlessly so any aspect of filtering not done by the +extended back-end is handled by the original back-end. Of all the +export customization in Org, extending is very powerful as it operates +at the parser level. + + For this example, make the ‘ascii’ back-end display the language used +in a source code block. Also make it display only when some attribute +is non-‘nil’, like the following: + + #+ATTR_ASCII: :language t + + Then extend ‘ascii’ back-end with a custom ‘my-ascii’ back-end. + + (defun my-ascii-src-block (src-block contents info) + "Transcode a SRC-BLOCK element from Org to ASCII. + CONTENTS is nil. INFO is a plist used as a communication + channel." + (if (not (org-export-read-attribute :attr_ascii src-block :language)) + (org-export-with-backend 'ascii src-block contents info) + (concat + (format ",--[ %s ]--\n%s`----" + (org-element-property :language src-block) + (replace-regexp-in-string + "^" "| " + (org-element-normalize-string + (org-export-format-code-default src-block info))))))) + + (org-export-define-derived-backend 'my-ascii 'ascii + :translate-alist '((src-block . my-ascii-src-block))) + + The ‘my-ascii-src-block’ function looks at the attribute above the +current element. If not true, hands over to ‘ascii’ back-end. If true, +which it is in this example, it creates a box around the code and leaves +room for the inserting a string for language. The last form creates the +new back-end that springs to action only when translating ‘src-block’ +type elements. + + To use the newly defined back-end, call the following from an Org +buffer: + + (org-export-to-buffer 'my-ascii "*Org MY-ASCII Export*") + + Further steps to consider would be an interactive function, +self-installing an item in the export dispatcher menu, and other +user-friendly improvements. + + +File: org, Node: Export in foreign buffers, Prev: Advanced configuration, Up: Exporting + +12.18 Export in foreign buffers +=============================== + +The export back-ends in Org often include commands to convert selected +regions. A convenient feature of this in-place conversion is that the +exported output replaces the original source. Here are such functions: + +‘org-html-convert-region-to-html’ + Convert the selected region into HTML. +‘org-latex-convert-region-to-latex’ + Convert the selected region into LaTeX. +‘org-texinfo-convert-region-to-texinfo’ + Convert the selected region into ‘Texinfo’. +‘org-md-convert-region-to-md’ + Convert the selected region into ‘MarkDown’. + + In-place conversions are particularly handy for quick conversion of +tables and lists in foreign buffers. For example, turn on the minor +mode ‘M-x orgstruct-mode’ in an HTML buffer, then use the convenient Org +keyboard commands to create a list, select it, and covert it to HTML +with ‘M-x org-html-convert-region-to-html ’. + + +File: org, Node: Publishing, Next: Working with source code, Prev: Exporting, Up: Top + +13 Publishing +************* + +Org includes a publishing management system that allows you to configure +automatic HTML conversion of _projects_ composed of interlinked org +files. You can also configure Org to automatically upload your exported +HTML pages and related attachments, such as images and source code +files, to a web server. + + You can also use Org to convert files into PDF, or even combine HTML +and PDF conversion so that files are available in both formats on the +server. + + Publishing has been contributed to Org by David O’Toole. + +* Menu: + +* Configuration:: Defining projects +* Uploading files:: How to get files up on the server +* Sample configuration:: Example projects +* Triggering publication:: Publication commands + + +File: org, Node: Configuration, Next: Uploading files, Up: Publishing + +13.1 Configuration +================== + +Publishing needs significant configuration to specify files, destination +and many other properties of a project. + +* Menu: + +* Project alist:: The central configuration variable +* Sources and destinations:: From here to there +* Selecting files:: What files are part of the project? +* Publishing action:: Setting the function doing the publishing +* Publishing options:: Tweaking HTML/LaTeX export +* Publishing links:: Which links keep working after publishing? +* Sitemap:: Generating a list of all pages +* Generating an index:: An index that reaches across pages + + +File: org, Node: Project alist, Next: Sources and destinations, Up: Configuration + +13.1.1 The variable ‘org-publish-project-alist’ +----------------------------------------------- + +Publishing is configured almost entirely through setting the value of +one variable, called ‘org-publish-project-alist’. Each element of the +list configures one project, and may be in one of the two following +forms: + + ("project-name" :property value :property value ...) + i.e., a well-formed property list with alternating keys and values + or + ("project-name" :components ("project-name" "project-name" ...)) + + + In both cases, projects are configured by specifying property values. +A project defines the set of files that will be published, as well as +the publishing configuration to use when publishing those files. When a +project takes the second form listed above, the individual members of +the ‘:components’ property are taken to be sub-projects, which group +together files requiring different publishing options. When you publish +such a “meta-project”, all the components will also be published, in the +sequence given. + + +File: org, Node: Sources and destinations, Next: Selecting files, Prev: Project alist, Up: Configuration + +13.1.2 Sources and destinations for files +----------------------------------------- + +Most properties are optional, but some should always be set. In +particular, Org needs to know where to look for source files, and where +to put published files. + +‘:base-directory’ Directory containing publishing source files +‘:publishing-directory’Directory where output files will be published. + You can directly publish to a web server using a + file name syntax appropriate for the Emacs + ‘tramp’ package. Or you can publish to a local + directory and use external tools to upload your + website (*note Uploading files::). +‘:preparation-function’Function or list of functions to be called + before starting the publishing process, for + example, to run ‘make’ for updating files to be + published. Each preparation function is called + with a single argument, the project property + list. +‘:completion-function’ Function or list of functions called after + finishing the publishing process, for example, + to change permissions of the resulting files. + Each completion function is called with a single + argument, the project property list. + + +File: org, Node: Selecting files, Next: Publishing action, Prev: Sources and destinations, Up: Configuration + +13.1.3 Selecting files +---------------------- + +By default, all files with extension ‘.org’ in the base directory are +considered part of the project. This can be modified by setting the +properties +‘:base-extension’ Extension (without the dot!) of source files. This + actually is a regular expression. Set this to the + symbol ‘any’ if you want to get all files in + ‘:base-directory’, even without extension. + +‘:exclude’ Regular expression to match file names that should + not be published, even though they have been + selected on the basis of their extension. + +‘:include’ List of files to be included regardless of + ‘:base-extension’ and ‘:exclude’. + +‘:recursive’ non-‘nil’ means, check base-directory recursively + for files to publish. + + +File: org, Node: Publishing action, Next: Publishing options, Prev: Selecting files, Up: Configuration + +13.1.4 Publishing action +------------------------ + +Publishing means that a file is copied to the destination directory and +possibly transformed in the process. The default transformation is to +export Org files as HTML files, and this is done by the function +‘org-html-publish-to-html’, which calls the HTML exporter (*note HTML +export::). But you also can publish your content as PDF files using +‘org-latex-publish-to-pdf’ or as ‘ascii’, ‘Texinfo’, etc., using the +corresponding functions. + + If you want to publish the Org file as an ‘.org’ file but with the +archived, commented and tag-excluded trees removed, use the function +‘org-org-publish-to-org’. This will produce ‘file.org’ and put it in +the publishing directory. If you want a htmlized version of this file, +set the parameter ‘:htmlized-source’ to ‘t’, it will produce +‘file.org.html’ in the publishing directory(1). + + Other files like images only need to be copied to the publishing +destination. For this you can use ‘org-publish-attachment’. For +non-org files, you always need to specify the publishing function: + +‘:publishing-function’ Function executing the publication of a file. + This may also be a list of functions, which will + all be called in turn. +‘:htmlized-source’ non-‘nil’ means, publish htmlized source. + + The function must accept three arguments: a property list containing +at least a ‘:publishing-directory’ property, the name of the file to be +published and the path to the publishing directory of the output file. +It should take the specified file, make the necessary transformation (if +any) and place the result into the destination folder. + + ---------- Footnotes ---------- + + (1) If the publishing directory is the same than the source +directory, ‘file.org’ will be exported as ‘file.org.org’, so probably +don’t want to do this. + + +File: org, Node: Publishing options, Next: Publishing links, Prev: Publishing action, Up: Configuration + +13.1.5 Options for the exporters +-------------------------------- + +The property list can be used to set export options during the +publishing process. In most cases, these properties correspond to user +variables in Org. While some properties are available for all export +back-ends, most of them are back-end specific. The following sections +list properties along with the variable they belong to. See the +documentation string of these options for details. + + When a property is given a value in ‘org-publish-project-alist’, its +setting overrides the value of the corresponding user variable (if any) +during publishing. Options set within a file (*note Export settings::), +however, override everything. + +Generic properties +.................. + +‘:archived-trees’ ‘org-export-with-archived-trees’ +‘:exclude-tags’ ‘org-export-exclude-tags’ +‘:headline-levels’ ‘org-export-headline-levels’ +‘:language’ ‘org-export-default-language’ +‘:preserve-breaks’ ‘org-export-preserve-breaks’ +‘:section-numbers’ ‘org-export-with-section-numbers’ +‘:select-tags’ ‘org-export-select-tags’ +‘:with-author’ ‘org-export-with-author’ +‘:with-broken-links’ ‘org-export-with-broken-links’ +‘:with-clocks’ ‘org-export-with-clocks’ +‘:with-creator’ ‘org-export-with-creator’ +‘:with-date’ ‘org-export-with-date’ +‘:with-drawers’ ‘org-export-with-drawers’ +‘:with-email’ ‘org-export-with-email’ +‘:with-emphasize’ ‘org-export-with-emphasize’ +‘:with-fixed-width’ ‘org-export-with-fixed-width’ +‘:with-footnotes’ ‘org-export-with-footnotes’ +‘:with-latex’ ‘org-export-with-latex’ +‘:with-planning’ ‘org-export-with-planning’ +‘:with-priority’ ‘org-export-with-priority’ +‘:with-properties’ ‘org-export-with-properties’ +‘:with-special-strings’ ‘org-export-with-special-strings’ +‘:with-sub-superscript’ ‘org-export-with-sub-superscripts’ +‘:with-tables’ ‘org-export-with-tables’ +‘:with-tags’ ‘org-export-with-tags’ +‘:with-tasks’ ‘org-export-with-tasks’ +‘:with-timestamps’ ‘org-export-with-timestamps’ +‘:with-title’ ‘org-export-with-title’ +‘:with-toc’ ‘org-export-with-toc’ +‘:with-todo-keywords’ ‘org-export-with-todo-keywords’ + +ASCII specific properties +......................... + +‘:ascii-bullets’ ‘org-ascii-bullets’ +‘:ascii-caption-above’ ‘org-ascii-caption-above’ +‘:ascii-charset’ ‘org-ascii-charset’ +‘:ascii-global-margin’ ‘org-ascii-global-margin’ +‘:ascii-format-drawer-function’ ‘org-ascii-format-drawer-function’ +‘:ascii-format-inlinetask-function’ ‘org-ascii-format-inlinetask-function’ +‘:ascii-headline-spacing’ ‘org-ascii-headline-spacing’ +‘:ascii-indented-line-width’ ‘org-ascii-indented-line-width’ +‘:ascii-inlinetask-width’ ‘org-ascii-inlinetask-width’ +‘:ascii-inner-margin’ ‘org-ascii-inner-margin’ +‘:ascii-links-to-notes’ ‘org-ascii-links-to-notes’ +‘:ascii-list-margin’ ‘org-ascii-list-margin’ +‘:ascii-paragraph-spacing’ ‘org-ascii-paragraph-spacing’ +‘:ascii-quote-margin’ ‘org-ascii-quote-margin’ +‘:ascii-table-keep-all-vertical-lines’ ‘org-ascii-table-keep-all-vertical-lines’ +‘:ascii-table-use-ascii-art’ ‘org-ascii-table-use-ascii-art’ +‘:ascii-table-widen-columns’ ‘org-ascii-table-widen-columns’ +‘:ascii-text-width’ ‘org-ascii-text-width’ +‘:ascii-underline’ ‘org-ascii-underline’ +‘:ascii-verbatim-format’ ‘org-ascii-verbatim-format’ + +Beamer specific properties +.......................... + +‘:beamer-theme’ ‘org-beamer-theme’ +‘:beamer-column-view-format’ ‘org-beamer-column-view-format’ +‘:beamer-environments-extra’ ‘org-beamer-environments-extra’ +‘:beamer-frame-default-options’ ‘org-beamer-frame-default-options’ +‘:beamer-outline-frame-options’ ‘org-beamer-outline-frame-options’ +‘:beamer-outline-frame-title’ ‘org-beamer-outline-frame-title’ +‘:beamer-subtitle-format’ ‘org-beamer-subtitle-format’ + +HTML specific properties +........................ + +‘:html-allow-name-attribute-in-anchors’ ‘org-html-allow-name-attribute-in-anchors’ +‘:html-checkbox-type’ ‘org-html-checkbox-type’ +‘:html-container’ ‘org-html-container-element’ +‘:html-divs’ ‘org-html-divs’ +‘:html-doctype’ ‘org-html-doctype’ +‘:html-extension’ ‘org-html-extension’ +‘:html-footnote-format’ ‘org-html-footnote-format’ +‘:html-footnote-separator’ ‘org-html-footnote-separator’ +‘:html-footnotes-section’ ‘org-html-footnotes-section’ +‘:html-format-drawer-function’ ‘org-html-format-drawer-function’ +‘:html-format-headline-function’ ‘org-html-format-headline-function’ +‘:html-format-inlinetask-function’ ‘org-html-format-inlinetask-function’ +‘:html-head-extra’ ‘org-html-head-extra’ +‘:html-head-include-default-style’ ‘org-html-head-include-default-style’ +‘:html-head-include-scripts’ ‘org-html-head-include-scripts’ +‘:html-head’ ‘org-html-head’ +‘:html-home/up-format’ ‘org-html-home/up-format’ +‘:html-html5-fancy’ ‘org-html-html5-fancy’ +‘:html-indent’ ‘org-html-indent’ +‘:html-infojs-options’ ‘org-html-infojs-options’ +‘:html-infojs-template’ ‘org-html-infojs-template’ +‘:html-inline-image-rules’ ‘org-html-inline-image-rules’ +‘:html-inline-images’ ‘org-html-inline-images’ +‘:html-link-home’ ‘org-html-link-home’ +‘:html-link-org-files-as-html’ ‘org-html-link-org-files-as-html’ +‘:html-link-up’ ‘org-html-link-up’ +‘:html-link-use-abs-url’ ‘org-html-link-use-abs-url’ +‘:html-mathjax-options’ ‘org-html-mathjax-options’ +‘:html-mathjax-template’ ‘org-html-mathjax-template’ +‘:html-metadata-timestamp-format’ ‘org-html-metadata-timestamp-format’ +‘:html-postamble-format’ ‘org-html-postamble-format’ +‘:html-postamble’ ‘org-html-postamble’ +‘:html-preamble-format’ ‘org-html-preamble-format’ +‘:html-preamble’ ‘org-html-preamble’ +‘:html-table-align-individual-fields’ ‘org-html-table-align-individual-fields’ +‘:html-table-attributes’ ‘org-html-table-default-attributes’ +‘:html-table-caption-above’ ‘org-html-table-caption-above’ +‘:html-table-data-tags’ ‘org-html-table-data-tags’ +‘:html-table-header-tags’ ‘org-html-table-header-tags’ +‘:html-table-row-tags’ ‘org-html-table-row-tags’ +‘:html-table-use-header-tags-for-first-column’ ‘org-html-table-use-header-tags-for-first-column’ +‘:html-tag-class-prefix’ ‘org-html-tag-class-prefix’ +‘:html-text-markup-alist’ ‘org-html-text-markup-alist’ +‘:html-todo-kwd-class-prefix’ ‘org-html-todo-kwd-class-prefix’ +‘:html-toplevel-hlevel’ ‘org-html-toplevel-hlevel’ +‘:html-use-infojs’ ‘org-html-use-infojs’ +‘:html-validation-link’ ‘org-html-validation-link’ +‘:html-viewport’ ‘org-html-viewport’ +‘:html-xml-declaration’ ‘org-html-xml-declaration’ + +LaTeX specific properties +......................... + +‘:latex-active-timestamp-format’ ‘org-latex-active-timestamp-format’ +‘:latex-caption-above’ ‘org-latex-caption-above’ +‘:latex-classes’ ‘org-latex-classes’ +‘:latex-class’ ‘org-latex-default-class’ +‘:latex-compiler’ ‘org-latex-compiler’ +‘:latex-default-figure-position’ ‘org-latex-default-figure-position’ +‘:latex-default-table-environment’ ‘org-latex-default-table-environment’ +‘:latex-default-table-mode’ ‘org-latex-default-table-mode’ +‘:latex-diary-timestamp-format’ ‘org-latex-diary-timestamp-format’ +‘:latex-footnote-defined-format’ ‘org-latex-footnote-defined-format’ +‘:latex-footnote-separator’ ‘org-latex-footnote-separator’ +‘:latex-format-drawer-function’ ‘org-latex-format-drawer-function’ +‘:latex-format-headline-function’ ‘org-latex-format-headline-function’ +‘:latex-format-inlinetask-function’ ‘org-latex-format-inlinetask-function’ +‘:latex-hyperref-template’ ‘org-latex-hyperref-template’ +‘:latex-image-default-height’ ‘org-latex-image-default-height’ +‘:latex-image-default-option’ ‘org-latex-image-default-option’ +‘:latex-image-default-width’ ‘org-latex-image-default-width’ +‘:latex-images-centered’ ‘org-latex-images-centered’ +‘:latex-inactive-timestamp-format’ ‘org-latex-inactive-timestamp-format’ +‘:latex-inline-image-rules’ ‘org-latex-inline-image-rules’ +‘:latex-link-with-unknown-path-format’ ‘org-latex-link-with-unknown-path-format’ +‘:latex-listings-langs’ ‘org-latex-listings-langs’ +‘:latex-listings-options’ ‘org-latex-listings-options’ +‘:latex-listings’ ‘org-latex-listings’ +‘:latex-minted-langs’ ‘org-latex-minted-langs’ +‘:latex-minted-options’ ‘org-latex-minted-options’ +‘:latex-prefer-user-labels’ ‘org-latex-prefer-user-labels’ +‘:latex-subtitle-format’ ‘org-latex-subtitle-format’ +‘:latex-subtitle-separate’ ‘org-latex-subtitle-separate’ +‘:latex-table-scientific-notation’ ‘org-latex-table-scientific-notation’ +‘:latex-tables-booktabs’ ‘org-latex-tables-booktabs’ +‘:latex-tables-centered’ ‘org-latex-tables-centered’ +‘:latex-text-markup-alist’ ‘org-latex-text-markup-alist’ +‘:latex-title-command’ ‘org-latex-title-command’ +‘:latex-toc-command’ ‘org-latex-toc-command’ + +Markdown specific properties +............................ + +‘:md-footnote-format’ ‘org-md-footnote-format’ +‘:md-footnotes-section’ ‘org-md-footnotes-section’ +‘:md-headline-style’ ‘org-md-headline-style’ + +ODT specific properties +....................... + +‘:odt-content-template-file’ ‘org-odt-content-template-file’ +‘:odt-display-outline-level’ ‘org-odt-display-outline-level’ +‘:odt-fontify-srcblocks’ ‘org-odt-fontify-srcblocks’ +‘:odt-format-drawer-function’ ‘org-odt-format-drawer-function’ +‘:odt-format-headline-function’ ‘org-odt-format-headline-function’ +‘:odt-format-inlinetask-function’ ‘org-odt-format-inlinetask-function’ +‘:odt-inline-formula-rules’ ‘org-odt-inline-formula-rules’ +‘:odt-inline-image-rules’ ‘org-odt-inline-image-rules’ +‘:odt-pixels-per-inch’ ‘org-odt-pixels-per-inch’ +‘:odt-styles-file’ ‘org-odt-styles-file’ +‘:odt-table-styles’ ‘org-odt-table-styles’ +‘:odt-use-date-fields’ ‘org-odt-use-date-fields’ + +Texinfo specific properties +........................... + +‘:texinfo-active-timestamp-format’ ‘org-texinfo-active-timestamp-format’ +‘:texinfo-classes’ ‘org-texinfo-classes’ +‘:texinfo-class’ ‘org-texinfo-default-class’ +‘:texinfo-table-default-markup’ ‘org-texinfo-table-default-markup’ +‘:texinfo-diary-timestamp-format’ ‘org-texinfo-diary-timestamp-format’ +‘:texinfo-filename’ ‘org-texinfo-filename’ +‘:texinfo-format-drawer-function’ ‘org-texinfo-format-drawer-function’ +‘:texinfo-format-headline-function’ ‘org-texinfo-format-headline-function’ +‘:texinfo-format-inlinetask-function’ ‘org-texinfo-format-inlinetask-function’ +‘:texinfo-inactive-timestamp-format’ ‘org-texinfo-inactive-timestamp-format’ +‘:texinfo-link-with-unknown-path-format’ ‘org-texinfo-link-with-unknown-path-format’ +‘:texinfo-node-description-column’ ‘org-texinfo-node-description-column’ +‘:texinfo-table-scientific-notation’ ‘org-texinfo-table-scientific-notation’ +‘:texinfo-tables-verbatim’ ‘org-texinfo-tables-verbatim’ +‘:texinfo-text-markup-alist’ ‘org-texinfo-text-markup-alist’ + + +File: org, Node: Publishing links, Next: Sitemap, Prev: Publishing options, Up: Configuration + +13.1.6 Links between published files +------------------------------------ + +To create a link from one Org file to another, you would use something +like ‘[[file:foo.org][The foo]]’ or simply ‘file:foo.org’ (*note +External links::). When published, this link becomes a link to +‘foo.html’. You can thus interlink the pages of your “org web” project +and the links will work as expected when you publish them to HTML. If +you also publish the Org source file and want to link to it, use an +‘http:’ link instead of a ‘file:’ link, because ‘file:’ links are +converted to link to the corresponding ‘html’ file. + + You may also link to related files, such as images. Provided you are +careful with relative file names, and provided you have also configured +Org to upload the related files, these links will work too. See *note +Complex example::, for an example of this usage. + + Eventually, links between published documents can contain some search +options (*note Search options::), which will be resolved to the +appropriate location in the linked file. For example, once published to +HTML, the following links all point to a dedicated anchor in ‘foo.html’. + + [[file:foo.org::*heading]] + [[file:foo.org::#custom-id]] + [[file:foo.org::target]] + + +File: org, Node: Sitemap, Next: Generating an index, Prev: Publishing links, Up: Configuration + +13.1.7 Generating a sitemap +--------------------------- + +The following properties may be used to control publishing of a map of +files for a given project. + +‘:auto-sitemap’ When non-‘nil’, publish a sitemap during + ‘org-publish-current-project’ or + ‘org-publish-all’. + +‘:sitemap-filename’ Filename for output of sitemap. Defaults to + ‘sitemap.org’ (which becomes ‘sitemap.html’). + +‘:sitemap-title’ Title of sitemap page. Defaults to name of + file. + +‘:sitemap-format-entry’ With this option one can tell how a site-map + entry is formatted in the site-map. It is a + function called with three arguments: the + file or directory name relative to base + directory of the project, the site-map style + and the current project. It is expected to + return a string. Default value turns file + names into links and use document titles as + descriptions. For specific formatting needs, + one can use ‘org-publish-find-date’, + ‘org-publish-find-title’ and + ‘org-publish-find-property’, to retrieve + additional information about published + documents. + +‘:sitemap-function’ Plug-in function to use for generation of the + sitemap. It is called with two arguments: + the title of the site-map and a + representation of the files and directories + involved in the project as a radio list + (*note Radio lists::). The latter can + further be transformed using + ‘org-list-to-generic’, ‘org-list-to-subtree’ + and alike. Default value generates a plain + list of links to all files in the project. + +‘:sitemap-sort-folders’ Where folders should appear in the sitemap. + Set this to ‘first’ (default) or ‘last’ to + display folders first or last, respectively. + When set to ‘ignore’, folders are ignored + altogether. Any other value will mix files + and folders. This variable has no effect + when site-map style is ‘tree’. + +‘:sitemap-sort-files’ How the files are sorted in the site map. + Set this to ‘alphabetically’ (default), + ‘chronologically’ or ‘anti-chronologically’. + ‘chronologically’ sorts the files with older + date first while ‘anti-chronologically’ sorts + the files with newer date first. + ‘alphabetically’ sorts the files + alphabetically. The date of a file is + retrieved with ‘org-publish-find-date’. + +‘:sitemap-ignore-case’ Should sorting be case-sensitive? Default + ‘nil’. + +‘:sitemap-date-format’ Format string for the ‘format-time-string’ + function that tells how a sitemap entry’s + date is to be formatted. This property + bypasses ‘org-publish-sitemap-date-format’ + which defaults to ‘%Y-%m-%d’. + + + +File: org, Node: Generating an index, Prev: Sitemap, Up: Configuration + +13.1.8 Generating an index +-------------------------- + +Org mode can generate an index across the files of a publishing project. + +‘:makeindex’ When non-‘nil’, generate in index in the file + ‘theindex.org’ and publish it as ‘theindex.html’. + + The file will be created when first publishing a project with the +‘:makeindex’ set. The file only contains a statement ‘#+INCLUDE: +"theindex.inc"’. You can then build around this include statement by +adding a title, style information, etc. + + Index entries are specified with ‘#+INDEX’ keyword. An entry that +contains an exclamation mark will create a sub item. + + * Curriculum Vitae + #+INDEX: CV + #+INDEX: Application!CV + + +File: org, Node: Uploading files, Next: Sample configuration, Prev: Configuration, Up: Publishing + +13.2 Uploading files +==================== + +For those people already utilizing third party sync tools such as +‘rsync’ or ‘unison’, it might be preferable not to use the built in +remote publishing facilities of Org mode which rely heavily on Tramp. +Tramp, while very useful and powerful, tends not to be so efficient for +multiple file transfer and has been known to cause problems under heavy +usage. + + Specialized synchronization utilities offer several advantages. In +addition to timestamp comparison, they also do content and +permissions/attribute checks. For this reason you might prefer to +publish your web to a local directory (possibly even in place with your +Org files) and then use ‘unison’ or ‘rsync’ to do the synchronization +with the remote host. + + Since Unison (for example) can be configured as to which files to +transfer to a certain remote destination, it can greatly simplify the +project publishing definition. Simply keep all files in the correct +location, process your Org files with ‘org-publish’ and let the +synchronization tool do the rest. You do not need, in this scenario, to +include attachments such as ‘jpg’, ‘css’ or ‘gif’ files in the project +definition since the 3rd party tool syncs them. + + Publishing to a local directory is also much faster than to a remote +one, so that you can afford more easily to republish entire projects. +If you set ‘org-publish-use-timestamps-flag’ to ‘nil’, you gain the main +benefit of re-including any changed external files such as source +example files you might include with ‘#+INCLUDE:’. The timestamp +mechanism in Org is not smart enough to detect if included files have +been modified. + + +File: org, Node: Sample configuration, Next: Triggering publication, Prev: Uploading files, Up: Publishing + +13.3 Sample configuration +========================= + +Below we provide two example configurations. The first one is a simple +project publishing only a set of Org files. The second example is more +complex, with a multi-component project. + +* Menu: + +* Simple example:: One-component publishing +* Complex example:: A multi-component publishing example + + +File: org, Node: Simple example, Next: Complex example, Up: Sample configuration + +13.3.1 Example: simple publishing configuration +----------------------------------------------- + +This example publishes a set of Org files to the ‘public_html’ directory +on the local machine. + + (setq org-publish-project-alist + '(("org" + :base-directory "~/org/" + :publishing-directory "~/public_html" + :publishing-function org-html-publish-to-html + :section-numbers nil + :with-toc nil + :html-head ""))) + + +File: org, Node: Complex example, Prev: Simple example, Up: Sample configuration + +13.3.2 Example: complex publishing configuration +------------------------------------------------ + +This more complicated example publishes an entire website, including Org +files converted to HTML, image files, Emacs Lisp source code, and style +sheets. The publishing directory is remote and private files are +excluded. + + To ensure that links are preserved, care should be taken to replicate +your directory structure on the web server, and to use relative file +paths. For example, if your Org files are kept in ‘~/org’ and your +publishable images in ‘~/images’, you would link to an image with + file:../images/myimage.png + On the web server, the relative path to the image should be the same. +You can accomplish this by setting up an "images" folder in the right +place on the web server, and publishing images to it. + + (setq org-publish-project-alist + '(("orgfiles" + :base-directory "~/org/" + :base-extension "org" + :publishing-directory "/ssh:user@host:~/html/notebook/" + :publishing-function org-html-publish-to-html + :exclude "PrivatePage.org" ;; regexp + :headline-levels 3 + :section-numbers nil + :with-toc nil + :html-head "" + :html-preamble t) + + ("images" + :base-directory "~/images/" + :base-extension "jpg\\|gif\\|png" + :publishing-directory "/ssh:user@host:~/html/images/" + :publishing-function org-publish-attachment) + + ("other" + :base-directory "~/other/" + :base-extension "css\\|el" + :publishing-directory "/ssh:user@host:~/html/other/" + :publishing-function org-publish-attachment) + ("website" :components ("orgfiles" "images" "other")))) + + +File: org, Node: Triggering publication, Prev: Sample configuration, Up: Publishing + +13.4 Triggering publication +=========================== + +Once properly configured, Org can publish with the following commands: + +‘C-c C-e P x (org-publish)’ + Prompt for a specific project and publish all files that belong to + it. +‘C-c C-e P p (org-publish-current-project)’ + Publish the project containing the current file. +‘C-c C-e P f (org-publish-current-file)’ + Publish only the current file. +‘C-c C-e P a (org-publish-all)’ + Publish every project. + + Org uses timestamps to track when a file has changed. The above +functions normally only publish changed files. You can override this +and force publishing of all files by giving a prefix argument to any of +the commands above, or by customizing the variable +‘org-publish-use-timestamps-flag’. This may be necessary in particular +if files include other files via ‘#+SETUPFILE:’ or ‘#+INCLUDE:’. + + +File: org, Node: Working with source code, Next: Miscellaneous, Prev: Publishing, Up: Top + +14 Working with source code +*************************** + +Source code here refers to any code typed in Org mode documents. Org +can manage source code in any Org file once such code is tagged with +begin and end markers. Working with source code begins with tagging +source code blocks. Tagged ‘src’ code blocks are not restricted to the +preamble or the end of an Org document; they can go anywhere—with a few +exceptions, such as not inside comments and fixed width areas. Here’s a +sample ‘src’ code block in emacs-lisp: + + #+BEGIN_SRC emacs-lisp + (defun org-xor (a b) + "Exclusive or." + (if a (not b) b)) + #+END_SRC + + Org can take the code in the block between the ‘#+BEGIN_SRC’ and +‘#+END_SRC’ tags, and format, compile, execute, and show the results. +Org can simplify many housekeeping tasks essential to modern code +maintenance. That’s why these blocks in Org mode literature are +sometimes referred to as ‘live code’ blocks (as compared to the static +text and documentation around it). Users can control how ‘live’ they +want each block by tweaking the headers for compiling, execution, +extraction. + + Org’s ‘src’ code block type is one of many block types, such as +quote, export, verse, latex, example, and verbatim. This section +pertains to ‘src’ code blocks between ‘#+BEGIN_SRC’ and ‘#+END_SRC’ + + For editing ‘src’ code blocks, Org provides native Emacs major-modes. +That leverages the latest Emacs features for that source code language +mode. + + For exporting, Org can then extract ‘src’ code blocks into compilable +source files (in a conversion process known as “tangling” in literate +programming terminology). + + For publishing, Org’s back-ends can handle the ‘src’ code blocks and +the text for output to a variety of formats with native syntax +highlighting. + + For executing the source code in the ‘src’ code blocks, Org provides +facilities that glue the tasks of compiling, collecting the results of +the execution, and inserting them back to the Org file. Besides text +output, results may include links to other data types that Emacs can +handle: audio, video, and graphics. + + An important feature of Org’s execution of the ‘src’ code blocks is +passing variables, functions, and results between ‘src’ blocks. Such +interoperability uses a common syntax even if these ‘src’ blocks are in +different source code languages. The integration extends to linking the +debugger’s error messages to the line in the ‘src’ code block in the Org +file. That should partly explain why this functionality by the original +contributors, Eric Schulte and Dan Davison, was called ‘Org Babel’. + + In literate programming, the main appeal is code and documentation +co-existing in one file. Org mode takes this several steps further. +First by enabling execution, and then by inserting results of that +execution back into the Org file. Along the way, Org provides extensive +formatting features, including handling tables. Org handles multiple +source code languages in one file, and provides a common syntax for +passing variables, functions, and results between ‘src’ code blocks. + + Org mode fulfills the promise of easy verification and maintenance of +publishing reproducible research by keeping all these in the same file: +text, data, code, configuration settings of the execution environment, +the results of the execution, and associated narratives, claims, +references, and internal and external links. + + Details of Org’s facilities for working with source code are shown +next. + +* Menu: + +* Structure of code blocks:: Code block syntax described +* Editing source code:: Language major-mode editing +* Exporting code blocks:: Export contents and/or results +* Extracting source code:: Create pure source code files +* Evaluating code blocks:: Place results of evaluation in the Org mode buffer +* Library of Babel:: Use and contribute to a library of useful code blocks +* Languages:: List of supported code block languages +* Header arguments:: Configure code block functionality +* Results of evaluation:: How evaluation results are handled +* Noweb reference syntax:: Literate programming in Org mode +* Key bindings and useful functions:: Work quickly with code blocks +* Batch execution:: Call functions from the command line + + +File: org, Node: Structure of code blocks, Next: Editing source code, Up: Working with source code + +14.1 Structure of code blocks +============================= + +Org offers two ways to structure source code in Org documents: in a +‘src’ block, and directly inline. Both specifications are shown below. + + A ‘src’ block conforms to this structure: + + #+NAME: + #+BEGIN_SRC
+ + #+END_SRC + + Org mode’s templates system (*note Easy templates::) speeds up +creating ‘src’ code blocks with just three keystrokes. Do not be +put-off by having to remember the source block syntax. Org also works +with other completion systems in Emacs, some of which predate Org and +have custom domain-specific languages for defining templates. Regular +use of templates reduces errors, increases accuracy, and maintains +consistency. + + An inline code block conforms to this structure: + + src_{} + + or + + src_[
]{} + +‘#+NAME: ’ + Optional. Names the ‘src’ block so it can be called, like a + function, from other ‘src’ blocks or inline blocks to evaluate or + to capture the results. Code from other blocks, other files, and + from table formulas (*note The spreadsheet::) can use the name to + reference a ‘src’ block. This naming serves the same purpose as + naming Org tables. Org mode requires unique names. For duplicate + names, Org mode’s behavior is undefined. +‘#+BEGIN_SRC’ +‘#+END_SRC’ + Mandatory. They mark the start and end of a block that Org + requires. The ‘#+BEGIN_SRC’ line takes additional arguments, as + described next. +‘’ + Mandatory for live code blocks. It is the identifier of the source + code language in the block. *Note Languages::, for identifiers of + supported languages. +‘’ + Optional. Switches provide finer control of the code execution, + export, and format (see the discussion of switches in *note Literal + examples::) +‘
’ + Optional. Heading arguments control many aspects of evaluation, + export and tangling of code blocks (*note Header arguments::). + Using Org’s properties feature, header arguments can be selectively + applied to the entire buffer or specific sub-trees of the Org + document. +‘source code, header arguments’ +‘’ + Source code in the dialect of the specified language identifier. + + +File: org, Node: Editing source code, Next: Exporting code blocks, Prev: Structure of code blocks, Up: Working with source code + +14.2 Editing source code +======================== + +‘C-c '’ for editing the current code block. It opens a new major-mode +edit buffer containing the body of the ‘src’ code block, ready for any +edits. ‘C-c '’ again to close the buffer and return to the Org buffer. + + ‘C-x C-s’ saves the buffer and updates the contents of the Org +buffer. + + Set ‘org-edit-src-auto-save-idle-delay’ to save the base buffer after +a certain idle delay time. + + Set ‘org-edit-src-turn-on-auto-save’ to auto-save this buffer into a +separate file using ‘auto-save-mode’. + + ‘C-c '’ to close the major-mode buffer and return back to the Org +buffer. + + While editing the source code in the major-mode, the ‘org-src-mode’ +minor mode remains active. It provides these customization variables as +described below. For even more variables, look in the customization +group ‘org-edit-structure’. + +‘org-src-lang-modes’ + If an Emacs major-mode named ‘-mode’ exists, where ‘’ + is the language identifier from code block’s header line, then the + edit buffer uses that major-mode. Use this variable to arbitrarily + map language identifiers to major modes. +‘org-src-window-setup’ + For specifying Emacs window arrangement when the new edit buffer is + created. +‘org-src-preserve-indentation’ + Default is ‘nil’. Source code is indented. This indentation + applies during export or tangling, and depending on the context, + may alter leading spaces and tabs. When non-‘nil’, source code is + aligned with the leftmost column. No lines are modified during + export or tangling, which is very useful for white-space sensitive + languages, such as Python. +‘org-src-ask-before-returning-to-edit-buffer’ + When ‘nil’, Org returns to the edit buffer without further prompts. + The default prompts for a confirmation. + + Set ‘org-src-fontify-natively’ to non-‘nil’ to turn on native code +fontification in the _Org_ buffer. Fontification of ‘src’ code blocks +can give visual separation of text and code on the display page. To +further customize the appearance of ‘org-block’ for specific languages, +customize ‘org-src-block-faces’. The following example shades the +background of regular blocks, and colors source blocks only for Python +and Emacs-Lisp languages. + (require 'color) + (set-face-attribute 'org-block nil :background + (color-darken-name + (face-attribute 'default :background) 3)) + + (setq org-src-block-faces '(("emacs-lisp" (:background "#EEE2FF")) + ("python" (:background "#E5FFB8")))) + + +File: org, Node: Exporting code blocks, Next: Extracting source code, Prev: Editing source code, Up: Working with source code + +14.3 Exporting code blocks +========================== + +Org can flexibly export just the _code_ from the code blocks, just the +_results_ of evaluation of the code block, _both_ the code and the +results of the code block evaluation, or _none_. Org defaults to +exporting _code_ for most languages. For some languages, such as +‘ditaa’, Org defaults to _results_. To export just the body of code +blocks, *note Literal examples::. To selectively export sub-trees of an +Org document, *note Exporting::. + + The ‘:exports’ header arguments control exporting code blocks only +and not inline code: + +Header arguments: +................. + +‘:exports code’ + This is the default for most languages where the body of the code + block is exported. See *note Literal examples:: for more. +‘:exports results’ + On export, Org includes only the results and not the code block. + After each evaluation, Org inserts the results after the end of + code block in the Org buffer. By default, Org replaces any + previous results. Org can also append results. +‘:exports both’ + Org exports both the code block and the results. +‘:exports none’ + Org does not export the code block nor the results. + + To stop Org from evaluating code blocks to speed exports, use the +header argument ‘:eval never-export’ (*note eval::). To stop Org from +evaluating code blocks for greater security, set the +‘org-export-use-babel’ variable to ‘nil’, but understand that header +arguments will have no effect. + + Turning off evaluation comes in handy when batch processing. For +example, markup languages for wikis, which have a high risk of untrusted +code. Stopping code block evaluation also stops evaluation of all +header arguments of the code block. This may not be desirable in some +circumstances. So during export, to allow evaluation of just the header +arguments but not any code evaluation in the source block, set ‘:eval +never-export’ (*note eval::). + + Org never evaluates code blocks in commented sub-trees when exporting +(*note Comment lines::). On the other hand, Org does evaluate code +blocks in sub-trees excluded from export (*note Export settings::). + + +File: org, Node: Extracting source code, Next: Evaluating code blocks, Prev: Exporting code blocks, Up: Working with source code + +14.4 Extracting source code +=========================== + +Extracting source code from code blocks is a basic task in literate +programming. Org has features to make this easy. In literate +programming parlance, documents on creation are _woven_ with code and +documentation, and on export, the code is _tangled_ for execution by a +computer. Org facilitates weaving and tangling for producing, +maintaining, sharing, and exporting literate programming documents. Org +provides extensive customization options for extracting source code. + + When Org tangles ‘src’ code blocks, it expands, merges, and +transforms them. Then Org recomposes them into one or more separate +files, as configured through the options. During this _tangling_ +process, Org expands variables in the source code, and resolves any +Noweb style references (*note Noweb reference syntax::). + +Header arguments +................ + +‘:tangle no’ + By default, Org does not tangle the ‘src’ code block on export. +‘:tangle yes’ + Org extracts the contents of the code block for the tangled output. + By default, the output file name is the same as the Org file but + with a file extension derived from the language identifier of the + ‘src’ code block. +‘:tangle filename’ + Override the default file name with this one for the tangled + output. + +Functions +......... + +‘org-babel-tangle’ + Tangle the current file. Bound to ‘C-c C-v t’. + + With prefix argument only tangle the current ‘src’ code block. +‘org-babel-tangle-file’ + Choose a file to tangle. Bound to ‘C-c C-v f’. + +Hooks +..... + +‘org-babel-post-tangle-hook’ + This hook runs from within code tangled by ‘org-babel-tangle’, + making it suitable for post-processing, compilation, and evaluation + of code in the tangled files. + +Jumping between code and Org +............................ + +Debuggers normally link errors and messages back to the source code. +But for tangled files, we want to link back to the Org file, not to the +tangled source file. To make this extra jump, Org uses +‘org-babel-tangle-jump-to-org’ function with two additional source code +block header arguments: One, set ‘padline’ (*note padline::) to true +(the default setting). Two, set ‘comments’ (*note comments::) to +‘link’, which makes Org insert links to the Org file. + + +File: org, Node: Evaluating code blocks, Next: Library of Babel, Prev: Extracting source code, Up: Working with source code + +14.5 Evaluating code blocks +=========================== + +A note about security: With code evaluation comes the risk of harm. Org +safeguards by prompting for user’s permission before executing any code +in the source block. To customize this safeguard (or disable it) see +*note Code evaluation security::. + + Org captures the results of the ‘src’ code block evaluation and +inserts them in the Org file, right after the ‘src’ code block. The +insertion point is after a newline and the ‘#+RESULTS’ label. Org +creates the ‘#+RESULTS’ label if one is not already there. + + By default, Org enables only ‘emacs-lisp’ ‘src’ code blocks for +execution. See *note Languages:: for identifiers to enable other +languages. + + Org provides many ways to execute ‘src’ code blocks. ‘C-c C-c’ or +‘C-c C-v e’ with the point on a ‘src’ code block(1) calls the +‘org-babel-execute-src-block’ function, which executes the code in the +block, collects the results, and inserts them in the buffer. + + By calling a named code block(2) from an Org mode buffer or a table. +Org can call the named ‘src’ code blocks from the current Org mode +buffer or from the “Library of Babel” (*note Library of Babel::). +Whether inline syntax or the ‘#+CALL:’ syntax is used, the result is +wrapped based on the variable ‘org-babel-inline-result-wrap’, which by +default is set to ‘"=%s="’ to produce verbatim text suitable for markup. + + The syntax for ‘#+CALL:’ is + + #+CALL: () + #+CALL: []() + + The syntax for inline named code block is + + ... call_() ... + ... call_[]()[] ... + +‘’ + This is the name of the code block to be evaluated (*note Structure + of code blocks::). +‘’ + Org passes arguments to the code block using standard function call + syntax. For example, a ‘#+CALL:’ line that passes ‘4’ to a code + block named ‘double’, which declares the header argument ‘:var + n=2’, would be written as ‘#+CALL: double(n=4)’. Note how this + function call syntax is different from the header argument syntax. +‘’ + Org passes inside header arguments to the named ‘src’ code block + using the header argument syntax. Inside header arguments apply to + code block evaluation. For example, ‘[:results output]’ collects + results printed to ‘STDOUT’ during code execution of that block. + Note how this header argument syntax is different from the function + call syntax. +‘’ + End header arguments affect the results returned by the code block. + For example, ‘:results html’ wraps the results in a ‘BEGIN_EXPORT + html’ block before inserting the results in the Org buffer. + + For more examples of header arguments for ‘#+CALL:’ lines, *note + Arguments in function calls::. + + ---------- Footnotes ---------- + + (1) The option ‘org-babel-no-eval-on-ctrl-c-ctrl-c’ can be used to +remove code evaluation from the ‘C-c C-c’ key binding. + + (2) Actually, the constructs call_() and src_{} are not +evaluated when they appear in a keyword line (i.e. lines starting with +‘#+KEYWORD:’, *note In-buffer settings::). + + +File: org, Node: Library of Babel, Next: Languages, Prev: Evaluating code blocks, Up: Working with source code + +14.6 Library of Babel +===================== + +The “Library of Babel” is a collection of code blocks. Like a function +library, these code blocks can be called from other Org files. A +collection of useful code blocks is available on Worg +(https://orgmode.org/worg/library-of-babel.html). For remote code block +evaluation syntax, *note Evaluating code blocks::. + + For any user to add code to the library, first save the code in +regular ‘src’ code blocks of an Org file, and then load the Org file +with ‘org-babel-lob-ingest’, which is bound to ‘C-c C-v i’. + + +File: org, Node: Languages, Next: Header arguments, Prev: Library of Babel, Up: Working with source code + +14.7 Languages +============== + +Org supports the following languages for the ‘src’ code blocks: + +Language Identifier Language Identifier +---------------------------------------------------------------------------- +Asymptote asymptote Awk awk +C C C++ C++ +Clojure clojure CSS css +D d ditaa ditaa +Graphviz dot Emacs Calc calc +Emacs Lisp emacs-lisp Fortran fortran +gnuplot gnuplot Haskell haskell +Java java Javascript js +LaTeX latex Ledger ledger +Lisp lisp Lilypond lilypond +Lua lua MATLAB matlab +Mscgen mscgen Objective Caml ocaml +Octave octave Org mode org +Oz oz Perl perl +Plantuml plantuml Processing.js processing +Python python R R +Ruby ruby Sass sass +Scheme scheme GNU Screen screen +Sed sed shell sh +SQL sql SQLite sqlite +Vala vala + + Additional documentation for some languages are at +. + + By default, only ‘emacs-lisp’ is enabled for evaluation. To enable +or disable other languages, customize the ‘org-babel-load-languages’ +variable either through the Emacs customization interface, or by adding +code to the init file as shown next: + + In this example, evaluation is disabled for ‘emacs-lisp’, and enabled +for ‘R’. + + (org-babel-do-load-languages + 'org-babel-load-languages + '((emacs-lisp . nil) + (R . t))) + + Note that this is not the only way to enable a language. Org also +enables languages when loaded with ‘require’ statement. For example, +the following enables execution of ‘clojure’ code blocks: + + (require 'ob-clojure) + + +File: org, Node: Header arguments, Next: Results of evaluation, Prev: Languages, Up: Working with source code + +14.8 Header arguments +===================== + +Details of configuring header arguments are shown here. + +* Menu: + +* Using header arguments:: Different ways to set header arguments +* Specific header arguments:: List of header arguments + + +File: org, Node: Using header arguments, Next: Specific header arguments, Up: Header arguments + +14.8.1 Using header arguments +----------------------------- + +Since header arguments can be set in several ways, Org prioritizes them +in case of overlaps or conflicts by giving local settings a higher +priority. Header values in function calls, for example, override header +values from global defaults. +* Menu: + +* System-wide header arguments:: Set globally, language-specific +* Language-specific header arguments:: Set in the Org file’s headers +* Header arguments in Org mode properties:: Set in the Org file +* Language-specific mode properties:: +* Code block specific header arguments:: The most commonly used method +* Arguments in function calls:: The most specific level, takes highest priority + + +File: org, Node: System-wide header arguments, Next: Language-specific header arguments, Up: Using header arguments + +System-wide header arguments +............................ + +System-wide values of header arguments can be specified by adapting the +‘org-babel-default-header-args’ variable: + + :session => "none" + :results => "replace" + :exports => "code" + :cache => "no" + :noweb => "no" + + This example sets ‘:noweb’ header arguments to ‘yes’, which makes Org +expand ‘:noweb’ references by default. + + (setq org-babel-default-header-args + (cons '(:noweb . "yes") + (assq-delete-all :noweb org-babel-default-header-args))) + + +File: org, Node: Language-specific header arguments, Next: Header arguments in Org mode properties, Prev: System-wide header arguments, Up: Using header arguments + +Language-specific header arguments +.................................. + +Each language can have separate default header arguments by customizing +the variable ‘org-babel-default-header-args:’, where ‘’ is +the name of the language. For details, see the language-specific online +documentation at . + + +File: org, Node: Header arguments in Org mode properties, Next: Language-specific mode properties, Prev: Language-specific header arguments, Up: Using header arguments + +Header arguments in Org mode properties +....................................... + +For header arguments applicable to the buffer, use ‘#+PROPERTY:’ lines +anywhere in the Org mode file (*note Property syntax::). + + The following example sets only for ‘R’ code blocks to ‘session’, +making all the ‘R’ code blocks execute in the same session. Setting +‘results’ to ‘silent’ ignores the results of executions for all blocks, +not just ‘R’ code blocks; no results inserted for any block. + + #+PROPERTY: header-args:R :session *R* + #+PROPERTY: header-args :results silent + + Header arguments set through Org’s property drawers (*note Property +syntax::) apply at the sub-tree level on down. Since these property +drawers can appear anywhere in the file hierarchy, Org uses outermost +call or source block to resolve the values. Org ignores +‘org-use-property-inheritance’ setting. + + In this example, ‘:cache’ defaults to ‘yes’ for all code blocks in +the sub-tree starting with ‘sample header’. + + * sample header + :PROPERTIES: + :header-args: :cache yes + :END: + + Properties defined through ‘org-set-property’ function, bound to ‘C-c +C-x p’, apply to all active languages. They override properties set in +‘org-babel-default-header-args’. + + +File: org, Node: Language-specific mode properties, Next: Code block specific header arguments, Prev: Header arguments in Org mode properties, Up: Using header arguments + +Language-specific mode properties +................................. + +Language-specific header arguments are also read from properties +‘header-args:’ where ‘’ is the language identifier. For +example, + + * Heading + :PROPERTIES: + :header-args:clojure: :session *clojure-1* + :header-args:R: :session *R* + :END: + ** Subheading + :PROPERTIES: + :header-args:clojure: :session *clojure-2* + :END: + + would force separate sessions for clojure blocks in Heading and +Subheading, but use the same session for all ‘R’ blocks. Blocks in +Subheading inherit settings from Heading. + + +File: org, Node: Code block specific header arguments, Next: Arguments in function calls, Prev: Language-specific mode properties, Up: Using header arguments + +Code block specific header arguments +.................................... + +Header arguments are most commonly set at the ‘src’ code block level, on +the ‘#+BEGIN_SRC’ line. Arguments set at this level take precedence +over those set in the ‘org-babel-default-header-args’ variable, and also +those set as header properties. + + In the following example, setting ‘results’ to ‘silent’ makes it +ignore results of the code execution. Setting ‘:exports’ to ‘code’ +exports only the body of the ‘src’ code block to HTML or LaTeX.: + + #+NAME: factorial + #+BEGIN_SRC haskell :results silent :exports code :var n=0 + fac 0 = 1 + fac n = n * fac (n-1) + #+END_SRC + + The same header arguments in an inline ‘src’ code block: + + src_haskell[:exports both]{fac 5} + + Code block header arguments can span multiple lines using ‘#+HEADER:’ +on each line. Note that Org currently accepts the plural spelling of +‘#+HEADER:’ only as a convenience for backward-compatibility. It may be +removed at some point. + + Multi-line header arguments on an unnamed ‘src’ code block: + + #+HEADER: :var data1=1 + #+BEGIN_SRC emacs-lisp :var data2=2 + (message "data1:%S, data2:%S" data1 data2) + #+END_SRC + + #+RESULTS: + : data1:1, data2:2 + + Multi-line header arguments on a named ‘src’ code block: + + #+NAME: named-block + #+HEADER: :var data=2 + #+BEGIN_SRC emacs-lisp + (message "data:%S" data) + #+END_SRC + + #+RESULTS: named-block + : data:2 + + +File: org, Node: Arguments in function calls, Prev: Code block specific header arguments, Up: Using header arguments + +Arguments in function calls +........................... + +Header arguments in function calls are the most specific and override +all other settings in case of an overlap. They get the highest +priority. Two ‘#+CALL:’ examples are shown below. For the complete +syntax of ‘#+CALL:’ lines, see *note Evaluating code blocks::. + + In this example, ‘:exports results’ header argument is applied to the +evaluation of the ‘#+CALL:’ line. + + #+CALL: factorial(n=5) :exports results + + In this example, ‘:session special’ header argument is applied to the +evaluation of ‘factorial’ code block. + + #+CALL: factorial[:session special](n=5) + + +File: org, Node: Specific header arguments, Prev: Using header arguments, Up: Header arguments + +14.8.2 Specific header arguments +-------------------------------- + +Org comes with many header arguments common to all languages. New +header arguments are added for specific languages as they become +available for use in ‘src’ code blocks. A header argument is specified +with an initial colon followed by the argument’s name in lowercase. +Common header arguments are: + +* Menu: + +* var:: Pass arguments to ‘src’ code blocks +* results:: Specify results type; how to collect +* file:: Specify a path for output file +* file-desc:: Specify a description for file results +* file-ext:: Specify an extension for file output +* output-dir:: Specify a directory for output file +* dir:: Specify the default directory for code block execution +* exports:: Specify exporting code, results, both, none +* tangle:: Toggle tangling; or specify file name +* mkdirp:: Toggle for parent directory creation for target files during tangling +* comments:: Toggle insertion of comments in tangled code files +* padline:: Control insertion of padding lines in tangled code files +* no-expand:: Turn off variable assignment and noweb expansion during tangling +* session:: Preserve the state of code evaluation +* noweb:: Toggle expansion of noweb references +* noweb-ref:: Specify block’s noweb reference resolution target +* noweb-sep:: String to separate noweb references +* cache:: Avoid re-evaluating unchanged code blocks +* sep:: Delimiter for writing tabular results outside Org +* hlines:: Handle horizontal lines in tables +* colnames:: Handle column names in tables +* rownames:: Handle row names in tables +* shebang:: Make tangled files executable +* tangle-mode:: Set permission of tangled files +* eval:: Limit evaluation of specific code blocks +* wrap:: Mark source block evaluation results +* post:: Post processing of results of code block evaluation +* prologue:: Text to prepend to body of code block +* epilogue:: Text to append to body of code block + + For language-specific header arguments, see *note Languages::. + + +File: org, Node: var, Next: results, Up: Specific header arguments + +14.8.2.1 ‘:var’ +............... + +Use ‘:var’ for passing arguments to ‘src’ code blocks. The specifics of +variables in ‘src’ code blocks vary by the source language and are +covered in the language-specific documentation. The syntax for ‘:var’, +however, is the same for all languages. This includes declaring a +variable, and assigning a default value. + + Arguments can take values as literals, or as references, or even as +Emacs Lisp code (*note Emacs Lisp evaluation of variables: var.). +References are names from the Org file from the lines ‘#+NAME:’ or +‘#+RESULTS:’. References can also refer to tables, lists, +‘#+BEGIN_EXAMPLE’ blocks, other types of ‘src’ code blocks, or the +results of execution of ‘src’ code blocks. + + For better performance, Org can cache results of evaluations. But +caching comes with severe limitations (*note cache::). + + Argument values are indexed like arrays (*note Indexable variable +values: var.). + + The following syntax is used to pass arguments to ‘src’ code blocks +using the ‘:var’ header argument. + + :var name=assign + + The ‘assign’ is a literal value, such as a string ‘"string"’, a +number ‘9’, a reference to a table, a list, a literal example, another +code block (with or without arguments), or the results from evaluating a +code block. + + Here are examples of passing values by reference: + +“table” + an Org mode table named with either a ‘#+NAME:’ line + + #+NAME: example-table + | 1 | + | 2 | + | 3 | + | 4 | + + #+NAME: table-length + #+BEGIN_SRC emacs-lisp :var table=example-table + (length table) + #+END_SRC + + #+RESULTS: table-length + : 4 + +“list” + a simple list named with a ‘#+NAME:’ line. Note that only the top + level list items are passed along. Nested list items are ignored. + + #+NAME: example-list + - simple + - not + - nested + - list + + #+BEGIN_SRC emacs-lisp :var x=example-list + (print x) + #+END_SRC + + #+RESULTS: + | simple | list | + +“code block without arguments” + a code block name (from the example above), as assigned by + ‘#+NAME:’, optionally followed by parentheses + + #+BEGIN_SRC emacs-lisp :var length=table-length() + (* 2 length) + #+END_SRC + + #+RESULTS: + : 8 + +“code block with arguments” + a ‘src’ code block name, as assigned by ‘#+NAME:’, followed by + parentheses and optional arguments passed within the parentheses + following the ‘src’ code block name using standard function call + syntax + + #+NAME: double + #+BEGIN_SRC emacs-lisp :var input=8 + (* 2 input) + #+END_SRC + + #+RESULTS: double + : 16 + + #+NAME: squared + #+BEGIN_SRC emacs-lisp :var input=double(input=2) + (* input input) + #+END_SRC + + #+RESULTS: squared + : 4 + +“literal example” + a literal example block named with a ‘#+NAME:’ line + + #+NAME: literal-example + #+BEGIN_EXAMPLE + A literal example + on two lines + #+END_EXAMPLE + + #+NAME: read-literal-example + #+BEGIN_SRC emacs-lisp :var x=literal-example + (concatenate 'string x " for you.") + #+END_SRC + + #+RESULTS: read-literal-example + : A literal example + : on two lines for you. + + +Indexable variable values +......................... + +Indexing variable values enables referencing portions of a variable. +Indexes are 0 based with negative values counting backwards from the +end. If an index is separated by ‘,’s then each subsequent section will +index as the next dimension. Note that this indexing occurs _before_ +other table-related header arguments are applied, such as ‘:hlines’, +‘:colnames’ and ‘:rownames’. The following example assigns the last +cell of the first row the table ‘example-table’ to the variable ‘data’: + + #+NAME: example-table + | 1 | a | + | 2 | b | + | 3 | c | + | 4 | d | + + #+BEGIN_SRC emacs-lisp :var data=example-table[0,-1] + data + #+END_SRC + + #+RESULTS: + : a + + Ranges of variable values can be referenced using two integers +separated by a ‘:’, in which case the entire inclusive range is +referenced. For example the following assigns the middle three rows of +‘example-table’ to ‘data’. + + #+NAME: example-table + | 1 | a | + | 2 | b | + | 3 | c | + | 4 | d | + | 5 | 3 | + + #+BEGIN_SRC emacs-lisp :var data=example-table[1:3] + data + #+END_SRC + + #+RESULTS: + | 2 | b | + | 3 | c | + | 4 | d | + + To pick the entire range, use an empty index, or the single character +‘*’. ‘0:-1’ does the same thing. Example below shows how to reference +the first column only. + + #+NAME: example-table + | 1 | a | + | 2 | b | + | 3 | c | + | 4 | d | + + #+BEGIN_SRC emacs-lisp :var data=example-table[,0] + data + #+END_SRC + + #+RESULTS: + | 1 | 2 | 3 | 4 | + + Index referencing can be used for tables and code blocks. Index +referencing can handle any number of dimensions. Commas delimit +multiple dimensions, as shown below. + + #+NAME: 3D + #+BEGIN_SRC emacs-lisp + '(((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))) + #+END_SRC + + #+BEGIN_SRC emacs-lisp :var data=3D[1,,1] + data + #+END_SRC + + #+RESULTS: + | 11 | 14 | 17 | + +Emacs Lisp evaluation of variables +.................................. + +Emacs lisp code can set the values for variables. To differentiate a +value from lisp code, Org interprets any value starting with ‘(’, ‘[’, +‘'’ or ‘`’ as Emacs Lisp code. The result of evaluating that code is +then assigned to the value of that variable. The following example +shows how to reliably query and pass file name of the Org mode buffer to +a code block using headers. We need reliability here because the file’s +name could change once the code in the block starts executing. + + #+BEGIN_SRC sh :var filename=(buffer-file-name) :exports both + wc -w $filename + #+END_SRC + + Note that values read from tables and lists will not be mistakenly +evaluated as Emacs Lisp code, as illustrated in the following example. + + #+NAME: table + | (a b c) | + + #+HEADER: :var data=table[0,0] + #+BEGIN_SRC perl + $data + #+END_SRC + + #+RESULTS: + : (a b c) + + +File: org, Node: results, Next: file, Prev: var, Up: Specific header arguments + +14.8.2.2 ‘:results’ +................... + +There are four classes of ‘:results’ header arguments. Each ‘src’ code +block can take only one option per class. + + • collection for how the results should be collected from the ‘src’ + code block + • type for which type of result the code block will return; affects + how Org processes and inserts results in the Org buffer + • format for the result; affects how Org processes and inserts + results in the Org buffer + • handling for processing results after evaluation of the ‘src’ code + block + +Collection +.......... + +Collection options specify the results. Choose one of the options; they +are mutually exclusive. + + • ‘value’ Default. Functional mode. Result is the value returned by + the last statement in the ‘src’ code block. Languages like Python + may require an explicit ‘return’ statement in the ‘src’ code block. + Usage example: ‘:results value’. + • ‘output’ Scripting mode. Result is collected from STDOUT during + execution of the code in the ‘src’ code block. Usage example: + ‘:results output’. + +Type +.... + +Type tells what result types to expect from the execution of the code +block. Choose one of the options; they are mutually exclusive. The +default behavior is to automatically determine the result type. + + • ‘table’, ‘vector’ Interpret the results as an Org table. If the + result is a single value, create a table with one row and one + column. Usage example: ‘:results value table’. + • ‘list’ Interpret the results as an Org list. If the result is a + single value, create a list of one element. + • ‘scalar’, ‘verbatim’ Interpret literally and insert as quoted text. + Do not create a table. Usage example: ‘:results value verbatim’. + • ‘file’ Interpret as path to a file. Inserts a link to the file. + Usage example: ‘:results value file’. + +Format +...... + +Format pertains to the type of the result returned by the ‘src’ code +block. Choose one of the options; they are mutually exclusive. The +default follows from the type specified above. + + • ‘raw’ Interpreted as raw Org mode. Inserted directly into the + buffer. Aligned if it is a table. Usage example: ‘:results value + raw’. + • ‘org’ Results enclosed in a ‘BEGIN_SRC org’ block. For + comma-escape, either in the block, or export the file. Usage + example: ‘:results value org’. + • ‘html’ Results enclosed in a ‘BEGIN_EXPORT html’ block. Usage + example: ‘:results value html’. + • ‘latex’ Results enclosed in a ‘BEGIN_EXPORT latex’ block. Usage + example: ‘:results value latex’. + • ‘code’ Result enclosed in a ‘src’ code block. Useful for parsing. + Usage example: ‘:results value code’. + • ‘pp’ Result converted to pretty-print source code. Enclosed in a + ‘src’ code block. Languages supported: Emacs Lisp, Python, and + Ruby. Usage example: ‘:results value pp’. + • ‘drawer’ Result wrapped in a RESULTS drawer. Useful for containing + ‘raw’ or ‘org’ results for later scripting and automated + processing. Usage example: ‘:results value drawer’. + +Handling +........ + +Handling options after collecting the results. + + • ‘silent’ Do not insert results in the Org mode buffer, but echo + them in the minibuffer. Usage example: ‘:results output silent’. + • ‘replace’ Default. Insert results in the Org buffer. Remove + previous results. Usage example: ‘:results output replace’. + • ‘append’ Append results to the Org buffer. Latest results are at + the bottom. Does not remove previous results. Usage example: + ‘:results output append’. + • ‘prepend’ Prepend results to the Org buffer. Latest results are at + the top. Does not remove previous results. Usage example: + ‘:results output prepend’. + + +File: org, Node: file, Next: file-desc, Prev: results, Up: Specific header arguments + +14.8.2.3 ‘:file’ +................ + +An external ‘:file’ that saves the results of execution of the code +block. The ‘:file’ is either a file name or two strings, where the +first is the file name and the second is the description. A link to the +file is inserted. It uses an Org mode style ‘[[file:]]’ link (*note +Link format::). Some languages, such as ‘R’, ‘dot’, ‘ditaa’, and +‘gnuplot’, automatically wrap the source code in additional boilerplate +code. Such code wrapping helps recreate the output, especially graphics +output, by executing just the ‘:file’ contents. + + +File: org, Node: file-desc, Next: file-ext, Prev: file, Up: Specific header arguments + +14.8.2.4 ‘:file-desc’ +..................... + +A description of the results file. Org uses this description for the +link (see *note Link format::) it inserts in the Org file. If the +‘:file-desc’ has no value, Org will use file name for both the “link” +and the “description” portion of the Org mode link. + + +File: org, Node: file-ext, Next: output-dir, Prev: file-desc, Up: Specific header arguments + +14.8.2.5 ‘:file-ext’ +.................... + +File name extension for the output file. Org generates the file’s +complete name, and extension by combining ‘:file-ext’, ‘#+NAME:’ of the +source block, and the *note output-dir:: header argument. To override +this auto generated file name, use the ‘:file’ header argument. + + +File: org, Node: output-dir, Next: dir, Prev: file-ext, Up: Specific header arguments + +14.8.2.6 ‘:output-dir’ +...................... + +Specifies the ‘:output-dir’ for the results file. Org accepts an +absolute path (beginning with ‘/’) or a relative directory (without +‘/’). The value can be combined with ‘#+NAME:’ of the source block and +*note file:: or *note file-ext:: header arguments. + + +File: org, Node: dir, Next: exports, Prev: output-dir, Up: Specific header arguments + +14.8.2.7 ‘:dir’ and remote execution +.................................... + +While the ‘:file’ header argument can be used to specify the path to the +output file, ‘:dir’ specifies the default directory during ‘src’ code +block execution. If it is absent, then the directory associated with +the current buffer is used. In other words, supplying ‘:dir path’ +temporarily has the same effect as changing the current directory with +‘M-x cd path ’, and then not supplying ‘:dir’. Under the surface, +‘:dir’ simply sets the value of the Emacs variable ‘default-directory’. + + When using ‘:dir’, relative paths (for example, ‘:file myfile.jpg’ or +‘:file results/myfile.jpg’) become relative to the default directory. + + For example, to save the plot file in the ‘Work’ folder of the home +directory (notice tilde is expanded): + + #+BEGIN_SRC R :file myplot.png :dir ~/Work + matplot(matrix(rnorm(100), 10), type="l") + #+END_SRC + +Remote execution +................ + +To evaluate the ‘src’ code block on a remote machine, supply a remote s +directory name using ‘Tramp’ syntax. For example: + + #+BEGIN_SRC R :file plot.png :dir /scp:dand@yakuba.princeton.edu: + plot(1:10, main=system("hostname", intern=TRUE)) + #+END_SRC + + Org first captures the text results as usual for insertion in the Org +file. Then Org also inserts a link to the remote file, thanks to Emacs +‘Tramp’. Org constructs the remote path to the file name from ‘:dir’ +and ‘default-directory’, as illustrated here: + + [[file:/scp:dand@yakuba.princeton.edu:/home/dand/plot.png][plot.png]] + +Some more warnings +.................. + + • When ‘:dir’ is used with ‘:session’, Org sets the starting + directory for a new session. But Org will not alter the directory + of an already existing session. + • Do not use ‘:dir’ with ‘:exports results’ or with ‘:exports both’ + to avoid Org inserting incorrect links to remote files. That is + because Org does not expand ‘default directory’ to avoid some + underlying portability issues. + + +File: org, Node: exports, Next: tangle, Prev: dir, Up: Specific header arguments + +14.8.2.8 ‘:exports’ +................... + +The ‘:exports’ header argument is to specify if that part of the Org +file is exported to, say, HTML or LaTeX formats. Note that ‘:exports’ +affects only ‘src’ code blocks and not inline code. + + • ‘code’ The default. The body of code is included into the exported + file. Example: ‘:exports code’. + • ‘results’ The results of evaluation of the code is included in the + exported file. Example: ‘:exports results’. + • ‘both’ Both the code and results of evaluation are included in the + exported file. Example: ‘:exports both’. + • ‘none’ Neither the code nor the results of evaluation is included + in the exported file. Whether the code is evaluated at all depends + on other options. Example: ‘:exports none’. + + +File: org, Node: tangle, Next: mkdirp, Prev: exports, Up: Specific header arguments + +14.8.2.9 ‘:tangle’ +.................. + +The ‘:tangle’ header argument specifies if the ‘src’ code block is +exported to source file(s). + + • ‘tangle’ Export the ‘src’ code block to source file. The file name + for the source file is derived from the name of the Org file, and + the file extension is derived from the source code language + identifier. Example: ‘:tangle yes’. + • ‘no’ The default. Do not extract the code a source code file. + Example: ‘:tangle no’. + • other Export the ‘src’ code block to source file whose file name is + derived from any string passed to the ‘:tangle’ header argument. + Org derives the file name as being relative to the directory of the + Org file’s location. Example: ‘:tangle path’. + + +File: org, Node: mkdirp, Next: comments, Prev: tangle, Up: Specific header arguments + +14.8.2.10 ‘:mkdirp’ +................... + +The ‘:mkdirp’ header argument creates parent directories for tangled +files if the directory does not exist. ‘yes’ enables directory creation +and ‘no’ inhibits directory creation. + + +File: org, Node: comments, Next: padline, Prev: mkdirp, Up: Specific header arguments + +14.8.2.11 ‘:comments’ +..................... + +Controls inserting comments into tangled files. These are above and +beyond whatever comments may already exist in the ‘src’ code block. + + • ‘no’ The default. Do not insert any extra comments during + tangling. + • ‘link’ Wrap the ‘src’ code block in comments. Include links + pointing back to the place in the Org file from where the code was + tangled. + • ‘yes’ Kept for backward compatibility; same as “link”. + • ‘org’ Nearest headline text from Org file is inserted as comment. + The exact text that is inserted is picked from the leading context + of the source block. + • ‘both’ Includes both “link” and “org” comment options. + • ‘noweb’ Includes “link” comment option, expands noweb references, + and wraps them in link comments inside the body of the ‘src’ code + block. + + +File: org, Node: padline, Next: no-expand, Prev: comments, Up: Specific header arguments + +14.8.2.12 ‘:padline’ +.................... + +Control insertion of newlines to pad ‘src’ code blocks in the tangled +file. + • ‘yes’ Default. Insert a newline before and after each ‘src’ code + block in the tangled file. + • ‘no’ Do not insert newlines to pad the tangled ‘src’ code blocks. + + +File: org, Node: no-expand, Next: session, Prev: padline, Up: Specific header arguments + +14.8.2.13 ‘:no-expand’ +...................... + +By default Org expands ‘src’ code blocks during tangling. The +‘:no-expand’ header argument turns off such expansions. Note that one +side-effect of expansion by ‘org-babel-expand-src-block’ also assigns +values to ‘:var’ (*note var::) variables. Expansions also replace Noweb +references with their targets (*note Noweb reference syntax::). Some of +these expansions may cause premature assignment, hence this option. +This option makes a difference only for tangling. It has no effect when +exporting since ‘src’ code blocks for execution have to be expanded +anyway. + + +File: org, Node: session, Next: noweb, Prev: no-expand, Up: Specific header arguments + +14.8.2.14 ‘:session’ +.................... + +The ‘:session’ header argument is for running multiple source code +blocks under one session. Org runs ‘src’ code blocks with the same +session name in the same interpreter process. + + • ‘none’ Default. Each ‘src’ code block gets a new interpreter + process to execute. The process terminates once the block is + evaluated. + • ‘other’ Any string besides ‘none’ turns that string into the name + of that session. For example, ‘:session mysession’ names it + ‘mysession’. If ‘:session’ has no argument, then the session name + is derived from the source language identifier. Subsequent blocks + with the same source code language use the same session. Depending + on the language, state variables, code from other blocks, and the + overall interpreted environment may be shared. Some interpreted + languages support concurrent sessions when subsequent source code + language blocks change session names. + + +File: org, Node: noweb, Next: noweb-ref, Prev: session, Up: Specific header arguments + +14.8.2.15 ‘:noweb’ +.................. + +The ‘:noweb’ header argument controls expansion of Noweb syntax +references (*note Noweb reference syntax::). Expansions occur when +source code blocks are evaluated, tangled, or exported. + + • ‘no’ Default. No expansion of Noweb syntax references in the body + of the code when evaluating, tangling, or exporting. + • ‘yes’ Expansion of Noweb syntax references in the body of the ‘src’ + code block when evaluating, tangling, or exporting. + • ‘tangle’ Expansion of Noweb syntax references in the body of the + ‘src’ code block when tangling. No expansion when evaluating or + exporting. + • ‘no-export’ Expansion of Noweb syntax references in the body of the + ‘src’ code block when evaluating or tangling. No expansion when + exporting. + • ‘strip-export’ Expansion of Noweb syntax references in the body of + the ‘src’ code block when expanding prior to evaluating or + tangling. Removes Noweb syntax references when exporting. + • ‘eval’ Expansion of Noweb syntax references in the body of the + ‘src’ code block only before evaluating. + +Noweb prefix lines +.................. + +Noweb insertions now honor prefix characters that appear before the +Noweb syntax reference. + + This behavior is illustrated in the following example. Because the +‘<>’ noweb reference appears behind the SQL comment syntax, +each line of the expanded noweb reference will be commented. + + With: + + #+NAME: example + #+BEGIN_SRC text + this is the + multi-line body of example + #+END_SRC + + this ‘src’ code block: + + #+BEGIN_SRC sql :noweb yes + -- <> + #+END_SRC + + expands to: + + -- this is the + -- multi-line body of example + + Since this change will not affect noweb replacement text without +newlines in them, inline noweb references are acceptable. + + This feature can also be used for management of indentation in +exported code snippets. + + With: + + #+NAME: if-true + #+BEGIN_SRC python :exports none + print('Do things when True') + #+END_SRC + + #+NAME: if-false + #+BEGIN_SRC python :exports none + print('Do things when False') + #+END_SRC + + this ‘src’ code block: + + #+BEGIN_SRC python :noweb yes :results output + if True: + <> + else: + <> + #+END_SRC + + expands to: + + if True: + print('Do things when True') + else: + print('Do things when False') + + and evaluates to: + + Do things when True + + +File: org, Node: noweb-ref, Next: noweb-sep, Prev: noweb, Up: Specific header arguments + +14.8.2.16 ‘:noweb-ref’ +...................... + +When expanding Noweb style references, Org concatenates ‘src’ code +blocks by matching the reference name to either the code block name or +the ‘:noweb-ref’ header argument. + + For simple concatenation, set this ‘:noweb-ref’ header argument at +the sub-tree or file level. In the example Org file shown next, the +body of the source code in each block is extracted for concatenation to +a pure code file when tangled. + + #+BEGIN_SRC sh :tangle yes :noweb yes :shebang #!/bin/sh + <> + #+END_SRC + * the mount point of the fullest disk + :PROPERTIES: + :header-args: :noweb-ref fullest-disk + :END: + + ** query all mounted disks + #+BEGIN_SRC sh + df \ + #+END_SRC + + ** strip the header row + #+BEGIN_SRC sh + |sed '1d' \ + #+END_SRC + + ** output mount point of fullest disk + #+BEGIN_SRC sh + |awk '{if (u < +$5) {u = +$5; m = $6}} END {print m}' + #+END_SRC + + +File: org, Node: noweb-sep, Next: cache, Prev: noweb-ref, Up: Specific header arguments + +14.8.2.17 ‘:noweb-sep’ +...................... + +By default a newline separates each noweb reference concatenation. To +change this newline separator, edit the ‘:noweb-sep’ (*note noweb-sep::) +header argument. + + +File: org, Node: cache, Next: sep, Prev: noweb-sep, Up: Specific header arguments + +14.8.2.18 ‘:cache’ +.................. + +The ‘:cache’ header argument is for caching results of evaluating code +blocks. Caching results can avoid re-evaluating ‘src’ code blocks that +have not changed since the previous run. To benefit from the cache and +avoid redundant evaluations, the source block must have a result already +present in the buffer, and neither the header arguments (including the +value of ‘:var’ references) nor the text of the block itself has changed +since the result was last computed. This feature greatly helps avoid +long-running calculations. For some edge cases, however, the cached +results may not be reliable. + + The caching feature is best for when ‘src’ blocks are pure functions, +that is functions that return the same value for the same input +arguments (*note var::), and that do not have side effects, and do not +rely on external variables other than the input arguments. Functions +that depend on a timer, file system objects, and random number +generators are clearly unsuitable for caching. + + A note of warning: when ‘:cache’ is used for a ‘:session’, caching +may cause unexpected results. + + When the caching mechanism tests for any source code changes, it will +not expand Noweb style references (*note Noweb reference syntax::). For +reasons why, see . + + The ‘:cache’ header argument can have one of two values: ‘yes’ or +‘no’. + + • ‘no’ Default. No caching of results; ‘src’ code block evaluated + every time. + • ‘yes’ Whether to run the code or return the cached results is + determined by comparing the SHA1 hash value of the combined ‘src’ + code block and arguments passed to it. This hash value is packed + on the ‘#+RESULTS:’ line from previous evaluation. When hash + values match, Org does not evaluate the ‘src’ code block. When + hash values mismatch, Org evaluates the ‘src’ code block, inserts + the results, recalculates the hash value, and updates ‘#+RESULTS:’ + line. + + In this example, both functions are cached. But ‘caller’ runs only +if the result from ‘random’ has changed since the last run. + + #+NAME: random + #+BEGIN_SRC R :cache yes + runif(1) + #+END_SRC + + #+RESULTS[a2a72cd647ad44515fab62e144796432793d68e1]: random + 0.4659510825295 + + #+NAME: caller + #+BEGIN_SRC emacs-lisp :var x=random :cache yes + x + #+END_SRC + + #+RESULTS[bec9c8724e397d5df3b696502df3ed7892fc4f5f]: caller + 0.254227238707244 + + +File: org, Node: sep, Next: hlines, Prev: cache, Up: Specific header arguments + +14.8.2.19 ‘:sep’ +................ + +The ‘:sep’ header argument is the delimiter for saving results as tables +to files (*note file::) external to Org mode. Org defaults to tab +delimited output. The function, ‘org-open-at-point’, which is bound to +‘C-c C-o’, also uses ‘:sep’ for opening tabular results. + + +File: org, Node: hlines, Next: colnames, Prev: sep, Up: Specific header arguments + +14.8.2.20 ‘:hlines’ +................... + +In-between each table row or below the table headings, sometimes results +have horizontal lines, which are also known as hlines. The ‘:hlines’ +argument with the value ‘yes’ accepts such lines. The default is ‘no’. + + • ‘no’ Strips horizontal lines from the input table. For most code, + this is desirable, or else those ‘hline’ symbols raise unbound + variable errors. + + The default is ‘:hlines no’. The example shows hlines removed from + the input table. + + #+NAME: many-cols + | a | b | c | + |---+---+---| + | d | e | f | + |---+---+---| + | g | h | i | + + #+NAME: echo-table + #+BEGIN_SRC python :var tab=many-cols + return tab + #+END_SRC + + #+RESULTS: echo-table + | a | b | c | + | d | e | f | + | g | h | i | + + • ‘yes’ For ‘:hlines yes’, the example shows hlines unchanged. + + #+NAME: many-cols + | a | b | c | + |---+---+---| + | d | e | f | + |---+---+---| + | g | h | i | + + #+NAME: echo-table + #+BEGIN_SRC python :var tab=many-cols :hlines yes + return tab + #+END_SRC + + #+RESULTS: echo-table + | a | b | c | + |---+---+---| + | d | e | f | + |---+---+---| + | g | h | i | + + +File: org, Node: colnames, Next: rownames, Prev: hlines, Up: Specific header arguments + +14.8.2.21 ‘:colnames’ +..................... + +The ‘:colnames’ header argument accepts ‘yes’, ‘no’, or ‘nil’ values. +The default value is ‘nil’, which is unassigned. But this header +argument behaves differently depending on the source code language. + + • ‘nil’ If an input table has column names (because the second row is + an hline), then Org removes the column names, processes the table, + puts back the column names, and then writes the table to the + results block. + + #+NAME: less-cols + | a | + |---| + | b | + | c | + + #+NAME: echo-table-again + #+BEGIN_SRC python :var tab=less-cols + return [[val + '*' for val in row] for row in tab] + #+END_SRC + + #+RESULTS: echo-table-again + | a | + |----| + | b* | + | c* | + + Note that column names have to accounted for when using variable + indexing (*note Indexable variable values: var.) because column + names are not removed for indexing. + + • ‘no’ Do not pre-process column names. + + • ‘yes’ For an input table that has no hlines, process it like the + ‘nil’ value. That is, Org removes the column names, processes the + table, puts back the column names, and then writes the table to the + results block. + + +File: org, Node: rownames, Next: shebang, Prev: colnames, Up: Specific header arguments + +14.8.2.22 ‘:rownames’ +..................... + +The ‘:rownames’ header argument can take on values ‘yes’ or ‘no’ values. +The default is ‘no’. Note that ‘emacs-lisp’ code blocks ignore +‘:rownames’ header argument because of the ease of table-handling in +Emacs. + + • ‘no’ Org will not pre-process row names. + + • ‘yes’ If an input table has row names, then Org removes the row + names, processes the table, puts back the row names, and then + writes the table to the results block. + + #+NAME: with-rownames + | one | 1 | 2 | 3 | 4 | 5 | + | two | 6 | 7 | 8 | 9 | 10 | + + #+NAME: echo-table-once-again + #+BEGIN_SRC python :var tab=with-rownames :rownames yes + return [[val + 10 for val in row] for row in tab] + #+END_SRC + + #+RESULTS: echo-table-once-again + | one | 11 | 12 | 13 | 14 | 15 | + | two | 16 | 17 | 18 | 19 | 20 | + + Note that row names have to accounted for when using variable + indexing (*note Indexable variable values: var.) because row names + are not removed for indexing. + + +File: org, Node: shebang, Next: tangle-mode, Prev: rownames, Up: Specific header arguments + +14.8.2.23 ‘:shebang’ +.................... + +This header argument can turn results into executable script files. By +setting the ‘:shebang’ header argument to a string value (for example, +‘:shebang "#!/bin/bash"’), Org inserts that string as the first line of +the tangled file that the ‘src’ code block is extracted to. Org then +turns on the tangled file’s executable permission. + + +File: org, Node: tangle-mode, Next: eval, Prev: shebang, Up: Specific header arguments + +14.8.2.24 ‘:tangle-mode’ +........................ + +The ‘tangle-mode’ header argument specifies what permissions to set for +tangled files by ‘set-file-modes’. For example, to make read-only +tangled file, use ‘:tangle-mode (identity #o444)’. To make it +executable, use ‘:tangle-mode (identity #o755)’. + + On ‘src’ code blocks with ‘shebang’ (*note shebang::) header +argument, Org will automatically set the tangled file to executable +permissions. But this can be overridden with custom permissions using +‘tangle-mode’ header argument. + + When multiple ‘src’ code blocks tangle to a single file with +different and conflicting ‘tangle-mode’ header arguments, Org’s behavior +is undefined. + + +File: org, Node: eval, Next: wrap, Prev: tangle-mode, Up: Specific header arguments + +14.8.2.25 ‘:eval’ +................. + +The ‘:eval’ header argument can limit evaluation of specific code +blocks. It is useful for protection against evaluating untrusted ‘src’ +code blocks by prompting for a confirmation. This protection is +independent of the ‘org-confirm-babel-evaluate’ setting. + +‘never or no’ + Org will never evaluate this ‘src’ code block. +‘query’ + Org prompts the user for permission to evaluate this ‘src’ code + block. +‘never-export or no-export’ + Org will not evaluate this ‘src’ code block when exporting, yet the + user can evaluate this source block interactively. +‘query-export’ + Org prompts the user for permission to export this ‘src’ code + block. + + If ‘:eval’ header argument is not set for a source block, then Org +determines whether to evaluate from the ‘org-confirm-babel-evaluate’ +variable (*note Code evaluation security::). + + +File: org, Node: wrap, Next: post, Prev: eval, Up: Specific header arguments + +14.8.2.26 ‘:wrap’ +................. + +The ‘:wrap’ header argument marks the results block by appending strings +to ‘#+BEGIN_’ and ‘#+END_’. If no string is specified, Org wraps the +results in a ‘#+BEGIN/END_RESULTS’ block. + + +File: org, Node: post, Next: prologue, Prev: wrap, Up: Specific header arguments + +14.8.2.27 ‘:post’ +................. + +The ‘:post’ header argument is for post-processing results from ‘src’ +block evaluation. When ‘:post’ has any value, Org binds the results to +‘*this*’ variable for easy passing to *note var:: header argument +specifications. That makes results available to other ‘src’ code +blocks, or for even direct Emacs Lisp code execution. + + The following two examples illustrate ‘:post’ header argument in +action. The first one shows how to attach ‘#+ATTR_LATEX:’ line using +‘:post’. + + #+name: attr_wrap + #+begin_src sh :var data="" :var width="\\textwidth" :results output + echo "#+ATTR_LATEX: :width $width" + echo "$data" + #+end_src + + #+header: :file /tmp/it.png + #+begin_src dot :post attr_wrap(width="5cm", data=*this*) :results drawer + digraph{ + a -> b; + b -> c; + c -> a; + } + #+end_src + + #+RESULTS: + :RESULTS: + #+ATTR_LATEX :width 5cm + [[file:/tmp/it.png]] + :END: + + The second example shows use of ‘:colnames’ in ‘:post’ to pass data +between ‘src’ code blocks. + + #+name: round-tbl + #+begin_src emacs-lisp :var tbl="" fmt="%.3f" + (mapcar (lambda (row) + (mapcar (lambda (cell) + (if (numberp cell) + (format fmt cell) + cell)) + row)) + tbl) + #+end_src + + #+begin_src R :colnames yes :post round-tbl[:colnames yes](*this*) + set.seed(42) + data.frame(foo=rnorm(1)) + #+end_src + + #+RESULTS: + | foo | + |-------| + | 1.371 | + + +File: org, Node: prologue, Next: epilogue, Prev: post, Up: Specific header arguments + +14.8.2.28 ‘:prologue’ +..................... + +The ‘prologue’ header argument is for appending to the top of the code +block for execution. For example, a clear or reset code at the start of +new execution of a ‘src’ code block. A ‘reset’ for ‘gnuplot’: +‘:prologue "reset"’. See also *note epilogue::. + + (add-to-list 'org-babel-default-header-args:gnuplot + '((:prologue . "reset"))) + + +File: org, Node: epilogue, Prev: prologue, Up: Specific header arguments + +14.8.2.29 ‘:epilogue’ +..................... + +The value of the ‘epilogue’ header argument is for appending to the end +of the code block for execution. See also *note prologue::. + + +File: org, Node: Results of evaluation, Next: Noweb reference syntax, Prev: Header arguments, Up: Working with source code + +14.9 Results of evaluation +========================== + +How Org handles results of a code block execution depends on many header +arguments working together. Here is only a summary of these. For an +enumeration of all the header arguments that affect results, see *note +results::. + + The primary determinant is the execution context. Is it in a +‘:session’ or not? Orthogonal to that is if the expected result is a +‘:results value’ or ‘:results output’, which is a concatenation of +output from start to finish of the ‘src’ code block’s evaluation. + + Non-session Session +‘:results value’ value of last value of last expression + expression +‘:results output’ contents of STDOUT concatenation of interpreter + output + + For ‘:session’ and non-session, the ‘:results value’ turns the +results into an Org mode table format. Single values are wrapped in a +one dimensional vector. Rows and columns of a table are wrapped in a +two-dimensional vector. + +14.9.1 Non-session +------------------ + +14.9.1.1 ‘:results value’ +......................... + +Default. Org gets the value by wrapping the code in a function +definition in the language of the ‘src’ block. That is why when using +‘:results value’, code should execute like a function and return a +value. For languages like Python, an explicit ‘return’ statement is +mandatory when using ‘:results value’. + + This is one of four evaluation contexts where Org automatically wraps +the code in a function definition. + +14.9.1.2 ‘:results output’ +.......................... + +For ‘:results output’, the code is passed to an external process running +the interpreter. Org returns the contents of the standard output stream +as as text results. + +14.9.2 Session +-------------- + +14.9.2.1 ‘:results value’ +......................... + +For ‘:results value’ from a ‘:session’, Org passes the code to an +interpreter running as an interactive Emacs inferior process. So only +languages that provide interactive evaluation can have session support. +Not all languages provide this support, such as ‘C’ and ‘ditaa’. Even +those that do support, such as ‘Python’ and ‘Haskell’, they impose +limitations on allowable language constructs that can run interactively. +Org inherits those limitations for those ‘src’ code blocks running in a +‘:session’. + + Org gets the value from the source code interpreter’s last statement +output. Org has to use language-specific methods to obtain the value. +For example, from the variable ‘_’ in ‘Python’ and ‘Ruby’, and the value +of ‘.Last.value’ in ‘R’). + +14.9.2.2 ‘:results output’ +.......................... + +For ‘:results output’, Org passes the code to the interpreter running as +an interactive Emacs inferior process. Org concatenates whatever text +output emitted by the interpreter to return the collection as a result. +Note that this collection is not the same as collected from ‘STDOUT’ of +a non-interactive interpreter running as an external process. Compare +for example these two blocks: + + #+BEGIN_SRC python :results output + print "hello" + 2 + print "bye" + #+END_SRC + + #+RESULTS: + : hello + : bye + + In the above non-session mode, the “2” is not printed; so does not +appear in results. + + #+BEGIN_SRC python :results output :session + print "hello" + 2 + print "bye" + #+END_SRC + + #+RESULTS: + : hello + : 2 + : bye + + In the above ‘:session’ mode, the interactive interpreter receives +and prints “2”. Results show that. + + +File: org, Node: Noweb reference syntax, Next: Key bindings and useful functions, Prev: Results of evaluation, Up: Working with source code + +14.10 Noweb reference syntax +============================ + +Org supports named blocks in Noweb style syntax. For Noweb literate +programming details, see ). + + <> + + For the header argument ‘:noweb yes’, Org expands Noweb style +references in the ‘src’ code block before evaluation. + + For the header argument ‘:noweb no’, Org does not expand Noweb style +references in the ‘src’ code block before evaluation. + + The default is ‘:noweb no’. Org defaults to ‘:noweb no’ so as not to +cause errors in languages where Noweb syntax is ambiguous. Change Org’s +default to ‘:noweb yes’ for languages where there is no risk of +confusion. + + Org offers a more flexible way to resolve Noweb style references +(*note noweb-ref::). + + Org can include the _results_ of a code block rather than its body. +To that effect, append parentheses, possibly including arguments, to the +code block name, as show below. + + <> + + Note that when using the above approach to a code block’s results, +the code block name set by ‘#+NAME’ keyword is required; the reference +set by ‘:noweb-ref’ will not work. + + Here is an example that demonstrates how the exported content changes +when Noweb style references are used with parentheses versus without. + + With: + + #+NAME: some-code + #+BEGIN_SRC python :var num=0 :results output :exports none + print(num*10) + #+END_SRC + + this code block: + + #+BEGIN_SRC text :noweb yes + <> + #+END_SRC + + expands to: + + print(num*10) + + Below, a similar Noweb style reference is used, but with parentheses, +while setting a variable ‘num’ to 10: + + #+BEGIN_SRC text :noweb yes + <> + #+END_SRC + + Note that now the expansion contains the _results_ of the code block +‘some-code’, not the code block itself: + + 100 + + For faster tangling of large Org mode files, set +‘org-babel-use-quick-and-dirty-noweb-expansion’ variable to ‘t’. The +speedup comes at the expense of not correctly resolving inherited values +of the ‘:noweb-ref’ header argument. + + +File: org, Node: Key bindings and useful functions, Next: Batch execution, Prev: Noweb reference syntax, Up: Working with source code + +14.11 Key bindings and useful functions +======================================= + +Many common Org mode key sequences are re-bound depending on the +context. + + Active key bindings in code blocks: + +‘C-c C-c’ ‘org-babel-execute-src-block’ +‘C-c C-o’ ‘org-babel-open-src-block-result’ +‘M-’ ‘org-babel-load-in-session’ +‘M-’ ‘org-babel-switch-to-session’ + + Active key bindings in Org mode buffer: + +‘C-c C-v p’ or ‘C-c C-v C-p’ ‘org-babel-previous-src-block’ +‘C-c C-v n’ or ‘C-c C-v C-n’ ‘org-babel-next-src-block’ +‘C-c C-v e’ or ‘C-c C-v C-e’ ‘org-babel-execute-maybe’ +‘C-c C-v o’ or ‘C-c C-v C-o’ ‘org-babel-open-src-block-result’ +‘C-c C-v v’ or ‘C-c C-v C-v’ ‘org-babel-expand-src-block’ +‘C-c C-v u’ or ‘C-c C-v C-u’ ‘org-babel-goto-src-block-head’ +‘C-c C-v g’ or ‘C-c C-v C-g’ ‘org-babel-goto-named-src-block’ +‘C-c C-v r’ or ‘C-c C-v C-r’ ‘org-babel-goto-named-result’ +‘C-c C-v b’ or ‘C-c C-v C-b’ ‘org-babel-execute-buffer’ +‘C-c C-v s’ or ‘C-c C-v C-s’ ‘org-babel-execute-subtree’ +‘C-c C-v d’ or ‘C-c C-v C-d’ ‘org-babel-demarcate-block’ +‘C-c C-v t’ or ‘C-c C-v C-t’ ‘org-babel-tangle’ +‘C-c C-v f’ or ‘C-c C-v C-f’ ‘org-babel-tangle-file’ +‘C-c C-v c’ or ‘C-c C-v C-c’ ‘org-babel-check-src-block’ +‘C-c C-v j’ or ‘C-c C-v C-j’ ‘org-babel-insert-header-arg’ +‘C-c C-v l’ or ‘C-c C-v C-l’ ‘org-babel-load-in-session’ +‘C-c C-v i’ or ‘C-c C-v C-i’ ‘org-babel-lob-ingest’ +‘C-c C-v I’ or ‘C-c C-v C-I’ ‘org-babel-view-src-block-info’ +‘C-c C-v z’ or ‘C-c C-v C-z’ ‘org-babel-switch-to-session-with-code’ +‘C-c C-v a’ or ‘C-c C-v C-a’ ‘org-babel-sha1-hash’ +‘C-c C-v h’ or ‘C-c C-v C-h’ ‘org-babel-describe-bindings’ +‘C-c C-v x’ or ‘C-c C-v C-x’ ‘org-babel-do-key-sequence-in-edit-buffer’ + + +File: org, Node: Batch execution, Prev: Key bindings and useful functions, Up: Working with source code + +14.12 Batch execution +===================== + +Org mode features, including working with source code facilities can be +invoked from the command line. This enables building shell scripts for +batch processing, running automated system tasks, and expanding Org +mode’s usefulness. + + The sample script shows batch processing of multiple files using +‘org-babel-tangle’. + + #!/bin/sh + # tangle files with org-mode + # + emacs -Q --batch --eval " + (progn + (require 'ob-tangle) + (dolist (file command-line-args-left) + (with-current-buffer (find-file-noselect file) + (org-babel-tangle)))) + " "$@" + + +File: org, Node: Miscellaneous, Next: Hacking, Prev: Working with source code, Up: Top + +15 Miscellaneous +**************** + +* Menu: + +* Completion:: M- guesses completions +* Easy templates:: Quick insertion of structural elements +* Speed keys:: Electric commands at the beginning of a headline +* Code evaluation security:: Org mode files evaluate inline code +* Customization:: Adapting Org to changing tastes +* In-buffer settings:: Overview of the ‘#+KEYWORDS’ +* The very busy C-c C-c key:: When in doubt, press C-c C-c +* Clean view:: Getting rid of leading stars in the outline +* TTY keys:: Using Org on a tty +* Interaction:: With other Emacs packages +* org-crypt:: Encrypting Org files + + +File: org, Node: Completion, Next: Easy templates, Up: Miscellaneous + +15.1 Completion +=============== + +Org has in-buffer completions. Unlike minibuffer completions, which are +useful for quick command interactions, Org’s in-buffer completions are +more suitable for content creation in Org documents. Type one or more +letters and invoke the hot key to complete the text in-place. Depending +on the context and the keys, Org will offer different types of +completions. No minibuffer is involved. Such mode-specific hot keys +have become an integral part of Emacs and Org provides several +shortcuts. + +‘M-’ + Complete word at point + • At the beginning of a headline, complete TODO keywords. + • After ‘\’, complete TeX symbols supported by the exporter. + • After ‘*’, complete headlines in the current buffer so that + they can be used in search links like ‘[[*find this + headline]]’. + • After ‘:’ in a headline, complete tags. The list of tags is + taken from the variable ‘org-tag-alist’ (possibly set through + the ‘#+TAGS’ in-buffer option, *note Setting tags::), or it is + created dynamically from all tags used in the current buffer. + • After ‘:’ and not in a headline, complete property keys. The + list of keys is constructed dynamically from all keys used in + the current buffer. + • After ‘[’, complete link abbreviations (*note Link + abbreviations::). + • After ‘#+’, complete the special keywords like ‘TYP_TODO’ or + file-specific ‘OPTIONS’. After option keyword is complete, + pressing ‘M-’ again will insert example settings for that + option. + • After ‘#+STARTUP:’, complete startup keywords. + • When the point is anywhere else, complete dictionary words + using Ispell. + If your desktop intercepts the combo ‘M-’ to switch windows, + use ‘C-M-i’ or ‘ ’ as an alternative or customize your + environment. + + +File: org, Node: Easy templates, Next: Speed keys, Prev: Completion, Up: Miscellaneous + +15.2 Easy templates +=================== + +With just a few keystrokes, Org’s easy templates inserts empty pairs of +structural elements, such as ‘#+BEGIN_SRC’ and ‘#+END_SRC’. Easy +templates use an expansion mechanism, which is native to Org, in a +process similar to ‘yasnippet’ and other Emacs template expansion +packages. + + ‘<’ ‘s’ ‘’ expands to a ‘src’ code block. + + ‘<’ ‘l’ ‘’ expands to: + + #+BEGIN_EXPORT latex + + #+END_EXPORT + + Org comes with these pre-defined easy templates: + +‘s’ ‘#+BEGIN_SRC ... #+END_SRC’ +‘e’ ‘#+BEGIN_EXAMPLE ... #+END_EXAMPLE’ +‘q’ ‘#+BEGIN_QUOTE ... #+END_QUOTE’ +‘v’ ‘#+BEGIN_VERSE ... #+END_VERSE’ +‘c’ ‘#+BEGIN_CENTER ... #+END_CENTER’ +‘C’ ‘#+BEGIN_COMMENT ... #+END_COMMENT’ +‘l’ ‘#+BEGIN_EXPORT latex ... #+END_EXPORT’ +‘L’ ‘#+LATEX:’ +‘h’ ‘#+BEGIN_EXPORT html ... #+END_EXPORT’ +‘H’ ‘#+HTML:’ +‘a’ ‘#+BEGIN_EXPORT ascii ... #+END_EXPORT’ +‘A’ ‘#+ASCII:’ +‘i’ ‘#+INDEX:’ line +‘I’ ‘#+INCLUDE:’ line + + More templates can added by customizing the variable +‘org-structure-template-alist’, whose docstring has additional details. + + +File: org, Node: Speed keys, Next: Code evaluation security, Prev: Easy templates, Up: Miscellaneous + +15.3 Speed keys +=============== + +Single keystrokes can execute custom commands in an Org file when the +cursor is on a headline. Without the extra burden of a meta or modifier +key, Speed Keys can speed navigation or execute custom commands. +Besides faster navigation, Speed Keys may come in handy on small mobile +devices that do not have full keyboards. Speed Keys may also work on +TTY devices known for their problems when entering Emacs keychords. + + By default, Org has Speed Keys disabled. To activate Speed Keys, set +the variable ‘org-use-speed-commands’ to a non-‘nil’ value. To trigger +a Speed Key, the cursor must be at the beginning of an Org headline, +before any of the stars. + + Org comes with a pre-defined list of Speed Keys. To add or modify +Speed Keys, customize the variable, ‘org-speed-commands-user’. For more +details, see the variable’s docstring. With Speed Keys activated, ‘M-x +org-speed-command-help’, or ‘?’ when cursor is at the beginning of an +Org headline, shows currently active Speed Keys, including the +user-defined ones. + + +File: org, Node: Code evaluation security, Next: Customization, Prev: Speed keys, Up: Miscellaneous + +15.4 Code evaluation and security issues +======================================== + +Unlike plain text, running code comes with risk. Each ‘src’ code block, +in terms of risk, is equivalent to an executable file. Org therefore +puts a few confirmation prompts by default. This is to alert the casual +user from accidentally running untrusted code. + + For users who do not run code blocks or write code regularly, Org’s +default settings should suffice. However, some users may want to tweak +the prompts for fewer interruptions. To weigh the risks of automatic +execution of code blocks, here are some details about code evaluation. + + Org evaluates code in the following circumstances: + +Source code blocks + Org evaluates ‘src’ code blocks in an Org file during export. Org + also evaluates a ‘src’ code block with the ‘C-c C-c’ key chord. + Users exporting or running code blocks must load files only from + trusted sources. Be wary of customizing variables that remove or + alter default security measures. + + -- User Option: org-confirm-babel-evaluate + When ‘t’, Org prompts the user for confirmation before + executing each code block. When ‘nil’, Org executes code + blocks without prompting the user for confirmation. When this + option is set to a custom function, Org invokes the function + with these two arguments: the source code language and the + body of the code block. The custom function must return + either a ‘t’ or ‘nil’, which determines if the user is + prompted. Each source code language can be handled separately + through this function argument. + + For example, this function enables execution of ‘ditaa’ code + +blocks without prompting: + + (defun my-org-confirm-babel-evaluate (lang body) + (not (string= lang "ditaa"))) ; don't ask for ditaa + (setq org-confirm-babel-evaluate 'my-org-confirm-babel-evaluate) + +Following ‘shell’ and ‘elisp’ links + Org has two link types that can also directly evaluate code (*note + External links::). Because such code is not visible, these links + have a potential risk. Org therefore prompts the user when it + encounters such links. The customization variables are: + + -- User Option: org-confirm-shell-link-function + Function that prompts the user before executing a shell link. + -- User Option: org-confirm-elisp-link-function + Function that prompts the user before executing an Emacs Lisp + link. + +Formulas in tables + Org executes formulas in tables (*note The spreadsheet::) either + through the _calc_ or the _Emacs Lisp_ interpreters. + + +File: org, Node: Customization, Next: In-buffer settings, Prev: Code evaluation security, Up: Miscellaneous + +15.5 Customization +================== + +Org has more than 500 variables for customization. They can be accessed +through the usual ‘M-x org-customize ’ command. Or through the Org +menu, ‘Org->Customization->Browse Org Group’. Org also has per-file +settings for some variables (*note In-buffer settings::). + + +File: org, Node: In-buffer settings, Next: The very busy C-c C-c key, Prev: Customization, Up: Miscellaneous + +15.6 Summary of in-buffer settings +================================== + +In-buffer settings start with ‘#+’, followed by a keyword, a colon, and +then a word for each setting. Org accepts multiple settings on the same +line. Org also accepts multiple lines for a keyword. This manual +describes these settings throughout. A summary follows here. + + ‘C-c C-c’ activates any changes to the in-buffer settings. Closing +and reopening the Org file in Emacs also activates the changes. + +‘#+ARCHIVE: %s_done::’ + Sets the archive location of the agenda file. This location + applies to the lines until the next ‘#+ARCHIVE’ line, if any, in + the Org file. The first archive location in the Org file also + applies to any entries before it. The corresponding variable is + ‘org-archive-location’. +‘#+CATEGORY:’ + Sets the category of the agenda file, which applies to the entire + document. +‘#+COLUMNS: %25ITEM ...’ + Sets the default format for columns view. Org uses this format for + column views where there is no ‘COLUMNS’ property. +‘#+CONSTANTS: name1=value1 ...’ + Set file-local values for constants that table formulas can use. + This line sets the local variable + ‘org-table-formula-constants-local’. The global version of this + variable is ‘org-table-formula-constants’. +‘#+FILETAGS: :tag1:tag2:tag3:’ + Set tags that all entries in the file will inherit from here, + including the top-level entries. +‘#+LINK: linkword replace’ + Each line specifies one abbreviation for one link. Use multiple + ‘#+LINK:’ lines for more, *note Link abbreviations::. The + corresponding variable is ‘org-link-abbrev-alist’. +‘#+PRIORITIES: highest lowest default’ + This line sets the limits and the default for the priorities. All + three must be either letters A–Z or numbers 0–9. The highest + priority must have a lower ASCII number than the lowest priority. +‘#+PROPERTY: Property_Name Value’ + This line sets a default inheritance value for entries in the + current buffer, most useful for specifying the allowed values of a + property. +‘#+SETUPFILE: file or URL’ + The setup file or a URL pointing to such file is for additional + in-buffer settings. Org loads this file and parses it for any + settings in it only when Org opens the main file. If URL is + specified, the contents are downloaded and stored in a temporary + file cache. ‘C-c C-c’ on the settings line will parse and load the + file, and also reset the temporary file cache. Org also parses and + loads the document during normal exporting process. Org parses the + contents of this document as if it was included in the buffer. It + can be another Org file. To visit the file (not a URL), ‘C-c '’ + while the cursor is on the line with the file name. +‘#+STARTUP:’ + Startup options Org uses when first visiting a file. + + The first set of options deals with the initial visibility of the + outline tree. The corresponding variable for global default + settings is ‘org-startup-folded’ with a default value of ‘t’, which + is the same as ‘overview’. + + overview top-level headlines only + content all headlines + showall no folding of any entries + showeverything show even drawer contents + + Dynamic virtual indentation is controlled by the variable + ‘org-startup-indented’ + indent start with ‘org-indent-mode’ turned on + noindent start with ‘org-indent-mode’ turned off + + Aligns tables consistently upon visiting a file; useful for + restoring narrowed table columns. The corresponding variable is + ‘org-startup-align-all-tables’ with ‘nil’ as default value. + + align align all tables + noalign don’t align tables on startup + + Whether Org should automatically display inline images. The + corresponding variable is ‘org-startup-with-inline-images’, with a + default value ‘nil’ to avoid delays when visiting a file. + inlineimages show inline images + noinlineimages don’t show inline images on startup + + Whether Org should automatically convert LaTeX fragments to images. + The variable ‘org-startup-with-latex-preview’, which controls this + setting, is set to ‘nil’ by default to avoid startup delays. + latexpreview preview LaTeX fragments + nolatexpreview don’t preview LaTeX fragments + + Logging the closing and reopening of TODO items and clock intervals + can be configured using these options (see variables + ‘org-log-done’, ‘org-log-note-clock-out’ and ‘org-log-repeat’) + logdone record a timestamp when an item is marked DONE + lognotedone record timestamp and a note when DONE + nologdone don’t record when items are marked DONE + logrepeat record a time when reinstating a repeating item + lognoterepeat record a note when reinstating a repeating item + nologrepeat do not record when reinstating repeating item + lognoteclock-out record a note when clocking out + nolognoteclock-out don’t record a note when clocking out + logreschedule record a timestamp when scheduling time changes + lognotereschedule record a note when scheduling time changes + nologreschedule do not record when a scheduling date changes + logredeadline record a timestamp when deadline changes + lognoteredeadline record a note when deadline changes + nologredeadline do not record when a deadline date changes + logrefile record a timestamp when refiling + lognoterefile record a note when refiling + nologrefile do not record when refiling + logdrawer store log into drawer + nologdrawer store log outside of drawer + logstatesreversed reverse the order of states notes + nologstatesreversed do not reverse the order of states notes + + These options hide leading stars in outline headings, and indent + outlines. The corresponding variables are ‘org-hide-leading-stars’ + and ‘org-odd-levels-only’, both with a default setting of ‘nil’ + (meaning ‘showstars’ and ‘oddeven’). + hidestars hide all stars on the headline except one. + showstars show all stars on the headline + indent virtual indents according to the outline level + noindent no virtual indents + odd show odd outline levels only (1,3,...) + oddeven show all outline levels + + To turn on custom format overlays over timestamps (variables + ‘org-put-time-stamp-overlays’ and + ‘org-time-stamp-overlay-formats’), use + customtime overlay custom time format + + The following options influence the table spreadsheet (variable + ‘constants-unit-system’). + constcgs ‘constants.el’ should use the c-g-s unit system + constSI ‘constants.el’ should use the SI unit system + + For footnote settings, use the following keywords. The + corresponding variables are ‘org-footnote-define-inline’, + ‘org-footnote-auto-label’, and ‘org-footnote-auto-adjust’. + fninline define footnotes inline + fnnoinline define footnotes in separate section + fnlocal define footnotes near first reference, but not inline + fnprompt prompt for footnote labels + fnauto create ‘[fn:1]’-like labels automatically (default) + fnconfirm offer automatic label for editing or confirmation + fnplain create ‘[1]’-like labels automatically + fnadjust automatically renumber and sort footnotes + nofnadjust do not renumber and sort automatically + + To hide blocks on startup, use these keywords. The corresponding + variable is ‘org-hide-block-startup’. + hideblocks Hide all begin/end blocks on startup + nohideblocks Do not hide blocks on startup + + The display of entities as UTF-8 characters is governed by the + variable ‘org-pretty-entities’ and the keywords + entitiespretty Show entities as UTF-8 characters where possible + entitiesplain Leave entities plain + +‘#+TAGS: TAG1(c1) TAG2(c2)’ + These lines specify valid tags for this file. Org accepts multiple + tags lines. Tags could correspond to the _fast tag selection_ + keys. The corresponding variable is ‘org-tag-alist’. +‘#+TBLFM:’ + This line is for formulas for the table directly above. A table + can have multiple ‘#+TBLFM:’ lines. On table recalculation, Org + applies only the first ‘#+TBLFM:’ line. For details see *note + Using multiple #+TBLFM lines:: in *note Editing and debugging + formulas::. +‘#+TITLE:, #+AUTHOR:, #+EMAIL:, #+LANGUAGE:, #+DATE:,’ +‘#+OPTIONS:, #+BIND:,’ +‘#+SELECT_TAGS:, #+EXCLUDE_TAGS:’ + These lines provide settings for exporting files. For more details + see *note Export settings::. +‘#+TODO: #+SEQ_TODO: #+TYP_TODO:’ + These lines set the TODO keywords and their significance to the + current file. The corresponding variable is ‘org-todo-keywords’. + + +File: org, Node: The very busy C-c C-c key, Next: Clean view, Prev: In-buffer settings, Up: Miscellaneous + +15.7 The very busy C-c C-c key +============================== + +The ‘C-c C-c’ key in Org serves many purposes depending on the context. +It is probably the most over-worked, multi-purpose key combination in +Org. Its uses are well-documented through out this manual, but here is +a consolidated list for easy reference. + + − If any highlights shown in the buffer from the creation of a sparse + tree, or from clock display, remove such highlights. + − If the cursor is in one of the special ‘#+KEYWORD’ lines, scan the + buffer for these lines and update the information. Also reset the + Org file cache used to temporary store the contents of URLs used as + values for keywords like ‘#+SETUPFILE’. + − If the cursor is inside a table, realign the table. The table + realigns even if automatic table editor is turned off. + − If the cursor is on a ‘#+TBLFM’ line, re-apply the formulas to the + entire table. + − If the current buffer is a capture buffer, close the note and file + it. With a prefix argument, also jump to the target location after + saving the note. + − If the cursor is on a ‘<<>>’, update radio targets and + corresponding links in this buffer. + − If the cursor is on a property line or at the start or end of a + property drawer, offer property commands. + − If the cursor is at a footnote reference, go to the corresponding + definition, and _vice versa_. + − If the cursor is on a statistics cookie, update it. + − If the cursor is in a plain list item with a checkbox, toggle the + status of the checkbox. + − If the cursor is on a numbered item in a plain list, renumber the + ordered list. + − If the cursor is on the ‘#+BEGIN’ line of a dynamic block, the + block is updated. + − If the cursor is at a timestamp, fix the day name in the timestamp. + + +File: org, Node: Clean view, Next: TTY keys, Prev: The very busy C-c C-c key, Up: Miscellaneous + +15.8 A cleaner outline view +=========================== + +Org’s default outline with stars and no indents can become too cluttered +for short documents. For _book-like_ long documents, the effect is not +as noticeable. Org provides an alternate stars and indentation scheme, +as shown on the right in the following table. It uses only one star and +indents text to line with the heading: + + * Top level headline | * Top level headline + ** Second level | * Second level + *** 3rd level | * 3rd level + some text | some text + *** 3rd level | * 3rd level + more text | more text + * Another top level headline | * Another top level headline + + + To turn this mode on, use the minor mode, ‘org-indent-mode’. Text +lines that are not headlines are prefixed with spaces to vertically +align with the headline text(1). + + To make more horizontal space, the headlines are shifted by two +stars. This can be configured by the ‘org-indent-indentation-per-level’ +variable. Only one star on each headline is visible, the rest are +masked with the same font color as the background. This font face can +be configured with the ‘org-hide’ variable. + + Note that turning on ‘org-indent-mode’ sets ‘org-hide-leading-stars’ +to ‘t’ and ‘org-adapt-indentation’ to ‘nil’; ‘2.’ below shows how this +works. + + To globally turn on ‘org-indent-mode’ for all files, customize the +variable ‘org-startup-indented’. + + To turn on indenting for individual files, use ‘#+STARTUP’ option as +follows: + + #+STARTUP: indent + + Indent on startup makes Org use hard spaces to align text with +headings as shown in examples below. + + 1. _Indentation of text below headlines_ + Indent text to align with the headline. + + *** 3rd level + more text, now indented + + Org adapts indentations with paragraph filling, line wrapping, and + structure editing(2). + + 2. _Hiding leading stars_ + Org can make leading stars invisible. For global preference, + configure the variable ‘org-hide-leading-stars’. For per-file + preference, use these file ‘#+STARTUP’ options: + + #+STARTUP: hidestars + #+STARTUP: showstars + + With stars hidden, the tree is shown as: + + * Top level headline + * Second level + * 3rd level + ... + + Because Org makes the font color same as the background color to + hide to stars, sometimes ‘org-hide’ face may need tweaking to get + the effect right. For some black and white combinations, ‘grey90’ + on a white background might mask the stars better. + + 3. Using stars for only odd levels, 1, 3, 5, ..., can also clean up + the clutter. This removes two stars from each level(3). For Org + to properly handle this cleaner structure during edits and exports, + configure the variable ‘org-odd-levels-only’. To set this + per-file, use either one of the following lines: + + #+STARTUP: odd + #+STARTUP: oddeven + + To switch between single and double stars layouts, use ‘M-x + org-convert-to-odd-levels ’ and ‘M-x + org-convert-to-oddeven-levels ’. + + ---------- Footnotes ---------- + + (1) The ‘org-indent-mode’ also sets the ‘wrap-prefix’ correctly for +indenting and wrapping long lines of headlines or text. This minor mode +handles ‘visual-line-mode’ and directly applied settings through +‘word-wrap’. + + (2) Also see the variable ‘org-adapt-indentation’. + + (3) Because ‘LEVEL=2’ has 3 stars, ‘LEVEL=3’ has 4 stars, and so on + + +File: org, Node: TTY keys, Next: Interaction, Prev: Clean view, Up: Miscellaneous + +15.9 Using Org on a tty +======================= + +Org provides alternative key bindings for TTY and modern mobile devices +that cannot handle cursor keys and complex modifier key chords. Some of +these workarounds may be more cumbersome than necessary. Users should +look into customizing these further based on their usage needs. For +example, the normal ‘S-’ for editing timestamp might be better +with ‘C-c .’ chord. + +Default Alternative Speed Alternative + 1 key 2 +‘S-’ ‘C-u ’ ‘C’ +‘M-’ ‘C-c C-x l’ ‘l’ ‘ + ’ +‘M-S-’‘C-c C-x L’ ‘L’ +‘M-’ ‘C-c C-x r’ ‘r’ ‘ + ’ +‘M-S-’‘C-c C-x R’ ‘R’ +‘M-’ ‘C-c C-x u’ ‘ ’ ‘ ’ +‘M-S-’ ‘C-c C-x U’ ‘U’ +‘M-’ ‘C-c C-x d’ ‘ ’ ‘ + ’ +‘M-S-’‘C-c C-x D’ ‘D’ +‘S-’ ‘C-c C-x c’ ‘ ’ +‘M-’ ‘C-c C-x m’ ‘ ’ ‘ + ’ +‘M-S-’ ‘C-c C-x M’ ‘ ’ +‘S-’ ‘C-c ’ ‘ ’ +‘S-’ ‘C-c ‘ ’ + ’ +‘S-’ ‘C-c ’ ‘ ’ +‘S-’ ‘C-c ’ ‘ ’ +‘C-S-’‘C-c C-x ‘ ’ + ’ +‘C-S-’‘C-c C-x ‘ ’ + ’ + + +File: org, Node: Interaction, Next: org-crypt, Prev: TTY keys, Up: Miscellaneous + +15.10 Interaction with other packages +===================================== + +Org’s compatibility and the level of interaction with other Emacs +packages are documented here. + +* Menu: + +* Cooperation:: Packages Org cooperates with +* Conflicts:: Packages that lead to conflicts + + +File: org, Node: Cooperation, Next: Conflicts, Up: Interaction + +15.10.1 Packages that Org cooperates with +----------------------------------------- + +‘calc.el’ by Dave Gillespie + Org uses the Calc package for tables to implement spreadsheet + functionality (*note The spreadsheet::). Org also uses Calc for + embedded calculations. *Note Embedded Mode: (calc)Embedded Mode. +‘constants.el’ by Carsten Dominik + Org can use names for constants in formulas in tables. Org can + also use calculation suffixes for units, such as ‘M’ for ‘Mega’. + For a standard collection of such constants, install the + ‘constants’ package. Install version 2.0 of this package, + available at . Org + checks if the function ‘constants-get’ has been autoloaded. + Installation instructions are in the file, ‘constants.el’. +‘cdlatex.el’ by Carsten Dominik + Org mode can use CDLaTeX package to efficiently enter LaTeX + fragments into Org files (*note CDLaTeX mode::). +‘imenu.el’ by Ake Stenhoff and Lars Lindberg + Imenu creates dynamic menus based on an index of items in a file. + Org mode supports Imenu menus. Enable it with a mode hook as + follows: + (add-hook 'org-mode-hook + (lambda () (imenu-add-to-menubar "Imenu"))) + By default the Imenu index is two levels deep. Change the index + depth using thes variable, ‘org-imenu-depth’. +‘speedbar.el’ by Eric M. Ludlam + Speedbar package creates a special Emacs frame for displaying files + and index items in files. Org mode supports Speedbar; users can + drill into Org files directly from the Speedbar. The ‘<’ in the + Speedbar frame tweaks the agenda commands to that file or to a + subtree. +‘table.el’ by Takaaki Ota + + Complex ASCII tables with automatic line wrapping, column- and + row-spanning, and alignment can be created using the Emacs table + package by Takaaki Ota. Org mode recognizes such tables and export + them properly. ‘C-c '’ to edit these tables in a special buffer, + much like Org’s ‘src’ code blocks. Because of interference with + other Org mode functionality, Takaaki Ota tables cannot be edited + directly in the Org buffer. + ‘C-c ' (org-edit-special)’ + Edit a ‘table.el’ table. Works when the cursor is in a + table.el table. + ‘C-c ~ (org-table-create-with-table.el)’ + Insert a ‘table.el’ table. If there is already a table at + point, this command converts it between the ‘table.el’ format + and the Org mode format. See the documentation string of the + command ‘org-convert-table’ for details. + + +File: org, Node: Conflicts, Prev: Cooperation, Up: Interaction + +15.10.2 Packages that conflict with Org mode +-------------------------------------------- + + In Emacs, ‘shift-selection-mode’ combines cursor motions with shift + key to enlarge regions. Emacs sets this mode by default. This + conflicts with Org’s use of ‘S-’ commands to change + timestamps, TODO keywords, priorities, and item bullet types, etc. + Since ‘S-’ commands outside of specific contexts don’t do + anything, Org offers the variable ‘org-support-shift-select’ for + customization. Org mode accommodates shift selection by (i) making + it available outside of the special contexts where special commands + apply, and (ii) extending an existing active region even if the + cursor moves across a special context. + +‘CUA.el’ by Kim. F. Storm + Org key bindings conflict with ‘S-’ keys used by CUA mode. + For Org to relinquish these bindings to CUA mode, configure the + variable ‘org-replace-disputed-keys’. When set, Org moves the + following key bindings in Org files, and in the agenda buffer (but + not during date selection). + + S- ⇒ M-p S- ⇒ M-n + S- ⇒ M-- S- ⇒ M-+ + C-S- ⇒ M-S-- C-S- ⇒ M-S-+ + + Yes, these are unfortunately more difficult to remember. To define + a different replacement keys, look at the variable + ‘org-disputed-keys’. + +‘ecomplete.el’ by Lars Magne Ingebrigtsen + + Ecomplete provides “electric” address completion in address header + lines in message buffers. Sadly Orgtbl mode cuts ecompletes power + supply: No completion happens when Orgtbl mode is enabled in + message buffers while entering text in address header lines. If + one wants to use ecomplete one should _not_ follow the advice to + automagically turn on Orgtbl mode in message buffers (see *note + Orgtbl mode::), but instead—after filling in the message + headers—turn on Orgtbl mode manually when needed in the messages + body. + +‘filladapt.el’ by Kyle Jones + + Org mode tries to do the right thing when filling paragraphs, list + items and other elements. Many users reported problems using both + ‘filladapt.el’ and Org mode, so a safe thing to do is to disable + filladapt like this: + + (add-hook 'org-mode-hook 'turn-off-filladapt-mode) + +‘yasnippet.el’ + The way Org mode binds the key (binding to ‘[tab]’ instead of + ‘"\t"’) overrules YASnippet’s access to this key. The following + code fixed this problem: + + (add-hook 'org-mode-hook + (lambda () + (setq-local yas/trigger-key [tab]) + (define-key yas/keymap [tab] 'yas/next-field-or-maybe-expand))) + + The latest version of yasnippet doesn’t play well with Org mode. + If the above code does not fix the conflict, first define the + following function: + + (defun yas/org-very-safe-expand () + (let ((yas/fallback-behavior 'return-nil)) (yas/expand))) + + Then tell Org mode to use that function: + + (add-hook 'org-mode-hook + (lambda () + (make-variable-buffer-local 'yas/trigger-key) + (setq yas/trigger-key [tab]) + (add-to-list 'org-tab-first-hook 'yas/org-very-safe-expand) + (define-key yas/keymap [tab] 'yas/next-field))) + +‘windmove.el’ by Hovav Shacham + This package also uses the ‘S-’ keys, so everything written + in the paragraph above about CUA mode also applies here. If you + want make the windmove function active in locations where Org mode + does not have special functionality on ‘S-’, add this to + your configuration: + + ;; Make windmove work in org-mode: + (add-hook 'org-shiftup-final-hook 'windmove-up) + (add-hook 'org-shiftleft-final-hook 'windmove-left) + (add-hook 'org-shiftdown-final-hook 'windmove-down) + (add-hook 'org-shiftright-final-hook 'windmove-right) + +‘viper.el’ by Michael Kifer + Viper uses ‘C-c /’ and therefore makes this key not access the + corresponding Org mode command ‘org-sparse-tree’. You need to find + another key for this command, or override the key in + ‘viper-vi-global-user-map’ with + + (define-key viper-vi-global-user-map "C-c /" 'org-sparse-tree) + + +File: org, Node: org-crypt, Prev: Interaction, Up: Miscellaneous + +15.11 org-crypt.el +================== + +Org crypt encrypts the text of an Org entry, but not the headline, or +properties. Org crypt uses the Emacs EasyPG library to encrypt and +decrypt. + + Any text below a headline that has a ‘:crypt:’ tag will be +automatically be encrypted when the file is saved. To use a different +tag, customize the ‘org-crypt-tag-matcher’ variable. + + Suggested Org crypt settings in Emacs init file: + + (require 'org-crypt) + (org-crypt-use-before-save-magic) + (setq org-tags-exclude-from-inheritance (quote ("crypt"))) + + (setq org-crypt-key nil) + ;; GPG key to use for encryption + ;; Either the Key ID or set to nil to use symmetric encryption. + + (setq auto-save-default nil) + ;; Auto-saving does not cooperate with org-crypt.el: so you need + ;; to turn it off if you plan to use org-crypt.el quite often. + ;; Otherwise, you'll get an (annoying) message each time you + ;; start Org. + + ;; To turn it off only locally, you can insert this: + ;; + ;; # -*- buffer-auto-save-file-name: nil; -*- + + Excluding the crypt tag from inheritance prevents encrypting +previously encrypted text. + + +File: org, Node: Hacking, Next: MobileOrg, Prev: Miscellaneous, Up: Top + +Appendix A Hacking +****************** + +This appendix covers some areas where users can extend the functionality +of Org. + +* Menu: + +* Hooks:: How to reach into Org’s internals +* Add-on packages:: Available extensions +* Adding hyperlink types:: New custom link types +* Adding export back-ends:: How to write new export back-ends +* Context-sensitive commands:: How to add functionality to such commands +* Tables in arbitrary syntax:: Orgtbl for LaTeX and other programs +* Dynamic blocks:: Automatically filled blocks +* Special agenda views:: Customized views +* Speeding up your agendas:: Tips on how to speed up your agendas +* Extracting agenda information:: Post-processing of agenda information +* Using the property API:: Writing programs that use entry properties +* Using the mapping API:: Mapping over all or selected entries + + +File: org, Node: Hooks, Next: Add-on packages, Up: Hacking + +A.1 Hooks +========= + +Org has a large number of hook variables for adding functionality. This +appendix illustrates using a few. A complete list of hooks with +documentation is maintained by the Worg project at +. + + +File: org, Node: Add-on packages, Next: Adding hyperlink types, Prev: Hooks, Up: Hacking + +A.2 Add-on packages +=================== + +Various authors wrote a large number of add-on packages for Org. + + These packages are not part of Emacs, but they are distributed as +contributed packages with the separate release available at +. See the ‘contrib/README’ file in the source code +directory for a list of contributed files. Worg page with more +information is at: . + + +File: org, Node: Adding hyperlink types, Next: Adding export back-ends, Prev: Add-on packages, Up: Hacking + +A.3 Adding hyperlink types +========================== + +Org has many built-in hyperlink types (*note Hyperlinks::), and an +interface for adding new link types. The example file, ‘org-man.el’, +shows the process of adding Org links to Unix man pages, which look like +this: ‘[[man:printf][The printf manpage]]’: + + ;;; org-man.el - Support for links to manpages in Org + + (require 'org) + + (org-add-link-type "man" 'org-man-open) + (add-hook 'org-store-link-functions 'org-man-store-link) + + (defcustom org-man-command 'man + "The Emacs command to be used to display a man page." + :group 'org-link + :type '(choice (const man) (const woman))) + + (defun org-man-open (path) + "Visit the manpage on PATH. + PATH should be a topic that can be thrown at the man command." + (funcall org-man-command path)) + + (defun org-man-store-link () + "Store a link to a manpage." + (when (memq major-mode '(Man-mode woman-mode)) + ;; This is a man page, we do make this link + (let* ((page (org-man-get-page-name)) + (link (concat "man:" page)) + (description (format "Manpage for %s" page))) + (org-store-link-props + :type "man" + :link link + :description description)))) + + (defun org-man-get-page-name () + "Extract the page name from the buffer name." + ;; This works for both `Man-mode' and `woman-mode'. + (if (string-match " \\(\\S-+\\)\\*" (buffer-name)) + (match-string 1 (buffer-name)) + (error "Cannot create link to this man page"))) + + (provide 'org-man) + + ;;; org-man.el ends here + +To activate links to man pages in Org, enter this in the init file: + + (require 'org-man) + +A review of ‘org-man.el’: + 1. First, ‘(require 'org)’ ensures ‘org.el’ is loaded. + 2. The ‘org-add-link-type’ defines a new link type with ‘man’ prefix. + The call contains the function to call that follows the link type. + 3. The next line adds a function to ‘org-store-link-functions’ that + records a useful link with the command ‘C-c l’ in a buffer + displaying a man page. + + The rest of the file defines necessary variables and functions. +First is the customization variable ‘org-man-command’. It has two +options, ‘man’ and ‘woman’. Next is a function whose argument is the +link path, which for man pages is the topic of the man command. To +follow the link, the function calls the ‘org-man-command’ to display the +man page. + + ‘C-c l’ constructs and stores the link. + + ‘C-c l’ calls the function ‘org-man-store-link’, which first checks +if the ‘major-mode’ is appropriate. If check fails, the function +returns ‘nil’. Otherwise the function makes a link string by combining +the ‘man:’ prefix with the man topic. The function then calls +‘org-store-link-props’ with ‘:type’ and ‘:link’ properties. A +‘:description’ property is an optional string that is displayed when the +function inserts the link in the Org buffer. + + ‘C-c C-l’ inserts the stored link. + + To define new link types, define a function that implements +completion support with ‘C-c C-l’. This function should not accept any +arguments but return the appropriate prefix and complete link string. + + +File: org, Node: Adding export back-ends, Next: Context-sensitive commands, Prev: Adding hyperlink types, Up: Hacking + +A.4 Adding export back-ends +=========================== + +Org’s export engine makes it easy for writing new back-ends. The +framework on which the engine was built makes it easy to derive new +back-ends from existing ones. + + The two main entry points to the export engine are: +‘org-export-define-backend’ and ‘org-export-define-derived-backend’. To +grok these functions, see ‘ox-latex.el’ for an example of defining a new +back-end from scratch, and ‘ox-beamer.el’ for an example of deriving +from an existing engine. + + For creating a new back-end from scratch, first set its name as a +symbol in an alist consisting of elements and export functions. To make +the back-end visible to the export dispatcher, set ‘:menu-entry’ +keyword. For export options specific to this back-end, set the +‘:options-alist’. + + For creating a new back-end from an existing one, set +‘:translate-alist’ to an alist of export functions. This alist replaces +the parent back-end functions. + + For complete documentation, see the Org Export Reference on Worg +(https://orgmode.org/worg/dev/org-export-reference.html). + + +File: org, Node: Context-sensitive commands, Next: Tables in arbitrary syntax, Prev: Adding export back-ends, Up: Hacking + +A.5 Context-sensitive commands +============================== + +Org has facilities for building context sensitive commands. Authors of +Org add-ons can tap into this functionality. + + Some Org commands change depending on the context. The most +important example of this behavior is the ‘C-c C-c’ (*note The very busy +C-c C-c key::). Other examples are ‘M-cursor’ and ‘M-S-cursor’. + + These context sensitive commands work by providing a function that +detects special context for that add-on and executes functionality +appropriate for that context. + + +File: org, Node: Tables in arbitrary syntax, Next: Dynamic blocks, Prev: Context-sensitive commands, Up: Hacking + +A.6 Tables and lists in arbitrary syntax +======================================== + +Because of Org’s success in handling tables with Orgtbl, a frequently +asked feature is to Org’s usability functions to other table formats +native to other modem’s, such as LaTeX. This would be hard to do in a +general way without complicated customization nightmares. Moreover, +that would take Org away from its simplicity roots that Orgtbl has +proven. There is, however, an alternate approach to accomplishing the +same. + + This approach involves implementing a custom _translate_ function +that operates on a native Org _source table_ to produce a table in +another format. This strategy would keep the excellently working Orgtbl +simple and isolate complications, if any, confined to the translate +function. To add more alien table formats, we just add more translate +functions. Also the burden of developing custom translate functions for +new table formats will be in the hands of those who know those formats +best. + + For an example of how this strategy works, see Orgstruct mode. In +that mode, Bastien added the ability to use Org’s facilities to edit and +re-structure lists. He did by turning ‘orgstruct-mode’ on, and then +exporting the list locally to another format, such as HTML, LaTeX or +Texinfo. + +* Menu: + +* Radio tables:: Sending and receiving radio tables +* A LaTeX example:: Step by step, almost a tutorial +* Translator functions:: Copy and modify +* Radio lists:: Sending and receiving lists + + +File: org, Node: Radio tables, Next: A LaTeX example, Up: Tables in arbitrary syntax + +A.6.1 Radio tables +------------------ + +Radio tables are target locations for translated tables that are not +near their source. Org finds the target location and inserts the +translated table. + + The key to finding the target location are the magic words ‘BEGIN/END +RECEIVE ORGTBL’. They have to appear as comments in the current mode. +If the mode is C, then: + + /* BEGIN RECEIVE ORGTBL table_name */ + /* END RECEIVE ORGTBL table_name */ + +At the location of source, Org needs a special line to direct Orgtbl to +translate and to find the target for inserting the translated table. +For example: + #+ORGTBL: SEND table_name translation_function arguments... + +‘table_name’ is the table’s reference name, which is also used in the +receiver lines, and the ‘translation_function’ is the Lisp function that +translates. This line, in addition, may also contain alternating key +and value arguments at the end. The translation function gets these +values as a property list. A few standard parameters are already +recognized and acted upon before the translation function is called: + +‘:skip N’ + Skip the first N lines of the table. Hlines do count; include them + if they are to be skipped. + +‘:skipcols (n1 n2 ...)’ + List of columns to be skipped. First Org automatically discards + columns with calculation marks and then sends the table to the + translator function, which then skips columns as specified in + ‘skipcols’. + +To keep the source table intact in the buffer without being disturbed +when the source file is compiled or otherwise being worked on, use one +of these strategies: + + • Place the table in a block comment. For example, in C mode you + could wrap the table between ‘/*’ and ‘*/’ lines. + • Put the table after an ‘END’ statement. For example ‘\bye’ in TeX + and ‘\end{document}’ in LaTeX. + • Comment and uncomment each line of the table during edits. The + ‘M-x orgtbl-toggle-comment ’ command makes toggling easy. + + +File: org, Node: A LaTeX example, Next: Translator functions, Prev: Radio tables, Up: Tables in arbitrary syntax + +A.6.2 A LaTeX example of radio tables +------------------------------------- + +To wrap a source table in LaTeX, use the ‘comment’ environment provided +by ‘comment.sty’. To activate it, put ‘\usepackage{comment}’ in the +document header. Orgtbl mode inserts a radio table skeleton(1) with the +command ‘M-x orgtbl-insert-radio-table ’, which prompts for a table +name. For example, if ‘salesfigures’ is the name, the template inserts: + + % BEGIN RECEIVE ORGTBL salesfigures + % END RECEIVE ORGTBL salesfigures + \begin{comment} + #+ORGTBL: SEND salesfigures orgtbl-to-latex + | | | + \end{comment} + +The line ‘#+ORGTBL: SEND’ tells Orgtbl mode to use the function +‘orgtbl-to-latex’ to convert the table to LaTeX format, then insert the +table at the target (receive) location named ‘salesfigures’. Now the +table is ready for data entry. It can even use spreadsheet features(2): + + % BEGIN RECEIVE ORGTBL salesfigures + % END RECEIVE ORGTBL salesfigures + \begin{comment} + #+ORGTBL: SEND salesfigures orgtbl-to-latex + | Month | Days | Nr sold | per day | + |-------+------+---------+---------| + | Jan | 23 | 55 | 2.4 | + | Feb | 21 | 16 | 0.8 | + | March | 22 | 278 | 12.6 | + #+TBLFM: $4=$3/$2;%.1f + % $ (optional extra dollar to keep font-lock happy, see footnote) + \end{comment} + +After editing, ‘C-c C-c’ inserts translated table at the target +location, between the two marker lines. + + For hand-made custom tables, note that the translator needs to skip +the first two lines of the source table. Also the command has to +_splice_ out the target table without the header and footer. + + \begin{tabular}{lrrr} + Month & \multicolumn{1}{c}{Days} & Nr.\ sold & per day\\ + % BEGIN RECEIVE ORGTBL salesfigures + % END RECEIVE ORGTBL salesfigures + \end{tabular} + % + \begin{comment} + #+ORGTBL: SEND salesfigures orgtbl-to-latex :splice t :skip 2 + | Month | Days | Nr sold | per day | + |-------+------+---------+---------| + | Jan | 23 | 55 | 2.4 | + | Feb | 21 | 16 | 0.8 | + | March | 22 | 278 | 12.6 | + #+TBLFM: $4=$3/$2;%.1f + \end{comment} + + The LaTeX translator function ‘orgtbl-to-latex’ is already part of +Orgtbl mode and uses ‘tabular’ environment by default to typeset the +table and mark the horizontal lines with ‘\hline’. For additional +parameters to control output, *note Translator functions::: + +‘:splice nil/t’ + When non-‘nil’, returns only table body lines; not wrapped in + tabular environment. Default is ‘nil’. + +‘:fmt fmt’ + Format to warp each field. It should contain ‘%s’ for the original + field value. For example, to wrap each field value in dollar + symbol, you could use ‘:fmt "$%s$"’. Format can also wrap a + property list with column numbers and formats, for example ‘:fmt (2 + "$%s$" 4 "%s\\%%")’. In place of a string, a function of one + argument can be used; the function must return a formatted string. + +‘:efmt efmt’ + Format numbers as exponentials. The spec should have ‘%s’ twice + for inserting mantissa and exponent, for example + ‘"%s\\times10^{%s}"’. This may also be a property list with column + numbers and formats, for example ‘:efmt (2 "$%s\\times10^{%s}$" 4 + "$%s\\cdot10^{%s}$")’. After ‘efmt’ has been applied to a value, + ‘fmt’ will also be applied. Functions with two arguments can be + supplied instead of strings. By default, no special formatting is + applied. + + ---------- Footnotes ---------- + + (1) By default this works only for LaTeX, HTML, and Texinfo. +Configure the variable ‘orgtbl-radio-table-templates’ to install +templates for other export formats. + + (2) If the ‘#+TBLFM’ line contains an odd number of dollar +characters, this may cause problems with font-lock in LaTeX mode. As +shown in the example you can fix this by adding an extra line inside the +‘comment’ environment that is used to balance the dollar expressions. +If you are using AUCTeX with the font-latex library, a much better +solution is to add the ‘comment’ environment to the variable +‘LaTeX-verbatim-environments’. + + +File: org, Node: Translator functions, Next: Radio lists, Prev: A LaTeX example, Up: Tables in arbitrary syntax + +A.6.3 Translator functions +-------------------------- + +Orgtbl mode has built-in translator functions: ‘orgtbl-to-csv’ +(comma-separated values), ‘orgtbl-to-tsv’ (TAB-separated values), +‘orgtbl-to-latex’, ‘orgtbl-to-html’, ‘orgtbl-to-texinfo’, +‘orgtbl-to-unicode’ and ‘orgtbl-to-orgtbl’. They use the generic +translator, ‘orgtbl-to-generic’, which delegates translations to various +export back-ends. + + Properties passed to the function through the ‘ORGTBL SEND’ line take +precedence over properties defined inside the function. For example, +this overrides the default LaTeX line endings, ‘\\’, with ‘\\[2mm]’: + + #+ORGTBL: SEND test orgtbl-to-latex :lend " \\\\[2mm]" + + For a new language translator, define a converter function. It can +be a generic function, such as shown in this example. It marks a +beginning and ending of a table with ‘!BTBL!’ and ‘!ETBL!’; a beginning +and ending of lines with ‘!BL!’ and ‘!EL!’; and uses a TAB for a field +separator: + + (defun orgtbl-to-language (table params) + "Convert the orgtbl-mode TABLE to language." + (orgtbl-to-generic + table + (org-combine-plists + '(:tstart "!BTBL!" :tend "!ETBL!" :lstart "!BL!" :lend "!EL!" :sep "\t") + params))) + +The documentation for the ‘orgtbl-to-generic’ function shows a complete +list of parameters, each of which can be passed through to +‘orgtbl-to-latex’, ‘orgtbl-to-texinfo’, and any other function using +that generic function. + + For complicated translations the generic translator function could be +replaced by a custom translator function. Such a custom function must +take two arguments and return a single string containing the formatted +table. The first argument is the table whose lines are a list of fields +or the symbol ‘hline’. The second argument is the property list +consisting of parameters specified in the ‘#+ORGTBL: SEND’ line. Please +share your translator functions by posting them to the Org users mailing +list, . + + +File: org, Node: Radio lists, Prev: Translator functions, Up: Tables in arbitrary syntax + +A.6.4 Radio lists +----------------- + +Call the ‘org-list-insert-radio-list’ function to insert a radio list +template in HTML, LaTeX, and Texinfo mode documents. Sending and +receiving radio lists works is the same as for radio tables (*note Radio +tables::) except for these differences: + + − Orgstruct mode must be active. + − Use ‘ORGLST’ keyword instead of ‘ORGTBL’. + − ‘C-c C-c’ works only on the first list item. + + Built-in translators functions are: ‘org-list-to-latex’, +‘org-list-to-html’ and ‘org-list-to-texinfo’. They use the +‘org-list-to-generic’ translator function. See its documentation for +parameters for accurate customizations of lists. Here is a LaTeX +example: + + % BEGIN RECEIVE ORGLST to-buy + % END RECEIVE ORGLST to-buy + \begin{comment} + #+ORGLST: SEND to-buy org-list-to-latex + - a new house + - a new computer + + a new keyboard + + a new mouse + - a new life + \end{comment} + + ‘C-c C-c’ on ‘a new house’ inserts the translated LaTeX list +in-between the BEGIN and END marker lines. + + +File: org, Node: Dynamic blocks, Next: Special agenda views, Prev: Tables in arbitrary syntax, Up: Hacking + +A.7 Dynamic blocks +================== + +Org supports _dynamic blocks_ in Org documents. They are inserted with +begin and end markers like any other ‘src’ code block, but the contents +are updated automatically by a user function. For example, ‘C-c C-x +C-r’ inserts a dynamic table that updates the work time (*note Clocking +work time::). + + Dynamic blocks can have names and function parameters. The syntax is +similar to ‘src’ code block specifications: + + #+BEGIN: myblock :parameter1 value1 :parameter2 value2 ... + + #+END: + + These command update dynamic blocks: + +‘C-c C-x C-u (org-dblock-update)’ + Update dynamic block at point. +‘C-u C-c C-x C-u’ + Update all dynamic blocks in the current file. + + Before updating a dynamic block, Org removes content between the +BEGIN and END markers. Org then reads the parameters on the BEGIN line +for passing to the writer function. If the function expects to access +the removed content, then Org expects an extra parameter, ‘:content’, on +the BEGIN line. + + To syntax for calling a writer function with a named block, ‘myblock’ +is: ‘org-dblock-write:myblock’. Parameters come from the BEGIN line. + + The following is an example of a dynamic block and a block writer +function that updates the time when the function was last run: + + #+BEGIN: block-update-time :format "on %m/%d/%Y at %H:%M" + + #+END: + +The dynamic block’s writer function: + + (defun org-dblock-write:block-update-time (params) + (let ((fmt (or (plist-get params :format) "%d. %m. %Y"))) + (insert "Last block update at: " + (format-time-string fmt)))) + + To keep dynamic blocks up-to-date in an Org file, use the function, +‘org-update-all-dblocks’ in hook, such as ‘before-save-hook’. The +‘org-update-all-dblocks’ function does not run if the file is not in Org +mode. + + Dynamic blocks, like any other block, can be narrowed with +‘org-narrow-to-block’. + + +File: org, Node: Special agenda views, Next: Speeding up your agendas, Prev: Dynamic blocks, Up: Hacking + +A.8 Special agenda views +======================== + +Org provides a special hook to further limit items in agenda views: +‘agenda’, ‘agenda*’(1), ‘todo’, ‘alltodo’, ‘tags’, ‘tags-todo’, +‘tags-tree’. Specify a custom function that tests inclusion of every +matched item in the view. This function can also skip as much as is +needed. + + For a global condition applicable to agenda views, use the +‘org-agenda-skip-function-global’ variable. Org uses a global condition +with ‘org-agenda-skip-function’ for custom searching. + + This example defines a function for a custom view showing TODO items +with WAITING status. Manually this is a multi step search process, but +with a custom view, this can be automated as follows: + + The custom function searches the subtree for the WAITING tag and +returns ‘nil’ on match. Otherwise it gives the location from where the +search continues. + + (defun my-skip-unless-waiting () + "Skip trees that are not waiting" + (let ((subtree-end (save-excursion (org-end-of-subtree t)))) + (if (re-search-forward ":waiting:" subtree-end t) + nil ; tag found, do not skip + subtree-end))) ; tag not found, continue after end of subtree + + To use this custom function in a custom agenda command: + + (org-add-agenda-custom-command + '("b" todo "PROJECT" + ((org-agenda-skip-function 'my-skip-unless-waiting) + (org-agenda-overriding-header "Projects waiting for something: ")))) + + Note that this also binds ‘org-agenda-overriding-header’ to a more +meaningful string suitable for the agenda view. + + Search for entries with a limit set on levels for the custom search. +This is a general approach to creating custom searches in Org. To +include all levels, use ‘LEVEL>0’(2). Then to selectively pick the +matched entries, use ‘org-agenda-skip-function’, which also accepts Lisp +forms, such as ‘org-agenda-skip-entry-if’ and +‘org-agenda-skip-subtree-if’. For example: + +‘(org-agenda-skip-entry-if 'scheduled)’ + Skip current entry if it has been scheduled. +‘(org-agenda-skip-entry-if 'notscheduled)’ + Skip current entry if it has not been scheduled. +‘(org-agenda-skip-entry-if 'deadline)’ + Skip current entry if it has a deadline. +‘(org-agenda-skip-entry-if 'scheduled 'deadline)’ + Skip current entry if it has a deadline, or if it is scheduled. +‘(org-agenda-skip-entry-if 'todo '("TODO" "WAITING"))’ + Skip current entry if the TODO keyword is TODO or WAITING. +‘(org-agenda-skip-entry-if 'todo 'done)’ + Skip current entry if the TODO keyword marks a DONE state. +‘(org-agenda-skip-entry-if 'timestamp)’ + Skip current entry if it has any timestamp, may also be deadline or + scheduled. +‘(org-agenda-skip-entry-if 'regexp "regular expression")’ + Skip current entry if the regular expression matches in the entry. +‘(org-agenda-skip-entry-if 'notregexp "regular expression")’ + Skip current entry unless the regular expression matches. +‘(org-agenda-skip-subtree-if 'regexp "regular expression")’ + Same as above, but check and skip the entire subtree. + + The following is an example of a search for ‘WAITING’ without the +special function: + + (org-add-agenda-custom-command + '("b" todo "PROJECT" + ((org-agenda-skip-function '(org-agenda-skip-subtree-if + 'regexp ":waiting:")) + (org-agenda-overriding-header "Projects waiting for something: ")))) + + ---------- Footnotes ---------- + + (1) The ‘agenda*’ view is the same as ‘agenda’ except that it only +considers _appointments_, i.e., scheduled and deadline items that have a +time specification ‘[h]h:mm’ in their time-stamps. + + (2) Note that, for ‘org-odd-levels-only’, a level number corresponds +to order in the hierarchy, not to the number of stars. + + +File: org, Node: Speeding up your agendas, Next: Extracting agenda information, Prev: Special agenda views, Up: Hacking + +A.9 Speeding up your agendas +============================ + +Some agenda commands slow down when the Org files grow in size or +number. Here are tips to speed up: + + 1. Reduce the number of Org agenda files to avoid slowdowns due to + hard drive accesses. + 2. Reduce the number of ‘DONE’ and archived headlines so agenda + operations that skip over these can finish faster. + 3. Do not dim blocked tasks: + (setq org-agenda-dim-blocked-tasks nil) + 4. Stop preparing agenda buffers on startup: + (setq org-agenda-inhibit-startup nil) + 5. Disable tag inheritance for agendas: + (setq org-agenda-use-tag-inheritance nil) + + These options can be applied to selected agenda views. For more +details about generation of agenda views, see the docstrings for the +relevant variables, and this dedicated Worg page +(https://orgmode.org/worg/agenda-optimization.html) for agenda +optimization. + + +File: org, Node: Extracting agenda information, Next: Using the property API, Prev: Speeding up your agendas, Up: Hacking + +A.10 Extracting agenda information +================================== + +Org provides commands to access agendas through Emacs batch mode. +Through this command-line interface, agendas are automated for further +processing or printing. + + ‘org-batch-agenda’ creates an agenda view in ASCII and outputs to +STDOUT. This command takes one string parameter. When string length=1, +Org uses it as a key to ‘org-agenda-custom-commands’. These are the +same ones available through ‘C-c a’. + + This example command line directly prints the TODO list to the +printer: + + emacs -batch -l ~/.emacs -eval '(org-batch-agenda "t")' | lpr + + When the string parameter length is two or more characters, Org +matches it with tags/TODO strings. For example, this example command +line prints items tagged with ‘shop’, but excludes items tagged with +‘NewYork’: + + emacs -batch -l ~/.emacs \ + -eval '(org-batch-agenda "+shop-NewYork")' | lpr + +An example showing on-the-fly parameter modifications: + + emacs -batch -l ~/.emacs \ + -eval '(org-batch-agenda "a" \ + org-agenda-span (quote month) \ + org-agenda-include-diary nil \ + org-agenda-files (quote ("~/org/project.org")))' \ + | lpr + +which will produce an agenda for the next 30 days from just the +‘~/org/projects.org’ file. + + For structured processing of agenda output, use +‘org-batch-agenda-csv’ with the following fields: + + category The category of the item + head The headline, without TODO keyword, TAGS and PRIORITY + type The type of the agenda entry, can be + todo selected in TODO match + tagsmatch selected in tags match + diary imported from diary + deadline a deadline + scheduled scheduled + timestamp appointment, selected by timestamp + closed entry was closed on date + upcoming-deadline warning about nearing deadline + past-scheduled forwarded scheduled item + block entry has date block including date + todo The TODO keyword, if any + tags All tags including inherited ones, separated by colons + date The relevant date, like 2007-2-14 + time The time, like 15:00-16:50 + extra String with extra planning info + priority-l The priority letter if any was given + priority-n The computed numerical priority + +If the selection of the agenda item was based on a timestamp, including +those items with ‘DEADLINE’ and ‘SCHEDULED’ keywords, then Org includes +date and time in the output. + + If the selection of the agenda item was based on a timestamp (or +deadline/scheduled), then Org includes date and time in the output. + + Here is an example of a post-processing script in Perl. It takes the +CSV output from Emacs and prints with a checkbox: + + #!/usr/bin/perl + + # define the Emacs command to run + $cmd = "emacs -batch -l ~/.emacs -eval '(org-batch-agenda-csv \"t\")'"; + + # run it and capture the output + $agenda = qx{$cmd 2>/dev/null}; + + # loop over all lines + foreach $line (split(/\n/,$agenda)) { + # get the individual values + ($category,$head,$type,$todo,$tags,$date,$time,$extra, + $priority_l,$priority_n) = split(/,/,$line); + # process and print + print "[ ] $head\n"; + } + + +File: org, Node: Using the property API, Next: Using the mapping API, Prev: Extracting agenda information, Up: Hacking + +A.11 Using the property API +=========================== + +Functions for working with properties. + + -- Function: org-entry-properties &optional pom which + Get all properties of the entry at point-or-marker POM. + This includes the TODO keyword, the tags, time strings for + deadline, scheduled, and clocking, and any additional properties + defined in the entry. The return value is an alist. Keys may + occur multiple times if the property key was used several times. + POM may also be ‘nil’, in which case the current entry is used. If + WHICH is ‘nil’ or ‘all’, get all properties. If WHICH is ‘special’ + or ‘standard’, only get that subclass. + + -- Function: org-entry-get pom property &optional inherit + Get value of ‘PROPERTY’ for entry at point-or-marker ‘POM’. By + default, this only looks at properties defined locally in the + entry. If ‘INHERIT’ is non-‘nil’ and the entry does not have the + property, then also check higher levels of the hierarchy. If + ‘INHERIT’ is the symbol ‘selective’, use inheritance if and only if + the setting of ‘org-use-property-inheritance’ selects ‘PROPERTY’ + for inheritance. + + -- Function: org-entry-delete pom property + Delete the property ‘PROPERTY’ from entry at point-or-marker POM. + + -- Function: org-entry-put pom property value + Set ‘PROPERTY’ to ‘VALUE’ for entry at point-or-marker POM. + + -- Function: org-buffer-property-keys &optional include-specials + Get all property keys in the current buffer. + + -- Function: org-insert-property-drawer + Insert a property drawer for the current entry. + + -- Function: org-entry-put-multivalued-property pom property &rest + values + Set ‘PROPERTY’ at point-or-marker ‘POM’ to ‘VALUES’. ‘VALUES’ + should be a list of strings. They will be concatenated, with + spaces as separators. + + -- Function: org-entry-get-multivalued-property pom property + Treat the value of the property ‘PROPERTY’ as a + whitespace-separated list of values and return the values as a list + of strings. + + -- Function: org-entry-add-to-multivalued-property pom property value + Treat the value of the property ‘PROPERTY’ as a + whitespace-separated list of values and make sure that ‘VALUE’ is + in this list. + + -- Function: org-entry-remove-from-multivalued-property pom property + value + Treat the value of the property ‘PROPERTY’ as a + whitespace-separated list of values and make sure that ‘VALUE’ is + _not_ in this list. + + -- Function: org-entry-member-in-multivalued-property pom property + value + Treat the value of the property ‘PROPERTY’ as a + whitespace-separated list of values and check if ‘VALUE’ is in this + list. + + -- User Option: org-property-allowed-value-functions + Hook for functions supplying allowed values for a specific + property. The functions must take a single argument, the name of + the property, and return a flat list of allowed values. If ‘:ETC’ + is one of the values, use the values as completion help, but allow + also other values to be entered. The functions must return ‘nil’ + if they are not responsible for this property. + + +File: org, Node: Using the mapping API, Prev: Using the property API, Up: Hacking + +A.12 Using the mapping API +========================== + +Org has sophisticated mapping capabilities for finding entries. Org +uses this functionality internally for generating agenda views. Org +also exposes an API for executing arbitrary functions for each selected +entry. The API’s main entry point is: + + -- Function: org-map-entries func &optional match scope &rest skip + Call ‘FUNC’ at each headline selected by ‘MATCH’ in ‘SCOPE’. + + ‘FUNC’ is a function or a Lisp form. With the cursor positioned at + the beginning of the headline, call the function without arguments. + Org returns an alist of return values of calls to the function. + + To avoid preserving point, Org wraps the call to ‘FUNC’ in + save-excursion form. After evaluation, Org moves the cursor to the + end of the line that was just processed. Search continues from + that point forward. This may not always work as expected under + some conditions, such as if the current sub-tree was removed by a + previous archiving operation. In such rare circumstances, Org + skips the next entry entirely when it should not. To stop Org from + such skips, make ‘FUNC’ set the variable ‘org-map-continue-from’ to + a specific buffer position. + + ‘MATCH’ is a tags/property/TODO match. Org iterates only matched + headlines. Org iterates over all headlines when ‘MATCH’ is ‘nil’ + or ‘t’. + + ‘SCOPE’ determines the scope of this command. It can be any of: + + nil the current buffer, respecting the restriction if any + tree the subtree started with the entry at point + region The entries within the active region, if any + file the current buffer, without restriction + file-with-archives + the current buffer, and any archives associated with it + agenda all agenda files + agenda-with-archives + all agenda files with any archive files associated with them + (file1 file2 ...) + if this is a list, all files in the list will be scanned + The remaining args are treated as settings for the scanner’s + skipping facilities. Valid args are: + + archive skip trees with the archive tag + comment skip trees with the COMMENT keyword + function or Lisp form + will be used as value for ‘org-agenda-skip-function’, + so whenever the function returns t, FUNC + will not be called for that entry and search will + continue from the point where the function leaves it + + The mapping routine can call any arbitrary function, even functions +that change meta data or query the property API (*note Using the +property API::). Here are some handy functions: + + -- Function: org-todo &optional arg + Change the TODO state of the entry. See the docstring of the + functions for the many possible values for the argument ‘ARG’. + + -- Function: org-priority &optional action + Change the priority of the entry. See the docstring of this + function for the possible values for ‘ACTION’. + + -- Function: org-toggle-tag tag &optional onoff + Toggle the tag ‘TAG’ in the current entry. Setting ‘ONOFF’ to + either ‘on’ or ‘off’ will not toggle tag, but ensure that it is + either on or off. + + -- Function: org-promote + Promote the current entry. + + -- Function: org-demote + Demote the current entry. + + This example turns all entries tagged with ‘TOMORROW’ into TODO +entries with keyword ‘UPCOMING’. Org ignores entries in comment trees +and archive trees. + + (org-map-entries + '(org-todo "UPCOMING") + "+TOMORROW" 'file 'archive 'comment) + + The following example counts the number of entries with TODO keyword +‘WAITING’, in all agenda files. + + (length (org-map-entries t "/+WAITING" 'agenda)) + + +File: org, Node: MobileOrg, Next: History and acknowledgments, Prev: Hacking, Up: Top + +Appendix B MobileOrg +******************** + +MobileOrg is a companion mobile app that runs on iOS and Android +devices. MobileOrg enables offline-views and capture support for an Org +mode system that is rooted on a “real” computer. MobileOrg can record +changes to existing entries. + + The iOS implementation (https://github.com/MobileOrg/) for the +_iPhone/iPod Touch/iPad_ series of devices, was started by Richard +Moreland and is now in the hands Sean Escriva. Android users should +check out MobileOrg Android +(http://wiki.github.com/matburt/mobileorg-android/) by Matt Jones. +Though the two implementations are not identical, they offer similar +features. + + This appendix describes Org’s support for agenda view formats +compatible with MobileOrg. It also describes synchronizing changes, +such as to notes, between MobileOrg and the computer. + + To change tags and TODO states in MobileOrg, first customize the +variables ‘org-todo-keywords’ and ‘org-tag-alist’. These should cover +all the important tags and TODO keywords, even if Org files use only +some of them. Though MobileOrg has in-buffer settings, it understands +TODO states _sets_ (*note Per-file keywords::) and _mutually exclusive_ +tags (*note Setting tags::) only for those set in these variables. + +* Menu: + +* Setting up the staging area:: For the mobile device +* Pushing to MobileOrg:: Uploading Org files and agendas +* Pulling from MobileOrg:: Integrating captured and flagged items + + +File: org, Node: Setting up the staging area, Next: Pushing to MobileOrg, Up: MobileOrg + +B.1 Setting up the staging area +=============================== + +MobileOrg needs access to a file directory on a server to interact with +Emacs. With a public server, consider encrypting the files. MobileOrg +version 1.5 supports encryption for the iPhone. Org also requires +‘openssl’ installed on the local computer. To turn on encryption, set +the same password in MobileOrg and in Emacs. Set the password in the +variable ‘org-mobile-use-encryption’(1). Note that even after MobileOrg +encrypts the file contents, the file names will remain visible on the +file systems of the local computer, the server, and the mobile device. + + For a server to host files, consider options like Dropbox.com +(http://dropbox.com) account(2). On first connection, MobileOrg creates +a directory ‘MobileOrg/’ on Dropbox. Pass its location to Emacs through +an init file variable as follows: + + (setq org-mobile-directory "~/Dropbox/MobileOrg") + + Org copies files to the above directory for MobileOrg. Org also uses +the same directory for sharing notes between Org and MobileOrg. + + ---------- Footnotes ---------- + + (1) If Emacs is configured for safe storing of passwords, then +configure the variable, ‘org-mobile-encryption-password’; please read +the docstring of that variable. + + (2) An alternative is to use webdav server. MobileOrg documentation +has details of webdav server configuration. Additional help is at FAQ +entry (https://orgmode.org/worg/org-faq.html#mobileorg_webdav). + + +File: org, Node: Pushing to MobileOrg, Next: Pulling from MobileOrg, Prev: Setting up the staging area, Up: MobileOrg + +B.2 Pushing to MobileOrg +======================== + +Org pushes files listed in ‘org-mobile-files’ to ‘org-mobile-directory’. +Files include agenda files (as listed in ‘org-agenda-files’). Customize +‘org-mobile-files’ to add other files. File names will be staged with +paths relative to ‘org-directory’, so all files should be inside this +directory(1). + + Push creates a special Org file ‘agendas.org’ with custom agenda +views defined by the user(2). + + Org writes the file ‘index.org’, containing links to other files. +MobileOrg reads this file first from the server to determine what other +files to download for agendas. For faster downloads, MobileOrg will +read only those files whose checksums(3) have changed. + + ---------- Footnotes ---------- + + (1) Symbolic links in ‘org-directory’ should have the same name as +their targets. + + (2) While creating the agendas, Org mode will force ID properties on +all referenced entries, so that these entries can be uniquely identified +if MobileOrg flags them for further action. To avoid setting properties +configure the variable ‘org-mobile-force-id-on-agenda-items’ to ‘nil’. +Org mode will then rely on outline paths, assuming they are unique. + + (3) Checksums are stored automatically in the file ‘checksums.dat’. + + +File: org, Node: Pulling from MobileOrg, Prev: Pushing to MobileOrg, Up: MobileOrg + +B.3 Pulling from MobileOrg +========================== + +When MobileOrg synchronizes with the server, it pulls the Org files for +viewing. It then appends to the file ‘mobileorg.org’ on the server the +captured entries, pointers to flagged and changed entries. Org +integrates its data in an inbox file format. + + 1. Org moves all entries found in ‘mobileorg.org’(1) and appends them + to the file pointed to by the variable ‘org-mobile-inbox-for-pull’. + Each captured entry and each editing event is a top-level entry in + the inbox file. + 2. After moving the entries, Org attempts changes to MobileOrg. Some + changes are applied directly and without user interaction. + Examples include changes to tags, TODO state, headline and body + text. Entries for further action are tagged as ‘:FLAGGED:’. Org + marks entries with problems with an error message in the inbox. + They have to be resolved manually. + 3. Org generates an agenda view for flagged entries for user + intervention to clean up. For notes stored in flagged entries, + MobileOrg displays them in the echo area when the cursor is on the + corresponding agenda item. + + ‘?’ + Pressing ‘?’ displays the entire flagged note in another + window. Org also pushes it to the kill ring. To store + flagged note as a normal note, use ‘? z C-y C-c C-c’. + Pressing ‘?’ twice does these things: first it removes the + ‘:FLAGGED:’ tag; second, it removes the flagged note from the + property drawer; third, it signals that manual editing of the + flagged entry is now finished. + + ‘C-c a ?’ returns to the agenda view to finish processing flagged +entries. Note that these entries may not be the most recent since +MobileOrg searches files that were last pulled. To get an updated +agenda view with changes since the last pull, pull again. + + ---------- Footnotes ---------- + + (1) ‘mobileorg.org’ will be empty after this operation. + + +File: org, Node: History and acknowledgments, Next: GNU Free Documentation License, Prev: MobileOrg, Up: Top + +Appendix C History and acknowledgments +************************************** + +C.1 From Carsten +================ + +Org was born in 2003, out of frustration over the user interface of the +Emacs Outline mode. I was trying to organize my notes and projects, and +using Emacs seemed to be the natural way to go. However, having to +remember eleven different commands with two or three keys per command, +only to hide and show parts of the outline tree, that seemed entirely +unacceptable. Also, when using outlines to take notes, I constantly +wanted to restructure the tree, organizing it paralleling my thoughts +and plans. _Visibility cycling_ and _structure editing_ were originally +implemented in the package ‘outline-magic.el’, but quickly moved to the +more general ‘org.el’. As this environment became comfortable for +project planning, the next step was adding _TODO entries_, basic +_timestamps_, and _table support_. These areas highlighted the two main +goals that Org still has today: to be a new, outline-based, plain text +mode with innovative and intuitive editing features, and to incorporate +project planning functionality directly into a notes file. + + Since the first release, literally thousands of emails to me or to + have provided a constant stream of bug reports, +feedback, new ideas, and sometimes patches and add-on code. Many thanks +to everyone who has helped to improve this package. I am trying to keep +here a list of the people who had significant influence in shaping one +or more aspects of Org. The list may not be complete, if I have +forgotten someone, please accept my apologies and let me know. + + Before I get to this list, a few special mentions are in order: + +Bastien Guerry + Bastien has written a large number of extensions to Org (most of + them integrated into the core by now), including the LaTeX exporter + and the plain list parser. His support during the early days was + central to the success of this project. Bastien also invented + Worg, helped establishing the Web presence of Org, and sponsored + hosting costs for the orgmode.org website. Bastien stepped in as + maintainer of Org between 2011 and 2013, at a time when I + desperately needed a break. +Eric Schulte and Dan Davison + Eric and Dan are jointly responsible for the Org-babel system, + which turns Org into a multi-language environment for evaluating + code and doing literate programming and reproducible research. + This has become one of Org’s killer features that define what Org + is today. +John Wiegley + John has contributed a number of great ideas and patches directly + to Org, including the attachment system (‘org-attach.el’), + integration with Apple Mail (‘org-mac-message.el’), hierarchical + dependencies of TODO items, habit tracking (‘org-habits.el’), and + encryption (‘org-crypt.el’). Also, the capture system is really an + extended copy of his great ‘remember.el’. +Sebastian Rose + Without Sebastian, the HTML/XHTML publishing of Org would be the + pitiful work of an ignorant amateur. Sebastian has pushed this + part of Org onto a much higher level. He also wrote ‘org-info.js’, + a Java script for displaying web pages derived from Org using an + Info-like or a folding interface with single-key navigation. + +See below for the full list of contributions! Again, please let me know +what I am missing here! + +C.2 From Bastien +================ + +I (Bastien) have been maintaining Org between 2011 and 2013. This +appendix would not be complete without adding a few more acknowledgments +and thanks. + + I am first grateful to Carsten for his trust while handing me over +the maintainership of Org. His unremitting support is what really +helped me getting more confident over time, with both the community and +the code. + + When I took over maintainership, I knew I would have to make Org more +collaborative than ever, as I would have to rely on people that are more +knowledgeable than I am on many parts of the code. Here is a list of +the persons I could rely on, they should really be considered +co-maintainers, either of the code or the community: + +Eric Schulte + Eric is maintaining the Babel parts of Org. His reactivity here + kept me away from worrying about possible bugs here and let me + focus on other parts. + +Nicolas Goaziou + Nicolas is maintaining the consistency of the deepest parts of Org. + His work on ‘org-element.el’ and ‘ox.el’ has been outstanding, and + it opened the doors for many new ideas and features. He rewrote + many of the old exporters to use the new export engine, and helped + with documenting this major change. More importantly (if that’s + possible), he has been more than reliable during all the work done + for Org 8.0, and always very reactive on the mailing list. + +Achim Gratz + Achim rewrote the building process of Org, turning some _ad hoc_ + tools into a flexible and conceptually clean process. He patiently + coped with the many hiccups that such a change can create for + users. + +Nick Dokos + The Org mode mailing list would not be such a nice place without + Nick, who patiently helped users so many times. It is impossible + to overestimate such a great help, and the list would not be so + active without him. + + I received support from so many users that it is clearly impossible +to be fair when shortlisting a few of them, but Org’s history would not +be complete if the ones above were not mentioned in this manual. + +C.3 List of contributions +========================= + + • Russel Adams came up with the idea for drawers. + • Suvayu Ali has steadily helped on the mailing list, providing + useful feedback on many features and several patches. + • Luis Anaya wrote ‘ox-man.el’. + • Thomas Baumann wrote ‘org-bbdb.el’ and ‘org-mhe.el’. + • Michael Brand helped by reporting many bugs and testing many + features. He also implemented the distinction between empty fields + and 0-value fields in Org’s spreadsheets. + • Christophe Bataillon created the great unicorn logo that we use on + the Org mode website. + • Alex Bochannek provided a patch for rounding timestamps. + • Jan Böcker wrote ‘org-docview.el’. + • Brad Bozarth showed how to pull RSS feed data into Org mode files. + • Tom Breton wrote ‘org-choose.el’. + • Charles Cave’s suggestion sparked the implementation of templates + for Remember, which are now templates for capture. + • Pavel Chalmoviansky influenced the agenda treatment of items with + specified time. + • Gregory Chernov patched support for Lisp forms into table + calculations and improved XEmacs compatibility, in particular by + porting ‘nouline.el’ to XEmacs. + • Sacha Chua suggested copying some linking code from Planner, and + helped make Org popular through her blog. + • Toby S. Cubitt contributed to the code for clock formats. + • Baoqiu Cui contributed the first DocBook exporter. In Org 8.0, we + go a different route: you can now export to Texinfo and export the + ‘.texi’ file to DocBook using ‘makeinfo’. + • Eddward DeVilla proposed and tested checkbox statistics. He also + came up with the idea of properties, and that there should be an + API for them. + • Nick Dokos tracked down several nasty bugs. + • Kees Dullemond used to edit projects lists directly in HTML and so + inspired some of the early development, including HTML export. He + also asked for a way to narrow wide table columns. + • Jason Dunsmore has been maintaining the Org-Mode server at + Rackspace for several years now. He also sponsored the hosting + costs until Rackspace started to host us for free. + • Thomas S. Dye contributed documentation on Worg and helped + integrating the Org-Babel documentation into the manual. + • Christian Egli converted the documentation into Texinfo format, + inspired the agenda, patched CSS formatting into the HTML exporter, + and wrote ‘org-taskjuggler.el’, which has been rewritten by Nicolas + Goaziou as ‘ox-taskjuggler.el’ for Org 8.0. + • David Emery provided a patch for custom CSS support in exported + HTML agendas. + • Sean Escriva took over MobileOrg development on the iPhone + platform. + • Nic Ferrier contributed mailcap and XOXO support. + • Miguel A. Figueroa-Villanueva implemented hierarchical checkboxes. + • John Foerch figured out how to make incremental search show context + around a match in a hidden outline tree. + • Raimar Finken wrote ‘org-git-line.el’. + • Mikael Fornius works as a mailing list moderator. + • Austin Frank works as a mailing list moderator. + • Eric Fraga drove the development of BEAMER export with ideas and + testing. + • Barry Gidden did proofreading the manual in preparation for the + book publication through Network Theory Ltd. + • Niels Giesen had the idea to automatically archive DONE trees. + • Nicolas Goaziou rewrote much of the plain list code. He also wrote + ‘org-element.el’ and ‘org-export.el’, which was a huge step forward + in implementing a clean framework for Org exporters. + • Kai Grossjohann pointed out key-binding conflicts with other + packages. + • Brian Gough of Network Theory Ltd publishes the Org mode manual as + a book. + • Bernt Hansen has driven much of the support for auto-repeating + tasks, task state change logging, and the clocktable. His clear + explanations have been critical when we started to adopt the Git + version control system. + • Manuel Hermenegildo has contributed various ideas, small fixes and + patches. + • Phil Jackson wrote ‘org-irc.el’. + • Scott Jaderholm proposed footnotes, control over whitespace between + folded entries, and column view for properties. + • Matt Jones wrote MobileOrg Android. + • Tokuya Kameshima wrote ‘org-wl.el’ and ‘org-mew.el’. + • Jonathan Leech-Pepin wrote ‘ox-texinfo.el’. + • Shidai Liu ("Leo") asked for embedded LaTeX and tested it. He also + provided frequent feedback and some patches. + • Matt Lundin has proposed last-row references for table formulas and + named invisible anchors. He has also worked a lot on the FAQ. + • David Maus wrote ‘org-atom.el’, maintains the issues file for Org, + and is a prolific contributor on the mailing list with competent + replies, small fixes and patches. + • Jason F. McBrayer suggested agenda export to CSV format. + • Max Mikhanosha came up with the idea of refiling and sticky + agendas. + • Dmitri Minaev sent a patch to set priority limits on a per-file + basis. + • Stefan Monnier provided a patch to keep the Emacs-Lisp compiler + happy. + • Richard Moreland wrote MobileOrg for the iPhone. + • Rick Moynihan proposed allowing multiple TODO sequences in a file + and being able to quickly restrict the agenda to a subtree. + • Todd Neal provided patches for links to Info files and Elisp forms. + • Greg Newman refreshed the unicorn logo into its current form. + • Tim O’Callaghan suggested in-file links, search options for general + file links, and TAGS. + • Osamu Okano wrote ‘orgcard2ref.pl’, a Perl program to create a text + version of the reference card. + • Takeshi Okano translated the manual and David O’Toole’s tutorial + into Japanese. + • Oliver Oppitz suggested multi-state TODO items. + • Scott Otterson sparked the introduction of descriptive text for + links, among other things. + • Pete Phillips helped during the development of the TAGS feature, + and provided frequent feedback. + • Francesco Pizzolante provided patches that helped speeding up the + agenda generation. + • Martin Pohlack provided the code snippet to bundle character + insertion into bundles of 20 for undo. + • Rackspace.com is hosting our website for free. Thank you + Rackspace! + • T.V. Raman reported bugs and suggested improvements. + • Matthias Rempe (Oelde) provided ideas, Windows support, and quality + control. + • Paul Rivier provided the basic implementation of named footnotes. + He also acted as mailing list moderator for some time. + • Kevin Rogers contributed code to access VM files on remote hosts. + • Frank Ruell solved the mystery of the ‘keymapp nil’ bug, a conflict + with ‘allout.el’. + • Jason Riedy generalized the send-receive mechanism for Orgtbl + tables with extensive patches. + • Philip Rooke created the Org reference card, provided lots of + feedback, developed and applied standards to the Org documentation. + • Christian Schlauer proposed angular brackets around links, among + other things. + • Christopher Schmidt reworked ‘orgstruct-mode’ so that users can + enjoy folding in non-org buffers by using Org headlines in + comments. + • Paul Sexton wrote ‘org-ctags.el’. + • Linking to VM/BBDB/Gnus was first inspired by Tom Shannon’s + ‘organizer-mode.el’. + • Ilya Shlyakhter proposed the Archive Sibling, line numbering in + literal examples, and remote highlighting for referenced code + lines. + • Stathis Sideris wrote the ‘ditaa.jar’ ASCII to PNG converter that + is now packaged into Org’s ‘contrib’ directory. + • Daniel Sinder came up with the idea of internal archiving by + locking subtrees. + • Dale Smith proposed link abbreviations. + • James TD Smith has contributed a large number of patches for useful + tweaks and features. + • Adam Spiers asked for global linking commands, inspired the link + extension system, added support for mairix, and proposed the + mapping API. + • Ulf Stegemann created the table to translate special symbols to + HTML, LaTeX, UTF-8, Latin-1 and ASCII. + • Andy Stewart contributed code to ‘org-w3m.el’, to copy HTML content + with links transformation to Org syntax. + • David O’Toole wrote ‘org-publish.el’ and drafted the manual chapter + about publishing. + • Jambunathan K contributed the ODT exporter and rewrote the HTML + exporter. + • Sebastien Vauban reported many issues with LaTeX and BEAMER export + and enabled source code highlighting in Gnus. + • Stefan Vollmar organized a video-recorded talk at the + Max-Planck-Institute for Neurology. He also inspired the creation + of a concept index for HTML export. + • Jürgen Vollmer contributed code generating the table of contents in + HTML output. + • Samuel Wales has provided important feedback and bug reports. + • Chris Wallace provided a patch implementing the ‘QUOTE’ keyword. + • David Wainberg suggested archiving, and improvements to the linking + system. + • Carsten Wimmer suggested some changes and helped fix a bug in + linking to Gnus. + • Roland Winkler requested additional key bindings to make Org work + on a tty. + • Piotr Zielinski wrote ‘org-mouse.el’, proposed agenda blocks and + contributed various ideas and code snippets. + • Marco Wahl wrote ‘org-eww.el’. + + +File: org, Node: GNU Free Documentation License, Next: Main Index, Prev: History and acknowledgments, Up: Top + +Appendix D GNU Free Documentation License +***************************************** + + Version 1.3, 3 November 2008 + + Copyright © 2000, 2001, 2002, 2007, 2008, 2013, 2014, 2018 Free Software Foundation, Inc. + + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + 0. PREAMBLE + + The purpose of this License is to make a manual, textbook, or other + functional and useful document “free” in the sense of freedom: to + assure everyone the effective freedom to copy and redistribute it, + with or without modifying it, either commercially or + noncommercially. Secondarily, this License preserves for the + author and publisher a way to get credit for their work, while not + being considered responsible for modifications made by others. + + This License is a kind of “copyleft”, which means that derivative + works of the document must themselves be free in the same sense. + It complements the GNU General Public License, which is a copyleft + license designed for free software. + + We have designed this License in order to use it for manuals for + free software, because free software needs free documentation: a + free program should come with manuals providing the same freedoms + that the software does. But this License is not limited to + software manuals; it can be used for any textual work, regardless + of subject matter or whether it is published as a printed book. We + recommend this License principally for works whose purpose is + instruction or reference. + + 1. APPLICABILITY AND DEFINITIONS + + This License applies to any manual or other work, in any medium, + that contains a notice placed by the copyright holder saying it can + be distributed under the terms of this License. Such a notice + grants a world-wide, royalty-free license, unlimited in duration, + to use that work under the conditions stated herein. The + “Document”, below, refers to any such manual or work. Any member + of the public is a licensee, and is addressed as “you”. You accept + the license if you copy, modify or distribute the work in a way + requiring permission under copyright law. + + A “Modified Version” of the Document means any work containing the + Document or a portion of it, either copied verbatim, or with + modifications and/or translated into another language. + + A “Secondary Section” is a named appendix or a front-matter section + of the Document that deals exclusively with the relationship of the + publishers or authors of the Document to the Document’s overall + subject (or to related matters) and contains nothing that could + fall directly within that overall subject. (Thus, if the Document + is in part a textbook of mathematics, a Secondary Section may not + explain any mathematics.) The relationship could be a matter of + historical connection with the subject or with related matters, or + of legal, commercial, philosophical, ethical or political position + regarding them. + + The “Invariant Sections” are certain Secondary Sections whose + titles are designated, as being those of Invariant Sections, in the + notice that says that the Document is released under this License. + If a section does not fit the above definition of Secondary then it + is not allowed to be designated as Invariant. The Document may + contain zero Invariant Sections. If the Document does not identify + any Invariant Sections then there are none. + + The “Cover Texts” are certain short passages of text that are + listed, as Front-Cover Texts or Back-Cover Texts, in the notice + that says that the Document is released under this License. A + Front-Cover Text may be at most 5 words, and a Back-Cover Text may + be at most 25 words. + + A “Transparent” copy of the Document means a machine-readable copy, + represented in a format whose specification is available to the + general public, that is suitable for revising the document + straightforwardly with generic text editors or (for images composed + of pixels) generic paint programs or (for drawings) some widely + available drawing editor, and that is suitable for input to text + formatters or for automatic translation to a variety of formats + suitable for input to text formatters. A copy made in an otherwise + Transparent file format whose markup, or absence of markup, has + been arranged to thwart or discourage subsequent modification by + readers is not Transparent. An image format is not Transparent if + used for any substantial amount of text. A copy that is not + “Transparent” is called “Opaque”. + + Examples of suitable formats for Transparent copies include plain + ASCII without markup, Texinfo input format, LaTeX input format, + SGML or XML using a publicly available DTD, and standard-conforming + simple HTML, PostScript or PDF designed for human modification. + Examples of transparent image formats include PNG, XCF and JPG. + Opaque formats include proprietary formats that can be read and + edited only by proprietary word processors, SGML or XML for which + the DTD and/or processing tools are not generally available, and + the machine-generated HTML, PostScript or PDF produced by some word + processors for output purposes only. + + The “Title Page” means, for a printed book, the title page itself, + plus such following pages as are needed to hold, legibly, the + material this License requires to appear in the title page. For + works in formats which do not have any title page as such, “Title + Page” means the text near the most prominent appearance of the + work’s title, preceding the beginning of the body of the text. + + The “publisher” means any person or entity that distributes copies + of the Document to the public. + + A section “Entitled XYZ” means a named subunit of the Document + whose title either is precisely XYZ or contains XYZ in parentheses + following text that translates XYZ in another language. (Here XYZ + stands for a specific section name mentioned below, such as + “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) + To “Preserve the Title” of such a section when you modify the + Document means that it remains a section “Entitled XYZ” according + to this definition. + + The Document may include Warranty Disclaimers next to the notice + which states that this License applies to the Document. These + Warranty Disclaimers are considered to be included by reference in + this License, but only as regards disclaiming warranties: any other + implication that these Warranty Disclaimers may have is void and + has no effect on the meaning of this License. + + 2. VERBATIM COPYING + + You may copy and distribute the Document in any medium, either + commercially or noncommercially, provided that this License, the + copyright notices, and the license notice saying this License + applies to the Document are reproduced in all copies, and that you + add no other conditions whatsoever to those of this License. You + may not use technical measures to obstruct or control the reading + or further copying of the copies you make or distribute. However, + you may accept compensation in exchange for copies. If you + distribute a large enough number of copies you must also follow the + conditions in section 3. + + You may also lend copies, under the same conditions stated above, + and you may publicly display copies. + + 3. COPYING IN QUANTITY + + If you publish printed copies (or copies in media that commonly + have printed covers) of the Document, numbering more than 100, and + the Document’s license notice requires Cover Texts, you must + enclose the copies in covers that carry, clearly and legibly, all + these Cover Texts: Front-Cover Texts on the front cover, and + Back-Cover Texts on the back cover. Both covers must also clearly + and legibly identify you as the publisher of these copies. The + front cover must present the full title with all words of the title + equally prominent and visible. You may add other material on the + covers in addition. Copying with changes limited to the covers, as + long as they preserve the title of the Document and satisfy these + conditions, can be treated as verbatim copying in other respects. + + If the required texts for either cover are too voluminous to fit + legibly, you should put the first ones listed (as many as fit + reasonably) on the actual cover, and continue the rest onto + adjacent pages. + + If you publish or distribute Opaque copies of the Document + numbering more than 100, you must either include a machine-readable + Transparent copy along with each Opaque copy, or state in or with + each Opaque copy a computer-network location from which the general + network-using public has access to download using public-standard + network protocols a complete Transparent copy of the Document, free + of added material. If you use the latter option, you must take + reasonably prudent steps, when you begin distribution of Opaque + copies in quantity, to ensure that this Transparent copy will + remain thus accessible at the stated location until at least one + year after the last time you distribute an Opaque copy (directly or + through your agents or retailers) of that edition to the public. + + It is requested, but not required, that you contact the authors of + the Document well before redistributing any large number of copies, + to give them a chance to provide you with an updated version of the + Document. + + 4. MODIFICATIONS + + You may copy and distribute a Modified Version of the Document + under the conditions of sections 2 and 3 above, provided that you + release the Modified Version under precisely this License, with the + Modified Version filling the role of the Document, thus licensing + distribution and modification of the Modified Version to whoever + possesses a copy of it. In addition, you must do these things in + the Modified Version: + + A. Use in the Title Page (and on the covers, if any) a title + distinct from that of the Document, and from those of previous + versions (which should, if there were any, be listed in the + History section of the Document). You may use the same title + as a previous version if the original publisher of that + version gives permission. + + B. List on the Title Page, as authors, one or more persons or + entities responsible for authorship of the modifications in + the Modified Version, together with at least five of the + principal authors of the Document (all of its principal + authors, if it has fewer than five), unless they release you + from this requirement. + + C. State on the Title page the name of the publisher of the + Modified Version, as the publisher. + + D. Preserve all the copyright notices of the Document. + + E. Add an appropriate copyright notice for your modifications + adjacent to the other copyright notices. + + F. Include, immediately after the copyright notices, a license + notice giving the public permission to use the Modified + Version under the terms of this License, in the form shown in + the Addendum below. + + G. Preserve in that license notice the full lists of Invariant + Sections and required Cover Texts given in the Document’s + license notice. + + H. Include an unaltered copy of this License. + + I. Preserve the section Entitled “History”, Preserve its Title, + and add to it an item stating at least the title, year, new + authors, and publisher of the Modified Version as given on the + Title Page. If there is no section Entitled “History” in the + Document, create one stating the title, year, authors, and + publisher of the Document as given on its Title Page, then add + an item describing the Modified Version as stated in the + previous sentence. + + J. Preserve the network location, if any, given in the Document + for public access to a Transparent copy of the Document, and + likewise the network locations given in the Document for + previous versions it was based on. These may be placed in the + “History” section. You may omit a network location for a work + that was published at least four years before the Document + itself, or if the original publisher of the version it refers + to gives permission. + + K. For any section Entitled “Acknowledgements” or “Dedications”, + Preserve the Title of the section, and preserve in the section + all the substance and tone of each of the contributor + acknowledgements and/or dedications given therein. + + L. Preserve all the Invariant Sections of the Document, unaltered + in their text and in their titles. Section numbers or the + equivalent are not considered part of the section titles. + + M. Delete any section Entitled “Endorsements”. Such a section + may not be included in the Modified Version. + + N. Do not retitle any existing section to be Entitled + “Endorsements” or to conflict in title with any Invariant + Section. + + O. Preserve any Warranty Disclaimers. + + If the Modified Version includes new front-matter sections or + appendices that qualify as Secondary Sections and contain no + material copied from the Document, you may at your option designate + some or all of these sections as invariant. To do this, add their + titles to the list of Invariant Sections in the Modified Version’s + license notice. These titles must be distinct from any other + section titles. + + You may add a section Entitled “Endorsements”, provided it contains + nothing but endorsements of your Modified Version by various + parties—for example, statements of peer review or that the text has + been approved by an organization as the authoritative definition of + a standard. + + You may add a passage of up to five words as a Front-Cover Text, + and a passage of up to 25 words as a Back-Cover Text, to the end of + the list of Cover Texts in the Modified Version. Only one passage + of Front-Cover Text and one of Back-Cover Text may be added by (or + through arrangements made by) any one entity. If the Document + already includes a cover text for the same cover, previously added + by you or by arrangement made by the same entity you are acting on + behalf of, you may not add another; but you may replace the old + one, on explicit permission from the previous publisher that added + the old one. + + The author(s) and publisher(s) of the Document do not by this + License give permission to use their names for publicity for or to + assert or imply endorsement of any Modified Version. + + 5. COMBINING DOCUMENTS + + You may combine the Document with other documents released under + this License, under the terms defined in section 4 above for + modified versions, provided that you include in the combination all + of the Invariant Sections of all of the original documents, + unmodified, and list them all as Invariant Sections of your + combined work in its license notice, and that you preserve all + their Warranty Disclaimers. + + The combined work need only contain one copy of this License, and + multiple identical Invariant Sections may be replaced with a single + copy. If there are multiple Invariant Sections with the same name + but different contents, make the title of each such section unique + by adding at the end of it, in parentheses, the name of the + original author or publisher of that section if known, or else a + unique number. Make the same adjustment to the section titles in + the list of Invariant Sections in the license notice of the + combined work. + + In the combination, you must combine any sections Entitled + “History” in the various original documents, forming one section + Entitled “History”; likewise combine any sections Entitled + “Acknowledgements”, and any sections Entitled “Dedications”. You + must delete all sections Entitled “Endorsements.” + + 6. COLLECTIONS OF DOCUMENTS + + You may make a collection consisting of the Document and other + documents released under this License, and replace the individual + copies of this License in the various documents with a single copy + that is included in the collection, provided that you follow the + rules of this License for verbatim copying of each of the documents + in all other respects. + + You may extract a single document from such a collection, and + distribute it individually under this License, provided you insert + a copy of this License into the extracted document, and follow this + License in all other respects regarding verbatim copying of that + document. + + 7. AGGREGATION WITH INDEPENDENT WORKS + + A compilation of the Document or its derivatives with other + separate and independent documents or works, in or on a volume of a + storage or distribution medium, is called an “aggregate” if the + copyright resulting from the compilation is not used to limit the + legal rights of the compilation’s users beyond what the individual + works permit. When the Document is included in an aggregate, this + License does not apply to the other works in the aggregate which + are not themselves derivative works of the Document. + + If the Cover Text requirement of section 3 is applicable to these + copies of the Document, then if the Document is less than one half + of the entire aggregate, the Document’s Cover Texts may be placed + on covers that bracket the Document within the aggregate, or the + electronic equivalent of covers if the Document is in electronic + form. Otherwise they must appear on printed covers that bracket + the whole aggregate. + + 8. TRANSLATION + + Translation is considered a kind of modification, so you may + distribute translations of the Document under the terms of section + 4. Replacing Invariant Sections with translations requires special + permission from their copyright holders, but you may include + translations of some or all Invariant Sections in addition to the + original versions of these Invariant Sections. You may include a + translation of this License, and all the license notices in the + Document, and any Warranty Disclaimers, provided that you also + include the original English version of this License and the + original versions of those notices and disclaimers. In case of a + disagreement between the translation and the original version of + this License or a notice or disclaimer, the original version will + prevail. + + If a section in the Document is Entitled “Acknowledgements”, + “Dedications”, or “History”, the requirement (section 4) to + Preserve its Title (section 1) will typically require changing the + actual title. + + 9. TERMINATION + + You may not copy, modify, sublicense, or distribute the Document + except as expressly provided under this License. Any attempt + otherwise to copy, modify, sublicense, or distribute it is void, + and will automatically terminate your rights under this License. + + However, if you cease all violation of this License, then your + license from a particular copyright holder is reinstated (a) + provisionally, unless and until the copyright holder explicitly and + finally terminates your license, and (b) permanently, if the + copyright holder fails to notify you of the violation by some + reasonable means prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is + reinstated permanently if the copyright holder notifies you of the + violation by some reasonable means, this is the first time you have + received notice of violation of this License (for any work) from + that copyright holder, and you cure the violation prior to 30 days + after your receipt of the notice. + + Termination of your rights under this section does not terminate + the licenses of parties who have received copies or rights from you + under this License. If your rights have been terminated and not + permanently reinstated, receipt of a copy of some or all of the + same material does not give you any rights to use it. + + 10. FUTURE REVISIONS OF THIS LICENSE + + The Free Software Foundation may publish new, revised versions of + the GNU Free Documentation License from time to time. Such new + versions will be similar in spirit to the present version, but may + differ in detail to address new problems or concerns. See + . + + Each version of the License is given a distinguishing version + number. If the Document specifies that a particular numbered + version of this License “or any later version” applies to it, you + have the option of following the terms and conditions either of + that specified version or of any later version that has been + published (not as a draft) by the Free Software Foundation. If the + Document does not specify a version number of this License, you may + choose any version ever published (not as a draft) by the Free + Software Foundation. If the Document specifies that a proxy can + decide which future versions of this License can be used, that + proxy’s public statement of acceptance of a version permanently + authorizes you to choose that version for the Document. + + 11. RELICENSING + + “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any + World Wide Web server that publishes copyrightable works and also + provides prominent facilities for anybody to edit those works. A + public wiki that anybody can edit is an example of such a server. + A “Massive Multiauthor Collaboration” (or “MMC”) contained in the + site means any set of copyrightable works thus published on the MMC + site. + + “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0 + license published by Creative Commons Corporation, a not-for-profit + corporation with a principal place of business in San Francisco, + California, as well as future copyleft versions of that license + published by that same organization. + + “Incorporate” means to publish or republish a Document, in whole or + in part, as part of another Document. + + An MMC is “eligible for relicensing” if it is licensed under this + License, and if all works that were first published under this + License somewhere other than this MMC, and subsequently + incorporated in whole or in part into the MMC, (1) had no cover + texts or invariant sections, and (2) were thus incorporated prior + to November 1, 2008. + + The operator of an MMC Site may republish an MMC contained in the + site under CC-BY-SA on the same site at any time before August 1, + 2009, provided the MMC is eligible for relicensing. + +ADDENDUM: How to use this License for your documents +==================================================== + +To use this License in a document you have written, include a copy of +the License in the document and put the following copyright and license +notices just after the title page: + + Copyright (C) YEAR YOUR NAME. + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU Free Documentation License, Version 1.3 + or any later version published by the Free Software Foundation; + with no Invariant Sections, no Front-Cover Texts, and no Back-Cover + Texts. A copy of the license is included in the section entitled ``GNU + Free Documentation License''. + + If you have Invariant Sections, Front-Cover Texts and Back-Cover +Texts, replace the “with...Texts.” line with this: + + with the Invariant Sections being LIST THEIR TITLES, with + the Front-Cover Texts being LIST, and with the Back-Cover Texts + being LIST. + + If you have Invariant Sections without Cover Texts, or some other +combination of the three, merge those two alternatives to suit the +situation. + + If your document contains nontrivial examples of program code, we +recommend releasing these examples in parallel under your choice of free +software license, such as the GNU General Public License, to permit +their use in free software. + + +File: org, Node: Main Index, Next: Key Index, Prev: GNU Free Documentation License, Up: Top + +Concept index +************* + +[index] +* Menu: + +* #+ARCHIVE: Moving subtrees. (line 33) +* #+ASCII: ASCII/Latin-1/UTF-8 export. + (line 56) +* #+ATTR_ASCII: ASCII/Latin-1/UTF-8 export. + (line 67) +* #+ATTR_BEAMER: Beamer specific syntax. + (line 35) +* #+ATTR_HTML: Links in HTML export. + (line 27) +* #+ATTR_HTML <1>: Tables in HTML export. + (line 11) +* #+ATTR_HTML <2>: Images in HTML export. + (line 29) +* #+ATTR_LATEX, in example blocks: Example blocks in LaTeX export. + (line 6) +* #+ATTR_LATEX, in horizontal rules: Horizontal rules in LaTeX export. + (line 6) +* #+ATTR_LATEX, in images: Images in LaTeX export. + (line 6) +* #+ATTR_LATEX, in plain lists: Plain lists in LaTeX export. + (line 6) +* #+ATTR_LATEX, in source blocks: Source blocks in LaTeX export. + (line 6) +* #+ATTR_LATEX, in special blocks: Special blocks in LaTeX export. + (line 6) +* #+ATTR_LATEX, in tables: Tables in LaTeX export. + (line 6) +* #+ATTR_ODT: Tables in ODT export. + (line 20) +* #+ATTR_ODT <1>: Images in ODT export. + (line 31) +* #+ATTR_ODT <2>: Images in ODT export. + (line 76) +* #+ATTR_ODT <3>: Customizing tables in ODT export. + (line 6) +* #+ATTR_TEXINFO, in images: Images in Texinfo export. + (line 6) +* #+ATTR_TEXINFO, in plain lists: Plain lists in Texinfo export. + (line 6) +* #+ATTR_TEXINFO, in special blocks: Special blocks in Texinfo export. + (line 6) +* #+ATTR_TEXINFO, in tables: Tables in Texinfo export. + (line 6) +* #+AUTHOR: Export settings. (line 25) +* #+BEAMER: Beamer specific syntax. + (line 19) +* #+BEAMER_FONT_THEME: Beamer specific export settings. + (line 16) +* #+BEAMER_HEADER: Beamer specific export settings. + (line 25) +* #+BEAMER_INNER_THEME: Beamer specific export settings. + (line 19) +* #+BEAMER_OUTER_THEME: Beamer specific export settings. + (line 22) +* #+BEAMER_THEME: Beamer specific export settings. + (line 11) +* #+BEGIN, clocktable: The clock table. (line 32) +* #+BEGIN, columnview: Capturing column view. + (line 11) +* #+BEGIN, dynamic block: Dynamic blocks. (line 15) +* #+BEGIN_CENTER: Paragraphs. (line 31) +* #+BEGIN_COMMENT: Comment lines. (line 10) +* #+BEGIN_EXAMPLE: Literal examples. (line 8) +* #+BEGIN_EXPORT ascii: ASCII/Latin-1/UTF-8 export. + (line 56) +* #+BEGIN_EXPORT beamer: Beamer specific syntax. + (line 19) +* #+BEGIN_EXPORT html: Quoting HTML tags. (line 14) +* #+BEGIN_EXPORT latex: Quoting LaTeX code. (line 17) +* #+BEGIN_EXPORT texinfo: Quoting Texinfo code. + (line 9) +* #+BEGIN_JUSTIFYLEFT: ASCII/Latin-1/UTF-8 export. + (line 77) +* #+BEGIN_JUSTIFYRIGHT: ASCII/Latin-1/UTF-8 export. + (line 77) +* #+BEGIN_QUOTE: Paragraphs. (line 26) +* #+BEGIN_SRC: Literal examples. (line 28) +* #+BEGIN_SRC <1>: Structure of code blocks. + (line 6) +* #+BEGIN_VERSE: Paragraphs. (line 13) +* #+BIND: Export settings. (line 210) +* #+CALL: Evaluating code blocks. + (line 25) +* #+CAPTION: Images and tables. (line 6) +* #+CAPTION <1>: Tables in HTML export. + (line 11) +* #+CAPTION <2>: Images in HTML export. + (line 29) +* #+CATEGORY: Categories. (line 6) +* #+CINDEX: Indices. (line 6) +* #+COLUMNS: Scope of column definitions. + (line 8) +* #+CONSTANTS: References. (line 108) +* #+CREATOR: Export settings. (line 28) +* #+DATE: Export settings. (line 32) +* #+DESCRIPTION (Beamer): Beamer specific export settings. + (line 29) +* #+DESCRIPTION (HTML): HTML Specific export settings. + (line 10) +* #+DESCRIPTION (LaTeX): LaTeX specific export settings. + (line 11) +* #+DESCRIPTION (ODT): ODT specific export settings. + (line 11) +* #+EMAIL: Export settings. (line 35) +* #+EXCLUDE_TAGS: Export settings. (line 52) +* #+EXPORT_FILE_NAME: Export settings. (line 64) +* #+FILETAGS: Tag inheritance. (line 20) +* #+FINDEX: Indices. (line 6) +* #+HEADER:: Code block specific header arguments. + (line 30) +* #+HTML: Quoting HTML tags. (line 12) +* #+HTML_CONTAINER: HTML Specific export settings. + (line 19) +* #+HTML_DOCTYPE: HTML Specific export settings. + (line 16) +* #+HTML_HEAD: HTML Specific export settings. + (line 35) +* #+HTML_HEAD <1>: CSS support. (line 48) +* #+HTML_HEAD_EXTRA: HTML Specific export settings. + (line 39) +* #+HTML_HEAD_EXTRA <1>: CSS support. (line 48) +* #+HTML_INCLUDE_STYLE: CSS support. (line 43) +* #+HTML_LINK_HOME: HTML Specific export settings. + (line 23) +* #+HTML_LINK_UP: HTML Specific export settings. + (line 26) +* #+HTML_MATHJAX: HTML Specific export settings. + (line 30) +* #+INCLUDE: Include files. (line 7) +* #+INDEX: Generating an index. (line 16) +* #+INFOJS_OPT: JavaScript support. (line 20) +* #+KEYWORDS (Beamer): Beamer specific export settings. + (line 36) +* #+KEYWORDS (HTML): HTML Specific export settings. + (line 43) +* #+KEYWORDS (LaTeX): LaTeX specific export settings. + (line 46) +* #+KEYWORDS (ODT): ODT specific export settings. + (line 16) +* #+KINDEX: Indices. (line 6) +* #+LANGUAGE: Export settings. (line 38) +* #+LATEX: Quoting LaTeX code. (line 13) +* #+LATEX_CLASS: LaTeX specific export settings. + (line 20) +* #+LATEX_CLASS <1>: LaTeX header and sectioning. + (line 23) +* #+LATEX_CLASS_OPTIONS: LaTeX specific export settings. + (line 28) +* #+LATEX_CLASS_OPTIONS <1>: LaTeX header and sectioning. + (line 23) +* #+LATEX_COMPILER: LaTeX specific export settings. + (line 32) +* #+LATEX_HEADER: LaTeX specific export settings. + (line 36) +* #+LATEX_HEADER <1>: LaTeX header and sectioning. + (line 30) +* #+LATEX_HEADER (HTML): HTML Specific export settings. + (line 48) +* #+LATEX_HEADER_EXTRA: LaTeX specific export settings. + (line 41) +* #+LATEX_HEADER_EXTRA <1>: LaTeX header and sectioning. + (line 30) +* #+LINK: Link abbreviations. (line 49) +* #+MACRO: Macro replacement. (line 6) +* #+NAME: Internal links. (line 21) +* #+NAME <1>: Images and tables. (line 6) +* #+NAME <2>: Structure of code blocks. + (line 6) +* #+NAME <3>: Structure of code blocks. + (line 39) +* #+NAME, for table: References. (line 129) +* #+ODT_STYLES_FILE: Applying custom styles. + (line 25) +* #+OPTIONS: Export settings. (line 6) +* #+ORGLST: Radio lists. (line 11) +* #+ORGTBL: Radio tables. (line 19) +* #+ORGTBL, SEND: A LaTeX example. (line 12) +* #+PINDEX: Indices. (line 6) +* #+PLOT: Org-Plot. (line 6) +* #+PRIORITIES: Priorities. (line 42) +* #+PROPERTY: Property syntax. (line 44) +* #+RESULTS: Evaluating code blocks. + (line 6) +* #+SELECT_TAGS: Export settings. (line 44) +* #+SEQ_TODO: Per-file keywords. (line 6) +* #+SETUPFILE: Export settings. (line 13) +* #+SETUPFILE <1>: In-buffer settings. (line 45) +* #+STARTUP: In-buffer settings. (line 58) +* #+SUBAUTHOR: Texinfo specific export settings. + (line 14) +* #+SUBAUTHOR <1>: Texinfo title and copyright page. + (line 12) +* #+SUBTITLE (ASCII): ASCII/Latin-1/UTF-8 export. + (line 39) +* #+SUBTITLE (Beamer): Beamer specific export settings. + (line 44) +* #+SUBTITLE (HTML): HTML Specific export settings. + (line 53) +* #+SUBTITLE (LaTeX): LaTeX specific export settings. + (line 55) +* #+SUBTITLE (Texinfo): Texinfo specific export settings. + (line 11) +* #+TAGS: Setting tags. (line 28) +* #+TBLFM: Field and range formulas. + (line 12) +* #+TBLFM <1>: Editing and debugging formulas. + (line 84) +* #+TBLFM <2>: In-buffer settings. (line 166) +* #+TBLFM line, multiple: Editing and debugging formulas. + (line 84) +* #+TBLFM, switching: Editing and debugging formulas. + (line 84) +* #+TEXINFO: Quoting Texinfo code. + (line 9) +* #+TEXINFO_CLASS: Texinfo specific export settings. + (line 20) +* #+TEXINFO_CLASS <1>: Texinfo file header. (line 11) +* #+TEXINFO_CLASS <2>: Headings and sectioning structure. + (line 6) +* #+TEXINFO_DIR_CATEGORY: Texinfo specific export settings. + (line 30) +* #+TEXINFO_DIR_CATEGORY <1>: Info directory file. (line 6) +* #+TEXINFO_DIR_DESC: Texinfo specific export settings. + (line 36) +* #+TEXINFO_DIR_DESC <1>: Info directory file. (line 6) +* #+TEXINFO_DIR_TITLE: Texinfo specific export settings. + (line 33) +* #+TEXINFO_DIR_TITLE <1>: Info directory file. (line 6) +* #+TEXINFO_FILENAME: Texinfo specific export settings. + (line 17) +* #+TEXINFO_FILENAME <1>: Texinfo file header. (line 6) +* #+TEXINFO_HEADER: Texinfo specific export settings. + (line 24) +* #+TEXINFO_HEADER <1>: Texinfo file header. (line 11) +* #+TEXINFO_POST_HEADER: Texinfo specific export settings. + (line 27) +* #+TEXINFO_PRINTED_TITLE: Texinfo specific export settings. + (line 39) +* #+TEXINFO_PRINTED_TITLE <1>: Texinfo title and copyright page. + (line 6) +* #+TINDEX: Indices. (line 6) +* #+TITLE: Export settings. (line 60) +* #+TOC: Table of contents. (line 6) +* #+TODO: Per-file keywords. (line 6) +* #+TYP_TODO: Per-file keywords. (line 6) +* #+VINDEX: Indices. (line 6) +* %:annotation template expansion in capture: capture protocol. + (line 23) +* %:description template expansion in capture: capture protocol. + (line 23) +* %:link template expansion in capture: capture protocol. (line 23) +* :base-url property in open-source protocol: open-source protocol. + (line 13) +* :cache, src header argument: System-wide header arguments. + (line 9) +* :cache, src header argument <1>: cache. (line 6) +* :colnames, src header argument: colnames. (line 6) +* :comments, src header argument: comments. (line 6) +* :dir, src header argument: dir. (line 6) +* :epilogue, src header argument: epilogue. (line 6) +* :eval, src header argument: eval. (line 6) +* :exports, src header argument: Exporting code blocks. + (line 20) +* :exports, src header argument <1>: System-wide header arguments. + (line 9) +* :exports, src header argument <2>: exports. (line 6) +* :file, src header argument: file. (line 6) +* :file-ext, src header argument: file-ext. (line 6) +* :hlines, src header argument: hlines. (line 6) +* :indic attribute, in Texinfo export: Plain lists in Texinfo export. + (line 12) +* :mkdirp, src header argument: mkdirp. (line 6) +* :no-expand, src header argument: no-expand. (line 6) +* :noweb, src header argument: System-wide header arguments. + (line 9) +* :noweb, src header argument <1>: noweb. (line 6) +* :noweb-ref, src header argument: noweb-ref. (line 6) +* :noweb-sep, src header argument: noweb-sep. (line 6) +* :online-suffix property in open-source protocol: open-source protocol. + (line 13) +* :output-dir, src header argument: output-dir. (line 6) +* :padline, src header argument: padline. (line 6) +* :post, src header argument: post. (line 6) +* :prologue, src header argument: prologue. (line 6) +* :results, src header argument: System-wide header arguments. + (line 9) +* :results, src header argument <1>: results. (line 6) +* :results, src header argument <2>: Results of evaluation. + (line 33) +* :results, src header argument <3>: Results of evaluation. + (line 45) +* :results, src header argument <4>: Results of evaluation. + (line 55) +* :results, src header argument <5>: Results of evaluation. + (line 72) +* :rewrites property in open-source protocol: open-source protocol. + (line 43) +* :rownames, src header argument: rownames. (line 6) +* :sep attribute, in Texinfo export: Plain lists in Texinfo export. + (line 17) +* :sep, src header argument: sep. (line 6) +* :session, src header argument: System-wide header arguments. + (line 9) +* :session, src header argument <1>: session. (line 6) +* :shebang, src header argument: shebang. (line 6) +* :table-type attribute, in Texinfo export: Plain lists in Texinfo export. + (line 6) +* :tangle, src header argument: Extracting source code. + (line 23) +* :tangle, src header argument <1>: tangle. (line 6) +* :tangle-mode, src header argument: tangle-mode. (line 6) +* :var, src header argument: var. (line 6) +* :working-directory property in open-source protocol: open-source protocol. + (line 13) +* :working-suffix property in open-source protocol: open-source protocol. + (line 13) +* :wrap, src header argument: wrap. (line 6) +* abbreviation, links: Link abbreviations. (line 6) +* abstract, in LaTeX export: Special blocks in LaTeX export. + (line 6) +* acknowledgments: History and acknowledgments. + (line 6) +* action, for publishing: Publishing action. (line 6) +* activation: Activation. (line 6) +* active region: Structure editing. (line 116) +* active region <1>: Built-in table editor. + (line 145) +* active region <2>: ODT export commands. (line 6) +* add-on packages: Add-on packages. (line 6) +* add-ons, context-sensitive commands: Context-sensitive commands. + (line 6) +* agenda: Weekly/daily agenda. (line 6) +* agenda dispatcher: Agenda dispatcher. (line 6) +* agenda files: Agenda files. (line 6) +* agenda files, removing buffers: Agenda commands. (line 440) +* agenda views: Agenda views. (line 6) +* agenda views, custom: Custom agenda views. (line 6) +* agenda views, exporting: Agenda commands. (line 426) +* agenda views, exporting <1>: Exporting agenda views. + (line 6) +* agenda views, exporting <2>: Exporting agenda views. + (line 13) +* agenda views, main example: Storing searches. (line 9) +* agenda views, optimization: Speeding up your agendas. + (line 6) +* agenda views, user-defined: Special agenda views. + (line 6) +* agenda*, as an agenda views: Storing searches. (line 9) +* agenda, as an agenda views: Storing searches. (line 9) +* agenda, column view: Agenda column view. (line 6) +* agenda, pipe: Extracting agenda information. + (line 6) +* agenda, sticky: Agenda dispatcher. (line 43) +* agenda, with block views: Block agenda. (line 6) +* align, STARTUP keyword: In-buffer settings. (line 79) +* alignment in tables: Column width and alignment. + (line 6) +* anniversaries, from BBDB: Weekly/daily agenda. (line 79) +* API, for mapping: Using the mapping API. + (line 6) +* API, for properties: Property API. (line 6) +* API, for properties <1>: Using the property API. + (line 6) +* appointment: Timestamps. (line 14) +* appointment <1>: Weekly/daily agenda. (line 126) +* appointment reminders: Weekly/daily agenda. (line 126) +* appt.el: Weekly/daily agenda. (line 126) +* archive locations: Moving subtrees. (line 23) +* archive tag: Internal archiving. (line 6) +* archived entries, in agenda views: Agenda views. (line 32) +* Archives mode: Agenda commands. (line 115) +* archiving: Archiving. (line 6) +* ASCII export: ASCII/Latin-1/UTF-8 export. + (line 6) +* Atom feeds: RSS feeds. (line 6) +* attachments: Attachments. (line 6) +* author: Feedback. (line 6) +* author, macro: Macro replacement. (line 24) +* autoload: Activation. (line 6) +* babel, languages: Languages. (line 6) +* babel, library of: Library of Babel. (line 6) +* backtrace of an error: Feedback. (line 63) +* BBDB links: External links. (line 6) +* BBDB, anniversaries: Weekly/daily agenda. (line 79) +* Beamer export: Beamer export. (line 6) +* begin block, end block: Structure of code blocks. + (line 44) +* block agenda: Block agenda. (line 6) +* blocking, of checkboxes: Checkboxes. (line 46) +* blocks, folding: Blocks. (line 6) +* bold text, markup rules: Emphasis and monospace. + (line 6) +* Boolean logic, for tag/property searches: Matching tags and properties. + (line 33) +* bug reports: Feedback. (line 6) +* C-c C-c, overview: The very busy C-c C-c key. + (line 6) +* calc package: The spreadsheet. (line 6) +* calc.el: Cooperation. (line 6) +* calculations, in tables: Built-in table editor. + (line 145) +* calculations, in tables <1>: The spreadsheet. (line 6) +* calendar commands, from agenda: Agenda commands. (line 381) +* calendar integration: Weekly/daily agenda. (line 32) +* calendar, for selecting date: The date/time prompt. + (line 76) +* capture: Capture - Refile - Archive. + (line 6) +* capture <1>: Capture. (line 6) +* capture protocol: capture protocol. (line 6) +* capture, %:annotation placeholder: capture protocol. (line 23) +* capture, %:description placeholder: capture protocol. (line 23) +* capture, %:link placeholder: capture protocol. (line 23) +* capturing, from agenda: Agenda commands. (line 292) +* category: Categories. (line 6) +* category filtering, in agenda: Filtering/limiting agenda items. + (line 17) +* category, require for tags/property match: Matching tags and properties. + (line 67) +* CDLaTeX: CDLaTeX mode. (line 6) +* cdlatex.el: Cooperation. (line 19) +* center blocks: Paragraphs. (line 31) +* center image (LaTeX export): Images in LaTeX export. + (line 46) +* checkbox blocking: Checkboxes. (line 46) +* checkbox statistics: Checkboxes. (line 30) +* checkboxes: Checkboxes. (line 6) +* checkboxes and TODO dependencies: TODO dependencies. (line 51) +* children, subtree visibility state: Global and local cycling. + (line 10) +* clean outline view: Clean view. (line 6) +* clocking time: Clocking work time. (line 6) +* clocktable, dynamic block: The clock table. (line 6) +* code block, batch execution: Batch execution. (line 6) +* code block, editing: Editing source code. (line 6) +* code block, evaluating: Evaluating code blocks. + (line 6) +* code block, exporting: Exporting code blocks. + (line 6) +* code block, extracting source code: Extracting source code. + (line 6) +* code block, header arguments: Header arguments. (line 6) +* code block, key bindings: Key bindings and useful functions. + (line 6) +* code block, languages: Languages. (line 6) +* code block, library: Library of Babel. (line 6) +* code block, noweb reference: Noweb reference syntax. + (line 6) +* code block, results of evaluation: Results of evaluation. + (line 6) +* code block, structure: Structure of code blocks. + (line 6) +* code line references, markup rules: Literal examples. (line 6) +* code text, markup rules: Emphasis and monospace. + (line 6) +* column formula: Column formulas. (line 6) +* column view, for properties: Defining columns. (line 6) +* column view, in agenda: Agenda column view. (line 6) +* column, of field coordinates: References. (line 86) +* commands, in agenda buffer: Agenda commands. (line 6) +* comment lines: Comment lines. (line 6) +* comment trees: Comment lines. (line 13) +* commented entries, in agenda views: Agenda views. (line 32) +* completion, of dictionary words: Completion. (line 6) +* completion, of file names: Handling links. (line 87) +* completion, of link abbreviations: Completion. (line 6) +* completion, of links: Handling links. (line 65) +* completion, of option keywords: Per-file keywords. (line 23) +* completion, of option keywords <1>: Completion. (line 6) +* completion, of property keys: Completion. (line 6) +* completion, of tags: Setting tags. (line 11) +* completion, of tags <1>: Completion. (line 6) +* completion, of TeX symbols: Completion. (line 6) +* completion, of TODO keywords: Workflow states. (line 15) +* completion, of TODO keywords <1>: Completion. (line 6) +* concept index, in Texinfo export: Indices. (line 6) +* constants, in calculations: References. (line 108) +* constants, in calculations <1>: References. (line 129) +* constants.el: Cooperation. (line 11) +* constcgs, STARTUP keyword: In-buffer settings. (line 136) +* constSI, STARTUP keyword: In-buffer settings. (line 136) +* content, STARTUP keyword: Initial visibility. (line 6) +* content, STARTUP keyword <1>: In-buffer settings. (line 65) +* contents, global visibility state: Global and local cycling. + (line 18) +* context-sensitive commands, hooks: Context-sensitive commands. + (line 6) +* continuous clocking: Resolving idle time. (line 74) +* convert: Configuring a document converter. + (line 6) +* converter: Configuring a document converter. + (line 6) +* coordinates, of field: References. (line 86) +* copying notes: Refile and copy. (line 6) +* copying, of subtrees: Structure editing. (line 6) +* countdown timer: Timers. (line 6) +* counter, macro: Macro replacement. (line 55) +* creating timestamps: Creating timestamps. (line 6) +* CSS, for HTML export: CSS support. (line 6) +* CUA.el: Conflicts. (line 18) +* custom agenda views: Custom agenda views. (line 6) +* custom date/time format: Custom time format. (line 6) +* custom search strings: Custom searches. (line 6) +* customization: Customization. (line 6) +* customtime, STARTUP keyword: In-buffer settings. (line 132) +* cutting, of subtrees: Structure editing. (line 6) +* cycling, in plain lists: Plain lists. (line 67) +* cycling, of agenda files: Agenda files. (line 21) +* cycling, of TODO states: TODO basics. (line 14) +* cycling, visibility: Visibility cycling. (line 6) +* daily agenda: Weekly/daily agenda. (line 6) +* dash, special symbol: Special symbols. (line 39) +* data type index, in Texinfo export: Indices. (line 6) +* date format, custom: Custom time format. (line 6) +* date range: Timestamps. (line 42) +* date stamp: Dates and times. (line 6) +* date stamps: Timestamps. (line 6) +* date tree: Using capture. (line 9) +* date, macro: Macro replacement. (line 29) +* date, reading in minibuffer: The date/time prompt. + (line 6) +* dates: Dates and times. (line 6) +* Davison, Dan: Working with source code. + (line 6) +* DEADLINE keyword: Deadlines and scheduling. + (line 11) +* deadlines: Timestamps. (line 6) +* debugging, of table formulas: Editing and debugging formulas. + (line 117) +* defining new protocols: Protocols. (line 25) +* demotion, of subtrees: Structure editing. (line 6) +* dependencies, of TODO states: TODO dependencies. (line 6) +* diary entries, creating from agenda: Agenda commands. (line 385) +* diary integration: Weekly/daily agenda. (line 32) +* dictionary word completion: Completion. (line 6) +* dir file, in Texinfo export: Info directory file. (line 6) +* directories, for publishing: Sources and destinations. + (line 6) +* dispatching agenda commands: Agenda dispatcher. (line 6) +* display changing, in agenda: Agenda commands. (line 61) +* doc, docx, rtf: Configuring a document converter. + (line 6) +* document structure: Document structure. (line 6) +* document title: Export settings. (line 60) +* Dominik, Carsten: Cooperation. (line 11) +* Dominik, Carsten <1>: Cooperation. (line 19) +* DONE, final TODO keyword: Per-file keywords. (line 26) +* dragging, agenda lines: Agenda commands. (line 297) +* drawer, for properties: Property syntax. (line 6) +* drawer, for state change recording: Tracking TODO state changes. + (line 6) +* drawers: Drawers. (line 6) +* Duration, computing: Durations and time values. + (line 6) +* dvipng: Math formatting in HTML export. + (line 6) +* dvipng <1>: Working with LaTeX math snippets. + (line 48) +* dvisvgm: Math formatting in HTML export. + (line 6) +* dvisvgm <1>: Working with LaTeX math snippets. + (line 48) +* dynamic blocks: Dynamic blocks. (line 6) +* dynamic indentation: Clean view. (line 6) +* ecomplete.el: Conflicts. (line 33) +* editing tables: Tables. (line 6) +* editing, of table formulas: Editing and debugging formulas. + (line 6) +* edits, catching invisible: Catching invisible edits. + (line 6) +* effort estimates: Effort estimates. (line 6) +* effort filtering, in agenda: Filtering/limiting agenda items. + (line 17) +* Elisp links: External links. (line 6) +* ellipsis, special symbol: Special symbols. (line 39) +* ELPA: Activation. (line 6) +* email, macro: Macro replacement. (line 24) +* embedding images in ODT: Images in ODT export. + (line 6) +* entitiesplain, STARTUP keyword: In-buffer settings. (line 159) +* entitiespretty, STARTUP keyword: Special symbols. (line 34) +* entitiespretty, STARTUP keyword <1>: In-buffer settings. (line 159) +* escaping characters: Special symbols. (line 27) +* evaluate time range: Creating timestamps. (line 52) +* even, STARTUP keyword: In-buffer settings. (line 122) +* example blocks, in LaTeX export: Example blocks in LaTeX export. + (line 6) +* export back-end: Exporting. (line 12) +* export back-ends, built-in: Other built-in back-ends. + (line 6) +* Export, dispatcher: The export dispatcher. + (line 6) +* export, OpenDocument: OpenDocument Text export. + (line 6) +* Export, settings: Export settings. (line 6) +* Export, writing back-ends: Adding export back-ends. + (line 6) +* exporting: Exporting. (line 6) +* exporting agenda views: Agenda commands. (line 426) +* exporting agenda views <1>: Exporting agenda views. + (line 13) +* exporting, not: Comment lines. (line 6) +* extended TODO keywords: TODO extensions. (line 6) +* external archiving: Moving subtrees. (line 6) +* external links: External links. (line 6) +* external links, in HTML export: Links in HTML export. + (line 6) +* faces, for TODO keywords: Faces for TODO keywords. + (line 6) +* FAQ: Summary. (line 49) +* feedback: Feedback. (line 6) +* field coordinates: References. (line 86) +* field formula: Field and range formulas. + (line 6) +* field references: References. (line 15) +* file links: External links. (line 6) +* file links, searching: Search options. (line 6) +* file name completion: Handling links. (line 87) +* files for agenda: Agenda files. (line 6) +* files, adding to agenda list: Agenda files. (line 15) +* files, selecting for publishing: Selecting files. (line 6) +* filladapt.el: Conflicts. (line 45) +* filtering, by tag, category, top headline and effort, in agenda: Filtering/limiting agenda items. + (line 17) +* Filters, exporting: Advanced configuration. + (line 32) +* fnadjust, STARTUP keyword: In-buffer settings. (line 142) +* fnauto, STARTUP keyword: In-buffer settings. (line 142) +* fnconfirm, STARTUP keyword: In-buffer settings. (line 142) +* fninline, STARTUP keyword: In-buffer settings. (line 142) +* fnlocal, STARTUP keyword: In-buffer settings. (line 142) +* fnplain, STARTUP keyword: In-buffer settings. (line 142) +* fnprompt, STARTUP keyword: In-buffer settings. (line 142) +* folded, subtree visibility state: Global and local cycling. + (line 10) +* folding, sparse trees: Sparse trees. (line 6) +* following links: Handling links. (line 98) +* footnotes: Footnotes. (line 6) +* format specifier: Formula syntax for Calc. + (line 14) +* format, of links: Link format. (line 6) +* formatting source code, markup rules: Literal examples. (line 23) +* formula debugging: Editing and debugging formulas. + (line 117) +* formula editing: Editing and debugging formulas. + (line 6) +* formula syntax, Calc: Formula syntax for Calc. + (line 6) +* formula, for individual table field: Field and range formulas. + (line 6) +* formula, for range of fields: Field and range formulas. + (line 6) +* formula, for table column: Column formulas. (line 6) +* formula, in tables: Built-in table editor. + (line 145) +* function index, in Texinfo export: Indices. (line 6) +* Gillespie, Dave: Cooperation. (line 6) +* global cycling: Global and local cycling. + (line 18) +* global key bindings: Activation. (line 6) +* global TODO list: Global TODO list. (line 6) +* global visibility states: Global and local cycling. + (line 18) +* Gnus links: External links. (line 6) +* graph, in tables: Org-Plot. (line 6) +* group tags: Tag hierarchy. (line 6) +* group tags, as regular expressions: Matching tags and properties. + (line 60) +* grouping columns in tables: Column groups. (line 6) +* habits: Tracking your habits. + (line 6) +* hacking: Hacking. (line 6) +* handle rewritten URL in open-source protocol: open-source protocol. + (line 32) +* header, for LaTeX files: LaTeX header and sectioning. + (line 6) +* headline navigation: Motion. (line 6) +* headline tagging: Tags. (line 6) +* headline, promotion and demotion: Structure editing. (line 6) +* headlines: Headlines. (line 6) +* hide text: Visibility cycling. (line 6) +* hideblocks, STARTUP keyword: Blocks. (line 13) +* hideblocks, STARTUP keyword <1>: In-buffer settings. (line 154) +* hidestars, STARTUP keyword: In-buffer settings. (line 122) +* hiding leading stars: Clean view. (line 6) +* history: History and acknowledgments. + (line 6) +* hooks: Hooks. (line 6) +* horizontal rules, in ASCII export: ASCII/Latin-1/UTF-8 export. + (line 67) +* horizontal rules, in LaTeX export: Horizontal rules in LaTeX export. + (line 6) +* horizontal rules, markup rules: Horizontal rules. (line 6) +* HTML entities: Special symbols. (line 6) +* HTML export: HTML export. (line 6) +* HTML export, CSS: CSS support. (line 6) +* HTML, and Orgtbl mode: Translator functions. + (line 6) +* HTML5, export new elements: HTML doctypes. (line 25) +* hyperlinks: Hyperlinks. (line 6) +* hyperlinks, adding new types: Adding hyperlink types. + (line 6) +* iCalendar export: iCalendar export. (line 6) +* identify, ImageMagick: Images in ODT export. + (line 34) +* idle, resolve, dangling: Resolving idle time. (line 9) +* image, centering (LaTeX export): Images in LaTeX export. + (line 46) +* imagemagick: Math formatting in HTML export. + (line 6) +* imagemagick <1>: Working with LaTeX math snippets. + (line 48) +* images, embedding in ODT: Images in ODT export. + (line 6) +* images, inline in HTML: Images in HTML export. + (line 6) +* images, inline in LaTeX: Images in LaTeX export. + (line 6) +* images, inlining: Handling links. (line 129) +* imenu.el: Cooperation. (line 22) +* in-buffer settings: In-buffer settings. (line 6) +* inactive timestamp: Timestamps. (line 50) +* include files, during export: Include files. (line 6) +* indent, STARTUP keyword: In-buffer settings. (line 70) +* indentation, in source blocks: Literal examples. (line 72) +* indentation, in source blocks <1>: Editing source code. (line 36) +* index, in a publishing project: Generating an index. (line 6) +* Info directory file, in Texinfo export: Info directory file. + (line 6) +* Info links: External links. (line 6) +* inheritance, of properties: Property inheritance. + (line 6) +* inheritance, of tags: Tag inheritance. (line 6) +* inline, in LaTeX export: Quoting LaTeX code. (line 10) +* inlined images, markup rules: Images and tables. (line 22) +* inlineimages, STARTUP keyword: Handling links. (line 129) +* inlineimages, STARTUP keyword <1>: In-buffer settings. (line 84) +* inlining images: Handling links. (line 129) +* inlining images in HTML: Images in HTML export. + (line 6) +* inlining images in LaTeX: Images in LaTeX export. + (line 6) +* input file, macro: Macro replacement. (line 44) +* inserting links: Handling links. (line 65) +* insertion, of templates: Easy templates. (line 6) +* install-info parameters, in Texinfo export: Info directory file. + (line 6) +* installation: Installation. (line 6) +* Installing Org protocol: Protocols. (line 14) +* internal links: Internal links. (line 6) +* internal links, in HTML export: Links in HTML export. + (line 6) +* introduction: Introduction. (line 6) +* iPhone: MobileOrg. (line 6) +* IRC links: External links. (line 6) +* italic text, markup rules: Emphasis and monospace. + (line 6) +* jumping, to headlines: Motion. (line 6) +* key bindings, global: Activation. (line 6) +* keystroke index, in Texinfo export: Indices. (line 6) +* keyword options: Per-file keywords. (line 6) +* LaTeX class: LaTeX header and sectioning. + (line 6) +* LaTeX entities: Special symbols. (line 6) +* LaTeX export: LaTeX export. (line 6) +* LaTeX fragments: LaTeX fragments. (line 6) +* LaTeX fragments, preview: Previewing LaTeX fragments. + (line 6) +* LaTeX header: LaTeX header and sectioning. + (line 6) +* LaTeX interpretation: Embedded LaTeX. (line 6) +* LaTeX sectioning structure: LaTeX header and sectioning. + (line 6) +* LaTeX, and Orgtbl mode: A LaTeX example. (line 6) +* latexpreview, STARTUP keyword: In-buffer settings. (line 90) +* Latin-1 export: ASCII/Latin-1/UTF-8 export. + (line 6) +* level, require for tags/property match: Matching tags and properties. + (line 67) +* LibreOffice: OpenDocument Text export. + (line 6) +* LibreOffice <1>: Extending ODT export. + (line 12) +* limits, in agenda: Filtering/limiting agenda items. + (line 118) +* link abbreviations: Link abbreviations. (line 6) +* link abbreviations, completion of: Completion. (line 6) +* link completion: Handling links. (line 65) +* link format: Link format. (line 6) +* links, external: External links. (line 6) +* links, finding next/previous: Handling links. (line 146) +* links, handling: Handling links. (line 6) +* links, in HTML export: Links in HTML export. + (line 6) +* links, in ODT export: Links in ODT export. (line 6) +* links, internal: Internal links. (line 6) +* links, publishing: Publishing links. (line 6) +* links, radio targets: Radio targets. (line 6) +* links, returning to: Handling links. (line 140) +* linter: Org syntax. (line 24) +* Lisp forms, as table formulas: Formula syntax for Lisp. + (line 6) +* list of listings: Table of contents. (line 6) +* list of tables: Table of contents. (line 6) +* lists, in other modes: Tables in arbitrary syntax. + (line 6) +* lists, ordered: Plain lists. (line 6) +* lists, plain: Plain lists. (line 6) +* literal examples, markup rules: Literal examples. (line 6) +* logdone, STARTUP keyword: In-buffer settings. (line 96) +* logdrawer, STARTUP keyword: In-buffer settings. (line 96) +* logging, of progress: Progress logging. (line 6) +* lognoteclock-out, STARTUP keyword: In-buffer settings. (line 96) +* lognotedone, STARTUP keyword: In-buffer settings. (line 96) +* lognoteredeadline, STARTUP keyword: In-buffer settings. (line 96) +* lognoterefile, STARTUP keyword: In-buffer settings. (line 96) +* lognoterepeat, STARTUP keyword: In-buffer settings. (line 96) +* lognotereschedule, STARTUP keyword: In-buffer settings. (line 96) +* logredeadline, STARTUP keyword: In-buffer settings. (line 96) +* logrefile, STARTUP keyword: In-buffer settings. (line 96) +* logrepeat, STARTUP keyword: In-buffer settings. (line 96) +* logreschedule, STARTUP keyword: In-buffer settings. (line 96) +* logstatesreversed, STARTUP keyword: In-buffer settings. (line 96) +* lookup functions in tables: Lookup functions. (line 6) +* Ludlam, Eric M.: Cooperation. (line 30) +* macro replacement, during export: Macro replacement. (line 6) +* maintainer: Feedback. (line 6) +* mapping entries, API: Using the mapping API. + (line 6) +* mark ring: Handling links. (line 137) +* Markdown export: Markdown export. (line 6) +* marking characters, tables: Advanced features. (line 39) +* match view: Matching tags and properties. + (line 6) +* matching, of properties: Matching tags and properties. + (line 6) +* matching, of tags: Matching tags and properties. + (line 6) +* matching, tags: Tags. (line 6) +* math symbols: Special symbols. (line 6) +* MathJax: Math formatting in HTML export. + (line 6) +* MathML: Working with LaTeX math snippets. + (line 9) +* MH-E links: External links. (line 6) +* minor mode for structure editing: Orgstruct mode. (line 6) +* minor mode for tables: Orgtbl mode. (line 6) +* MobileOrg: MobileOrg. (line 6) +* mode, for calc: Formula syntax for Calc. + (line 14) +* modification time, macro: Macro replacement. (line 36) +* motion commands in agenda: Agenda commands. (line 19) +* motion, between headlines: Motion. (line 6) +* Multiple entries in two-column tables, in Texinfo export: Plain lists in Texinfo export. + (line 17) +* n, macro: Macro replacement. (line 55) +* name, of column or field: References. (line 108) +* name, of column or field <1>: References. (line 129) +* named references: References. (line 108) +* names as TODO keywords: TODO types. (line 6) +* narrow columns in tables: Column width and alignment. + (line 6) +* noalign, STARTUP keyword: In-buffer settings. (line 79) +* nofnadjust, STARTUP keyword: In-buffer settings. (line 142) +* nofninline, STARTUP keyword: In-buffer settings. (line 142) +* nohideblocks, STARTUP keyword: Blocks. (line 13) +* nohideblocks, STARTUP keyword <1>: In-buffer settings. (line 154) +* noindent, STARTUP keyword: In-buffer settings. (line 70) +* noinlineimages, STARTUP keyword: Handling links. (line 129) +* noinlineimages, STARTUP keyword <1>: In-buffer settings. (line 84) +* nolatexpreview, STARTUP keyword: In-buffer settings. (line 90) +* nologdone, STARTUP keyword: In-buffer settings. (line 96) +* nologdrawer, STARTUP keyword: In-buffer settings. (line 96) +* nolognoteclock-out, STARTUP keyword: In-buffer settings. (line 96) +* nologredeadline, STARTUP keyword: In-buffer settings. (line 96) +* nologrefile, STARTUP keyword: In-buffer settings. (line 96) +* nologrepeat, STARTUP keyword: In-buffer settings. (line 96) +* nologreschedule, STARTUP keyword: In-buffer settings. (line 96) +* nologstatesreversed, STARTUP keyword: In-buffer settings. (line 96) +* occur, command: Sparse trees. (line 6) +* occur-tree: Storing searches. (line 9) +* odd, STARTUP keyword: In-buffer settings. (line 122) +* odd-levels-only outlines: Clean view. (line 6) +* ODT: OpenDocument Text export. + (line 6) +* ODT_STYLES_FILE: ODT specific export settings. + (line 22) +* open-source protocol: open-source protocol. + (line 6) +* OpenDocument: OpenDocument Text export. + (line 6) +* option keyword completion: Completion. (line 6) +* options, for custom agenda views: Setting options. (line 6) +* options, for customization: Customization. (line 6) +* options, for publishing: Publishing options. (line 6) +* ordered lists: Plain lists. (line 6) +* Org entities: Special symbols. (line 6) +* Org export: Org export. (line 6) +* Org mode, turning on: Activation. (line 21) +* Org protocol, set-up: Protocols. (line 14) +* Org syntax: Org syntax. (line 6) +* org-agenda, command: Weekly/daily agenda. (line 9) +* org-capture-last-stored: Using capture. (line 48) +* org-crypt.el: org-crypt. (line 6) +* org-decrypt-entry: org-crypt. (line 6) +* org-hide-block-startup: In-buffer settings. (line 153) +* org-insert-drawer: Drawers. (line 6) +* org-insert-drawer <1>: Property syntax. (line 87) +* org-list-insert-radio-list: Radio lists. (line 6) +* org-pretty-entities: In-buffer settings. (line 158) +* org-publish-project-alist: Project alist. (line 6) +* Orgstruct mode: Orgstruct mode. (line 6) +* Orgtbl mode: Orgtbl mode. (line 6) +* Orgtbl mode <1>: Tables in arbitrary syntax. + (line 6) +* Ota, Takaaki: Cooperation. (line 36) +* Outline mode: Outlines. (line 6) +* outline tree: Headlines. (line 6) +* outlines: Outlines. (line 6) +* overview, global visibility state: Global and local cycling. + (line 18) +* overview, STARTUP keyword: Initial visibility. (line 6) +* overview, STARTUP keyword <1>: In-buffer settings. (line 65) +* packages, interaction with other: Interaction. (line 6) +* paragraphs, markup rules: Paragraphs. (line 6) +* pasting, of subtrees: Structure editing. (line 6) +* PDF export: LaTeX export. (line 6) +* per-file keywords: Per-file keywords. (line 6) +* plain lists: Plain lists. (line 6) +* plain lists, in LaTeX export: Plain lists in LaTeX export. + (line 6) +* plain text external links: External links. (line 68) +* plot tables using Gnuplot: Org-Plot. (line 6) +* presentation, of agenda items: Presentation and sorting. + (line 6) +* print edition: Summary. (line 52) +* printing sparse trees: Sparse trees. (line 49) +* priorities: Priorities. (line 6) +* priorities, of agenda items: Sorting agenda items. + (line 6) +* program index, in Texinfo export: Indices. (line 6) +* progress logging: Progress logging. (line 6) +* projects, for publishing: Project alist. (line 6) +* promotion, of subtrees: Structure editing. (line 6) +* proof, in LaTeX export: Special blocks in LaTeX export. + (line 6) +* properties: Properties and columns. + (line 6) +* properties, API: Property API. (line 6) +* properties, API <1>: Using the property API. + (line 6) +* properties, column view: Defining columns. (line 6) +* properties, inheritance: Property inheritance. + (line 6) +* properties, searching: Property searches. (line 6) +* properties, special: Special properties. (line 6) +* property syntax: Property syntax. (line 6) +* property, +: Property syntax. (line 52) +* property, + <1>: Property syntax. (line 58) +* property, ALT_TITLE: Table of contents. (line 41) +* property, APPENDIX: Headings and sectioning structure. + (line 20) +* property, ARCHIVE: Property inheritance. + (line 32) +* property, ARCHIVE <1>: Moving subtrees. (line 35) +* property, ATTACH_DIR: Attachments. (line 74) +* property, ATTACH_DIR_INHERIT: Attachments. (line 79) +* property, BEAMER_ACT: Sectioning Frames and Blocks in Beamer. + (line 41) +* property, BEAMER_COL: Sectioning Frames and Blocks in Beamer. + (line 49) +* property, BEAMER_ENV: Sectioning Frames and Blocks in Beamer. + (line 14) +* property, BEAMER_OPT: Sectioning Frames and Blocks in Beamer. + (line 41) +* property, BEAMER_REF: Sectioning Frames and Blocks in Beamer. + (line 27) +* property, CATEGORY: Property inheritance. + (line 29) +* property, CATEGORY <1>: Categories. (line 12) +* property, CLOCK_MODELINE_TOTAL: Clocking commands. (line 20) +* property, COLUMNS: Property inheritance. + (line 22) +* property, COLUMNS <1>: In-buffer settings. (line 24) +* property, COOKIE_DATA: Breaking down tasks. (line 21) +* property, COOKIE_DATA <1>: Checkboxes. (line 30) +* property, COPYING: Texinfo title and copyright page. + (line 19) +* property, CUSTOM_ID: Internal links. (line 6) +* property, CUSTOM_ID <1>: Handling links. (line 21) +* property, DESCRIPTION: Headings and sectioning structure. + (line 24) +* property, DESCRIPTION <1>: iCalendar export. (line 49) +* property, EFFORT: Effort estimates. (line 6) +* property, EXPORT_FILE_NAME: ODT export commands. (line 7) +* property, EXPORT_LATEX_CLASS: LaTeX header and sectioning. + (line 23) +* property, EXPORT_LATEX_CLASS_OPTIONS: LaTeX header and sectioning. + (line 23) +* property, ID: Handling links. (line 21) +* property, ID <1>: Capturing column view. + (line 22) +* property, ID <2>: iCalendar export. (line 26) +* property, INDEX: Indices. (line 14) +* property, LAST_REPEAT: Clocking commands. (line 20) +* property, LOCATION: iCalendar export. (line 49) +* property, LOGGING: Tracking TODO state changes. + (line 45) +* property, LOGGING <1>: Property inheritance. + (line 35) +* property, LOG_INTO_DRAWER: Tracking TODO state changes. + (line 6) +* property, LOG_INTO_DRAWER <1>: Clocking commands. (line 7) +* property, macro: Macro replacement. (line 48) +* property, ORDERED: TODO dependencies. (line 6) +* property, ORDERED <1>: TODO dependencies. (line 38) +* property, ORDERED <2>: Checkboxes. (line 46) +* property, ORDERED <3>: Checkboxes. (line 75) +* property, special, ALLTAGS: Special properties. (line 13) +* property, special, BLOCKED: Special properties. (line 13) +* property, special, CLOCKSUM: Special properties. (line 13) +* property, special, CLOCKSUM <1>: Agenda column view. (line 28) +* property, special, CLOCKSUM_T: Special properties. (line 13) +* property, special, CLOCKSUM_T <1>: Agenda column view. (line 51) +* property, special, CLOSED: Special properties. (line 13) +* property, special, DEADLINE: Special properties. (line 13) +* property, special, FILE: Special properties. (line 13) +* property, special, ITEM: Special properties. (line 13) +* property, special, PRIORITY: Special properties. (line 13) +* property, special, SCHEDULED: Special properties. (line 13) +* property, special, TAGS: Special properties. (line 13) +* property, special, TIMESTAMP: Special properties. (line 13) +* property, special, TIMESTAMP_IA: Special properties. (line 13) +* property, special, TODO: Special properties. (line 13) +* property, SUMMARY: iCalendar export. (line 49) +* property, TIMEZONE: iCalendar export. (line 49) +* property, UNNUMBERED: Export settings. (line 149) +* property, VISIBILITY: Initial visibility. (line 17) +* property, _ALL: Property syntax. (line 44) +* protocol, capture: capture protocol. (line 6) +* protocol, new protocol: Protocols. (line 25) +* protocol, open-source: open-source protocol. + (line 6) +* protocol, open-source rewritten URL: open-source protocol. + (line 32) +* protocol, open-source, :base-url property: open-source protocol. + (line 13) +* protocol, open-source, :online-suffix property: open-source protocol. + (line 13) +* protocol, open-source, :rewrites property: open-source protocol. + (line 43) +* protocol, open-source, :working-directory property: open-source protocol. + (line 13) +* protocol, open-source, :working-suffix property: open-source protocol. + (line 13) +* protocol, open-source, set-up mapping: open-source protocol. + (line 67) +* protocol, store-link: store-link protocol. (line 6) +* protocols, for external access: Protocols. (line 6) +* publishing: Publishing. (line 6) +* query editing, in agenda: Filtering/limiting agenda items. + (line 17) +* quote blocks: Paragraphs. (line 26) +* radio lists: Radio lists. (line 6) +* radio tables: Radio tables. (line 6) +* radio targets: Radio targets. (line 6) +* range formula: Field and range formulas. + (line 6) +* range references: References. (line 63) +* ranges, time: Timestamps. (line 6) +* recomputing table fields: Updating the table. (line 6) +* references: References. (line 6) +* references, named: References. (line 108) +* references, remote: References. (line 129) +* references, to a different table: References. (line 129) +* references, to fields: References. (line 15) +* references, to ranges: References. (line 63) +* refiling notes: Refile and copy. (line 6) +* region, active: Structure editing. (line 116) +* region, active <1>: Built-in table editor. + (line 145) +* region, active <2>: ODT export commands. (line 6) +* regular expressions, with tags search: Matching tags and properties. + (line 56) +* relative timer: Timers. (line 6) +* reminders: Weekly/daily agenda. (line 126) +* remote editing, bulk, from agenda: Agenda commands. (line 308) +* remote editing, from agenda: Agenda commands. (line 200) +* remote editing, undo: Agenda commands. (line 201) +* remote references: References. (line 129) +* repeated tasks: Repeated tasks. (line 6) +* report, of clocked time: The clock table. (line 6) +* resolve idle time: Resolving idle time. (line 9) +* revealing context: Global and local cycling. + (line 37) +* RMAIL links: External links. (line 6) +* Rose, Sebastian: JavaScript support. (line 6) +* row, of field coordinates: References. (line 86) +* RSS feeds: RSS feeds. (line 6) +* rsync: Uploading files. (line 6) +* SCHEDULED keyword: Deadlines and scheduling. + (line 32) +* scheduling: Timestamps. (line 6) +* Schulte, Eric: Working with source code. + (line 6) +* Scripts, for agenda processing: Extracting agenda information. + (line 6) +* search option in file links: Search options. (line 6) +* search strings, custom: Custom searches. (line 6) +* search view: Search view. (line 6) +* searching for tags: Tag searches. (line 6) +* searching, for text: Search view. (line 6) +* searching, of properties: Property searches. (line 6) +* sectioning structure, for LaTeX export: LaTeX header and sectioning. + (line 6) +* set startup visibility, command: Global and local cycling. + (line 33) +* set-up mappings in open-source protocol: open-source protocol. + (line 67) +* setting tags: Setting tags. (line 6) +* SHELL links: External links. (line 6) +* shift-selection-mode: Plain lists. (line 90) +* shift-selection-mode <1>: Conflicts. (line 6) +* show all, command: Global and local cycling. + (line 35) +* show all, global visibility state: Global and local cycling. + (line 18) +* show branches, command: Global and local cycling. + (line 45) +* show children, command: Global and local cycling. + (line 48) +* show hidden text: Visibility cycling. (line 6) +* showall, STARTUP keyword: Initial visibility. (line 6) +* showall, STARTUP keyword <1>: In-buffer settings. (line 65) +* showeverything, STARTUP keyword: Initial visibility. (line 6) +* showeverything, STARTUP keyword <1>: In-buffer settings. (line 65) +* showstars, STARTUP keyword: In-buffer settings. (line 122) +* shy hyphen, special symbol: Special symbols. (line 39) +* sitemap, of published pages: Sitemap. (line 6) +* sorting, of agenda items: Sorting agenda items. + (line 6) +* sorting, of plain list: Plain lists. (line 142) +* sorting, of subtrees: Structure editing. (line 6) +* source blocks, in LaTeX export: Source blocks in LaTeX export. + (line 6) +* source code, batch execution: Batch execution. (line 6) +* source code, block header arguments: Header arguments. (line 6) +* source code, block structure: Structure of code blocks. + (line 6) +* source code, editing: Editing source code. (line 6) +* source code, evaluating: Evaluating code blocks. + (line 6) +* source code, exporting: Exporting code blocks. + (line 6) +* source code, extracting: Extracting source code. + (line 6) +* source code, inline: Structure of code blocks. + (line 24) +* source code, language: Structure of code blocks. + (line 48) +* source code, languages: Languages. (line 6) +* source code, library: Library of Babel. (line 6) +* source code, noweb reference: Noweb reference syntax. + (line 6) +* source code, results of evaluation: Results of evaluation. + (line 6) +* source code, switches: Structure of code blocks. + (line 52) +* source code, working with: Working with source code. + (line 6) +* sparse tree, for deadlines: Inserting deadline/schedule. + (line 23) +* sparse tree, for TODO: TODO basics. (line 41) +* sparse tree, tag based: Tags. (line 6) +* sparse trees: Sparse trees. (line 6) +* special blocks, in ASCII export: ASCII/Latin-1/UTF-8 export. + (line 77) +* special blocks, in LaTeX export: Special blocks in LaTeX export. + (line 6) +* special keywords: In-buffer settings. (line 6) +* special symbols: Special symbols. (line 6) +* special symbols, in-buffer display: Special symbols. (line 31) +* speed keys: Speed keys. (line 6) +* speedbar.el: Cooperation. (line 30) +* spreadsheet capabilities: The spreadsheet. (line 6) +* square brackets, around links: External links. (line 68) +* statistics, for checkboxes: Checkboxes. (line 30) +* statistics, for TODO items: Breaking down tasks. (line 6) +* store-link protocol: store-link protocol. (line 6) +* storing links: Handling links. (line 10) +* Storm, Kim. F.: Conflicts. (line 18) +* strike-through text, markup rules: Emphasis and monospace. + (line 6) +* structure editing: Structure editing. (line 6) +* structure of document: Document structure. (line 6) +* styles, custom: Applying custom styles. + (line 6) +* styles, custom <1>: Working with OpenDocument style files. + (line 6) +* sublevels, inclusion into tags match: Tag inheritance. (line 6) +* sublevels, inclusion into TODO list: Global TODO list. (line 34) +* subscript: Subscripts and superscripts. + (line 6) +* SUBTITLE (ODT): ODT specific export settings. + (line 26) +* subtree cycling: Global and local cycling. + (line 10) +* subtree visibility states: Global and local cycling. + (line 10) +* subtree, cut and paste: Structure editing. (line 6) +* subtree, subtree visibility state: Global and local cycling. + (line 10) +* subtrees, cut and paste: Structure editing. (line 6) +* summary: Summary. (line 6) +* superscript: Subscripts and superscripts. + (line 6) +* syntax checker: Org syntax. (line 24) +* syntax, noweb: Noweb reference syntax. + (line 6) +* syntax, of formulas: Formula syntax for Calc. + (line 6) +* table editor, built-in: Built-in table editor. + (line 6) +* table editor, table.el: Cooperation. (line 36) +* table lookup functions: Lookup functions. (line 6) +* table of contents: Table of contents. (line 6) +* table.el: Cooperation. (line 34) +* table.el <1>: Cooperation. (line 36) +* tables: Tables. (line 6) +* tables, in HTML: Tables in HTML export. + (line 6) +* tables, in LaTeX export: Tables in LaTeX export. + (line 6) +* tables, in ODT export: Tables in ODT export. + (line 6) +* tables, in ODT export <1>: Customizing tables in ODT export. + (line 6) +* tables, in other modes: Tables in arbitrary syntax. + (line 6) +* tables, markup rules: Images and tables. (line 6) +* tag completion: Completion. (line 6) +* tag filtering, in agenda: Filtering/limiting agenda items. + (line 17) +* tag hierarchy: Tag hierarchy. (line 6) +* tag inheritance: Tag inheritance. (line 6) +* tag searches: Tag searches. (line 6) +* tags: Tags. (line 6) +* tags view: Matching tags and properties. + (line 6) +* tags, as an agenda view: Storing searches. (line 9) +* tags, groups: Tag hierarchy. (line 6) +* tags, setting: Setting tags. (line 6) +* tags-todo: Storing searches. (line 9) +* tags-tree: Storing searches. (line 9) +* tangling: Extracting source code. + (line 6) +* targets, for links: Internal links. (line 6) +* targets, radio: Radio targets. (line 6) +* tasks, breaking down: Breaking down tasks. (line 6) +* tasks, repeated: Repeated tasks. (line 6) +* template insertion: Easy templates. (line 6) +* template, custom: Applying custom styles. + (line 6) +* template, custom <1>: Working with OpenDocument style files. + (line 6) +* templates, for Capture: Capture templates. (line 6) +* TeX interpretation: Embedded LaTeX. (line 6) +* TeX symbol completion: Completion. (line 6) +* Texinfo export: Texinfo export. (line 6) +* Texinfo export, data type index: Indices. (line 6) +* Texinfo export, dir file: Info directory file. (line 6) +* Texinfo export, index, concept: Indices. (line 6) +* Texinfo export, index, function: Indices. (line 6) +* Texinfo export, Info directory file: Info directory file. (line 6) +* Texinfo export, install-info parameters: Info directory file. + (line 6) +* Texinfo export, keystroke index: Indices. (line 6) +* Texinfo export, program index: Indices. (line 6) +* Texinfo export, Top node: Headings and sectioning structure. + (line 37) +* Texinfo export, variable index: Indices. (line 6) +* text areas, in HTML: Text areas in HTML export. + (line 6) +* text search: Search view. (line 6) +* thanks: History and acknowledgments. + (line 5) +* The Top node, in Texinfo export: Headings and sectioning structure. + (line 37) +* time clocking: Clocking work time. (line 6) +* time format, custom: Custom time format. (line 6) +* time grid: Time-of-day specifications. + (line 29) +* Time, computing: Durations and time values. + (line 6) +* time, macro: Macro replacement. (line 36) +* time, reading in minibuffer: The date/time prompt. + (line 6) +* time-of-day specification: Time-of-day specifications. + (line 6) +* timerange: Timestamps. (line 42) +* times: Dates and times. (line 6) +* timestamp: Dates and times. (line 6) +* timestamp <1>: Timestamps. (line 14) +* timestamp, inactive: Timestamps. (line 50) +* timestamp, with repeater interval: Timestamps. (line 25) +* timestamps: Timestamps. (line 6) +* timestamps, creating: Creating timestamps. (line 6) +* title, macro: Macro replacement. (line 24) +* TODO dependencies: TODO dependencies. (line 6) +* TODO dependencies, NOBLOCKING: TODO dependencies. (line 6) +* TODO items: TODO items. (line 6) +* TODO keyword matching: Global TODO list. (line 17) +* TODO keyword matching, with tags search: Matching tags and properties. + (line 67) +* TODO keyword sets: Multiple sets in one file. + (line 6) +* TODO keywords completion: Completion. (line 6) +* TODO list, global: Global TODO list. (line 6) +* TODO types: TODO types. (line 6) +* TODO workflow: Workflow states. (line 6) +* todo, as an agenda view: Storing searches. (line 9) +* todo-tree: Storing searches. (line 9) +* top headline filtering, in agenda: Filtering/limiting agenda items. + (line 17) +* transient mark mode: Structure editing. (line 116) +* transient mark mode <1>: Built-in table editor. + (line 145) +* transient-mark-mode: ODT export commands. (line 6) +* translator function: Translator functions. + (line 6) +* trees, sparse: Sparse trees. (line 6) +* trees, visibility: Visibility cycling. (line 6) +* tty key bindings: TTY keys. (line 6) +* Two-column tables, in Texinfo export: Plain lists in Texinfo export. + (line 6) +* types as TODO keywords: TODO types. (line 6) +* underlined text, markup rules: Emphasis and monospace. + (line 6) +* undoing remote-editing events: Agenda commands. (line 201) +* unison: Uploading files. (line 6) +* unoconv: Extending ODT export. + (line 12) +* updating, table: Updating the table. (line 6) +* URL links: External links. (line 6) +* USENET links: External links. (line 6) +* UTF-8 export: ASCII/Latin-1/UTF-8 export. + (line 6) +* variable index, in Texinfo export: Indices. (line 6) +* variables, for customization: Customization. (line 6) +* vectors, in table calculations: Formula syntax for Calc. + (line 11) +* verbatim blocks, in LaTeX export: Example blocks in LaTeX export. + (line 6) +* verbatim text, markup rules: Emphasis and monospace. + (line 6) +* verse blocks: Paragraphs. (line 13) +* viper.el: Conflicts. (line 93) +* visibility cycling: Visibility cycling. (line 6) +* visibility cycling, drawers: Drawers. (line 6) +* visibility, initialize: Initial visibility. (line 6) +* visible text, printing: Sparse trees. (line 49) +* VM links: External links. (line 41) +* WANDERLUST links: External links. (line 41) +* weekly agenda: Weekly/daily agenda. (line 6) +* windmove.el: Conflicts. (line 80) +* workflow states as TODO keywords: Workflow states. (line 6) +* yasnippet.el: Conflicts. (line 54) +* zip: Pre-requisites for ODT export. + (line 6) + + +File: org, Node: Key Index, Next: Command and Function Index, Prev: Main Index, Up: Top + +Key index +********* + +[index] +* Menu: + +* $: Agenda commands. (line 226) +* %: Agenda commands. (line 320) +* ': CDLaTeX mode. (line 38) +* *: Agenda commands. (line 310) +* +: Agenda commands. (line 243) +* ,: Agenda commands. (line 237) +* -: Agenda commands. (line 247) +* .: Agenda commands. (line 90) +* /: Filtering/limiting agenda items. + (line 17) +* / <1>: Agenda commands. (line 176) +* :: Agenda commands. (line 234) +* ;: Timers. (line 6) +* <: Using column view. (line 61) +* < <1>: The date/time prompt. + (line 82) +* < <2>: Agenda files. (line 53) +* < <3>: Filtering/limiting agenda items. + (line 65) +* < <4>: Agenda commands. (line 180) +* =: Filtering/limiting agenda items. + (line 80) +* = <1>: Agenda commands. (line 188) +* >: Using column view. (line 61) +* > <1>: The date/time prompt. + (line 82) +* > <2>: Agenda files. (line 57) +* > <3>: Agenda commands. (line 276) +* ?: Pulling from MobileOrg. + (line 26) +* [: Filtering/limiting agenda items. + (line 56) +* [ <1>: Agenda commands. (line 109) +* ]: Filtering/limiting agenda items. + (line 56) +* ^: Filtering/limiting agenda items. + (line 76) +* ^ <1>: Agenda commands. (line 184) +* ^ <2>: CDLaTeX mode. (line 30) +* _: Filtering/limiting agenda items. + (line 91) +* _ <1>: Agenda commands. (line 191) +* _ <2>: CDLaTeX mode. (line 30) +* `: CDLaTeX mode. (line 35) +* {: Filtering/limiting agenda items. + (line 56) +* |: Filtering/limiting agenda items. + (line 112) +* | <1>: Agenda commands. (line 194) +* }: Filtering/limiting agenda items. + (line 56) +* ~: Filtering/limiting agenda items. + (line 151) +* a: Using column view. (line 51) +* A: Agenda commands. (line 61) +* a <1>: Agenda commands. (line 217) +* b: Agenda commands. (line 88) +* B: Agenda commands. (line 322) +* c: Agenda commands. (line 381) +* c <1>: Agenda commands. (line 382) +* C: Agenda commands. (line 410) +* C-#: Advanced features. (line 10) +* C-': Agenda files. (line 21) +* C-,: Agenda files. (line 21) +* C-0 C-c C-w: Refile and copy. (line 42) +* C-c !: Creating timestamps. (line 15) +* C-c #: Checkboxes. (line 80) +* C-c $: Moving subtrees. (line 9) +* C-c %: Handling links. (line 135) +* C-c &: Handling links. (line 139) +* C-c ': Footnotes. (line 81) +* C-c ' <1>: Editing and debugging formulas. + (line 32) +* C-c ' <2>: Literal examples. (line 87) +* C-c ' <3>: Include files. (line 59) +* C-c ' <4>: Editing source code. (line 6) +* C-c ' <5>: Cooperation. (line 44) +* C-c *: Structure editing. (line 106) +* C-c * <1>: Plain lists. (line 130) +* C-c * <2>: Updating the table. (line 13) +* C-c +: Built-in table editor. + (line 145) +* C-c ,: Priorities. (line 24) +* C-c -: Plain lists. (line 119) +* C-c - <1>: Built-in table editor. + (line 94) +* C-c .: Creating timestamps. (line 10) +* C-c /: Sparse trees. (line 15) +* C-c / <1>: Conflicts. (line 93) +* C-c / /: Sparse trees. (line 17) +* C-c / a: Inserting deadline/schedule. + (line 29) +* C-c / b: Inserting deadline/schedule. + (line 27) +* C-c / d: Inserting deadline/schedule. + (line 21) +* C-c / m: Tag searches. (line 9) +* C-c / m <1>: Property searches. (line 10) +* C-c / p: Property searches. (line 27) +* C-c / r: Sparse trees. (line 17) +* C-c / t: TODO basics. (line 39) +* C-c ;: Comment lines. (line 19) +* C-c <: Creating timestamps. (line 25) +* C-c =: Column formulas. (line 32) +* C-c = <1>: Editing and debugging formulas. + (line 13) +* C-c >: Creating timestamps. (line 28) +* C-c ?: Editing and debugging formulas. + (line 21) +* C-c @: Structure editing. (line 54) +* C-c a: Conventions. (line 33) +* C-c a !: Stuck projects. (line 14) +* C-c a #: Stuck projects. (line 13) +* C-c a ?: Pulling from MobileOrg. + (line 35) +* C-c a a: Weekly/daily agenda. (line 9) +* C-c a C: Storing searches. (line 9) +* C-c a e: Exporting agenda views. + (line 63) +* C-c a m: Tag searches. (line 13) +* C-c a M: Tag searches. (line 16) +* C-c a m <1>: Property searches. (line 12) +* C-c a M <1>: Property searches. (line 15) +* C-c a m <2>: Matching tags and properties. + (line 12) +* C-c a M <2>: Matching tags and properties. + (line 17) +* C-c a s: Search view. (line 9) +* C-c a t: TODO basics. (line 49) +* C-c a t <1>: Global TODO list. (line 9) +* C-c a T: Global TODO list. (line 15) +* C-c c: Conventions. (line 33) +* C-c c <1>: Using capture. (line 6) +* C-c c C: Capture templates. (line 10) +* C-c C-*: Plain lists. (line 134) +* C-c C-a: Attachments. (line 26) +* C-c C-a <1>: Agenda commands. (line 253) +* C-c C-a a: Attachments. (line 31) +* C-c C-a c: Attachments. (line 37) +* C-c C-a d: Attachments. (line 66) +* C-c C-a D: Attachments. (line 69) +* C-c C-a f: Attachments. (line 60) +* C-c C-a F: Attachments. (line 63) +* C-c C-a i: Attachments. (line 78) +* C-c C-a l: Attachments. (line 37) +* C-c C-a m: Attachments. (line 37) +* C-c C-a n: Attachments. (line 44) +* C-c C-a o: Attachments. (line 51) +* C-c C-a O: Attachments. (line 57) +* C-c C-a s: Attachments. (line 73) +* C-c C-a u: Attachments. (line 41) +* C-c C-a z: Attachments. (line 47) +* C-c C-b: Motion. (line 13) +* C-c C-b <1>: Editing support. (line 11) +* C-c C-c: Plain lists. (line 115) +* C-c C-c <1>: Footnotes. (line 71) +* C-c C-c <2>: Built-in table editor. + (line 58) +* C-c C-c <3>: Editing and debugging formulas. + (line 41) +* C-c C-c <4>: Editing and debugging formulas. + (line 77) +* C-c C-c <5>: Editing and debugging formulas. + (line 84) +* C-c C-c <6>: Checkboxes. (line 52) +* C-c C-c <7>: Setting tags. (line 19) +* C-c C-c <8>: Property syntax. (line 89) +* C-c C-c <9>: Using column view. (line 46) +* C-c C-c <10>: Capturing column view. + (line 48) +* C-c C-c <11>: Creating timestamps. (line 23) +* C-c C-c <12>: Clocking commands. (line 48) +* C-c C-c <13>: Clocking commands. (line 48) +* C-c C-c <14>: The clock table. (line 16) +* C-c C-c <15>: Using capture. (line 15) +* C-c C-c <16>: Previewing LaTeX fragments. + (line 23) +* C-c C-c <17>: Evaluating code blocks. + (line 20) +* C-c C-c <18>: Key bindings and useful functions. + (line 11) +* C-c C-c <19>: The very busy C-c C-c key. + (line 6) +* C-c C-c <20>: Cooperation. (line 36) +* C-c C-c c: Property syntax. (line 102) +* C-c C-c d: Property syntax. (line 98) +* C-c C-c D: Property syntax. (line 100) +* C-c C-c s: Property syntax. (line 92) +* C-c C-d: Inserting deadline/schedule. + (line 9) +* C-c C-d <1>: Agenda commands. (line 258) +* C-c C-e: The export dispatcher. + (line 15) +* C-c C-e c a: iCalendar export. (line 40) +* C-c C-e c c: iCalendar export. (line 43) +* C-c C-e c f: iCalendar export. (line 38) +* C-c C-e C-v: Sparse trees. (line 49) +* C-c C-e h h: HTML Export commands. + (line 6) +* C-c C-e h H: HTML Export commands. + (line 11) +* C-c C-e i i: Texinfo export commands. + (line 8) +* C-c C-e i t: Texinfo export commands. + (line 6) +* C-c C-e l b: Beamer export commands. + (line 6) +* C-c C-e l B: Beamer export commands. + (line 8) +* C-c C-e l l: LaTeX export commands. + (line 6) +* C-c C-e l L: LaTeX export commands. + (line 11) +* C-c C-e l P: Beamer export commands. + (line 10) +* C-c C-e l p: LaTeX export commands. + (line 12) +* C-c C-e m m: Markdown export. (line 16) +* C-c C-e m M: Markdown export. (line 18) +* C-c C-e o o: ODT export commands. (line 6) +* C-c C-e O o: Org export. (line 13) +* C-c C-e O O: Org export. (line 17) +* C-c C-e P a: Triggering publication. + (line 14) +* C-c C-e P f: Triggering publication. + (line 12) +* C-c C-e P p: Triggering publication. + (line 10) +* C-c C-e P x: Triggering publication. + (line 8) +* C-c C-e t a/l/u: ASCII/Latin-1/UTF-8 export. + (line 23) +* C-c C-e t A/L/U: ASCII/Latin-1/UTF-8 export. + (line 27) +* C-c C-f: Motion. (line 11) +* C-c C-j: Motion. (line 17) +* C-c C-k: Global and local cycling. + (line 45) +* C-c C-k <1>: Using capture. (line 31) +* C-c C-l: Handling links. (line 64) +* C-c C-n: Motion. (line 8) +* C-c C-o: Footnotes. (line 75) +* C-c C-o <1>: Handling links. (line 98) +* C-c C-o <2>: Creating timestamps. (line 32) +* C-c C-o <3>: Agenda commands. (line 53) +* C-c C-o <4>: Key bindings and useful functions. + (line 11) +* C-c C-p: Motion. (line 9) +* C-c C-q: Editing and debugging formulas. + (line 44) +* C-c C-q <1>: Setting tags. (line 10) +* C-c C-r: Global and local cycling. + (line 37) +* C-c C-r <1>: Editing and debugging formulas. + (line 45) +* C-c C-s: Inserting deadline/schedule. + (line 16) +* C-c C-s <1>: Agenda commands. (line 255) +* C-c C-t: TODO basics. (line 13) +* C-c C-t <1>: Clocking commands. (line 61) +* C-c C-u: Motion. (line 15) +* C-c C-v a: Key bindings and useful functions. + (line 37) +* C-c C-v b: Key bindings and useful functions. + (line 25) +* C-c C-v c: Key bindings and useful functions. + (line 30) +* C-c C-v C-a: Key bindings and useful functions. + (line 37) +* C-c C-v C-b: Key bindings and useful functions. + (line 25) +* C-c C-v C-c: Key bindings and useful functions. + (line 30) +* C-c C-v C-d: Key bindings and useful functions. + (line 27) +* C-c C-v C-e: Key bindings and useful functions. + (line 19) +* C-c C-v C-f: Key bindings and useful functions. + (line 29) +* C-c C-v C-g: Key bindings and useful functions. + (line 23) +* C-c C-v C-h: Key bindings and useful functions. + (line 37) +* C-c C-v C-i: Key bindings and useful functions. + (line 33) +* C-c C-v C-I: Key bindings and useful functions. + (line 34) +* C-c C-v C-j: Key bindings and useful functions. + (line 31) +* C-c C-v C-l: Key bindings and useful functions. + (line 32) +* C-c C-v C-n: Key bindings and useful functions. + (line 18) +* C-c C-v C-o: Key bindings and useful functions. + (line 20) +* C-c C-v C-p: Key bindings and useful functions. + (line 18) +* C-c C-v C-r: Key bindings and useful functions. + (line 24) +* C-c C-v C-s: Key bindings and useful functions. + (line 26) +* C-c C-v C-t: Key bindings and useful functions. + (line 28) +* C-c C-v C-u: Key bindings and useful functions. + (line 22) +* C-c C-v C-v: Key bindings and useful functions. + (line 21) +* C-c C-v C-x: Key bindings and useful functions. + (line 38) +* C-c C-v C-z: Key bindings and useful functions. + (line 35) +* C-c C-v d: Key bindings and useful functions. + (line 27) +* C-c C-v e: Key bindings and useful functions. + (line 19) +* C-c C-v f: Key bindings and useful functions. + (line 29) +* C-c C-v g: Key bindings and useful functions. + (line 23) +* C-c C-v h: Key bindings and useful functions. + (line 37) +* C-c C-v i: Library of Babel. (line 12) +* C-c C-v i <1>: Key bindings and useful functions. + (line 33) +* C-c C-v I: Key bindings and useful functions. + (line 34) +* C-c C-v j: Key bindings and useful functions. + (line 31) +* C-c C-v l: Key bindings and useful functions. + (line 32) +* C-c C-v n: Key bindings and useful functions. + (line 18) +* C-c C-v o: Key bindings and useful functions. + (line 20) +* C-c C-v p: Key bindings and useful functions. + (line 18) +* C-c C-v r: Key bindings and useful functions. + (line 24) +* C-c C-v s: Key bindings and useful functions. + (line 26) +* C-c C-v t: Extracting source code. + (line 34) +* C-c C-v t <1>: Key bindings and useful functions. + (line 28) +* C-c C-v u: Key bindings and useful functions. + (line 22) +* C-c C-v v: Key bindings and useful functions. + (line 21) +* C-c C-v x: Key bindings and useful functions. + (line 38) +* C-c C-v z: Key bindings and useful functions. + (line 35) +* C-c C-w: Structure editing. (line 86) +* C-c C-w <1>: Using capture. (line 22) +* C-c C-w <2>: Refile and copy. (line 14) +* C-c C-w <3>: Agenda commands. (line 215) +* C-c C-x ,: Timers. (line 41) +* C-c C-x -: Timers. (line 34) +* C-c C-x .: Timers. (line 30) +* C-c C-x 0: Timers. (line 12) +* C-c C-x ;: Timers. (line 20) +* C-c C-x <: Agenda files. (line 39) +* C-c C-x >: Agenda files. (line 46) +* C-c C-x > <1>: Agenda commands. (line 166) +* C-c C-x a: Internal archiving. (line 33) +* C-c C-x A: Internal archiving. (line 44) +* C-c C-x a <1>: Agenda commands. (line 221) +* C-c C-x A <1>: Agenda commands. (line 223) +* C-c C-x b: Global and local cycling. + (line 51) +* C-c C-x b <1>: Agenda commands. (line 45) +* C-c C-x c: Structure editing. (line 79) +* C-c C-x C-a: Archiving. (line 11) +* C-c C-x C-a <1>: Agenda commands. (line 217) +* C-c C-x C-b: Checkboxes. (line 56) +* C-c C-x C-c: Using column view. (line 9) +* C-c C-x C-c <1>: Agenda commands. (line 156) +* C-c C-x C-c <2>: Agenda column view. (line 11) +* C-c C-x C-d: Clocking commands. (line 71) +* C-c C-x C-e: Clocking commands. (line 46) +* C-c C-x C-e <1>: Effort estimates. (line 17) +* C-c C-x C-i: Clocking commands. (line 6) +* C-c C-x C-j: Clocking commands. (line 67) +* C-c C-x C-l: Previewing LaTeX fragments. + (line 17) +* C-c C-x C-n: Handling links. (line 143) +* C-c C-x C-o: Clocking commands. (line 34) +* C-c C-x C-p: Handling links. (line 143) +* C-c C-x C-q: Clocking commands. (line 64) +* C-c C-x C-r: The clock table. (line 10) +* C-c C-x C-s: Moving subtrees. (line 9) +* C-c C-x C-s <1>: Agenda commands. (line 226) +* C-c C-x C-t: Custom time format. (line 12) +* C-c C-x C-u: Capturing column view. + (line 48) +* C-c C-x C-u <1>: The clock table. (line 16) +* C-c C-x C-u <2>: Dynamic blocks. (line 21) +* C-c C-x C-v: Handling links. (line 127) +* C-c C-x C-w: Structure editing. (line 57) +* C-c C-x C-w <1>: Built-in table editor. + (line 122) +* C-c C-x C-x: Clocking commands. (line 41) +* C-c C-x C-y: Structure editing. (line 63) +* C-c C-x C-y <1>: Built-in table editor. + (line 126) +* C-c C-x d: Drawers. (line 6) +* C-c C-x e: Effort estimates. (line 14) +* C-c C-x f: Footnotes. (line 39) +* C-c C-x g: RSS feeds. (line 23) +* C-c C-x G: RSS feeds. (line 26) +* C-c C-x i: Capturing column view. + (line 46) +* C-c C-x M-w: Structure editing. (line 60) +* C-c C-x M-w <1>: Built-in table editor. + (line 118) +* C-c C-x o: TODO dependencies. (line 37) +* C-c C-x o <1>: Checkboxes. (line 73) +* C-c C-x p: Property syntax. (line 82) +* C-c C-x p <1>: Header arguments in Org mode properties. + (line 31) +* C-c C-x q: Tag hierarchy. (line 86) +* C-c C-x v: Global and local cycling. + (line 56) +* C-c C-x \: Special symbols. (line 34) +* C-c C-x \ <1>: Subscripts and superscripts. + (line 20) +* C-c C-x _: Timers. (line 43) +* C-c C-y: Creating timestamps. (line 50) +* C-c C-y <1>: Clocking commands. (line 48) +* C-c C-y <2>: Clocking commands. (line 48) +* C-c C-z: Drawers. (line 35) +* C-c C-z <1>: Agenda commands. (line 249) +* C-c l: Handling links. (line 9) +* C-c l <1>: Literal examples. (line 95) +* C-c M-w: Refile and copy. (line 12) +* C-c : Built-in table editor. + (line 97) +* C-c : Built-in table editor. + (line 59) +* C-c : Global and local cycling. + (line 48) +* C-c [: Agenda files. (line 15) +* C-c \: Tag searches. (line 9) +* C-c \ <1>: Property searches. (line 10) +* C-c ]: Agenda files. (line 19) +* C-c ^: Structure editing. (line 89) +* C-c ^ <1>: Plain lists. (line 142) +* C-c ^ <2>: Built-in table editor. + (line 100) +* C-c `: Built-in table editor. + (line 161) +* C-c {: Editing and debugging formulas. + (line 29) +* C-c { <1>: CDLaTeX mode. (line 20) +* C-c |: Built-in table editor. + (line 41) +* C-c | <1>: Built-in table editor. + (line 177) +* C-c }: Editing and debugging formulas. + (line 24) +* C-c } <1>: Editing and debugging formulas. + (line 67) +* C-c ~: Cooperation. (line 46) +* C-k: Agenda commands. (line 210) +* C-M-i: Completion. (line 38) +* C-: Structure editing. (line 23) +* C-S-LEFT: Multiple sets in one file. + (line 25) +* C-S-: Agenda commands. (line 209) +* C-S-: Structure editing. (line 28) +* C-S-RIGHT: Multiple sets in one file. + (line 25) +* C-S-: Agenda commands. (line 207) +* C-S-: Clocking commands. (line 52) +* C-: Internal archiving. (line 42) +* C-u C-c !: Creating timestamps. (line 17) +* C-u C-c *: Updating the table. (line 16) +* C-u C-c .: Creating timestamps. (line 17) +* C-u C-c =: Field and range formulas. + (line 27) +* C-u C-c = <1>: Editing and debugging formulas. + (line 13) +* C-u C-c c: Using capture. (line 42) +* C-u C-c C-c: Updating the table. (line 18) +* C-u C-c C-l: Handling links. (line 85) +* C-u C-c C-t: TODO basics. (line 28) +* C-u C-c C-w: Refile and copy. (line 32) +* C-u C-c C-x a: Internal archiving. (line 36) +* C-u C-c C-x C-s: Moving subtrees. (line 11) +* C-u C-c C-x C-u: Capturing column view. + (line 50) +* C-u C-c C-x C-u <1>: The clock table. (line 18) +* C-u C-c C-x C-u <2>: Dynamic blocks. (line 22) +* C-u C-u C-c *: Updating the table. (line 21) +* C-u C-u C-c =: Editing and debugging formulas. + (line 16) +* C-u C-u C-c c: Using capture. (line 44) +* C-u C-u C-c C-c: Updating the table. (line 21) +* C-u C-u C-c C-t: Multiple sets in one file. + (line 25) +* C-u C-u C-c C-w: Refile and copy. (line 34) +* C-u C-u C-c C-x C-s: Moving subtrees. (line 17) +* C-u C-u C-u C-c C-t: TODO dependencies. (line 42) +* C-u C-u C-u : Global and local cycling. + (line 35) +* C-u C-u : Global and local cycling. + (line 33) +* C-u C-u <1>: Initial visibility. (line 21) +* C-v: The date/time prompt. + (line 82) +* C-x C-s: Editing and debugging formulas. + (line 41) +* C-x C-s <1>: Agenda commands. (line 153) +* C-x C-w: Agenda commands. (line 425) +* C-x C-w <1>: Exporting agenda views. + (line 12) +* C-x n b: Structure editing. (line 102) +* C-x n s: Structure editing. (line 100) +* C-x n w: Structure editing. (line 104) +* C-y: Structure editing. (line 68) +* C-_: Agenda commands. (line 201) +* d: Agenda commands. (line 65) +* D: Agenda commands. (line 96) +* e: Using column view. (line 41) +* E: Agenda commands. (line 136) +* F: Agenda commands. (line 39) +* f: Agenda commands. (line 83) +* g: Using column view. (line 23) +* G: Agenda commands. (line 142) +* g <1>: Agenda commands. (line 151) +* H: Agenda commands. (line 413) +* I: Agenda commands. (line 279) +* i: Agenda commands. (line 385) +* j: Agenda commands. (line 92) +* J: Agenda commands. (line 94) +* J <1>: Agenda commands. (line 286) +* k: Agenda commands. (line 288) +* L: Agenda commands. (line 33) +* l: Agenda commands. (line 99) +* m: Agenda commands. (line 308) +* M: Agenda commands. (line 403) +* M-*: Agenda commands. (line 318) +* M-: Agenda commands. (line 301) +* M-: Agenda commands. (line 297) +* M-a: Built-in table editor. + (line 70) +* M-: Structure editing. (line 47) +* M-DOWN: Plain lists. (line 93) +* M- <1>: Built-in table editor. + (line 86) +* M- <2>: Editing and debugging formulas. + (line 64) +* M-DOWN <1>: Key bindings and useful functions. + (line 13) +* M-e: Built-in table editor. + (line 73) +* M-g M-n: Sparse trees. (line 28) +* M-g M-p: Sparse trees. (line 30) +* M-g n: Sparse trees. (line 28) +* M-g p: Sparse trees. (line 30) +* M-h: Structure editing. (line 49) +* M-: Structure editing. (line 37) +* M-LEFT: Plain lists. (line 98) +* M- <1>: Built-in table editor. + (line 80) +* M-m: Agenda commands. (line 316) +* M-: Structure editing. (line 6) +* M- <1>: Plain lists. (line 77) +* M- <2>: Built-in table editor. + (line 131) +* M- <3>: Timers. (line 38) +* M-: Structure editing. (line 39) +* M-RIGHT: Plain lists. (line 98) +* M- <1>: Built-in table editor. + (line 80) +* M-S-: Built-in table editor. + (line 91) +* M-S- <1>: Editing and debugging formulas. + (line 60) +* M-S-DOWN: The date/time prompt. + (line 82) +* M-S-: Structure editing. (line 41) +* M-S-LEFT: Plain lists. (line 102) +* M-S- <1>: Built-in table editor. + (line 82) +* M-S-LEFT <1>: The date/time prompt. + (line 82) +* M-S-: Structure editing. (line 25) +* M-S-RET: Plain lists. (line 86) +* M-S- <1>: Checkboxes. (line 71) +* M-S-: Structure editing. (line 43) +* M-S-RIGHT: Plain lists. (line 102) +* M-S- <1>: Built-in table editor. + (line 84) +* M-S-RIGHT <1>: The date/time prompt. + (line 82) +* M-S-: Built-in table editor. + (line 89) +* M-S- <1>: Editing and debugging formulas. + (line 60) +* M-S-UP: The date/time prompt. + (line 82) +* M-: Editing and debugging formulas. + (line 54) +* M-TAB: Per-file keywords. (line 23) +* M-TAB <1>: Setting tags. (line 6) +* M- <1>: Property syntax. (line 80) +* M-TAB <2>: Completion. (line 15) +* M-: Structure editing. (line 45) +* M-UP: Plain lists. (line 93) +* M- <1>: Built-in table editor. + (line 86) +* M- <2>: Editing and debugging formulas. + (line 64) +* M-UP <1>: Key bindings and useful functions. + (line 12) +* M-v: The date/time prompt. + (line 82) +* mouse-1: Footnotes. (line 75) +* mouse-1 <1>: Handling links. (line 120) +* mouse-1 <2>: The date/time prompt. + (line 82) +* mouse-2: Footnotes. (line 75) +* mouse-2 <1>: Handling links. (line 120) +* mouse-2 <2>: Agenda commands. (line 35) +* mouse-3: Handling links. (line 124) +* mouse-3 <1>: Agenda commands. (line 31) +* n: Using column view. (line 38) +* n <1>: Agenda commands. (line 19) +* N: Agenda commands. (line 22) +* o: Agenda commands. (line 63) +* O: Agenda commands. (line 282) +* p: Using column view. (line 38) +* p <1>: Agenda commands. (line 20) +* P: Agenda commands. (line 24) +* P <1>: Agenda commands. (line 241) +* q: Using column view. (line 25) +* q <1>: Agenda commands. (line 439) +* r: Using column view. (line 20) +* r <1>: Global TODO list. (line 22) +* R: Agenda commands. (line 118) +* r <2>: Agenda commands. (line 145) +* : Built-in table editor. + (line 66) +* <1>: Handling links. (line 118) +* RET: Setting tags. (line 116) +* RET <1>: The date/time prompt. + (line 82) +* <2>: Agenda commands. (line 37) +* s: Agenda commands. (line 153) +* S: Agenda commands. (line 406) +* S-DOWN: Plain lists. (line 87) +* S-DOWN <1>: Editing and debugging formulas. + (line 56) +* S-: Priorities. (line 28) +* S- <1>: Creating timestamps. (line 39) +* S-DOWN <2>: The date/time prompt. + (line 82) +* S- <2>: Agenda commands. (line 247) +* S-LEFT: Plain lists. (line 138) +* S-LEFT <1>: Editing and debugging formulas. + (line 56) +* S-LEFT <2>: TODO basics. (line 34) +* S-LEFT <3>: Multiple sets in one file. + (line 32) +* S-: Property syntax. (line 95) +* S-LEFT <4>: Using column view. (line 33) +* S- <1>: Creating timestamps. (line 35) +* S-LEFT <5>: The date/time prompt. + (line 82) +* S- <2>: The clock table. (line 21) +* S- <3>: Agenda commands. (line 273) +* S-M-: Using column view. (line 65) +* S-M-: TODO basics. (line 56) +* S-M-: Using column view. (line 63) +* S-M-: Clocking commands. (line 55) +* S-: Built-in table editor. + (line 148) +* S-RIGHT: Plain lists. (line 138) +* S-RIGHT <1>: Editing and debugging formulas. + (line 56) +* S-RIGHT <2>: TODO basics. (line 34) +* S-RIGHT <3>: Multiple sets in one file. + (line 32) +* S-: Property syntax. (line 95) +* S-RIGHT <4>: Using column view. (line 33) +* S- <1>: Creating timestamps. (line 35) +* S-RIGHT <5>: The date/time prompt. + (line 82) +* S- <2>: The clock table. (line 21) +* S- <3>: Agenda commands. (line 261) +* S-: Global and local cycling. + (line 18) +* S- <1>: Built-in table editor. + (line 64) +* S-UP: Editing and debugging formulas. + (line 56) +* S-: Priorities. (line 28) +* S- <1>: Creating timestamps. (line 39) +* S-UP <1>: The date/time prompt. + (line 82) +* S- <2>: Agenda commands. (line 243) +* SPC: Setting tags. (line 113) +* : Agenda commands. (line 31) +* t: Agenda commands. (line 204) +* T: Agenda commands. (line 230) +* : Global and local cycling. + (line 10) +* <1>: Structure editing. (line 32) +* <2>: Plain lists. (line 66) +* <3>: Built-in table editor. + (line 61) +* <4>: Editing and debugging formulas. + (line 48) +* TAB: Setting tags. (line 107) +* <5>: Agenda commands. (line 35) +* TAB <1>: CDLaTeX mode. (line 21) +* u: Agenda commands. (line 312) +* U: Agenda commands. (line 314) +* v: Using column view. (line 48) +* v a: Agenda commands. (line 112) +* v A: Agenda commands. (line 114) +* v c: Agenda commands. (line 128) +* v d: Agenda commands. (line 65) +* v E: Agenda commands. (line 136) +* v l: Agenda commands. (line 99) +* v L: Agenda commands. (line 101) +* v m: Agenda commands. (line 69) +* v R: Agenda commands. (line 118) +* v : Agenda commands. (line 71) +* v t: Agenda commands. (line 68) +* v w: Agenda commands. (line 67) +* v y: Agenda commands. (line 70) +* v [: Agenda commands. (line 109) +* w: Agenda commands. (line 67) +* X: Agenda commands. (line 284) +* x: Agenda commands. (line 440) +* z: Agenda commands. (line 249) + + +File: org, Node: Command and Function Index, Next: Variable Index, Prev: Key Index, Up: Top + +Command and function index +************************** + +[index] +* Menu: + +* lisp-complete-symbol: Editing and debugging formulas. + (line 54) +* next-error: Sparse trees. (line 28) +* org-agenda: Activation. (line 6) +* org-agenda <1>: Conventions. (line 33) +* org-agenda-add-note: Agenda commands. (line 249) +* org-agenda-archive: Agenda commands. (line 226) +* org-agenda-archive-default-with-confirmation: Agenda commands. + (line 217) +* org-agenda-archive-to-archive-sibling: Agenda commands. (line 223) +* org-agenda-archives-mode: Agenda commands. (line 112) +* org-agenda-archives-mode 'files: Agenda commands. (line 114) +* org-agenda-bulk-action: Agenda commands. (line 322) +* org-agenda-bulk-mark: Agenda commands. (line 308) +* org-agenda-bulk-mark-all: Agenda commands. (line 310) +* org-agenda-bulk-mark-regexp: Agenda commands. (line 320) +* org-agenda-bulk-remove-all-marks: Agenda commands. (line 314) +* org-agenda-bulk-toggle: Agenda commands. (line 316) +* org-agenda-bulk-toggle-all: Agenda commands. (line 318) +* org-agenda-bulk-unmark: Agenda commands. (line 312) +* org-agenda-capture: Agenda commands. (line 288) +* org-agenda-clock-cancel: Agenda commands. (line 284) +* org-agenda-clock-goto: Agenda commands. (line 94) +* org-agenda-clock-goto <1>: Agenda commands. (line 286) +* org-agenda-clock-in: Agenda commands. (line 279) +* org-agenda-clock-out: Agenda commands. (line 282) +* org-agenda-clockreport-mode: Agenda commands. (line 118) +* org-agenda-columns: Agenda commands. (line 156) +* org-agenda-columns <1>: Agenda column view. (line 11) +* org-agenda-convert-date: Agenda commands. (line 410) +* org-agenda-date-prompt: Agenda commands. (line 276) +* org-agenda-day-view: Agenda commands. (line 65) +* org-agenda-deadline: Agenda commands. (line 258) +* org-agenda-diary-entry: Agenda commands. (line 385) +* org-agenda-do-date-earlier: Agenda commands. (line 273) +* org-agenda-do-date-later: Agenda commands. (line 261) +* org-agenda-drag-line-backward: Agenda commands. (line 297) +* org-agenda-drag-line-forward: Agenda commands. (line 301) +* org-agenda-earlier: Agenda commands. (line 88) +* org-agenda-entry-text-mode: Agenda commands. (line 136) +* org-agenda-exit: Agenda commands. (line 440) +* org-agenda-file-to-front: Agenda files. (line 15) +* org-agenda-filter-by-category: Filtering/limiting agenda items. + (line 65) +* org-agenda-filter-by-category <1>: Agenda commands. (line 180) +* org-agenda-filter-by-effort: Filtering/limiting agenda items. + (line 91) +* org-agenda-filter-by-effort <1>: Agenda commands. (line 191) +* org-agenda-filter-by-regexp: Filtering/limiting agenda items. + (line 80) +* org-agenda-filter-by-regexp <1>: Agenda commands. (line 188) +* org-agenda-filter-by-tag: Filtering/limiting agenda items. + (line 17) +* org-agenda-filter-by-tag <1>: Agenda commands. (line 176) +* org-agenda-filter-by-top-headline: Filtering/limiting agenda items. + (line 76) +* org-agenda-filter-by-top-headline <1>: Agenda commands. (line 184) +* org-agenda-filter-remove-all: Filtering/limiting agenda items. + (line 112) +* org-agenda-filter-remove-all <1>: Agenda commands. (line 194) +* org-agenda-follow-mode: Agenda commands. (line 39) +* org-agenda-fortnight-view: Agenda commands. (line 68) +* org-agenda-goto: Agenda commands. (line 35) +* org-agenda-goto-calendar: Agenda commands. (line 381) +* org-agenda-goto-date: Agenda commands. (line 92) +* org-agenda-goto-today: Agenda commands. (line 90) +* org-agenda-holidays: Agenda commands. (line 413) +* org-agenda-kill: Agenda commands. (line 210) +* org-agenda-later: Agenda commands. (line 83) +* org-agenda-limit-interactively: Filtering/limiting agenda items. + (line 151) +* org-agenda-list: Weekly/daily agenda. (line 9) +* org-agenda-list-stuck-projects: Stuck projects. (line 13) +* org-agenda-log-mode: Agenda commands. (line 99) +* org-agenda-manipulate-query-add: Agenda commands. (line 109) +* org-agenda-month-view: Agenda commands. (line 69) +* org-agenda-next-item: Agenda commands. (line 22) +* org-agenda-next-line: Agenda commands. (line 19) +* org-agenda-open-link: Agenda commands. (line 53) +* org-agenda-phases-of-moon: Agenda commands. (line 403) +* org-agenda-previous-item: Agenda commands. (line 24) +* org-agenda-previous-line: Agenda commands. (line 20) +* org-agenda-priority-down: Agenda commands. (line 247) +* org-agenda-priority-up: Agenda commands. (line 243) +* org-agenda-quit: Agenda commands. (line 439) +* org-agenda-recenter: Agenda commands. (line 33) +* org-agenda-redo: Agenda commands. (line 145) +* org-agenda-redo <1>: Agenda commands. (line 151) +* org-agenda-refile: Agenda commands. (line 215) +* org-agenda-remove-restriction-lock: Agenda files. (line 46) +* org-agenda-remove-restriction-lock <1>: Agenda files. (line 57) +* org-agenda-remove-restriction-lock <2>: Agenda commands. (line 166) +* org-agenda-reset-view: Agenda commands. (line 71) +* org-agenda-schedule: Agenda commands. (line 255) +* org-agenda-set-restriction-lock: Agenda files. (line 39) +* org-agenda-set-tags: Agenda commands. (line 234) +* org-agenda-show-and-scroll-up: Agenda commands. (line 31) +* org-agenda-show-priority: Agenda commands. (line 241) +* org-agenda-show-tags: Agenda commands. (line 230) +* org-agenda-sunrise-sunset: Agenda commands. (line 406) +* org-agenda-switch-to: Agenda commands. (line 37) +* org-agenda-todo: Agenda commands. (line 204) +* org-agenda-todo-nextset: Agenda commands. (line 207) +* org-agenda-todo-previousset: Agenda commands. (line 209) +* org-agenda-toggle-archive-tag: Agenda commands. (line 221) +* org-agenda-toggle-diary: Agenda commands. (line 96) +* org-agenda-toggle-time-grid: Agenda commands. (line 142) +* org-agenda-tree-to-indirect-buffer: Agenda commands. (line 45) +* org-agenda-undo: Agenda commands. (line 201) +* org-agenda-week-view: Agenda commands. (line 67) +* org-agenda-write: Agenda commands. (line 425) +* org-agenda-write <1>: Exporting agenda views. + (line 12) +* org-agenda-year-view: Agenda commands. (line 70) +* org-archive-subtree: Moving subtrees. (line 9) +* org-archive-subtree-default: Archiving. (line 11) +* org-archive-to-archive-sibling: Internal archiving. (line 44) +* org-ascii-export-as-ascii: ASCII/Latin-1/UTF-8 export. + (line 27) +* org-ascii-export-to-ascii: ASCII/Latin-1/UTF-8 export. + (line 23) +* org-attach: Attachments. (line 26) +* org-attach <1>: Agenda commands. (line 253) +* org-attach-attach: Attachments. (line 31) +* org-attach-delete-all: Attachments. (line 69) +* org-attach-delete-one: Attachments. (line 66) +* org-attach-new: Attachments. (line 44) +* org-attach-open: Attachments. (line 51) +* org-attach-open-in-emacs: Attachments. (line 57) +* org-attach-reveal: Attachments. (line 60) +* org-attach-reveal-in-emacs: Attachments. (line 63) +* org-attach-set-directory: Attachments. (line 73) +* org-attach-set-inherit: Attachments. (line 78) +* org-attach-sync: Attachments. (line 47) +* org-attach-url: Attachments. (line 41) +* org-backward-same-level: Motion. (line 13) +* org-beamer-export-as-latex: Beamer export commands. + (line 8) +* org-beamer-export-to-latex: Beamer export commands. + (line 6) +* org-beamer-export-to-pdf: Beamer export commands. + (line 10) +* org-beamer-select-environment: Editing support. (line 11) +* org-buffer-property-keys: Using the property API. + (line 33) +* org-calendar-goto-agenda: Agenda commands. (line 382) +* org-capture: Activation. (line 6) +* org-capture <1>: Conventions. (line 33) +* org-capture <2>: Using capture. (line 6) +* org-capture-finalize: Using capture. (line 15) +* org-capture-kill: Using capture. (line 31) +* org-capture-refile: Using capture. (line 22) +* org-check-after-date: Inserting deadline/schedule. + (line 29) +* org-check-before-date: Inserting deadline/schedule. + (line 27) +* org-check-deadlines: Inserting deadline/schedule. + (line 21) +* org-clock-cancel: Clocking commands. (line 64) +* org-clock-display: Clocking commands. (line 71) +* org-clock-goto: Clocking commands. (line 67) +* org-clock-in: Clocking commands. (line 6) +* org-clock-in-last: Clocking commands. (line 41) +* org-clock-modify-effort-estimate: Clocking commands. (line 46) +* org-clock-modify-effort-estimate <1>: Effort estimates. (line 17) +* org-clock-out: Clocking commands. (line 34) +* org-clock-report: The clock table. (line 10) +* org-clock-timestamps-up/down: Clocking commands. (line 52) +* org-clocktable-try-shift: The clock table. (line 21) +* org-clone-subtree-with-time-shift: Structure editing. (line 79) +* org-columns: Using column view. (line 9) +* org-columns-delete: Using column view. (line 65) +* org-columns-edit-allowed: Using column view. (line 51) +* org-columns-edit-value: Using column view. (line 41) +* org-columns-narrow: Using column view. (line 61) +* org-columns-new: Using column view. (line 63) +* org-columns-next-allowed-value: Using column view. (line 38) +* org-columns-previous-allowed-value: Using column view. (line 38) +* org-columns-quit: Using column view. (line 25) +* org-columns-redo: Using column view. (line 20) +* org-columns-redo <1>: Using column view. (line 23) +* org-columns-set-tags-or-toggle: Using column view. (line 46) +* org-columns-show-value: Using column view. (line 48) +* org-columns-widen: Using column view. (line 61) +* org-compute-property-at-point: Property syntax. (line 102) +* org-copy: Refile and copy. (line 12) +* org-copy <1>: Refile and copy. (line 13) +* org-copy-subtree: Structure editing. (line 60) +* org-copy-visible: Global and local cycling. + (line 56) +* org-cut-subtree: Structure editing. (line 57) +* org-cycle: Global and local cycling. + (line 10) +* org-cycle <1>: Structure editing. (line 32) +* org-cycle <2>: Plain lists. (line 66) +* org-cycle-agenda-files: Agenda files. (line 21) +* org-date-from-calendar: Creating timestamps. (line 25) +* org-dblock-update: Capturing column view. + (line 48) +* org-dblock-update <1>: The clock table. (line 16) +* org-dblock-update <2>: Dynamic blocks. (line 21) +* org-deadline: Inserting deadline/schedule. + (line 9) +* org-delete-property: Property syntax. (line 98) +* org-delete-property-globally: Property syntax. (line 100) +* org-demote: Using the mapping API. + (line 76) +* org-demote-subtree: Structure editing. (line 43) +* org-do-demote: Structure editing. (line 39) +* org-do-promote: Structure editing. (line 37) +* org-edit-special: Cooperation. (line 44) +* org-entities-help: Special symbols. (line 16) +* org-entry-add-to-multivalued-property: Using the property API. + (line 50) +* org-entry-delete: Using the property API. + (line 27) +* org-entry-get: Using the property API. + (line 18) +* org-entry-get-multivalued-property: Using the property API. + (line 45) +* org-entry-member-in-multivalued-property: Using the property API. + (line 61) +* org-entry-properties: Using the property API. + (line 8) +* org-entry-put: Using the property API. + (line 30) +* org-entry-put-multivalued-property: Using the property API. + (line 39) +* org-entry-remove-from-multivalued-property: Using the property API. + (line 55) +* org-evaluate-time-range: Creating timestamps. (line 50) +* org-evaluate-time-range <1>: Clocking commands. (line 48) +* org-export-dispatch: The export dispatcher. + (line 15) +* org-feed-goto-inbox: RSS feeds. (line 26) +* org-feed-update-all: RSS feeds. (line 23) +* org-force-cycle-archived: Internal archiving. (line 42) +* org-forward-same-level: Motion. (line 11) +* org-global-cycle: Global and local cycling. + (line 18) +* org-goto: Motion. (line 17) +* org-goto-calendar: Creating timestamps. (line 28) +* org-html-export-as-html: HTML Export commands. + (line 11) +* org-html-export-to-html: HTML Export commands. + (line 6) +* org-icalendar-combine-agenda-files: iCalendar export. (line 43) +* org-icalendar-export-agenda-files: iCalendar export. (line 40) +* org-icalendar-export-to-ics: iCalendar export. (line 38) +* org-insert-columns-dblock: Capturing column view. + (line 46) +* org-insert-heading: Plain lists. (line 77) +* org-insert-heading <1>: Timers. (line 38) +* org-insert-heading-respect-content: Structure editing. (line 23) +* org-insert-link: Handling links. (line 64) +* org-insert-property-drawer: Using the property API. + (line 18) +* org-insert-property-drawer <1>: Using the property API. + (line 36) +* org-insert-todo-heading: Structure editing. (line 25) +* org-insert-todo-heading <1>: TODO basics. (line 56) +* org-insert-todo-heading <2>: Checkboxes. (line 71) +* org-insert-todo-heading-respect-content: Structure editing. (line 28) +* org-latex-export-as-latex: LaTeX export commands. + (line 11) +* org-latex-export-to-latex: LaTeX export commands. + (line 6) +* org-latex-export-to-pdf: LaTeX export commands. + (line 12) +* org-lookup-all: Lookup functions. (line 20) +* org-lookup-first: Lookup functions. (line 8) +* org-lookup-last: Lookup functions. (line 17) +* org-map-entries: Using the mapping API. + (line 11) +* org-mark-element: Structure editing. (line 49) +* org-mark-ring-goto: Handling links. (line 139) +* org-mark-ring-push: Handling links. (line 135) +* org-mark-subtree: Structure editing. (line 54) +* org-match-sparse-tree: Tag searches. (line 9) +* org-match-sparse-tree <1>: Property searches. (line 10) +* org-md-export-as-markdown: Markdown export. (line 18) +* org-md-export-to-markdown: Markdown export. (line 16) +* org-meta-return: Structure editing. (line 6) +* org-move-subtree-down: Structure editing. (line 47) +* org-move-subtree-up: Structure editing. (line 45) +* org-narrow-to-block: Structure editing. (line 102) +* org-narrow-to-subtree: Structure editing. (line 100) +* org-next-link: Handling links. (line 143) +* org-next-visible-heading: Motion. (line 8) +* org-occur: Sparse trees. (line 17) +* org-odt-export-to-odt: ODT export commands. (line 6) +* org-open-at-point: Handling links. (line 98) +* org-open-at-point <1>: Creating timestamps. (line 32) +* org-org-export-as-org: Org export. (line 17) +* org-org-export-to-org: Org export. (line 13) +* org-paste-subtree: Structure editing. (line 63) +* org-previous-link: Handling links. (line 143) +* org-previous-visible-heading: Motion. (line 9) +* org-priority: Priorities. (line 24) +* org-priority <1>: Using the mapping API. + (line 64) +* org-priority-down: Priorities. (line 28) +* org-priority-up: Priorities. (line 28) +* org-promote: Using the mapping API. + (line 73) +* org-promote-subtree: Structure editing. (line 41) +* org-property-action: Property syntax. (line 89) +* org-property-next-allowed-value: Property syntax. (line 95) +* org-property-previous-allowed-value: Property syntax. (line 95) +* org-protocol-create: open-source protocol. + (line 67) +* org-protocol-create-for-org: open-source protocol. + (line 67) +* org-publish: Triggering publication. + (line 8) +* org-publish-all: Triggering publication. + (line 14) +* org-publish-current-file: Triggering publication. + (line 12) +* org-publish-current-project: Triggering publication. + (line 10) +* org-refile: Structure editing. (line 86) +* org-refile <1>: Refile and copy. (line 14) +* org-refile <2>: Refile and copy. (line 16) +* org-refile-cache-clear: Refile and copy. (line 42) +* org-refile-goto-last-stored: Refile and copy. (line 34) +* org-remove-file: Agenda files. (line 19) +* org-reveal: Global and local cycling. + (line 37) +* org-save-all-org-buffers: Agenda commands. (line 153) +* org-schedule: Inserting deadline/schedule. + (line 16) +* org-search-view: Search view. (line 9) +* org-set-effort: Effort estimates. (line 14) +* org-set-property: Property syntax. (line 82) +* org-set-property <1>: Property syntax. (line 92) +* org-set-startup-visibility: Global and local cycling. + (line 33) +* org-set-startup-visibility <1>: Initial visibility. (line 21) +* org-set-tags-command: Setting tags. (line 10) +* org-set-tags-command <1>: Setting tags. (line 19) +* org-show-todo-tree: TODO basics. (line 39) +* org-sort: Structure editing. (line 89) +* org-sparse-tree: Sparse trees. (line 15) +* org-speed-command-help: Speed keys. (line 18) +* org-speedbar-set-agenda-restriction: Agenda files. (line 53) +* org-store-agenda-views: Exporting agenda views. + (line 63) +* org-store-link: Activation. (line 6) +* org-store-link <1>: Handling links. (line 9) +* org-switchb: Activation. (line 6) +* org-table-align: Built-in table editor. + (line 58) +* org-table-beginning-of-field: Built-in table editor. + (line 70) +* org-table-blank-field: Built-in table editor. + (line 59) +* org-table-copy-down: Built-in table editor. + (line 148) +* org-table-copy-region: Built-in table editor. + (line 118) +* org-table-create-or-convert-from-region: Built-in table editor. + (line 41) +* org-table-create-or-convert-from-region <1>: Built-in table editor. + (line 177) +* org-table-create-with-table.el: Cooperation. (line 46) +* org-table-cut-region: Built-in table editor. + (line 122) +* org-table-delete-column: Built-in table editor. + (line 82) +* org-table-edit-field: Built-in table editor. + (line 161) +* org-table-edit-formulas: Editing and debugging formulas. + (line 32) +* org-table-end-of-field: Built-in table editor. + (line 73) +* org-table-eval-formula: Field and range formulas. + (line 27) +* org-table-eval-formula <1>: Column formulas. (line 32) +* org-table-eval-formula <2>: Editing and debugging formulas. + (line 13) +* org-table-eval-formula <3>: Editing and debugging formulas. + (line 16) +* org-table-export: Built-in table editor. + (line 183) +* org-table-fedit-abort: Editing and debugging formulas. + (line 44) +* org-table-fedit-finish: Editing and debugging formulas. + (line 41) +* org-table-fedit-line-down: Editing and debugging formulas. + (line 60) +* org-table-fedit-line-up: Editing and debugging formulas. + (line 60) +* org-table-fedit-lisp-indent: Editing and debugging formulas. + (line 48) +* org-table-fedit-ref-down: Editing and debugging formulas. + (line 56) +* org-table-fedit-ref-left: Editing and debugging formulas. + (line 56) +* org-table-fedit-ref-right: Editing and debugging formulas. + (line 56) +* org-table-fedit-ref-up: Editing and debugging formulas. + (line 56) +* org-table-fedit-scroll-down: Editing and debugging formulas. + (line 64) +* org-table-fedit-scroll-up: Editing and debugging formulas. + (line 64) +* org-table-fedit-toggle-ref-type: Editing and debugging formulas. + (line 45) +* org-table-field-info: Editing and debugging formulas. + (line 21) +* org-table-hline-and-move: Built-in table editor. + (line 97) +* org-table-insert-column: Built-in table editor. + (line 84) +* org-table-insert-hline: Built-in table editor. + (line 94) +* org-table-insert-row: Built-in table editor. + (line 91) +* org-table-iterate: Updating the table. (line 21) +* org-table-iterate-buffer-tables: Updating the table. (line 29) +* org-table-kill-row: Built-in table editor. + (line 89) +* org-table-move-column-left: Built-in table editor. + (line 80) +* org-table-move-column-right: Built-in table editor. + (line 80) +* org-table-move-row-down: Built-in table editor. + (line 86) +* org-table-move-row-up: Built-in table editor. + (line 86) +* org-table-next-field: Built-in table editor. + (line 61) +* org-table-next-row: Built-in table editor. + (line 66) +* org-table-paste-rectangle: Built-in table editor. + (line 126) +* org-table-previous-field: Built-in table editor. + (line 64) +* org-table-recalculate: Updating the table. (line 13) +* org-table-recalculate-buffer-tables: Updating the table. (line 27) +* org-table-rotate-recalc-marks: Advanced features. (line 10) +* org-table-sort-lines: Built-in table editor. + (line 100) +* org-table-sum: Built-in table editor. + (line 145) +* org-table-toggle-coordinate-overlays: Editing and debugging formulas. + (line 24) +* org-table-toggle-coordinate-overlays <1>: Editing and debugging formulas. + (line 67) +* org-table-toggle-formula-debugger: Editing and debugging formulas. + (line 29) +* org-table-wrap-region: Built-in table editor. + (line 131) +* org-tags-view: Tag searches. (line 13) +* org-tags-view <1>: Tag searches. (line 16) +* org-tags-view <2>: Property searches. (line 12) +* org-tags-view <3>: Property searches. (line 15) +* org-tags-view <4>: Matching tags and properties. + (line 12) +* org-tags-view <5>: Matching tags and properties. + (line 17) +* org-texinfo-export-to-info: Texinfo export commands. + (line 8) +* org-texinfo-export-to-texinfo: Texinfo export commands. + (line 6) +* org-time-stamp: Creating timestamps. (line 10) +* org-time-stamp-inactive: Creating timestamps. (line 15) +* org-timer: Timers. (line 30) +* org-timer-item: Timers. (line 34) +* org-timer-pause-or-continue: Timers. (line 41) +* org-timer-set-timer: Timers. (line 20) +* org-timer-start: Timers. (line 12) +* org-timer-stop: Timers. (line 43) +* org-timestamp-down-day: Creating timestamps. (line 35) +* org-timestamp-down-down: Creating timestamps. (line 39) +* org-timestamp-up: Creating timestamps. (line 39) +* org-timestamp-up-day: Creating timestamps. (line 35) +* org-timestamp-up/down: Clocking commands. (line 55) +* org-todo: TODO basics. (line 13) +* org-todo <1>: Clocking commands. (line 61) +* org-todo <2>: Using the mapping API. + (line 60) +* org-todo-list: TODO basics. (line 49) +* org-todo-list <1>: Global TODO list. (line 9) +* org-todo-list <2>: Global TODO list. (line 15) +* org-toggle-archive-tag: Internal archiving. (line 33) +* org-toggle-checkbox: Checkboxes. (line 52) +* org-toggle-checkbox <1>: Checkboxes. (line 56) +* org-toggle-heading: Structure editing. (line 106) +* org-toggle-inline-images: Handling links. (line 127) +* org-toggle-ordered-property: TODO dependencies. (line 37) +* org-toggle-ordered-property <1>: Checkboxes. (line 73) +* org-toggle-tag: Using the mapping API. + (line 68) +* org-toggle-time-stamp-overlays: Custom time format. (line 12) +* org-tree-to-indirect-buffer: Global and local cycling. + (line 51) +* org-update-all-dblocks: Capturing column view. + (line 50) +* org-update-statistics-cookies: Checkboxes. (line 80) +* org-yank: Structure editing. (line 68) +* outline-show-all: Global and local cycling. + (line 35) +* outline-show-branches: Global and local cycling. + (line 45) +* outline-show-children: Global and local cycling. + (line 48) +* outline-up-heading: Motion. (line 15) +* pcomplete: Property syntax. (line 80) +* previous-error: Sparse trees. (line 30) +* widen: Structure editing. (line 104) + + +File: org, Node: Variable Index, Prev: Command and Function Index, Up: Top + +Variable index +************** + +This is not a complete index of variables and faces, only the ones that +are mentioned in the manual. For a complete list, use ‘M-x +org-customize ’. + +[index] +* Menu: + +* cdlatex-simplify-sub-super-scripts: CDLaTeX mode. (line 30) +* constants-unit-system: References. (line 115) +* constants-unit-system <1>: In-buffer settings. (line 135) +* htmlize-output-type: Exporting agenda views. + (line 20) +* LaTeX-verbatim-environments: A LaTeX example. (line 19) +* org-adapt-indentation: Clean view. (line 52) +* org-agenda-add-entry-text-maxlines: Exporting agenda views. + (line 20) +* org-agenda-bulk-custom-functions: Agenda commands. (line 308) +* org-agenda-category-filter-preset: Filtering/limiting agenda items. + (line 66) +* org-agenda-clock-consistency-checks: Agenda commands. (line 130) +* org-agenda-columns-add-appointments-to-effort-sum: Effort estimates. + (line 40) +* org-agenda-confirm-kill: Agenda commands. (line 212) +* org-agenda-custom-commands: Sparse trees. (line 34) +* org-agenda-custom-commands <1>: Storing searches. (line 9) +* org-agenda-custom-commands <2>: Setting options. (line 6) +* org-agenda-custom-commands <3>: Setting options. (line 31) +* org-agenda-custom-commands <4>: Extracting agenda information. + (line 6) +* org-agenda-custom-commands-contexts: Setting options. (line 60) +* org-agenda-diary-file: Agenda commands. (line 387) +* org-agenda-dim-blocked-tasks: TODO dependencies. (line 46) +* org-agenda-dim-blocked-tasks <1>: Speeding up your agendas. + (line 13) +* org-agenda-effort-filter-preset: Filtering/limiting agenda items. + (line 92) +* org-agenda-entry-text-maxlines: Agenda commands. (line 137) +* org-agenda-exporter-settings: Agenda commands. (line 426) +* org-agenda-exporter-settings <1>: Exporting agenda views. + (line 13) +* org-agenda-files: Agenda files. (line 6) +* org-agenda-files <1>: Sorting agenda items. + (line 8) +* org-agenda-files <2>: iCalendar export. (line 42) +* org-agenda-inhibit-startup: Initial visibility. (line 6) +* org-agenda-inhibit-startup <1>: Speeding up your agendas. + (line 15) +* org-agenda-log-mode-items: Agenda commands. (line 101) +* org-agenda-max-effort: Filtering/limiting agenda items. + (line 118) +* org-agenda-max-entries: Filtering/limiting agenda items. + (line 118) +* org-agenda-max-tags: Filtering/limiting agenda items. + (line 118) +* org-agenda-max-todos: Filtering/limiting agenda items. + (line 118) +* org-agenda-ndays: Weekly/daily agenda. (line 15) +* org-agenda-overriding-header: Special agenda views. + (line 38) +* org-agenda-prefix-format: Presentation and sorting. + (line 6) +* org-agenda-regexp-filter-preset: Filtering/limiting agenda items. + (line 81) +* org-agenda-restore-windows-after-quit: Agenda views. (line 37) +* org-agenda-search-headline-for-time: Time-of-day specifications. + (line 14) +* org-agenda-show-inherited-tags: Agenda commands. (line 232) +* org-agenda-show-inherited-tags <1>: Speeding up your agendas. + (line 17) +* org-agenda-skip-archived-trees: Internal archiving. (line 20) +* org-agenda-skip-archived-trees <1>: Agenda views. (line 32) +* org-agenda-skip-comment-trees: Agenda views. (line 32) +* org-agenda-skip-deadline-prewarning-if-scheduled: Deadlines and scheduling. + (line 15) +* org-agenda-skip-function: Special agenda views. + (line 6) +* org-agenda-skip-function <1>: Special agenda views. + (line 41) +* org-agenda-skip-function <2>: Using the mapping API. + (line 48) +* org-agenda-skip-function-global: Special agenda views. + (line 6) +* org-agenda-skip-scheduled-delay-if-deadline: Deadlines and scheduling. + (line 44) +* org-agenda-skip-scheduled-if-deadline-is-shown: Repeated tasks. + (line 72) +* org-agenda-skip-scheduled-if-done: Deadlines and scheduling. + (line 36) +* org-agenda-sorting-strategy: Sorting agenda items. + (line 25) +* org-agenda-span: Weekly/daily agenda. (line 15) +* org-agenda-span <1>: Agenda commands. (line 72) +* org-agenda-start-day: Weekly/daily agenda. (line 15) +* org-agenda-start-on-weekday: Weekly/daily agenda. (line 15) +* org-agenda-start-with-clockreport-mode: Agenda commands. (line 120) +* org-agenda-start-with-entry-text-mode: Agenda commands. (line 137) +* org-agenda-start-with-follow-mode: Agenda commands. (line 41) +* org-agenda-sticky: Agenda dispatcher. (line 43) +* org-agenda-tag-filter-preset: Filtering/limiting agenda items. + (line 18) +* org-agenda-tags-column: Presentation and sorting. + (line 6) +* org-agenda-tags-todo-honor-ignore-options: Matching tags and properties. + (line 19) +* org-agenda-text-search-extra-files: Agenda dispatcher. (line 25) +* org-agenda-text-search-extra-files <1>: Search view. (line 24) +* org-agenda-time-grid: Time-of-day specifications. + (line 44) +* org-agenda-time-grid <1>: Agenda commands. (line 144) +* org-agenda-todo-ignore-deadlines: Global TODO list. (line 37) +* org-agenda-todo-ignore-scheduled: Global TODO list. (line 37) +* org-agenda-todo-ignore-timestamp: Global TODO list. (line 37) +* org-agenda-todo-ignore-with-date: Global TODO list. (line 37) +* org-agenda-todo-list-sublevels: Breaking down tasks. (line 6) +* org-agenda-todo-list-sublevels <1>: Global TODO list. (line 45) +* org-agenda-use-tag-inheritance: Tag inheritance. (line 32) +* org-agenda-use-tag-inheritance <1>: Speeding up your agendas. + (line 17) +* org-agenda-use-time-grid: Time-of-day specifications. + (line 44) +* org-agenda-use-time-grid <1>: Agenda commands. (line 144) +* org-agenda-window-setup: Agenda views. (line 37) +* org-archive-default-command: Archiving. (line 12) +* org-archive-default-command <1>: Agenda commands. (line 219) +* org-archive-location: Moving subtrees. (line 10) +* org-archive-location <1>: In-buffer settings. (line 14) +* org-archive-save-context-info: Moving subtrees. (line 39) +* org-ascii-links-to-notes: ASCII/Latin-1/UTF-8 export. + (line 16) +* org-ascii-text-width: ASCII/Latin-1/UTF-8 export. + (line 13) +* org-attach-directory: Attachments. (line 6) +* org-attach-method: Attachments. (line 32) +* org-babel-default-header-args: System-wide header arguments. + (line 6) +* org-babel-default-header-args <1>: Header arguments in Org mode properties. + (line 31) +* org-babel-load-languages: Languages. (line 35) +* org-beamer-environments-default: Sectioning Frames and Blocks in Beamer. + (line 21) +* org-beamer-environments-extra: Sectioning Frames and Blocks in Beamer. + (line 21) +* org-beamer-frame-level: Sectioning Frames and Blocks in Beamer. + (line 10) +* org-beamer-subtitle-format: Beamer specific export settings. + (line 44) +* org-beamer-theme: Beamer specific export settings. + (line 11) +* org-calc-default-modes: Formula syntax for Calc. + (line 14) +* org-capture-bookmark: Using capture. (line 48) +* org-capture-templates: Capture templates. (line 11) +* org-capture-templates-contexts: Templates in contexts. + (line 6) +* org-capture-use-agenda-date: Agenda commands. (line 292) +* org-catch-invisible-edits: Catching invisible edits. + (line 6) +* org-checkbox-hierarchical-statistics: Checkboxes. (line 30) +* org-clock-continuously: Clocking commands. (line 7) +* org-clock-continuously <1>: Clocking commands. (line 43) +* org-clock-continuously <2>: Resolving idle time. (line 74) +* org-clock-idle-time: Resolving idle time. (line 14) +* org-clock-into-drawer: Clocking commands. (line 7) +* org-clock-modeline-total: Clocking commands. (line 20) +* org-clock-report-include-clocking-task: Agenda commands. (line 120) +* org-clock-x11idle-program-name: Resolving idle time. (line 9) +* org-clocktable-defaults: The clock table. (line 34) +* org-closed-keep-when-no-todo: Closing items. (line 11) +* org-coderef-label-format: Literal examples. (line 75) +* org-columns-default-format: Using column view. (line 10) +* org-columns-default-format <1>: Effort estimates. (line 30) +* org-columns-default-format <2>: Agenda commands. (line 158) +* org-columns-default-format <3>: Agenda column view. (line 18) +* org-columns-skip-archived-trees: Internal archiving. (line 28) +* org-columns-summary-types: Column attributes. (line 64) +* org-confirm-babel-evaluate: Code evaluation security. + (line 25) +* org-confirm-elisp-link-function: Code evaluation security. + (line 51) +* org-confirm-shell-link-function: Code evaluation security. + (line 49) +* org-create-file-search-functions: Custom searches. (line 12) +* org-ctrl-c-ctrl-c-hook: Context-sensitive commands. + (line 6) +* org-ctrl-k-protect-subtree: Headlines. (line 6) +* org-cycle-emulate-tab: Global and local cycling. + (line 16) +* org-cycle-global-at-bob: Global and local cycling. + (line 29) +* org-cycle-include-plain-lists: Plain lists. (line 67) +* org-cycle-open-archived-trees: Internal archiving. (line 12) +* org-cycle-separator-lines: Headlines. (line 26) +* org-deadline-warning-days: Deadlines and scheduling. + (line 15) +* org-deadline-warning-days <1>: Inserting deadline/schedule. + (line 23) +* org-default-notes-file: Setting up capture. (line 9) +* org-default-notes-file <1>: Template elements. (line 45) +* org-default-priority: Priorities. (line 36) +* org-default-priority <1>: In-buffer settings. (line 39) +* org-display-custom-times: Custom time format. (line 6) +* org-display-internal-link-with-indirect-buffer: Handling links. + (line 126) +* org-disputed-keys: Conflicts. (line 28) +* org-done (face): Faces for TODO keywords. + (line 6) +* org-edit-footnote-reference: Footnotes. (line 81) +* org-edit-src-auto-save-idle-delay: Editing source code. (line 6) +* org-edit-src-turn-on-auto-save: Editing source code. (line 6) +* org-emphasis-alist: Emphasis and monospace. + (line 6) +* org-emphasis-regexp-components: Emphasis and monospace. + (line 6) +* org-enforce-todo-dependencies: TODO dependencies. (line 6) +* org-enforce-todo-dependencies <1>: TODO dependencies. (line 51) +* org-entities-user: Special symbols. (line 16) +* org-execute-file-search-functions: Custom searches. (line 12) +* org-export-allow-bind-keywords: Export settings. (line 210) +* org-export-async-init-file: The export dispatcher. + (line 28) +* org-export-backends: Exporting. (line 33) +* org-export-backends <1>: Other built-in back-ends. + (line 6) +* org-export-before-parsing-hook: Advanced configuration. + (line 9) +* org-export-before-processing-hook: Advanced configuration. + (line 9) +* org-export-creator-string: Export settings. (line 28) +* org-export-creator-string <1>: HTML preamble and postamble. + (line 6) +* org-export-date-timestamp-format: Export settings. (line 32) +* org-export-default-language: Export settings. (line 38) +* org-export-dispatch-use-expert-ui: The export dispatcher. + (line 6) +* org-export-exclude-tags: Export settings. (line 52) +* org-export-global-macros: Macro replacement. (line 6) +* org-export-headline-levels: Export settings. (line 141) +* org-export-in-background: The export dispatcher. + (line 39) +* org-export-initial-scope: The export dispatcher. + (line 48) +* org-export-preserve-breaks: Export settings. (line 93) +* org-export-select-tags: Export settings. (line 44) +* org-export-time-stamp-file: Export settings. (line 186) +* org-export-time-stamp-file <1>: HTML preamble and postamble. + (line 6) +* org-export-use-babel: Exporting code blocks. + (line 33) +* org-export-with-archived-trees: Internal archiving. (line 25) +* org-export-with-archived-trees <1>: Export settings. (line 102) +* org-export-with-author: Export settings. (line 107) +* org-export-with-broken-links: Export settings. (line 111) +* org-export-with-clocks: Export settings. (line 116) +* org-export-with-creator: Export settings. (line 119) +* org-export-with-date: Export settings. (line 127) +* org-export-with-drawers: Drawers. (line 38) +* org-export-with-drawers <1>: Export settings. (line 123) +* org-export-with-email: Export settings. (line 134) +* org-export-with-entities: Export settings. (line 131) +* org-export-with-fixed-width: Export settings. (line 86) +* org-export-with-footnotes: Export settings. (line 138) +* org-export-with-inlinetasks: Export settings. (line 146) +* org-export-with-latex: LaTeX fragments. (line 37) +* org-export-with-latex <1>: Export settings. (line 182) +* org-export-with-planning: Export settings. (line 156) +* org-export-with-priority: Export settings. (line 162) +* org-export-with-properties: Drawers. (line 38) +* org-export-with-properties <1>: Export settings. (line 165) +* org-export-with-section-numbers: Export settings. (line 149) +* org-export-with-smart-quotes: Export settings. (line 73) +* org-export-with-special-strings: Export settings. (line 82) +* org-export-with-statistics-cookies: Export settings. (line 169) +* org-export-with-sub-superscripts: Export settings. (line 97) +* org-export-with-tables: Export settings. (line 201) +* org-export-with-tags: Export settings. (line 173) +* org-export-with-tasks: Export settings. (line 177) +* org-export-with-timestamps: Export settings. (line 89) +* org-export-with-title: Export settings. (line 190) +* org-export-with-toc: Export settings. (line 193) +* org-export-with-toc <1>: Table of contents. (line 6) +* org-export-with-todo-keywords: Export settings. (line 197) +* org-fast-tag-selection-include-todo: Fast access to TODO states. + (line 16) +* org-fast-tag-selection-single-key: Setting tags. (line 142) +* org-file-apps: Handling links. (line 100) +* org-file-apps <1>: Attachments. (line 52) +* org-fontify-emphasized-text: Emphasis and monospace. + (line 6) +* org-footnote-auto-adjust: Footnotes. (line 45) +* org-footnote-auto-adjust <1>: In-buffer settings. (line 140) +* org-footnote-auto-label: Footnotes. (line 32) +* org-footnote-auto-label <1>: In-buffer settings. (line 140) +* org-footnote-define-inline: Footnotes. (line 45) +* org-footnote-define-inline <1>: In-buffer settings. (line 140) +* org-footnote-section: Headlines. (line 18) +* org-footnote-section <1>: Footnotes. (line 45) +* org-format-latex-header: LaTeX fragments. (line 6) +* org-format-latex-header <1>: Previewing LaTeX fragments. + (line 12) +* org-format-latex-options: Previewing LaTeX fragments. + (line 12) +* org-from-is-user-regexp: Template expansion. (line 49) +* org-global-properties: Property syntax. (line 75) +* org-global-properties <1>: Effort estimates. (line 30) +* org-goto-auto-isearch: Motion. (line 21) +* org-goto-interface: Motion. (line 32) +* org-group-tags: Tag hierarchy. (line 86) +* org-hide (face): Clean view. (line 70) +* org-hide-block-startup: Blocks. (line 6) +* org-hide-leading-stars: In-buffer settings. (line 119) +* org-hide-leading-stars <1>: Clean view. (line 55) +* org-hierarchical-todo-statistics: Breaking down tasks. (line 25) +* org-highest-priority: Priorities. (line 36) +* org-highest-priority <1>: In-buffer settings. (line 39) +* org-html-container-element: HTML Specific export settings. + (line 19) +* org-html-doctype: HTML Specific export settings. + (line 16) +* org-html-doctype <1>: HTML doctypes. (line 8) +* org-html-doctype-alist: HTML doctypes. (line 8) +* org-html-head: HTML Specific export settings. + (line 35) +* org-html-head <1>: CSS support. (line 43) +* org-html-head-extra: HTML Specific export settings. + (line 39) +* org-html-head-extra <1>: CSS support. (line 43) +* org-html-head-include-default-style: CSS support. (line 43) +* org-html-html5-elements: HTML doctypes. (line 58) +* org-html-html5-fancy: HTML doctypes. (line 25) +* org-html-infojs-options: JavaScript support. (line 51) +* org-html-inline-images: Images in HTML export. + (line 6) +* org-html-link-home: HTML Specific export settings. + (line 23) +* org-html-link-org-files-as-html: Links in HTML export. + (line 6) +* org-html-link-up: HTML Specific export settings. + (line 26) +* org-html-mathjax-options: HTML Specific export settings. + (line 30) +* org-html-postamble: HTML preamble and postamble. + (line 6) +* org-html-postamble-format: HTML preamble and postamble. + (line 6) +* org-html-preamble: HTML preamble and postamble. + (line 6) +* org-html-preamble-format: HTML preamble and postamble. + (line 6) +* org-html-style-default: CSS support. (line 43) +* org-html-table-align-individual-fields: Tables in HTML export. + (line 19) +* org-html-table-caption-above: Tables in HTML export. + (line 23) +* org-html-table-data-tags: Tables in HTML export. + (line 26) +* org-html-table-default-attributes: Tables in HTML export. + (line 6) +* org-html-table-default-attributes <1>: Tables in HTML export. + (line 29) +* org-html-table-header-tags: Tables in HTML export. + (line 32) +* org-html-table-row-tags: Tables in HTML export. + (line 35) +* org-html-table-use-header-tags-for-first-column: Tables in HTML export. + (line 38) +* org-html-tag-class-prefix: CSS support. (line 6) +* org-html-todo-kwd-class-prefix: CSS support. (line 6) +* org-html-use-infojs: JavaScript support. (line 51) +* org-html-validation-link: HTML preamble and postamble. + (line 6) +* org-icalendar-alarm-time: iCalendar export. (line 6) +* org-icalendar-categories: iCalendar export. (line 6) +* org-icalendar-combined-agenda-file: iCalendar export. (line 45) +* org-icalendar-include-body: iCalendar export. (line 49) +* org-icalendar-include-todo: iCalendar export. (line 6) +* org-icalendar-store-UID: iCalendar export. (line 26) +* org-icalendar-use-deadline: iCalendar export. (line 6) +* org-icalendar-use-scheduled: iCalendar export. (line 6) +* org-id-link-to-org-use-id: Handling links. (line 21) +* org-imenu-depth: Cooperation. (line 27) +* org-insert-mode-line-in-empty-file: Activation. (line 27) +* org-irc-link-to-logs: Handling links. (line 45) +* org-keep-stored-link-after-insertion: Handling links. (line 65) +* org-latex-bibtex-compiler: LaTeX export commands. + (line 19) +* org-latex-classes: LaTeX specific export settings. + (line 20) +* org-latex-classes <1>: LaTeX specific export settings. + (line 36) +* org-latex-classes <2>: LaTeX specific export settings. + (line 41) +* org-latex-classes <3>: LaTeX header and sectioning. + (line 13) +* org-latex-compiler: LaTeX export commands. + (line 19) +* org-latex-compiler <1>: LaTeX specific export settings. + (line 32) +* org-latex-default-class: LaTeX specific export settings. + (line 20) +* org-latex-default-class <1>: LaTeX header and sectioning. + (line 13) +* org-latex-default-packages-alist: LaTeX export commands. + (line 19) +* org-latex-default-packages-alist <1>: LaTeX header and sectioning. + (line 13) +* org-latex-default-table-environment: Tables in LaTeX export. + (line 21) +* org-latex-default-table-mode: Tables in LaTeX export. + (line 11) +* org-latex-images-centered: Images in LaTeX export. + (line 46) +* org-latex-listings: Literal examples. (line 23) +* org-latex-listings-options: Source blocks in LaTeX export. + (line 21) +* org-latex-minted-options: Source blocks in LaTeX export. + (line 21) +* org-latex-packages-alist: LaTeX header and sectioning. + (line 13) +* org-latex-subtitle-format: LaTeX specific export settings. + (line 55) +* org-latex-subtitle-separate: LaTeX specific export settings. + (line 55) +* org-latex-tables-booktabs: Tables in LaTeX export. + (line 58) +* org-latex-tables-centered: Tables in LaTeX export. + (line 58) +* org-latex-to-mathml-convert-command: Working with LaTeX math snippets. + (line 21) +* org-latex-to-mathml-jar-file: Working with LaTeX math snippets. + (line 21) +* org-link-abbrev-alist: Link abbreviations. (line 12) +* org-link-abbrev-alist <1>: In-buffer settings. (line 35) +* org-link-frame-setup: Handling links. (line 100) +* org-link-parameters: Handling links. (line 65) +* org-list-allow-alphabetical: Plain lists. (line 13) +* org-list-automatic-rules: Plain lists. (line 60) +* org-list-automatic-rules <1>: Plain lists. (line 79) +* org-list-automatic-rules <2>: Checkboxes. (line 6) +* org-list-demote-modify-bullet: Plain lists. (line 54) +* org-list-indent-offset: Plain lists. (line 54) +* org-list-use-circular-motion: Plain lists. (line 90) +* org-log-done: Tracking TODO state changes. + (line 29) +* org-log-done <1>: Agenda commands. (line 101) +* org-log-done <2>: In-buffer settings. (line 94) +* org-log-into-drawer: Tracking TODO state changes. + (line 6) +* org-log-into-drawer <1>: Agenda commands. (line 251) +* org-log-note-clock-out: Clocking commands. (line 36) +* org-log-note-clock-out <1>: In-buffer settings. (line 94) +* org-log-refile: Refile and copy. (line 16) +* org-log-repeat: Repeated tasks. (line 37) +* org-log-repeat <1>: In-buffer settings. (line 94) +* org-log-states-order-reversed: Tracking TODO state changes. + (line 6) +* org-lowest-priority: Priorities. (line 36) +* org-lowest-priority <1>: In-buffer settings. (line 39) +* org-M-RET-may-split-line: Structure editing. (line 7) +* org-M-RET-may-split-line <1>: Plain lists. (line 79) +* org-md-headline-style: Markdown export. (line 27) +* org-odd-levels-only: Matching tags and properties. + (line 67) +* org-odd-levels-only <1>: In-buffer settings. (line 119) +* org-odd-levels-only <2>: Clean view. (line 75) +* org-odd-levels-only <3>: Special agenda views. + (line 41) +* org-odt-category-map-alist: Labels and captions in ODT export. + (line 21) +* org-odt-convert: Extending ODT export. + (line 36) +* org-odt-convert-capabilities: Configuring a document converter. + (line 18) +* org-odt-convert-process: Configuring a document converter. + (line 25) +* org-odt-convert-processes: Configuring a document converter. + (line 12) +* org-odt-create-custom-styles-for-srcblocks: Literal examples in ODT export. + (line 16) +* org-odt-fontify-srcblocks: Literal examples in ODT export. + (line 13) +* org-odt-pixels-per-inch: Images in ODT export. + (line 34) +* org-odt-preferred-output-format: ODT export commands. (line 10) +* org-odt-preferred-output-format <1>: ODT export commands. (line 29) +* org-odt-preferred-output-format <2>: Extending ODT export. + (line 21) +* org-odt-schema-dir: Validating OpenDocument XML. + (line 14) +* org-odt-styles-file: ODT specific export settings. + (line 22) +* org-odt-styles-file <1>: Applying custom styles. + (line 25) +* org-odt-table-styles: Customizing tables in ODT export. + (line 13) +* org-odt-table-styles <1>: Customizing tables in ODT export. + (line 82) +* org-outline-path-complete-in-steps: Refile and copy. (line 16) +* org-overriding-columns-format: Agenda column view. (line 18) +* org-plain-list-ordered-item-terminator: Plain lists. (line 13) +* org-plain-list-ordered-item-terminator <1>: Plain lists. (line 119) +* org-popup-calendar-for-date-prompt: The date/time prompt. + (line 76) +* org-preview-latex-default-process: Previewing LaTeX fragments. + (line 6) +* org-priority-faces: Priorities. (line 13) +* org-priority-start-cycle-with-default: Priorities. (line 31) +* org-property-allowed-value-functions: Using the property API. + (line 67) +* org-protocol-default-template-key: capture protocol. (line 19) +* org-protocol-project-alist: open-source protocol. + (line 13) +* org-publish-project-alist: Project alist. (line 6) +* org-publish-project-alist <1>: Publishing options. (line 13) +* org-publish-use-timestamps-flag: Triggering publication. + (line 18) +* org-put-time-stamp-overlays: In-buffer settings. (line 130) +* org-read-date-display-live: The date/time prompt. + (line 91) +* org-read-date-force-compatible-dates: The date/time prompt. + (line 61) +* org-read-date-prefer-future: The date/time prompt. + (line 6) +* org-refile-allow-creating-parent-nodes: Refile and copy. (line 16) +* org-refile-keep: Refile and copy. (line 16) +* org-refile-targets: Refile and copy. (line 16) +* org-refile-use-cache: Refile and copy. (line 16) +* org-refile-use-outline-path: Refile and copy. (line 16) +* org-remove-highlights-with-change: Sparse trees. (line 19) +* org-remove-highlights-with-change <1>: Clocking commands. (line 73) +* org-replace-disputed-keys: Conflicts. (line 18) +* org-return-follows-link: Handling links. (line 119) +* org-reverse-note-order: Refile and copy. (line 16) +* org-scheduled-delay-days: Deadlines and scheduling. + (line 44) +* org-show-context-detail: Sparse trees. (line 6) +* org-sort-agenda-noeffort-is-high: Filtering/limiting agenda items. + (line 92) +* org-sparse-tree-open-archived-trees: Internal archiving. (line 17) +* org-special-ctrl-a/e: Headlines. (line 6) +* org-special-ctrl-k: Headlines. (line 6) +* org-speed-commands-user: Speed keys. (line 18) +* org-startup-align-all-tables: Column width and alignment. + (line 33) +* org-startup-align-all-tables <1>: In-buffer settings. (line 75) +* org-startup-folded: Initial visibility. (line 6) +* org-startup-folded <1>: In-buffer settings. (line 65) +* org-startup-folded <2>: Speeding up your agendas. + (line 15) +* org-startup-indented: In-buffer settings. (line 70) +* org-startup-with-inline-images: Handling links. (line 129) +* org-startup-with-inline-images <1>: In-buffer settings. (line 82) +* org-startup-with-latex-preview: Previewing LaTeX fragments. + (line 27) +* org-startup-with-latex-preview <1>: In-buffer settings. (line 88) +* org-store-link-functions: Adding hyperlink types. + (line 59) +* org-stuck-projects: Stuck projects. (line 16) +* org-support-shift-select: Plain lists. (line 90) +* org-support-shift-select <1>: Plain lists. (line 140) +* org-support-shift-select <2>: Conflicts. (line 6) +* org-table-auto-blank-field: Built-in table editor. + (line 30) +* org-table-copy-increment: Built-in table editor. + (line 150) +* org-table-duration-custom-format: Durations and time values. + (line 6) +* org-table-export-default-format: Built-in table editor. + (line 183) +* org-table-formula: In-buffer settings. (line 27) +* org-table-formula-constants: References. (line 108) +* org-table-formula-constants <1>: In-buffer settings. (line 27) +* org-table-formula-constants <2>: Cooperation. (line 11) +* org-table-use-standard-references: References. (line 17) +* org-table-use-standard-references <1>: Editing and debugging formulas. + (line 6) +* org-tag-alist: Setting tags. (line 22) +* org-tag-alist <1>: In-buffer settings. (line 164) +* org-tag-faces: Tags. (line 10) +* org-tag-persistent-alist: Setting tags. (line 37) +* org-tags-column: Setting tags. (line 11) +* org-tags-exclude-from-inheritance: Tag inheritance. (line 22) +* org-tags-match-list-sublevels: Tag inheritance. (line 26) +* org-tags-match-list-sublevels <1>: Tag searches. (line 18) +* org-tags-match-list-sublevels <2>: Property searches. (line 17) +* org-tags-match-list-sublevels <3>: Matching tags and properties. + (line 19) +* org-texinfo-classes: Texinfo file header. (line 11) +* org-texinfo-classes <1>: Headings and sectioning structure. + (line 6) +* org-texinfo-coding-system: Texinfo file header. (line 11) +* org-texinfo-default-class: Texinfo specific export settings. + (line 20) +* org-texinfo-default-class <1>: Headings and sectioning structure. + (line 6) +* org-texinfo-info-process: Texinfo export commands. + (line 6) +* org-texinfo-table-default-markup: Plain lists in Texinfo export. + (line 12) +* org-time-stamp-custom-formats: Custom time format. (line 6) +* org-time-stamp-overlay-formats: In-buffer settings. (line 130) +* org-time-stamp-rounding-minutes: Creating timestamps. (line 20) +* org-todo (face): Faces for TODO keywords. + (line 6) +* org-todo-keyword-faces: Faces for TODO keywords. + (line 6) +* org-todo-keywords: TODO basics. (line 41) +* org-todo-keywords <1>: TODO extensions. (line 6) +* org-todo-keywords <2>: Global TODO list. (line 17) +* org-todo-keywords <3>: In-buffer settings. (line 179) +* org-todo-repeat-to-state: Repeated tasks. (line 19) +* org-todo-state-tags-triggers: TODO basics. (line 60) +* org-track-ordered-property-with-tag: TODO dependencies. (line 38) +* org-track-ordered-property-with-tag <1>: Checkboxes. (line 75) +* org-treat-insert-todo-heading-as-state-change: Structure editing. + (line 27) +* org-treat-S-cursor-todo-selection-as-state-change: TODO basics. + (line 35) +* org-use-fast-todo-selection: TODO basics. (line 14) +* org-use-property-inheritance: Property inheritance. + (line 6) +* org-use-property-inheritance <1>: iCalendar export. (line 49) +* org-use-property-inheritance <2>: Header arguments in Org mode properties. + (line 17) +* org-use-property-inheritance <3>: Using the property API. + (line 18) +* org-use-speed-commands: Speed keys. (line 13) +* org-use-sub-superscripts: Subscripts and superscripts. + (line 14) +* org-use-tag-inheritance: Tag inheritance. (line 22) +* org-yank-adjusted-subtrees: Structure editing. (line 70) +* org-yank-folded-subtrees: Structure editing. (line 70) +* orgstruct-heading-prefix-regexp: Orgstruct mode. (line 26) +* parse-time-months: The date/time prompt. + (line 57) +* parse-time-weekdays: The date/time prompt. + (line 57) +* ps-landscape-mode: Exporting agenda views. + (line 20) +* ps-number-of-columns: Exporting agenda views. + (line 20) +* user-full-name: Export settings. (line 25) +* user-mail-address: Export settings. (line 35) + + + +Tag Table: +Node: Top907 +Node: Introduction24445 +Node: Summary24874 +Node: Installation27573 +Node: Activation30379 +Ref: Activation-Footnote-131939 +Node: Feedback32067 +Ref: Feedback-Footnote-135716 +Node: Conventions35843 +Node: Document structure37954 +Node: Outlines38949 +Node: Headlines39582 +Ref: Headlines-Footnote-140795 +Ref: Headlines-Footnote-240995 +Node: Visibility cycling41066 +Node: Global and local cycling41445 +Ref: Global and local cycling-Footnote-144149 +Ref: Global and local cycling-Footnote-244211 +Node: Initial visibility44462 +Ref: Initial visibility-Footnote-145533 +Node: Catching invisible edits45722 +Node: Motion46194 +Node: Structure editing47561 +Node: Sparse trees54353 +Ref: Sparse trees-Footnote-156927 +Ref: Sparse trees-Footnote-257042 +Node: Plain lists57117 +Ref: Plain lists-Footnote-164685 +Ref: Plain lists-Footnote-265047 +Ref: Plain lists-Footnote-365147 +Ref: Plain lists-Footnote-465414 +Ref: Plain lists-Footnote-565591 +Ref: Plain lists-Footnote-665695 +Ref: Plain lists-Footnote-765801 +Node: Drawers65871 +Ref: Drawers-Footnote-167772 +Node: Blocks67920 +Node: Footnotes68485 +Ref: Footnotes-Footnote-172512 +Ref: Footnotes-Footnote-272617 +Node: Orgstruct mode72702 +Node: Org syntax74359 +Node: Tables75365 +Node: Built-in table editor76010 +Ref: Built-in table editor-Footnote-185627 +Node: Column width and alignment85735 +Ref: Column width and alignment-Footnote-188341 +Node: Column groups88438 +Node: Orgtbl mode90033 +Node: The spreadsheet90848 +Node: References92314 +Ref: References-Footnote-199274 +Ref: References-Footnote-299504 +Ref: References-Footnote-399785 +Ref: References-Footnote-499902 +Node: Formula syntax for Calc100220 +Ref: Formula syntax for Calc-Footnote-1105559 +Node: Formula syntax for Lisp105903 +Node: Durations and time values107683 +Node: Field and range formulas109107 +Node: Column formulas111570 +Node: Lookup functions113696 +Node: Editing and debugging formulas115738 +Ref: Using multiple #+TBLFM lines120078 +Ref: Editing and debugging formulas-Footnote-1121371 +Node: Updating the table121519 +Node: Advanced features122891 +Ref: Advanced features-Footnote-1127503 +Node: Org-Plot127609 +Node: Hyperlinks131998 +Node: Link format132755 +Node: Internal links134054 +Ref: Internal links-Footnote-1136395 +Ref: Internal links-Footnote-2136639 +Node: Radio targets136785 +Node: External links137464 +Ref: External links-Footnote-1141512 +Ref: External links-Footnote-2141948 +Node: Handling links142212 +Ref: Handling links-Footnote-1150222 +Ref: Handling links-Footnote-2150382 +Ref: Handling links-Footnote-3150584 +Ref: Handling links-Footnote-4150881 +Ref: Handling links-Footnote-5151139 +Ref: Handling links-Footnote-6151266 +Ref: Handling links-Footnote-7151342 +Node: Using links outside Org151438 +Node: Link abbreviations151923 +Node: Search options154755 +Ref: Search options-Footnote-1156697 +Node: Custom searches156778 +Node: TODO items157808 +Ref: TODO items-Footnote-1158916 +Node: TODO basics159030 +Node: TODO extensions161918 +Node: Workflow states162952 +Ref: Workflow states-Footnote-1164267 +Node: TODO types164360 +Ref: TODO types-Footnote-1165988 +Node: Multiple sets in one file166061 +Node: Fast access to TODO states168016 +Ref: Fast access to TODO states-Footnote-1168899 +Ref: Fast access to TODO states-Footnote-2168987 +Node: Per-file keywords169284 +Ref: Per-file keywords-Footnote-1170672 +Node: Faces for TODO keywords170881 +Node: TODO dependencies171937 +Node: Progress logging174306 +Node: Closing items175018 +Ref: Closing items-Footnote-1176017 +Ref: Closing items-Footnote-2176090 +Node: Tracking TODO state changes176168 +Ref: Tracking TODO state changes-Footnote-1179276 +Ref: Tracking TODO state changes-Footnote-2179335 +Ref: Tracking TODO state changes-Footnote-3179492 +Node: Tracking your habits179789 +Node: Priorities184114 +Ref: Priorities-Footnote-1186155 +Node: Breaking down tasks186228 +Ref: Breaking down tasks-Footnote-1188243 +Node: Checkboxes188343 +Ref: Checkboxes-Footnote-1193063 +Ref: Checkboxes-Footnote-2193191 +Ref: Checkboxes-Footnote-3193369 +Node: Tags193493 +Node: Tag inheritance194569 +Ref: Tag inheritance-Footnote-1196430 +Ref: Tag inheritance-Footnote-2196534 +Node: Setting tags196660 +Ref: Setting tags-Footnote-1203162 +Node: Tag hierarchy203245 +Node: Tag searches206714 +Node: Properties and columns208032 +Node: Property syntax209488 +Node: Special properties213868 +Node: Property searches215521 +Node: Property inheritance216966 +Node: Column view218833 +Node: Defining columns220077 +Node: Scope of column definitions220455 +Node: Column attributes221368 +Ref: Column attributes-Footnote-1226284 +Ref: Column attributes-Footnote-2226408 +Ref: Column attributes-Footnote-3226613 +Ref: Column attributes-Footnote-4226867 +Node: Using column view227001 +Node: Capturing column view229995 +Ref: Capturing column view-Footnote-1233083 +Node: Property API233220 +Node: Dates and times233574 +Node: Timestamps234481 +Ref: Timestamps-Footnote-1236891 +Ref: Timestamps-Footnote-2237077 +Ref: Timestamps-Footnote-3237208 +Node: Creating timestamps238013 +Node: The date/time prompt240858 +Ref: The date/time prompt-Footnote-1245489 +Ref: The date/time prompt-Footnote-2245660 +Ref: The date/time prompt-Footnote-3245772 +Node: Custom time format245870 +Node: Deadlines and scheduling247621 +Ref: Deadlines and scheduling-Footnote-1251135 +Node: Inserting deadline/schedule251296 +Ref: Inserting deadline/schedule-Footnote-1253135 +Ref: Inserting deadline/schedule-Footnote-2253259 +Node: Repeated tasks253383 +Ref: Repeated tasks-Footnote-1257858 +Ref: Repeated tasks-Footnote-2258115 +Node: Clocking work time258338 +Ref: Clocking work time-Footnote-1259526 +Ref: Clocking work time-Footnote-2259678 +Node: Clocking commands259820 +Ref: Clocking commands-Footnote-1264844 +Ref: Clocking commands-Footnote-2264959 +Ref: Clocking commands-Footnote-3265013 +Ref: Clocking commands-Footnote-4265075 +Node: The clock table265157 +Ref: The clock table-Footnote-1272762 +Ref: The clock table-Footnote-2272860 +Node: Resolving idle time272986 +Ref: Resolving idle time-Footnote-1276917 +Node: Effort estimates277401 +Ref: Effort estimates-Footnote-1280193 +Node: Timers280300 +Node: Capture - Refile - Archive282611 +Node: Capture283601 +Node: Setting up capture284702 +Ref: Setting up capture-Footnote-1285110 +Node: Using capture285180 +Node: Capture templates287646 +Node: Template elements289645 +Ref: Template elements-Footnote-1296417 +Ref: Template elements-Footnote-2296750 +Node: Template expansion296937 +Ref: Template expansion-Footnote-1301053 +Ref: Template expansion-Footnote-2301144 +Ref: Template expansion-Footnote-3301355 +Ref: Template expansion-Footnote-4301541 +Node: Templates in contexts301643 +Node: Attachments302479 +Ref: Attachments-Footnote-1306012 +Node: RSS feeds306166 +Node: Protocols307679 +Node: store-link protocol309144 +Node: capture protocol309976 +Node: open-source protocol311118 +Node: Refile and copy314265 +Ref: Refile and copy-Footnote-1316733 +Node: Archiving316845 +Node: Moving subtrees317551 +Node: Internal archiving319598 +Node: Agenda views322289 +Node: Agenda files324646 +Ref: Agenda files-Footnote-1327499 +Ref: Agenda files-Footnote-2327648 +Node: Agenda dispatcher327849 +Ref: Agenda dispatcher-Footnote-1330753 +Ref: Agenda dispatcher-Footnote-2330851 +Node: Built-in agenda views330957 +Node: Weekly/daily agenda331541 +Ref: Weekly/daily agenda-Footnote-1337381 +Ref: Weekly/daily agenda-Footnote-2337612 +Node: Global TODO list337799 +Node: Matching tags and properties340375 +Node: Search view347717 +Node: Stuck projects349076 +Ref: Stuck projects-Footnote-1351157 +Node: Presentation and sorting351187 +Node: Categories352152 +Node: Time-of-day specifications352895 +Ref: Time-of-day specifications-Footnote-1354930 +Node: Sorting agenda items355053 +Node: Filtering/limiting agenda items356646 +Ref: Filtering/limiting agenda items-Footnote-1363938 +Node: Agenda commands364358 +Ref: Agenda commands-Footnote-1385792 +Ref: Agenda commands-Footnote-2385873 +Ref: Agenda commands-Footnote-3385996 +Ref: Agenda commands-Footnote-4386100 +Node: Custom agenda views386187 +Node: Storing searches386828 +Ref: Storing searches-Footnote-1389863 +Ref: Storing searches-Footnote-2389980 +Node: Block agenda390232 +Node: Setting options391514 +Node: Exporting agenda views395160 +Ref: Exporting agenda views-Footnote-1400131 +Ref: Exporting agenda views-Footnote-2400254 +Ref: Exporting agenda views-Footnote-3400414 +Ref: Exporting agenda views-Footnote-4400601 +Node: Agenda column view400683 +Node: Markup403803 +Node: Paragraphs404790 +Node: Emphasis and monospace405959 +Node: Horizontal rules406830 +Node: Images and tables407081 +Node: Literal examples408808 +Ref: Literal examples-Footnote-1413417 +Ref: Literal examples-Footnote-2413941 +Ref: Literal examples-Footnote-3414114 +Ref: Literal examples-Footnote-4414301 +Ref: Literal examples-Footnote-5414571 +Node: Special symbols414669 +Ref: Special symbols-Footnote-1416677 +Ref: Special symbols-Footnote-2416844 +Node: Subscripts and superscripts416937 +Node: Embedded LaTeX418073 +Ref: Embedded LaTeX-Footnote-1418886 +Node: LaTeX fragments419082 +Ref: LaTeX fragments-Footnote-1421195 +Node: Previewing LaTeX fragments421430 +Ref: Previewing LaTeX fragments-Footnote-1422892 +Node: CDLaTeX mode423146 +Ref: CDLaTeX mode-Footnote-1425717 +Node: Exporting425869 +Node: The export dispatcher428541 +Node: Export settings431176 +Ref: Export settings-Footnote-1439281 +Ref: Export settings-Footnote-2439393 +Node: Table of contents439499 +Node: Include files441391 +Ref: Include files-Footnote-1444252 +Node: Macro replacement444430 +Ref: Macro replacement-Footnote-1447321 +Node: Comment lines447538 +Ref: Comment lines-Footnote-1448368 +Node: ASCII/Latin-1/UTF-8 export448468 +Node: Beamer export451487 +Node: Beamer export commands452257 +Node: Beamer specific export settings452944 +Node: Sectioning Frames and Blocks in Beamer454863 +Ref: Sectioning Frames and Blocks in Beamer-Footnote-1458174 +Node: Beamer specific syntax458335 +Node: Editing support460316 +Node: A Beamer example460804 +Node: HTML export462071 +Node: HTML Export commands463078 +Node: HTML Specific export settings463609 +Node: HTML doctypes465694 +Node: HTML preamble and postamble467853 +Node: Quoting HTML tags469043 +Node: Links in HTML export469727 +Node: Tables in HTML export471192 +Node: Images in HTML export472639 +Node: Math formatting in HTML export474124 +Ref: Math formatting in HTML export-Footnote-1475538 +Node: Text areas in HTML export475662 +Node: CSS support476815 +Ref: CSS support-Footnote-1480287 +Node: JavaScript support480467 +Node: LaTeX export483790 +Node: LaTeX export commands485526 +Ref: LaTeX export commands-Footnote-1486847 +Node: LaTeX specific export settings487055 +Node: LaTeX header and sectioning489940 +Node: Quoting LaTeX code492081 +Node: Tables in LaTeX export492862 +Node: Images in LaTeX export497402 +Ref: Images in LaTeX export-Footnote-1499932 +Node: Plain lists in LaTeX export499979 +Node: Source blocks in LaTeX export500996 +Node: Example blocks in LaTeX export502430 +Node: Special blocks in LaTeX export503138 +Node: Horizontal rules in LaTeX export504388 +Node: Markdown export504783 +Node: OpenDocument Text export506128 +Ref: OpenDocument Text export-Footnote-1507229 +Node: Pre-requisites for ODT export507373 +Node: ODT export commands507759 +Ref: x-export-to-odt507963 +Node: ODT specific export settings509127 +Node: Extending ODT export510164 +Ref: x-export-to-other-formats511049 +Ref: x-convert-to-other-formats511474 +Node: Applying custom styles511949 +Node: Links in ODT export513742 +Node: Tables in ODT export514399 +Node: Images in ODT export516389 +Node: Math formatting in ODT export519259 +Node: Working with LaTeX math snippets519720 +Ref: Working with LaTeX math snippets-Footnote-1521998 +Ref: Working with LaTeX math snippets-Footnote-2522074 +Node: Working with MathML or OpenDocument formula files522119 +Node: Labels and captions in ODT export522654 +Node: Literal examples in ODT export523926 +Node: Advanced topics in ODT export524764 +Node: Configuring a document converter525418 +Ref: x-odt-converter-capabilities526102 +Node: Working with OpenDocument style files526509 +Ref: x-factory-styles526914 +Ref: x-orgodtstyles-xml527156 +Ref: x-orgodtcontenttemplate-xml527502 +Ref: x-overriding-factory-styles528186 +Ref: x-org-odt-styles-file528457 +Ref: x-org-odt-content-template-file529423 +Node: Creating one-off styles529574 +Node: Customizing tables in ODT export531752 +Ref: Customizing tables in ODT export-Footnote-1536764 +Ref: Customizing tables in ODT export-Footnote-2536868 +Ref: Customizing tables in ODT export-Footnote-3536960 +Node: Validating OpenDocument XML537307 +Node: Org export538231 +Node: Texinfo export538987 +Node: Texinfo export commands540007 +Node: Texinfo specific export settings540622 +Node: Texinfo file header541753 +Node: Texinfo title and copyright page542717 +Node: Info directory file544079 +Node: Headings and sectioning structure544796 +Node: Indices546818 +Node: Quoting Texinfo code547854 +Node: Plain lists in Texinfo export548343 +Node: Tables in Texinfo export549698 +Node: Images in Texinfo export550189 +Node: Special blocks in Texinfo export550826 +Node: A Texinfo example551420 +Node: iCalendar export553527 +Node: Other built-in back-ends557247 +Node: Advanced configuration557863 +Node: Export in foreign buffers564677 +Node: Publishing565745 +Node: Configuration566615 +Node: Project alist567378 +Node: Sources and destinations568535 +Node: Selecting files570105 +Node: Publishing action571207 +Ref: Publishing action-Footnote-1573096 +Node: Publishing options573263 +Node: Publishing links587797 +Node: Sitemap589185 +Node: Generating an index593321 +Node: Uploading files594131 +Node: Sample configuration595939 +Node: Simple example596428 +Node: Complex example597139 +Node: Triggering publication599197 +Node: Working with source code600204 +Node: Structure of code blocks604754 +Node: Editing source code607293 +Node: Exporting code blocks610146 +Node: Extracting source code612478 +Node: Evaluating code blocks614985 +Ref: Evaluating code blocks-Footnote-1618221 +Ref: Evaluating code blocks-Footnote-2618355 +Node: Library of Babel618546 +Node: Languages619239 +Node: Header arguments621688 +Node: Using header arguments622045 +Node: System-wide header arguments622852 +Node: Language-specific header arguments623563 +Node: Header arguments in Org mode properties624093 +Node: Language-specific mode properties625594 +Node: Code block specific header arguments626426 +Node: Arguments in function calls628129 +Node: Specific header arguments628913 +Node: var631607 +Node: results638359 +Node: file642486 +Node: file-desc643187 +Node: file-ext643601 +Node: output-dir644036 +Node: dir644454 +Node: exports646677 +Node: tangle647602 +Node: mkdirp648496 +Node: comments648826 +Node: padline649845 +Node: no-expand650263 +Node: session650997 +Node: noweb652119 +Node: noweb-ref654802 +Node: noweb-sep655922 +Node: cache656234 +Node: sep658913 +Node: hlines659324 +Node: colnames660846 +Node: rownames662296 +Node: shebang663523 +Node: tangle-mode664019 +Node: eval664845 +Node: wrap665882 +Node: post666209 +Node: prologue667992 +Node: epilogue668512 +Node: Results of evaluation668778 +Node: Noweb reference syntax672627 +Node: Key bindings and useful functions674958 +Node: Batch execution677293 +Node: Miscellaneous678071 +Node: Completion678918 +Node: Easy templates681031 +Node: Speed keys682409 +Node: Code evaluation security683599 +Node: Customization686448 +Node: In-buffer settings686884 +Node: The very busy C-c C-c key696540 +Node: Clean view698543 +Ref: Clean view-Footnote-1702032 +Ref: Clean view-Footnote-2702271 +Ref: Clean view-Footnote-3702330 +Node: TTY keys702410 +Node: Interaction704107 +Node: Cooperation704506 +Node: Conflicts707300 +Node: org-crypt711927 +Node: Hacking713187 +Node: Hooks714175 +Node: Add-on packages714494 +Node: Adding hyperlink types715028 +Node: Adding export back-ends718487 +Node: Context-sensitive commands719739 +Node: Tables in arbitrary syntax720432 +Node: Radio tables722107 +Node: A LaTeX example724235 +Ref: A LaTeX example-Footnote-1728049 +Ref: A LaTeX example-Footnote-2728219 +Node: Translator functions728670 +Node: Radio lists730858 +Node: Dynamic blocks732052 +Node: Special agenda views734143 +Ref: x-agenda-skip-entry-regexp737048 +Ref: Special agenda views-Footnote-1737828 +Ref: Special agenda views-Footnote-2738035 +Node: Speeding up your agendas738167 +Node: Extracting agenda information739212 +Node: Using the property API743070 +Node: Using the mapping API746512 +Node: MobileOrg750565 +Node: Setting up the staging area752139 +Ref: Setting up the staging area-Footnote-1753353 +Ref: Setting up the staging area-Footnote-2753526 +Node: Pushing to MobileOrg753734 +Ref: Pushing to MobileOrg-Footnote-1754641 +Ref: Pushing to MobileOrg-Footnote-2754731 +Ref: Pushing to MobileOrg-Footnote-3755097 +Node: Pulling from MobileOrg755173 +Ref: Pulling from MobileOrg-Footnote-1757230 +Node: History and acknowledgments757294 +Node: GNU Free Documentation License772747 +Node: Main Index798127 +Node: Key Index896893 +Node: Command and Function Index950348 +Node: Variable Index987240 + +End Tag Table + + +Local Variables: +coding: utf-8 +End: diff --git a/elpa/org-9.1.14/org-agenda.el b/elpa/org-9.1.14/org-agenda.el new file mode 100644 index 00000000..322480cf --- /dev/null +++ b/elpa/org-9.1.14/org-agenda.el @@ -0,0 +1,10224 @@ +;;; org-agenda.el --- Dynamic task and appointment lists for Org + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file contains the code for creating and using the Agenda for Org. +;; +;; The functions `org-batch-agenda', `org-batch-agenda-csv', and +;; `org-batch-store-agenda-views' are implemented as macros to provide +;; a convenient way for extracting agenda information from the command +;; line. The Lisp does not evaluate parameters of a macro call; thus +;; it is not necessary to quote the parameters passed to one of those +;; functions. E.g. you can write: +;; +;; emacs -batch -l ~/.emacs -eval '(org-batch-agenda "a" org-agenda-span 7)' +;; +;; To export an agenda spanning 7 days. If `org-batch-agenda' would +;; have been implemented as a regular function you'd have to quote the +;; symbol org-agenda-span. Moreover: To use a symbol as parameter +;; value you would have to double quote the symbol. +;; +;; This is a hack, but it works even when running Org byte-compiled. +;; + +;;; Code: + +(require 'cl-lib) +(require 'org) +(require 'org-macs) + +(declare-function diary-add-to-list "diary-lib" + (date string specifier &optional marker globcolor literal)) +(declare-function calendar-iso-to-absolute "cal-iso" (date)) +(declare-function calendar-astro-date-string "cal-julian" (&optional date)) +(declare-function calendar-bahai-date-string "cal-bahai" (&optional date)) +(declare-function calendar-chinese-date-string "cal-china" (&optional date)) +(declare-function calendar-coptic-date-string "cal-coptic" (&optional date)) +(declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date)) +(declare-function calendar-french-date-string "cal-french" (&optional date)) +(declare-function calendar-goto-date "cal-move" (date)) +(declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date)) +(declare-function calendar-islamic-date-string "cal-islam" (&optional date)) +(declare-function calendar-iso-date-string "cal-iso" (&optional date)) +(declare-function calendar-iso-from-absolute "cal-iso" (date)) +(declare-function calendar-julian-date-string "cal-julian" (&optional date)) +(declare-function calendar-mayan-date-string "cal-mayan" (&optional date)) +(declare-function calendar-persian-date-string "cal-persia" (&optional date)) +(declare-function calendar-check-holidays "holidays" (date)) + +(declare-function org-columns-remove-overlays "org-colview" ()) +(declare-function org-datetree-find-date-create "org-datetree" + (date &optional keep-restriction)) +(declare-function org-columns-quit "org-colview" ()) +(declare-function diary-date-display-form "diary-lib" (&optional type)) +(declare-function org-mobile-write-agenda-for-mobile "org-mobile" (file)) +(declare-function org-habit-insert-consistency-graphs + "org-habit" (&optional line)) +(declare-function org-is-habit-p "org-habit" (&optional pom)) +(declare-function org-habit-parse-todo "org-habit" (&optional pom)) +(declare-function org-habit-get-priority "org-habit" (habit &optional moment)) +(declare-function org-agenda-columns "org-colview" ()) +(declare-function org-add-archive-files "org-archive" (files)) +(declare-function org-capture "org-capture" (&optional goto keys)) + +(defvar calendar-mode-map) +(defvar org-clock-current-task) +(defvar org-current-tag-alist) +(defvar org-mobile-force-id-on-agenda-items) +(defvar org-habit-show-habits) +(defvar org-habit-show-habits-only-for-today) +(defvar org-habit-show-all-today) + +;; Defined somewhere in this file, but used before definition. +(defvar org-agenda-buffer-name "*Org Agenda*") +(defvar org-agenda-overriding-header nil) +(defvar org-agenda-title-append nil) +(with-no-warnings (defvar entry)) ;; unprefixed, from calendar.el +(with-no-warnings (defvar date)) ;; unprefixed, from calendar.el +(defvar original-date) ; dynamically scoped, calendar.el does scope this + +(defvar org-agenda-undo-list nil + "List of undoable operations in the agenda since last refresh.") +(defvar org-agenda-pending-undo-list nil + "In a series of undo commands, this is the list of remaining undo items.") + +(defcustom org-agenda-confirm-kill 1 + "When set, remote killing from the agenda buffer needs confirmation. +When t, a confirmation is always needed. When a number N, confirmation is +only needed when the text to be killed contains more than N non-white lines." + :group 'org-agenda + :type '(choice + (const :tag "Never" nil) + (const :tag "Always" t) + (integer :tag "When more than N lines"))) + +(defcustom org-agenda-compact-blocks nil + "Non-nil means make the block agenda more compact. +This is done globally by leaving out lines like the agenda span +name and week number or the separator lines." + :group 'org-agenda + :type 'boolean) + +(defcustom org-agenda-block-separator ?= + "The separator between blocks in the agenda. +If this is a string, it will be used as the separator, with a newline added. +If it is a character, it will be repeated to fill the window width. +If nil the separator is disabled. In `org-agenda-custom-commands' this +addresses the separator between the current and the previous block." + :group 'org-agenda + :type '(choice + (const :tag "Disabled" nil) + (character) + (string))) + +(defgroup org-agenda-export nil + "Options concerning exporting agenda views in Org mode." + :tag "Org Agenda Export" + :group 'org-agenda) + +(defcustom org-agenda-with-colors t + "Non-nil means use colors in agenda views." + :group 'org-agenda-export + :type 'boolean) + +(defcustom org-agenda-exporter-settings nil + "Alist of variable/value pairs that should be active during agenda export. +This is a good place to set options for ps-print and for htmlize. +Note that the way this is implemented, the values will be evaluated +before assigned to the variables. So make sure to quote values you do +*not* want evaluated, for example + + (setq org-agenda-exporter-settings + \\='((ps-print-color-p \\='black-white)))" + :group 'org-agenda-export + :type '(repeat + (list + (variable) + (sexp :tag "Value")))) + +(defcustom org-agenda-before-write-hook '(org-agenda-add-entry-text) + "Hook run in a temporary buffer before writing the agenda to an export file. +A useful function for this hook is `org-agenda-add-entry-text'." + :group 'org-agenda-export + :type 'hook + :options '(org-agenda-add-entry-text)) + +(defcustom org-agenda-add-entry-text-maxlines 0 + "Maximum number of entry text lines to be added to agenda. +This is only relevant when `org-agenda-add-entry-text' is part of +`org-agenda-before-write-hook', which is the default. +When this is 0, nothing will happen. When it is greater than 0, it +specifies the maximum number of lines that will be added for each entry +that is listed in the agenda view. + +Note that this variable is not used during display, only when exporting +the agenda. For agenda display, see the variables `org-agenda-entry-text-mode' +and `org-agenda-entry-text-maxlines'." + :group 'org-agenda + :type 'integer) + +(defcustom org-agenda-add-entry-text-descriptive-links t + "Non-nil means export org-links as descriptive links in agenda added text. +This variable applies to the text added to the agenda when +`org-agenda-add-entry-text-maxlines' is larger than 0. +When this variable nil, the URL will (also) be shown." + :group 'org-agenda + :type 'boolean) + +(defcustom org-agenda-export-html-style nil + "The style specification for exported HTML Agenda files. +If this variable contains a string, it will replace the default + +or, if you want to keep the style in a file, + + + +As the value of this option simply gets inserted into the HTML header, +you can \"misuse\" it to also add other text to the header." + :group 'org-agenda-export + :group 'org-export-html + :type '(choice + (const nil) + (string))) + +(defcustom org-agenda-persistent-filter nil + "When set, keep filters from one agenda view to the next." + :group 'org-agenda + :type 'boolean) + +(defgroup org-agenda-custom-commands nil + "Options concerning agenda views in Org mode." + :tag "Org Agenda Custom Commands" + :group 'org-agenda) + +(defconst org-sorting-choice + '(choice + (const time-up) (const time-down) + (const timestamp-up) (const timestamp-down) + (const scheduled-up) (const scheduled-down) + (const deadline-up) (const deadline-down) + (const ts-up) (const ts-down) + (const tsia-up) (const tsia-down) + (const category-keep) (const category-up) (const category-down) + (const tag-down) (const tag-up) + (const priority-up) (const priority-down) + (const todo-state-up) (const todo-state-down) + (const effort-up) (const effort-down) + (const habit-up) (const habit-down) + (const alpha-up) (const alpha-down) + (const user-defined-up) (const user-defined-down)) + "Sorting choices.") + +;; Keep custom values for `org-agenda-filter-preset' compatible with +;; the new variable `org-agenda-tag-filter-preset'. +(defvaralias 'org-agenda-filter-preset 'org-agenda-tag-filter-preset) +(defvaralias 'org-agenda-filter 'org-agenda-tag-filter) + +(defvar org-agenda-entry-types '(:deadline :scheduled :timestamp :sexp) + "List of types searched for when creating the daily/weekly agenda. +This variable is a list of symbols that controls the types of +items that appear in the daily/weekly agenda. Allowed symbols in this +list are are + + :timestamp List items containing a date stamp or date range matching + the selected date. This includes sexp entries in angular + brackets. + + :sexp List entries resulting from plain diary-like sexps. + + :deadline List deadline due on that date. When the date is today, + also list any deadlines past due, or due within + `org-deadline-warning-days'. + + :deadline* Same as above, but only include the deadline if it has an + hour specification as [h]h:mm. + + :scheduled List all items which are scheduled for the given date. + The diary for *today* also contains items which were + scheduled earlier and are not yet marked DONE. + + :scheduled* Same as above, but only include the scheduled item if it + has an hour specification as [h]h:mm. + +By default, all four non-starred types are turned on. + +When :scheduled* or :deadline* are included, :schedule or :deadline +will be ignored. + +Never set this variable globally using `setq', because then it +will apply to all future agenda commands. Instead, bind it with +`let' to scope it dynamically into the agenda-constructing +command. A good way to set it is through options in +`org-agenda-custom-commands'. For a more flexible (though +somewhat less efficient) way of determining what is included in +the daily/weekly agenda, see `org-agenda-skip-function'.") + +(defconst org-agenda-custom-commands-local-options + `(repeat :tag "Local settings for this command. Remember to quote values" + (choice :tag "Setting" + (list :tag "Heading for this block" + (const org-agenda-overriding-header) + (string :tag "Headline")) + (list :tag "Files to be searched" + (const org-agenda-files) + (list + (const :format "" quote) + (repeat (file)))) + (list :tag "Sorting strategy" + (const org-agenda-sorting-strategy) + (list + (const :format "" quote) + (repeat + ,org-sorting-choice))) + (list :tag "Prefix format" + (const org-agenda-prefix-format :value " %-12:c%?-12t% s") + (string)) + (list :tag "Number of days in agenda" + (const org-agenda-span) + (list + (const :format "" quote) + (choice (const :tag "Day" day) + (const :tag "Week" week) + (const :tag "Fortnight" fortnight) + (const :tag "Month" month) + (const :tag "Year" year) + (integer :tag "Custom")))) + (list :tag "Fixed starting date" + (const org-agenda-start-day) + (string :value "2007-11-01")) + (list :tag "Start on day of week" + (const org-agenda-start-on-weekday) + (choice :value 1 + (const :tag "Today" nil) + (integer :tag "Weekday No."))) + (list :tag "Include data from diary" + (const org-agenda-include-diary) + (boolean)) + (list :tag "Deadline Warning days" + (const org-deadline-warning-days) + (integer :value 1)) + (list :tag "Category filter preset" + (const org-agenda-category-filter-preset) + (list + (const :format "" quote) + (repeat + (string :tag "+category or -category")))) + (list :tag "Tags filter preset" + (const org-agenda-tag-filter-preset) + (list + (const :format "" quote) + (repeat + (string :tag "+tag or -tag")))) + (list :tag "Effort filter preset" + (const org-agenda-effort-filter-preset) + (list + (const :format "" quote) + (repeat + (string :tag "+=10 or -=10 or +<10 or ->10")))) + (list :tag "Regexp filter preset" + (const org-agenda-regexp-filter-preset) + (list + (const :format "" quote) + (repeat + (string :tag "+regexp or -regexp")))) + (list :tag "Set daily/weekly entry types" + (const org-agenda-entry-types) + (list + (const :format "" quote) + (set :greedy t :value ,org-agenda-entry-types + (const :deadline) + (const :scheduled) + (const :deadline*) + (const :scheduled*) + (const :timestamp) + (const :sexp)))) + (list :tag "Standard skipping condition" + :value (org-agenda-skip-function '(org-agenda-skip-entry-if)) + (const org-agenda-skip-function) + (list + (const :format "" quote) + (list + (choice + :tag "Skipping range" + (const :tag "Skip entry" org-agenda-skip-entry-if) + (const :tag "Skip subtree" org-agenda-skip-subtree-if)) + (repeat :inline t :tag "Conditions for skipping" + (choice + :tag "Condition type" + (list :tag "Regexp matches" :inline t + (const :format "" regexp) + (regexp)) + (list :tag "Regexp does not match" :inline t + (const :format "" notregexp) + (regexp)) + (list :tag "TODO state is" :inline t + (const todo) + (choice + (const :tag "Any not-done state" todo) + (const :tag "Any done state" done) + (const :tag "Any state" any) + (list :tag "Keyword list" + (const :format "" quote) + (repeat (string :tag "Keyword"))))) + (list :tag "TODO state is not" :inline t + (const nottodo) + (choice + (const :tag "Any not-done state" todo) + (const :tag "Any done state" done) + (const :tag "Any state" any) + (list :tag "Keyword list" + (const :format "" quote) + (repeat (string :tag "Keyword"))))) + (const :tag "scheduled" scheduled) + (const :tag "not scheduled" notscheduled) + (const :tag "deadline" deadline) + (const :tag "no deadline" notdeadline) + (const :tag "timestamp" timestamp) + (const :tag "no timestamp" nottimestamp)))))) + (list :tag "Non-standard skipping condition" + :value (org-agenda-skip-function) + (const org-agenda-skip-function) + (sexp :tag "Function or form (quoted!)")) + (list :tag "Any variable" + (variable :tag "Variable") + (sexp :tag "Value (sexp)")))) + "Selection of examples for agenda command settings. +This will be spliced into the custom type of +`org-agenda-custom-commands'.") + + +(defcustom org-agenda-custom-commands + '(("n" "Agenda and all TODOs" ((agenda "") (alltodo "")))) + "Custom commands for the agenda. +\\ +These commands will be offered on the splash screen displayed by the +agenda dispatcher `\\[org-agenda]'. Each entry is a list like this: + + (key desc type match settings files) + +key The key (one or more characters as a string) to be associated + with the command. +desc A description of the command, when omitted or nil, a default + description is built using MATCH. +type The command type, any of the following symbols: + agenda The daily/weekly agenda. + todo Entries with a specific TODO keyword, in all agenda files. + search Entries containing search words entry or headline. + tags Tags/Property/TODO match in all agenda files. + tags-todo Tags/P/T match in all agenda files, TODO entries only. + todo-tree Sparse tree of specific TODO keyword in *current* file. + tags-tree Sparse tree with all tags matches in *current* file. + occur-tree Occur sparse tree for *current* file. + ... A user-defined function. +match What to search for: + - a single keyword for TODO keyword searches + - a tags match expression for tags searches + - a word search expression for text searches. + - a regular expression for occur searches + For all other commands, this should be the empty string. +settings A list of option settings, similar to that in a let form, so like + this: ((opt1 val1) (opt2 val2) ...). The values will be + evaluated at the moment of execution, so quote them when needed. +files A list of files to write the produced agenda buffer to with + the command `org-store-agenda-views'. + If a file name ends in \".html\", an HTML version of the buffer + is written out. If it ends in \".ps\", a postscript version is + produced. Otherwise, only the plain text is written to the file. + +You can also define a set of commands, to create a composite agenda buffer. +In this case, an entry looks like this: + + (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files) + +where + +desc A description string to be displayed in the dispatcher menu. +cmd An agenda command, similar to the above. However, tree commands + are not allowed, but instead you can get agenda and global todo list. + So valid commands for a set are: + (agenda \"\" settings) + (alltodo \"\" settings) + (stuck \"\" settings) + (todo \"match\" settings files) + (search \"match\" settings files) + (tags \"match\" settings files) + (tags-todo \"match\" settings files) + +Each command can carry a list of options, and another set of options can be +given for the whole set of commands. Individual command options take +precedence over the general options. + +When using several characters as key to a command, the first characters +are prefix commands. For the dispatcher to display useful information, you +should provide a description for the prefix, like + + (setq org-agenda-custom-commands + \\='((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\" + (\"hl\" tags \"+HOME+Lisa\") + (\"hp\" tags \"+HOME+Peter\") + (\"hk\" tags \"+HOME+Kim\")))" + :group 'org-agenda-custom-commands + :type `(repeat + (choice :value ("x" "Describe command here" tags "" nil) + (list :tag "Single command" + (string :tag "Access Key(s) ") + (option (string :tag "Description")) + (choice + (const :tag "Agenda" agenda) + (const :tag "TODO list" alltodo) + (const :tag "Search words" search) + (const :tag "Stuck projects" stuck) + (const :tag "Tags/Property match (all agenda files)" tags) + (const :tag "Tags/Property match of TODO entries (all agenda files)" tags-todo) + (const :tag "TODO keyword search (all agenda files)" todo) + (const :tag "Tags sparse tree (current buffer)" tags-tree) + (const :tag "TODO keyword tree (current buffer)" todo-tree) + (const :tag "Occur tree (current buffer)" occur-tree) + (sexp :tag "Other, user-defined function")) + (string :tag "Match (only for some commands)") + ,org-agenda-custom-commands-local-options + (option (repeat :tag "Export" (file :tag "Export to")))) + (list :tag "Command series, all agenda files" + (string :tag "Access Key(s)") + (string :tag "Description ") + (repeat :tag "Component" + (choice + (list :tag "Agenda" + (const :format "" agenda) + (const :tag "" :format "" "") + ,org-agenda-custom-commands-local-options) + (list :tag "TODO list (all keywords)" + (const :format "" alltodo) + (const :tag "" :format "" "") + ,org-agenda-custom-commands-local-options) + (list :tag "Search words" + (const :format "" search) + (string :tag "Match") + ,org-agenda-custom-commands-local-options) + (list :tag "Stuck projects" + (const :format "" stuck) + (const :tag "" :format "" "") + ,org-agenda-custom-commands-local-options) + (list :tag "Tags search" + (const :format "" tags) + (string :tag "Match") + ,org-agenda-custom-commands-local-options) + (list :tag "Tags search, TODO entries only" + (const :format "" tags-todo) + (string :tag "Match") + ,org-agenda-custom-commands-local-options) + (list :tag "TODO keyword search" + (const :format "" todo) + (string :tag "Match") + ,org-agenda-custom-commands-local-options) + (list :tag "Other, user-defined function" + (symbol :tag "function") + (string :tag "Match") + ,org-agenda-custom-commands-local-options))) + + (repeat :tag "Settings for entire command set" + (list (variable :tag "Any variable") + (sexp :tag "Value"))) + (option (repeat :tag "Export" (file :tag "Export to")))) + (cons :tag "Prefix key documentation" + (string :tag "Access Key(s)") + (string :tag "Description "))))) + +(defcustom org-agenda-query-register ?o + "The register holding the current query string. +The purpose of this is that if you construct a query string interactively, +you can then use it to define a custom command." + :group 'org-agenda-custom-commands + :type 'character) + +(defcustom org-stuck-projects + '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "") + "How to identify stuck projects. +This is a list of four items: +1. A tags/todo/property matcher string that is used to identify a project. + See the manual for a description of tag and property searches. + The entire tree below a headline matched by this is considered one project. +2. A list of TODO keywords identifying non-stuck projects. + If the project subtree contains any headline with one of these todo + keywords, the project is considered to be not stuck. If you specify + \"*\" as a keyword, any TODO keyword will mark the project unstuck. +3. A list of tags identifying non-stuck projects. + If the project subtree contains any headline with one of these tags, + the project is considered to be not stuck. If you specify \"*\" as + a tag, any tag will mark the project unstuck. Note that this is about + the explicit presence of a tag somewhere in the subtree, inherited + tags do not count here. If inherited tags make a project not stuck, + use \"-TAG\" in the tags part of the matcher under (1.) above. +4. An arbitrary regular expression matching non-stuck projects. + +If the project turns out to be not stuck, search continues also in the +subtree to see if any of the subtasks have project status. + +See also the variable `org-tags-match-list-sublevels' which applies +to projects matched by this search as well. + +After defining this variable, you may use `org-agenda-list-stuck-projects' +\(bound to `\\[org-agenda] #') to produce the list." + :group 'org-agenda-custom-commands + :type '(list + (string :tag "Tags/TODO match to identify a project") + (repeat :tag "Projects are *not* stuck if they have an entry with \ +TODO keyword any of" (string)) + (repeat :tag "Projects are *not* stuck if they have an entry with \ +TAG being any of" (string)) + (regexp :tag "Projects are *not* stuck if this regexp matches inside \ +the subtree"))) + +(defgroup org-agenda-skip nil + "Options concerning skipping parts of agenda files." + :tag "Org Agenda Skip" + :group 'org-agenda) + +(defcustom org-agenda-skip-function-global nil + "Function to be called at each match during agenda construction. +If this function returns nil, the current match should not be skipped. +If the function decided to skip an agenda match, is must return the +buffer position from which the search should be continued. +This may also be a Lisp form, which will be evaluated. + +This variable will be applied to every agenda match, including +tags/property searches and TODO lists. So try to make the test function +do its checking as efficiently as possible. To implement a skipping +condition just for specific agenda commands, use the variable +`org-agenda-skip-function' which can be set in the options section +of custom agenda commands." + :group 'org-agenda-skip + :type 'sexp) + +(defgroup org-agenda-daily/weekly nil + "Options concerning the daily/weekly agenda." + :tag "Org Agenda Daily/Weekly" + :group 'org-agenda) +(defgroup org-agenda-todo-list nil + "Options concerning the global todo list agenda view." + :tag "Org Agenda Todo List" + :group 'org-agenda) +(defgroup org-agenda-match-view nil + "Options concerning the general tags/property/todo match agenda view." + :tag "Org Agenda Match View" + :group 'org-agenda) +(defgroup org-agenda-search-view nil + "Options concerning the search agenda view." + :tag "Org Agenda Search View" + :group 'org-agenda) + +(defvar org-agenda-archives-mode nil + "Non-nil means the agenda will include archived items. +If this is the symbol `trees', trees in the selected agenda scope +that are marked with the ARCHIVE tag will be included anyway. When this is +t, also all archive files associated with the current selection of agenda +files will be included.") + +(defcustom org-agenda-restriction-lock-highlight-subtree t + "Non-nil means highlight the whole subtree when restriction is active. +Otherwise only highlight the headline. Highlighting the whole subtree is +useful to ensure no edits happen beyond the restricted region." + :group 'org-agenda + :type 'boolean) + +(defcustom org-agenda-skip-comment-trees t + "Non-nil means skip trees that start with the COMMENT keyword. +When nil, these trees are also scanned by agenda commands." + :group 'org-agenda-skip + :type 'boolean) + +(defcustom org-agenda-todo-list-sublevels t + "Non-nil means check also the sublevels of a TODO entry for TODO entries. +When nil, the sublevels of a TODO entry are not checked, resulting in +potentially much shorter TODO lists." + :group 'org-agenda-skip + :group 'org-agenda-todo-list + :type 'boolean) + +(defcustom org-agenda-todo-ignore-with-date nil + "Non-nil means don't show entries with a date in the global todo list. +You can use this if you prefer to mark mere appointments with a TODO keyword, +but don't want them to show up in the TODO list. +When this is set, it also covers deadlines and scheduled items, the settings +of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines' +will be ignored. +See also the variable `org-agenda-tags-todo-honor-ignore-options'." + :group 'org-agenda-skip + :group 'org-agenda-todo-list + :type 'boolean) + +(defcustom org-agenda-todo-ignore-timestamp nil + "Non-nil means don't show entries with a timestamp. +This applies when creating the global todo list. +Valid values are: + +past Don't show entries for today or in the past. + +future Don't show entries with a timestamp in the future. + The idea behind this is that if it has a future + timestamp, you don't want to think about it until the + date. + +all Don't show any entries with a timestamp in the global todo list. + The idea behind this is that by setting a timestamp, you + have already \"taken care\" of this item. + +This variable can also have an integer as a value. If positive (N), +todos with a timestamp N or more days in the future will be ignored. If +negative (-N), todos with a timestamp N or more days in the past will be +ignored. If 0, todos with a timestamp either today or in the future will +be ignored. For example, a value of -1 will exclude todos with a +timestamp in the past (yesterday or earlier), while a value of 7 will +exclude todos with a timestamp a week or more in the future. + +See also `org-agenda-todo-ignore-with-date'. +See also the variable `org-agenda-tags-todo-honor-ignore-options' if you want +to make his option also apply to the tags-todo list." + :group 'org-agenda-skip + :group 'org-agenda-todo-list + :version "24.1" + :type '(choice + (const :tag "Ignore future timestamp todos" future) + (const :tag "Ignore past or present timestamp todos" past) + (const :tag "Ignore all timestamp todos" all) + (const :tag "Show timestamp todos" nil) + (integer :tag "Ignore if N or more days in past(-) or future(+)."))) + +(defcustom org-agenda-todo-ignore-scheduled nil + "Non-nil means, ignore some scheduled TODO items when making TODO list. +This applies when creating the global todo list. +Valid values are: + +past Don't show entries scheduled today or in the past. + +future Don't show entries scheduled in the future. + The idea behind this is that by scheduling it, you don't want to + think about it until the scheduled date. + +all Don't show any scheduled entries in the global todo list. + The idea behind this is that by scheduling it, you have already + \"taken care\" of this item. + +t Same as `all', for backward compatibility. + +This variable can also have an integer as a value. See +`org-agenda-todo-ignore-timestamp' for more details. + +See also `org-agenda-todo-ignore-with-date'. +See also the variable `org-agenda-tags-todo-honor-ignore-options' if you want +to make his option also apply to the tags-todo list." + :group 'org-agenda-skip + :group 'org-agenda-todo-list + :type '(choice + (const :tag "Ignore future-scheduled todos" future) + (const :tag "Ignore past- or present-scheduled todos" past) + (const :tag "Ignore all scheduled todos" all) + (const :tag "Ignore all scheduled todos (compatibility)" t) + (const :tag "Show scheduled todos" nil) + (integer :tag "Ignore if N or more days in past(-) or future(+)."))) + +(defcustom org-agenda-todo-ignore-deadlines nil + "Non-nil means ignore some deadline TODO items when making TODO list. + +There are different motivations for using different values, please think +carefully when configuring this variable. + +This applies when creating the global TODO list. + +Valid values are: + +near Don't show near deadline entries. A deadline is near when it is + closer than `org-deadline-warning-days' days. The idea behind this + is that such items will appear in the agenda anyway. + +far Don't show TODO entries where a deadline has been defined, but + is not going to happen anytime soon. This is useful if you want to use + the TODO list to figure out what to do now. + +past Don't show entries with a deadline timestamp for today or in the past. + +future Don't show entries with a deadline timestamp in the future, not even + when they become `near' ones. Use it with caution. + +all Ignore all TODO entries that do have a deadline. + +t Same as `near', for backward compatibility. + +This variable can also have an integer as a value. See +`org-agenda-todo-ignore-timestamp' for more details. + +See also `org-agenda-todo-ignore-with-date'. +See also the variable `org-agenda-tags-todo-honor-ignore-options' if you want +to make his option also apply to the tags-todo list." + :group 'org-agenda-skip + :group 'org-agenda-todo-list + :type '(choice + (const :tag "Ignore near deadlines" near) + (const :tag "Ignore near deadlines (compatibility)" t) + (const :tag "Ignore far deadlines" far) + (const :tag "Ignore all TODOs with a deadlines" all) + (const :tag "Show all TODOs, even if they have a deadline" nil) + (integer :tag "Ignore if N or more days in past(-) or future(+)."))) + +(defcustom org-agenda-todo-ignore-time-comparison-use-seconds nil + "Time unit to use when possibly ignoring an agenda item. + +See the docstring of various `org-agenda-todo-ignore-*' options. +The default is to compare time stamps using days. An item is thus +considered to be in the future if it is at least one day after today. +Non-nil means to compare time stamps using seconds. An item is then +considered future if it has a time value later than current time." + :group 'org-agenda-skip + :group 'org-agenda-todo-list + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "Compare time with days" nil) + (const :tag "Compare time with seconds" t))) + +(defcustom org-agenda-tags-todo-honor-ignore-options nil + "Non-nil means honor todo-list ignores options also in tags-todo search. +The variables + `org-agenda-todo-ignore-with-date', + `org-agenda-todo-ignore-timestamp', + `org-agenda-todo-ignore-scheduled', + `org-agenda-todo-ignore-deadlines' +make the global TODO list skip entries that have time stamps of certain +kinds. If this option is set, the same options will also apply for the +tags-todo search, which is the general tags/property matcher +restricted to unfinished TODO entries only." + :group 'org-agenda-skip + :group 'org-agenda-todo-list + :group 'org-agenda-match-view + :type 'boolean) + +(defcustom org-agenda-skip-scheduled-if-done nil + "Non-nil means don't show scheduled items in agenda when they are done. +This is relevant for the daily/weekly agenda, not for the TODO list. It +applies only to the actual date of the scheduling. Warnings about an item +with a past scheduling dates are always turned off when the item is DONE." + :group 'org-agenda-skip + :group 'org-agenda-daily/weekly + :type 'boolean) + +(defcustom org-agenda-skip-scheduled-if-deadline-is-shown nil + "Non-nil means skip scheduling line if same entry shows because of deadline. + +In the agenda of today, an entry can show up multiple times +because it is both scheduled and has a nearby deadline, and maybe +a plain time stamp as well. + +When this variable is nil, the entry will be shown several times. + +When set to t, then only the deadline is shown and the fact that +the entry is scheduled today or was scheduled previously is not +shown. + +When set to the symbol `not-today', skip scheduled previously, +but not scheduled today. + +When set to the symbol `repeated-after-deadline', skip scheduled +items if they are repeated beyond the current deadline." + :group 'org-agenda-skip + :group 'org-agenda-daily/weekly + :type '(choice + (const :tag "Never" nil) + (const :tag "Always" t) + (const :tag "Not when scheduled today" not-today) + (const :tag "When repeated past deadline" repeated-after-deadline))) + +(defcustom org-agenda-skip-timestamp-if-deadline-is-shown nil + "Non-nil means skip timestamp line if same entry shows because of deadline. +In the agenda of today, an entry can show up multiple times +because it has both a plain timestamp and has a nearby deadline. +When this variable is t, then only the deadline is shown and the +fact that the entry has a timestamp for or including today is not +shown. When this variable is nil, the entry will be shown +several times." + :group 'org-agenda-skip + :group 'org-agenda-daily/weekly + :version "24.1" + :type '(choice + (const :tag "Never" nil) + (const :tag "Always" t))) + +(defcustom org-agenda-skip-deadline-if-done nil + "Non-nil means don't show deadlines when the corresponding item is done. +When nil, the deadline is still shown and should give you a happy feeling. +This is relevant for the daily/weekly agenda. It applies only to the +actual date of the deadline. Warnings about approaching and past-due +deadlines are always turned off when the item is DONE." + :group 'org-agenda-skip + :group 'org-agenda-daily/weekly + :type 'boolean) + +(defcustom org-agenda-skip-deadline-prewarning-if-scheduled nil + "Non-nil means skip deadline prewarning when entry is also scheduled. +This will apply on all days where a prewarning for the deadline would +be shown, but not at the day when the entry is actually due. On that day, +the deadline will be shown anyway. +This variable may be set to nil, t, the symbol `pre-scheduled', +or a number which will then give the number of days before the actual +deadline when the prewarnings should resume. The symbol `pre-scheduled' +eliminates the deadline prewarning only prior to the scheduled date. +This can be used in a workflow where the first showing of the deadline will +trigger you to schedule it, and then you don't want to be reminded of it +because you will take care of it on the day when scheduled." + :group 'org-agenda-skip + :group 'org-agenda-daily/weekly + :version "24.1" + :type '(choice + (const :tag "Always show prewarning" nil) + (const :tag "Remove prewarning prior to scheduled date" pre-scheduled) + (const :tag "Remove prewarning if entry is scheduled" t) + (integer :tag "Restart prewarning N days before deadline"))) + +(defcustom org-agenda-skip-scheduled-delay-if-deadline nil + "Non-nil means skip scheduled delay when entry also has a deadline. +This variable may be set to nil, t, the symbol `post-deadline', +or a number which will then give the number of days after the actual +scheduled date when the delay should expire. The symbol `post-deadline' +eliminates the schedule delay when the date is posterior to the deadline." + :group 'org-agenda-skip + :group 'org-agenda-daily/weekly + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "Always honor delay" nil) + (const :tag "Ignore delay if posterior to the deadline" post-deadline) + (const :tag "Ignore delay if entry has a deadline" t) + (integer :tag "Honor delay up until N days after the scheduled date"))) + +(defcustom org-agenda-skip-additional-timestamps-same-entry nil + "When nil, multiple same-day timestamps in entry make multiple agenda lines. +When non-nil, after the search for timestamps has matched once in an +entry, the rest of the entry will not be searched." + :group 'org-agenda-skip + :type 'boolean) + +(defcustom org-agenda-skip-timestamp-if-done nil + "Non-nil means don't select item by timestamp or -range if it is DONE." + :group 'org-agenda-skip + :group 'org-agenda-daily/weekly + :type 'boolean) + +(defcustom org-agenda-dim-blocked-tasks t + "Non-nil means dim blocked tasks in the agenda display. +This causes some overhead during agenda construction, but if you +have turned on `org-enforce-todo-dependencies', +`org-enforce-todo-checkbox-dependencies', or any other blocking +mechanism, this will create useful feedback in the agenda. + +Instead of t, this variable can also have the value `invisible'. +Then blocked tasks will be invisible and only become visible when +they become unblocked. An exemption to this behavior is when a task is +blocked because of unchecked checkboxes below it. Since checkboxes do +not show up in the agenda views, making this task invisible you remove any +trace from agenda views that there is something to do. Therefore, a task +that is blocked because of checkboxes will never be made invisible, it +will only be dimmed." + :group 'org-agenda-daily/weekly + :group 'org-agenda-todo-list + :version "24.3" + :type '(choice + (const :tag "Do not dim" nil) + (const :tag "Dim to a gray face" t) + (const :tag "Make invisible" invisible))) + +(defgroup org-agenda-startup nil + "Options concerning initial settings in the Agenda in Org Mode." + :tag "Org Agenda Startup" + :group 'org-agenda) + +(defcustom org-agenda-menu-show-matcher t + "Non-nil means show the match string in the agenda dispatcher menu. +When nil, the matcher string is not shown, but is put into the help-echo +property so than moving the mouse over the command shows it. +Setting it to nil is good if matcher strings are very long and/or if +you want to use two-columns display (see `org-agenda-menu-two-columns')." + :group 'org-agenda + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-menu-two-columns nil + "Non-nil means, use two columns to show custom commands in the dispatcher. +If you use this, you probably want to set `org-agenda-menu-show-matcher' +to nil." + :group 'org-agenda + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-finalize-hook nil + "Hook run just before displaying an agenda buffer. +The buffer is still writable when the hook is called. + +You can modify some of the buffer substrings but you should be +extra careful not to modify the text properties of the agenda +headlines as the agenda display heavily relies on them." + :group 'org-agenda-startup + :type 'hook) + +(defcustom org-agenda-mouse-1-follows-link nil + "Non-nil means mouse-1 on a link will follow the link in the agenda. +A longer mouse click will still set point. Needs to be set +before org.el is loaded." + :group 'org-agenda-startup + :type 'boolean) + +(defcustom org-agenda-start-with-follow-mode nil + "The initial value of follow mode in a newly created agenda window." + :group 'org-agenda-startup + :type 'boolean) + +(defcustom org-agenda-follow-indirect nil + "Non-nil means `org-agenda-follow-mode' displays only the +current item's tree, in an indirect buffer." + :group 'org-agenda + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-show-outline-path t + "Non-nil means show outline path in echo area after line motion." + :group 'org-agenda-startup + :type 'boolean) + +(defcustom org-agenda-start-with-entry-text-mode nil + "The initial value of entry-text-mode in a newly created agenda window." + :group 'org-agenda-startup + :type 'boolean) + +(defcustom org-agenda-entry-text-maxlines 5 + "Number of text lines to be added when `E' is pressed in the agenda. + +Note that this variable only used during agenda display. To add entry text +when exporting the agenda, configure the variable +`org-agenda-add-entry-text-maxlines'." + :group 'org-agenda + :type 'integer) + +(defcustom org-agenda-entry-text-exclude-regexps nil + "List of regular expressions to clean up entry text. +The complete matches of all regular expressions in this list will be +removed from entry text before it is shown in the agenda." + :group 'org-agenda + :type '(repeat (regexp))) + +(defcustom org-agenda-entry-text-leaders " > " + "Text prepended to the entry text in agenda buffers." + :version "24.4" + :package-version '(Org . "8.0") + :group 'org-agenda + :type 'string) + +(defvar org-agenda-entry-text-cleanup-hook nil + "Hook that is run after basic cleanup of entry text to be shown in agenda. +This cleanup is done in a temporary buffer, so the function may inspect and +change the entire buffer. +Some default stuff like drawers and scheduling/deadline dates will already +have been removed when this is called, as will any matches for regular +expressions listed in `org-agenda-entry-text-exclude-regexps'.") + +(defvar org-agenda-include-inactive-timestamps nil + "Non-nil means include inactive time stamps in agenda. +Dynamically scoped.") + +(defgroup org-agenda-windows nil + "Options concerning the windows used by the Agenda in Org Mode." + :tag "Org Agenda Windows" + :group 'org-agenda) + +(defcustom org-agenda-window-setup 'reorganize-frame + "How the agenda buffer should be displayed. +Possible values for this option are: + +current-window Show agenda in the current window, keeping all other windows. +other-window Use `switch-to-buffer-other-window' to display agenda. +only-window Show agenda, deleting all other windows. +reorganize-frame Show only two windows on the current frame, the current + window and the agenda. +other-frame Use `switch-to-buffer-other-frame' to display agenda. + Also, when exiting the agenda, kill that frame. +See also the variable `org-agenda-restore-windows-after-quit'." + :group 'org-agenda-windows + :type '(choice + (const current-window) + (const other-frame) + (const other-window) + (const only-window) + (const reorganize-frame))) + +(defcustom org-agenda-window-frame-fractions '(0.5 . 0.75) + "The min and max height of the agenda window as a fraction of frame height. +The value of the variable is a cons cell with two numbers between 0 and 1. +It only matters if `org-agenda-window-setup' is `reorganize-frame'." + :group 'org-agenda-windows + :type '(cons (number :tag "Minimum") (number :tag "Maximum"))) + +(defcustom org-agenda-restore-windows-after-quit nil + "Non-nil means restore window configuration upon exiting agenda. +Before the window configuration is changed for displaying the agenda, +the current status is recorded. When the agenda is exited with +`q' or `x' and this option is set, the old state is restored. If +`org-agenda-window-setup' is `other-frame', the value of this +option will be ignored." + :group 'org-agenda-windows + :type 'boolean) + +(defcustom org-agenda-span 'week + "Number of days to include in overview display. +Can be day, week, month, year, or any number of days. +Custom commands can set this variable in the options section." + :group 'org-agenda-daily/weekly + :type '(choice (const :tag "Day" day) + (const :tag "Week" week) + (const :tag "Fortnight" fortnight) + (const :tag "Month" month) + (const :tag "Year" year) + (integer :tag "Custom"))) + +(defcustom org-agenda-start-on-weekday 1 + "Non-nil means start the overview always on the specified weekday. +0 denotes Sunday, 1 denotes Monday, etc. +When nil, always start on the current day. +Custom commands can set this variable in the options section." + :group 'org-agenda-daily/weekly + :type '(choice (const :tag "Today" nil) + (integer :tag "Weekday No."))) + +(defcustom org-agenda-show-all-dates t + "Non-nil means `org-agenda' shows every day in the selected range. +When nil, only the days which actually have entries are shown." + :group 'org-agenda-daily/weekly + :type 'boolean) + +(defcustom org-agenda-format-date 'org-agenda-format-date-aligned + "Format string for displaying dates in the agenda. +Used by the daily/weekly agenda. This should be a format string +understood by `format-time-string', or a function returning the +formatted date as a string. The function must take a single +argument, a calendar-style date list like (month day year)." + :group 'org-agenda-daily/weekly + :type '(choice + (string :tag "Format string") + (function :tag "Function"))) + +(defun org-agenda-format-date-aligned (date) + "Format a DATE string for display in the daily/weekly agenda. +This function makes sure that dates are aligned for easy reading." + (require 'cal-iso) + (let* ((dayname (calendar-day-name date)) + (day (cadr date)) + (day-of-week (calendar-day-of-week date)) + (month (car date)) + (monthname (calendar-month-name month)) + (year (nth 2 date)) + (iso-week (org-days-to-iso-week + (calendar-absolute-from-gregorian date))) + (weekyear (cond ((and (= month 1) (>= iso-week 52)) + (1- year)) + ((and (= month 12) (<= iso-week 1)) + (1+ year)) + (t year))) + (weekstring (if (= day-of-week 1) + (format " W%02d" iso-week) + ""))) + (format "%-10s %2d %s %4d%s" + dayname day monthname year weekstring))) + +(defcustom org-agenda-time-leading-zero nil + "Non-nil means use leading zero for military times in agenda. +For example, 9:30am would become 09:30 rather than 9:30." + :group 'org-agenda-daily/weekly + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-timegrid-use-ampm nil + "When set, show AM/PM style timestamps on the timegrid." + :group 'org-agenda + :version "24.1" + :type 'boolean) + +(defun org-agenda-time-of-day-to-ampm (time) + "Convert TIME of a string like \"13:45\" to an AM/PM style time string." + (let* ((hour-number (string-to-number (substring time 0 -3))) + (minute (substring time -2)) + (ampm "am")) + (cond + ((equal hour-number 12) + (setq ampm "pm")) + ((> hour-number 12) + (setq ampm "pm") + (setq hour-number (- hour-number 12)))) + (concat + (if org-agenda-time-leading-zero + (format "%02d" hour-number) + (format "%02s" (number-to-string hour-number))) + ":" minute ampm))) + +(defun org-agenda-time-of-day-to-ampm-maybe (time) + "Conditionally convert TIME to AM/PM format based on `org-agenda-timegrid-use-ampm'." + (if org-agenda-timegrid-use-ampm + (org-agenda-time-of-day-to-ampm time) + time)) + +(defcustom org-agenda-weekend-days '(6 0) + "Which days are weekend? +These days get the special face `org-agenda-date-weekend' in the agenda." + :group 'org-agenda-daily/weekly + :type '(set :greedy t + (const :tag "Monday" 1) + (const :tag "Tuesday" 2) + (const :tag "Wednesday" 3) + (const :tag "Thursday" 4) + (const :tag "Friday" 5) + (const :tag "Saturday" 6) + (const :tag "Sunday" 0))) + +(defcustom org-agenda-move-date-from-past-immediately-to-today t + "Non-nil means jump to today when moving a past date forward in time. +When using S-right in the agenda to move a a date forward, and the date +stamp currently points to the past, the first key press will move it +to today. WHen nil, just move one day forward even if the date stays +in the past." + :group 'org-agenda-daily/weekly + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-include-diary nil + "If non-nil, include in the agenda entries from the Emacs Calendar's diary. +Custom commands can set this variable in the options section." + :group 'org-agenda-daily/weekly + :type 'boolean) + +(defcustom org-agenda-include-deadlines t + "If non-nil, include entries within their deadline warning period. +Custom commands can set this variable in the options section." + :group 'org-agenda-daily/weekly + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-show-future-repeats t + "Non-nil shows repeated entries in the future part of the agenda. +When set to the symbol `next' only the first future repeat is shown." + :group 'org-agenda-daily/weekly + :type '(choice + (const :tag "Show all repeated entries" t) + (const :tag "Show next repeated entry" next) + (const :tag "Do not show repeated entries" nil)) + :version "26.1" + :package-version '(Org . "9.1") + :safe #'symbolp) + +(defcustom org-agenda-prefer-last-repeat nil + "Non-nil sets date for repeated entries to their last repeat. + +When nil, display SCHEDULED and DEADLINE dates at their base +date, and in today's agenda, as a reminder. Display plain +time-stamps, on the other hand, at every repeat date in the past +in addition to the base date. + +When non-nil, show a repeated entry at its latest repeat date, +possibly being today even if it wasn't marked as done. This +setting is useful if you do not always mark repeated entries as +done and, yet, consider that reaching repeat date starts the task +anew. + +When set to a list of strings, prefer last repeats only for +entries with these TODO keywords." + :group 'org-agenda-daily/weekly + :type '(choice + (const :tag "Prefer last repeat" t) + (const :tag "Prefer base date" nil) + (repeat :tag "Prefer last repeat for entries with these TODO keywords" + (string :tag "TODO keyword"))) + :version "26.1" + :package-version '(Org . "9.1") + :safe (lambda (x) (or (booleanp x) (consp x)))) + +(defcustom org-scheduled-past-days 10000 + "Number of days to continue listing scheduled items not marked DONE. +When an item is scheduled on a date, it shows up in the agenda on +this day and will be listed until it is marked done or for the +number of days given here." + :group 'org-agenda-daily/weekly + :type 'integer + :safe 'integerp) + +(defcustom org-deadline-past-days 10000 + "Number of days to warn about missed deadlines. +When an item has deadline on a date, it shows up in the agenda on +this day and will appear as a reminder until it is marked DONE or +for the number of days given here." + :group 'org-agenda-daily/weekly + :type 'integer + :version "26.1" + :package-version '(Org . "9.1") + :safe 'integerp) + +(defcustom org-agenda-log-mode-items '(closed clock) + "List of items that should be shown in agenda log mode. +\\\ +This list may contain the following symbols: + + closed Show entries that have been closed on that day. + clock Show entries that have received clocked time on that day. + state Show all logged state changes. +Note that instead of changing this variable, you can also press \ +`\\[universal-argument] \\[org-agenda-log-mode]' in +the agenda to display all available LOG items temporarily." + :group 'org-agenda-daily/weekly + :type '(set :greedy t (const closed) (const clock) (const state))) + +(defcustom org-agenda-clock-consistency-checks + '(:max-duration "10:00" :min-duration 0 :max-gap "0:05" + :gap-ok-around ("4:00") + :default-face ((:background "DarkRed") (:foreground "white")) + :overlap-face nil :gap-face nil :no-end-time-face nil + :long-face nil :short-face nil) + "This is a property list, with the following keys: + +:max-duration Mark clocking chunks that are longer than this time. + This is a time string like \"HH:MM\", or the number + of minutes as an integer. + +:min-duration Mark clocking chunks that are shorter that this. + This is a time string like \"HH:MM\", or the number + of minutes as an integer. + +:max-gap Mark gaps between clocking chunks that are longer than + this duration. A number of minutes, or a string + like \"HH:MM\". + +:gap-ok-around List of times during the day which are usually not working + times. When a gap is detected, but the gap contains any + of these times, the gap is *not* reported. For example, + if this is (\"4:00\" \"13:00\") then gaps that contain + 4:00 in the morning (i.e. the night) and 13:00 + (i.e. a typical lunch time) do not cause a warning. + You should have at least one time during the night in this + list, or otherwise the first task each morning will trigger + a warning because it follows a long gap. + +Furthermore, the following properties can be used to define faces for +issue display. + +:default-face the default face, if the specific face is undefined +:overlap-face face for overlapping clocks +:gap-face face for gaps between clocks +:no-end-time-face face for incomplete clocks +:long-face face for clock intervals that are too long +:short-face face for clock intervals that are too short" + :group 'org-agenda-daily/weekly + :group 'org-clock + :version "24.1" + :type 'plist) + +(defcustom org-agenda-log-mode-add-notes t + "Non-nil means add first line of notes to log entries in agenda views. +If a log item like a state change or a clock entry is associated with +notes, the first line of these notes will be added to the entry in the +agenda display." + :group 'org-agenda-daily/weekly + :type 'boolean) + +(defcustom org-agenda-start-with-log-mode nil + "The initial value of log-mode in a newly created agenda window. +See `org-agenda-log-mode' and `org-agenda-log-mode-items' for further +explanations on the possible values." + :group 'org-agenda-startup + :group 'org-agenda-daily/weekly + :type '(choice (const :tag "Don't show log items" nil) + (const :tag "Show only log items" only) + (const :tag "Show all possible log items" clockcheck) + (repeat :tag "Choose among possible values for `org-agenda-log-mode-items'" + (choice (const :tag "Show closed log items" closed) + (const :tag "Show clocked log items" clock) + (const :tag "Show all logged state changes" state))))) + +(defcustom org-agenda-start-with-clockreport-mode nil + "The initial value of clockreport-mode in a newly created agenda window." + :group 'org-agenda-startup + :group 'org-agenda-daily/weekly + :type 'boolean) + +(defcustom org-agenda-clockreport-parameter-plist '(:link t :maxlevel 2) + "Property list with parameters for the clocktable in clockreport mode. +This is the display mode that shows a clock table in the daily/weekly +agenda, the properties for this dynamic block can be set here. +The usual clocktable parameters are allowed here, but you cannot set +the properties :name, :tstart, :tend, :block, and :scope - these will +be overwritten to make sure the content accurately reflects the +current display in the agenda." + :group 'org-agenda-daily/weekly + :type 'plist) + +(defcustom org-agenda-search-view-always-boolean nil + "Non-nil means the search string is interpreted as individual parts. + +The search string for search view can either be interpreted as a phrase, +or as a list of snippets that define a boolean search for a number of +strings. + +When this is non-nil, the string will be split on whitespace, and each +snippet will be searched individually, and all must match in order to +select an entry. A snippet is then a single string of non-white +characters, or a string in double quotes, or a regexp in {} braces. +If a snippet is preceded by \"-\", the snippet must *not* match. +\"+\" is syntactic sugar for positive selection. Each snippet may +be found as a full word or a partial word, but see the variable +`org-agenda-search-view-force-full-words'. + +When this is nil, search will look for the entire search phrase as one, +with each space character matching any amount of whitespace, including +line breaks. + +Even when this is nil, you can still switch to Boolean search dynamically +by preceding the first snippet with \"+\" or \"-\". If the first snippet +is a regexp marked with braces like \"{abc}\", this will also switch to +boolean search." + :group 'org-agenda-search-view + :version "24.1" + :type 'boolean) + +(defvaralias 'org-agenda-search-view-search-words-only + 'org-agenda-search-view-always-boolean) + +(defcustom org-agenda-search-view-force-full-words nil + "Non-nil means, search words must be matches as complete words. +When nil, they may also match part of a word." + :group 'org-agenda-search-view + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-search-view-max-outline-level 0 + "Maximum outline level to display in search view. +E.g. when this is set to 1, the search view will only +show headlines of level 1. When set to 0, the default +value, don't limit agenda view by outline level." + :group 'org-agenda-search-view + :version "26.1" + :package-version '(Org . "8.3") + :type 'integer) + +(defgroup org-agenda-time-grid nil + "Options concerning the time grid in the Org Agenda." + :tag "Org Agenda Time Grid" + :group 'org-agenda) + +(defcustom org-agenda-search-headline-for-time t + "Non-nil means search headline for a time-of-day. +If the headline contains a time-of-day in one format or another, it will +be used to sort the entry into the time sequence of items for a day. +Some people have time stamps in the headline that refer to the creation +time or so, and then this produces an unwanted side effect. If this is +the case for your, use this variable to turn off searching the headline +for a time." + :group 'org-agenda-time-grid + :type 'boolean) + +(defcustom org-agenda-use-time-grid t + "Non-nil means show a time grid in the agenda schedule. +A time grid is a set of lines for specific times (like every two hours between +8:00 and 20:00). The items scheduled for a day at specific times are +sorted in between these lines. +For details about when the grid will be shown, and what it will look like, see +the variable `org-agenda-time-grid'." + :group 'org-agenda-time-grid + :type 'boolean) + +(defcustom org-agenda-time-grid + '((daily today require-timed) + (800 1000 1200 1400 1600 1800 2000) + "......" + "----------------") + + "The settings for time grid for agenda display. +This is a list of four items. The first item is again a list. It contains +symbols specifying conditions when the grid should be displayed: + + daily if the agenda shows a single day + weekly if the agenda shows an entire week + today show grid on current date, independent of daily/weekly display + require-timed show grid only if at least one item has a time specification + remove-match skip grid times already present in an entry + +The second item is a list of integers, indicating the times that +should have a grid line. + +The third item is a string which will be placed right after the +times that have a grid line. + +The fourth item is a string placed after the grid times. This +will align with agenda items" + :group 'org-agenda-time-grid + :type + '(list + (set :greedy t :tag "Grid Display Options" + (const :tag "Show grid in single day agenda display" daily) + (const :tag "Show grid in weekly agenda display" weekly) + (const :tag "Always show grid for today" today) + (const :tag "Show grid only if any timed entries are present" + require-timed) + (const :tag "Skip grid times already present in an entry" + remove-match)) + (repeat :tag "Grid Times" (integer :tag "Time")) + (string :tag "Grid String (after agenda times)") + (string :tag "Grid String (aligns with agenda items)"))) + +(defcustom org-agenda-show-current-time-in-grid t + "Non-nil means show the current time in the time grid." + :group 'org-agenda-time-grid + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-current-time-string + "now - - - - - - - - - - - - - - - - - - - - - - - - -" + "The string for the current time marker in the agenda." + :group 'org-agenda-time-grid + :version "24.1" + :type 'string) + +(defgroup org-agenda-sorting nil + "Options concerning sorting in the Org Agenda." + :tag "Org Agenda Sorting" + :group 'org-agenda) + +(defcustom org-agenda-sorting-strategy + '((agenda habit-down time-up priority-down category-keep) + (todo priority-down category-keep) + (tags priority-down category-keep) + (search category-keep)) + "Sorting structure for the agenda items of a single day. +This is a list of symbols which will be used in sequence to determine +if an entry should be listed before another entry. The following +symbols are recognized: + +time-up Put entries with time-of-day indications first, early first +time-down Put entries with time-of-day indications first, late first +timestamp-up Sort by any timestamp, early first +timestamp-down Sort by any timestamp, late first +scheduled-up Sort by scheduled timestamp, early first +scheduled-down Sort by scheduled timestamp, late first +deadline-up Sort by deadline timestamp, early first +deadline-down Sort by deadline timestamp, late first +ts-up Sort by active timestamp, early first +ts-down Sort by active timestamp, late first +tsia-up Sort by inactive timestamp, early first +tsia-down Sort by inactive timestamp, late first +category-keep Keep the default order of categories, corresponding to the + sequence in `org-agenda-files'. +category-up Sort alphabetically by category, A-Z. +category-down Sort alphabetically by category, Z-A. +tag-up Sort alphabetically by last tag, A-Z. +tag-down Sort alphabetically by last tag, Z-A. +priority-up Sort numerically by priority, high priority last. +priority-down Sort numerically by priority, high priority first. +todo-state-up Sort by todo state, tasks that are done last. +todo-state-down Sort by todo state, tasks that are done first. +effort-up Sort numerically by estimated effort, high effort last. +effort-down Sort numerically by estimated effort, high effort first. +user-defined-up Sort according to `org-agenda-cmp-user-defined', high last. +user-defined-down Sort according to `org-agenda-cmp-user-defined', high first. +habit-up Put entries that are habits first +habit-down Put entries that are habits last +alpha-up Sort headlines alphabetically +alpha-down Sort headlines alphabetically, reversed + +The different possibilities will be tried in sequence, and testing stops +if one comparison returns a \"not-equal\". For example, the default + '(time-up category-keep priority-down) +means: Pull out all entries having a specified time of day and sort them, +in order to make a time schedule for the current day the first thing in the +agenda listing for the day. Of the entries without a time indication, keep +the grouped in categories, don't sort the categories, but keep them in +the sequence given in `org-agenda-files'. Within each category sort by +priority. + +Leaving out `category-keep' would mean that items will be sorted across +categories by priority. + +Instead of a single list, this can also be a set of list for specific +contents, with a context symbol in the car of the list, any of +`agenda', `todo', `tags', `search' for the corresponding agenda views. + +Custom commands can bind this variable in the options section." + :group 'org-agenda-sorting + :type `(choice + (repeat :tag "General" ,org-sorting-choice) + (list :tag "Individually" + (cons (const :tag "Strategy for Weekly/Daily agenda" agenda) + (repeat ,org-sorting-choice)) + (cons (const :tag "Strategy for TODO lists" todo) + (repeat ,org-sorting-choice)) + (cons (const :tag "Strategy for Tags matches" tags) + (repeat ,org-sorting-choice)) + (cons (const :tag "Strategy for search matches" search) + (repeat ,org-sorting-choice))))) + +(defcustom org-agenda-cmp-user-defined nil + "A function to define the comparison `user-defined'. +This function must receive two arguments, agenda entry a and b. +If a>b, return +1. If a effort operator. Then, tasks with no effort defined will be treated +as tasks with high effort. +When nil, such items are sorted as 0 minutes effort." + :group 'org-agenda-sorting + :type 'boolean) + +(defgroup org-agenda-line-format nil + "Options concerning the entry prefix in the Org agenda display." + :tag "Org Agenda Line Format" + :group 'org-agenda) + +(defcustom org-agenda-prefix-format + '((agenda . " %i %-12:c%?-12t% s") + (todo . " %i %-12:c") + (tags . " %i %-12:c") + (search . " %i %-12:c")) + "Format specifications for the prefix of items in the agenda views. + +An alist with one entry per agenda type. The keys of the +sublists are `agenda', `todo', `search' and `tags'. The values +are format strings. + +This format works similar to a printf format, with the following meaning: + + %c the category of the item, \"Diary\" for entries from the diary, + or as given by the CATEGORY keyword or derived from the file name + %e the effort required by the item + %l the level of the item (insert X space(s) if item is of level X) + %i the icon category of the item, see `org-agenda-category-icon-alist' + %T the last tag of the item (ignore inherited tags, which come first) + %t the HH:MM time-of-day specification if one applies to the entry + %s Scheduling/Deadline information, a short string + %b show breadcrumbs, i.e., the names of the higher levels + %(expression) Eval EXPRESSION and replace the control string + by the result + +All specifiers work basically like the standard `%s' of printf, but may +contain two additional characters: a question mark just after the `%' +and a whitespace/punctuation character just before the final letter. + +If the first character after `%' is a question mark, the entire field +will only be included if the corresponding value applies to the current +entry. This is useful for fields which should have fixed width when +present, but zero width when absent. For example, \"%?-12t\" will +result in a 12 character time field if a time of the day is specified, +but will completely disappear in entries which do not contain a time. + +If there is punctuation or whitespace character just before the +final format letter, this character will be appended to the field +value if the value is not empty. For example, the format +\"%-12:c\" leads to \"Diary: \" if the category is \"Diary\". If +the category is empty, no additional colon is inserted. + +The default value for the agenda sublist is \" %-12:c%?-12t% s\", +which means: + +- Indent the line with two space characters +- Give the category a 12 chars wide field, padded with whitespace on + the right (because of `-'). Append a colon if there is a category + (because of `:'). +- If there is a time-of-day, put it into a 12 chars wide field. If no + time, don't put in an empty field, just skip it (because of '?'). +- Finally, put the scheduling information. + +See also the variables `org-agenda-remove-times-when-in-prefix' and +`org-agenda-remove-tags'. + +Custom commands can set this variable in the options section." + :type '(choice + (string :tag "General format") + (list :greedy t :tag "View dependent" + (cons (const agenda) (string :tag "Format")) + (cons (const todo) (string :tag "Format")) + (cons (const tags) (string :tag "Format")) + (cons (const search) (string :tag "Format")))) + :group 'org-agenda-line-format + :version "26.1" + :package-version '(Org . "9.1")) + +(defvar org-prefix-format-compiled nil + "The compiled prefix format and associated variables. +This is a list where first element is a list of variable bindings, and second +element is the compiled format expression. See the variable +`org-agenda-prefix-format'.") + +(defcustom org-agenda-todo-keyword-format "%-1s" + "Format for the TODO keyword in agenda lines. +Set this to something like \"%-12s\" if you want all TODO keywords +to occupy a fixed space in the agenda display." + :group 'org-agenda-line-format + :type 'string) + +(defcustom org-agenda-diary-sexp-prefix nil + "A regexp that matches part of a diary sexp entry +which should be treated as scheduling/deadline information in +`org-agenda'. + +For example, you can use this to extract the `diary-remind-message' from +`diary-remind' entries." + :group 'org-agenda-line-format + :type '(choice (const :tag "None" nil) (regexp :tag "Regexp"))) + +(defcustom org-agenda-timerange-leaders '("" "(%d/%d): ") + "Text preceding timerange entries in the agenda view. +This is a list with two strings. The first applies when the range +is entirely on one day. The second applies if the range spans several days. +The strings may have two \"%d\" format specifiers which will be filled +with the sequence number of the days, and the total number of days in the +range, respectively." + :group 'org-agenda-line-format + :type '(list + (string :tag "Deadline today ") + (choice :tag "Deadline relative" + (string :tag "Format string") + (function)))) + +(defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ") + "Text preceding scheduled items in the agenda view. +This is a list with two strings. The first applies when the item is +scheduled on the current day. The second applies when it has been scheduled +previously, it may contain a %d indicating that this is the nth time that +this item is scheduled, due to automatic rescheduling of unfinished items +for the following day. So this number is one larger than the number of days +that passed since this item was scheduled first." + :group 'org-agenda-line-format + :version "24.4" + :package-version '(Org . "8.0") + :type '(list + (string :tag "Scheduled today ") + (string :tag "Scheduled previously"))) + +(defcustom org-agenda-inactive-leader "[" + "Text preceding item pulled into the agenda by inactive time stamps. +These entries are added to the agenda when pressing \"[\"." + :group 'org-agenda-line-format + :version "24.1" + :type 'string) + +(defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: " "%2d d. ago: ") + "Text preceding deadline items in the agenda view. +This is a list with three strings. The first applies when the item has its +deadline on the current day. The second applies when the deadline is in the +future, the third one when it is in the past. The strings may contain %d +to capture the number of days." + :group 'org-agenda-line-format + :version "24.4" + :package-version '(Org . "8.0") + :type '(list + (string :tag "Deadline today ") + (string :tag "Deadline in the future ") + (string :tag "Deadline in the past "))) + +(defcustom org-agenda-remove-times-when-in-prefix t + "Non-nil means remove duplicate time specifications in agenda items. +When the format `org-agenda-prefix-format' contains a `%t' specifier, a +time-of-day specification in a headline or diary entry is extracted and +placed into the prefix. If this option is non-nil, the original specification +\(a timestamp or -range, or just a plain time(range) specification like +11:30-4pm) will be removed for agenda display. This makes the agenda less +cluttered. +The option can be t or nil. It may also be the symbol `beg', indicating +that the time should only be removed when it is located at the beginning of +the headline/diary entry." + :group 'org-agenda-line-format + :type '(choice + (const :tag "Always" t) + (const :tag "Never" nil) + (const :tag "When at beginning of entry" beg))) + +(defcustom org-agenda-remove-timeranges-from-blocks nil + "Non-nil means remove time ranges specifications in agenda +items that span on several days." + :group 'org-agenda-line-format + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-default-appointment-duration nil + "Default duration for appointments that only have a starting time. +When nil, no duration is specified in such cases. +When non-nil, this must be the number of minutes, e.g. 60 for one hour." + :group 'org-agenda-line-format + :type '(choice + (integer :tag "Minutes") + (const :tag "No default duration"))) + +(defcustom org-agenda-show-inherited-tags t + "Non-nil means show inherited tags in each agenda line. + +When this option is set to `always', it takes precedence over +`org-agenda-use-tag-inheritance' and inherited tags are shown +in every agenda. + +When this option is set to t (the default), inherited tags are +shown when they are available, i.e. when the value of +`org-agenda-use-tag-inheritance' enables tag inheritance for the +given agenda type. + +This can be set to a list of agenda types in which the agenda +must display the inherited tags. Available types are `todo', +`agenda' and `search'. + +When set to nil, never show inherited tags in agenda lines." + :group 'org-agenda-line-format + :group 'org-agenda + :version "24.3" + :type '(choice + (const :tag "Show inherited tags when available" t) + (const :tag "Always show inherited tags" always) + (repeat :tag "Show inherited tags only in selected agenda types" + (symbol :tag "Agenda type")))) + +(defcustom org-agenda-use-tag-inheritance '(todo search agenda) + "List of agenda view types where to use tag inheritance. + +In tags/tags-todo/tags-tree agenda views, tag inheritance is +controlled by `org-use-tag-inheritance'. In other agenda types, +`org-use-tag-inheritance' is not used for the selection of the +agenda entries. Still, you may want the agenda to be aware of +the inherited tags anyway, e.g. for later tag filtering. + +Allowed value are `todo', `search' and `agenda'. + +This variable has no effect if `org-agenda-show-inherited-tags' +is set to `always'. In that case, the agenda is aware of those +tags. + +The default value sets tags in every agenda type. Setting this +option to nil will speed up non-tags agenda view a lot." + :group 'org-agenda + :version "26.1" + :package-version '(Org . "9.1") + :type '(choice + (const :tag "Use tag inheritance in all agenda types" t) + (repeat :tag "Use tag inheritance in selected agenda types" + (symbol :tag "Agenda type")))) + +(defcustom org-agenda-hide-tags-regexp nil + "Regular expression used to filter away specific tags in agenda views. +This means that these tags will be present, but not be shown in the agenda +line. Secondary filtering will still work on the hidden tags. +Nil means don't hide any tags." + :group 'org-agenda-line-format + :type '(choice + (const :tag "Hide none" nil) + (string :tag "Regexp "))) + +(defcustom org-agenda-remove-tags nil + "Non-nil means remove the tags from the headline copy in the agenda. +When this is the symbol `prefix', only remove tags when +`org-agenda-prefix-format' contains a `%T' specifier." + :group 'org-agenda-line-format + :type '(choice + (const :tag "Always" t) + (const :tag "Never" nil) + (const :tag "When prefix format contains %T" prefix))) + +(defvaralias 'org-agenda-remove-tags-when-in-prefix + 'org-agenda-remove-tags) + +(defcustom org-agenda-tags-column 'auto + "Shift tags in agenda items to this column. +If set to `auto', tags will be automatically aligned to the right +edge of the window. + +If set to a positive number, tags will be left-aligned to that +column. If set to a negative number, tags will be right-aligned +to that column. For example, -80 works well for a normal 80 +character screen." + :group 'org-agenda-line-format + :type '(choice + (const :tag "Automatically align to right edge of window" auto) + (integer :tag "Specific column" -80)) + :package-version '(Org . "9.1") + :version "26.1") + +(defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column) + +(defcustom org-agenda-fontify-priorities 'cookies + "Non-nil means highlight low and high priorities in agenda. +When t, the highest priority entries are bold, lowest priority italic. +However, settings in `org-priority-faces' will overrule these faces. +When this variable is the symbol `cookies', only fontify the +cookies, not the entire task. +This may also be an association list of priority faces, whose +keys are the character values of `org-highest-priority', +`org-default-priority', and `org-lowest-priority' (the default values +are ?A, ?B, and ?C, respectively). The face may be a named face, a +color as a string, or a list like `(:background \"Red\")'. +If it is a color, the variable `org-faces-easy-properties' +determines if it is a foreground or a background color." + :group 'org-agenda-line-format + :type '(choice + (const :tag "Never" nil) + (const :tag "Defaults" t) + (const :tag "Cookies only" cookies) + (repeat :tag "Specify" + (list (character :tag "Priority" :value ?A) + (choice :tag "Face " + (string :tag "Color") + (sexp :tag "Face")))))) + +(defcustom org-agenda-day-face-function nil + "Function called to determine what face should be used to display a day. +The only argument passed to that function is the day. It should +returns a face, or nil if does not want to specify a face and let +the normal rules apply." + :group 'org-agenda-line-format + :version "24.1" + :type '(choice (const nil) (function))) + +(defcustom org-agenda-category-icon-alist nil + "Alist of category icon to be displayed in agenda views. + +Each entry should have the following format: + + (CATEGORY-REGEXP FILE-OR-DATA TYPE DATA-P PROPS) + +Where CATEGORY-REGEXP is a regexp matching the categories where +the icon should be displayed. +FILE-OR-DATA either a file path or a string containing image data. + +The other fields can be omitted safely if not needed: +TYPE indicates the image type. +DATA-P is a boolean indicating whether the FILE-OR-DATA string is +image data. +PROPS are additional image attributes to assign to the image, +like, e.g. `:ascent center'. + + (\"Org\" \"/path/to/icon.png\" nil nil :ascent center) + +If you want to set the display properties yourself, just put a +list as second element: + + (CATEGORY-REGEXP (MY PROPERTY LIST)) + +For example, to display a 16px horizontal space for Emacs +category, you can use: + + (\"Emacs\" \\='(space . (:width (16))))" + :group 'org-agenda-line-format + :version "24.1" + :type '(alist :key-type (string :tag "Regexp matching category") + :value-type (choice (list :tag "Icon" + (string :tag "File or data") + (symbol :tag "Type") + (boolean :tag "Data?") + (repeat :tag "Extra image properties" :inline t symbol)) + (list :tag "Display properties" sexp)))) + +(defgroup org-agenda-column-view nil + "Options concerning column view in the agenda." + :tag "Org Agenda Column View" + :group 'org-agenda) + +(defcustom org-agenda-view-columns-initially nil + "When non-nil, switch to columns view right after creating the agenda." + :group 'org-agenda-column-view + :type 'boolean + :version "26.1" + :package-version '(Org . "9.0") + :safe #'booleanp) + +(defcustom org-agenda-columns-show-summaries t + "Non-nil means show summaries for columns displayed in the agenda view." + :group 'org-agenda-column-view + :type 'boolean) + +(defcustom org-agenda-columns-compute-summary-properties t + "Non-nil means recompute all summary properties before column view. +When column view in the agenda is listing properties that have a summary +operator, it can go to all relevant buffers and recompute the summaries +there. This can mean overhead for the agenda column view, but is necessary +to have thing up to date. +As a special case, a CLOCKSUM property also makes sure that the clock +computations are current." + :group 'org-agenda-column-view + :type 'boolean) + +(defcustom org-agenda-columns-add-appointments-to-effort-sum nil + "Non-nil means the duration of an appointment will add to day effort. +The property to which appointment durations will be added is the one given +in the option `org-effort-property'. If an appointment does not have +an end time, `org-agenda-default-appointment-duration' will be used. If that +is not set, an appointment without end time will not contribute to the time +estimate." + :group 'org-agenda-column-view + :type 'boolean) + +(defcustom org-agenda-auto-exclude-function nil + "A function called with a tag to decide if it is filtered on \ +\\`\\[org-agenda-filter-by-tag] RET'. +The sole argument to the function, which is called once for each +possible tag, is a string giving the name of the tag. The +function should return either nil if the tag should be included +as normal, or \"-\" to exclude the tag. +Note that for the purpose of tag filtering, only the lower-case version of +all tags will be considered, so that this function will only ever see +the lower-case version of all tags." + :group 'org-agenda + :type '(choice (const nil) (function))) + +(defcustom org-agenda-bulk-custom-functions nil + "Alist of characters and custom functions for bulk actions. +For example, this value makes those two functions available: + + \\='((?R set-category) + (?C bulk-cut)) + +With selected entries in an agenda buffer, `B R' will call +the custom function `set-category' on the selected entries. +Note that functions in this alist don't need to be quoted." + :type '(alist :key-type character :value-type (group function)) + :version "24.1" + :group 'org-agenda) + +(defmacro org-agenda-with-point-at-orig-entry (string &rest body) + "Execute BODY with point at location given by `org-hd-marker' property. +If STRING is non-nil, the text property will be fetched from position 0 +in that string. If STRING is nil, it will be fetched from the beginning +of the current line." + (org-with-gensyms (marker) + `(let ((,marker (get-text-property (if ,string 0 (point-at-bol)) + 'org-hd-marker ,string))) + (with-current-buffer (marker-buffer ,marker) + (save-excursion + (goto-char ,marker) + ,@body))))) +(def-edebug-spec org-agenda-with-point-at-orig-entry (form body)) + +(defun org-add-agenda-custom-command (entry) + "Replace or add a command in `org-agenda-custom-commands'. +This is mostly for hacking and trying a new command - once the command +works you probably want to add it to `org-agenda-custom-commands' for good." + (let ((ass (assoc (car entry) org-agenda-custom-commands))) + (if ass + (setcdr ass (cdr entry)) + (push entry org-agenda-custom-commands)))) + +;;; Define the org-agenda-mode + +(defvar org-agenda-mode-map (make-sparse-keymap) + "Keymap for `org-agenda-mode'.") +(defvaralias 'org-agenda-keymap 'org-agenda-mode-map) + +(defvar org-agenda-menu) ; defined later in this file. +(defvar org-agenda-restrict nil) ; defined later in this file. +(defvar org-agenda-follow-mode nil) +(defvar org-agenda-entry-text-mode nil) +(defvar org-agenda-clockreport-mode nil) +(defvar org-agenda-show-log nil + "When non-nil, show the log in the agenda. +Do not set this directly; instead use +`org-agenda-start-with-log-mode', which see.") +(defvar org-agenda-redo-command nil) +(defvar org-agenda-query-string nil) +(defvar org-agenda-mode-hook nil + "Hook run after `org-agenda-mode' is turned on. +The buffer is still writable when this hook is called.") +(defvar org-agenda-type nil) +(defvar org-agenda-force-single-file nil) +(defvar org-agenda-bulk-marked-entries nil + "List of markers that refer to marked entries in the agenda.") +(defvar org-agenda-current-date nil + "Active date when building the agenda.") + +;;; Multiple agenda buffers support + +(defcustom org-agenda-sticky nil + "Non-nil means agenda q key will bury agenda buffers. +Agenda commands will then show existing buffer instead of generating new ones. +When nil, `q' will kill the single agenda buffer." + :group 'org-agenda + :version "24.3" + :type 'boolean) + + +;;;###autoload +(defun org-toggle-sticky-agenda (&optional arg) + "Toggle `org-agenda-sticky'." + (interactive "P") + (let ((new-value (if arg + (> (prefix-numeric-value arg) 0) + (not org-agenda-sticky)))) + (if (equal new-value org-agenda-sticky) + (and (called-interactively-p 'interactive) + (message "Sticky agenda was already %s" + (if org-agenda-sticky "enabled" "disabled"))) + (setq org-agenda-sticky new-value) + (org-agenda-kill-all-agenda-buffers) + (and (called-interactively-p 'interactive) + (message "Sticky agenda %s" + (if org-agenda-sticky "enabled" "disabled")))))) + +(defvar org-agenda-buffer nil + "Agenda buffer currently being generated.") + +(defvar org-agenda-last-prefix-arg nil) +(defvar org-agenda-this-buffer-name nil) +(defvar org-agenda-doing-sticky-redo nil) +(defvar org-agenda-this-buffer-is-sticky nil) +(defvar org-agenda-last-indirect-buffer nil + "Last buffer loaded by `org-agenda-tree-to-indirect-buffer'.") + +(defconst org-agenda-local-vars + '(org-agenda-this-buffer-name + org-agenda-undo-list + org-agenda-pending-undo-list + org-agenda-follow-mode + org-agenda-entry-text-mode + org-agenda-clockreport-mode + org-agenda-show-log + org-agenda-redo-command + org-agenda-query-string + org-agenda-type + org-agenda-bulk-marked-entries + org-agenda-undo-has-started-in + org-agenda-info + org-agenda-pre-window-conf + org-agenda-columns-active + org-agenda-tag-filter + org-agenda-category-filter + org-agenda-top-headline-filter + org-agenda-regexp-filter + org-agenda-effort-filter + org-agenda-markers + org-agenda-last-search-view-search-was-boolean + org-agenda-last-indirect-buffer + org-agenda-filtered-by-category + org-agenda-filter-form + org-agenda-cycle-counter + org-agenda-last-prefix-arg) + "Variables that must be local in agenda buffers to allow multiple buffers.") + +(defun org-agenda-mode () + "Mode for time-sorted view on action items in Org files. + +The following commands are available: + +\\{org-agenda-mode-map}" + (interactive) + (cond (org-agenda-doing-sticky-redo + ;; Refreshing sticky agenda-buffer + ;; + ;; Preserve the value of `org-agenda-local-vars' variables, + ;; while letting `kill-all-local-variables' kill the rest + (let ((save (buffer-local-variables))) + (kill-all-local-variables) + (mapc #'make-local-variable org-agenda-local-vars) + (dolist (elem save) + (pcase elem + (`(,var . ,val) ;ignore unbound variables + (when (and val (memq var org-agenda-local-vars)) + (set var val)))))) + (setq-local org-agenda-this-buffer-is-sticky t)) + (org-agenda-sticky + ;; Creating a sticky Agenda buffer for the first time + (kill-all-local-variables) + (mapc 'make-local-variable org-agenda-local-vars) + (setq-local org-agenda-this-buffer-is-sticky t)) + (t + ;; Creating a non-sticky agenda buffer + (kill-all-local-variables) + (setq-local org-agenda-this-buffer-is-sticky nil))) + (setq org-agenda-undo-list nil + org-agenda-pending-undo-list nil + org-agenda-bulk-marked-entries nil) + (setq major-mode 'org-agenda-mode) + ;; Keep global-font-lock-mode from turning on font-lock-mode + (setq-local font-lock-global-modes (list 'not major-mode)) + (setq mode-name "Org-Agenda") + (setq indent-tabs-mode nil) + (use-local-map org-agenda-mode-map) + (easy-menu-add org-agenda-menu) + (if org-startup-truncated (setq truncate-lines t)) + (setq-local line-move-visual nil) + (add-hook 'post-command-hook 'org-agenda-update-agenda-type nil 'local) + (add-hook 'pre-command-hook 'org-unhighlight nil 'local) + ;; Make sure properties are removed when copying text + (add-hook 'filter-buffer-substring-functions + (lambda (fun start end delete) + (substring-no-properties (funcall fun start end delete))) + nil t) + (unless org-agenda-keep-modes + (setq org-agenda-follow-mode org-agenda-start-with-follow-mode + org-agenda-entry-text-mode org-agenda-start-with-entry-text-mode + org-agenda-show-log org-agenda-start-with-log-mode + org-agenda-clockreport-mode org-agenda-start-with-clockreport-mode)) + (add-to-invisibility-spec '(org-filtered)) + (add-to-invisibility-spec '(org-link)) + (easy-menu-change + '("Agenda") "Agenda Files" + (append + (list + (vector + (if (get 'org-agenda-files 'org-restrict) + "Restricted to single file" + "Edit File List") + '(org-edit-agenda-file-list) + (not (get 'org-agenda-files 'org-restrict))) + "--") + (mapcar 'org-file-menu-entry (org-agenda-files)))) + (org-agenda-set-mode-name) + (apply + (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks) + (list 'org-agenda-mode-hook))) + +(substitute-key-definition 'undo 'org-agenda-undo + org-agenda-mode-map global-map) +(org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto) +(org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto) +(org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to) +(org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill) +(org-defkey org-agenda-mode-map "\C-c\C-w" 'org-agenda-refile) +(org-defkey org-agenda-mode-map [(meta down)] 'org-agenda-drag-line-forward) +(org-defkey org-agenda-mode-map [(meta up)] 'org-agenda-drag-line-backward) +(org-defkey org-agenda-mode-map "m" 'org-agenda-bulk-mark) +(org-defkey org-agenda-mode-map "\M-m" 'org-agenda-bulk-toggle) +(org-defkey org-agenda-mode-map "*" 'org-agenda-bulk-mark-all) +(org-defkey org-agenda-mode-map "\M-*" 'org-agenda-bulk-toggle-all) +(org-defkey org-agenda-mode-map "#" 'org-agenda-dim-blocked-tasks) +(org-defkey org-agenda-mode-map "%" 'org-agenda-bulk-mark-regexp) +(org-defkey org-agenda-mode-map "u" 'org-agenda-bulk-unmark) +(org-defkey org-agenda-mode-map "U" 'org-agenda-bulk-unmark-all) +(org-defkey org-agenda-mode-map "B" 'org-agenda-bulk-action) +(org-defkey org-agenda-mode-map "k" 'org-agenda-capture) +(org-defkey org-agenda-mode-map "A" 'org-agenda-append-agenda) +(org-defkey org-agenda-mode-map "\C-c\C-x!" 'org-reload) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-a" 'org-agenda-archive-default) +(org-defkey org-agenda-mode-map "\C-c\C-xa" 'org-agenda-toggle-archive-tag) +(org-defkey org-agenda-mode-map "\C-c\C-xA" 'org-agenda-archive-to-archive-sibling) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive) +(org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive) +(org-defkey org-agenda-mode-map "$" 'org-agenda-archive) +(org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link) +(org-defkey org-agenda-mode-map " " 'org-agenda-show-and-scroll-up) +(org-defkey org-agenda-mode-map [backspace] 'org-agenda-show-scroll-down) +(org-defkey org-agenda-mode-map "\d" 'org-agenda-show-scroll-down) +(org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset) +(org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset) +(org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer) +(org-defkey org-agenda-mode-map "o" 'delete-other-windows) +(org-defkey org-agenda-mode-map "L" 'org-agenda-recenter) +(org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo) +(org-defkey org-agenda-mode-map "t" 'org-agenda-todo) +(org-defkey org-agenda-mode-map "a" 'org-agenda-archive-default-with-confirmation) +(org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags) +(org-defkey org-agenda-mode-map "\C-c\C-q" 'org-agenda-set-tags) +(org-defkey org-agenda-mode-map "." 'org-agenda-goto-today) +(org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date) +(org-defkey org-agenda-mode-map "d" 'org-agenda-day-view) +(org-defkey org-agenda-mode-map "w" 'org-agenda-week-view) +(org-defkey org-agenda-mode-map "y" 'org-agenda-year-view) +(org-defkey org-agenda-mode-map "\C-c\C-z" 'org-agenda-add-note) +(org-defkey org-agenda-mode-map "z" 'org-agenda-add-note) +(org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-do-date-later) +(org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-do-date-earlier) +(org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-do-date-later) +(org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-do-date-earlier) + +(org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt) +(org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule) +(org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline) +(let ((l '(1 2 3 4 5 6 7 8 9 0))) + (while l (org-defkey org-agenda-mode-map + (int-to-string (pop l)) 'digit-argument))) + +(org-defkey org-agenda-mode-map "F" 'org-agenda-follow-mode) +(org-defkey org-agenda-mode-map "R" 'org-agenda-clockreport-mode) +(org-defkey org-agenda-mode-map "E" 'org-agenda-entry-text-mode) +(org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode) +(org-defkey org-agenda-mode-map "v" 'org-agenda-view-mode-dispatch) +(org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary) +(org-defkey org-agenda-mode-map "!" 'org-agenda-toggle-deadlines) +(org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid) +(org-defkey org-agenda-mode-map "r" 'org-agenda-redo) +(org-defkey org-agenda-mode-map "g" 'org-agenda-redo-all) +(org-defkey org-agenda-mode-map "e" 'org-agenda-set-effort) +(org-defkey org-agenda-mode-map "\C-c\C-xe" 'org-agenda-set-effort) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-e" + 'org-clock-modify-effort-estimate) +(org-defkey org-agenda-mode-map "\C-c\C-xp" 'org-agenda-set-property) +(org-defkey org-agenda-mode-map "q" 'org-agenda-quit) +(org-defkey org-agenda-mode-map "Q" 'org-agenda-Quit) +(org-defkey org-agenda-mode-map "x" 'org-agenda-exit) +(org-defkey org-agenda-mode-map "\C-x\C-w" 'org-agenda-write) +(org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers) +(org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers) +(org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags) +(org-defkey org-agenda-mode-map "n" 'org-agenda-next-line) +(org-defkey org-agenda-mode-map "p" 'org-agenda-previous-line) +(org-defkey org-agenda-mode-map "N" 'org-agenda-next-item) +(org-defkey org-agenda-mode-map "P" 'org-agenda-previous-item) +(substitute-key-definition 'next-line 'org-agenda-next-line + org-agenda-mode-map global-map) +(substitute-key-definition 'previous-line 'org-agenda-previous-line + org-agenda-mode-map global-map) +(org-defkey org-agenda-mode-map "\C-c\C-a" 'org-attach) +(org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line) +(org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line) +(org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority) +(org-defkey org-agenda-mode-map "," 'org-agenda-priority) +(org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry) +(org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar) +(org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date) +(org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon) +(org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset) +(org-defkey org-agenda-mode-map "h" 'org-agenda-holidays) +(org-defkey org-agenda-mode-map "H" 'org-agenda-holidays) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in) +(org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out) +(org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel) +(org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto) +(org-defkey org-agenda-mode-map "J" 'org-agenda-clock-goto) +(org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up) +(org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down) +(org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up) +(org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down) +(org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up) +(org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down) +(org-defkey org-agenda-mode-map "f" 'org-agenda-later) +(org-defkey org-agenda-mode-map "b" 'org-agenda-earlier) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns) +(org-defkey org-agenda-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock) +(org-defkey org-agenda-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock-from-agenda) + +(org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add) +(org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract) +(org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re) +(org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re) +(org-defkey org-agenda-mode-map "/" 'org-agenda-filter-by-tag) +(org-defkey org-agenda-mode-map "_" 'org-agenda-filter-by-effort) +(org-defkey org-agenda-mode-map "=" 'org-agenda-filter-by-regexp) +(org-defkey org-agenda-mode-map "|" 'org-agenda-filter-remove-all) +(org-defkey org-agenda-mode-map "~" 'org-agenda-limit-interactively) +(org-defkey org-agenda-mode-map "<" 'org-agenda-filter-by-category) +(org-defkey org-agenda-mode-map "^" 'org-agenda-filter-by-top-headline) +(org-defkey org-agenda-mode-map ";" 'org-timer-set-timer) +(org-defkey org-agenda-mode-map "\C-c\C-x_" 'org-timer-stop) +(define-key org-agenda-mode-map "?" 'org-agenda-show-the-flagging-note) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull) +(org-defkey org-agenda-mode-map "\C-c\C-x\C-mp" 'org-mobile-push) + +(org-defkey org-agenda-mode-map [mouse-2] 'org-agenda-goto-mouse) +(org-defkey org-agenda-mode-map [mouse-3] 'org-agenda-show-mouse) + +(define-key org-agenda-mode-map [remap forward-paragraph] 'org-agenda-forward-block) +(define-key org-agenda-mode-map [remap backward-paragraph] 'org-agenda-backward-block) + +(when org-agenda-mouse-1-follows-link + (org-defkey org-agenda-mode-map [follow-link] 'mouse-face)) +(easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu" + '("Agenda" + ("Agenda Files") + "--" + ("Agenda Dates" + ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda)] + ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)] + ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)] + ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]) + "--" + ("View" + ["Day View" org-agenda-day-view + :active (org-agenda-check-type nil 'agenda) + :style radio :selected (eq org-agenda-current-span 'day) + :keys "v d (or just d)"] + ["Week View" org-agenda-week-view + :active (org-agenda-check-type nil 'agenda) + :style radio :selected (eq org-agenda-current-span 'week) + :keys "v w"] + ["Fortnight View" org-agenda-fortnight-view + :active (org-agenda-check-type nil 'agenda) + :style radio :selected (eq org-agenda-current-span 'fortnight) + :keys "v t"] + ["Month View" org-agenda-month-view + :active (org-agenda-check-type nil 'agenda) + :style radio :selected (eq org-agenda-current-span 'month) + :keys "v m"] + ["Year View" org-agenda-year-view + :active (org-agenda-check-type nil 'agenda) + :style radio :selected (eq org-agenda-current-span 'year) + :keys "v y"] + "--" + ["Include Diary" org-agenda-toggle-diary + :style toggle :selected org-agenda-include-diary + :active (org-agenda-check-type nil 'agenda)] + ["Include Deadlines" org-agenda-toggle-deadlines + :style toggle :selected org-agenda-include-deadlines + :active (org-agenda-check-type nil 'agenda)] + ["Use Time Grid" org-agenda-toggle-time-grid + :style toggle :selected org-agenda-use-time-grid + :active (org-agenda-check-type nil 'agenda)] + "--" + ["Show clock report" org-agenda-clockreport-mode + :style toggle :selected org-agenda-clockreport-mode + :active (org-agenda-check-type nil 'agenda)] + ["Show some entry text" org-agenda-entry-text-mode + :style toggle :selected org-agenda-entry-text-mode + :active t] + "--" + ["Show Logbook entries" org-agenda-log-mode + :style toggle :selected org-agenda-show-log + :active (org-agenda-check-type nil 'agenda) + :keys "v l (or just l)"] + ["Include archived trees" org-agenda-archives-mode + :style toggle :selected org-agenda-archives-mode :active t + :keys "v a"] + ["Include archive files" (org-agenda-archives-mode t) + :style toggle :selected (eq org-agenda-archives-mode t) :active t + :keys "v A"] + "--" + ["Remove Restriction" org-agenda-remove-restriction-lock org-agenda-restrict]) + ["Write view to file" org-agenda-write t] + ["Rebuild buffer" org-agenda-redo t] + ["Save all Org buffers" org-save-all-org-buffers t] + "--" + ["Show original entry" org-agenda-show t] + ["Go To (other window)" org-agenda-goto t] + ["Go To (this window)" org-agenda-switch-to t] + ["Capture with cursor date" org-agenda-capture t] + ["Follow Mode" org-agenda-follow-mode + :style toggle :selected org-agenda-follow-mode :active t] + ;; ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t] + "--" + ("TODO" + ["Cycle TODO" org-agenda-todo t] + ["Next TODO set" org-agenda-todo-nextset t] + ["Previous TODO set" org-agenda-todo-previousset t] + ["Add note" org-agenda-add-note t]) + ("Archive/Refile/Delete" + ["Archive default" org-agenda-archive-default t] + ["Archive default" org-agenda-archive-default-with-confirmation t] + ["Toggle ARCHIVE tag" org-agenda-toggle-archive-tag t] + ["Move to archive sibling" org-agenda-archive-to-archive-sibling t] + ["Archive subtree" org-agenda-archive t] + "--" + ["Refile" org-agenda-refile t] + "--" + ["Delete subtree" org-agenda-kill t]) + ("Bulk action" + ["Mark entry" org-agenda-bulk-mark t] + ["Mark all" org-agenda-bulk-mark-all t] + ["Unmark entry" org-agenda-bulk-unmark t] + ["Unmark all" org-agenda-bulk-unmark-all :active t :keys "U"] + ["Toggle mark" org-agenda-bulk-toggle t] + ["Toggle all" org-agenda-bulk-toggle-all t] + ["Mark regexp" org-agenda-bulk-mark-regexp t]) + ["Act on all marked" org-agenda-bulk-action t] + "--" + ("Tags and Properties" + ["Show all Tags" org-agenda-show-tags t] + ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))] + ["Change tag in region" org-agenda-set-tags (org-region-active-p)] + "--" + ["Column View" org-columns t]) + ("Deadline/Schedule" + ["Schedule" org-agenda-schedule t] + ["Set Deadline" org-agenda-deadline t] + "--" + ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda)] + ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda)] + ["Change Time +1 hour" org-agenda-do-date-later :active (org-agenda-check-type nil 'agenda) :keys "C-u S-right"] + ["Change Time -1 hour" org-agenda-do-date-earlier :active (org-agenda-check-type nil 'agenda) :keys "C-u S-left"] + ["Change Time + min" org-agenda-date-later :active (org-agenda-check-type nil 'agenda) :keys "C-u C-u S-right"] + ["Change Time - min" org-agenda-date-earlier :active (org-agenda-check-type nil 'agenda) :keys "C-u C-u S-left"] + ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda)]) + ("Clock and Effort" + ["Clock in" org-agenda-clock-in t] + ["Clock out" org-agenda-clock-out t] + ["Clock cancel" org-agenda-clock-cancel t] + ["Goto running clock" org-clock-goto t] + "--" + ["Set Effort" org-agenda-set-effort t] + ["Change clocked effort" org-clock-modify-effort-estimate + (org-clock-is-active)]) + ("Priority" + ["Set Priority" org-agenda-priority t] + ["Increase Priority" org-agenda-priority-up t] + ["Decrease Priority" org-agenda-priority-down t] + ["Show Priority" org-show-priority t]) + ("Calendar/Diary" + ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda)] + ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda)] + ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda)] + ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda)] + ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda)] + ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda)] + "--" + ["Create iCalendar File" org-icalendar-combine-agenda-files t]) + "--" + ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list] + "--" + ("MobileOrg" + ["Push Files and Views" org-mobile-push t] + ["Get Captured and Flagged" org-mobile-pull t] + ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"] + ["Show note / unflag" org-agenda-show-the-flagging-note t] + "--" + ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t]) + "--" + ["Quit" org-agenda-quit t] + ["Exit and Release Buffers" org-agenda-exit t] + )) + +;;; Agenda undo + +(defvar org-agenda-allow-remote-undo t + "Non-nil means allow remote undo from the agenda buffer.") +(defvar org-agenda-undo-has-started-in nil + "Buffers that have already seen `undo-start' in the current undo sequence.") + +(defun org-agenda-undo () + "Undo a remote editing step in the agenda. +This undoes changes both in the agenda buffer and in the remote buffer +that have been changed along." + (interactive) + (or org-agenda-allow-remote-undo + (user-error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo")) + (if (not (eq this-command last-command)) + (setq org-agenda-undo-has-started-in nil + org-agenda-pending-undo-list org-agenda-undo-list)) + (if (not org-agenda-pending-undo-list) + (user-error "No further undo information")) + (let* ((entry (pop org-agenda-pending-undo-list)) + buf line cmd rembuf) + (setq cmd (pop entry) line (pop entry)) + (setq rembuf (nth 2 entry)) + (org-with-remote-undo rembuf + (while (bufferp (setq buf (pop entry))) + (if (pop entry) + (with-current-buffer buf + (let ((last-undo-buffer buf) + (inhibit-read-only t)) + (unless (memq buf org-agenda-undo-has-started-in) + (push buf org-agenda-undo-has-started-in) + (make-local-variable 'pending-undo-list) + (undo-start)) + (while (and pending-undo-list + (listp pending-undo-list) + (not (car pending-undo-list))) + (pop pending-undo-list)) + (undo-more 1)))))) + (org-goto-line line) + (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf)))) + +(defun org-verify-change-for-undo (l1 l2) + "Verify that a real change occurred between the undo lists L1 and L2." + (while (and l1 (listp l1) (null (car l1))) (pop l1)) + (while (and l2 (listp l2) (null (car l2))) (pop l2)) + (not (eq l1 l2))) + +;;; Agenda dispatch + +(defvar org-agenda-restrict-begin (make-marker)) +(defvar org-agenda-restrict-end (make-marker)) +(defvar org-agenda-last-dispatch-buffer nil) +(defvar org-agenda-overriding-restriction nil) + +(defcustom org-agenda-custom-commands-contexts nil + "Alist of custom agenda keys and contextual rules. + +For example, if you have a custom agenda command \"p\" and you +want this command to be accessible only from plain text files, +use this: + + \\='((\"p\" ((in-file . \"\\\\.txt\\\\'\")))) + +Here are the available contexts definitions: + + in-file: command displayed only in matching files + in-mode: command displayed only in matching modes + not-in-file: command not displayed in matching files + not-in-mode: command not displayed in matching modes + in-buffer: command displayed only in matching buffers +not-in-buffer: command not displayed in matching buffers + [function]: a custom function taking no argument + +If you define several checks, the agenda command will be +accessible if there is at least one valid check. + +You can also bind a key to another agenda custom command +depending on contextual rules. + + \\='((\"p\" \"q\" ((in-file . \"\\\\.txt\\\\'\")))) + +Here it means: in .txt files, use \"p\" as the key for the +agenda command otherwise associated with \"q\". (The command +originally associated with \"q\" is not displayed to avoid +duplicates.)" + :version "24.3" + :group 'org-agenda-custom-commands + :type '(repeat (list :tag "Rule" + (string :tag " Agenda key") + (string :tag "Replace by command") + (repeat :tag "Available when" + (choice + (cons :tag "Condition" + (choice + (const :tag "In file" in-file) + (const :tag "Not in file" not-in-file) + (const :tag "In buffer" in-buffer) + (const :tag "Not in buffer" not-in-buffer) + (const :tag "In mode" in-mode) + (const :tag "Not in mode" not-in-mode)) + (regexp)) + (function :tag "Custom function")))))) + +(defcustom org-agenda-max-entries nil + "Maximum number of entries to display in an agenda. +This can be nil (no limit) or an integer or an alist of agenda +types with an associated number of entries to display in this +type." + :version "24.4" + :package-version '(Org . "8.0") + :group 'org-agenda-custom-commands + :type '(choice (symbol :tag "No limit" nil) + (integer :tag "Max number of entries") + (repeat + (cons (choice :tag "Agenda type" + (const agenda) + (const todo) + (const tags) + (const search)) + (integer :tag "Max number of entries"))))) + +(defcustom org-agenda-max-todos nil + "Maximum number of TODOs to display in an agenda. +This can be nil (no limit) or an integer or an alist of agenda +types with an associated number of entries to display in this +type." + :version "24.4" + :package-version '(Org . "8.0") + :group 'org-agenda-custom-commands + :type '(choice (symbol :tag "No limit" nil) + (integer :tag "Max number of TODOs") + (repeat + (cons (choice :tag "Agenda type" + (const agenda) + (const todo) + (const tags) + (const search)) + (integer :tag "Max number of TODOs"))))) + +(defcustom org-agenda-max-tags nil + "Maximum number of tagged entries to display in an agenda. +This can be nil (no limit) or an integer or an alist of agenda +types with an associated number of entries to display in this +type." + :version "24.4" + :package-version '(Org . "8.0") + :group 'org-agenda-custom-commands + :type '(choice (symbol :tag "No limit" nil) + (integer :tag "Max number of tagged entries") + (repeat + (cons (choice :tag "Agenda type" + (const agenda) + (const todo) + (const tags) + (const search)) + (integer :tag "Max number of tagged entries"))))) + +(defcustom org-agenda-max-effort nil + "Maximum cumulated effort duration for the agenda. +This can be nil (no limit) or a number of minutes (as an integer) +or an alist of agenda types with an associated number of minutes +to limit entries to in this type." + :version "24.4" + :package-version '(Org . "8.0") + :group 'org-agenda-custom-commands + :type '(choice (symbol :tag "No limit" nil) + (integer :tag "Max number of minutes") + (repeat + (cons (choice :tag "Agenda type" + (const agenda) + (const todo) + (const tags) + (const search)) + (integer :tag "Max number of minutes"))))) + +(defvar org-agenda-keep-restricted-file-list nil) +(defvar org-keys nil) +(defvar org-match nil) +;;;###autoload +(defun org-agenda (&optional arg org-keys restriction) + "Dispatch agenda commands to collect entries to the agenda buffer. +Prompts for a command to execute. Any prefix arg will be passed +on to the selected command. The default selections are: + +a Call `org-agenda-list' to display the agenda for current day or week. +t Call `org-todo-list' to display the global todo list. +T Call `org-todo-list' to display the global todo list, select only + entries with a specific TODO keyword (the user gets a prompt). +m Call `org-tags-view' to display headlines with tags matching + a condition (the user is prompted for the condition). +M Like `m', but select only TODO entries, no ordinary headlines. +e Export views to associated files. +s Search entries for keywords. +S Search entries for keywords, only with TODO keywords. +/ Multi occur across all agenda files and also files listed + in `org-agenda-text-search-extra-files'. +< Restrict agenda commands to buffer, subtree, or region. + Press several times to get the desired effect. +> Remove a previous restriction. +# List \"stuck\" projects. +! Configure what \"stuck\" means. +C Configure custom agenda commands. + +More commands can be added by configuring the variable +`org-agenda-custom-commands'. In particular, specific tags and TODO keyword +searches can be pre-defined in this way. + +If the current buffer is in Org mode and visiting a file, you can also +first press `<' once to indicate that the agenda should be temporarily +\(until the next use of `\\[org-agenda]') restricted to the current file. +Pressing `<' twice means to restrict to the current subtree or region +\(if active)." + (interactive "P") + (catch 'exit + (let* ((prefix-descriptions nil) + (org-agenda-buffer-name org-agenda-buffer-name) + (org-agenda-window-setup (if (equal (buffer-name) + org-agenda-buffer-name) + 'current-window + org-agenda-window-setup)) + (org-agenda-custom-commands-orig org-agenda-custom-commands) + (org-agenda-custom-commands + ;; normalize different versions + (delq nil + (mapcar + (lambda (x) + (cond ((stringp (cdr x)) + (push x prefix-descriptions) + nil) + ((stringp (nth 1 x)) x) + ((not (nth 1 x)) (cons (car x) (cons "" (cddr x)))) + (t (cons (car x) (cons "" (cdr x)))))) + org-agenda-custom-commands))) + (org-agenda-custom-commands + (org-contextualize-keys + org-agenda-custom-commands org-agenda-custom-commands-contexts)) + (buf (current-buffer)) + (bfn (buffer-file-name (buffer-base-buffer))) + entry key type org-match lprops ans) + ;; Turn off restriction unless there is an overriding one, + (unless org-agenda-overriding-restriction + (unless org-agenda-keep-restricted-file-list + ;; There is a request to keep the file list in place + (put 'org-agenda-files 'org-restrict nil)) + (setq org-agenda-restrict nil) + (move-marker org-agenda-restrict-begin nil) + (move-marker org-agenda-restrict-end nil)) + ;; Delete old local properties + (put 'org-agenda-redo-command 'org-lprops nil) + ;; Delete previously set last-arguments + (put 'org-agenda-redo-command 'last-args nil) + ;; Remember where this call originated + (setq org-agenda-last-dispatch-buffer (current-buffer)) + (unless org-keys + (setq ans (org-agenda-get-restriction-and-command prefix-descriptions) + org-keys (car ans) + restriction (cdr ans))) + ;; If we have sticky agenda buffers, set a name for the buffer, + ;; depending on the invoking keys. The user may still set this + ;; as a command option, which will overwrite what we do here. + (if org-agenda-sticky + (setq org-agenda-buffer-name + (format "*Org Agenda(%s)*" org-keys))) + ;; Establish the restriction, if any + (when (and (not org-agenda-overriding-restriction) restriction) + (put 'org-agenda-files 'org-restrict (list bfn)) + (cond + ((eq restriction 'region) + (setq org-agenda-restrict (current-buffer)) + (move-marker org-agenda-restrict-begin (region-beginning)) + (move-marker org-agenda-restrict-end (region-end))) + ((eq restriction 'subtree) + (save-excursion + (setq org-agenda-restrict (current-buffer)) + (org-back-to-heading t) + (move-marker org-agenda-restrict-begin (point)) + (move-marker org-agenda-restrict-end + (progn (org-end-of-subtree t))))))) + + ;; For example the todo list should not need it (but does...) + (cond + ((setq entry (assoc org-keys org-agenda-custom-commands)) + (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry))) + (progn + (setq type (nth 2 entry) org-match (eval (nth 3 entry)) + lprops (nth 4 entry)) + (if org-agenda-sticky + (setq org-agenda-buffer-name + (or (and (stringp org-match) (format "*Org Agenda(%s:%s)*" org-keys org-match)) + (format "*Org Agenda(%s)*" org-keys)))) + (put 'org-agenda-redo-command 'org-lprops lprops) + (cond + ((eq type 'agenda) + (org-let lprops '(org-agenda-list current-prefix-arg))) + ((eq type 'agenda*) + (org-let lprops '(org-agenda-list current-prefix-arg nil nil t))) + ((eq type 'alltodo) + (org-let lprops '(org-todo-list current-prefix-arg))) + ((eq type 'search) + (org-let lprops '(org-search-view current-prefix-arg org-match nil))) + ((eq type 'stuck) + (org-let lprops '(org-agenda-list-stuck-projects + current-prefix-arg))) + ((eq type 'tags) + (org-let lprops '(org-tags-view current-prefix-arg org-match))) + ((eq type 'tags-todo) + (org-let lprops '(org-tags-view '(4) org-match))) + ((eq type 'todo) + (org-let lprops '(org-todo-list org-match))) + ((eq type 'tags-tree) + (org-check-for-org-mode) + (org-let lprops '(org-match-sparse-tree current-prefix-arg org-match))) + ((eq type 'todo-tree) + (org-check-for-org-mode) + (org-let lprops + '(org-occur (concat "^" org-outline-regexp "[ \t]*" + (regexp-quote org-match) "\\>")))) + ((eq type 'occur-tree) + (org-check-for-org-mode) + (org-let lprops '(org-occur org-match))) + ((functionp type) + (org-let lprops '(funcall type org-match))) + ((fboundp type) + (org-let lprops '(funcall type org-match))) + (t (user-error "Invalid custom agenda command type %s" type)))) + (org-agenda-run-series (nth 1 entry) (cddr entry)))) + ((equal org-keys "C") + (setq org-agenda-custom-commands org-agenda-custom-commands-orig) + (customize-variable 'org-agenda-custom-commands)) + ((equal org-keys "a") (call-interactively 'org-agenda-list)) + ((equal org-keys "s") (call-interactively 'org-search-view)) + ((equal org-keys "S") (org-call-with-arg 'org-search-view (or arg '(4)))) + ((equal org-keys "t") (call-interactively 'org-todo-list)) + ((equal org-keys "T") (org-call-with-arg 'org-todo-list (or arg '(4)))) + ((equal org-keys "m") (call-interactively 'org-tags-view)) + ((equal org-keys "M") (org-call-with-arg 'org-tags-view (or arg '(4)))) + ((equal org-keys "e") (call-interactively 'org-store-agenda-views)) + ((equal org-keys "?") (org-tags-view nil "+FLAGGED") + (add-hook + 'post-command-hook + (lambda () + (unless (current-message) + (let* ((m (org-agenda-get-any-marker)) + (note (and m (org-entry-get m "THEFLAGGINGNOTE")))) + (when note + (message (concat + "FLAGGING-NOTE ([?] for more info): " + (org-add-props + (replace-regexp-in-string + "\\\\n" "//" + (copy-sequence note)) + nil 'face 'org-warning))))))) + t t)) + ((equal org-keys "#") (call-interactively 'org-agenda-list-stuck-projects)) + ((equal org-keys "/") (call-interactively 'org-occur-in-agenda-files)) + ((equal org-keys "!") (customize-variable 'org-stuck-projects)) + (t (user-error "Invalid agenda key")))))) + +(defvar org-agenda-multi) + +(defun org-agenda-append-agenda () + "Append another agenda view to the current one. +This function allows interactive building of block agendas. +Agenda views are separated by `org-agenda-block-separator'." + (interactive) + (unless (derived-mode-p 'org-agenda-mode) + (user-error "Can only append from within agenda buffer")) + (let ((org-agenda-multi t)) + (org-agenda) + (widen) + (org-agenda-finalize) + (setq buffer-read-only t) + (org-agenda-fit-window-to-buffer))) + +(defun org-agenda-normalize-custom-commands (cmds) + "Normalize custom commands CMDS." + (delq nil + (mapcar + (lambda (x) + (cond ((stringp (cdr x)) nil) + ((stringp (nth 1 x)) x) + ((not (nth 1 x)) (cons (car x) (cons "" (cddr x)))) + (t (cons (car x) (cons "" (cdr x)))))) + cmds))) + +(defun org-agenda-get-restriction-and-command (prefix-descriptions) + "The user interface for selecting an agenda command." + (catch 'exit + (let* ((bfn (buffer-file-name (buffer-base-buffer))) + (restrict-ok (and bfn (derived-mode-p 'org-mode))) + (region-p (org-region-active-p)) + (custom org-agenda-custom-commands) + (selstring "") + restriction second-time + c entry key type match prefixes rmheader header-end custom1 desc + line lines left right n n1) + (save-window-excursion + (delete-other-windows) + (org-switch-to-buffer-other-window " *Agenda Commands*") + (erase-buffer) + (insert (eval-when-compile + (let ((header + "Press key for an agenda command: +-------------------------------- < Buffer, subtree/region restriction +a Agenda for current week or day > Remove restriction +t List of all TODO entries e Export agenda views +m Match a TAGS/PROP/TODO query T Entries with special TODO kwd +s Search for keywords M Like m, but only TODO entries +/ Multi-occur S Like s, but only TODO entries +? Find :FLAGGED: entries C Configure custom agenda commands +* Toggle sticky agenda views # List stuck projects (!=configure) +") + (start 0)) + (while (string-match + "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" + header start) + (setq start (match-end 0)) + (add-text-properties (match-beginning 2) (match-end 2) + '(face bold) header)) + header))) + (setq header-end (point-marker)) + (while t + (setq custom1 custom) + (when (eq rmheader t) + (org-goto-line 1) + (re-search-forward ":" nil t) + (delete-region (match-end 0) (point-at-eol)) + (forward-char 1) + (looking-at "-+") + (delete-region (match-end 0) (point-at-eol)) + (move-marker header-end (match-end 0))) + (goto-char header-end) + (delete-region (point) (point-max)) + + ;; Produce all the lines that describe custom commands and prefixes + (setq lines nil) + (while (setq entry (pop custom1)) + (setq key (car entry) desc (nth 1 entry) + type (nth 2 entry) + match (nth 3 entry)) + (if (> (length key) 1) + (cl-pushnew (string-to-char key) prefixes :test #'equal) + (setq line + (format + "%-4s%-14s" + (org-add-props (copy-sequence key) + '(face bold)) + (cond + ((string-match "\\S-" desc) desc) + ((eq type 'agenda) "Agenda for current week or day") + ((eq type 'agenda*) "Appointments for current week or day") + ((eq type 'alltodo) "List of all TODO entries") + ((eq type 'search) "Word search") + ((eq type 'stuck) "List of stuck projects") + ((eq type 'todo) "TODO keyword") + ((eq type 'tags) "Tags query") + ((eq type 'tags-todo) "Tags (TODO)") + ((eq type 'tags-tree) "Tags tree") + ((eq type 'todo-tree) "TODO kwd tree") + ((eq type 'occur-tree) "Occur tree") + ((functionp type) (if (symbolp type) + (symbol-name type) + "Lambda expression")) + (t "???")))) + (if org-agenda-menu-show-matcher + (setq line + (concat line ": " + (cond + ((stringp match) + (setq match (copy-sequence match)) + (org-add-props match nil 'face 'org-warning)) + ((listp type) + (format "set of %d commands" (length type)))))) + (if (org-string-nw-p match) + (add-text-properties + 0 (length line) (list 'help-echo + (concat "Matcher: " match)) line))) + (push line lines))) + (setq lines (nreverse lines)) + (when prefixes + (mapc (lambda (x) + (push + (format "%s %s" + (org-add-props (char-to-string x) + nil 'face 'bold) + (or (cdr (assoc (concat selstring + (char-to-string x)) + prefix-descriptions)) + "Prefix key")) + lines)) + prefixes)) + + ;; Check if we should display in two columns + (if org-agenda-menu-two-columns + (progn + (setq n (length lines) + n1 (+ (/ n 2) (mod n 2)) + right (nthcdr n1 lines) + left (copy-sequence lines)) + (setcdr (nthcdr (1- n1) left) nil)) + (setq left lines right nil)) + (while left + (insert "\n" (pop left)) + (when right + (if (< (current-column) 40) + (move-to-column 40 t) + (insert " ")) + (insert (pop right)))) + + ;; Make the window the right size + (goto-char (point-min)) + (if second-time + (if (not (pos-visible-in-window-p (point-max))) + (org-fit-window-to-buffer)) + (setq second-time t) + (org-fit-window-to-buffer)) + + ;; Ask for selection + (message "Press key for agenda command%s:" + (if (or restrict-ok org-agenda-overriding-restriction) + (if org-agenda-overriding-restriction + " (restriction lock active)" + (if restriction + (format " (restricted to %s)" restriction) + " (unrestricted)")) + "")) + (setq c (read-char-exclusive)) + (message "") + (cond + ((assoc (char-to-string c) custom) + (setq selstring (concat selstring (char-to-string c))) + (throw 'exit (cons selstring restriction))) + ((memq c prefixes) + (setq selstring (concat selstring (char-to-string c)) + prefixes nil + rmheader (or rmheader t) + custom (delq nil (mapcar + (lambda (x) + (if (or (= (length (car x)) 1) + (/= (string-to-char (car x)) c)) + nil + (cons (substring (car x) 1) (cdr x)))) + custom)))) + ((eq c ?*) + (call-interactively 'org-toggle-sticky-agenda) + (sit-for 2)) + ((and (not restrict-ok) (memq c '(?1 ?0 ?<))) + (message "Restriction is only possible in Org buffers") + (ding) (sit-for 1)) + ((eq c ?1) + (org-agenda-remove-restriction-lock 'noupdate) + (setq restriction 'buffer)) + ((eq c ?0) + (org-agenda-remove-restriction-lock 'noupdate) + (setq restriction (if region-p 'region 'subtree))) + ((eq c ?<) + (org-agenda-remove-restriction-lock 'noupdate) + (setq restriction + (cond + ((eq restriction 'buffer) + (if region-p 'region 'subtree)) + ((memq restriction '(subtree region)) + nil) + (t 'buffer)))) + ((eq c ?>) + (org-agenda-remove-restriction-lock 'noupdate) + (setq restriction nil)) + ((and (equal selstring "") (memq c '(?s ?S ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/ ??))) + (throw 'exit (cons (setq selstring (char-to-string c)) restriction))) + ((and (> (length selstring) 0) (eq c ?\d)) + (delete-window) + (org-agenda-get-restriction-and-command prefix-descriptions)) + + ((equal c ?q) (error "Abort")) + (t (user-error "Invalid key %c" c)))))))) + +(defun org-agenda-fit-window-to-buffer () + "Fit the window to the buffer size." + (and (memq org-agenda-window-setup '(reorganize-frame)) + (fboundp 'fit-window-to-buffer) + (if (and (= (cdr org-agenda-window-frame-fractions) 1.0) + (= (car org-agenda-window-frame-fractions) 1.0)) + (delete-other-windows) + (org-fit-window-to-buffer + nil + (floor (* (frame-height) (cdr org-agenda-window-frame-fractions))) + (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))) + +(defvar org-cmd nil) +(defvar org-agenda-overriding-cmd nil) +(defvar org-agenda-overriding-arguments nil) +(defvar org-agenda-overriding-cmd-arguments nil) +(defun org-agenda-run-series (name series) + "Run agenda NAME as a SERIES of agenda commands." + (org-let (nth 1 series) '(org-agenda-prepare name)) + ;; We need to reset agenda markers here, because when constructing a + ;; block agenda, the individual blocks do not do that. + (org-agenda-reset-markers) + (let* ((org-agenda-multi t) + (redo (list 'org-agenda-run-series name (list 'quote series))) + (cmds (car series)) + (gprops (nth 1 series)) + match ;; The byte compiler incorrectly complains about this. Keep it! + org-cmd type lprops) + (while (setq org-cmd (pop cmds)) + (setq type (car org-cmd)) + (setq match (eval (nth 1 org-cmd))) + (setq lprops (nth 2 org-cmd)) + (let ((org-agenda-overriding-arguments + (if (eq org-agenda-overriding-cmd org-cmd) + (or org-agenda-overriding-arguments + org-agenda-overriding-cmd-arguments)))) + (cond + ((eq type 'agenda) + (org-let2 gprops lprops + '(call-interactively 'org-agenda-list))) + ((eq type 'agenda*) + (org-let2 gprops lprops + '(funcall 'org-agenda-list nil nil t))) + ((eq type 'alltodo) + (org-let2 gprops lprops + '(call-interactively 'org-todo-list))) + ((eq type 'search) + (org-let2 gprops lprops + '(org-search-view current-prefix-arg match nil))) + ((eq type 'stuck) + (org-let2 gprops lprops + '(call-interactively 'org-agenda-list-stuck-projects))) + ((eq type 'tags) + (org-let2 gprops lprops + '(org-tags-view current-prefix-arg match))) + ((eq type 'tags-todo) + (org-let2 gprops lprops + '(org-tags-view '(4) match))) + ((eq type 'todo) + (org-let2 gprops lprops + '(org-todo-list match))) + ((fboundp type) + (org-let2 gprops lprops + '(funcall type match))) + (t (error "Invalid type in command series"))))) + (widen) + (let ((inhibit-read-only t)) + (add-text-properties (point-min) (point-max) + `(org-series t org-series-redo-cmd ,redo))) + (setq org-agenda-redo-command redo) + (goto-char (point-min))) + (org-agenda-fit-window-to-buffer) + (org-let (nth 1 series) '(org-agenda-finalize))) + +;;;###autoload +(defmacro org-batch-agenda (cmd-key &rest parameters) + "Run an agenda command in batch mode and send the result to STDOUT. +If CMD-KEY is a string of length 1, it is used as a key in +`org-agenda-custom-commands' and triggers this command. If it is a +longer string it is used as a tags/todo match string. +Parameters are alternating variable names and values that will be bound +before running the agenda command." + (org-eval-in-environment (org-make-parameter-alist parameters) + (let (org-agenda-sticky) + (if (> (length cmd-key) 1) + (org-tags-view nil cmd-key) + (org-agenda nil cmd-key)))) + (set-buffer org-agenda-buffer-name) + (princ (buffer-string))) + +(defvar org-agenda-info nil) + +;;;###autoload +(defmacro org-batch-agenda-csv (cmd-key &rest parameters) + "Run an agenda command in batch mode and send the result to STDOUT. +If CMD-KEY is a string of length 1, it is used as a key in +`org-agenda-custom-commands' and triggers this command. If it is a +longer string it is used as a tags/todo match string. +Parameters are alternating variable names and values that will be bound +before running the agenda command. + +The output gives a line for each selected agenda item. Each +item is a list of comma-separated values, like this: + +category,head,type,todo,tags,date,time,extra,priority-l,priority-n + +category The category of the item +head The headline, without TODO kwd, TAGS and PRIORITY +type The type of the agenda entry, can be + todo selected in TODO match + tagsmatch selected in tags match + diary imported from diary + deadline a deadline on given date + scheduled scheduled on given date + timestamp entry has timestamp on given date + closed entry was closed on given date + upcoming-deadline warning about deadline + past-scheduled forwarded scheduled item + block entry has date block including g. date +todo The todo keyword, if any +tags All tags including inherited ones, separated by colons +date The relevant date, like 2007-2-14 +time The time, like 15:00-16:50 +extra Sting with extra planning info +priority-l The priority letter if any was given +priority-n The computed numerical priority +agenda-day The day in the agenda where this is listed" + (org-eval-in-environment (append '((org-agenda-remove-tags t)) + (org-make-parameter-alist parameters)) + (if (> (length cmd-key) 2) + (org-tags-view nil cmd-key) + (org-agenda nil cmd-key))) + (set-buffer org-agenda-buffer-name) + (let* ((lines (org-split-string (buffer-string) "\n")) + line) + (while (setq line (pop lines)) + (catch 'next + (if (not (get-text-property 0 'org-category line)) (throw 'next nil)) + (setq org-agenda-info + (org-fix-agenda-info (text-properties-at 0 line))) + (princ + (mapconcat 'org-agenda-export-csv-mapper + '(org-category txt type todo tags date time extra + priority-letter priority agenda-day) + ",")) + (princ "\n"))))) + +(defun org-fix-agenda-info (props) + "Make sure all properties on an agenda item have a canonical form. +This ensures the export commands can easily use it." + (let (tmp re) + (when (setq tmp (plist-get props 'tags)) + (setq props (plist-put props 'tags (mapconcat 'identity tmp ":")))) + (when (setq tmp (plist-get props 'date)) + (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp))) + (let ((calendar-date-display-form '(year "-" month "-" day))) + '((format "%4d, %9s %2s, %4s" dayname monthname day year)) + + (setq tmp (calendar-date-string tmp))) + (setq props (plist-put props 'date tmp))) + (when (setq tmp (plist-get props 'day)) + (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp))) + (let ((calendar-date-display-form '(year "-" month "-" day))) + (setq tmp (calendar-date-string tmp))) + (setq props (plist-put props 'day tmp)) + (setq props (plist-put props 'agenda-day tmp))) + (when (setq tmp (plist-get props 'txt)) + (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp) + (plist-put props 'priority-letter (match-string 1 tmp)) + (setq tmp (replace-match "" t t tmp))) + (when (and (setq re (plist-get props 'org-todo-regexp)) + (setq re (concat "\\`\\.*" re " ?")) + (let ((case-fold-search nil)) (string-match re tmp))) + (plist-put props 'todo (match-string 1 tmp)) + (setq tmp (replace-match "" t t tmp))) + (plist-put props 'txt tmp))) + props) + +(defun org-agenda-export-csv-mapper (prop) + (let ((res (plist-get org-agenda-info prop))) + (setq res + (cond + ((not res) "") + ((stringp res) res) + (t (prin1-to-string res)))) + (org-trim (replace-regexp-in-string "," ";" res nil t)))) + +;;;###autoload +(defun org-store-agenda-views (&rest parameters) + "Store agenda views." + (interactive) + (eval (list 'org-batch-store-agenda-views))) + +;;;###autoload +(defmacro org-batch-store-agenda-views (&rest parameters) + "Run all custom agenda commands that have a file argument." + (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands)) + (pop-up-frames nil) + (dir default-directory) + (pars (org-make-parameter-alist parameters)) + cmd thiscmdkey thiscmdcmd match files opts cmd-or-set bufname) + (save-window-excursion + (while cmds + (setq cmd (pop cmds) + thiscmdkey (car cmd) + thiscmdcmd (cdr cmd) + match (nth 2 thiscmdcmd) + bufname (if org-agenda-sticky + (or (and (stringp match) + (format "*Org Agenda(%s:%s)*" thiscmdkey match)) + (format "*Org Agenda(%s)*" thiscmdkey)) + org-agenda-buffer-name) + cmd-or-set (nth 2 cmd) + opts (nth (if (listp cmd-or-set) 3 4) cmd) + files (nth (if (listp cmd-or-set) 4 5) cmd)) + (if (stringp files) (setq files (list files))) + (when files + (org-eval-in-environment (append org-agenda-exporter-settings + opts pars) + (org-agenda nil thiscmdkey)) + (set-buffer bufname) + (while files + (org-eval-in-environment (append org-agenda-exporter-settings + opts pars) + (org-agenda-write (expand-file-name (pop files) dir) nil t bufname))) + (and (get-buffer bufname) + (kill-buffer bufname))))))) + +(defvar org-agenda-current-span nil + "The current span used in the agenda view.") ; local variable in the agenda buffer +(defun org-agenda-mark-header-line (pos) + "Mark the line at POS as an agenda structure header." + (save-excursion + (goto-char pos) + (put-text-property (point-at-bol) (point-at-eol) + 'org-agenda-structural-header t) + (when org-agenda-title-append + (put-text-property (point-at-bol) (point-at-eol) + 'org-agenda-title-append org-agenda-title-append)))) + +(defvar org-mobile-creating-agendas) ; defined in org-mobile.el +(defvar org-agenda-write-buffer-name "Agenda View") +(defun org-agenda-write (file &optional open nosettings agenda-bufname) + "Write the current buffer (an agenda view) as a file. + +Depending on the extension of the file name, plain text (.txt), +HTML (.html or .htm), PDF (.pdf) or Postscript (.ps) is produced. +If the extension is .ics, translate visible agenda into iCalendar +format. If the extension is .org, collect all subtrees +corresponding to the agenda entries and add them in an .org file. + +With prefix argument OPEN, open the new file immediately. If +NOSETTINGS is given, do not scope the settings of +`org-agenda-exporter-settings' into the export commands. This is +used when the settings have already been scoped and we do not +wish to overrule other, higher priority settings. If +AGENDA-BUFFER-NAME is provided, use this as the buffer name for +the agenda to write." + (interactive "FWrite agenda to file: \nP") + (if (or (not (file-writable-p file)) + (and (file-exists-p file) + (if (called-interactively-p 'any) + (not (y-or-n-p (format "Overwrite existing file %s? " file)))))) + (user-error "Cannot write agenda to file %s" file)) + (org-let (if nosettings nil org-agenda-exporter-settings) + '(save-excursion + (save-window-excursion + (let ((bs (copy-sequence (buffer-string))) + (extension (file-name-extension file)) + (default-directory (file-name-directory file)) + beg content) + (with-temp-buffer + (rename-buffer org-agenda-write-buffer-name t) + (set-buffer-modified-p nil) + (insert bs) + (org-agenda-remove-marked-text 'invisible 'org-filtered) + (run-hooks 'org-agenda-before-write-hook) + (cond + ((bound-and-true-p org-mobile-creating-agendas) + (org-mobile-write-agenda-for-mobile file)) + ((string= "org" extension) + (let (content p m message-log-max) + (goto-char (point-min)) + (while (setq p (next-single-property-change (point) 'org-hd-marker nil)) + (goto-char p) + (setq m (get-text-property (point) 'org-hd-marker)) + (when m + (push (save-excursion + (set-buffer (marker-buffer m)) + (goto-char m) + (org-copy-subtree 1 nil t t) + org-subtree-clip) + content))) + (find-file file) + (erase-buffer) + (dolist (s content) (org-paste-subtree 1 s)) + (write-file file) + (kill-buffer (current-buffer)) + (message "Org file written to %s" file))) + ((member extension '("html" "htm")) + (or (require 'htmlize nil t) + (error "Please install htmlize from https://github.com/hniksic/emacs-htmlize")) + (set-buffer (htmlize-buffer (current-buffer))) + (when org-agenda-export-html-style + ;; replace ")) + (insert org-agenda-export-html-style)) + (write-file file) + (kill-buffer (current-buffer)) + (message "HTML written to %s" file)) + ((string= "ps" extension) + (require 'ps-print) + (ps-print-buffer-with-faces file) + (message "Postscript written to %s" file)) + ((string= "pdf" extension) + (require 'ps-print) + (ps-print-buffer-with-faces + (concat (file-name-sans-extension file) ".ps")) + (call-process "ps2pdf" nil nil nil + (expand-file-name + (concat (file-name-sans-extension file) ".ps")) + (expand-file-name file)) + (delete-file (concat (file-name-sans-extension file) ".ps")) + (message "PDF written to %s" file)) + ((string= "ics" extension) + (require 'ox-icalendar) + (org-icalendar-export-current-agenda (expand-file-name file))) + (t + (let ((bs (buffer-string))) + (find-file file) + (erase-buffer) + (insert bs) + (save-buffer 0) + (kill-buffer (current-buffer)) + (message "Plain text written to %s" file)))))))) + (set-buffer (or agenda-bufname + (and (called-interactively-p 'any) (buffer-name)) + org-agenda-buffer-name))) + (when open (org-open-file file))) + +(defun org-agenda-remove-marked-text (property &optional value) + "Delete all text marked with VALUE of PROPERTY. +VALUE defaults to t." + (let (beg) + (setq value (or value t)) + (while (setq beg (text-property-any (point-min) (point-max) + property value)) + (delete-region + beg (or (next-single-property-change beg property) + (point-max)))))) + +(defun org-agenda-add-entry-text () + "Add entry text to agenda lines. +This will add a maximum of `org-agenda-add-entry-text-maxlines' lines of the +entry text following headings shown in the agenda. +Drawers will be excluded, also the line with scheduling/deadline info." + (when (and (> org-agenda-add-entry-text-maxlines 0) + (not (bound-and-true-p org-mobile-creating-agendas))) + (let (m txt) + (goto-char (point-min)) + (while (not (eobp)) + (if (not (setq m (org-get-at-bol 'org-hd-marker))) + (beginning-of-line 2) + (setq txt (org-agenda-get-some-entry-text + m org-agenda-add-entry-text-maxlines " > ")) + (end-of-line 1) + (if (string-match "\\S-" txt) + (insert "\n" txt) + (or (eobp) (forward-char 1)))))))) + +(defun org-agenda-get-some-entry-text (marker n-lines &optional indent + &rest keep) + "Extract entry text from MARKER, at most N-LINES lines. +This will ignore drawers etc, just get the text. +If INDENT is given, prefix every line with this string. If KEEP is +given, it is a list of symbols, defining stuff that should not be +removed from the entry content. Currently only `planning' is allowed here." + (let (txt drawer-re kwd-time-re ind) + (save-excursion + (with-current-buffer (marker-buffer marker) + (if (not (derived-mode-p 'org-mode)) + (setq txt "") + (org-with-wide-buffer + (goto-char marker) + (end-of-line 1) + (setq txt (buffer-substring + (min (1+ (point)) (point-max)) + (progn (outline-next-heading) (point))) + drawer-re org-drawer-regexp + kwd-time-re (concat "^[ \t]*" org-keyword-time-regexp + ".*\n?")) + (with-temp-buffer + (insert txt) + (when org-agenda-add-entry-text-descriptive-links + (goto-char (point-min)) + (while (org-activate-links (point-max)) + (add-text-properties (match-beginning 0) (match-end 0) + '(face org-link)))) + (goto-char (point-min)) + (while (re-search-forward org-bracket-link-regexp (point-max) t) + (set-text-properties (match-beginning 0) (match-end 0) + nil)) + (goto-char (point-min)) + (while (re-search-forward drawer-re nil t) + (delete-region + (match-beginning 0) + (progn (re-search-forward + "^[ \t]*:END:.*\n?" nil 'move) + (point)))) + (unless (member 'planning keep) + (goto-char (point-min)) + (while (re-search-forward kwd-time-re nil t) + (replace-match ""))) + (goto-char (point-min)) + (when org-agenda-entry-text-exclude-regexps + (let ((re-list org-agenda-entry-text-exclude-regexps) re) + (while (setq re (pop re-list)) + (goto-char (point-min)) + (while (re-search-forward re nil t) + (replace-match ""))))) + (goto-char (point-max)) + (skip-chars-backward " \t\n") + (if (looking-at "[ \t\n]+\\'") (replace-match "")) + + ;; find and remove min common indentation + (goto-char (point-min)) + (untabify (point-min) (point-max)) + (setq ind (org-get-indentation)) + (while (not (eobp)) + (unless (looking-at "[ \t]*$") + (setq ind (min ind (org-get-indentation)))) + (beginning-of-line 2)) + (goto-char (point-min)) + (while (not (eobp)) + (unless (looking-at "[ \t]*$") + (move-to-column ind) + (delete-region (point-at-bol) (point))) + (beginning-of-line 2)) + + (run-hooks 'org-agenda-entry-text-cleanup-hook) + + (goto-char (point-min)) + (when indent + (while (and (not (eobp)) (re-search-forward "^" nil t)) + (replace-match indent t t))) + (goto-char (point-min)) + (while (looking-at "[ \t]*\n") (replace-match "")) + (goto-char (point-max)) + (when (> (org-current-line) + n-lines) + (org-goto-line (1+ n-lines)) + (backward-char 1)) + (setq txt (buffer-substring (point-min) (point)))))))) + txt)) + +(defun org-check-for-org-mode () + "Make sure current buffer is in Org mode. Error if not." + (or (derived-mode-p 'org-mode) + (error "Cannot execute Org agenda command on buffer in %s" + major-mode))) + +;;; Agenda prepare and finalize + +(defvar org-agenda-multi nil) ; dynamically scoped +(defvar org-agenda-pre-window-conf nil) +(defvar org-agenda-columns-active nil) +(defvar org-agenda-name nil) +(defvar org-agenda-tag-filter nil) +(defvar org-agenda-category-filter nil) +(defvar org-agenda-regexp-filter nil) +(defvar org-agenda-effort-filter nil) +(defvar org-agenda-top-headline-filter nil) +(defvar org-agenda-tag-filter-preset nil + "A preset of the tags filter used for secondary agenda filtering. +This must be a list of strings, each string must be a single tag preceded +by \"+\" or \"-\". +This variable should not be set directly, but agenda custom commands can +bind it in the options section. The preset filter is a global property of +the entire agenda view. In a block agenda, it will not work reliably to +define a filter for one of the individual blocks. You need to set it in +the global options and expect it to be applied to the entire view.") + +(defvar org-agenda-category-filter-preset nil + "A preset of the category filter used for secondary agenda filtering. +This must be a list of strings, each string must be a single category +preceded by \"+\" or \"-\". +This variable should not be set directly, but agenda custom commands can +bind it in the options section. The preset filter is a global property of +the entire agenda view. In a block agenda, it will not work reliably to +define a filter for one of the individual blocks. You need to set it in +the global options and expect it to be applied to the entire view.") + +(defvar org-agenda-regexp-filter-preset nil + "A preset of the regexp filter used for secondary agenda filtering. +This must be a list of strings, each string must be a single regexp +preceded by \"+\" or \"-\". +This variable should not be set directly, but agenda custom commands can +bind it in the options section. The preset filter is a global property of +the entire agenda view. In a block agenda, it will not work reliably to +define a filter for one of the individual blocks. You need to set it in +the global options and expect it to be applied to the entire view.") + +(defvar org-agenda-effort-filter-preset nil + "A preset of the effort condition used for secondary agenda filtering. +This must be a list of strings, each string must be a single regexp +preceded by \"+\" or \"-\". +This variable should not be set directly, but agenda custom commands can +bind it in the options section. The preset filter is a global property of +the entire agenda view. In a block agenda, it will not work reliably to +define a filter for one of the individual blocks. You need to set it in +the global options and expect it to be applied to the entire view.") + +(defun org-agenda-use-sticky-p () + "Return non-nil if an agenda buffer named +`org-agenda-buffer-name' exists and should be shown instead of +generating a new one." + (and + ;; turned off by user + org-agenda-sticky + ;; For multi-agenda buffer already exists + (not org-agenda-multi) + ;; buffer found + (get-buffer org-agenda-buffer-name) + ;; C-u parameter is same as last call + (with-current-buffer (get-buffer org-agenda-buffer-name) + (and + (equal current-prefix-arg + org-agenda-last-prefix-arg) + ;; In case user turned stickiness on, while having existing + ;; Agenda buffer active, don't reuse that buffer, because it + ;; does not have org variables local + org-agenda-this-buffer-is-sticky)))) + +(defun org-agenda-prepare-window (abuf filter-alist) + "Setup agenda buffer in the window. +ABUF is the buffer for the agenda window. +FILTER-ALIST is an alist of filters we need to apply when +`org-agenda-persistent-filter' is non-nil." + (let* ((awin (get-buffer-window abuf)) wconf) + (cond + ((equal (current-buffer) abuf) nil) + (awin (select-window awin)) + ((not (setq wconf (current-window-configuration)))) + ((eq org-agenda-window-setup 'current-window) + (pop-to-buffer-same-window abuf)) + ((eq org-agenda-window-setup 'other-window) + (org-switch-to-buffer-other-window abuf)) + ((eq org-agenda-window-setup 'other-frame) + (switch-to-buffer-other-frame abuf)) + ((eq org-agenda-window-setup 'only-window) + (delete-other-windows) + (pop-to-buffer-same-window abuf)) + ((eq org-agenda-window-setup 'reorganize-frame) + (delete-other-windows) + (org-switch-to-buffer-other-window abuf))) + (setq org-agenda-tag-filter (cdr (assq 'tag filter-alist))) + (setq org-agenda-category-filter (cdr (assq 'cat filter-alist))) + (setq org-agenda-effort-filter (cdr (assq 'effort filter-alist))) + (setq org-agenda-regexp-filter (cdr (assq 're filter-alist))) + ;; Additional test in case agenda is invoked from within agenda + ;; buffer via elisp link. + (unless (equal (current-buffer) abuf) + (pop-to-buffer-same-window abuf)) + (setq org-agenda-pre-window-conf + (or wconf org-agenda-pre-window-conf)))) + +(defun org-agenda-prepare (&optional name) + (let ((filter-alist (if org-agenda-persistent-filter + (with-current-buffer + (get-buffer-create org-agenda-buffer-name) + (list `(tag . ,org-agenda-tag-filter) + `(re . ,org-agenda-regexp-filter) + `(effort . ,org-agenda-effort-filter) + `(cat . ,org-agenda-category-filter)))))) + (if (org-agenda-use-sticky-p) + (progn + (put 'org-agenda-tag-filter :preset-filter nil) + (put 'org-agenda-category-filter :preset-filter nil) + (put 'org-agenda-regexp-filter :preset-filter nil) + ;; Popup existing buffer + (org-agenda-prepare-window (get-buffer org-agenda-buffer-name) + filter-alist) + (message "Sticky Agenda buffer, use `r' to refresh") + (or org-agenda-multi (org-agenda-fit-window-to-buffer)) + (throw 'exit "Sticky Agenda buffer, use `r' to refresh")) + (setq org-todo-keywords-for-agenda nil) + (put 'org-agenda-tag-filter :preset-filter + org-agenda-tag-filter-preset) + (put 'org-agenda-category-filter :preset-filter + org-agenda-category-filter-preset) + (put 'org-agenda-regexp-filter :preset-filter + org-agenda-regexp-filter-preset) + (put 'org-agenda-effort-filter :preset-filter + org-agenda-effort-filter-preset) + (if org-agenda-multi + (progn + (setq buffer-read-only nil) + (goto-char (point-max)) + (unless (or (bobp) org-agenda-compact-blocks + (not org-agenda-block-separator)) + (insert "\n" + (if (stringp org-agenda-block-separator) + org-agenda-block-separator + (make-string (window-width) org-agenda-block-separator)) + "\n")) + (narrow-to-region (point) (point-max))) + (setq org-done-keywords-for-agenda nil) + ;; Setting any org variables that are in org-agenda-local-vars + ;; list need to be done after the prepare call + (org-agenda-prepare-window + (get-buffer-create org-agenda-buffer-name) filter-alist) + (setq buffer-read-only nil) + (org-agenda-reset-markers) + (let ((inhibit-read-only t)) (erase-buffer)) + (org-agenda-mode) + (setq org-agenda-buffer (current-buffer)) + (setq org-agenda-contributing-files nil) + (setq org-agenda-columns-active nil) + (org-agenda-prepare-buffers (org-agenda-files nil 'ifmode)) + (setq org-todo-keywords-for-agenda + (org-uniquify org-todo-keywords-for-agenda)) + (setq org-done-keywords-for-agenda + (org-uniquify org-done-keywords-for-agenda)) + (setq org-agenda-last-prefix-arg current-prefix-arg) + (setq org-agenda-this-buffer-name org-agenda-buffer-name) + (and name (not org-agenda-name) + (setq-local org-agenda-name name))) + (setq buffer-read-only nil)))) + +(defvar org-agenda-overriding-columns-format) ; From org-colview.el +(defun org-agenda-finalize () + "Finishing touch for the agenda buffer, called just before displaying it." + (unless org-agenda-multi + (save-excursion + (let ((inhibit-read-only t)) + (goto-char (point-min)) + (save-excursion + (while (org-activate-links (point-max)) + (add-text-properties (match-beginning 0) (match-end 0) + '(face org-link)))) + (unless (eq org-agenda-remove-tags t) + (org-agenda-align-tags)) + (unless org-agenda-with-colors + (remove-text-properties (point-min) (point-max) '(face nil))) + (if (and (boundp 'org-agenda-overriding-columns-format) + org-agenda-overriding-columns-format) + (setq-local org-agenda-overriding-columns-format + org-agenda-overriding-columns-format)) + (if (and (boundp 'org-agenda-view-columns-initially) + org-agenda-view-columns-initially) + (org-agenda-columns)) + (when org-agenda-fontify-priorities + (org-agenda-fontify-priorities)) + (when (and org-agenda-dim-blocked-tasks org-blocker-hook) + (org-agenda-dim-blocked-tasks)) + (org-agenda-mark-clocking-task) + (when org-agenda-entry-text-mode + (org-agenda-entry-text-hide) + (org-agenda-entry-text-show)) + (if (and (functionp 'org-habit-insert-consistency-graphs) + (save-excursion (next-single-property-change (point-min) 'org-habit-p))) + (org-habit-insert-consistency-graphs)) + (setq org-agenda-type (org-get-at-bol 'org-agenda-type)) + (unless (or (eq org-agenda-show-inherited-tags 'always) + (and (listp org-agenda-show-inherited-tags) + (memq org-agenda-type org-agenda-show-inherited-tags)) + (and (eq org-agenda-show-inherited-tags t) + (or (eq org-agenda-use-tag-inheritance t) + (and (listp org-agenda-use-tag-inheritance) + (not (memq org-agenda-type + org-agenda-use-tag-inheritance)))))) + (let (mrk) + (save-excursion + (goto-char (point-min)) + (while (equal (forward-line) 0) + (when (setq mrk (get-text-property (point) 'org-hd-marker)) + (put-text-property (point-at-bol) (point-at-eol) + 'tags (org-with-point-at mrk + (delete-dups + (mapcar 'downcase (org-get-tags-at)))))))))) + (run-hooks 'org-agenda-finalize-hook) + (when org-agenda-top-headline-filter + (org-agenda-filter-top-headline-apply + org-agenda-top-headline-filter)) + (when org-agenda-tag-filter + (org-agenda-filter-apply org-agenda-tag-filter 'tag t)) + (when (get 'org-agenda-tag-filter :preset-filter) + (org-agenda-filter-apply + (get 'org-agenda-tag-filter :preset-filter) 'tag t)) + (when org-agenda-category-filter + (org-agenda-filter-apply org-agenda-category-filter 'category)) + (when (get 'org-agenda-category-filter :preset-filter) + (org-agenda-filter-apply + (get 'org-agenda-category-filter :preset-filter) 'category)) + (when org-agenda-regexp-filter + (org-agenda-filter-apply org-agenda-regexp-filter 'regexp)) + (when (get 'org-agenda-regexp-filter :preset-filter) + (org-agenda-filter-apply + (get 'org-agenda-regexp-filter :preset-filter) 'regexp)) + (when org-agenda-effort-filter + (org-agenda-filter-apply org-agenda-effort-filter 'effort)) + (when (get 'org-agenda-effort-filter :preset-filter) + (org-agenda-filter-apply + (get 'org-agenda-effort-filter :preset-filter) 'effort)) + (add-hook 'kill-buffer-hook 'org-agenda-reset-markers 'append 'local))))) + +(defun org-agenda-mark-clocking-task () + "Mark the current clock entry in the agenda if it is present." + ;; We need to widen when `org-agenda-finalize' is called from + ;; `org-agenda-change-all-lines' (e.g. in `org-agenda-clock-in') + (when (bound-and-true-p org-clock-current-task) + (save-restriction + (widen) + (org-agenda-unmark-clocking-task) + (when (marker-buffer org-clock-hd-marker) + (save-excursion + (goto-char (point-min)) + (let (s ov) + (while (setq s (next-single-property-change (point) 'org-hd-marker)) + (goto-char s) + (when (equal (org-get-at-bol 'org-hd-marker) + org-clock-hd-marker) + (setq ov (make-overlay (point-at-bol) (1+ (point-at-eol)))) + (overlay-put ov 'type 'org-agenda-clocking) + (overlay-put ov 'face 'org-agenda-clocking) + (overlay-put ov 'help-echo + "The clock is running in this item"))))))))) + +(defun org-agenda-unmark-clocking-task () + "Unmark the current clocking task." + (mapc (lambda (o) + (if (eq (overlay-get o 'type) 'org-agenda-clocking) + (delete-overlay o))) + (overlays-in (point-min) (point-max)))) + +(defun org-agenda-fontify-priorities () + "Make highest priority lines bold, and lowest italic." + (interactive) + (mapc (lambda (o) (if (eq (overlay-get o 'org-type) 'org-priority) + (delete-overlay o))) + (overlays-in (point-min) (point-max))) + (save-excursion + (let (b e p ov h l) + (goto-char (point-min)) + (while (re-search-forward "\\[#\\(.\\)\\]" nil t) + (setq h (or (get-char-property (point) 'org-highest-priority) + org-highest-priority) + l (or (get-char-property (point) 'org-lowest-priority) + org-lowest-priority) + p (string-to-char (match-string 1)) + b (match-beginning 0) + e (if (eq org-agenda-fontify-priorities 'cookies) + (match-end 0) + (point-at-eol)) + ov (make-overlay b e)) + (overlay-put + ov 'face + (let ((special-face + (cond ((org-face-from-face-or-color + 'priority 'org-priority + (cdr (assoc p org-priority-faces)))) + ((and (listp org-agenda-fontify-priorities) + (org-face-from-face-or-color + 'priority 'org-priority + (cdr (assoc p org-agenda-fontify-priorities))))) + ((equal p l) 'italic) + ((equal p h) 'bold)))) + (if special-face (list special-face 'org-priority) 'org-priority))) + (overlay-put ov 'org-type 'org-priority))))) + +(defvar org-depend-tag-blocked) + +(defun org-agenda-dim-blocked-tasks (&optional invisible) + "Dim currently blocked TODOs in the agenda display. +When INVISIBLE is non-nil, hide currently blocked TODO instead of +dimming them." + (interactive "P") + (when (called-interactively-p 'interactive) + (message "Dim or hide blocked tasks...")) + (dolist (o (overlays-in (point-min) (point-max))) + (when (eq (overlay-get o 'org-type) 'org-blocked-todo) + (delete-overlay o))) + (save-excursion + (let ((inhibit-read-only t)) + (goto-char (point-min)) + (while (let ((pos (text-property-not-all + (point) (point-max) 'org-todo-blocked nil))) + (when pos (goto-char pos))) + (let* ((invisible (eq (org-get-at-bol 'org-todo-blocked) 'invisible)) + (ov (make-overlay (if invisible + (line-end-position 0) + (line-beginning-position)) + (line-end-position)))) + (if invisible + (overlay-put ov 'invisible t) + (overlay-put ov 'face 'org-agenda-dimmed-todo-face)) + (overlay-put ov 'org-type 'org-blocked-todo)) + (forward-line)))) + (when (called-interactively-p 'interactive) + (message "Dim or hide blocked tasks...done"))) + +(defun org-agenda--mark-blocked-entry (entry) + "For ENTRY a string with the text property `org-hd-marker', if +the header at `org-hd-marker' is blocked according to +`org-entry-blocked-p', then if `org-agenda-dim-blocked-tasks' is +'invisible and the header is not blocked by checkboxes, set the +text property `org-todo-blocked' to 'invisible, otherwise set it +to t." + (when (get-text-property 0 'todo-state entry) + (let ((entry-marker (get-text-property 0 'org-hd-marker entry)) + (org-blocked-by-checkboxes nil) + ;; Necessary so that `org-entry-blocked-p' does not change + ;; the buffer. + (org-depend-tag-blocked nil)) + (when entry-marker + (let ((blocked + (with-current-buffer (marker-buffer entry-marker) + (save-excursion + (goto-char entry-marker) + (org-entry-blocked-p))))) + (when blocked + (let ((really-invisible + (and (not org-blocked-by-checkboxes) + (eq org-agenda-dim-blocked-tasks 'invisible)))) + (put-text-property + 0 (length entry) 'org-todo-blocked + (if really-invisible 'invisible t) + entry))))))) + entry) + +(defvar org-agenda-skip-function nil + "Function to be called at each match during agenda construction. +If this function returns nil, the current match should not be skipped. +Otherwise, the function must return a position from where the search +should be continued. +This may also be a Lisp form, it will be evaluated. +Never set this variable using `setq' or so, because then it will apply +to all future agenda commands. If you do want a global skipping condition, +use the option `org-agenda-skip-function-global' instead. +The correct usage for `org-agenda-skip-function' is to bind it with +`let' to scope it dynamically into the agenda-constructing command. +A good way to set it is through options in `org-agenda-custom-commands'.") + +(defun org-agenda-skip () + "Throw to `:skip' in places that should be skipped. +Also moves point to the end of the skipped region, so that search can +continue from there." + (let ((p (point-at-bol)) to) + (when (or + (save-excursion (goto-char p) (looking-at comment-start-skip)) + (and org-agenda-skip-archived-trees (not org-agenda-archives-mode) + (get-text-property p :org-archived) + (org-end-of-subtree t)) + (and org-agenda-skip-comment-trees + (get-text-property p :org-comment) + (org-end-of-subtree t)) + (and (setq to (or (org-agenda-skip-eval org-agenda-skip-function-global) + (org-agenda-skip-eval org-agenda-skip-function))) + (goto-char to)) + (org-in-src-block-p t)) + (throw :skip t)))) + +(defun org-agenda-skip-eval (form) + "If FORM is a function or a list, call (or eval) it and return the result. +`save-excursion' and `save-match-data' are wrapped around the call, so point +and match data are returned to the previous state no matter what these +functions do." + (let (fp) + (and form + (or (setq fp (functionp form)) + (consp form)) + (save-excursion + (save-match-data + (if fp + (funcall form) + (eval form))))))) + +(defvar org-agenda-markers nil + "List of all currently active markers created by `org-agenda'.") +(defvar org-agenda-last-marker-time (float-time) + "Creation time of the last agenda marker.") + +(defun org-agenda-new-marker (&optional pos) + "Return a new agenda marker. +Maker is at point, or at POS if non-nil. Org mode keeps a list of +these markers and resets them when they are no longer in use." + (let ((m (copy-marker (or pos (point)) t))) + (setq org-agenda-last-marker-time (float-time)) + (if org-agenda-buffer + (with-current-buffer org-agenda-buffer + (push m org-agenda-markers)) + (push m org-agenda-markers)) + m)) + +(defun org-agenda-reset-markers () + "Reset markers created by `org-agenda'." + (while org-agenda-markers + (move-marker (pop org-agenda-markers) nil))) + +(defun org-agenda-save-markers-for-cut-and-paste (beg end) + "Save relative positions of markers in region. +This check for agenda markers in all agenda buffers currently active." + (dolist (buf (buffer-list)) + (with-current-buffer buf + (when (eq major-mode 'org-agenda-mode) + (mapc (lambda (m) (org-check-and-save-marker m beg end)) + org-agenda-markers))))) + +;;; Entry text mode + +(defun org-agenda-entry-text-show-here () + "Add some text from the entry as context to the current line." + (let (m txt o) + (setq m (org-get-at-bol 'org-hd-marker)) + (unless (marker-buffer m) + (error "No marker points to an entry here")) + (setq txt (concat "\n" (org-no-properties + (org-agenda-get-some-entry-text + m org-agenda-entry-text-maxlines + org-agenda-entry-text-leaders)))) + (when (string-match "\\S-" txt) + (setq o (make-overlay (point-at-bol) (point-at-eol))) + (overlay-put o 'evaporate t) + (overlay-put o 'org-overlay-type 'agenda-entry-content) + (overlay-put o 'after-string txt)))) + +(defun org-agenda-entry-text-show () + "Add entry context for all agenda lines." + (interactive) + (save-excursion + (goto-char (point-max)) + (beginning-of-line 1) + (while (not (bobp)) + (when (org-get-at-bol 'org-hd-marker) + (org-agenda-entry-text-show-here)) + (beginning-of-line 0)))) + +(defun org-agenda-entry-text-hide () + "Remove any shown entry context." + (delq nil + (mapcar (lambda (o) + (if (eq (overlay-get o 'org-overlay-type) + 'agenda-entry-content) + (progn (delete-overlay o) t))) + (overlays-in (point-min) (point-max))))) + +(defun org-agenda-get-day-face (date) + "Return the face DATE should be displayed with." + (cond ((and (functionp org-agenda-day-face-function) + (funcall org-agenda-day-face-function date))) + ((org-agenda-today-p date) 'org-agenda-date-today) + ((memq (calendar-day-of-week date) org-agenda-weekend-days) + 'org-agenda-date-weekend) + (t 'org-agenda-date))) + +(defvar org-agenda-show-log-scoped) + +;;; Agenda Daily/Weekly + +(defvar org-agenda-start-day nil ; dynamically scoped parameter + "Start day for the agenda view. +Custom commands can set this variable in the options section. +This is usually a string like \"2007-11-01\", \"+2d\" or any other +input allowed when reading a date through the Org calendar. +See the docstring of `org-read-date' for details.") +(defvar org-starting-day nil) ; local variable in the agenda buffer +(defvar org-arg-loc nil) ; local variable + +(defvar org-agenda-buffer-tmp-name nil) +;;;###autoload +(defun org-agenda-list (&optional arg start-day span with-hour) + "Produce a daily/weekly view from all files in variable `org-agenda-files'. +The view will be for the current day or week, but from the overview buffer +you will be able to go to other days/weeks. + +With a numeric prefix argument in an interactive call, the agenda will +span ARG days. Lisp programs should instead specify SPAN to change +the number of days. SPAN defaults to `org-agenda-span'. + +START-DAY defaults to TODAY, or to the most recent match for the weekday +given in `org-agenda-start-on-weekday'. + +When WITH-HOUR is non-nil, only include scheduled and deadline +items if they have an hour specification like [h]h:mm." + (interactive "P") + (if org-agenda-overriding-arguments + (setq arg (car org-agenda-overriding-arguments) + start-day (nth 1 org-agenda-overriding-arguments) + span (nth 2 org-agenda-overriding-arguments))) + (if (and (integerp arg) (> arg 0)) + (setq span arg arg nil)) + (catch 'exit + (setq org-agenda-buffer-name + (or org-agenda-buffer-tmp-name + (and org-agenda-doing-sticky-redo org-agenda-buffer-name) + (if org-agenda-sticky + (cond ((and org-keys (stringp org-match)) + (format "*Org Agenda(%s:%s)*" org-keys org-match)) + (org-keys + (format "*Org Agenda(%s)*" org-keys)) + (t "*Org Agenda(a)*"))) + "*Org Agenda*")) + (org-agenda-prepare "Day/Week") + (setq start-day (or start-day org-agenda-start-day)) + (if (stringp start-day) + ;; Convert to an absolute day number + (setq start-day (time-to-days (org-read-date nil t start-day)))) + (org-compile-prefix-format 'agenda) + (org-set-sorting-strategy 'agenda) + (let* ((span (org-agenda-ndays-to-span (or span org-agenda-span))) + (today (org-today)) + (sd (or start-day today)) + (ndays (org-agenda-span-to-ndays span sd)) + (org-agenda-start-on-weekday + (if (or (eq ndays 7) (eq ndays 14)) + org-agenda-start-on-weekday)) + (thefiles (org-agenda-files nil 'ifmode)) + (files thefiles) + (start (if (or (null org-agenda-start-on-weekday) + (< ndays 7)) + sd + (let* ((nt (calendar-day-of-week + (calendar-gregorian-from-absolute sd))) + (n1 org-agenda-start-on-weekday) + (d (- nt n1))) + (- sd (+ (if (< d 0) 7 0) d))))) + (day-numbers (list start)) + (day-cnt 0) + (inhibit-redisplay (not debug-on-error)) + (org-agenda-show-log-scoped org-agenda-show-log) + s e rtn rtnall file date d start-pos end-pos todayp + clocktable-start clocktable-end filter) + (setq org-agenda-redo-command + (list 'org-agenda-list (list 'quote arg) start-day (list 'quote span) with-hour)) + (dotimes (n (1- ndays)) + (push (1+ (car day-numbers)) day-numbers)) + (setq day-numbers (nreverse day-numbers)) + (setq clocktable-start (car day-numbers) + clocktable-end (1+ (or (org-last day-numbers) 0))) + (setq-local org-starting-day (car day-numbers)) + (setq-local org-arg-loc arg) + (setq-local org-agenda-current-span (org-agenda-ndays-to-span span)) + (unless org-agenda-compact-blocks + (let* ((d1 (car day-numbers)) + (d2 (org-last day-numbers)) + (w1 (org-days-to-iso-week d1)) + (w2 (org-days-to-iso-week d2))) + (setq s (point)) + (if org-agenda-overriding-header + (insert (org-add-props (copy-sequence org-agenda-overriding-header) + nil 'face 'org-agenda-structure) "\n") + (insert (org-agenda-span-name span) + "-agenda" + (if (< (- d2 d1) 350) + (if (= w1 w2) + (format " (W%02d)" w1) + (format " (W%02d-W%02d)" w1 w2)) + "") + ":\n"))) + (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure + 'org-date-line t)) + (org-agenda-mark-header-line s)) + (while (setq d (pop day-numbers)) + (setq date (calendar-gregorian-from-absolute d) + s (point)) + (if (or (setq todayp (= d today)) + (and (not start-pos) (= d sd))) + (setq start-pos (point)) + (if (and start-pos (not end-pos)) + (setq end-pos (point)))) + (setq files thefiles + rtnall nil) + (while (setq file (pop files)) + (catch 'nextfile + (org-check-agenda-file file) + (let ((org-agenda-entry-types org-agenda-entry-types)) + ;; Starred types override non-starred equivalents + (when (member :deadline* org-agenda-entry-types) + (setq org-agenda-entry-types + (delq :deadline org-agenda-entry-types))) + (when (member :scheduled* org-agenda-entry-types) + (setq org-agenda-entry-types + (delq :scheduled org-agenda-entry-types))) + ;; Honor with-hour + (when with-hour + (when (member :deadline org-agenda-entry-types) + (setq org-agenda-entry-types + (delq :deadline org-agenda-entry-types)) + (push :deadline* org-agenda-entry-types)) + (when (member :scheduled org-agenda-entry-types) + (setq org-agenda-entry-types + (delq :scheduled org-agenda-entry-types)) + (push :scheduled* org-agenda-entry-types))) + (unless org-agenda-include-deadlines + (setq org-agenda-entry-types + (delq :deadline* (delq :deadline org-agenda-entry-types)))) + (cond + ((memq org-agenda-show-log-scoped '(only clockcheck)) + (setq rtn (org-agenda-get-day-entries + file date :closed))) + (org-agenda-show-log-scoped + (setq rtn (apply 'org-agenda-get-day-entries + file date + (append '(:closed) org-agenda-entry-types)))) + (t + (setq rtn (apply 'org-agenda-get-day-entries + file date + org-agenda-entry-types))))) + (setq rtnall (append rtnall rtn)))) ;; all entries + (if org-agenda-include-diary + (let ((org-agenda-search-headline-for-time t)) + (require 'diary-lib) + (setq rtn (org-get-entries-from-diary date)) + (setq rtnall (append rtnall rtn)))) + (if (or rtnall org-agenda-show-all-dates) + (progn + (setq day-cnt (1+ day-cnt)) + (insert + (if (stringp org-agenda-format-date) + (format-time-string org-agenda-format-date + (org-time-from-absolute date)) + (funcall org-agenda-format-date date)) + "\n") + (put-text-property s (1- (point)) 'face + (org-agenda-get-day-face date)) + (put-text-property s (1- (point)) 'org-date-line t) + (put-text-property s (1- (point)) 'org-agenda-date-header t) + (put-text-property s (1- (point)) 'org-day-cnt day-cnt) + (when todayp + (put-text-property s (1- (point)) 'org-today t)) + (setq rtnall + (org-agenda-add-time-grid-maybe rtnall ndays todayp)) + (if rtnall (insert ;; all entries + (org-agenda-finalize-entries rtnall 'agenda) + "\n")) + (put-text-property s (1- (point)) 'day d) + (put-text-property s (1- (point)) 'org-day-cnt day-cnt)))) + (when (and org-agenda-clockreport-mode clocktable-start) + (let ((org-agenda-files (org-agenda-files nil 'ifmode)) + ;; the above line is to ensure the restricted range! + (p (copy-sequence org-agenda-clockreport-parameter-plist)) + tbl) + (setq p (org-plist-delete p :block)) + (setq p (plist-put p :tstart clocktable-start)) + (setq p (plist-put p :tend clocktable-end)) + (setq p (plist-put p :scope 'agenda)) + (setq tbl (apply 'org-clock-get-clocktable p)) + (insert tbl))) + (goto-char (point-min)) + (or org-agenda-multi (org-agenda-fit-window-to-buffer)) + (unless (or (not (get-buffer-window)) + (and (pos-visible-in-window-p (point-min)) + (pos-visible-in-window-p (point-max)))) + (goto-char (1- (point-max))) + (recenter -1) + (if (not (pos-visible-in-window-p (or start-pos 1))) + (progn + (goto-char (or start-pos 1)) + (recenter 1)))) + (goto-char (or start-pos 1)) + (add-text-properties (point-min) (point-max) + `(org-agenda-type agenda + org-last-args (,arg ,start-day ,span) + org-redo-cmd ,org-agenda-redo-command + org-series-cmd ,org-cmd)) + (if (eq org-agenda-show-log-scoped 'clockcheck) + (org-agenda-show-clocking-issues)) + (org-agenda-finalize) + (setq buffer-read-only t) + (message "")))) + +(defun org-agenda-ndays-to-span (n) + "Return a span symbol for a span of N days, or N if none matches." + (cond ((symbolp n) n) + ((= n 1) 'day) + ((= n 7) 'week) + ((= n 14) 'fortnight) + (t n))) + +(defun org-agenda-span-to-ndays (span &optional start-day) + "Return ndays from SPAN, possibly starting at START-DAY. +START-DAY is an absolute time value." + (cond ((numberp span) span) + ((eq span 'day) 1) + ((eq span 'week) 7) + ((eq span 'fortnight) 14) + ((eq span 'month) + (let ((date (calendar-gregorian-from-absolute start-day))) + (calendar-last-day-of-month (car date) (cl-caddr date)))) + ((eq span 'year) + (let ((date (calendar-gregorian-from-absolute start-day))) + (if (calendar-leap-year-p (cl-caddr date)) 366 365))))) + +(defun org-agenda-span-name (span) + "Return a SPAN name." + (if (null span) + "" + (if (symbolp span) + (capitalize (symbol-name span)) + (format "%d days" span)))) + +;;; Agenda word search + +(defvar org-agenda-search-history nil) + +(defvar org-search-syntax-table nil + "Special syntax table for Org search. +In this table, we have single quotes not as word constituents, to +that when \"+Ameli\" is searched as a work, it will also match \"Ameli's\"") + +(defvar org-mode-syntax-table) ; From org.el +(defun org-search-syntax-table () + (unless org-search-syntax-table + (setq org-search-syntax-table (copy-syntax-table org-mode-syntax-table)) + (modify-syntax-entry ?' "." org-search-syntax-table) + (modify-syntax-entry ?` "." org-search-syntax-table)) + org-search-syntax-table) + +(defvar org-agenda-last-search-view-search-was-boolean nil) + +;;;###autoload +(defun org-search-view (&optional todo-only string edit-at) + "Show all entries that contain a phrase or words or regular expressions. + +With optional prefix argument TODO-ONLY, only consider entries that are +TODO entries. The argument STRING can be used to pass a default search +string into this function. If EDIT-AT is non-nil, it means that the +user should get a chance to edit this string, with cursor at position +EDIT-AT. + +The search string can be viewed either as a phrase that should be found as +is, or it can be broken into a number of snippets, each of which must match +in a Boolean way to select an entry. The default depends on the variable +`org-agenda-search-view-always-boolean'. +Even if this is turned off (the default) you can always switch to +Boolean search dynamically by preceding the first word with \"+\" or \"-\". + +The default is a direct search of the whole phrase, where each space in +the search string can expand to an arbitrary amount of whitespace, +including newlines. + +If using a Boolean search, the search string is split on whitespace and +each snippet is searched separately, with logical AND to select an entry. +Words prefixed with a minus must *not* occur in the entry. Words without +a prefix or prefixed with a plus must occur in the entry. Matching is +case-insensitive. Words are enclosed by word delimiters (i.e. they must +match whole words, not parts of a word) if +`org-agenda-search-view-force-full-words' is set (default is nil). + +Boolean search snippets enclosed by curly braces are interpreted as +regular expressions that must or (when preceded with \"-\") must not +match in the entry. Snippets enclosed into double quotes will be taken +as a whole, to include whitespace. + +- If the search string starts with an asterisk, search only in headlines. +- If (possibly after the leading star) the search string starts with an + exclamation mark, this also means to look at TODO entries only, an effect + that can also be achieved with a prefix argument. +- If (possibly after star and exclamation mark) the search string starts + with a colon, this will mean that the (non-regexp) snippets of the + Boolean search must match as full words. + +This command searches the agenda files, and in addition the files +listed in `org-agenda-text-search-extra-files' unless a restriction lock +is active." + (interactive "P") + (if org-agenda-overriding-arguments + (setq todo-only (car org-agenda-overriding-arguments) + string (nth 1 org-agenda-overriding-arguments) + edit-at (nth 2 org-agenda-overriding-arguments))) + (let* ((props (list 'face nil + 'done-face 'org-agenda-done + 'org-not-done-regexp org-not-done-regexp + 'org-todo-regexp org-todo-regexp + 'org-complex-heading-regexp org-complex-heading-regexp + 'mouse-face 'highlight + 'help-echo (format "mouse-2 or RET jump to location"))) + (full-words org-agenda-search-view-force-full-words) + (org-agenda-text-search-extra-files org-agenda-text-search-extra-files) + regexp rtn rtnall files file pos inherited-tags + marker category level tags c neg re boolean + ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str) + (unless (and (not edit-at) + (stringp string) + (string-match "\\S-" string)) + (setq string (read-string + (if org-agenda-search-view-always-boolean + "[+-]Word/{Regexp} ...: " + "Phrase or [+-]Word/{Regexp} ...: ") + (cond + ((integerp edit-at) (cons string edit-at)) + (edit-at string)) + 'org-agenda-search-history))) + (catch 'exit + (if org-agenda-sticky + (setq org-agenda-buffer-name + (if (stringp string) + (format "*Org Agenda(%s:%s)*" + (or org-keys (or (and todo-only "S") "s")) string) + (format "*Org Agenda(%s)*" (or (and todo-only "S") "s"))))) + (org-agenda-prepare "SEARCH") + (org-compile-prefix-format 'search) + (org-set-sorting-strategy 'search) + (setq org-agenda-redo-command + (list 'org-search-view (if todo-only t nil) + (list 'if 'current-prefix-arg nil string))) + (setq org-agenda-query-string string) + (if (equal (string-to-char string) ?*) + (setq hdl-only t + words (substring string 1)) + (setq words string)) + (when (equal (string-to-char words) ?!) + (setq todo-only t + words (substring words 1))) + (when (equal (string-to-char words) ?:) + (setq full-words t + words (substring words 1))) + (if (or org-agenda-search-view-always-boolean + (member (string-to-char words) '(?- ?+ ?\{))) + (setq boolean t)) + (setq words (split-string words)) + (let (www w) + (while (setq w (pop words)) + (while (and (string-match "\\\\\\'" w) words) + (setq w (concat (substring w 0 -1) " " (pop words)))) + (push w www)) + (setq words (nreverse www) www nil) + (while (setq w (pop words)) + (when (and (string-match "\\`[-+]?{" w) + (not (string-match "}\\'" w))) + (while (and words (not (string-match "}\\'" (car words)))) + (setq w (concat w " " (pop words)))) + (setq w (concat w " " (pop words)))) + (push w www)) + (setq words (nreverse www))) + (setq org-agenda-last-search-view-search-was-boolean boolean) + (when boolean + (let (wds w) + (while (setq w (pop words)) + (if (or (equal (substring w 0 1) "\"") + (and (> (length w) 1) + (member (substring w 0 1) '("+" "-")) + (equal (substring w 1 2) "\""))) + (while (and words (not (equal (substring w -1) "\""))) + (setq w (concat w " " (pop words))))) + (and (string-match "\\`\\([-+]?\\)\"" w) + (setq w (replace-match "\\1" nil nil w))) + (and (equal (substring w -1) "\"") (setq w (substring w 0 -1))) + (push w wds)) + (setq words (nreverse wds)))) + (if boolean + (mapc (lambda (w) + (setq c (string-to-char w)) + (if (equal c ?-) + (setq neg t w (substring w 1)) + (if (equal c ?+) + (setq neg nil w (substring w 1)) + (setq neg nil))) + (if (string-match "\\`{.*}\\'" w) + (setq re (substring w 1 -1)) + (if full-words + (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")) + (setq re (regexp-quote (downcase w))))) + (if neg (push re regexps-) (push re regexps+))) + words) + (push (mapconcat (lambda (w) (regexp-quote w)) words "\\s-+") + regexps+)) + (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b))))) + (if (not regexps+) + (setq regexp org-outline-regexp-bol) + (setq regexp (pop regexps+)) + (if hdl-only (setq regexp (concat org-outline-regexp-bol ".*?" + regexp)))) + (setq files (org-agenda-files nil 'ifmode)) + ;; Add `org-agenda-text-search-extra-files' unless there is some + ;; restriction. + (when (eq (car org-agenda-text-search-extra-files) 'agenda-archives) + (pop org-agenda-text-search-extra-files) + (unless (get 'org-agenda-files 'org-restrict) + (setq files (org-add-archive-files files)))) + ;; Uniquify files. However, let `org-check-agenda-file' handle + ;; non-existent ones. + (setq files (cl-remove-duplicates + (append files org-agenda-text-search-extra-files) + :test (lambda (a b) + (and (file-exists-p a) + (file-exists-p b) + (file-equal-p a b)))) + rtnall nil) + (while (setq file (pop files)) + (setq ee nil) + (catch 'nextfile + (org-check-agenda-file file) + (setq buffer (if (file-exists-p file) + (org-get-agenda-file-buffer file) + (error "No such file %s" file))) + (if (not buffer) + ;; If file does not exist, make sure an error message is sent + (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s" + file)))) + (with-current-buffer buffer + (with-syntax-table (org-search-syntax-table) + (unless (derived-mode-p 'org-mode) + (error "Agenda file %s is not in Org mode" file)) + (let ((case-fold-search t)) + (save-excursion + (save-restriction + (if (eq buffer org-agenda-restrict) + (narrow-to-region org-agenda-restrict-begin + org-agenda-restrict-end) + (widen)) + (goto-char (point-min)) + (unless (or (org-at-heading-p) + (outline-next-heading)) + (throw 'nextfile t)) + (goto-char (max (point-min) (1- (point)))) + (while (re-search-forward regexp nil t) + (org-back-to-heading t) + (while (and (not (zerop org-agenda-search-view-max-outline-level)) + (> (org-reduced-level (org-outline-level)) + org-agenda-search-view-max-outline-level) + (forward-line -1) + (org-back-to-heading t))) + (skip-chars-forward "* ") + (setq beg (point-at-bol) + beg1 (point) + end (progn + (outline-next-heading) + (while (and (not (zerop org-agenda-search-view-max-outline-level)) + (> (org-reduced-level (org-outline-level)) + org-agenda-search-view-max-outline-level) + (forward-line 1) + (outline-next-heading))) + (point))) + + (catch :skip + (goto-char beg) + (org-agenda-skip) + (setq str (buffer-substring-no-properties + (point-at-bol) + (if hdl-only (point-at-eol) end))) + (mapc (lambda (wr) (when (string-match wr str) + (goto-char (1- end)) + (throw :skip t))) + regexps-) + (mapc (lambda (wr) (unless (string-match wr str) + (goto-char (1- end)) + (throw :skip t))) + (if todo-only + (cons (concat "^\\*+[ \t]+" + org-not-done-regexp) + regexps+) + regexps+)) + (goto-char beg) + (setq marker (org-agenda-new-marker (point)) + category (org-get-category) + level (make-string (org-reduced-level (org-outline-level)) ? ) + inherited-tags + (or (eq org-agenda-show-inherited-tags 'always) + (and (listp org-agenda-show-inherited-tags) + (memq 'todo org-agenda-show-inherited-tags)) + (and (eq org-agenda-show-inherited-tags t) + (or (eq org-agenda-use-tag-inheritance t) + (memq 'todo org-agenda-use-tag-inheritance)))) + tags (org-get-tags-at nil (not inherited-tags)) + txt (org-agenda-format-item + "" + (buffer-substring-no-properties + beg1 (point-at-eol)) + level category tags t)) + (org-add-props txt props + 'org-marker marker 'org-hd-marker marker + 'org-todo-regexp org-todo-regexp + 'level level + 'org-complex-heading-regexp org-complex-heading-regexp + 'priority 1000 + 'type "search") + (push txt ee) + (goto-char (1- end)))))))))) + (setq rtn (nreverse ee)) + (setq rtnall (append rtnall rtn))) + (if org-agenda-overriding-header + (insert (org-add-props (copy-sequence org-agenda-overriding-header) + nil 'face 'org-agenda-structure) "\n") + (insert "Search words: ") + (add-text-properties (point-min) (1- (point)) + (list 'face 'org-agenda-structure)) + (setq pos (point)) + (insert string "\n") + (add-text-properties pos (1- (point)) (list 'face 'org-warning)) + (setq pos (point)) + (unless org-agenda-multi + (insert (substitute-command-keys "\ +Press `\\[org-agenda-manipulate-query-add]', \ +`\\[org-agenda-manipulate-query-subtract]' to add/sub word, \ +`\\[org-agenda-manipulate-query-add-re]', \ +`\\[org-agenda-manipulate-query-subtract-re]' to add/sub regexp, \ +`\\[universal-argument] \\[org-agenda-redo]' to edit\n")) + (add-text-properties pos (1- (point)) + (list 'face 'org-agenda-structure)))) + (org-agenda-mark-header-line (point-min)) + (when rtnall + (insert (org-agenda-finalize-entries rtnall 'search) "\n")) + (goto-char (point-min)) + (or org-agenda-multi (org-agenda-fit-window-to-buffer)) + (add-text-properties (point-min) (point-max) + `(org-agenda-type search + org-last-args (,todo-only ,string ,edit-at) + org-redo-cmd ,org-agenda-redo-command + org-series-cmd ,org-cmd)) + (org-agenda-finalize) + (setq buffer-read-only t)))) + +;;; Agenda TODO list + +(defun org-agenda-propertize-selected-todo-keywords (keywords) + "Use `org-todo-keyword-faces' for the selected todo KEYWORDS." + (concat + (if (or (equal keywords "ALL") (not keywords)) + (propertize "ALL" 'face 'warning) + (mapconcat + (lambda (kw) + (propertize kw 'face (org-get-todo-face kw))) + (org-split-string keywords "|") + "|")) + "\n")) + +(defvar org-select-this-todo-keyword nil) +(defvar org-last-arg nil) + +;;;###autoload +(defun org-todo-list (&optional arg) + "Show all (not done) TODO entries from all agenda file in a single list. +The prefix arg can be used to select a specific TODO keyword and limit +the list to these. When using `\\[universal-argument]', you will be prompted +for a keyword. A numeric prefix directly selects the Nth keyword in +`org-todo-keywords-1'." + (interactive "P") + (if org-agenda-overriding-arguments + (setq arg org-agenda-overriding-arguments)) + (if (and (stringp arg) (not (string-match "\\S-" arg))) (setq arg nil)) + (let* ((today (org-today)) + (date (calendar-gregorian-from-absolute today)) + (kwds org-todo-keywords-for-agenda) + (completion-ignore-case t) + (org-select-this-todo-keyword + (if (stringp arg) arg + (and arg (integerp arg) (> arg 0) + (nth (1- arg) kwds)))) + rtn rtnall files file pos) + (when (equal arg '(4)) + (setq org-select-this-todo-keyword + (completing-read "Keyword (or KWD1|K2D2|...): " + (mapcar #'list kwds) nil nil))) + (and (equal 0 arg) (setq org-select-this-todo-keyword nil)) + (catch 'exit + (if org-agenda-sticky + (setq org-agenda-buffer-name + (if (stringp org-select-this-todo-keyword) + (format "*Org Agenda(%s:%s)*" (or org-keys "t") + org-select-this-todo-keyword) + (format "*Org Agenda(%s)*" (or org-keys "t"))))) + (org-agenda-prepare "TODO") + (org-compile-prefix-format 'todo) + (org-set-sorting-strategy 'todo) + (setq org-agenda-redo-command + `(org-todo-list (or (and (numberp current-prefix-arg) + current-prefix-arg) + ,org-select-this-todo-keyword + current-prefix-arg ,arg))) + (setq files (org-agenda-files nil 'ifmode) + rtnall nil) + (while (setq file (pop files)) + (catch 'nextfile + (org-check-agenda-file file) + (setq rtn (org-agenda-get-day-entries file date :todo)) + (setq rtnall (append rtnall rtn)))) + (if org-agenda-overriding-header + (insert (org-add-props (copy-sequence org-agenda-overriding-header) + nil 'face 'org-agenda-structure) "\n") + (insert "Global list of TODO items of type: ") + (add-text-properties (point-min) (1- (point)) + (list 'face 'org-agenda-structure + 'short-heading + (concat "ToDo: " + (or org-select-this-todo-keyword "ALL")))) + (org-agenda-mark-header-line (point-min)) + (insert (org-agenda-propertize-selected-todo-keywords + org-select-this-todo-keyword)) + (setq pos (point)) + (unless org-agenda-multi + (insert (substitute-command-keys "Available with \ +`N \\[org-agenda-redo]': (0)[ALL]")) + (let ((n 0) s) + (mapc (lambda (x) + (setq s (format "(%d)%s" (setq n (1+ n)) x)) + (if (> (+ (current-column) (string-width s) 1) (frame-width)) + (insert "\n ")) + (insert " " s)) + kwds)) + (insert "\n")) + (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure))) + (org-agenda-mark-header-line (point-min)) + (when rtnall + (insert (org-agenda-finalize-entries rtnall 'todo) "\n")) + (goto-char (point-min)) + (or org-agenda-multi (org-agenda-fit-window-to-buffer)) + (add-text-properties (point-min) (point-max) + `(org-agenda-type todo + org-last-args ,arg + org-redo-cmd ,org-agenda-redo-command + org-series-cmd ,org-cmd)) + (org-agenda-finalize) + (setq buffer-read-only t)))) + +;;; Agenda tags match + +;;;###autoload +(defun org-tags-view (&optional todo-only match) + "Show all headlines for all `org-agenda-files' matching a TAGS criterion. +The prefix arg TODO-ONLY limits the search to TODO entries." + (interactive "P") + (if org-agenda-overriding-arguments + (setq todo-only (car org-agenda-overriding-arguments) + match (nth 1 org-agenda-overriding-arguments))) + (let* ((org-tags-match-list-sublevels + org-tags-match-list-sublevels) + (completion-ignore-case t) + (org--matcher-tags-todo-only todo-only) + rtn rtnall files file pos matcher + buffer) + (when (and (stringp match) (not (string-match "\\S-" match))) + (setq match nil)) + (catch 'exit + (if org-agenda-sticky + (setq org-agenda-buffer-name + (if (stringp match) + (format "*Org Agenda(%s:%s)*" + (or org-keys (or (and todo-only "M") "m")) match) + (format "*Org Agenda(%s)*" (or (and todo-only "M") "m"))))) + (setq matcher (org-make-tags-matcher match)) + ;; Prepare agendas (and `org-tag-alist-for-agenda') before + ;; expanding tags within `org-make-tags-matcher' + (org-agenda-prepare (concat "TAGS " match)) + (setq match (car matcher) + matcher (cdr matcher)) + (org-compile-prefix-format 'tags) + (org-set-sorting-strategy 'tags) + (setq org-agenda-query-string match) + (setq org-agenda-redo-command + (list 'org-tags-view + `(quote ,org--matcher-tags-todo-only) + `(if current-prefix-arg nil ,org-agenda-query-string))) + (setq files (org-agenda-files nil 'ifmode) + rtnall nil) + (while (setq file (pop files)) + (catch 'nextfile + (org-check-agenda-file file) + (setq buffer (if (file-exists-p file) + (org-get-agenda-file-buffer file) + (error "No such file %s" file))) + (if (not buffer) + ;; If file does not exist, error message to agenda + (setq rtn (list + (format "ORG-AGENDA-ERROR: No such org-file %s" file)) + rtnall (append rtnall rtn)) + (with-current-buffer buffer + (unless (derived-mode-p 'org-mode) + (error "Agenda file %s is not in Org mode" file)) + (save-excursion + (save-restriction + (if (eq buffer org-agenda-restrict) + (narrow-to-region org-agenda-restrict-begin + org-agenda-restrict-end) + (widen)) + (setq rtn (org-scan-tags 'agenda + matcher + org--matcher-tags-todo-only)) + (setq rtnall (append rtnall rtn)))))))) + (if org-agenda-overriding-header + (insert (org-add-props (copy-sequence org-agenda-overriding-header) + nil 'face 'org-agenda-structure) "\n") + (insert "Headlines with TAGS match: ") + (add-text-properties (point-min) (1- (point)) + (list 'face 'org-agenda-structure + 'short-heading + (concat "Match: " match))) + (setq pos (point)) + (insert match "\n") + (add-text-properties pos (1- (point)) (list 'face 'org-warning)) + (setq pos (point)) + (unless org-agenda-multi + (insert (substitute-command-keys + "Press `\\[universal-argument] \\[org-agenda-redo]' \ +to search again with new search string\n"))) + (add-text-properties pos (1- (point)) + (list 'face 'org-agenda-structure))) + (org-agenda-mark-header-line (point-min)) + (when rtnall + (insert (org-agenda-finalize-entries rtnall 'tags) "\n")) + (goto-char (point-min)) + (or org-agenda-multi (org-agenda-fit-window-to-buffer)) + (add-text-properties + (point-min) (point-max) + `(org-agenda-type tags + org-last-args (,org--matcher-tags-todo-only ,match) + org-redo-cmd ,org-agenda-redo-command + org-series-cmd ,org-cmd)) + (org-agenda-finalize) + (setq buffer-read-only t)))) + +;;; Agenda Finding stuck projects + +(defvar org-agenda-skip-regexp nil + "Regular expression used in skipping subtrees for the agenda. +This is basically a temporary global variable that can be set and then +used by user-defined selections using `org-agenda-skip-function'.") + +(defvar org-agenda-overriding-header nil + "When set during agenda, todo and tags searches it replaces the header. +This variable should not be set directly, but custom commands can bind it +in the options section.") + +(defun org-agenda-skip-entry-if (&rest conditions) + "Skip entry if any of CONDITIONS is true. +See `org-agenda-skip-if' for details." + (org-agenda-skip-if nil conditions)) + +(defun org-agenda-skip-subtree-if (&rest conditions) + "Skip subtree if any of CONDITIONS is true. +See `org-agenda-skip-if' for details." + (org-agenda-skip-if t conditions)) + +(defun org-agenda-skip-if (subtree conditions) + "Checks current entity for CONDITIONS. +If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only +the entry (i.e. the text before the next heading) is checked. + +CONDITIONS is a list of symbols, boolean OR is used to combine the results +from different tests. Valid conditions are: + +scheduled Check if there is a scheduled cookie +notscheduled Check if there is no scheduled cookie +deadline Check if there is a deadline +notdeadline Check if there is no deadline +timestamp Check if there is a timestamp (also deadline or scheduled) +nottimestamp Check if there is no timestamp (also deadline or scheduled) +regexp Check if regexp matches +notregexp Check if regexp does not match. +todo Check if TODO keyword matches +nottodo Check if TODO keyword does not match + +The regexp is taken from the conditions list, it must come right after +the `regexp' or `notregexp' element. + +`todo' and `nottodo' accept as an argument a list of todo +keywords, which may include \"*\" to match any todo keyword. + + (org-agenda-skip-entry-if \\='todo \\='(\"TODO\" \"WAITING\")) + +would skip all entries with \"TODO\" or \"WAITING\" keywords. + +Instead of a list, a keyword class may be given. For example: + + (org-agenda-skip-entry-if \\='nottodo \\='done) + +would skip entries that haven't been marked with any of \"DONE\" +keywords. Possible classes are: `todo', `done', `any'. + +If any of these conditions is met, this function returns the end point of +the entity, causing the search to continue from there. This is a function +that can be put into `org-agenda-skip-function' for the duration of a command." + (org-back-to-heading t) + (let* ((beg (point)) + (end (if subtree (save-excursion (org-end-of-subtree t) (point)) + (org-entry-end-position))) + (planning-end (if subtree end (line-end-position 2))) + m) + (and + (or (and (memq 'scheduled conditions) + (re-search-forward org-scheduled-time-regexp planning-end t)) + (and (memq 'notscheduled conditions) + (not + (save-excursion + (re-search-forward org-scheduled-time-regexp planning-end t)))) + (and (memq 'deadline conditions) + (re-search-forward org-deadline-time-regexp planning-end t)) + (and (memq 'notdeadline conditions) + (not + (save-excursion + (re-search-forward org-deadline-time-regexp planning-end t)))) + (and (memq 'timestamp conditions) + (re-search-forward org-ts-regexp end t)) + (and (memq 'nottimestamp conditions) + (not (save-excursion (re-search-forward org-ts-regexp end t)))) + (and (setq m (memq 'regexp conditions)) + (stringp (nth 1 m)) + (re-search-forward (nth 1 m) end t)) + (and (setq m (memq 'notregexp conditions)) + (stringp (nth 1 m)) + (not (save-excursion (re-search-forward (nth 1 m) end t)))) + (and (or + (setq m (memq 'nottodo conditions)) + (setq m (memq 'todo-unblocked conditions)) + (setq m (memq 'nottodo-unblocked conditions)) + (setq m (memq 'todo conditions))) + (org-agenda-skip-if-todo m end))) + end))) + +(defun org-agenda-skip-if-todo (args end) + "Helper function for `org-agenda-skip-if', do not use it directly. +ARGS is a list with first element either `todo', `nottodo', +`todo-unblocked' or `nottodo-unblocked'. The remainder is either +a list of TODO keywords, or a state symbol `todo' or `done' or +`any'." + (let ((todo-re + (concat "^\\*+[ \t]+" + (regexp-opt + (pcase args + (`(,_ todo) + (org-delete-all org-done-keywords + (copy-sequence org-todo-keywords-1))) + (`(,_ done) org-done-keywords) + (`(,_ any) org-todo-keywords-1) + (`(,_ ,(pred atom)) + (error "Invalid TODO class or type: %S" args)) + (`(,_ ,(pred (member "*"))) org-todo-keywords-1) + (`(,_ ,todo-list) todo-list)) + 'words)))) + (pcase args + (`(todo . ,_) + (let (case-fold-search) (re-search-forward todo-re end t))) + (`(nottodo . ,_) + (not (let (case-fold-search) (re-search-forward todo-re end t)))) + (`(todo-unblocked . ,_) + (catch :unblocked + (while (let (case-fold-search) (re-search-forward todo-re end t)) + (when (org-entry-blocked-p) (throw :unblocked t))) + nil)) + (`(nottodo-unblocked . ,_) + (catch :unblocked + (while (let (case-fold-search) (re-search-forward todo-re end t)) + (when (org-entry-blocked-p) (throw :unblocked nil))) + t)) + (`(,type . ,_) (error "Unknown TODO skip type: %S" type))))) + +;;;###autoload +(defun org-agenda-list-stuck-projects (&rest ignore) + "Create agenda view for projects that are stuck. +Stuck projects are project that have no next actions. For the definitions +of what a project is and how to check if it stuck, customize the variable +`org-stuck-projects'." + (interactive) + (let* ((org-agenda-overriding-header + (or org-agenda-overriding-header "List of stuck projects: ")) + (matcher (nth 0 org-stuck-projects)) + (todo (nth 1 org-stuck-projects)) + (tags (nth 2 org-stuck-projects)) + (gen-re (org-string-nw-p (nth 3 org-stuck-projects))) + (todo-wds + (if (not (member "*" todo)) todo + (org-agenda-prepare-buffers (org-agenda-files nil 'ifmode)) + (org-delete-all org-done-keywords-for-agenda + (copy-sequence org-todo-keywords-for-agenda)))) + (todo-re (and todo + (format "^\\*+[ \t]+\\(%s\\)\\>" + (mapconcat #'identity todo-wds "\\|")))) + (tags-re (cond ((null tags) nil) + ((member "*" tags) + (eval-when-compile + (concat org-outline-regexp-bol + ".*:[[:alnum:]_@#%]+:[ \t]*$"))) + (tags (concat org-outline-regexp-bol + ".*:\\(" + (mapconcat #'identity tags "\\|") + "\\):[[:alnum:]_@#%:]*[ \t]*$")) + (t nil))) + (re-list (delq nil (list todo-re tags-re gen-re))) + (skip-re + (if (null re-list) + (error "Missing information to identify unstuck projects") + (mapconcat #'identity re-list "\\|"))) + (org-agenda-skip-function + ;; Skip entry if `org-agenda-skip-regexp' matches anywhere + ;; in the subtree. + `(lambda () + (and (save-excursion + (let ((case-fold-search nil)) + (re-search-forward + ,skip-re (save-excursion (org-end-of-subtree t)) t))) + (progn (outline-next-heading) (point)))))) + (org-tags-view nil matcher) + (setq org-agenda-buffer-name (buffer-name)) + (with-current-buffer org-agenda-buffer-name + (setq org-agenda-redo-command + `(org-agenda-list-stuck-projects ,current-prefix-arg)) + (let ((inhibit-read-only t)) + (add-text-properties + (point-min) (point-max) + `(org-redo-cmd ,org-agenda-redo-command)))))) + +;;; Diary integration + +(defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param. +(defvar diary-list-entries-hook) +(defvar diary-time-regexp) +(defun org-get-entries-from-diary (date) + "Get the (Emacs Calendar) diary entries for DATE." + (require 'diary-lib) + (let* ((diary-fancy-buffer "*temporary-fancy-diary-buffer*") + (diary-display-function 'diary-fancy-display) + (pop-up-frames nil) + (diary-list-entries-hook + (cons 'org-diary-default-entry diary-list-entries-hook)) + (diary-file-name-prefix nil) ; turn this feature off + (diary-modify-entry-list-string-function 'org-modify-diary-entry-string) + entries + (org-disable-agenda-to-diary t)) + (save-excursion + (save-window-excursion + (funcall (if (fboundp 'diary-list-entries) + 'diary-list-entries 'list-diary-entries) + date 1))) + (if (not (get-buffer diary-fancy-buffer)) + (setq entries nil) + (with-current-buffer diary-fancy-buffer + (setq buffer-read-only nil) + (if (zerop (buffer-size)) + ;; No entries + (setq entries nil) + ;; Omit the date and other unnecessary stuff + (org-agenda-cleanup-fancy-diary) + ;; Add prefix to each line and extend the text properties + (if (zerop (buffer-size)) + (setq entries nil) + (setq entries (buffer-substring (point-min) (- (point-max) 1))) + (setq entries + (with-temp-buffer + (insert entries) (goto-char (point-min)) + (while (re-search-forward "\n[ \t]+\\(.+\\)$" nil t) + (unless (save-match-data (string-match diary-time-regexp (match-string 1))) + (replace-match (concat "; " (match-string 1))))) + (buffer-string))))) + (set-buffer-modified-p nil) + (kill-buffer diary-fancy-buffer))) + (when entries + (setq entries (org-split-string entries "\n")) + (setq entries + (mapcar + (lambda (x) + (setq x (org-agenda-format-item "" x nil "Diary" nil 'time)) + ;; Extend the text properties to the beginning of the line + (org-add-props x (text-properties-at (1- (length x)) x) + 'type "diary" 'date date 'face 'org-agenda-diary)) + entries))))) + +(defvar org-agenda-cleanup-fancy-diary-hook nil + "Hook run when the fancy diary buffer is cleaned up.") + +(defun org-agenda-cleanup-fancy-diary () + "Remove unwanted stuff in buffer created by `fancy-diary-display'. +This gets rid of the date, the underline under the date, and the +dummy entry installed by Org mode to ensure non-empty diary for +each date. It also removes lines that contain only whitespace." + (goto-char (point-min)) + (if (looking-at ".*?:[ \t]*") + (progn + (replace-match "") + (re-search-forward "\n=+$" nil t) + (replace-match "") + (while (re-search-backward "^ +\n?" nil t) (replace-match ""))) + (re-search-forward "\n=+$" nil t) + (delete-region (point-min) (min (point-max) (1+ (match-end 0))))) + (goto-char (point-min)) + (while (re-search-forward "^ +\n" nil t) + (replace-match "")) + (goto-char (point-min)) + (if (re-search-forward "^Org mode dummy\n?" nil t) + (replace-match "")) + (run-hooks 'org-agenda-cleanup-fancy-diary-hook)) + +;; Make sure entries from the diary have the right text properties. +(eval-after-load "diary-lib" + '(if (boundp 'diary-modify-entry-list-string-function) + ;; We can rely on the hook, nothing to do + nil + ;; Hook not available, must use advice to make this work + (defadvice add-to-diary-list (before org-mark-diary-entry activate) + "Make the position visible." + (if (and org-disable-agenda-to-diary ;; called from org-agenda + (stringp string) + buffer-file-name) + (setq string (org-modify-diary-entry-string string)))))) + +(defun org-modify-diary-entry-string (string) + "Add text properties to string, allowing Org to act on it." + (org-add-props string nil + 'mouse-face 'highlight + 'help-echo (if buffer-file-name + (format "mouse-2 or RET jump to diary file %s" + (abbreviate-file-name buffer-file-name)) + "") + 'org-agenda-diary-link t + 'org-marker (org-agenda-new-marker (point-at-bol)))) + +(defun org-diary-default-entry () + "Add a dummy entry to the diary. +Needed to avoid empty dates which mess up holiday display." + ;; Catch the error if dealing with the new add-to-diary-alist + (when org-disable-agenda-to-diary + (condition-case nil + (org-add-to-diary-list original-date "Org mode dummy" "") + (error + (org-add-to-diary-list original-date "Org mode dummy" "" nil))))) + +(defun org-add-to-diary-list (&rest args) + (if (fboundp 'diary-add-to-list) + (apply 'diary-add-to-list args) + (apply 'add-to-diary-list args))) + +(defvar org-diary-last-run-time nil) + +;;;###autoload +(defun org-diary (&rest args) + "Return diary information from org files. +This function can be used in a \"sexp\" diary entry in the Emacs calendar. +It accesses org files and extracts information from those files to be +listed in the diary. The function accepts arguments specifying what +items should be listed. For a list of arguments allowed here, see the +variable `org-agenda-entry-types'. + +The call in the diary file should look like this: + + &%%(org-diary) ~/path/to/some/orgfile.org + +Use a separate line for each org file to check. Or, if you omit the file name, +all files listed in `org-agenda-files' will be checked automatically: + + &%%(org-diary) + +If you don't give any arguments (as in the example above), the default value +of `org-agenda-entry-types' is used: (:deadline :scheduled :timestamp :sexp). +So the example above may also be written as + + &%%(org-diary :deadline :timestamp :sexp :scheduled) + +The function expects the lisp variables `entry' and `date' to be provided +by the caller, because this is how the calendar works. Don't use this +function from a program - use `org-agenda-get-day-entries' instead." + (when (> (- (float-time) + org-agenda-last-marker-time) + 5) + ;; I am not sure if this works with sticky agendas, because the marker + ;; list is then no longer a global variable. + (org-agenda-reset-markers)) + (org-compile-prefix-format 'agenda) + (org-set-sorting-strategy 'agenda) + (setq args (or args org-agenda-entry-types)) + (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry)) + (list entry) + (org-agenda-files t))) + (time (float-time)) + file rtn results) + (when (or (not org-diary-last-run-time) + (> (- time + org-diary-last-run-time) + 3)) + (org-agenda-prepare-buffers files)) + (setq org-diary-last-run-time time) + ;; If this is called during org-agenda, don't return any entries to + ;; the calendar. Org Agenda will list these entries itself. + (if org-disable-agenda-to-diary (setq files nil)) + (while (setq file (pop files)) + (setq rtn (apply 'org-agenda-get-day-entries file date args)) + (setq results (append results rtn))) + (when results + (setq results + (mapcar (lambda (i) (replace-regexp-in-string + org-bracket-link-regexp "\\3" i)) results)) + (concat (org-agenda-finalize-entries results) "\n")))) + +;;; Agenda entry finders + +(defun org-agenda--timestamp-to-absolute (&rest args) + "Call `org-time-string-to-absolute' with ARGS. +However, throw `:skip' whenever an error is raised." + (condition-case e + (apply #'org-time-string-to-absolute args) + (org-diary-sexp-no-match (throw :skip nil)) + (error + (message "%s; Skipping entry" (error-message-string e)) + (throw :skip nil)))) + +(defun org-agenda-get-day-entries (file date &rest args) + "Does the work for `org-diary' and `org-agenda'. +FILE is the path to a file to be checked for entries. DATE is date like +the one returned by `calendar-current-date'. ARGS are symbols indicating +which kind of entries should be extracted. For details about these, see +the documentation of `org-diary'." + (let* ((org-startup-folded nil) + (org-startup-align-all-tables nil) + (buffer (if (file-exists-p file) (org-get-agenda-file-buffer file) + (error "No such file %s" file)))) + (if (not buffer) + ;; If file does not exist, signal it in diary nonetheless. + (list (format "ORG-AGENDA-ERROR: No such org-file %s" file)) + (with-current-buffer buffer + (unless (derived-mode-p 'org-mode) + (error "Agenda file %s is not in Org mode" file)) + (setq org-agenda-buffer (or org-agenda-buffer buffer)) + (setf org-agenda-current-date date) + (save-excursion + (save-restriction + (if (eq buffer org-agenda-restrict) + (narrow-to-region org-agenda-restrict-begin + org-agenda-restrict-end) + (widen)) + ;; Rationalize ARGS. Also make sure `:deadline' comes + ;; first in order to populate DEADLINES before passing it. + ;; + ;; We use `delq' since `org-uniquify' duplicates ARGS, + ;; guarding us from modifying `org-agenda-entry-types'. + (setf args (org-uniquify (or args org-agenda-entry-types))) + (when (and (memq :scheduled args) (memq :scheduled* args)) + (setf args (delq :scheduled* args))) + (cond + ((memq :deadline args) + (setf args (cons :deadline + (delq :deadline (delq :deadline* args))))) + ((memq :deadline* args) + (setf args (cons :deadline* (delq :deadline* args))))) + ;; Collect list of headlines. Return them flattened. + (let ((case-fold-search nil) results deadlines) + (dolist (arg args (apply #'nconc (nreverse results))) + (pcase arg + ((and :todo (guard (org-agenda-today-p date))) + (push (org-agenda-get-todos) results)) + (:timestamp + (push (org-agenda-get-blocks) results) + (push (org-agenda-get-timestamps deadlines) results)) + (:sexp + (push (org-agenda-get-sexps) results)) + (:scheduled + (push (org-agenda-get-scheduled deadlines) results)) + (:scheduled* + (push (org-agenda-get-scheduled deadlines t) results)) + (:closed + (push (org-agenda-get-progress) results)) + (:deadline + (setf deadlines (org-agenda-get-deadlines)) + (push deadlines results)) + (:deadline* + (setf deadlines (org-agenda-get-deadlines t)) + (push deadlines results))))))))))) + +(defsubst org-em (x y list) + "Is X or Y a member of LIST?" + (or (memq x list) (memq y list))) + +(defvar org-heading-keyword-regexp-format) ; defined in org.el +(defvar org-agenda-sorting-strategy-selected nil) + +(defun org-agenda-entry-get-agenda-timestamp (pom) + "Retrieve timestamp information for sorting agenda views. +Given a point or marker POM, returns a cons cell of the timestamp +and the timestamp type relevant for the sorting strategy in +`org-agenda-sorting-strategy-selected'." + (let (ts ts-date-type) + (save-match-data + (cond ((org-em 'scheduled-up 'scheduled-down + org-agenda-sorting-strategy-selected) + (setq ts (org-entry-get pom "SCHEDULED") + ts-date-type " scheduled")) + ((org-em 'deadline-up 'deadline-down + org-agenda-sorting-strategy-selected) + (setq ts (org-entry-get pom "DEADLINE") + ts-date-type " deadline")) + ((org-em 'ts-up 'ts-down + org-agenda-sorting-strategy-selected) + (setq ts (org-entry-get pom "TIMESTAMP") + ts-date-type " timestamp")) + ((org-em 'tsia-up 'tsia-down + org-agenda-sorting-strategy-selected) + (setq ts (org-entry-get pom "TIMESTAMP_IA") + ts-date-type " timestamp_ia")) + ((org-em 'timestamp-up 'timestamp-down + org-agenda-sorting-strategy-selected) + (setq ts (or (org-entry-get pom "SCHEDULED") + (org-entry-get pom "DEADLINE") + (org-entry-get pom "TIMESTAMP") + (org-entry-get pom "TIMESTAMP_IA")) + ts-date-type "")) + (t (setq ts-date-type ""))) + (cons (when ts (ignore-errors (org-time-string-to-absolute ts))) + ts-date-type)))) + +(defun org-agenda-get-todos () + "Return the TODO information for agenda display." + (let* ((props (list 'face nil + 'done-face 'org-agenda-done + 'org-not-done-regexp org-not-done-regexp + 'org-todo-regexp org-todo-regexp + 'org-complex-heading-regexp org-complex-heading-regexp + 'mouse-face 'highlight + 'help-echo + (format "mouse-2 or RET jump to org file %s" + (abbreviate-file-name buffer-file-name)))) + (case-fold-search nil) + (regexp (format org-heading-keyword-regexp-format + (cond + ((and org-select-this-todo-keyword + (equal org-select-this-todo-keyword "*")) + org-todo-regexp) + (org-select-this-todo-keyword + (concat "\\(" + (mapconcat 'identity + (org-split-string + org-select-this-todo-keyword + "|") + "\\|") "\\)")) + (t org-not-done-regexp)))) + marker priority category level tags todo-state + ts-date ts-date-type ts-date-pair + ee txt beg end inherited-tags todo-state-end-pos) + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (catch :skip + (save-match-data + (beginning-of-line) + (org-agenda-skip) + (setq beg (point) end (save-excursion (outline-next-heading) (point))) + (unless (and (setq todo-state (org-get-todo-state)) + (setq todo-state-end-pos (match-end 2))) + (goto-char end) + (throw :skip nil)) + (when (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item end) + (goto-char (1+ beg)) + (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible)) + (throw :skip nil))) + (goto-char (match-beginning 2)) + (setq marker (org-agenda-new-marker (match-beginning 0)) + category (org-get-category) + ts-date-pair (org-agenda-entry-get-agenda-timestamp (point)) + ts-date (car ts-date-pair) + ts-date-type (cdr ts-date-pair) + txt (org-trim (buffer-substring (match-beginning 2) (match-end 0))) + inherited-tags + (or (eq org-agenda-show-inherited-tags 'always) + (and (listp org-agenda-show-inherited-tags) + (memq 'todo org-agenda-show-inherited-tags)) + (and (eq org-agenda-show-inherited-tags t) + (or (eq org-agenda-use-tag-inheritance t) + (memq 'todo org-agenda-use-tag-inheritance)))) + tags (org-get-tags-at nil (not inherited-tags)) + level (make-string (org-reduced-level (org-outline-level)) ? ) + txt (org-agenda-format-item "" txt level category tags t) + priority (1+ (org-get-priority txt))) + (org-add-props txt props + 'org-marker marker 'org-hd-marker marker + 'priority priority + 'level level + 'ts-date ts-date + 'type (concat "todo" ts-date-type) 'todo-state todo-state) + (push txt ee) + (if org-agenda-todo-list-sublevels + (goto-char todo-state-end-pos) + (org-end-of-subtree 'invisible)))) + (nreverse ee))) + +(defun org-agenda-todo-custom-ignore-p (time n) + "Check whether timestamp is farther away than n number of days. +This function is invoked if `org-agenda-todo-ignore-deadlines', +`org-agenda-todo-ignore-scheduled' or +`org-agenda-todo-ignore-timestamp' is set to an integer." + (let ((days (org-time-stamp-to-now + time org-agenda-todo-ignore-time-comparison-use-seconds))) + (if (>= n 0) + (>= days n) + (<= days n)))) + +;;;###autoload +(defun org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item + (&optional end) + "Do we have a reason to ignore this TODO entry because it has a time stamp?" + (when (or org-agenda-todo-ignore-with-date + org-agenda-todo-ignore-scheduled + org-agenda-todo-ignore-deadlines + org-agenda-todo-ignore-timestamp) + (setq end (or end (save-excursion (outline-next-heading) (point)))) + (save-excursion + (or (and org-agenda-todo-ignore-with-date + (re-search-forward org-ts-regexp end t)) + (and org-agenda-todo-ignore-scheduled + (re-search-forward org-scheduled-time-regexp end t) + (cond + ((eq org-agenda-todo-ignore-scheduled 'future) + (> (org-time-stamp-to-now + (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0)) + ((eq org-agenda-todo-ignore-scheduled 'past) + (<= (org-time-stamp-to-now + (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0)) + ((numberp org-agenda-todo-ignore-scheduled) + (org-agenda-todo-custom-ignore-p + (match-string 1) org-agenda-todo-ignore-scheduled)) + (t))) + (and org-agenda-todo-ignore-deadlines + (re-search-forward org-deadline-time-regexp end t) + (cond + ((memq org-agenda-todo-ignore-deadlines '(t all)) t) + ((eq org-agenda-todo-ignore-deadlines 'far) + (not (org-deadline-close-p (match-string 1)))) + ((eq org-agenda-todo-ignore-deadlines 'future) + (> (org-time-stamp-to-now + (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0)) + ((eq org-agenda-todo-ignore-deadlines 'past) + (<= (org-time-stamp-to-now + (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0)) + ((numberp org-agenda-todo-ignore-deadlines) + (org-agenda-todo-custom-ignore-p + (match-string 1) org-agenda-todo-ignore-deadlines)) + (t (org-deadline-close-p (match-string 1))))) + (and org-agenda-todo-ignore-timestamp + (let ((buffer (current-buffer)) + (regexp + (concat + org-scheduled-time-regexp "\\|" org-deadline-time-regexp)) + (start (point))) + ;; Copy current buffer into a temporary one + (with-temp-buffer + (insert-buffer-substring buffer start end) + (goto-char (point-min)) + ;; Delete SCHEDULED and DEADLINE items + (while (re-search-forward regexp end t) + (delete-region (match-beginning 0) (match-end 0))) + (goto-char (point-min)) + ;; No search for timestamp left + (when (re-search-forward org-ts-regexp nil t) + (cond + ((eq org-agenda-todo-ignore-timestamp 'future) + (> (org-time-stamp-to-now + (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0)) + ((eq org-agenda-todo-ignore-timestamp 'past) + (<= (org-time-stamp-to-now + (match-string 1) org-agenda-todo-ignore-time-comparison-use-seconds) 0)) + ((numberp org-agenda-todo-ignore-timestamp) + (org-agenda-todo-custom-ignore-p + (match-string 1) org-agenda-todo-ignore-timestamp)) + (t)))))))))) + +(defun org-agenda-get-timestamps (&optional deadlines) + "Return the date stamp information for agenda display. +Optional argument DEADLINES is a list of deadline items to be +displayed in agenda view." + (let* ((props (list 'face 'org-agenda-calendar-event + 'org-not-done-regexp org-not-done-regexp + 'org-todo-regexp org-todo-regexp + 'org-complex-heading-regexp org-complex-heading-regexp + 'mouse-face 'highlight + 'help-echo + (format "mouse-2 or RET jump to Org file %s" + (abbreviate-file-name buffer-file-name)))) + (current (calendar-absolute-from-gregorian date)) + (today (org-today)) + (deadline-position-alist + (mapcar (lambda (d) + (let ((m (get-text-property 0 'org-hd-marker d))) + (and m (marker-position m)))) + deadlines)) + ;; Match time-stamps set to current date, time-stamps with + ;; a repeater, and S-exp time-stamps. + (regexp + (concat + (if org-agenda-include-inactive-timestamps "[[<]" "<") + (regexp-quote + (substring + (format-time-string + (car org-time-stamp-formats) + (apply #'encode-time ; DATE bound by calendar + (list 0 0 0 (nth 1 date) (car date) (nth 2 date)))) + 1 11)) + "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[hdwmy]>\\)" + "\\|\\(<%%\\(([^>\n]+)\\)>\\)")) + timestamp-items) + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + ;; Skip date ranges, scheduled and deadlines, which are handled + ;; specially. Also skip time-stamps before first headline as + ;; there would be no entry to add to the agenda. Eventually, + ;; ignore clock entries. + (catch :skip + (save-match-data + (when (or (org-at-date-range-p) + (org-at-planning-p) + (org-before-first-heading-p) + (and org-agenda-include-inactive-timestamps + (org-at-clock-log-p))) + (throw :skip nil)) + (org-agenda-skip)) + (let* ((pos (match-beginning 0)) + (repeat (match-string 1)) + (sexp-entry (match-string 3)) + (time-stamp (if (or repeat sexp-entry) (match-string 0) + (save-excursion + (goto-char pos) + (looking-at org-ts-regexp-both) + (match-string 0)))) + (todo-state (org-get-todo-state)) + (warntime (get-text-property (point) 'org-appt-warntime)) + (done? (member todo-state org-done-keywords))) + ;; Possibly skip done tasks. + (when (and done? org-agenda-skip-timestamp-if-done) + (throw :skip t)) + ;; S-exp entry doesn't match current day: skip it. + (when (and sexp-entry (not (org-diary-sexp-entry sexp-entry "" date))) + (throw :skip nil)) + (when repeat + (let* ((past + ;; A repeating time stamp is shown at its base + ;; date and every repeated date up to TODAY. If + ;; `org-agenda-prefer-last-repeat' is non-nil, + ;; however, only the last repeat before today + ;; (inclusive) is shown. + (org-agenda--timestamp-to-absolute + repeat + (if (or (> current today) + (eq org-agenda-prefer-last-repeat t) + (member todo-state org-agenda-prefer-last-repeat)) + today + current) + 'past (current-buffer) pos)) + (future + ;; Display every repeated date past TODAY + ;; (exclusive) unless + ;; `org-agenda-show-future-repeats' is nil. If + ;; this variable is set to `next', only display + ;; the first repeated date after TODAY + ;; (exclusive). + (cond + ((<= current today) past) + ((not org-agenda-show-future-repeats) past) + (t + (let ((base (if (eq org-agenda-show-future-repeats 'next) + (1+ today) + current))) + (org-agenda--timestamp-to-absolute + repeat base 'future (current-buffer) pos)))))) + (when (and (/= current past) (/= current future)) + (throw :skip nil)))) + (save-excursion + (re-search-backward org-outline-regexp-bol nil t) + ;; Possibly skip time-stamp when a deadline is set. + (when (and org-agenda-skip-timestamp-if-deadline-is-shown + (assq (point) deadline-position-alist)) + (throw :skip nil)) + (let* ((category (org-get-category pos)) + (inherited-tags + (or (eq org-agenda-show-inherited-tags 'always) + (and (consp org-agenda-show-inherited-tags) + (memq 'agenda org-agenda-show-inherited-tags)) + (and (eq org-agenda-show-inherited-tags t) + (or (eq org-agenda-use-tag-inheritance t) + (memq 'agenda + org-agenda-use-tag-inheritance))))) + (tags (org-get-tags-at nil (not inherited-tags))) + (level (make-string (org-reduced-level (org-outline-level)) + ?\s)) + (head (and (looking-at "\\*+[ \t]+\\(.*\\)") + (match-string 1))) + (inactive? (= (char-after pos) ?\[)) + (habit? (and (fboundp 'org-is-habit-p) (org-is-habit-p))) + (item + (org-agenda-format-item + (and inactive? org-agenda-inactive-leader) + head level category tags time-stamp org-ts-regexp habit?))) + (org-add-props item props + 'priority (if habit? + (org-habit-get-priority (org-habit-parse-todo)) + (org-get-priority item)) + 'org-marker (org-agenda-new-marker pos) + 'org-hd-marker (org-agenda-new-marker) + 'date date + 'level level + 'ts-date (if repeat (org-agenda--timestamp-to-absolute repeat) + current) + 'todo-state todo-state + 'warntime warntime + 'type "timestamp") + (push item timestamp-items)))) + (when org-agenda-skip-additional-timestamps-same-entry + (outline-next-heading)))) + (nreverse timestamp-items))) + +(defun org-agenda-get-sexps () + "Return the sexp information for agenda display." + (require 'diary-lib) + (let* ((props (list 'face 'org-agenda-calendar-sexp + 'mouse-face 'highlight + 'help-echo + (format "mouse-2 or RET jump to org file %s" + (abbreviate-file-name buffer-file-name)))) + (regexp "^&?%%(") + marker category extra level ee txt tags entry + result beg b sexp sexp-entry todo-state warntime inherited-tags) + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (catch :skip + (org-agenda-skip) + (setq beg (match-beginning 0)) + (goto-char (1- (match-end 0))) + (setq b (point)) + (forward-sexp 1) + (setq sexp (buffer-substring b (point))) + (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)") + (org-trim (match-string 1)) + "")) + (setq result (org-diary-sexp-entry sexp sexp-entry date)) + (when result + (setq marker (org-agenda-new-marker beg) + level (make-string (org-reduced-level (org-outline-level)) ? ) + category (org-get-category beg) + inherited-tags + (or (eq org-agenda-show-inherited-tags 'always) + (and (listp org-agenda-show-inherited-tags) + (memq 'agenda org-agenda-show-inherited-tags)) + (and (eq org-agenda-show-inherited-tags t) + (or (eq org-agenda-use-tag-inheritance t) + (memq 'agenda org-agenda-use-tag-inheritance)))) + tags (org-get-tags-at nil (not inherited-tags)) + todo-state (org-get-todo-state) + warntime (get-text-property (point) 'org-appt-warntime) + extra nil) + + (dolist (r (if (stringp result) + (list result) + result)) ;; we expect a list here + (when (and org-agenda-diary-sexp-prefix + (string-match org-agenda-diary-sexp-prefix r)) + (setq extra (match-string 0 r) + r (replace-match "" nil nil r))) + (if (string-match "\\S-" r) + (setq txt r) + (setq txt "SEXP entry returned empty string")) + (setq txt (org-agenda-format-item extra txt level category tags 'time)) + (org-add-props txt props 'org-marker marker + 'date date 'todo-state todo-state + 'level level 'type "sexp" 'warntime warntime) + (push txt ee))))) + (nreverse ee))) + +;; Calendar sanity: define some functions that are independent of +;; `calendar-date-style'. +(defun org-anniversary (year month day &optional mark) + "Like `diary-anniversary', but with fixed (ISO) order of arguments." + (with-no-warnings + (let ((calendar-date-style 'iso)) + (diary-anniversary year month day mark)))) +(defun org-cyclic (N year month day &optional mark) + "Like `diary-cyclic', but with fixed (ISO) order of arguments." + (with-no-warnings + (let ((calendar-date-style 'iso)) + (diary-cyclic N year month day mark)))) +(defun org-block (Y1 M1 D1 Y2 M2 D2 &optional mark) + "Like `diary-block', but with fixed (ISO) order of arguments." + (with-no-warnings + (let ((calendar-date-style 'iso)) + (diary-block Y1 M1 D1 Y2 M2 D2 mark)))) +(defun org-date (year month day &optional mark) + "Like `diary-date', but with fixed (ISO) order of arguments." + (with-no-warnings + (let ((calendar-date-style 'iso)) + (diary-date year month day mark)))) + +;; Define the `org-class' function +(defun org-class (y1 m1 d1 y2 m2 d2 dayname &rest skip-weeks) + "Entry applies if date is between dates on DAYNAME, but skips SKIP-WEEKS. +DAYNAME is a number between 0 (Sunday) and 6 (Saturday). +SKIP-WEEKS is any number of ISO weeks in the block period for which the +item should be skipped. If any of the SKIP-WEEKS arguments is the symbol +`holidays', then any date that is known by the Emacs calendar to be a +holiday will also be skipped. If SKIP-WEEKS arguments are holiday strings, +then those holidays will be skipped." + (let* ((date1 (calendar-absolute-from-gregorian (list m1 d1 y1))) + (date2 (calendar-absolute-from-gregorian (list m2 d2 y2))) + (d (calendar-absolute-from-gregorian date)) + (h (when skip-weeks (calendar-check-holidays date)))) + (and + (<= date1 d) + (<= d date2) + (= (calendar-day-of-week date) dayname) + (or (not skip-weeks) + (progn + (require 'cal-iso) + (not (member (car (calendar-iso-from-absolute d)) skip-weeks)))) + (not (or (and h (memq 'holidays skip-weeks)) + (delq nil (mapcar (lambda(g) (member g skip-weeks)) h)))) + entry))) + +(defalias 'org-get-closed 'org-agenda-get-progress) +(defun org-agenda-get-progress () + "Return the logged TODO entries for agenda display." + (let* ((props (list 'mouse-face 'highlight + 'org-not-done-regexp org-not-done-regexp + 'org-todo-regexp org-todo-regexp + 'org-complex-heading-regexp org-complex-heading-regexp + 'help-echo + (format "mouse-2 or RET jump to org file %s" + (abbreviate-file-name buffer-file-name)))) + (items (if (consp org-agenda-show-log-scoped) + org-agenda-show-log-scoped + (if (eq org-agenda-show-log-scoped 'clockcheck) + '(clock) + org-agenda-log-mode-items))) + (parts + (delq nil + (list + (if (memq 'closed items) (concat "\\<" org-closed-string)) + (if (memq 'clock items) (concat "\\<" org-clock-string)) + (if (memq 'state items) + (format "- State \"%s\".*?" org-todo-regexp))))) + (parts-re (if parts (mapconcat 'identity parts "\\|") + (error "`org-agenda-log-mode-items' is empty"))) + (regexp (concat + "\\(" parts-re "\\)" + " *\\[" + (regexp-quote + (substring + (format-time-string + (car org-time-stamp-formats) + (apply 'encode-time ; DATE bound by calendar + (list 0 0 0 (nth 1 date) (car date) (nth 2 date)))) + 1 11)))) + (org-agenda-search-headline-for-time nil) + marker hdmarker priority category level tags closedp + statep clockp state ee txt extra timestr rest clocked inherited-tags) + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (catch :skip + (org-agenda-skip) + (setq marker (org-agenda-new-marker (match-beginning 0)) + closedp (equal (match-string 1) org-closed-string) + statep (equal (string-to-char (match-string 1)) ?-) + clockp (not (or closedp statep)) + state (and statep (match-string 2)) + category (org-get-category (match-beginning 0)) + timestr (buffer-substring (match-beginning 0) (point-at-eol))) + (when (string-match "\\]" timestr) + ;; substring should only run to end of time stamp + (setq rest (substring timestr (match-end 0)) + timestr (substring timestr 0 (match-end 0))) + (if (and (not closedp) (not statep) + (string-match "\\([0-9]\\{1,2\\}:[0-9]\\{2\\}\\)\\].*?\\([0-9]\\{1,2\\}:[0-9]\\{2\\}\\)" + rest)) + (progn (setq timestr (concat (substring timestr 0 -1) + "-" (match-string 1 rest) "]")) + (setq clocked (match-string 2 rest))) + (setq clocked "-"))) + (save-excursion + (setq extra + (cond + ((not org-agenda-log-mode-add-notes) nil) + (statep + (and (looking-at ".*\\\\\n[ \t]*\\([^-\n \t].*?\\)[ \t]*$") + (match-string 1))) + (clockp + (and (looking-at ".*\n[ \t]*-[ \t]+\\([^-\n \t].*?\\)[ \t]*$") + (match-string 1))))) + (if (not (re-search-backward org-outline-regexp-bol nil t)) + (throw :skip nil) + (goto-char (match-beginning 0)) + (setq hdmarker (org-agenda-new-marker) + inherited-tags + (or (eq org-agenda-show-inherited-tags 'always) + (and (listp org-agenda-show-inherited-tags) + (memq 'todo org-agenda-show-inherited-tags)) + (and (eq org-agenda-show-inherited-tags t) + (or (eq org-agenda-use-tag-inheritance t) + (memq 'todo org-agenda-use-tag-inheritance)))) + tags (org-get-tags-at nil (not inherited-tags)) + level (make-string (org-reduced-level (org-outline-level)) ? )) + (looking-at "\\*+[ \t]+\\([^\r\n]+\\)") + (setq txt (match-string 1)) + (when extra + (if (string-match "\\([ \t]+\\)\\(:[^ \n\t]*?:\\)[ \t]*$" txt) + (setq txt (concat (substring txt 0 (match-beginning 1)) + " - " extra " " (match-string 2 txt))) + (setq txt (concat txt " - " extra)))) + (setq txt (org-agenda-format-item + (cond + (closedp "Closed: ") + (statep (concat "State: (" state ")")) + (t (concat "Clocked: (" clocked ")"))) + txt level category tags timestr))) + (setq priority 100000) + (org-add-props txt props + 'org-marker marker 'org-hd-marker hdmarker 'face 'org-agenda-done + 'priority priority 'level level + 'type "closed" 'date date + 'undone-face 'org-warning 'done-face 'org-agenda-done) + (push txt ee)) + (goto-char (point-at-eol)))) + (nreverse ee))) + +(defun org-agenda-show-clocking-issues () + "Add overlays, showing issues with clocking. +See also the user option `org-agenda-clock-consistency-checks'." + (interactive) + (let* ((pl org-agenda-clock-consistency-checks) + (re (concat "^[ \t]*" + org-clock-string + "[ \t]+" + "\\(\\[.*?\\]\\)" ; group 1 is first stamp + "\\(-\\{1,3\\}\\(\\[.*?\\]\\)\\)?")) ; group 3 is second + (tlstart 0.) + (tlend 0.) + (maxtime (org-duration-to-minutes + (or (plist-get pl :max-duration) "24:00"))) + (mintime (org-duration-to-minutes + (or (plist-get pl :min-duration) 0))) + (maxgap (org-duration-to-minutes + ;; default 30:00 means never complain + (or (plist-get pl :max-gap) "30:00"))) + (gapok (mapcar #'org-duration-to-minutes + (plist-get pl :gap-ok-around))) + (def-face (or (plist-get pl :default-face) + '((:background "DarkRed") (:foreground "white")))) + issue face m te ts dt ov) + (goto-char (point-min)) + (while (re-search-forward " Clocked: +(-\\|\\([0-9]+:[0-9]+\\))" nil t) + (setq issue nil face def-face) + (catch 'next + (setq m (org-get-at-bol 'org-marker) + te nil ts nil) + (unless (and m (markerp m)) + (setq issue "No valid clock line") (throw 'next t)) + (org-with-point-at m + (save-excursion + (goto-char (point-at-bol)) + (unless (looking-at re) + (error "No valid Clock line") + (throw 'next t)) + (unless (match-end 3) + (setq issue "No end time" + face (or (plist-get pl :no-end-time-face) face)) + (throw 'next t)) + (setq ts (match-string 1) + te (match-string 3) + ts (float-time + (apply #'encode-time (org-parse-time-string ts))) + te (float-time + (apply #'encode-time (org-parse-time-string te))) + dt (- te ts)))) + (cond + ((> dt (* 60 maxtime)) + ;; a very long clocking chunk + (setq issue (format "Clocking interval is very long: %s" + (org-duration-from-minutes (floor (/ dt 60.)))) + face (or (plist-get pl :long-face) face))) + ((< dt (* 60 mintime)) + ;; a very short clocking chunk + (setq issue (format "Clocking interval is very short: %s" + (org-duration-from-minutes (floor (/ dt 60.)))) + face (or (plist-get pl :short-face) face))) + ((and (> tlend 0) (< ts tlend)) + ;; Two clock entries are overlapping + (setq issue (format "Clocking overlap: %d minutes" + (/ (- tlend ts) 60)) + face (or (plist-get pl :overlap-face) face))) + ((and (> tlend 0) (> ts (+ tlend (* 60 maxgap)))) + ;; There is a gap, lets see if we need to report it + (unless (org-agenda-check-clock-gap tlend ts gapok) + (setq issue (format "Clocking gap: %d minutes" + (/ (- ts tlend) 60)) + face (or (plist-get pl :gap-face) face)))) + (t nil))) + (setq tlend (or te tlend) tlstart (or ts tlstart)) + (when issue + ;; OK, there was some issue, add an overlay to show the issue + (setq ov (make-overlay (point-at-bol) (point-at-eol))) + (overlay-put ov 'before-string + (concat + (org-add-props + (format "%-43s" (concat " " issue)) + nil + 'face face) + "\n")) + (overlay-put ov 'evaporate t))))) + +(defun org-agenda-check-clock-gap (t1 t2 ok-list) + "Check if gap T1 -> T2 contains one of the OK-LIST time-of-day values." + (catch 'exit + (unless ok-list + ;; there are no OK times for gaps... + (throw 'exit nil)) + (if (> (- (/ t2 36000) (/ t1 36000)) 24) + ;; This is more than 24 hours, so it is OK. + ;; because we have at least one OK time, that must be in the + ;; 24 hour interval. + (throw 'exit t)) + ;; We have a shorter gap. + ;; Now we have to get the minute of the day when these times are + (let* ((t1dec (decode-time (seconds-to-time t1))) + (t2dec (decode-time (seconds-to-time t2))) + ;; compute the minute on the day + (min1 (+ (nth 1 t1dec) (* 60 (nth 2 t1dec)))) + (min2 (+ (nth 1 t2dec) (* 60 (nth 2 t2dec))))) + (when (< min2 min1) + ;; if min2 is smaller than min1, this means it is on the next day. + ;; Wrap it to after midnight. + (setq min2 (+ min2 1440))) + ;; Now check if any of the OK times is in the gap + (mapc (lambda (x) + ;; Wrap the time to after midnight if necessary + (if (< x min1) (setq x (+ x 1440))) + ;; Check if in interval + (and (<= min1 x) (>= min2 x) (throw 'exit t))) + ok-list) + ;; Nope, this gap is not OK + nil))) + +(defun org-agenda-get-deadlines (&optional with-hour) + "Return the deadline information for agenda display. +When WITH-HOUR is non-nil, only return deadlines with an hour +specification like [h]h:mm." + (let* ((props (list 'mouse-face 'highlight + 'org-not-done-regexp org-not-done-regexp + 'org-todo-regexp org-todo-regexp + 'org-complex-heading-regexp org-complex-heading-regexp + 'help-echo + (format "mouse-2 or RET jump to org file %s" + (abbreviate-file-name buffer-file-name)))) + (regexp (if with-hour + org-deadline-time-hour-regexp + org-deadline-time-regexp)) + (today (org-today)) + (today? (org-agenda-today-p date)) ; DATE bound by calendar. + (current (calendar-absolute-from-gregorian date)) + deadline-items) + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (catch :skip + (unless (save-match-data (org-at-planning-p)) (throw :skip nil)) + (org-agenda-skip) + (let* ((s (match-string 1)) + (pos (1- (match-beginning 1))) + (todo-state (save-match-data (org-get-todo-state))) + (done? (member todo-state org-done-keywords)) + (sexp? (string-prefix-p "%%" s)) + ;; DEADLINE is the deadline date for the entry. It is + ;; either the base date or the last repeat, according + ;; to `org-agenda-prefer-last-repeat'. + (deadline + (cond + (sexp? (org-agenda--timestamp-to-absolute s current)) + ((or (eq org-agenda-prefer-last-repeat t) + (member todo-state org-agenda-prefer-last-repeat)) + (org-agenda--timestamp-to-absolute + s today 'past (current-buffer) pos)) + (t (org-agenda--timestamp-to-absolute s)))) + ;; REPEAT is the future repeat closest from CURRENT, + ;; according to `org-agenda-show-future-repeats'. If + ;; the latter is nil, or if the time stamp has no + ;; repeat part, default to DEADLINE. + (repeat + (cond + (sexp? deadline) + ((<= current today) deadline) + ((not org-agenda-show-future-repeats) deadline) + (t + (let ((base (if (eq org-agenda-show-future-repeats 'next) + (1+ today) + current))) + (org-agenda--timestamp-to-absolute + s base 'future (current-buffer) pos))))) + (diff (- deadline current)) + (suppress-prewarning + (let ((scheduled + (and org-agenda-skip-deadline-prewarning-if-scheduled + (org-entry-get nil "SCHEDULED")))) + (cond + ((not scheduled) nil) + ;; The current item has a scheduled date, so + ;; evaluate its prewarning lead time. + ((integerp org-agenda-skip-deadline-prewarning-if-scheduled) + ;; Use global prewarning-restart lead time. + org-agenda-skip-deadline-prewarning-if-scheduled) + ((eq org-agenda-skip-deadline-prewarning-if-scheduled + 'pre-scheduled) + ;; Set pre-warning to no earlier than SCHEDULED. + (min (- deadline + (org-agenda--timestamp-to-absolute scheduled)) + org-deadline-warning-days)) + ;; Set pre-warning to deadline. + (t 0)))) + (wdays (or suppress-prewarning (org-get-wdays s)))) + (cond + ;; Only display deadlines at their base date, at future + ;; repeat occurrences or in today agenda. + ((= current deadline) nil) + ((= current repeat) nil) + ((not today?) (throw :skip nil)) + ;; Upcoming deadline: display within warning period WDAYS. + ((> deadline current) (when (> diff wdays) (throw :skip nil))) + ;; Overdue deadline: warn about it for + ;; `org-deadline-past-days' duration. + (t (when (< org-deadline-past-days (- diff)) (throw :skip nil)))) + ;; Possibly skip done tasks. + (when (and done? + (or org-agenda-skip-deadline-if-done + (/= deadline current))) + (throw :skip nil)) + (save-excursion + (re-search-backward "^\\*+[ \t]+" nil t) + (goto-char (match-end 0)) + (let* ((category (org-get-category)) + (level (make-string (org-reduced-level (org-outline-level)) + ?\s)) + (head (buffer-substring (point) (line-end-position))) + (inherited-tags + (or (eq org-agenda-show-inherited-tags 'always) + (and (listp org-agenda-show-inherited-tags) + (memq 'agenda org-agenda-show-inherited-tags)) + (and (eq org-agenda-show-inherited-tags t) + (or (eq org-agenda-use-tag-inheritance t) + (memq 'agenda + org-agenda-use-tag-inheritance))))) + (tags (org-get-tags-at nil (not inherited-tags))) + (time + (cond + ;; No time of day designation if it is only + ;; a reminder. + ((and (/= current deadline) (/= current repeat)) nil) + ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s) + (concat (substring s (match-beginning 1)) " ")) + (t 'time))) + (item + (org-agenda-format-item + ;; Insert appropriate suffixes before deadlines. + ;; Those only apply to today agenda. + (pcase-let ((`(,now ,future ,past) + org-agenda-deadline-leaders)) + (cond + ((and today? (< deadline today)) (format past (- diff))) + ((and today? (> deadline today)) (format future diff)) + (t now))) + head level category tags time)) + (face (org-agenda-deadline-face + (- 1 (/ (float diff) (max wdays 1))))) + (upcoming? (and today? (> deadline today))) + (warntime (get-text-property (point) 'org-appt-warntime))) + (org-add-props item props + 'org-marker (org-agenda-new-marker pos) + 'org-hd-marker (org-agenda-new-marker (line-beginning-position)) + 'warntime warntime + 'level level + 'ts-date deadline + 'priority + ;; Adjust priority to today reminders about deadlines. + ;; Overdue deadlines get the highest priority + ;; increase, then imminent deadlines and eventually + ;; more distant deadlines. + (let ((adjust (if today? (- diff) 0))) + (+ adjust (org-get-priority item))) + 'todo-state todo-state + 'type (if upcoming? "upcoming-deadline" "deadline") + 'date (if upcoming? date deadline) + 'face (if done? 'org-agenda-done face) + 'undone-face face + 'done-face 'org-agenda-done) + (push item deadline-items)))))) + (nreverse deadline-items))) + +(defun org-agenda-deadline-face (fraction) + "Return the face to displaying a deadline item. +FRACTION is what fraction of the head-warning time has passed." + (assoc-default fraction org-agenda-deadline-faces #'<=)) + +(defun org-agenda-get-scheduled (&optional deadlines with-hour) + "Return the scheduled information for agenda display. +Optional argument DEADLINES is a list of deadline items to be +displayed in agenda view. When WITH-HOUR is non-nil, only return +scheduled items with an hour specification like [h]h:mm." + (let* ((props (list 'org-not-done-regexp org-not-done-regexp + 'org-todo-regexp org-todo-regexp + 'org-complex-heading-regexp org-complex-heading-regexp + 'done-face 'org-agenda-done + 'mouse-face 'highlight + 'help-echo + (format "mouse-2 or RET jump to Org file %s" + (abbreviate-file-name buffer-file-name)))) + (regexp (if with-hour + org-scheduled-time-hour-regexp + org-scheduled-time-regexp)) + (today (org-today)) + (todayp (org-agenda-today-p date)) ; DATE bound by calendar. + (current (calendar-absolute-from-gregorian date)) + (deadline-pos + (mapcar (lambda (d) + (let ((m (get-text-property 0 'org-hd-marker d))) + (and m (marker-position m)))) + deadlines)) + scheduled-items) + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (catch :skip + (unless (save-match-data (org-at-planning-p)) (throw :skip nil)) + (org-agenda-skip) + (let* ((s (match-string 1)) + (pos (1- (match-beginning 1))) + (todo-state (save-match-data (org-get-todo-state))) + (donep (member todo-state org-done-keywords)) + (sexp? (string-prefix-p "%%" s)) + ;; SCHEDULE is the scheduled date for the entry. It is + ;; either the bare date or the last repeat, according + ;; to `org-agenda-prefer-last-repeat'. + (schedule + (cond + (sexp? (org-agenda--timestamp-to-absolute s current)) + ((or (eq org-agenda-prefer-last-repeat t) + (member todo-state org-agenda-prefer-last-repeat)) + (org-agenda--timestamp-to-absolute + s today 'past (current-buffer) pos)) + (t (org-agenda--timestamp-to-absolute s)))) + ;; REPEAT is the future repeat closest from CURRENT, + ;; according to `org-agenda-show-future-repeats'. If + ;; the latter is nil, or if the time stamp has no + ;; repeat part, default to SCHEDULE. + (repeat + (cond + (sexp? schedule) + ((<= current today) schedule) + ((not org-agenda-show-future-repeats) schedule) + (t + (let ((base (if (eq org-agenda-show-future-repeats 'next) + (1+ today) + current))) + (org-agenda--timestamp-to-absolute + s base 'future (current-buffer) pos))))) + (diff (- current schedule)) + (warntime (get-text-property (point) 'org-appt-warntime)) + (pastschedp (< schedule today)) + (habitp (and (fboundp 'org-is-habit-p) (org-is-habit-p))) + (suppress-delay + (let ((deadline (and org-agenda-skip-scheduled-delay-if-deadline + (org-entry-get nil "DEADLINE")))) + (cond + ((not deadline) nil) + ;; The current item has a deadline date, so + ;; evaluate its delay time. + ((integerp org-agenda-skip-scheduled-delay-if-deadline) + ;; Use global delay time. + (- org-agenda-skip-scheduled-delay-if-deadline)) + ((eq org-agenda-skip-scheduled-delay-if-deadline + 'post-deadline) + ;; Set delay to no later than DEADLINE. + (min (- schedule + (org-agenda--timestamp-to-absolute deadline)) + org-scheduled-delay-days)) + (t 0)))) + (ddays + (cond + ;; Nullify delay when a repeater triggered already + ;; and the delay is of the form --Xd. + ((and (string-match-p "--[0-9]+[hdwmy]" s) + (> schedule (org-agenda--timestamp-to-absolute s))) + 0) + (suppress-delay + (let ((org-scheduled-delay-days suppress-delay)) + (org-get-wdays s t t))) + (t (org-get-wdays s t))))) + ;; Display scheduled items at base date (SCHEDULE), today if + ;; scheduled before the current date, and at any repeat past + ;; today. However, skip delayed items and items that have + ;; been displayed for more than `org-scheduled-past-days'. + (unless (and todayp + habitp + (bound-and-true-p org-habit-show-all-today)) + (when (or (and (> ddays 0) (< diff ddays)) + (> diff org-scheduled-past-days) + (> schedule current) + (and (/= current schedule) + (/= current today) + (/= current repeat))) + (throw :skip nil))) + ;; Possibly skip done tasks. + (when (and donep + (or org-agenda-skip-scheduled-if-done + (/= schedule current))) + (throw :skip nil)) + ;; Skip entry if it already appears as a deadline, per + ;; `org-agenda-skip-scheduled-if-deadline-is-shown'. This + ;; doesn't apply to habits. + (when (pcase org-agenda-skip-scheduled-if-deadline-is-shown + ((guard + (or (not (memq (line-beginning-position 0) deadline-pos)) + habitp)) + nil) + (`repeated-after-deadline + (let ((deadline (time-to-days + (org-get-deadline-time (point))))) + (and (<= schedule deadline) (> current deadline)))) + (`not-today pastschedp) + (`t t) + (_ nil)) + (throw :skip nil)) + ;; Skip habits if `org-habit-show-habits' is nil, or if we + ;; only show them for today. Also skip done habits. + (when (and habitp + (or donep + (not (bound-and-true-p org-habit-show-habits)) + (and (not todayp) + (bound-and-true-p + org-habit-show-habits-only-for-today)))) + (throw :skip nil)) + (save-excursion + (re-search-backward "^\\*+[ \t]+" nil t) + (goto-char (match-end 0)) + (let* ((category (org-get-category)) + (inherited-tags + (or (eq org-agenda-show-inherited-tags 'always) + (and (listp org-agenda-show-inherited-tags) + (memq 'agenda org-agenda-show-inherited-tags)) + (and (eq org-agenda-show-inherited-tags t) + (or (eq org-agenda-use-tag-inheritance t) + (memq 'agenda + org-agenda-use-tag-inheritance))))) + (tags (org-get-tags-at nil (not inherited-tags))) + (level (make-string (org-reduced-level (org-outline-level)) + ?\s)) + (head (buffer-substring (point) (line-end-position))) + (time + (cond + ;; No time of day designation if it is only + ;; a reminder. + ((and (/= current schedule) (/= current repeat)) nil) + ((string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s) + (concat (substring s (match-beginning 1)) " ")) + (t 'time))) + (item + (org-agenda-format-item + (pcase-let ((`(,first ,past) org-agenda-scheduled-leaders)) + ;; Show a reminder of a past scheduled today. + (if (and todayp pastschedp) + (format past diff) + first)) + head level category tags time nil habitp)) + (face (cond ((and (not habitp) pastschedp) + 'org-scheduled-previously) + (todayp 'org-scheduled-today) + (t 'org-scheduled))) + (habitp (and habitp (org-habit-parse-todo)))) + (org-add-props item props + 'undone-face face + 'face (if donep 'org-agenda-done face) + 'org-marker (org-agenda-new-marker pos) + 'org-hd-marker (org-agenda-new-marker (line-beginning-position)) + 'type (if pastschedp "past-scheduled" "scheduled") + 'date (if pastschedp schedule date) + 'ts-date schedule + 'warntime warntime + 'level level + 'priority (if habitp (org-habit-get-priority habitp) + (+ 99 diff (org-get-priority item))) + 'org-habit-p habitp + 'todo-state todo-state) + (push item scheduled-items)))))) + (nreverse scheduled-items))) + +(defun org-agenda-get-blocks () + "Return the date-range information for agenda display." + (let* ((props (list 'face nil + 'org-not-done-regexp org-not-done-regexp + 'org-todo-regexp org-todo-regexp + 'org-complex-heading-regexp org-complex-heading-regexp + 'mouse-face 'highlight + 'help-echo + (format "mouse-2 or RET jump to org file %s" + (abbreviate-file-name buffer-file-name)))) + (regexp org-tr-regexp) + (d0 (calendar-absolute-from-gregorian date)) + marker hdmarker ee txt d1 d2 s1 s2 category + level todo-state tags pos head donep inherited-tags) + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (catch :skip + (org-agenda-skip) + (setq pos (point)) + (let ((start-time (match-string 1)) + (end-time (match-string 2))) + (setq s1 (match-string 1) + s2 (match-string 2) + d1 (time-to-days + (condition-case err + (org-time-string-to-time s1) + (error + (error + "Bad timestamp %S at %d in buffer %S\nError was: %s" + s1 + pos + (current-buffer) + (error-message-string err))))) + d2 (time-to-days + (condition-case err + (org-time-string-to-time s2) + (error + (error + "Bad timestamp %S at %d in buffer %S\nError was: %s" + s2 + pos + (current-buffer) + (error-message-string err)))))) + (if (and (> (- d0 d1) -1) (> (- d2 d0) -1)) + ;; Only allow days between the limits, because the normal + ;; date stamps will catch the limits. + (save-excursion + (setq todo-state (org-get-todo-state)) + (setq donep (member todo-state org-done-keywords)) + (if (and donep org-agenda-skip-timestamp-if-done) + (throw :skip t)) + (setq marker (org-agenda-new-marker (point)) + category (org-get-category)) + (if (not (re-search-backward org-outline-regexp-bol nil t)) + (throw :skip nil) + (goto-char (match-beginning 0)) + (setq hdmarker (org-agenda-new-marker (point)) + inherited-tags + (or (eq org-agenda-show-inherited-tags 'always) + (and (listp org-agenda-show-inherited-tags) + (memq 'agenda org-agenda-show-inherited-tags)) + (and (eq org-agenda-show-inherited-tags t) + (or (eq org-agenda-use-tag-inheritance t) + (memq 'agenda org-agenda-use-tag-inheritance)))) + + tags (org-get-tags-at nil (not inherited-tags))) + (setq level (make-string (org-reduced-level (org-outline-level)) ? )) + (looking-at "\\*+[ \t]+\\(.*\\)") + (setq head (match-string 1)) + (let ((remove-re + (if org-agenda-remove-timeranges-from-blocks + (concat + "<" (regexp-quote s1) ".*?>" + "--" + "<" (regexp-quote s2) ".*?>") + nil))) + (setq txt (org-agenda-format-item + (format + (nth (if (= d1 d2) 0 1) + org-agenda-timerange-leaders) + (1+ (- d0 d1)) (1+ (- d2 d1))) + head level category tags + (cond ((and (= d1 d0) (= d2 d0)) + (concat "<" start-time ">--<" end-time ">")) + ((= d1 d0) + (concat "<" start-time ">")) + ((= d2 d0) + (concat "<" end-time ">"))) + remove-re)))) + (org-add-props txt props + 'org-marker marker 'org-hd-marker hdmarker + 'type "block" 'date date + 'level level + 'todo-state todo-state + 'priority (org-get-priority txt)) + (push txt ee)))) + (goto-char pos))) + ;; Sort the entries by expiration date. + (nreverse ee))) + +;;; Agenda presentation and sorting + +(defvar org-prefix-has-time nil + "A flag, set by `org-compile-prefix-format'. +The flag is set if the currently compiled format contains a `%t'.") +(defvar org-prefix-has-tag nil + "A flag, set by `org-compile-prefix-format'. +The flag is set if the currently compiled format contains a `%T'.") +(defvar org-prefix-has-effort nil + "A flag, set by `org-compile-prefix-format'. +The flag is set if the currently compiled format contains a `%e'.") +(defvar org-prefix-has-breadcrumbs nil + "A flag, set by `org-compile-prefix-format'. +The flag is set if the currently compiled format contains a `%b'.") +(defvar org-prefix-category-length nil + "Used by `org-compile-prefix-format' to remember the category field width.") +(defvar org-prefix-category-max-length nil + "Used by `org-compile-prefix-format' to remember the category field width.") + +(defun org-agenda-get-category-icon (category) + "Return an image for CATEGORY according to `org-agenda-category-icon-alist'." + (cl-dolist (entry org-agenda-category-icon-alist) + (when (string-match-p (car entry) category) + (if (listp (cadr entry)) + (cl-return (cadr entry)) + (cl-return (apply #'create-image (cdr entry))))))) + +(defun org-agenda-format-item (extra txt &optional level category tags dotime + remove-re habitp) + "Format TXT to be inserted into the agenda buffer. +In particular, add the prefix and corresponding text properties. + +EXTRA must be a string to replace the `%s' specifier in the prefix format. +LEVEL may be a string to replace the `%l' specifier. +CATEGORY (a string, a symbol or nil) may be used to overrule the default +category taken from local variable or file name. It will replace the `%c' +specifier in the format. +DOTIME, when non-nil, indicates that a time-of-day should be extracted from +TXT for sorting of this entry, and for the `%t' specifier in the format. +When DOTIME is a string, this string is searched for a time before TXT is. +TAGS can be the tags of the headline. +Any match of REMOVE-RE will be removed from TXT." + ;; We keep the org-prefix-* variable values along with a compiled + ;; formatter, so that multiple agendas existing at the same time do + ;; not step on each other toes. + ;; + ;; It was inconvenient to make these variables buffer local in + ;; Agenda buffers, because this function expects to be called with + ;; the buffer where item comes from being current, and not agenda + ;; buffer + (let* ((bindings (car org-prefix-format-compiled)) + (formatter (cadr org-prefix-format-compiled))) + (cl-loop for (var value) in bindings + do (set var value)) + (save-match-data + ;; Diary entries sometimes have extra whitespace at the beginning + (setq txt (org-trim txt)) + + ;; Fix the tags part in txt + (setq txt (org-agenda-fix-displayed-tags + txt tags + org-agenda-show-inherited-tags + org-agenda-hide-tags-regexp)) + + (let* ((category (or category + (if buffer-file-name + (file-name-sans-extension + (file-name-nondirectory buffer-file-name)) + ""))) + (category-icon (org-agenda-get-category-icon category)) + (category-icon (if category-icon + (propertize " " 'display category-icon) + "")) + (effort (and (not (string= txt "")) + (get-text-property 1 'effort txt))) + ;; time, tag, effort are needed for the eval of the prefix format + (tag (if tags (nth (1- (length tags)) tags) "")) + (time-grid-trailing-characters (nth 2 org-agenda-time-grid)) + time + (ts (if dotime (concat + (if (stringp dotime) dotime "") + (and org-agenda-search-headline-for-time txt)))) + (time-of-day (and dotime (org-get-time-of-day ts))) + stamp plain s0 s1 s2 rtn srp l + duration breadcrumbs) + (and (derived-mode-p 'org-mode) buffer-file-name + (add-to-list 'org-agenda-contributing-files buffer-file-name)) + (when (and dotime time-of-day) + ;; Extract starting and ending time and move them to prefix + (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts)) + (setq plain (string-match org-plain-time-of-day-regexp ts))) + (setq s0 (match-string 0 ts) + srp (and stamp (match-end 3)) + s1 (match-string (if plain 1 2) ts) + s2 (match-string (if plain 8 (if srp 4 6)) ts)) + + ;; If the times are in TXT (not in DOTIMES), and the prefix will list + ;; them, we might want to remove them there to avoid duplication. + ;; The user can turn this off with a variable. + (if (and org-prefix-has-time + org-agenda-remove-times-when-in-prefix (or stamp plain) + (string-match (concat (regexp-quote s0) " *") txt) + (not (equal ?\] (string-to-char (substring txt (match-end 0))))) + (if (eq org-agenda-remove-times-when-in-prefix 'beg) + (= (match-beginning 0) 0) + t)) + (setq txt (replace-match "" nil nil txt)))) + ;; Normalize the time(s) to 24 hour + (if s1 (setq s1 (org-get-time-of-day s1 'string t))) + (if s2 (setq s2 (org-get-time-of-day s2 'string t))) + + ;; Try to set s2 if s1 and + ;; `org-agenda-default-appointment-duration' are set + (when (and s1 (not s2) org-agenda-default-appointment-duration) + (setq s2 + (org-duration-from-minutes + (+ (org-duration-to-minutes s1 t) + org-agenda-default-appointment-duration) + nil t))) + + ;; Compute the duration + (when s2 + (setq duration (- (org-duration-to-minutes s2) + (org-duration-to-minutes s1))))) + + (when (string-match "\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" txt) + ;; Tags are in the string + (if (or (eq org-agenda-remove-tags t) + (and org-agenda-remove-tags + org-prefix-has-tag)) + (setq txt (replace-match "" t t txt)) + (setq txt (replace-match + (concat (make-string (max (- 50 (length txt)) 1) ?\ ) + (match-string 2 txt)) + t t txt)))) + + (when remove-re + (while (string-match remove-re txt) + (setq txt (replace-match "" t t txt)))) + + ;; Set org-heading property on `txt' to mark the start of the + ;; heading. + (add-text-properties 0 (length txt) '(org-heading t) txt) + + ;; Prepare the variables needed in the eval of the compiled format + (if org-prefix-has-breadcrumbs + (setq breadcrumbs (org-with-point-at (org-get-at-bol 'org-marker) + (let ((s (org-display-outline-path nil nil "->" t))) + (if (eq "" s) "" (concat s "->")))))) + (setq time (cond (s2 (concat + (org-agenda-time-of-day-to-ampm-maybe s1) + "-" (org-agenda-time-of-day-to-ampm-maybe s2) + (if org-agenda-timegrid-use-ampm " "))) + (s1 (concat + (org-agenda-time-of-day-to-ampm-maybe s1) + (if org-agenda-timegrid-use-ampm + (concat time-grid-trailing-characters " ") + time-grid-trailing-characters))) + (t "")) + extra (or (and (not habitp) extra) "") + category (if (symbolp category) (symbol-name category) category) + level (or level "")) + (if (string-match org-bracket-link-regexp category) + (progn + (setq l (if (match-end 3) + (- (match-end 3) (match-beginning 3)) + (- (match-end 1) (match-beginning 1)))) + (when (< l (or org-prefix-category-length 0)) + (setq category (copy-sequence category)) + (org-add-props category nil + 'extra-space (make-string + (- org-prefix-category-length l 1) ?\ )))) + (if (and org-prefix-category-max-length + (>= (length category) org-prefix-category-max-length)) + (setq category (substring category 0 (1- org-prefix-category-max-length))))) + ;; Evaluate the compiled format + (setq rtn (concat (eval formatter) txt)) + + ;; And finally add the text properties + (remove-text-properties 0 (length rtn) '(line-prefix t wrap-prefix t) rtn) + (org-add-props rtn nil + 'org-category category + 'tags (mapcar 'org-downcase-keep-props tags) + 'org-highest-priority org-highest-priority + 'org-lowest-priority org-lowest-priority + 'time-of-day time-of-day + 'duration duration + 'breadcrumbs breadcrumbs + 'txt txt + 'level level + 'time time + 'extra extra + 'format org-prefix-format-compiled + 'dotime dotime))))) + +(defun org-agenda-fix-displayed-tags (txt tags add-inherited hide-re) + "Remove tags string from TXT, and add a modified list of tags. +The modified list may contain inherited tags, and tags matched by +`org-agenda-hide-tags-regexp' will be removed." + (when (or add-inherited hide-re) + (if (string-match "\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" txt) + (setq txt (substring txt 0 (match-beginning 0)))) + (setq tags + (delq nil + (mapcar (lambda (tg) + (if (or (and hide-re (string-match hide-re tg)) + (and (not add-inherited) + (get-text-property 0 'inherited tg))) + nil + tg)) + tags))) + (when tags + (let ((have-i (get-text-property 0 'inherited (car tags))) + i) + (setq txt (concat txt " :" + (mapconcat + (lambda (x) + (setq i (get-text-property 0 'inherited x)) + (if (and have-i (not i)) + (progn + (setq have-i nil) + (concat ":" x)) + x)) + tags ":") + (if have-i "::" ":")))))) + txt) + +(defun org-downcase-keep-props (s) + (let ((props (text-properties-at 0 s))) + (setq s (downcase s)) + (add-text-properties 0 (length s) props s) + s)) + +(defvar org-agenda-sorting-strategy) ;; because the def is in a let form + +(defun org-agenda-add-time-grid-maybe (list ndays todayp) + "Add a time-grid for agenda items which need it. + +LIST is the list of agenda items formatted by `org-agenda-list'. +NDAYS is the span of the current agenda view. +TODAYP is t when the current agenda view is on today." + (catch 'exit + (cond ((not org-agenda-use-time-grid) (throw 'exit list)) + ((and todayp (member 'today (car org-agenda-time-grid)))) + ((and (= ndays 1) (member 'daily (car org-agenda-time-grid)))) + ((member 'weekly (car org-agenda-time-grid))) + (t (throw 'exit list))) + (let* ((have (delq nil (mapcar + (lambda (x) (get-text-property 1 'time-of-day x)) + list))) + (string (nth 3 org-agenda-time-grid)) + (gridtimes (nth 1 org-agenda-time-grid)) + (req (car org-agenda-time-grid)) + (remove (member 'remove-match req)) + new time) + (if (and (member 'require-timed req) (not have)) + ;; don't show empty grid + (throw 'exit list)) + (while (setq time (pop gridtimes)) + (unless (and remove (member time have)) + (setq time (replace-regexp-in-string " " "0" (format "%04s" time))) + (push (org-agenda-format-item + nil string nil "" nil + (concat (substring time 0 -2) ":" (substring time -2))) + new) + (put-text-property + 2 (length (car new)) 'face 'org-time-grid (car new)))) + (when (and todayp org-agenda-show-current-time-in-grid) + (push (org-agenda-format-item + nil org-agenda-current-time-string nil "" nil + (format-time-string "%H:%M ")) + new) + (put-text-property + 2 (length (car new)) 'face 'org-agenda-current-time (car new))) + + (if (member 'time-up org-agenda-sorting-strategy-selected) + (append new list) + (append list new))))) + +(defun org-compile-prefix-format (key) + "Compile the prefix format into a Lisp form that can be evaluated. +The resulting form and associated variable bindings is returned +and stored in the variable `org-prefix-format-compiled'." + (setq org-prefix-has-time nil + org-prefix-has-tag nil + org-prefix-category-length nil + org-prefix-has-effort nil + org-prefix-has-breadcrumbs nil) + (let ((s (cond + ((stringp org-agenda-prefix-format) + org-agenda-prefix-format) + ((assq key org-agenda-prefix-format) + (cdr (assq key org-agenda-prefix-format))) + (t " %-12:c%?-12t% s"))) + (start 0) + varform vars var e c f opt) + (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cltseib]\\|(.+)\\)" + s start) + (setq var (or (cdr (assoc (match-string 4 s) + '(("c" . category) ("t" . time) ("l" . level) ("s" . extra) + ("i" . category-icon) ("T" . tag) ("e" . effort) ("b" . breadcrumbs)))) + 'eval) + c (or (match-string 3 s) "") + opt (match-beginning 1) + start (1+ (match-beginning 0))) + (if (eq var 'time) (setq org-prefix-has-time t)) + (if (eq var 'tag) (setq org-prefix-has-tag t)) + (if (eq var 'effort) (setq org-prefix-has-effort t)) + (if (eq var 'breadcrumbs) (setq org-prefix-has-breadcrumbs t)) + (setq f (concat "%" (match-string 2 s) "s")) + (when (eq var 'category) + (setq org-prefix-category-length + (floor (abs (string-to-number (match-string 2 s))))) + (setq org-prefix-category-max-length + (let ((x (match-string 2 s))) + (save-match-data + (if (string-match "\\.[0-9]+" x) + (string-to-number (substring (match-string 0 x) 1))))))) + (if (eq var 'eval) + (setq varform `(format ,f (org-eval ,(read (match-string 4 s))))) + (if opt + (setq varform + `(if (or (equal "" ,var) (equal nil ,var)) + "" + (format ,f (concat ,var ,c)))) + (setq varform + `(format ,f (if (or (equal ,var "") + (equal ,var nil)) "" + (concat ,var ,c (get-text-property 0 'extra-space ,var))))))) + (setq s (replace-match "%s" t nil s)) + (push varform vars)) + (setq vars (nreverse vars)) + (with-current-buffer (or org-agenda-buffer (current-buffer)) + (setq org-prefix-format-compiled + (list + `((org-prefix-has-time ,org-prefix-has-time) + (org-prefix-has-tag ,org-prefix-has-tag) + (org-prefix-category-length ,org-prefix-category-length) + (org-prefix-has-effort ,org-prefix-has-effort) + (org-prefix-has-breadcrumbs ,org-prefix-has-breadcrumbs)) + `(format ,s ,@vars)))))) + +(defun org-set-sorting-strategy (key) + (if (symbolp (car org-agenda-sorting-strategy)) + ;; the old format + (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy) + (setq org-agenda-sorting-strategy-selected + (or (cdr (assq key org-agenda-sorting-strategy)) + (cdr (assq 'agenda org-agenda-sorting-strategy)) + '(time-up category-keep priority-down))))) + +(defun org-get-time-of-day (s &optional string mod24) + "Check string S for a time of day. +If found, return it as a military time number between 0 and 2400. +If not found, return nil. +The optional STRING argument forces conversion into a 5 character wide string +HH:MM." + (save-match-data + (when + (and + (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s) + (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s)) + (not (eq (get-text-property 1 'face s) 'org-link))) + (let* ((h (string-to-number (match-string 1 s))) + (m (if (match-end 3) (string-to-number (match-string 3 s)) 0)) + (ampm (if (match-end 4) (downcase (match-string 4 s)))) + (am-p (equal ampm "am")) + (h1 (cond ((not ampm) h) + ((= h 12) (if am-p 0 12)) + (t (+ h (if am-p 0 12))))) + (h2 (if (and string mod24 (not (and (= m 0) (= h1 24)))) + (mod h1 24) h1)) + (t0 (+ (* 100 h2) m)) + (t1 (concat (if (>= h1 24) "+" " ") + (if (and org-agenda-time-leading-zero + (< t0 1000)) "0" "") + (if (< t0 100) "0" "") + (if (< t0 10) "0" "") + (int-to-string t0)))) + (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0))))) + +(defvar org-agenda-before-sorting-filter-function nil + "Function to be applied to agenda items prior to sorting. +Prior to sorting also means just before they are inserted into the agenda. + +To aid sorting, you may revisit the original entries and add more text +properties which will later be used by the sorting functions. + +The function should take a string argument, an agenda line. +It has access to the text properties in that line, which contain among +other things, the property `org-hd-marker' that points to the entry +where the line comes from. Note that not all lines going into the agenda +have this property, only most. + +The function should return the modified string. It is probably best +to ONLY change text properties. + +You can also use this function as a filter, by returning nil for lines +you don't want to have in the agenda at all. For this application, you +could bind the variable in the options section of a custom command.") + +(defun org-agenda-finalize-entries (list &optional type) + "Sort, limit and concatenate the LIST of agenda items. +The optional argument TYPE tells the agenda type." + (let ((max-effort (cond ((listp org-agenda-max-effort) + (cdr (assoc type org-agenda-max-effort))) + (t org-agenda-max-effort))) + (max-todo (cond ((listp org-agenda-max-todos) + (cdr (assoc type org-agenda-max-todos))) + (t org-agenda-max-todos))) + (max-tags (cond ((listp org-agenda-max-tags) + (cdr (assoc type org-agenda-max-tags))) + (t org-agenda-max-tags))) + (max-entries (cond ((listp org-agenda-max-entries) + (cdr (assoc type org-agenda-max-entries))) + (t org-agenda-max-entries)))) + (when org-agenda-before-sorting-filter-function + (setq list + (delq nil + (mapcar + org-agenda-before-sorting-filter-function list)))) + (setq list (mapcar 'org-agenda-highlight-todo list) + list (mapcar 'identity (sort list 'org-entries-lessp))) + (when max-effort + (setq list (org-agenda-limit-entries + list 'effort-minutes max-effort + (lambda (e) (or e (if org-sort-agenda-noeffort-is-high + 32767 -1)))))) + (when max-todo + (setq list (org-agenda-limit-entries list 'todo-state max-todo))) + (when max-tags + (setq list (org-agenda-limit-entries list 'tags max-tags))) + (when max-entries + (setq list (org-agenda-limit-entries list 'org-hd-marker max-entries))) + (when (and org-agenda-dim-blocked-tasks org-blocker-hook) + (setq list (mapcar #'org-agenda--mark-blocked-entry list))) + (mapconcat 'identity list "\n"))) + +(defun org-agenda-limit-entries (list prop limit &optional fn) + "Limit the number of agenda entries." + (let ((include (and limit (< limit 0)))) + (if limit + (let ((fun (or fn (lambda (p) (if p 1)))) + (lim 0)) + (delq nil + (mapcar + (lambda (e) + (let ((pval (funcall + fun (get-text-property (1- (length e)) + prop e)))) + (if pval (setq lim (+ lim pval))) + (cond ((and pval (<= lim (abs limit))) e) + ((and include (not pval)) e)))) + list))) + list))) + +(defun org-agenda-limit-interactively (remove) + "In agenda, interactively limit entries to various maximums." + (interactive "P") + (if remove + (progn (setq org-agenda-max-entries nil + org-agenda-max-todos nil + org-agenda-max-tags nil + org-agenda-max-effort nil) + (org-agenda-redo)) + (let* ((max (read-char "Number of [e]ntries [t]odos [T]ags [E]ffort? ")) + (msg (cond ((= max ?E) "How many minutes? ") + ((= max ?e) "How many entries? ") + ((= max ?t) "How many TODO entries? ") + ((= max ?T) "How many tagged entries? ") + (t (user-error "Wrong input")))) + (num (string-to-number (read-from-minibuffer msg)))) + (cond ((equal max ?e) + (let ((org-agenda-max-entries num)) (org-agenda-redo))) + ((equal max ?t) + (let ((org-agenda-max-todos num)) (org-agenda-redo))) + ((equal max ?T) + (let ((org-agenda-max-tags num)) (org-agenda-redo))) + ((equal max ?E) + (let ((org-agenda-max-effort num)) (org-agenda-redo)))))) + (org-agenda-fit-window-to-buffer)) + +(defun org-agenda-highlight-todo (x) + (let ((org-done-keywords org-done-keywords-for-agenda) + (case-fold-search nil) + re) + (if (eq x 'line) + (save-excursion + (beginning-of-line 1) + (setq re (org-get-at-bol 'org-todo-regexp)) + (goto-char (or (text-property-any (point-at-bol) (point-at-eol) 'org-heading t) (point))) + (when (looking-at (concat "[ \t]*\\.*\\(" re "\\) +")) + (add-text-properties (match-beginning 0) (match-end 1) + (list 'face (org-get-todo-face 1))) + (let ((s (buffer-substring (match-beginning 1) (match-end 1)))) + (delete-region (match-beginning 1) (1- (match-end 0))) + (goto-char (match-beginning 1)) + (insert (format org-agenda-todo-keyword-format s))))) + (let ((pl (text-property-any 0 (length x) 'org-heading t x))) + (setq re (get-text-property 0 'org-todo-regexp x)) + (when (and re + ;; Test `pl' because if there's no heading content, + ;; there's no point matching to highlight. Note + ;; that if we didn't test `pl' first, and there + ;; happened to be no keyword from `org-todo-regexp' + ;; on this heading line, then the `equal' comparison + ;; afterwards would spuriously succeed in the case + ;; where `pl' is nil -- causing an args-out-of-range + ;; error when we try to add text properties to text + ;; that isn't there. + pl + (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)") + x pl) pl)) + (add-text-properties + (or (match-end 1) (match-end 0)) (match-end 0) + (list 'face (org-get-todo-face (match-string 2 x))) + x) + (when (match-end 1) + (setq x + (concat + (substring x 0 (match-end 1)) + (format org-agenda-todo-keyword-format + (match-string 2 x)) + ;; Remove `display' property as the icon could leak + ;; on the white space. + (org-add-props " " (org-plist-delete (text-properties-at 0 x) + 'display)) + (substring x (match-end 3))))))) + x))) + +(defsubst org-cmp-values (a b property) + "Compare the numeric value of text PROPERTY for string A and B." + (let ((pa (or (get-text-property (1- (length a)) property a) 0)) + (pb (or (get-text-property (1- (length b)) property b) 0))) + (cond ((> pa pb) +1) + ((< pa pb) -1)))) + +(defsubst org-cmp-effort (a b) + "Compare the effort values of string A and B." + (let* ((def (if org-sort-agenda-noeffort-is-high 32767 -1)) + ;; `effort-minutes' property is not directly accessible from + ;; the strings, but is stored as a property in `txt'. + (ea (or (get-text-property + 0 'effort-minutes (get-text-property 0 'txt a)) + def)) + (eb (or (get-text-property + 0 'effort-minutes (get-text-property 0 'txt b)) + def))) + (cond ((> ea eb) +1) + ((< ea eb) -1)))) + +(defsubst org-cmp-category (a b) + "Compare the string values of categories of strings A and B." + (let ((ca (or (get-text-property (1- (length a)) 'org-category a) "")) + (cb (or (get-text-property (1- (length b)) 'org-category b) ""))) + (cond ((string-lessp ca cb) -1) + ((string-lessp cb ca) +1)))) + +(defsubst org-cmp-todo-state (a b) + "Compare the todo states of strings A and B." + (let* ((ma (or (get-text-property 1 'org-marker a) + (get-text-property 1 'org-hd-marker a))) + (mb (or (get-text-property 1 'org-marker b) + (get-text-property 1 'org-hd-marker b))) + (fa (and ma (marker-buffer ma))) + (fb (and mb (marker-buffer mb))) + (todo-kwds + (or (and fa (with-current-buffer fa org-todo-keywords-1)) + (and fb (with-current-buffer fb org-todo-keywords-1)))) + (ta (or (get-text-property 1 'todo-state a) "")) + (tb (or (get-text-property 1 'todo-state b) "")) + (la (- (length (member ta todo-kwds)))) + (lb (- (length (member tb todo-kwds)))) + (donepa (member ta org-done-keywords-for-agenda)) + (donepb (member tb org-done-keywords-for-agenda))) + (cond ((and donepa (not donepb)) -1) + ((and (not donepa) donepb) +1) + ((< la lb) -1) + ((< lb la) +1)))) + +(defsubst org-cmp-alpha (a b) + "Compare the headlines, alphabetically." + (let* ((pla (text-property-any 0 (length a) 'org-heading t a)) + (plb (text-property-any 0 (length b) 'org-heading t b)) + (ta (and pla (substring a pla))) + (tb (and plb (substring b plb))) + (case-fold-search nil)) + (when pla + (if (string-match (concat "\\`[ \t]*" (or (get-text-property 0 'org-todo-regexp a) "") + "\\([ \t]*\\[[a-zA-Z0-9]\\]\\)? *") ta) + (setq ta (substring ta (match-end 0)))) + (setq ta (downcase ta))) + (when plb + (if (string-match (concat "\\`[ \t]*" (or (get-text-property 0 'org-todo-regexp b) "") + "\\([ \t]*\\[[a-zA-Z0-9]\\]\\)? *") tb) + (setq tb (substring tb (match-end 0)))) + (setq tb (downcase tb))) + (cond ((not ta) +1) + ((not tb) -1) + ((string-lessp ta tb) -1) + ((string-lessp tb ta) +1)))) + +(defsubst org-cmp-tag (a b) + "Compare the string values of the first tags of A and B." + (let ((ta (car (last (get-text-property 1 'tags a)))) + (tb (car (last (get-text-property 1 'tags b))))) + (cond ((not ta) +1) + ((not tb) -1) + ((string-lessp ta tb) -1) + ((string-lessp tb ta) +1)))) + +(defsubst org-cmp-time (a b) + "Compare the time-of-day values of strings A and B." + (let* ((def (if org-sort-agenda-notime-is-late 9901 -1)) + (ta (or (get-text-property 1 'time-of-day a) def)) + (tb (or (get-text-property 1 'time-of-day b) def))) + (cond ((< ta tb) -1) + ((< tb ta) +1)))) + +(defsubst org-cmp-ts (a b type) + "Compare the timestamps values of entries A and B. +When TYPE is \"scheduled\", \"deadline\", \"timestamp\" or +\"timestamp_ia\", compare within each of these type. When TYPE +is the empty string, compare all timestamps without respect of +their type." + (let* ((def (if org-sort-agenda-notime-is-late most-positive-fixnum -1)) + (ta (or (and (string-match type (or (get-text-property 1 'type a) "")) + (get-text-property 1 'ts-date a)) + def)) + (tb (or (and (string-match type (or (get-text-property 1 'type b) "")) + (get-text-property 1 'ts-date b)) + def))) + (cond ((< ta tb) -1) + ((< tb ta) +1)))) + +(defsubst org-cmp-habit-p (a b) + "Compare the todo states of strings A and B." + (let ((ha (get-text-property 1 'org-habit-p a)) + (hb (get-text-property 1 'org-habit-p b))) + (cond ((and ha (not hb)) -1) + ((and (not ha) hb) +1)))) + +(defun org-entries-lessp (a b) + "Predicate for sorting agenda entries." + ;; The following variables will be used when the form is evaluated. + ;; So even though the compiler complains, keep them. + (let* ((ss org-agenda-sorting-strategy-selected) + (timestamp-up (and (org-em 'timestamp-up 'timestamp-down ss) + (org-cmp-ts a b ""))) + (timestamp-down (if timestamp-up (- timestamp-up) nil)) + (scheduled-up (and (org-em 'scheduled-up 'scheduled-down ss) + (org-cmp-ts a b "scheduled"))) + (scheduled-down (if scheduled-up (- scheduled-up) nil)) + (deadline-up (and (org-em 'deadline-up 'deadline-down ss) + (org-cmp-ts a b "deadline"))) + (deadline-down (if deadline-up (- deadline-up) nil)) + (tsia-up (and (org-em 'tsia-up 'tsia-down ss) + (org-cmp-ts a b "timestamp_ia"))) + (tsia-down (if tsia-up (- tsia-up) nil)) + (ts-up (and (org-em 'ts-up 'ts-down ss) + (org-cmp-ts a b "timestamp"))) + (ts-down (if ts-up (- ts-up) nil)) + (time-up (and (org-em 'time-up 'time-down ss) + (org-cmp-time a b))) + (time-down (if time-up (- time-up) nil)) + (stats-up (and (org-em 'stats-up 'stats-down ss) + (org-cmp-values a b 'org-stats))) + (stats-down (if stats-up (- stats-up) nil)) + (priority-up (and (org-em 'priority-up 'priority-down ss) + (org-cmp-values a b 'priority))) + (priority-down (if priority-up (- priority-up) nil)) + (effort-up (and (org-em 'effort-up 'effort-down ss) + (org-cmp-effort a b))) + (effort-down (if effort-up (- effort-up) nil)) + (category-up (and (or (org-em 'category-up 'category-down ss) + (memq 'category-keep ss)) + (org-cmp-category a b))) + (category-down (if category-up (- category-up) nil)) + (category-keep (if category-up +1 nil)) + (tag-up (and (org-em 'tag-up 'tag-down ss) + (org-cmp-tag a b))) + (tag-down (if tag-up (- tag-up) nil)) + (todo-state-up (and (org-em 'todo-state-up 'todo-state-down ss) + (org-cmp-todo-state a b))) + (todo-state-down (if todo-state-up (- todo-state-up) nil)) + (habit-up (and (org-em 'habit-up 'habit-down ss) + (org-cmp-habit-p a b))) + (habit-down (if habit-up (- habit-up) nil)) + (alpha-up (and (org-em 'alpha-up 'alpha-down ss) + (org-cmp-alpha a b))) + (alpha-down (if alpha-up (- alpha-up) nil)) + (need-user-cmp (org-em 'user-defined-up 'user-defined-down ss)) + user-defined-up user-defined-down) + (if (and need-user-cmp org-agenda-cmp-user-defined + (functionp org-agenda-cmp-user-defined)) + (setq user-defined-up + (funcall org-agenda-cmp-user-defined a b) + user-defined-down (if user-defined-up (- user-defined-up) nil))) + (cdr (assoc + (eval (cons 'or org-agenda-sorting-strategy-selected)) + '((-1 . t) (1 . nil) (nil . nil)))))) + +;;; Agenda restriction lock + +(defvar org-agenda-restriction-lock-overlay (make-overlay 1 1) + "Overlay to mark the headline to which agenda commands are restricted.") +(overlay-put org-agenda-restriction-lock-overlay + 'face 'org-agenda-restriction-lock) +(overlay-put org-agenda-restriction-lock-overlay + 'help-echo "Agendas are currently limited to this subtree.") +(delete-overlay org-agenda-restriction-lock-overlay) + +(defun org-agenda-set-restriction-lock-from-agenda (arg) + "Set the restriction lock to the agenda item at point from within the agenda. +When called with a `\\[universal-argument]' prefix, restrict to +the file which contains the item. +Argument ARG is the prefix argument." + (interactive "P") + (unless (derived-mode-p 'org-agenda-mode) + (user-error "Not in an Org agenda buffer")) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker))) + (with-current-buffer buffer + (goto-char pos) + (org-agenda-set-restriction-lock arg)))) + +;;;###autoload +(defun org-agenda-set-restriction-lock (&optional type) + "Set restriction lock for agenda, to current subtree or file. +Restriction will be the file if TYPE is `file', or if type is the +universal prefix \\='(4), or if the cursor is before the first headline +in the file. Otherwise, restriction will be to the current subtree." + (interactive "P") + (org-agenda-remove-restriction-lock 'noupdate) + (and (equal type '(4)) (setq type 'file)) + (setq type (cond + (type type) + ((org-at-heading-p) 'subtree) + ((condition-case nil (org-back-to-heading t) (error nil)) + 'subtree) + (t 'file))) + (if (eq type 'subtree) + (progn + (setq org-agenda-restrict (current-buffer)) + (setq org-agenda-overriding-restriction 'subtree) + (put 'org-agenda-files 'org-restrict + (list (buffer-file-name (buffer-base-buffer)))) + (org-back-to-heading t) + (move-overlay org-agenda-restriction-lock-overlay + (point) + (if org-agenda-restriction-lock-highlight-subtree + (save-excursion (org-end-of-subtree t t) (point)) + (point-at-eol))) + (move-marker org-agenda-restrict-begin (point)) + (move-marker org-agenda-restrict-end + (save-excursion (org-end-of-subtree t t))) + (message "Locking agenda restriction to subtree")) + (put 'org-agenda-files 'org-restrict + (list (buffer-file-name (buffer-base-buffer)))) + (setq org-agenda-restrict nil) + (setq org-agenda-overriding-restriction 'file) + (move-marker org-agenda-restrict-begin nil) + (move-marker org-agenda-restrict-end nil) + (message "Locking agenda restriction to file")) + (setq current-prefix-arg nil) + (org-agenda-maybe-redo)) + +(defun org-agenda-remove-restriction-lock (&optional noupdate) + "Remove the agenda restriction lock." + (interactive "P") + (delete-overlay org-agenda-restriction-lock-overlay) + (delete-overlay org-speedbar-restriction-lock-overlay) + (setq org-agenda-overriding-restriction nil) + (setq org-agenda-restrict nil) + (put 'org-agenda-files 'org-restrict nil) + (move-marker org-agenda-restrict-begin nil) + (move-marker org-agenda-restrict-end nil) + (setq current-prefix-arg nil) + (message "Agenda restriction lock removed") + (or noupdate (org-agenda-maybe-redo))) + +(defun org-agenda-maybe-redo () + "If there is any window showing the agenda view, update it." + (let ((w (get-buffer-window (or org-agenda-this-buffer-name + org-agenda-buffer-name) + t)) + (w0 (selected-window))) + (when w + (select-window w) + (org-agenda-redo) + (select-window w0) + (if org-agenda-overriding-restriction + (message "Agenda view shifted to new %s restriction" + org-agenda-overriding-restriction) + (message "Agenda restriction lock removed"))))) + +;;; Agenda commands + +(defun org-agenda-check-type (error &rest types) + "Check if agenda buffer is of allowed type. +If ERROR is non-nil, throw an error, otherwise just return nil. +Allowed types are `agenda' `todo' `tags' `search'." + (cond ((not org-agenda-type) + (error "No Org agenda currently displayed")) + ((memq org-agenda-type types) t) + (error + (error "Not allowed in %s-type agenda buffers" org-agenda-type)) + (t nil))) + +(defun org-agenda-Quit () + "Exit the agenda, killing the agenda buffer. +Like `org-agenda-quit', but kill the buffer even when +`org-agenda-sticky' is non-nil." + (interactive) + (org-agenda--quit)) + +(defun org-agenda-quit () + "Exit the agenda. + +When `org-agenda-sticky' is non-nil, bury the agenda buffer +instead of killing it. + +When `org-agenda-restore-windows-after-quit' is non-nil, restore +the pre-agenda window configuration. + +When column view is active, exit column view instead of the +agenda." + (interactive) + (org-agenda--quit org-agenda-sticky)) + +(defun org-agenda--quit (&optional bury) + (if org-agenda-columns-active + (org-columns-quit) + (let ((wconf org-agenda-pre-window-conf) + (buf (current-buffer)) + (org-agenda-last-indirect-window + (and (eq org-indirect-buffer-display 'other-window) + org-agenda-last-indirect-buffer + (get-buffer-window org-agenda-last-indirect-buffer)))) + (cond + ((eq org-agenda-window-setup 'other-frame) + (delete-frame)) + ((and org-agenda-restore-windows-after-quit + wconf) + ;; Maybe restore the pre-agenda window configuration. Reset + ;; `org-agenda-pre-window-conf' before running + ;; `set-window-configuration', which loses the current buffer. + (setq org-agenda-pre-window-conf nil) + (set-window-configuration wconf)) + (t + (when org-agenda-last-indirect-window + (delete-window org-agenda-last-indirect-window)) + (and (not (eq org-agenda-window-setup 'current-window)) + (not (one-window-p)) + (delete-window)))) + (if bury + ;; Set the agenda buffer as the current buffer instead of + ;; passing it as an argument to `bury-buffer' so that + ;; `bury-buffer' removes it from the window. + (with-current-buffer buf + (bury-buffer)) + (kill-buffer buf) + (setq org-agenda-archives-mode nil + org-agenda-buffer nil))))) + +(defun org-agenda-exit () + "Exit the agenda, killing Org buffers loaded by the agenda. +Like `org-agenda-Quit', but kill any buffers that were created by +the agenda. Org buffers visited directly by the user will not be +touched. Also, exit the agenda even if it is in column view." + (interactive) + (when org-agenda-columns-active + (org-columns-quit)) + (org-release-buffers org-agenda-new-buffers) + (setq org-agenda-new-buffers nil) + (org-agenda-Quit)) + +(defun org-agenda-kill-all-agenda-buffers () + "Kill all buffers in `org-agenda-mode'. +This is used when toggling sticky agendas." + (interactive) + (let (blist) + (dolist (buf (buffer-list)) + (when (with-current-buffer buf (eq major-mode 'org-agenda-mode)) + (push buf blist))) + (mapc 'kill-buffer blist))) + +(defun org-agenda-execute (arg) + "Execute another agenda command, keeping same window. +So this is just a shortcut for \\`\\[org-agenda]', available +in the agenda." + (interactive "P") + (let ((org-agenda-window-setup 'current-window)) + (org-agenda arg))) + +(defun org-agenda-redo (&optional all) + "Rebuild possibly ALL agenda view(s) in the current buffer." + (interactive "P") + (let* ((p (or (and (looking-at "\\'") (1- (point))) (point))) + (cpa (unless (eq all t) current-prefix-arg)) + (org-agenda-doing-sticky-redo org-agenda-sticky) + (org-agenda-sticky nil) + (org-agenda-buffer-name (or org-agenda-this-buffer-name + org-agenda-buffer-name)) + (org-agenda-keep-modes t) + (tag-filter org-agenda-tag-filter) + (tag-preset (get 'org-agenda-tag-filter :preset-filter)) + (top-hl-filter org-agenda-top-headline-filter) + (cat-filter org-agenda-category-filter) + (cat-preset (get 'org-agenda-category-filter :preset-filter)) + (re-filter org-agenda-regexp-filter) + (re-preset (get 'org-agenda-regexp-filter :preset-filter)) + (effort-filter org-agenda-effort-filter) + (effort-preset (get 'org-agenda-effort-filter :preset-filter)) + (org-agenda-tag-filter-while-redo (or tag-filter tag-preset)) + (cols org-agenda-columns-active) + (line (org-current-line)) + (window-line (- line (org-current-line (window-start)))) + (lprops (get 'org-agenda-redo-command 'org-lprops)) + (redo-cmd (get-text-property p 'org-redo-cmd)) + (last-args (get-text-property p 'org-last-args)) + (org-agenda-overriding-cmd (get-text-property p 'org-series-cmd)) + (org-agenda-overriding-cmd-arguments + (unless (eq all t) + (cond ((listp last-args) + (cons (or cpa (car last-args)) (cdr last-args))) + ((stringp last-args) + last-args)))) + (series-redo-cmd (get-text-property p 'org-series-redo-cmd))) + (put 'org-agenda-tag-filter :preset-filter nil) + (put 'org-agenda-category-filter :preset-filter nil) + (put 'org-agenda-regexp-filter :preset-filter nil) + (put 'org-agenda-effort-filter :preset-filter nil) + (and cols (org-columns-quit)) + (message "Rebuilding agenda buffer...") + (if series-redo-cmd + (eval series-redo-cmd) + (org-let lprops redo-cmd)) + (setq org-agenda-undo-list nil + org-agenda-pending-undo-list nil + org-agenda-tag-filter tag-filter + org-agenda-category-filter cat-filter + org-agenda-regexp-filter re-filter + org-agenda-effort-filter effort-filter + org-agenda-top-headline-filter top-hl-filter) + (message "Rebuilding agenda buffer...done") + (put 'org-agenda-tag-filter :preset-filter tag-preset) + (put 'org-agenda-category-filter :preset-filter cat-preset) + (put 'org-agenda-regexp-filter :preset-filter re-preset) + (put 'org-agenda-effort-filter :preset-filter effort-preset) + (let ((tag (or tag-filter tag-preset)) + (cat (or cat-filter cat-preset)) + (effort (or effort-filter effort-preset)) + (re (or re-filter re-preset))) + (when tag (org-agenda-filter-apply tag 'tag t)) + (when cat (org-agenda-filter-apply cat 'category)) + (when effort (org-agenda-filter-apply effort 'effort)) + (when re (org-agenda-filter-apply re 'regexp))) + (and top-hl-filter (org-agenda-filter-top-headline-apply top-hl-filter)) + (and cols (called-interactively-p 'any) (org-agenda-columns)) + (org-goto-line line) + (recenter window-line))) + +(defun org-agenda-redo-all (&optional exhaustive) + "Rebuild all agenda views in the current buffer. +With a prefix argument, do so in all agenda buffers." + (interactive "P") + (if exhaustive + (dolist (buffer (buffer-list)) + (with-current-buffer buffer + (when (derived-mode-p 'org-agenda-mode) + (org-agenda-redo t)))) + (org-agenda-redo t))) + +(defvar org-global-tags-completion-table nil) +(defvar org-agenda-filter-form nil) +(defvar org-agenda-filtered-by-category nil) + +(defun org-agenda-filter-by-category (strip) + "Filter lines in the agenda buffer that have a specific category. +The category is that of the current line. +Without prefix argument, keep only the lines of that category. +With a prefix argument, exclude the lines of that category. +" + (interactive "P") + (if (and org-agenda-filtered-by-category + org-agenda-category-filter) + (org-agenda-filter-show-all-cat) + (let ((cat (org-no-properties (org-get-at-eol 'org-category 1)))) + (cond + ((and cat strip) + (org-agenda-filter-apply + (push (concat "-" cat) org-agenda-category-filter) 'category)) + (cat + (org-agenda-filter-apply + (setq org-agenda-category-filter + (list (concat "+" cat))) 'category)) + (t (error "No category at point")))))) + +(defun org-find-top-headline (&optional pos) + "Find the topmost parent headline and return it. +POS when non-nil is the marker or buffer position to start the +search from." + (save-excursion + (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer)) + (when pos (goto-char pos)) + ;; Skip up to the topmost parent. + (while (org-up-heading-safe)) + (ignore-errors (nth 4 (org-heading-components)))))) + +(defvar org-agenda-filtered-by-top-headline nil) +(defun org-agenda-filter-by-top-headline (strip) + "Keep only those lines that are descendants from the same top headline. +The top headline is that of the current line." + (interactive "P") + (if org-agenda-filtered-by-top-headline + (progn + (setq org-agenda-filtered-by-top-headline nil + org-agenda-top-headline-filter nil) + (org-agenda-filter-show-all-top-filter)) + (let ((toph (org-find-top-headline (org-get-at-bol 'org-hd-marker)))) + (if toph (org-agenda-filter-top-headline-apply toph strip) + (error "No top-level headline at point"))))) + +(defvar org-agenda-regexp-filter nil) +(defun org-agenda-filter-by-regexp (strip) + "Filter agenda entries by a regular expression. +Regexp filters are cumulative. +With no prefix argument, keep entries matching the regexp. +With one prefix argument, filter out entries matching the regexp. +With two prefix arguments, remove the regexp filters." + (interactive "P") + (if (not (equal strip '(16))) + (let ((flt (concat (if (equal strip '(4)) "-" "+") + (read-from-minibuffer + (if (equal strip '(4)) + "Filter out entries matching regexp: " + "Narrow to entries matching regexp: "))))) + (push flt org-agenda-regexp-filter) + (org-agenda-filter-apply org-agenda-regexp-filter 'regexp)) + (org-agenda-filter-show-all-re) + (message "Regexp filter removed"))) + +(defvar org-agenda-effort-filter nil) +(defun org-agenda-filter-by-effort (strip) + "Filter agenda entries by effort. +With no prefix argument, keep entries matching the effort condition. +With one prefix argument, filter out entries matching the condition. +With two prefix arguments, remove the effort filters." + (interactive "P") + (cond + ((member strip '(nil 4)) + (let* ((efforts (split-string + (or (cdr (assoc (concat org-effort-property "_ALL") + org-global-properties)) + "0 0:10 0:30 1:00 2:00 3:00 4:00 5:00 6:00 7:00"))) + ;; XXX: the following handles only up to 10 different + ;; effort values. + (allowed-keys (if (null efforts) nil + (mapcar (lambda (n) (mod n 10)) ;turn 10 into 0 + (number-sequence 1 (length efforts))))) + (op nil)) + (while (not (memq op '(?< ?> ?=))) + (setq op (read-char-exclusive "Effort operator? (> = or <)"))) + ;; Select appropriate duration. Ignore non-digit characters. + (let ((prompt + (apply #'format + (concat "Effort %c " + (mapconcat (lambda (s) (concat "[%d]" s)) + efforts + " ")) + op allowed-keys)) + (eff -1)) + (while (not (memq eff allowed-keys)) + (message prompt) + (setq eff (- (read-char-exclusive) 48))) + (setq org-agenda-effort-filter + (list (concat (if strip "-" "+") + (char-to-string op) + ;; Numbering is 1 2 3 ... 9 0, but we want + ;; 0 1 2 ... 8 9. + (nth (mod (1- eff) 10) efforts))))) + (org-agenda-filter-apply org-agenda-effort-filter 'effort))) + (t (org-agenda-filter-show-all-effort) + (message "Effort filter removed")))) + +(defun org-agenda-filter-remove-all () + "Remove all filters from the current agenda buffer." + (interactive) + (when org-agenda-tag-filter + (org-agenda-filter-show-all-tag)) + (when org-agenda-category-filter + (org-agenda-filter-show-all-cat)) + (when org-agenda-regexp-filter + (org-agenda-filter-show-all-re)) + (when org-agenda-top-headline-filter + (org-agenda-filter-show-all-top-filter)) + (when org-agenda-effort-filter + (org-agenda-filter-show-all-effort)) + (org-agenda-finalize)) + +(defun org-agenda-filter-by-tag (arg &optional char exclude) + "Keep only those lines in the agenda buffer that have a specific tag. + +The tag is selected with its fast selection letter, as configured. + +With a `\\[universal-argument]' prefix, exclude the agenda search. + +With a `\\[universal-argument] \\[universal-argument]' prefix, filter the literal tag, \ +i.e. don't +filter on all its group members. + +A lisp caller can specify CHAR. EXCLUDE means that the new tag +should be used to exclude the search - the interactive user can +also press `-' or `+' to switch between filtering and excluding." + (interactive "P") + (let* ((alist org-tag-alist-for-agenda) + (tag-chars (mapconcat + (lambda (x) (if (and (not (symbolp (car x))) + (cdr x)) + (char-to-string (cdr x)) + "")) + org-tag-alist-for-agenda "")) + (valid-char-list (append '(?\t ?\r ?/ ?. ?\s ?q) + (string-to-list tag-chars))) + (exclude (or exclude (equal arg '(4)))) + (expand (not (equal arg '(16)))) + (inhibit-read-only t) + (current org-agenda-tag-filter) + a n tag) + (unless char + (while (not (memq char valid-char-list)) + (message + "%s by tag [%s ]:tag-char, [TAB]:tag, %s[/]:off, [+/-]:filter/exclude%s, [q]:quit" + (if exclude "Exclude" "Filter") + tag-chars + (if org-agenda-auto-exclude-function "[RET], " "") + (if expand "" ", no grouptag expand")) + (setq char (read-char-exclusive)) + ;; Excluding or filtering down + (cond ((eq char ?-) (setq exclude t)) + ((eq char ?+) (setq exclude nil))))) + (when (eq char ?\t) + (unless (local-variable-p 'org-global-tags-completion-table (current-buffer)) + (setq-local org-global-tags-completion-table + (org-global-tags-completion-table))) + (let ((completion-ignore-case t)) + (setq tag (completing-read + "Tag: " org-global-tags-completion-table nil t)))) + (cond + ((eq char ?\r) + (org-agenda-filter-show-all-tag) + (when org-agenda-auto-exclude-function + (setq org-agenda-tag-filter nil) + (dolist (tag (org-agenda-get-represented-tags)) + (let ((modifier (funcall org-agenda-auto-exclude-function tag))) + (if modifier + (push modifier org-agenda-tag-filter)))) + (if (not (null org-agenda-tag-filter)) + (org-agenda-filter-apply org-agenda-tag-filter 'tag expand)))) + ((eq char ?/) + (org-agenda-filter-show-all-tag) + (when (get 'org-agenda-tag-filter :preset-filter) + (org-agenda-filter-apply org-agenda-tag-filter 'tag expand))) + ((eq char ?.) + (setq org-agenda-tag-filter + (mapcar (lambda(tag) (concat "+" tag)) + (org-get-at-bol 'tags))) + (org-agenda-filter-apply org-agenda-tag-filter 'tag expand)) + ((eq char ?q)) ;If q, abort (even if there is a q-key for a tag...) + ((or (eq char ?\s) + (setq a (rassoc char alist)) + (and tag (setq a (cons tag nil)))) + (org-agenda-filter-show-all-tag) + (setq tag (car a)) + (setq org-agenda-tag-filter + (cons (concat (if exclude "-" "+") tag) + current)) + (org-agenda-filter-apply org-agenda-tag-filter 'tag expand)) + (t (error "Invalid tag selection character %c" char))))) + +(defun org-agenda-get-represented-tags () + "Get a list of all tags currently represented in the agenda." + (let (p tags) + (save-excursion + (goto-char (point-min)) + (while (setq p (next-single-property-change (point) 'tags)) + (goto-char p) + (mapc (lambda (x) (add-to-list 'tags x)) + (get-text-property (point) 'tags)))) + tags)) + + +(defun org-agenda-filter-make-matcher (filter type &optional expand) + "Create the form that tests a line for agenda filter. Optional +argument EXPAND can be used for the TYPE tag and will expand the +tags in the FILTER if any of the tags in FILTER are grouptags." + (let (f f1) + (cond + ;; Tag filter + ((eq type 'tag) + (setq filter + (delete-dups + (append (get 'org-agenda-tag-filter :preset-filter) + filter))) + (dolist (x filter) + (let ((op (string-to-char x))) + (if expand (setq x (org-agenda-filter-expand-tags (list x) t)) + (setq x (list x))) + (setq f1 (org-agenda-filter-make-matcher-tag-exp x op)) + (push f1 f)))) + ;; Category filter + ((eq type 'category) + (setq filter + (delete-dups + (append (get 'org-agenda-category-filter :preset-filter) + filter))) + (dolist (x filter) + (if (equal "-" (substring x 0 1)) + (setq f1 (list 'not (list 'equal (substring x 1) 'cat))) + (setq f1 (list 'equal (substring x 1) 'cat))) + (push f1 f))) + ;; Regexp filter + ((eq type 'regexp) + (setq filter + (delete-dups + (append (get 'org-agenda-regexp-filter :preset-filter) + filter))) + (dolist (x filter) + (if (equal "-" (substring x 0 1)) + (setq f1 (list 'not (list 'string-match (substring x 1) 'txt))) + (setq f1 (list 'string-match (substring x 1) 'txt))) + (push f1 f))) + ;; Effort filter + ((eq type 'effort) + (setq filter + (delete-dups + (append (get 'org-agenda-effort-filter :preset-filter) + filter))) + (dolist (x filter) + (push (org-agenda-filter-effort-form x) f)))) + (cons 'and (nreverse f)))) + +(defun org-agenda-filter-make-matcher-tag-exp (tags op) + "Return a form associated to tag-expression TAGS. +Build a form testing a line for agenda filter for +tag-expressions. OP is an operator of type CHAR that allows the +function to set the right switches in the returned form." + (let (form) + ;; Any of the expressions can match if OP is +, all must match if + ;; the operator is -. + (dolist (x tags (cons (if (eq op ?-) 'and 'or) form)) + (let* ((tag (substring x 1)) + (f (cond + ((string= "" tag) '(not tags)) + ((and (string-match-p "\\`{" tag) (string-match-p "}\\'" tag)) + ;; TAG is a regexp. + (list 'org-match-any-p (substring tag 1 -1) 'tags)) + (t (list 'member (downcase tag) 'tags))))) + (push (if (eq op ?-) (list 'not f) f) form))))) + +(defun org-agenda-filter-effort-form (e) + "Return the form to compare the effort of the current line with what E says. +E looks like \"+<2:25\"." + (let (op) + (setq e (substring e 1)) + (setq op (string-to-char e) e (substring e 1)) + (setq op (cond ((equal op ?<) '<=) + ((equal op ?>) '>=) + ((equal op ??) op) + (t '=))) + (list 'org-agenda-compare-effort (list 'quote op) + (org-duration-to-minutes e)))) + +(defun org-agenda-compare-effort (op value) + "Compare the effort of the current line with VALUE, using OP. +If the line does not have an effort defined, return nil." + ;; `effort-minutes' property cannot be extracted directly from + ;; current line but is stored as a property in `txt'. + (let ((effort (get-text-property 0 'effort-minutes (org-get-at-bol 'txt)))) + (funcall op + (or effort (if org-sort-agenda-noeffort-is-high 32767 -1)) + value))) + +(defun org-agenda-filter-expand-tags (filter &optional no-operator) + "Expand group tags in FILTER for the agenda. +When NO-OPERATOR is non-nil, do not add the + operator to returned tags." + (if org-group-tags + (let ((case-fold-search t) rtn) + (mapc + (lambda (f) + (let (f0 dir) + (if (string-match "^\\([+-]\\)\\(.+\\)" f) + (setq dir (match-string 1 f) f0 (match-string 2 f)) + (setq dir (if no-operator "" "+") f0 f)) + (setq rtn (append (mapcar (lambda(f1) (concat dir f1)) + (org-tags-expand f0 t t)) + rtn)))) + filter) + (reverse rtn)) + filter)) + +(defun org-agenda-filter-apply (filter type &optional expand) + "Set FILTER as the new agenda filter and apply it. Optional +argument EXPAND can be used for the TYPE tag and will expand the +tags in the FILTER if any of the tags in FILTER are grouptags." + ;; Deactivate `org-agenda-entry-text-mode' when filtering + (if org-agenda-entry-text-mode (org-agenda-entry-text-mode)) + (let (tags cat txt) + (setq org-agenda-filter-form (org-agenda-filter-make-matcher filter type expand)) + ;; Only set `org-agenda-filtered-by-category' to t when a unique + ;; category is used as the filter: + (setq org-agenda-filtered-by-category + (and (eq type 'category) + (not (equal (substring (car filter) 0 1) "-")))) + (org-agenda-set-mode-name) + (save-excursion + (goto-char (point-min)) + (while (not (eobp)) + (if (org-get-at-bol 'org-marker) + (progn + (setq tags (org-get-at-bol 'tags) + cat (org-get-at-eol 'org-category 1) + txt (org-get-at-bol 'txt)) + (if (not (eval org-agenda-filter-form)) + (org-agenda-filter-hide-line type)) + (beginning-of-line 2)) + (beginning-of-line 2)))) + (if (get-char-property (point) 'invisible) + (ignore-errors (org-agenda-previous-line))))) + +(defun org-agenda-filter-top-headline-apply (hl &optional negative) + "Filter by top headline HL." + (org-agenda-set-mode-name) + (save-excursion + (goto-char (point-min)) + (while (not (eobp)) + (let* ((pos (org-get-at-bol 'org-hd-marker)) + (tophl (and pos (org-find-top-headline pos)))) + (if (and tophl (funcall (if negative 'identity 'not) + (string= hl tophl))) + (org-agenda-filter-hide-line 'top-headline))) + (beginning-of-line 2))) + (if (get-char-property (point) 'invisible) + (org-agenda-previous-line)) + (setq org-agenda-top-headline-filter hl + org-agenda-filtered-by-top-headline t)) + +(defun org-agenda-filter-hide-line (type) + "Hide lines with TYPE in the agenda buffer." + (let* ((b (max (point-min) (1- (point-at-bol)))) + (e (point-at-eol))) + (let ((inhibit-read-only t)) + (add-text-properties + b e `(invisible org-filtered org-filter-type ,type))))) + +(defun org-agenda-remove-filter (type) + (interactive) + "Remove filter of type TYPE from the agenda buffer." + (save-excursion + (goto-char (point-min)) + (let ((inhibit-read-only t) pos) + (while (setq pos (text-property-any (point) (point-max) 'org-filter-type type)) + (goto-char pos) + (remove-text-properties + (point) (next-single-property-change (point) 'org-filter-type) + `(invisible org-filtered org-filter-type ,type)))) + (set (intern (format "org-agenda-%s-filter" (intern-soft type))) nil) + (setq org-agenda-filter-form nil) + (org-agenda-set-mode-name) + (org-agenda-finalize))) + +(defun org-agenda-filter-show-all-tag nil + (org-agenda-remove-filter 'tag)) +(defun org-agenda-filter-show-all-re nil + (org-agenda-remove-filter 'regexp)) +(defun org-agenda-filter-show-all-effort nil + (org-agenda-remove-filter 'effort)) +(defun org-agenda-filter-show-all-cat nil + (org-agenda-remove-filter 'category)) +(defun org-agenda-filter-show-all-top-filter nil + (org-agenda-remove-filter 'top-headline)) + +(defun org-agenda-manipulate-query-add () + "Manipulate the query by adding a search term with positive selection. +Positive selection means the term must be matched for selection of an entry." + (interactive) + (org-agenda-manipulate-query ?\[)) +(defun org-agenda-manipulate-query-subtract () + "Manipulate the query by adding a search term with negative selection. +Negative selection means term must not be matched for selection of an entry." + (interactive) + (org-agenda-manipulate-query ?\])) +(defun org-agenda-manipulate-query-add-re () + "Manipulate the query by adding a search regexp with positive selection. +Positive selection means the regexp must match for selection of an entry." + (interactive) + (org-agenda-manipulate-query ?\{)) +(defun org-agenda-manipulate-query-subtract-re () + "Manipulate the query by adding a search regexp with negative selection. +Negative selection means regexp must not match for selection of an entry." + (interactive) + (org-agenda-manipulate-query ?\})) +(defun org-agenda-manipulate-query (char) + (cond + ((eq org-agenda-type 'agenda) + (let ((org-agenda-include-inactive-timestamps t)) + (org-agenda-redo)) + (message "Display now includes inactive timestamps as well")) + ((eq org-agenda-type 'search) + (org-add-to-string + 'org-agenda-query-string + (if org-agenda-last-search-view-search-was-boolean + (cdr (assoc char '((?\[ . " +") (?\] . " -") + (?\{ . " +{}") (?\} . " -{}")))) + " ")) + (setq org-agenda-redo-command + (list 'org-search-view + (car (get-text-property (min (1- (point-max)) (point)) + 'org-last-args)) + org-agenda-query-string + (+ (length org-agenda-query-string) + (if (member char '(?\{ ?\})) 0 1)))) + (set-register org-agenda-query-register org-agenda-query-string) + (let ((org-agenda-overriding-arguments + (cdr org-agenda-redo-command))) + (org-agenda-redo))) + (t (error "Cannot manipulate query for %s-type agenda buffers" + org-agenda-type)))) + +(defun org-add-to-string (var string) + (set var (concat (symbol-value var) string))) + +(defun org-agenda-goto-date (span) + "Jump to DATE in agenda." + (interactive "P") + (let* ((org-read-date-prefer-future + (eval org-agenda-jump-prefer-future)) + (date (org-read-date)) + (day (time-to-days (org-time-string-to-time date))) + (org-agenda-sticky-orig org-agenda-sticky) + (org-agenda-buffer-tmp-name (buffer-name)) + (args (get-text-property (min (1- (point-max)) (point)) 'org-last-args)) + (0-arg (or current-prefix-arg (car args))) + (2-arg (nth 2 args)) + (with-hour-p (nth 4 org-agenda-redo-command)) + (newcmd (list 'org-agenda-list 0-arg date + (org-agenda-span-to-ndays + 2-arg (org-time-string-to-absolute date)) + with-hour-p)) + (newargs (cdr newcmd)) + (inhibit-read-only t) + org-agenda-sticky) + (if (not (org-agenda-check-type t 'agenda)) + (error "Not available in non-agenda views") + (add-text-properties (point-min) (point-max) + `(org-redo-cmd ,newcmd org-last-args ,newargs)) + (org-agenda-redo) + (goto-char (point-min)) + (while (not (or (= (or (get-text-property (point) 'day) 0) day) + (save-excursion (move-beginning-of-line 2) (eobp)))) + (move-beginning-of-line 2)) + (setq org-agenda-sticky org-agenda-sticky-orig + org-agenda-this-buffer-is-sticky org-agenda-sticky)))) + +(defun org-agenda-goto-today () + "Go to today." + (interactive) + (org-agenda-check-type t 'agenda) + (let* ((args (get-text-property (min (1- (point-max)) (point)) 'org-last-args)) + (curspan (nth 2 args)) + (tdpos (text-property-any (point-min) (point-max) 'org-today t))) + (cond + (tdpos (goto-char tdpos)) + ((eq org-agenda-type 'agenda) + (let* ((sd (org-agenda-compute-starting-span + (org-today) (or curspan org-agenda-span))) + (org-agenda-overriding-arguments args)) + (setf (nth 1 org-agenda-overriding-arguments) sd) + (org-agenda-redo) + (org-agenda-find-same-or-today-or-agenda))) + (t (error "Cannot find today"))))) + +(defun org-agenda-find-same-or-today-or-agenda (&optional cnt) + (goto-char + (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt)) + (text-property-any (point-min) (point-max) 'org-today t) + (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda) + (and (get-text-property (min (1- (point-max)) (point)) 'org-series) + (org-agenda-backward-block)) + (point-min)))) + +(defun org-agenda-backward-block () + "Move backward by one agenda block." + (interactive) + (org-agenda-forward-block 'backward)) + +(defun org-agenda-forward-block (&optional backward) + "Move forward by one agenda block. +When optional argument BACKWARD is set, go backward" + (interactive) + (cond ((not (derived-mode-p 'org-agenda-mode)) + (user-error + "Cannot execute this command outside of org-agenda-mode buffers")) + ((looking-at (if backward "\\`" "\\'")) + (message "Already at the %s block" (if backward "first" "last"))) + (t (let ((pos (prog1 (point) + (ignore-errors (if backward (backward-char 1) + (move-end-of-line 1))))) + (f (if backward + 'previous-single-property-change + 'next-single-property-change)) + moved dest) + (while (and (setq dest (funcall + f (point) 'org-agenda-structural-header)) + (not (get-text-property + (point) 'org-agenda-structural-header))) + (setq moved t) + (goto-char dest)) + (if moved (move-beginning-of-line 1) + (goto-char (if backward (point-min) (point-max))) + (move-beginning-of-line 1) + (message "No %s block" (if backward "previous" "further"))))))) + +(defun org-agenda-later (arg) + "Go forward in time by the current span. +With prefix ARG, go forward that many times the current span." + (interactive "p") + (org-agenda-check-type t 'agenda) + (let* ((args (get-text-property (min (1- (point-max)) (point)) 'org-last-args)) + (span (or (nth 2 args) org-agenda-current-span)) + (sd (or (nth 1 args) (org-get-at-bol 'day) org-starting-day)) + (greg (calendar-gregorian-from-absolute sd)) + (cnt (org-get-at-bol 'org-day-cnt)) + greg2) + (cond + ((numberp span) + (setq sd (+ (* span arg) sd))) + ((eq span 'day) + (setq sd (+ arg sd))) + ((eq span 'week) + (setq sd (+ (* 7 arg) sd))) + ((eq span 'fortnight) + (setq sd (+ (* 14 arg) sd))) + ((eq span 'month) + (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg)) + sd (calendar-absolute-from-gregorian greg2)) + (setcar greg2 (1+ (car greg2)))) + ((eq span 'year) + (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg))) + sd (calendar-absolute-from-gregorian greg2)) + (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))) + (t + (setq sd (+ (* span arg) sd)))) + (let ((org-agenda-overriding-cmd + ;; `cmd' may have been set by `org-agenda-run-series' which + ;; uses `org-agenda-overriding-cmd' to decide whether + ;; overriding is allowed for `cmd' + (get-text-property (min (1- (point-max)) (point)) 'org-series-cmd)) + (org-agenda-overriding-arguments + (list (car args) sd span))) + (org-agenda-redo) + (org-agenda-find-same-or-today-or-agenda cnt)))) + +(defun org-agenda-earlier (arg) + "Go backward in time by the current span. +With prefix ARG, go backward that many times the current span." + (interactive "p") + (org-agenda-later (- arg))) + +(defun org-agenda-view-mode-dispatch () + "Call one of the view mode commands." + (interactive) + (message "View: [d]ay [w]eek for[t]night [m]onth [y]ear [SPC]reset [q]uit/abort + time[G]rid [[]inactive [f]ollow [l]og [L]og-all [c]lockcheck + [a]rch-trees [A]rch-files clock[R]eport include[D]iary [E]ntryText") + (pcase (read-char-exclusive) + (?\ (call-interactively 'org-agenda-reset-view)) + (?d (call-interactively 'org-agenda-day-view)) + (?w (call-interactively 'org-agenda-week-view)) + (?t (call-interactively 'org-agenda-fortnight-view)) + (?m (call-interactively 'org-agenda-month-view)) + (?y (call-interactively 'org-agenda-year-view)) + (?l (call-interactively 'org-agenda-log-mode)) + (?L (org-agenda-log-mode '(4))) + (?c (org-agenda-log-mode 'clockcheck)) + ((or ?F ?f) (call-interactively 'org-agenda-follow-mode)) + (?a (call-interactively 'org-agenda-archives-mode)) + (?A (org-agenda-archives-mode 'files)) + ((or ?R ?r) (call-interactively 'org-agenda-clockreport-mode)) + ((or ?E ?e) (call-interactively 'org-agenda-entry-text-mode)) + (?G (call-interactively 'org-agenda-toggle-time-grid)) + (?D (call-interactively 'org-agenda-toggle-diary)) + (?\! (call-interactively 'org-agenda-toggle-deadlines)) + (?\[ (let ((org-agenda-include-inactive-timestamps t)) + (org-agenda-check-type t 'agenda) + (org-agenda-redo)) + (message "Display now includes inactive timestamps as well")) + (?q (message "Abort")) + (key (user-error "Invalid key: %s" key)))) + +(defun org-agenda-reset-view () + "Switch to default view for agenda." + (interactive) + (org-agenda-change-time-span org-agenda-span)) + +(defun org-agenda-day-view (&optional day-of-month) + "Switch to daily view for agenda. +With argument DAY-OF-MONTH, switch to that day of the month." + (interactive "P") + (org-agenda-change-time-span 'day day-of-month)) + +(defun org-agenda-week-view (&optional iso-week) + "Switch to weekly view for agenda. +With argument ISO-WEEK, switch to the corresponding ISO week. +If ISO-WEEK has more then 2 digits, only the last two encode +the week. Any digits before this encode a year. So 200712 +means week 12 of year 2007. Years ranging from 70 years ago +to 30 years in the future can also be written as 2-digit years." + (interactive "P") + (org-agenda-change-time-span 'week iso-week)) + +(defun org-agenda-fortnight-view (&optional iso-week) + "Switch to fortnightly view for agenda. +With argument ISO-WEEK, switch to the corresponding ISO week. +If ISO-WEEK has more then 2 digits, only the last two encode +the week. Any digits before this encode a year. So 200712 +means week 12 of year 2007. Years ranging from 70 years ago +to 30 years in the future can also be written as 2-digit years." + (interactive "P") + (org-agenda-change-time-span 'fortnight iso-week)) + +(defun org-agenda-month-view (&optional month) + "Switch to monthly view for agenda. +With argument MONTH, switch to that month. If MONTH has more +then 2 digits, only the last two encode the month. Any digits +before this encode a year. So 200712 means December year 2007. +Years ranging from 70 years ago to 30 years in the future can +also be written as 2-digit years." + (interactive "P") + (org-agenda-change-time-span 'month month)) + +(defun org-agenda-year-view (&optional year) + "Switch to yearly view for agenda. +With argument YEAR, switch to that year. Years ranging from 70 +years ago to 30 years in the future can also be written as +2-digit years." + (interactive "P") + (when year + (setq year (org-small-year-to-year year))) + (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ") + (org-agenda-change-time-span 'year year) + (error "Abort"))) + +(defun org-agenda-change-time-span (span &optional n) + "Change the agenda view to SPAN. +SPAN may be `day', `week', `fortnight', `month', `year'." + (org-agenda-check-type t 'agenda) + (let* ((args (get-text-property (min (1- (point-max)) (point)) 'org-last-args)) + (curspan (nth 2 args))) + (if (and (not n) (equal curspan span)) + (error "Viewing span is already \"%s\"" span)) + (let* ((sd (or (org-get-at-bol 'day) + (nth 1 args) + org-starting-day)) + (sd (org-agenda-compute-starting-span sd span n)) + (org-agenda-overriding-cmd + (get-text-property (min (1- (point-max)) (point)) 'org-series-cmd)) + (org-agenda-overriding-arguments + (list (car args) sd span))) + (org-agenda-redo) + (org-agenda-find-same-or-today-or-agenda)) + (org-agenda-set-mode-name) + (message "Switched to %s view" span))) + +(defun org-agenda-compute-starting-span (sd span &optional n) + "Compute starting date for agenda. +SPAN may be `day', `week', `fortnight', `month', `year'. The return value +is a cons cell with the starting date and the number of days, +so that the date SD will be in that range." + (let* ((greg (calendar-gregorian-from-absolute sd)) + (dg (nth 1 greg)) + (mg (car greg)) + (yg (nth 2 greg))) + (cond + ((eq span 'day) + (when n + (setq sd (+ (calendar-absolute-from-gregorian + (list mg 1 yg)) + n -1)))) + ((or (eq span 'week) (eq span 'fortnight)) + (let* ((nt (calendar-day-of-week + (calendar-gregorian-from-absolute sd))) + (d (if org-agenda-start-on-weekday + (- nt org-agenda-start-on-weekday) + 0)) + y1) + (setq sd (- sd (+ (if (< d 0) 7 0) d))) + (when n + (require 'cal-iso) + (when (> n 99) + (setq y1 (org-small-year-to-year (/ n 100)) + n (mod n 100))) + (setq sd + (calendar-iso-to-absolute + (list n 1 + (or y1 (nth 2 (calendar-iso-from-absolute sd))))))))) + ((eq span 'month) + (let (y1) + (when (and n (> n 99)) + (setq y1 (org-small-year-to-year (/ n 100)) + n (mod n 100))) + (setq sd (calendar-absolute-from-gregorian + (list (or n mg) 1 (or y1 yg)))))) + ((eq span 'year) + (setq sd (calendar-absolute-from-gregorian + (list 1 1 (or n yg)))))) + sd)) + +(defun org-agenda-next-date-line (&optional arg) + "Jump to the next line indicating a date in agenda buffer." + (interactive "p") + (org-agenda-check-type t 'agenda) + (beginning-of-line 1) + ;; This does not work if user makes date format that starts with a blank + (if (looking-at "^\\S-") (forward-char 1)) + (if (not (re-search-forward "^\\S-" nil t arg)) + (progn + (backward-char 1) + (error "No next date after this line in this buffer"))) + (goto-char (match-beginning 0))) + +(defun org-agenda-previous-date-line (&optional arg) + "Jump to the previous line indicating a date in agenda buffer." + (interactive "p") + (org-agenda-check-type t 'agenda) + (beginning-of-line 1) + (if (not (re-search-backward "^\\S-" nil t arg)) + (error "No previous date before this line in this buffer"))) + +;; Initialize the highlight +(defvar org-hl (make-overlay 1 1)) +(overlay-put org-hl 'face 'highlight) + +(defun org-highlight (begin end &optional buffer) + "Highlight a region with overlay." + (move-overlay org-hl begin end (or buffer (current-buffer)))) + +(defun org-unhighlight () + "Detach overlay INDEX." + (delete-overlay org-hl)) + +(defun org-unhighlight-once () + "Remove the highlight from its position, and this function from the hook." + (remove-hook 'pre-command-hook 'org-unhighlight-once) + (org-unhighlight)) + +(defvar org-agenda-pre-follow-window-conf nil) +(defun org-agenda-follow-mode () + "Toggle follow mode in an agenda buffer." + (interactive) + (unless org-agenda-follow-mode + (setq org-agenda-pre-follow-window-conf + (current-window-configuration))) + (setq org-agenda-follow-mode (not org-agenda-follow-mode)) + (unless org-agenda-follow-mode + (set-window-configuration org-agenda-pre-follow-window-conf)) + (org-agenda-set-mode-name) + (org-agenda-do-context-action) + (message "Follow mode is %s" + (if org-agenda-follow-mode "on" "off"))) + +(defun org-agenda-entry-text-mode (&optional arg) + "Toggle entry text mode in an agenda buffer." + (interactive "P") + (if (or org-agenda-tag-filter + org-agenda-category-filter + org-agenda-regexp-filter + org-agenda-top-headline-filter) + (user-error "Can't show entry text in filtered views") + (setq org-agenda-entry-text-mode (or (integerp arg) + (not org-agenda-entry-text-mode))) + (org-agenda-entry-text-hide) + (and org-agenda-entry-text-mode + (let ((org-agenda-entry-text-maxlines + (if (integerp arg) arg org-agenda-entry-text-maxlines))) + (org-agenda-entry-text-show))) + (org-agenda-set-mode-name) + (message "Entry text mode is %s%s" + (if org-agenda-entry-text-mode "on" "off") + (if (not org-agenda-entry-text-mode) "" + (format " (maximum number of lines is %d)" + (if (integerp arg) arg org-agenda-entry-text-maxlines)))))) + +(defun org-agenda-clockreport-mode () + "Toggle clocktable mode in an agenda buffer." + (interactive) + (org-agenda-check-type t 'agenda) + (setq org-agenda-clockreport-mode (not org-agenda-clockreport-mode)) + (org-agenda-set-mode-name) + (org-agenda-redo) + (message "Clocktable mode is %s" + (if org-agenda-clockreport-mode "on" "off"))) + +(defun org-agenda-log-mode (&optional special) + "Toggle log mode in an agenda buffer. + +With argument SPECIAL, show all possible log items, not only the ones +configured in `org-agenda-log-mode-items'. + +With a `\\[universal-argument] \\[universal-argument]' prefix, show *only* \ +log items, nothing else." + (interactive "P") + (org-agenda-check-type t 'agenda) + (setq org-agenda-show-log + (cond + ((equal special '(16)) 'only) + ((eq special 'clockcheck) + (if (eq org-agenda-show-log 'clockcheck) + nil 'clockcheck)) + (special '(closed clock state)) + (t (not org-agenda-show-log)))) + (org-agenda-set-mode-name) + (org-agenda-redo) + (message "Log mode is %s" (if org-agenda-show-log "on" "off"))) + +(defun org-agenda-archives-mode (&optional with-files) + "Toggle inclusion of items in trees marked with :ARCHIVE:. +When called with a prefix argument, include all archive files as well." + (interactive "P") + (setq org-agenda-archives-mode + (if with-files t (if org-agenda-archives-mode nil 'trees))) + (org-agenda-set-mode-name) + (org-agenda-redo) + (message + "%s" + (cond + ((eq org-agenda-archives-mode nil) + "No archives are included") + ((eq org-agenda-archives-mode 'trees) + (format "Trees with :%s: tag are included" org-archive-tag)) + ((eq org-agenda-archives-mode t) + (format "Trees with :%s: tag and all active archive files are included" + org-archive-tag))))) + +(defun org-agenda-toggle-diary () + "Toggle diary inclusion in an agenda buffer." + (interactive) + (org-agenda-check-type t 'agenda) + (setq org-agenda-include-diary (not org-agenda-include-diary)) + (org-agenda-redo) + (org-agenda-set-mode-name) + (message "Diary inclusion turned %s" + (if org-agenda-include-diary "on" "off"))) + +(defun org-agenda-toggle-deadlines () + "Toggle inclusion of entries with a deadline in an agenda buffer." + (interactive) + (org-agenda-check-type t 'agenda) + (setq org-agenda-include-deadlines (not org-agenda-include-deadlines)) + (org-agenda-redo) + (org-agenda-set-mode-name) + (message "Deadlines inclusion turned %s" + (if org-agenda-include-deadlines "on" "off"))) + +(defun org-agenda-toggle-time-grid () + "Toggle time grid in an agenda buffer." + (interactive) + (org-agenda-check-type t 'agenda) + (setq org-agenda-use-time-grid (not org-agenda-use-time-grid)) + (org-agenda-redo) + (org-agenda-set-mode-name) + (message "Time-grid turned %s" + (if org-agenda-use-time-grid "on" "off"))) + +(defun org-agenda-set-mode-name () + "Set the mode name to indicate all the small mode settings." + (setq mode-name + (list "Org-Agenda" + (if (get 'org-agenda-files 'org-restrict) " []" "") + " " + '(:eval (org-agenda-span-name org-agenda-current-span)) + (if org-agenda-follow-mode " Follow" "") + (if org-agenda-entry-text-mode " ETxt" "") + (if org-agenda-include-diary " Diary" "") + (if org-agenda-include-deadlines " Ddl" "") + (if org-agenda-use-time-grid " Grid" "") + (if (and (boundp 'org-habit-show-habits) + org-habit-show-habits) " Habit" "") + (cond + ((consp org-agenda-show-log) " LogAll") + ((eq org-agenda-show-log 'clockcheck) " ClkCk") + (org-agenda-show-log " Log") + (t "")) + (if (or org-agenda-category-filter + (get 'org-agenda-category-filter :preset-filter)) + '(:eval (propertize + (concat " <" + (mapconcat + 'identity + (append + (get 'org-agenda-category-filter :preset-filter) + org-agenda-category-filter) + "") + ">") + 'face 'org-agenda-filter-category + 'help-echo "Category used in filtering")) "") + (if (or org-agenda-tag-filter + (get 'org-agenda-tag-filter :preset-filter)) + '(:eval (propertize + (concat " {" + (mapconcat + 'identity + (append + (get 'org-agenda-tag-filter :preset-filter) + org-agenda-tag-filter) + "") + "}") + 'face 'org-agenda-filter-tags + 'help-echo "Tags used in filtering")) "") + (if (or org-agenda-effort-filter + (get 'org-agenda-effort-filter :preset-filter)) + '(:eval (propertize + (concat " {" + (mapconcat + 'identity + (append + (get 'org-agenda-effort-filter :preset-filter) + org-agenda-effort-filter) + "") + "}") + 'face 'org-agenda-filter-effort + 'help-echo "Effort conditions used in filtering")) "") + (if (or org-agenda-regexp-filter + (get 'org-agenda-regexp-filter :preset-filter)) + '(:eval (propertize + (concat " [" + (mapconcat + 'identity + (append + (get 'org-agenda-regexp-filter :preset-filter) + org-agenda-regexp-filter) + "") + "]") + 'face 'org-agenda-filter-regexp + 'help-echo "Regexp used in filtering")) "") + (if org-agenda-archives-mode + (if (eq org-agenda-archives-mode t) + " Archives" + (format " :%s:" org-archive-tag)) + "") + (if org-agenda-clockreport-mode " Clock" ""))) + (force-mode-line-update)) + +(defun org-agenda-update-agenda-type () + "Update the agenda type after each command." + (setq org-agenda-type + (or (get-text-property (point) 'org-agenda-type) + (get-text-property (max (point-min) (1- (point))) 'org-agenda-type)))) + +(defun org-agenda-next-line () + "Move cursor to the next line, and show if follow mode is active." + (interactive) + (call-interactively 'next-line) + (org-agenda-do-context-action)) + +(defun org-agenda-previous-line () + "Move cursor to the previous line, and show if follow-mode is active." + (interactive) + (call-interactively 'previous-line) + (org-agenda-do-context-action)) + +(defun org-agenda-next-item (n) + "Move cursor to next agenda item." + (interactive "p") + (let ((col (current-column))) + (dotimes (c n) + (when (next-single-property-change (point-at-eol) 'org-marker) + (move-end-of-line 1) + (goto-char (next-single-property-change (point) 'org-marker)))) + (org-move-to-column col)) + (org-agenda-do-context-action)) + +(defun org-agenda-previous-item (n) + "Move cursor to next agenda item." + (interactive "p") + (dotimes (c n) + (let ((col (current-column)) + (goto (save-excursion + (move-end-of-line 0) + (previous-single-property-change (point) 'org-marker)))) + (if goto (goto-char goto)) + (org-move-to-column col))) + (org-agenda-do-context-action)) + +(defun org-agenda-do-context-action () + "Show outline path and, maybe, follow mode window." + (let ((m (org-get-at-bol 'org-marker))) + (when (and (markerp m) (marker-buffer m)) + (and org-agenda-follow-mode + (if org-agenda-follow-indirect + (org-agenda-tree-to-indirect-buffer nil) + (org-agenda-show))) + (and org-agenda-show-outline-path + (org-with-point-at m (org-display-outline-path t)))))) + +(defun org-agenda-show-tags () + "Show the tags applicable to the current item." + (interactive) + (let* ((tags (org-get-at-bol 'tags))) + (if tags + (message "Tags are :%s:" + (org-no-properties (mapconcat 'identity tags ":"))) + (message "No tags associated with this line")))) + +(defun org-agenda-goto (&optional highlight) + "Go to the entry at point in the corresponding Org file." + (interactive) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker))) + (switch-to-buffer-other-window buffer) + (widen) + (push-mark) + (goto-char pos) + (when (derived-mode-p 'org-mode) + (org-show-context 'agenda) + (recenter (/ (window-height) 2)) + (org-back-to-heading t) + (let ((case-fold-search nil)) + (when (re-search-forward org-complex-heading-regexp nil t) + (goto-char (match-beginning 4))))) + (run-hooks 'org-agenda-after-show-hook) + (and highlight (org-highlight (point-at-bol) (point-at-eol))))) + +(defvar org-agenda-after-show-hook nil + "Normal hook run after an item has been shown from the agenda. +Point is in the buffer where the item originated.") + +(defun org-agenda-kill () + "Kill the entry or subtree belonging to the current agenda entry." + (interactive) + (or (eq major-mode 'org-agenda-mode) (error "Not in agenda")) + (let* ((bufname-orig (buffer-name)) + (marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker)) + (type (org-get-at-bol 'type)) + dbeg dend (n 0) conf) + (org-with-remote-undo buffer + (with-current-buffer buffer + (save-excursion + (goto-char pos) + (if (and (derived-mode-p 'org-mode) (not (member type '("sexp")))) + (setq dbeg (progn (org-back-to-heading t) (point)) + dend (org-end-of-subtree t t)) + (setq dbeg (point-at-bol) + dend (min (point-max) (1+ (point-at-eol))))) + (goto-char dbeg) + (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n))))) + (setq conf (or (eq t org-agenda-confirm-kill) + (and (numberp org-agenda-confirm-kill) + (> n org-agenda-confirm-kill)))) + (and conf + (not (y-or-n-p + (format "Delete entry with %d lines in buffer \"%s\"? " + n (buffer-name buffer)))) + (error "Abort")) + (let ((org-agenda-buffer-name bufname-orig)) + (org-remove-subtree-entries-from-agenda buffer dbeg dend)) + (with-current-buffer buffer (delete-region dbeg dend)) + (message "Agenda item and source killed")))) + +(defvar org-archive-default-command) ; defined in org-archive.el +(defun org-agenda-archive-default () + "Archive the entry or subtree belonging to the current agenda entry." + (interactive) + (require 'org-archive) + (org-agenda-archive-with org-archive-default-command)) + +(defun org-agenda-archive-default-with-confirmation () + "Archive the entry or subtree belonging to the current agenda entry." + (interactive) + (require 'org-archive) + (org-agenda-archive-with org-archive-default-command 'confirm)) + +(defun org-agenda-archive () + "Archive the entry or subtree belonging to the current agenda entry." + (interactive) + (org-agenda-archive-with 'org-archive-subtree)) + +(defun org-agenda-archive-to-archive-sibling () + "Move the entry to the archive sibling." + (interactive) + (org-agenda-archive-with 'org-archive-to-archive-sibling)) + +(defun org-agenda-archive-with (cmd &optional confirm) + "Move the entry to the archive sibling." + (interactive) + (or (eq major-mode 'org-agenda-mode) (error "Not in agenda")) + (let* ((bufname-orig (buffer-name)) + (marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker))) + (org-with-remote-undo buffer + (with-current-buffer buffer + (if (derived-mode-p 'org-mode) + (if (and confirm + (not (y-or-n-p "Archive this subtree or entry? "))) + (error "Abort") + (save-window-excursion + (goto-char pos) + (let ((org-agenda-buffer-name bufname-orig)) + (org-remove-subtree-entries-from-agenda)) + (org-back-to-heading t) + (funcall cmd))) + (error "Archiving works only in Org files")))))) + +(defun org-remove-subtree-entries-from-agenda (&optional buf beg end) + "Remove all lines in the agenda that correspond to a given subtree. +The subtree is the one in buffer BUF, starting at BEG and ending at END. +If this information is not given, the function uses the tree at point." + (let ((buf (or buf (current-buffer))) m p) + (save-excursion + (unless (and beg end) + (org-back-to-heading t) + (setq beg (point)) + (org-end-of-subtree t) + (setq end (point))) + (set-buffer (get-buffer org-agenda-buffer-name)) + (save-excursion + (goto-char (point-max)) + (beginning-of-line 1) + (while (not (bobp)) + (when (and (setq m (org-get-at-bol 'org-marker)) + (equal buf (marker-buffer m)) + (setq p (marker-position m)) + (>= p beg) + (< p end)) + (let ((inhibit-read-only t)) + (delete-region (point-at-bol) (1+ (point-at-eol))))) + (beginning-of-line 0)))))) + +(defun org-agenda-refile (&optional goto rfloc no-update) + "Refile the item at point. + +When called with `\\[universal-argument] \\[universal-argument]', \ +go to the location of the last +refiled item. + +When called with `\\[universal-argument] \\[universal-argument] \ +\\[universal-argument]' prefix or when GOTO is 0, clear +the refile cache. + +RFLOC can be a refile location obtained in a different way. + +When NO-UPDATE is non-nil, don't redo the agenda buffer." + (interactive "P") + (cond + ((member goto '(0 (64))) + (org-refile-cache-clear)) + ((equal goto '(16)) + (org-refile-goto-last-stored)) + (t + (let* ((buffer-orig (buffer-name)) + (marker (or (org-get-at-bol 'org-hd-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker)) + (rfloc (or rfloc + (org-refile-get-location + (if goto "Goto" "Refile to") buffer + org-refile-allow-creating-parent-nodes)))) + (with-current-buffer buffer + (org-with-wide-buffer + (goto-char marker) + (let ((org-agenda-buffer-name buffer-orig)) + (org-remove-subtree-entries-from-agenda)) + (org-refile goto buffer rfloc)))) + (unless no-update (org-agenda-redo))))) + +(defun org-agenda-open-link (&optional arg) + "Open the link(s) in the current entry, if any. +This looks for a link in the displayed line in the agenda. +It also looks at the text of the entry itself." + (interactive "P") + (let* ((marker (or (org-get-at-bol 'org-hd-marker) + (org-get-at-bol 'org-marker))) + (buffer (and marker (marker-buffer marker))) + (prefix (buffer-substring (point-at-bol) (point-at-eol))) + (lkall (and buffer (org-offer-links-in-entry + buffer marker arg prefix))) + (lk0 (car lkall)) + (lk (if (stringp lk0) (list lk0) lk0)) + (lkend (cdr lkall)) + trg) + (cond + ((and buffer lk) + (mapcar (lambda(l) + (with-current-buffer buffer + (setq trg (and (string-match org-bracket-link-regexp l) + (match-string 1 l))) + (if (or (not trg) (string-match org-any-link-re trg)) + (org-with-wide-buffer + (goto-char marker) + (when (search-forward l nil lkend) + (goto-char (match-beginning 0)) + (org-open-at-point))) + ;; This is an internal link, widen the buffer + (switch-to-buffer-other-window buffer) + (widen) + (goto-char marker) + (when (search-forward l nil lkend) + (goto-char (match-beginning 0)) + (org-open-at-point))))) + lk)) + ((or (org-in-regexp (concat "\\(" org-bracket-link-regexp "\\)")) + (save-excursion + (beginning-of-line 1) + (looking-at (concat ".*?\\(" org-bracket-link-regexp "\\)")))) + (org-open-link-from-string (match-string 1))) + (t (message "No link to open here"))))) + +(defun org-agenda-copy-local-variable (var) + "Get a variable from a referenced buffer and install it here." + (let ((m (org-get-at-bol 'org-marker))) + (when (and m (buffer-live-p (marker-buffer m))) + (set (make-local-variable var) + (with-current-buffer (marker-buffer m) + (symbol-value var)))))) + +(defun org-agenda-switch-to (&optional delete-other-windows) + "Go to the Org mode file which contains the item at point. +When optional argument DELETE-OTHER-WINDOWS is non-nil, the +displayed Org file fills the frame." + (interactive) + (if (and org-return-follows-link + (not (org-get-at-bol 'org-marker)) + (org-in-regexp org-bracket-link-regexp)) + (org-open-link-from-string (match-string 0)) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker))) + (unless buffer (user-error "Trying to switch to non-existent buffer")) + (pop-to-buffer-same-window buffer) + (when delete-other-windows (delete-other-windows)) + (widen) + (goto-char pos) + (when (derived-mode-p 'org-mode) + (org-show-context 'agenda) + (run-hooks 'org-agenda-after-show-hook))))) + +(defun org-agenda-goto-mouse (ev) + "Go to the Org file which contains the item at the mouse click." + (interactive "e") + (mouse-set-point ev) + (org-agenda-goto)) + +(defun org-agenda-show (&optional full-entry) + "Display the Org file which contains the item at point. +With prefix argument FULL-ENTRY, make the entire entry visible +if it was hidden in the outline." + (interactive "P") + (let ((win (selected-window))) + (org-agenda-goto t) + (when full-entry (org-show-entry)) + (select-window win))) + +(defvar org-agenda-show-window nil) +(defun org-agenda-show-and-scroll-up (&optional arg) + "Display the Org file which contains the item at point. + +When called repeatedly, scroll the window that is displaying the buffer. + +With a `\\[universal-argument]' prefix, use `org-show-entry' instead of \ +`outline-show-subtree' +to display the item, so that drawers and logbooks stay folded." + (interactive "P") + (let ((win (selected-window))) + (if (and (window-live-p org-agenda-show-window) + (eq this-command last-command)) + (progn + (select-window org-agenda-show-window) + (ignore-errors (scroll-up))) + (org-agenda-goto t) + (if arg (org-show-entry) (outline-show-subtree)) + (setq org-agenda-show-window (selected-window))) + (select-window win))) + +(defun org-agenda-show-scroll-down () + "Scroll down the window showing the agenda." + (interactive) + (let ((win (selected-window))) + (when (window-live-p org-agenda-show-window) + (select-window org-agenda-show-window) + (ignore-errors (scroll-down)) + (select-window win)))) + +(defun org-agenda-show-1 (&optional more) + "Display the Org file which contains the item at point. +The prefix arg selects the amount of information to display: + +0 hide the subtree +1 just show the entry according to defaults. +2 show the children view +3 show the subtree view +4 show the entire subtree and any LOGBOOK drawers +5 show the entire subtree and any drawers +With prefix argument FULL-ENTRY, make the entire entry visible +if it was hidden in the outline." + (interactive "p") + (let ((win (selected-window))) + (org-agenda-goto t) + (org-back-to-heading) + (set-window-start (selected-window) (point-at-bol)) + (cond + ((= more 0) + (outline-hide-subtree) + (save-excursion + (org-back-to-heading) + (run-hook-with-args 'org-cycle-hook 'folded)) + (message "Remote: FOLDED")) + ((and (called-interactively-p 'any) (= more 1)) + (message "Remote: show with default settings")) + ((= more 2) + (outline-show-entry) + (org-show-children) + (save-excursion + (org-back-to-heading) + (run-hook-with-args 'org-cycle-hook 'children)) + (message "Remote: CHILDREN")) + ((= more 3) + (outline-show-subtree) + (save-excursion + (org-back-to-heading) + (run-hook-with-args 'org-cycle-hook 'subtree)) + (message "Remote: SUBTREE")) + ((= more 4) + (outline-show-subtree) + (save-excursion + (org-back-to-heading) + (org-cycle-hide-drawers 'subtree '("LOGBOOK"))) + (message "Remote: SUBTREE AND LOGBOOK")) + ((> more 4) + (outline-show-subtree) + (message "Remote: SUBTREE AND ALL DRAWERS"))) + (select-window win))) + +(defvar org-agenda-cycle-counter nil) +(defun org-agenda-cycle-show (&optional n) + "Show the current entry in another window, with default settings. + +Default settings are taken from `org-show-context-detail'. When +use repeatedly in immediate succession, the remote entry will +cycle through visibility + + children -> subtree -> folded + +When called with a numeric prefix arg, that arg will be passed through to +`org-agenda-show-1'. For the interpretation of that argument, see the +docstring of `org-agenda-show-1'." + (interactive "P") + (if (integerp n) + (setq org-agenda-cycle-counter n) + (if (not (eq last-command this-command)) + (setq org-agenda-cycle-counter 1) + (if (equal org-agenda-cycle-counter 0) + (setq org-agenda-cycle-counter 2) + (setq org-agenda-cycle-counter (1+ org-agenda-cycle-counter)) + (if (> org-agenda-cycle-counter 3) + (setq org-agenda-cycle-counter 0))))) + (org-agenda-show-1 org-agenda-cycle-counter)) + +(defun org-agenda-recenter (arg) + "Display the Org file which contains the item at point and recenter." + (interactive "P") + (let ((win (selected-window))) + (org-agenda-goto t) + (recenter arg) + (select-window win))) + +(defun org-agenda-show-mouse (ev) + "Display the Org file which contains the item at the mouse click." + (interactive "e") + (mouse-set-point ev) + (org-agenda-show)) + +(defun org-agenda-check-no-diary () + "Check if the entry is a diary link and abort if yes." + (if (org-get-at-bol 'org-agenda-diary-link) + (org-agenda-error))) + +(defun org-agenda-error () + "Throw an error when a command is not allowed in the agenda." + (user-error "Command not allowed in this line")) + +(defun org-agenda-tree-to-indirect-buffer (arg) + "Show the subtree corresponding to the current entry in an indirect buffer. +This calls the command `org-tree-to-indirect-buffer' from the original buffer. + +With a numerical prefix ARG, go up to this level and then take that tree. +With a negative numeric ARG, go up by this number of levels. + +With a `\\[universal-argument]' prefix, make a separate frame for this tree, \ +i.e. don't use +the dedicated frame." + (interactive "P") + (if current-prefix-arg + (org-agenda-do-tree-to-indirect-buffer arg) + (let ((agenda-buffer (buffer-name)) + (agenda-window (selected-window)) + (indirect-window + (and org-last-indirect-buffer + (get-buffer-window org-last-indirect-buffer)))) + (save-window-excursion (org-agenda-do-tree-to-indirect-buffer arg)) + (unless (or (eq org-indirect-buffer-display 'new-frame) + (eq org-indirect-buffer-display 'dedicated-frame)) + (unwind-protect + (unless (and indirect-window (window-live-p indirect-window)) + (setq indirect-window (split-window agenda-window))) + (and indirect-window (select-window indirect-window)) + (switch-to-buffer org-last-indirect-buffer :norecord) + (fit-window-to-buffer indirect-window))) + (select-window (get-buffer-window agenda-buffer)) + (setq org-agenda-last-indirect-buffer org-last-indirect-buffer)))) + +(defun org-agenda-do-tree-to-indirect-buffer (arg) + "Same as `org-agenda-tree-to-indirect-buffer' without saving window." + (org-agenda-check-no-diary) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker))) + (with-current-buffer buffer + (save-excursion + (goto-char pos) + (funcall 'org-tree-to-indirect-buffer arg))))) + +(defvar org-last-heading-marker (make-marker) + "Marker pointing to the headline that last changed its TODO state +by a remote command from the agenda.") + +(defun org-agenda-todo-nextset () + "Switch TODO entry to next sequence." + (interactive) + (org-agenda-todo 'nextset)) + +(defun org-agenda-todo-previousset () + "Switch TODO entry to previous sequence." + (interactive) + (org-agenda-todo 'previousset)) + +(defun org-agenda-todo (&optional arg) + "Cycle TODO state of line at point, also in Org file. +This changes the line at point, all other lines in the agenda referring to +the same tree node, and the headline of the tree node in the Org file." + (interactive "P") + (org-agenda-check-no-diary) + (let* ((col (current-column)) + (marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker)) + (hdmarker (org-get-at-bol 'org-hd-marker)) + (todayp (org-agenda-today-p (org-get-at-bol 'day))) + (inhibit-read-only t) + org-agenda-headline-snapshot-before-repeat newhead just-one) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (org-show-context 'agenda) + (let ((current-prefix-arg arg)) + (call-interactively 'org-todo)) + (and (bolp) (forward-char 1)) + (setq newhead (org-get-heading)) + (when (and (bound-and-true-p + org-agenda-headline-snapshot-before-repeat) + (not (equal org-agenda-headline-snapshot-before-repeat + newhead)) + todayp) + (setq newhead org-agenda-headline-snapshot-before-repeat + just-one t)) + (save-excursion + (org-back-to-heading) + (move-marker org-last-heading-marker (point)))) + (beginning-of-line 1) + (save-window-excursion + (org-agenda-change-all-lines newhead hdmarker 'fixface just-one)) + (when (bound-and-true-p org-clock-out-when-done) + (string-match (concat "^" (regexp-opt org-done-keywords-for-agenda)) + newhead) + (org-agenda-unmark-clocking-task)) + (org-move-to-column col) + (org-agenda-mark-clocking-task)))) + +(defun org-agenda-add-note (&optional arg) + "Add a time-stamped note to the entry at point." + (interactive "P") + (org-agenda-check-no-diary) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker)) + (hdmarker (org-get-at-bol 'org-hd-marker)) + (inhibit-read-only t)) + (with-current-buffer buffer + (widen) + (goto-char pos) + (org-show-context 'agenda) + (org-add-note)))) + +(defun org-agenda-change-all-lines (newhead hdmarker + &optional fixface just-this) + "Change all lines in the agenda buffer which match HDMARKER. +The new content of the line will be NEWHEAD (as modified by +`org-agenda-format-item'). HDMARKER is checked with +`equal' against all `org-hd-marker' text properties in the file. +If FIXFACE is non-nil, the face of each item is modified according to +the new TODO state. +If JUST-THIS is non-nil, change just the current line, not all. +If FORCE-TAGS is non nil, the car of it returns the new tags." + (let* ((inhibit-read-only t) + (line (org-current-line)) + (org-agenda-buffer (current-buffer)) + (thetags (with-current-buffer (marker-buffer hdmarker) + (org-with-wide-buffer + (goto-char hdmarker) + (org-get-tags-at)))) + props m pl undone-face done-face finish new dotime level cat tags) + (save-excursion + (goto-char (point-max)) + (beginning-of-line 1) + (while (not finish) + (setq finish (bobp)) + (when (and (setq m (org-get-at-bol 'org-hd-marker)) + (or (not just-this) (= (org-current-line) line)) + (equal m hdmarker)) + (setq props (text-properties-at (point)) + dotime (org-get-at-bol 'dotime) + cat (org-get-at-eol 'org-category 1) + level (org-get-at-bol 'level) + tags thetags + new + (let ((org-prefix-format-compiled + (or (get-text-property (min (1- (point-max)) (point)) 'format) + org-prefix-format-compiled)) + (extra (org-get-at-bol 'extra))) + (with-current-buffer (marker-buffer hdmarker) + (org-with-wide-buffer + (org-agenda-format-item extra newhead level cat tags dotime)))) + pl (text-property-any (point-at-bol) (point-at-eol) 'org-heading t) + undone-face (org-get-at-bol 'undone-face) + done-face (org-get-at-bol 'done-face)) + (beginning-of-line 1) + (cond + ((equal new "") (delete-region (point) (line-beginning-position 2))) + ((looking-at ".*") + ;; When replacing the whole line, preserve bulk mark + ;; overlay, if any. + (let ((mark (catch :overlay + (dolist (o (overlays-in (point) (+ 2 (point)))) + (when (eq (overlay-get o 'type) + 'org-marked-entry-overlay) + (throw :overlay o)))))) + (replace-match new t t) + (beginning-of-line) + (when mark (move-overlay mark (point) (+ 2 (point))))) + (add-text-properties (point-at-bol) (point-at-eol) props) + (when fixface + (add-text-properties + (point-at-bol) (point-at-eol) + (list 'face + (if org-last-todo-state-is-todo + undone-face done-face)))) + (org-agenda-highlight-todo 'line) + (beginning-of-line 1)) + (t (error "Line update did not work"))) + (save-restriction + (narrow-to-region (point-at-bol) (point-at-eol)) + (org-agenda-finalize))) + (beginning-of-line 0))))) + +(defun org-agenda-align-tags (&optional line) + "Align all tags in agenda items to `org-agenda-tags-column'." + (let ((inhibit-read-only t) + (org-agenda-tags-column (if (eq 'auto org-agenda-tags-column) + (- (window-text-width)) + org-agenda-tags-column)) + l c) + (save-excursion + (goto-char (if line (point-at-bol) (point-min))) + (while (re-search-forward "\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" + (if line (point-at-eol) nil) t) + (add-text-properties + (match-beginning 2) (match-end 2) + (list 'face (delq nil (let ((prop (get-text-property + (match-beginning 2) 'face))) + (or (listp prop) (setq prop (list prop))) + (if (memq 'org-tag prop) + prop + (cons 'org-tag prop)))))) + (setq l (- (match-end 2) (match-beginning 2)) + c (if (< org-agenda-tags-column 0) + (- (abs org-agenda-tags-column) l) + org-agenda-tags-column)) + (delete-region (match-beginning 1) (match-end 1)) + (goto-char (match-beginning 1)) + (insert (org-add-props + (make-string (max 1 (- c (current-column))) ?\ ) + (plist-put (copy-sequence (text-properties-at (point))) + 'face nil)))) + (goto-char (point-min)) + (org-font-lock-add-tag-faces (point-max))))) + +(defun org-agenda-priority-up () + "Increase the priority of line at point, also in Org file." + (interactive) + (org-agenda-priority 'up)) + +(defun org-agenda-priority-down () + "Decrease the priority of line at point, also in Org file." + (interactive) + (org-agenda-priority 'down)) + +(defun org-agenda-priority (&optional force-direction) + "Set the priority of line at point, also in Org file. +This changes the line at point, all other lines in the agenda referring to +the same tree node, and the headline of the tree node in the Org file. +Called with a universal prefix arg, show the priority instead of setting it." + (interactive "P") + (if (equal force-direction '(4)) + (org-show-priority) + (unless org-enable-priority-commands + (error "Priority commands are disabled")) + (org-agenda-check-no-diary) + (let* ((col (current-column)) + (marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (hdmarker (org-get-at-bol 'org-hd-marker)) + (buffer (marker-buffer hdmarker)) + (pos (marker-position hdmarker)) + (inhibit-read-only t) + newhead) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (org-show-context 'agenda) + (funcall 'org-priority force-direction) + (end-of-line 1) + (setq newhead (org-get-heading))) + (org-agenda-change-all-lines newhead hdmarker) + (org-move-to-column col))))) + +;; FIXME: should fix the tags property of the agenda line. +(defun org-agenda-set-tags (&optional tag onoff) + "Set tags for the current headline." + (interactive) + (org-agenda-check-no-diary) + (if (and (org-region-active-p) (called-interactively-p 'any)) + (call-interactively 'org-change-tag-in-region) + (let* ((hdmarker (or (org-get-at-bol 'org-hd-marker) + (org-agenda-error))) + (buffer (marker-buffer hdmarker)) + (pos (marker-position hdmarker)) + (inhibit-read-only t) + newhead) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (org-show-context 'agenda) + (if tag + (org-toggle-tag tag onoff) + (call-interactively 'org-set-tags)) + (end-of-line 1) + (setq newhead (org-get-heading))) + (org-agenda-change-all-lines newhead hdmarker) + (beginning-of-line 1))))) + +(defun org-agenda-set-property () + "Set a property for the current headline." + (interactive) + (org-agenda-check-no-diary) + (let* ((hdmarker (or (org-get-at-bol 'org-hd-marker) + (org-agenda-error))) + (buffer (marker-buffer hdmarker)) + (pos (marker-position hdmarker)) + (inhibit-read-only t) + newhead) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (org-show-context 'agenda) + (call-interactively 'org-set-property))))) + +(defun org-agenda-set-effort () + "Set the effort property for the current headline." + (interactive) + (org-agenda-check-no-diary) + (let* ((hdmarker (or (org-get-at-bol 'org-hd-marker) + (org-agenda-error))) + (buffer (marker-buffer hdmarker)) + (pos (marker-position hdmarker)) + (inhibit-read-only t) + newhead) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (org-show-context 'agenda) + (call-interactively 'org-set-effort) + (end-of-line 1) + (setq newhead (org-get-heading))) + (org-agenda-change-all-lines newhead hdmarker)))) + +(defun org-agenda-toggle-archive-tag () + "Toggle the archive tag for the current entry." + (interactive) + (org-agenda-check-no-diary) + (let* ((hdmarker (or (org-get-at-bol 'org-hd-marker) + (org-agenda-error))) + (buffer (marker-buffer hdmarker)) + (pos (marker-position hdmarker)) + (inhibit-read-only t) + newhead) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (org-show-context 'agenda) + (call-interactively 'org-toggle-archive-tag) + (end-of-line 1) + (setq newhead (org-get-heading))) + (org-agenda-change-all-lines newhead hdmarker) + (beginning-of-line 1)))) + +(defun org-agenda-do-date-later (arg) + (interactive "P") + (cond + ((or (equal arg '(16)) + (memq last-command + '(org-agenda-date-later-minutes org-agenda-date-earlier-minutes))) + (setq this-command 'org-agenda-date-later-minutes) + (org-agenda-date-later-minutes 1)) + ((or (equal arg '(4)) + (memq last-command + '(org-agenda-date-later-hours org-agenda-date-earlier-hours))) + (setq this-command 'org-agenda-date-later-hours) + (org-agenda-date-later-hours 1)) + (t + (org-agenda-date-later (prefix-numeric-value arg))))) + +(defun org-agenda-do-date-earlier (arg) + (interactive "P") + (cond + ((or (equal arg '(16)) + (memq last-command + '(org-agenda-date-later-minutes org-agenda-date-earlier-minutes))) + (setq this-command 'org-agenda-date-earlier-minutes) + (org-agenda-date-earlier-minutes 1)) + ((or (equal arg '(4)) + (memq last-command + '(org-agenda-date-later-hours org-agenda-date-earlier-hours))) + (setq this-command 'org-agenda-date-earlier-hours) + (org-agenda-date-earlier-hours 1)) + (t + (org-agenda-date-earlier (prefix-numeric-value arg))))) + +(defun org-agenda-date-later (arg &optional what) + "Change the date of this item to ARG day(s) later." + (interactive "p") + (org-agenda-check-type t 'agenda) + (org-agenda-check-no-diary) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker)) + cdate today) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (unless (org-at-timestamp-p 'lax) (error "Cannot find time stamp")) + (when (and org-agenda-move-date-from-past-immediately-to-today + (equal arg 1) + (or (not what) (eq what 'day)) + (not (save-match-data (org-at-date-range-p)))) + (setq cdate (org-parse-time-string (match-string 0) 'nodefault) + cdate (calendar-absolute-from-gregorian + (list (nth 4 cdate) (nth 3 cdate) (nth 5 cdate))) + today (org-today)) + (if (> today cdate) + ;; immediately shift to today + (setq arg (- today cdate)))) + (org-timestamp-change arg (or what 'day)) + (when (and (org-at-date-range-p) + (re-search-backward org-tr-regexp-both (point-at-bol))) + (let ((end org-last-changed-timestamp)) + (org-timestamp-change arg (or what 'day)) + (setq org-last-changed-timestamp + (concat org-last-changed-timestamp "--" end))))) + (org-agenda-show-new-time marker org-last-changed-timestamp)) + (message "Time stamp changed to %s" org-last-changed-timestamp))) + +(defun org-agenda-date-earlier (arg &optional what) + "Change the date of this item to ARG day(s) earlier." + (interactive "p") + (org-agenda-date-later (- arg) what)) + +(defun org-agenda-date-later-minutes (arg) + "Change the time of this item, in units of `org-time-stamp-rounding-minutes'." + (interactive "p") + (setq arg (* arg (cadr org-time-stamp-rounding-minutes))) + (org-agenda-date-later arg 'minute)) + +(defun org-agenda-date-earlier-minutes (arg) + "Change the time of this item, in units of `org-time-stamp-rounding-minutes'." + (interactive "p") + (setq arg (* arg (cadr org-time-stamp-rounding-minutes))) + (org-agenda-date-earlier arg 'minute)) + +(defun org-agenda-date-later-hours (arg) + "Change the time of this item, in hour steps." + (interactive "p") + (org-agenda-date-later arg 'hour)) + +(defun org-agenda-date-earlier-hours (arg) + "Change the time of this item, in hour steps." + (interactive "p") + (org-agenda-date-earlier arg 'hour)) + +(defun org-agenda-show-new-time (marker stamp &optional prefix) + "Show new date stamp via text properties." + ;; We use text properties to make this undoable + (let ((inhibit-read-only t)) + (setq stamp (concat prefix " => " stamp " ")) + (save-excursion + (goto-char (point-max)) + (while (not (bobp)) + (when (equal marker (org-get-at-bol 'org-marker)) + (remove-text-properties (point-at-bol) (point-at-eol) '(display)) + (org-move-to-column (- (window-width) (length stamp)) t) + (add-text-properties + (1- (point)) (point-at-eol) + (list 'display (org-add-props stamp nil + 'face '(secondary-selection default)))) + (beginning-of-line 1)) + (beginning-of-line 0))))) + +(defun org-agenda-date-prompt (arg) + "Change the date of this item. Date is prompted for, with default today. +The prefix ARG is passed to the `org-time-stamp' command and can therefore +be used to request time specification in the time stamp." + (interactive "P") + (org-agenda-check-type t 'agenda) + (org-agenda-check-no-diary) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker))) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (unless (org-at-timestamp-p 'lax) (error "Cannot find time stamp")) + (org-time-stamp arg (equal (char-after (match-beginning 0)) ?\[))) + (org-agenda-show-new-time marker org-last-changed-timestamp)) + (message "Time stamp changed to %s" org-last-changed-timestamp))) + +(defun org-agenda-schedule (arg &optional time) + "Schedule the item at point. +ARG is passed through to `org-schedule'." + (interactive "P") + (org-agenda-check-type t 'agenda 'todo 'tags 'search) + (org-agenda-check-no-diary) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (type (marker-insertion-type marker)) + (buffer (marker-buffer marker)) + (pos (marker-position marker)) + ts) + (set-marker-insertion-type marker t) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (setq ts (org-schedule arg time))) + (org-agenda-show-new-time marker ts " S")) + (message "%s" ts))) + +(defun org-agenda-deadline (arg &optional time) + "Schedule the item at point. +ARG is passed through to `org-deadline'." + (interactive "P") + (org-agenda-check-type t 'agenda 'todo 'tags 'search) + (org-agenda-check-no-diary) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (buffer (marker-buffer marker)) + (pos (marker-position marker)) + ts) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (setq ts (org-deadline arg time))) + (org-agenda-show-new-time marker ts " D")) + (message "%s" ts))) + +(defun org-agenda-clock-in (&optional arg) + "Start the clock on the currently selected item." + (interactive "P") + (org-agenda-check-no-diary) + (if (equal arg '(4)) + (org-clock-in arg) + (let* ((marker (or (org-get-at-bol 'org-marker) + (org-agenda-error))) + (hdmarker (or (org-get-at-bol 'org-hd-marker) marker)) + (pos (marker-position marker)) + (col (current-column)) + newhead) + (org-with-remote-undo (marker-buffer marker) + (with-current-buffer (marker-buffer marker) + (widen) + (goto-char pos) + (org-show-context 'agenda) + (org-cycle-hide-drawers 'children) + (org-clock-in arg) + (setq newhead (org-get-heading))) + (org-agenda-change-all-lines newhead hdmarker)) + (org-move-to-column col)))) + +(defun org-agenda-clock-out () + "Stop the currently running clock." + (interactive) + (unless (marker-buffer org-clock-marker) + (error "No running clock")) + (let ((marker (make-marker)) (col (current-column)) newhead) + (org-with-remote-undo (marker-buffer org-clock-marker) + (with-current-buffer (marker-buffer org-clock-marker) + (org-with-wide-buffer + (goto-char org-clock-marker) + (org-back-to-heading t) + (move-marker marker (point)) + (org-clock-out) + (setq newhead (org-get-heading))))) + (org-agenda-change-all-lines newhead marker) + (move-marker marker nil) + (org-move-to-column col) + (org-agenda-unmark-clocking-task))) + +(defun org-agenda-clock-cancel (&optional arg) + "Cancel the currently running clock." + (interactive "P") + (unless (marker-buffer org-clock-marker) + (user-error "No running clock")) + (org-with-remote-undo (marker-buffer org-clock-marker) + (org-clock-cancel))) + +(defun org-agenda-clock-goto () + "Jump to the currently clocked in task within the agenda. +If the currently clocked in task is not listed in the agenda +buffer, display it in another window." + (interactive) + (let (pos) + (mapc (lambda (o) + (if (eq (overlay-get o 'type) 'org-agenda-clocking) + (setq pos (overlay-start o)))) + (overlays-in (point-min) (point-max))) + (cond (pos (goto-char pos)) + ;; If the currently clocked entry is not in the agenda + ;; buffer, we visit it in another window: + ((bound-and-true-p org-clock-current-task) + (org-switch-to-buffer-other-window (org-clock-goto))) + (t (message "No running clock, use `C-c C-x C-j' to jump to the most recent one"))))) + +(defun org-agenda-diary-entry-in-org-file () + "Make a diary entry in the file `org-agenda-diary-file'." + (let (d1 d2 char (text "") dp1 dp2) + (if (equal (buffer-name) "*Calendar*") + (setq d1 (calendar-cursor-to-date t) + d2 (car calendar-mark-ring)) + (setq dp1 (get-text-property (point-at-bol) 'day)) + (unless dp1 (user-error "No date defined in current line")) + (setq d1 (calendar-gregorian-from-absolute dp1) + d2 (and (ignore-errors (mark)) + (save-excursion + (goto-char (mark)) + (setq dp2 (get-text-property (point-at-bol) 'day))) + (calendar-gregorian-from-absolute dp2)))) + (message "Diary entry: [d]ay [a]nniversary [b]lock [j]ump to date tree") + (setq char (read-char-exclusive)) + (cond + ((equal char ?d) + (setq text (read-string "Day entry: ")) + (org-agenda-add-entry-to-org-agenda-diary-file 'day text d1) + (and (equal (buffer-name) org-agenda-buffer-name) (org-agenda-redo))) + ((equal char ?a) + (setq d1 (list (car d1) (nth 1 d1) + (read-number (format "Reference year [%d]: " (nth 2 d1)) + (nth 2 d1)))) + (setq text (read-string "Anniversary (use %d to show years): ")) + (org-agenda-add-entry-to-org-agenda-diary-file 'anniversary text d1) + (and (equal (buffer-name) org-agenda-buffer-name) (org-agenda-redo))) + ((equal char ?b) + (setq text (read-string "Block entry: ")) + (unless (and d1 d2 (not (equal d1 d2))) + (user-error "No block of days selected")) + (org-agenda-add-entry-to-org-agenda-diary-file 'block text d1 d2) + (and (equal (buffer-name) org-agenda-buffer-name) (org-agenda-redo))) + ((equal char ?j) + (org-switch-to-buffer-other-window + (find-file-noselect org-agenda-diary-file)) + (require 'org-datetree) + (org-datetree-find-date-create d1) + (org-reveal t)) + (t (user-error "Invalid selection character `%c'" char))))) + +(defcustom org-agenda-insert-diary-strategy 'date-tree + "Where in `org-agenda-diary-file' should new entries be added? +Valid values: + +date-tree in the date tree, as first child of the date +date-tree-last in the date tree, as last child of the date +top-level as top-level entries at the end of the file." + :group 'org-agenda + :type '(choice + (const :tag "first in a date tree" date-tree) + (const :tag "last in a date tree" date-tree-last) + (const :tag "as top level at end of file" top-level))) + +(defcustom org-agenda-insert-diary-extract-time nil + "Non-nil means extract any time specification from the diary entry." + :group 'org-agenda + :version "24.1" + :type 'boolean) + +(defcustom org-agenda-bulk-mark-char ">" + "A single-character string to be used as the bulk mark." + :group 'org-agenda + :version "24.1" + :type 'string) + +(defun org-agenda-add-entry-to-org-agenda-diary-file (type text &optional d1 d2) + "Add a diary entry with TYPE to `org-agenda-diary-file'. +If TEXT is not empty, it will become the headline of the new entry, and +the resulting entry will not be shown. When TEXT is empty, switch to +`org-agenda-diary-file' and let the user finish the entry there." + (let ((cw (current-window-configuration))) + (org-switch-to-buffer-other-window + (find-file-noselect org-agenda-diary-file)) + (widen) + (goto-char (point-min)) + (cond + ((eq type 'anniversary) + (or (re-search-forward "^*[ \t]+Anniversaries" nil t) + (progn + (or (org-at-heading-p t) + (progn + (outline-next-heading) + (insert "* Anniversaries\n\n") + (beginning-of-line -1))))) + (outline-next-heading) + (org-back-over-empty-lines) + (backward-char 1) + (insert "\n") + (insert (format "%%%%(org-anniversary %d %2d %2d) %s" + (nth 2 d1) (car d1) (nth 1 d1) text))) + ((eq type 'day) + (let ((org-prefix-has-time t) + (org-agenda-time-leading-zero t) + fmt time time2) + (if org-agenda-insert-diary-extract-time + ;; Use org-agenda-format-item to parse text for a time-range and + ;; remove it. FIXME: This is a hack, we should refactor + ;; that function to make time extraction available separately + (setq fmt (org-agenda-format-item nil text nil nil nil t) + time (get-text-property 0 'time fmt) + time2 (if (> (length time) 0) + ;; split-string removes trailing ...... if + ;; no end time given. First space + ;; separates time from date. + (concat " " (car (split-string time "\\."))) + nil) + text (get-text-property 0 'txt fmt))) + (if (eq org-agenda-insert-diary-strategy 'top-level) + (org-agenda-insert-diary-as-top-level text) + (require 'org-datetree) + (org-datetree-find-date-create d1) + (org-agenda-insert-diary-make-new-entry text)) + (org-insert-time-stamp (org-time-from-absolute + (calendar-absolute-from-gregorian d1)) + nil nil nil nil time2)) + (end-of-line 0)) + ((eq type 'block) + (if (> (calendar-absolute-from-gregorian d1) + (calendar-absolute-from-gregorian d2)) + (setq d1 (prog1 d2 (setq d2 d1)))) + (if (eq org-agenda-insert-diary-strategy 'top-level) + (org-agenda-insert-diary-as-top-level text) + (require 'org-datetree) + (org-datetree-find-date-create d1) + (org-agenda-insert-diary-make-new-entry text)) + (org-insert-time-stamp (org-time-from-absolute + (calendar-absolute-from-gregorian d1))) + (insert "--") + (org-insert-time-stamp (org-time-from-absolute + (calendar-absolute-from-gregorian d2))) + (end-of-line 0))) + (if (string-match "\\S-" text) + (progn + (set-window-configuration cw) + (message "%s entry added to %s" + (capitalize (symbol-name type)) + (abbreviate-file-name org-agenda-diary-file))) + (org-reveal t) + (message "Please finish entry here")))) + +(defun org-agenda-insert-diary-as-top-level (text) + "Make new entry as a top-level entry at the end of the file. +Add TEXT as headline, and position the cursor in the second line so that +a timestamp can be added there." + (widen) + (goto-char (point-max)) + (unless (bolp) (insert "\n")) + (org-insert-heading nil t t) + (insert text) + (org-end-of-meta-data) + (unless (bolp) (insert "\n")) + (when org-adapt-indentation (indent-to-column 2))) + +(defun org-agenda-insert-diary-make-new-entry (text) + "Make a new entry with TEXT as a child of the current subtree. +Position the point in the heading's first body line so that +a timestamp can be added there." + (cond + ((eq org-agenda-insert-diary-strategy 'date-tree-last) + (end-of-line) + (org-insert-heading '(4) t) + (org-do-demote)) + (t + (outline-next-heading) + (org-back-over-empty-lines) + (unless (looking-at "[ \t]*$") (save-excursion (insert "\n"))) + (org-insert-heading nil t) + (org-do-demote))) + (let ((col (current-column))) + (insert text) + (org-end-of-meta-data) + ;; Ensure point is left on a blank line, at proper indentation. + (unless (bolp) (insert "\n")) + (unless (looking-at-p "^[ \t]*$") (save-excursion (insert "\n"))) + (when org-adapt-indentation (indent-to-column col))) + (org-show-set-visibility 'lineage)) + +(defun org-agenda-diary-entry () + "Make a diary entry, like the `i' command from the calendar. +All the standard commands work: block, weekly etc. +When `org-agenda-diary-file' points to a file, +`org-agenda-diary-entry-in-org-file' is called instead to create +entries in that Org file." + (interactive) + (if (not (eq org-agenda-diary-file 'diary-file)) + (org-agenda-diary-entry-in-org-file) + (require 'diary-lib) + (let* ((char (progn + (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic") + (read-char-exclusive))) + (cmd (cdr (assoc char + '((?d . diary-insert-entry) + (?w . diary-insert-weekly-entry) + (?m . diary-insert-monthly-entry) + (?y . diary-insert-yearly-entry) + (?a . diary-insert-anniversary-entry) + (?b . diary-insert-block-entry) + (?c . diary-insert-cyclic-entry))))) + (oldf (symbol-function 'calendar-cursor-to-date)) + ;; (buf (get-file-buffer (substitute-in-file-name diary-file))) + (point (point)) + (mark (or (mark t) (point)))) + (unless cmd + (user-error "No command associated with <%c>" char)) + (unless (and (get-text-property point 'day) + (or (not (equal ?b char)) + (get-text-property mark 'day))) + (user-error "Don't know which date to use for diary entry")) + ;; We implement this by hacking the `calendar-cursor-to-date' function + ;; and the `calendar-mark-ring' variable. Saves a lot of code. + (let ((calendar-mark-ring + (list (calendar-gregorian-from-absolute + (or (get-text-property mark 'day) + (get-text-property point 'day)))))) + (unwind-protect + (progn + (fset 'calendar-cursor-to-date + (lambda (&optional error dummy) + (calendar-gregorian-from-absolute + (get-text-property point 'day)))) + (call-interactively cmd)) + (fset 'calendar-cursor-to-date oldf)))))) + +(defun org-agenda-execute-calendar-command (cmd) + "Execute a calendar command from the agenda with date from cursor." + (org-agenda-check-type t 'agenda) + (require 'diary-lib) + (unless (get-text-property (min (1- (point-max)) (point)) 'day) + (user-error "Don't know which date to use for the calendar command")) + (let* ((oldf (symbol-function 'calendar-cursor-to-date)) + (point (point)) + (date (calendar-gregorian-from-absolute + (get-text-property point 'day))) + ;; the following 2 vars are needed in the calendar + (displayed-month (car date)) + (displayed-year (nth 2 date))) + (unwind-protect + (progn + (fset 'calendar-cursor-to-date + (lambda (&optional error dummy) + (calendar-gregorian-from-absolute + (get-text-property point 'day)))) + (call-interactively cmd)) + (fset 'calendar-cursor-to-date oldf)))) + +(defun org-agenda-phases-of-moon () + "Display the phases of the moon for the 3 months around the cursor date." + (interactive) + (org-agenda-execute-calendar-command 'calendar-lunar-phases)) + +(defun org-agenda-holidays () + "Display the holidays for the 3 months around the cursor date." + (interactive) + (org-agenda-execute-calendar-command 'calendar-list-holidays)) + +(defvar calendar-longitude) ; defined in calendar.el +(defvar calendar-latitude) ; defined in calendar.el +(defvar calendar-location-name) ; defined in calendar.el + +(defun org-agenda-sunrise-sunset (arg) + "Display sunrise and sunset for the cursor date. +Latitude and longitude can be specified with the variables +`calendar-latitude' and `calendar-longitude'. When called with prefix +argument, latitude and longitude will be prompted for." + (interactive "P") + (require 'solar) + (let ((calendar-longitude (if arg nil calendar-longitude)) + (calendar-latitude (if arg nil calendar-latitude)) + (calendar-location-name + (if arg "the given coordinates" calendar-location-name))) + (org-agenda-execute-calendar-command 'calendar-sunrise-sunset))) + +(defun org-agenda-goto-calendar () + "Open the Emacs calendar with the date at the cursor." + (interactive) + (org-agenda-check-type t 'agenda) + (let* ((day (or (get-text-property (min (1- (point-max)) (point)) 'day) + (user-error "Don't know which date to open in calendar"))) + (date (calendar-gregorian-from-absolute day)) + (calendar-move-hook nil) + (calendar-view-holidays-initially-flag nil) + (calendar-view-diary-initially-flag nil)) + (calendar) + (calendar-goto-date date))) + +;;;###autoload +(defun org-calendar-goto-agenda () + "Compute the Org agenda for the calendar date displayed at the cursor. +This is a command that has to be installed in `calendar-mode-map'." + (interactive) + ;; Temporarily disable sticky agenda since user clearly wants to + ;; refresh view anyway. + (let ((org-agenda-buffer-tmp-name "*Org Agenda(a)*") + (org-agenda-sticky nil)) + (org-agenda-list nil (calendar-absolute-from-gregorian + (calendar-cursor-to-date)) + nil))) + +(defun org-agenda-convert-date () + (interactive) + (org-agenda-check-type t 'agenda) + (let ((day (get-text-property (min (1- (point-max)) (point)) 'day)) + date s) + (unless day + (user-error "Don't know which date to convert")) + (setq date (calendar-gregorian-from-absolute day)) + (setq s (concat + "Gregorian: " (calendar-date-string date) "\n" + "ISO: " (calendar-iso-date-string date) "\n" + "Day of Yr: " (calendar-day-of-year-string date) "\n" + "Julian: " (calendar-julian-date-string date) "\n" + "Astron. JD: " (calendar-astro-date-string date) + " (Julian date number at noon UTC)\n" + "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n" + "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n" + "French: " (calendar-french-date-string date) "\n" + "Bahá’í: " (calendar-bahai-date-string date) " (until sunset)\n" + "Mayan: " (calendar-mayan-date-string date) "\n" + "Coptic: " (calendar-coptic-date-string date) "\n" + "Ethiopic: " (calendar-ethiopic-date-string date) "\n" + "Persian: " (calendar-persian-date-string date) "\n" + "Chinese: " (calendar-chinese-date-string date) "\n")) + (with-output-to-temp-buffer "*Dates*" + (princ s)) + (org-fit-window-to-buffer (get-buffer-window "*Dates*")))) + +;;; Bulk commands + +(defun org-agenda-bulk-marked-p () + "Non-nil when current entry is marked for bulk action." + (eq (get-char-property (point-at-bol) 'type) + 'org-marked-entry-overlay)) + +(defun org-agenda-bulk-mark (&optional arg) + "Mark the entry at point for future bulk action." + (interactive "p") + (dotimes (i (or arg 1)) + (unless (org-get-at-bol 'org-agenda-diary-link) + (let* ((m (org-get-at-bol 'org-hd-marker)) + ov) + (unless (org-agenda-bulk-marked-p) + (unless m (user-error "Nothing to mark at point")) + (push m org-agenda-bulk-marked-entries) + (setq ov (make-overlay (point-at-bol) (+ 2 (point-at-bol)))) + (org-overlay-display ov (concat org-agenda-bulk-mark-char " ") + (org-get-todo-face "TODO") + 'evaporate) + (overlay-put ov 'type 'org-marked-entry-overlay)) + (end-of-line 1) + (or (ignore-errors + (goto-char (next-single-property-change (point) 'org-hd-marker))) + (beginning-of-line 2)) + (while (and (get-char-property (point) 'invisible) (not (eobp))) + (beginning-of-line 2)) + (message "%d entries marked for bulk action" + (length org-agenda-bulk-marked-entries)))))) + +(defun org-agenda-bulk-mark-all () + "Mark all entries for future agenda bulk action." + (interactive) + (org-agenda-bulk-mark-regexp ".")) + +(defun org-agenda-bulk-mark-regexp (regexp) + "Mark entries matching REGEXP for future agenda bulk action." + (interactive "sMark entries matching regexp: ") + (let ((entries-marked 0) txt-at-point) + (save-excursion + (goto-char (point-min)) + (goto-char (next-single-property-change (point) 'org-hd-marker)) + (while (and (re-search-forward regexp nil t) + (setq txt-at-point (get-text-property (point) 'txt))) + (if (get-char-property (point) 'invisible) + (beginning-of-line 2) + (when (string-match regexp txt-at-point) + (setq entries-marked (1+ entries-marked)) + (call-interactively 'org-agenda-bulk-mark))))) + + (if (not entries-marked) + (message "No entry matching this regexp.")))) + +(defun org-agenda-bulk-unmark (&optional arg) + "Unmark the entry at point for future bulk action." + (interactive "P") + (if arg + (org-agenda-bulk-unmark-all) + (cond ((org-agenda-bulk-marked-p) + (org-agenda-bulk-remove-overlays + (point-at-bol) (+ 2 (point-at-bol))) + (setq org-agenda-bulk-marked-entries + (delete (org-get-at-bol 'org-hd-marker) + org-agenda-bulk-marked-entries)) + (end-of-line 1) + (or (ignore-errors + (goto-char (next-single-property-change (point) 'txt))) + (beginning-of-line 2)) + (while (and (get-char-property (point) 'invisible) (not (eobp))) + (beginning-of-line 2)) + (message "%d entries left marked for bulk action" + (length org-agenda-bulk-marked-entries))) + (t (message "No entry to unmark here"))))) + +(defun org-agenda-bulk-toggle-all () + "Toggle all marks for bulk action." + (interactive) + (save-excursion + (goto-char (point-min)) + (while (ignore-errors + (goto-char (next-single-property-change (point) 'org-hd-marker))) + (org-agenda-bulk-toggle)))) + +(defun org-agenda-bulk-toggle () + "Toggle the mark at point for bulk action." + (interactive) + (if (org-agenda-bulk-marked-p) + (org-agenda-bulk-unmark) + (org-agenda-bulk-mark))) + +(defun org-agenda-bulk-remove-overlays (&optional beg end) + "Remove the mark overlays between BEG and END in the agenda buffer. +BEG and END default to the buffer limits. + +This only removes the overlays, it does not remove the markers +from the list in `org-agenda-bulk-marked-entries'." + (interactive) + (mapc (lambda (ov) + (and (eq (overlay-get ov 'type) 'org-marked-entry-overlay) + (delete-overlay ov))) + (overlays-in (or beg (point-min)) (or end (point-max))))) + +(defun org-agenda-bulk-unmark-all () + "Remove all marks in the agenda buffer. +This will remove the markers and the overlays." + (interactive) + (if (null org-agenda-bulk-marked-entries) + (message "No entry to unmark") + (setq org-agenda-bulk-marked-entries nil) + (org-agenda-bulk-remove-overlays (point-min) (point-max)))) + +(defcustom org-agenda-persistent-marks nil + "Non-nil means marked items will stay marked after a bulk action. +You can toggle this interactively by typing `p' when prompted for a +bulk action." + :group 'org-agenda + :version "24.1" + :type 'boolean) + +(defun org-agenda-bulk-action (&optional arg) + "Execute an remote-editing action on all marked entries. +The prefix arg is passed through to the command if possible." + (interactive "P") + ;; Make sure we have markers, and only valid ones. + (unless org-agenda-bulk-marked-entries (user-error "No entries are marked")) + (dolist (m org-agenda-bulk-marked-entries) + (unless (and (markerp m) + (marker-buffer m) + (buffer-live-p (marker-buffer m)) + (marker-position m)) + (user-error "Marker %s for bulk command is invalid" m))) + + ;; Prompt for the bulk command. + (message + (concat (if org-agenda-persistent-marks "Bulk (persistent): " "Bulk: ") + "[$]arch [A]rch->sib [t]odo [+/-]tag [s]chd [d]eadline [r]efile " + "[S]catter [f]unction " + (and org-agenda-bulk-custom-functions + (format " Custom: [%s]" + (mapconcat (lambda (f) (char-to-string (car f))) + org-agenda-bulk-custom-functions + ""))))) + (catch 'exit + (let* ((org-log-refile (if org-log-refile 'time nil)) + (entries (reverse org-agenda-bulk-marked-entries)) + (org-overriding-default-time + (and (get-text-property (point) 'org-agenda-date-header) + (org-get-cursor-date))) + redo-at-end + cmd) + (pcase (read-char-exclusive) + (?p + (let ((org-agenda-persistent-marks + (not org-agenda-persistent-marks))) + (org-agenda-bulk-action) + (throw 'exit nil))) + + (?$ + (setq cmd #'org-agenda-archive)) + + (?A + (setq cmd #'org-agenda-archive-to-archive-sibling)) + + ((or ?r ?w) + (let ((refile-location + (org-refile-get-location + "Refile to" + (marker-buffer (car entries)) + org-refile-allow-creating-parent-nodes))) + (when (nth 3 refile-location) + (setcar (nthcdr 3 refile-location) + (move-marker + (make-marker) + (nth 3 refile-location) + (or (get-file-buffer (nth 1 refile-location)) + (find-buffer-visiting (nth 1 refile-location)) + (error "This should not happen"))))) + + (setq cmd `(lambda () (org-agenda-refile nil ',refile-location t))) + (setq redo-at-end t))) + + (?t + (let ((state (completing-read + "Todo state: " + (with-current-buffer (marker-buffer (car entries)) + (mapcar #'list org-todo-keywords-1))))) + (setq cmd `(lambda () + (let ((org-inhibit-blocking t) + (org-inhibit-logging 'note)) + (org-agenda-todo ,state)))))) + + ((and (or ?- ?+) action) + (let ((tag (completing-read + (format "Tag to %s: " (if (eq action ?+) "add" "remove")) + (with-current-buffer (marker-buffer (car entries)) + (delq nil + (mapcar (lambda (x) (and (stringp (car x)) x)) + org-current-tag-alist)))))) + (setq cmd + `(lambda () + (org-agenda-set-tags ,tag + ,(if (eq action ?+) ''on ''off)))))) + + ((and (or ?s ?d) c) + (let* ((schedule? (eq c ?s)) + (prompt (if schedule? "(Re)Schedule to" "(Re)Set Deadline to")) + (time + (and (not arg) + (let ((new (org-read-date + nil nil nil prompt org-overriding-default-time))) + ;; A "double plus" answer applies to every + ;; scheduled time. Do not turn it into + ;; a fixed date yet. + (if (string-match-p "\\`[ \t]*\\+\\+" + org-read-date-final-answer) + org-read-date-final-answer + new))))) + ;; Make sure to not prompt for a note when bulk + ;; rescheduling/resetting deadline as Org cannot cope with + ;; simultaneous notes. Besides, it could be annoying + ;; depending on the number of marked items. + (setq cmd + (if schedule? + `(lambda () + (let ((org-log-reschedule + (and org-log-reschedule 'time))) + (org-agenda-schedule arg ,time))) + `(lambda () + (let ((org-log-redeadline (and org-log-redeadline 'time))) + (org-agenda-deadline arg ,time))))))) + + (?S + (unless (org-agenda-check-type nil 'agenda 'todo) + (user-error "Can't scatter tasks in \"%s\" agenda view" org-agenda-type)) + (let ((days (read-number + (format "Scatter tasks across how many %sdays: " + (if arg "week" "")) + 7))) + (setq cmd + `(lambda () + (let ((distance (1+ (random ,days)))) + (when arg + (let ((dist distance) + (day-of-week + (calendar-day-of-week + (calendar-gregorian-from-absolute (org-today))))) + (dotimes (i (1+ dist)) + (while (member day-of-week org-agenda-weekend-days) + (cl-incf distance) + (cl-incf day-of-week) + (when (= day-of-week 7) + (setq day-of-week 0))) + (cl-incf day-of-week) + (when (= day-of-week 7) + (setq day-of-week 0))))) + ;; Silently fail when try to replan a sexp entry. + (ignore-errors + (let* ((date (calendar-gregorian-from-absolute + (+ (org-today) distance))) + (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) + (nth 2 date)))) + (org-agenda-schedule nil time)))))))) + + (?f + (setq cmd + (intern + (completing-read "Function: " obarray #'fboundp t nil nil)))) + + (action + (pcase (assoc action org-agenda-bulk-custom-functions) + (`(,_ ,f) (setq cmd f) (setq redo-at-end t)) + (_ (user-error "Invalid bulk action: %c" action))))) + + ;; Sort the markers, to make sure that parents are handled + ;; before children. + (setq entries (sort entries + (lambda (a b) + (cond + ((eq (marker-buffer a) (marker-buffer b)) + (< (marker-position a) (marker-position b))) + (t + (string< (buffer-name (marker-buffer a)) + (buffer-name (marker-buffer b)))))))) + + ;; Now loop over all markers and apply CMD. + (let ((processed 0) + (skipped 0)) + (dolist (e entries) + (let ((pos (text-property-any (point-min) (point-max) 'org-hd-marker e))) + (if (not pos) + (progn (message "Skipping removed entry at %s" e) + (cl-incf skipped)) + (goto-char pos) + (let (org-loop-over-headlines-in-active-region) (funcall cmd)) + ;; `post-command-hook' is not run yet. We make sure any + ;; pending log note is processed. + (when (or (memq 'org-add-log-note (default-value 'post-command-hook)) + (memq 'org-add-log-note post-command-hook)) + (org-add-log-note)) + (cl-incf processed)))) + (when redo-at-end (org-agenda-redo)) + (unless org-agenda-persistent-marks (org-agenda-bulk-unmark-all)) + (message "Acted on %d entries%s%s" + processed + (if (= skipped 0) + "" + (format ", skipped %d (disappeared before their turn)" + skipped)) + (if (not org-agenda-persistent-marks) "" " (kept marked)")))))) + +(defun org-agenda-capture (&optional with-time) + "Call `org-capture' with the date at point. +With a `C-1' prefix, use the HH:MM value at point (if any) or the +current HH:MM time." + (interactive "P") + (if (not (eq major-mode 'org-agenda-mode)) + (user-error "You cannot do this outside of agenda buffers") + (let ((org-overriding-default-time + (org-get-cursor-date (equal with-time 1)))) + (call-interactively 'org-capture)))) + +;;; Dragging agenda lines forward/backward + +(defun org-agenda-reapply-filters () + "Re-apply all agenda filters." + (mapcar + (lambda(f) (when (car f) (org-agenda-filter-apply (car f) (cadr f) t))) + `((,org-agenda-tag-filter tag) + (,org-agenda-category-filter category) + (,org-agenda-regexp-filter regexp) + (,org-agenda-effort-filter effort) + (,(get 'org-agenda-tag-filter :preset-filter) tag) + (,(get 'org-agenda-category-filter :preset-filter) category) + (,(get 'org-agenda-effort-filter :preset-filter) effort) + (,(get 'org-agenda-regexp-filter :preset-filter) regexp)))) + +(defun org-agenda-drag-line-forward (arg &optional backward) + "Drag an agenda line forward by ARG lines. +When the optional argument `backward' is non-nil, move backward." + (interactive "p") + (let ((inhibit-read-only t) lst line) + (if (or (not (get-text-property (point) 'txt)) + (save-excursion + (dotimes (n arg) + (move-beginning-of-line (if backward 0 2)) + (push (not (get-text-property (point) 'txt)) lst)) + (delq nil lst))) + (message "Cannot move line forward") + (let ((end (save-excursion (move-beginning-of-line 2) (point)))) + (move-beginning-of-line 1) + (setq line (buffer-substring (point) end)) + (delete-region (point) end) + (move-beginning-of-line (funcall (if backward '1- '1+) arg)) + (insert line) + (org-agenda-reapply-filters) + (org-agenda-mark-clocking-task) + (move-beginning-of-line 0))))) + +(defun org-agenda-drag-line-backward (arg) + "Drag an agenda line backward by ARG lines." + (interactive "p") + (org-agenda-drag-line-forward arg t)) + +;;; Flagging notes + +(defun org-agenda-show-the-flagging-note () + "Display the flagging note in the other window. +When called a second time in direct sequence, offer to remove the FLAGGING +tag and (if present) the flagging note." + (interactive) + (let ((hdmarker (org-get-at-bol 'org-hd-marker)) + (win (selected-window)) + note heading newhead) + (unless hdmarker + (user-error "No linked entry at point")) + (if (and (eq this-command last-command) + (y-or-n-p "Unflag and remove any flagging note? ")) + (progn + (org-agenda-remove-flag hdmarker) + (let ((win (get-buffer-window "*Flagging Note*"))) + (and win (delete-window win))) + (message "Entry unflagged")) + (setq note (org-entry-get hdmarker "THEFLAGGINGNOTE")) + (unless note + (user-error "No flagging note")) + (org-kill-new note) + (org-switch-to-buffer-other-window "*Flagging Note*") + (erase-buffer) + (insert note) + (goto-char (point-min)) + (while (re-search-forward "\\\\n" nil t) + (replace-match "\n" t t)) + (goto-char (point-min)) + (select-window win) + (message "%s" (substitute-command-keys "Flagging note pushed to \ +kill ring. Press `\\[org-agenda-show-the-flagging-note]' again to remove \ +tag and note"))))) + +(defun org-agenda-remove-flag (marker) + "Remove the FLAGGED tag and any flagging note in the entry." + (let (newhead) + (org-with-point-at marker + (org-toggle-tag "FLAGGED" 'off) + (org-entry-delete nil "THEFLAGGINGNOTE") + (setq newhead (org-get-heading))) + (org-agenda-change-all-lines newhead marker) + (message "Entry unflagged"))) + +(defun org-agenda-get-any-marker (&optional pos) + (or (get-text-property (or pos (point-at-bol)) 'org-hd-marker) + (get-text-property (or pos (point-at-bol)) 'org-marker))) + +;;; Appointment reminders + +(defvar appt-time-msg-list) ; defined in appt.el + +;;;###autoload +(defun org-agenda-to-appt (&optional refresh filter &rest args) + "Activate appointments found in `org-agenda-files'. + +With a `\\[universal-argument]' prefix, refresh the list of \ +appointments. + +If FILTER is t, interactively prompt the user for a regular +expression, and filter out entries that don't match it. + +If FILTER is a string, use this string as a regular expression +for filtering entries out. + +If FILTER is a function, filter out entries against which +calling the function returns nil. This function takes one +argument: an entry from `org-agenda-get-day-entries'. + +FILTER can also be an alist with the car of each cell being +either `headline' or `category'. For example: + + \\='((headline \"IMPORTANT\") + (category \"Work\")) + +will only add headlines containing IMPORTANT or headlines +belonging to the \"Work\" category. + +ARGS are symbols indicating what kind of entries to consider. +By default `org-agenda-to-appt' will use :deadline*, :scheduled* +\(i.e., deadlines and scheduled items with a hh:mm specification) +and :timestamp entries. See the docstring of `org-diary' for +details and examples. + +If an entry has a APPT_WARNTIME property, its value will be used +to override `appt-message-warning-time'." + (interactive "P") + (if refresh (setq appt-time-msg-list nil)) + (if (eq filter t) + (setq filter (read-from-minibuffer "Regexp filter: "))) + (let* ((cnt 0) ; count added events + (scope (or args '(:deadline* :scheduled* :timestamp))) + (org-agenda-new-buffers nil) + (org-deadline-warning-days 0) + ;; Do not use `org-today' here because appt only takes + ;; time and without date as argument, so it may pass wrong + ;; information otherwise + (today (org-date-to-gregorian + (time-to-days (current-time)))) + (org-agenda-restrict nil) + (files (org-agenda-files 'unrestricted)) entries file + (org-agenda-buffer nil)) + ;; Get all entries which may contain an appt + (org-agenda-prepare-buffers files) + (while (setq file (pop files)) + (setq entries + (delq nil + (append entries + (apply 'org-agenda-get-day-entries + file today scope))))) + ;; Map thru entries and find if we should filter them out + (mapc + (lambda (x) + (let* ((evt (org-trim + (replace-regexp-in-string + org-bracket-link-regexp "\\3" + (or (get-text-property 1 'txt x) "")))) + (cat (get-text-property (1- (length x)) 'org-category x)) + (tod (get-text-property 1 'time-of-day x)) + (ok (or (null filter) + (and (stringp filter) (string-match filter evt)) + (and (functionp filter) (funcall filter x)) + (and (listp filter) + (let ((cat-filter (cadr (assq 'category filter))) + (evt-filter (cadr (assq 'headline filter)))) + (or (and (stringp cat-filter) + (string-match cat-filter cat)) + (and (stringp evt-filter) + (string-match evt-filter evt))))))) + (wrn (get-text-property 1 'warntime x))) + ;; FIXME: Shall we remove text-properties for the appt text? + ;; (setq evt (set-text-properties 0 (length evt) nil evt)) + (when (and ok tod (not (string-match "\\`DONE\\|CANCELLED" evt))) + (setq tod (concat "00" (number-to-string tod))) + (setq tod (when (string-match + "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)\\'" tod) + (concat (match-string 1 tod) ":" + (match-string 2 tod)))) + (when (appt-add tod evt wrn) + (setq cnt (1+ cnt)))))) + entries) + (org-release-buffers org-agenda-new-buffers) + (if (eq cnt 0) + (message "No event to add") + (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))) + +(defun org-agenda-today-p (date) + "Non nil when DATE means today. +DATE is either a list of the form (month day year) or a number of +days as returned by `calendar-absolute-from-gregorian' or +`org-today'. This function considers `org-extend-today-until' +when defining today." + (eq (org-today) + (if (consp date) (calendar-absolute-from-gregorian date) date))) + +(defun org-agenda-todo-yesterday (&optional arg) + "Like `org-agenda-todo' but the time of change will be 23:59 of yesterday." + (interactive "P") + (let* ((org-use-effective-time t) + (hour (nth 2 (decode-time (org-current-time)))) + (org-extend-today-until (1+ hour))) + (org-agenda-todo arg))) + +(provide 'org-agenda) + +;;; org-agenda.el ends here diff --git a/elpa/org-9.1.14/org-archive.el b/elpa/org-9.1.14/org-archive.el new file mode 100644 index 00000000..e020ec21 --- /dev/null +++ b/elpa/org-9.1.14/org-archive.el @@ -0,0 +1,618 @@ +;;; org-archive.el --- Archiving for Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file contains the face definitions for Org. + +;;; Code: + +(require 'org) + +(declare-function org-element-type "org-element" (element)) +(declare-function org-datetree-find-date-create "org-datetree" (date &optional keep-restriction)) +(declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ()) + +(defcustom org-archive-default-command 'org-archive-subtree + "The default archiving command." + :group 'org-archive + :type '(choice + (const org-archive-subtree) + (const org-archive-to-archive-sibling) + (const org-archive-set-tag))) + +(defcustom org-archive-reversed-order nil + "Non-nil means make the tree first child under the archive heading, not last." + :group 'org-archive + :version "24.1" + :type 'boolean) + +(defcustom org-archive-sibling-heading "Archive" + "Name of the local archive sibling that is used to archive entries locally. +Locally means: in the tree, under a sibling. +See `org-archive-to-archive-sibling' for more information." + :group 'org-archive + :type 'string) + +(defcustom org-archive-mark-done nil + "Non-nil means mark entries as DONE when they are moved to the archive file. +This can be a string to set the keyword to use. When non-nil, Org will +use the first keyword in its list that means done." + :group 'org-archive + :type '(choice + (const :tag "No" nil) + (const :tag "Yes" t) + (string :tag "Use this keyword"))) + +(defcustom org-archive-stamp-time t + "Non-nil means add a time stamp to entries moved to an archive file. +This variable is obsolete and has no effect anymore, instead add or remove +`time' from the variable `org-archive-save-context-info'." + :group 'org-archive + :type 'boolean) + +(defcustom org-archive-file-header-format "\nArchived entries from file %s\n\n" + "The header format string for newly created archive files. +When nil, no header will be inserted. +When a string, a %s formatter will be replaced by the file name." + :group 'org-archive + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-archive-subtree-add-inherited-tags 'infile + "Non-nil means append inherited tags when archiving a subtree." + :group 'org-archive + :version "24.1" + :type '(choice + (const :tag "Never" nil) + (const :tag "When archiving a subtree to the same file" infile) + (const :tag "Always" t))) + +(defcustom org-archive-save-context-info '(time file olpath category todo itags) + "Parts of context info that should be stored as properties when archiving. +When a subtree is moved to an archive file, it loses information given by +context, like inherited tags, the category, and possibly also the TODO +state (depending on the variable `org-archive-mark-done'). +This variable can be a list of any of the following symbols: + +time The time of archiving. +file The file where the entry originates. +ltags The local tags, in the headline of the subtree. +itags The tags the subtree inherits from further up the hierarchy. +todo The pre-archive TODO state. +category The category, taken from file name or #+CATEGORY lines. +olpath The outline path to the item. These are all headlines above + the current item, separated by /, like a file path. + +For each symbol present in the list, a property will be created in +the archived entry, with a prefix \"ARCHIVE_\", to remember this +information." + :group 'org-archive + :type '(set :greedy t + (const :tag "Time" time) + (const :tag "File" file) + (const :tag "Category" category) + (const :tag "TODO state" todo) + (const :tag "Priority" priority) + (const :tag "Inherited tags" itags) + (const :tag "Outline path" olpath) + (const :tag "Local tags" ltags))) + +(defvar org-archive-hook nil + "Hook run after successfully archiving a subtree. +Hook functions are called with point on the subtree in the +original file. At this stage, the subtree has been added to the +archive location, but not yet deleted from the original file.") + +(defun org-get-local-archive-location () + "Get the archive location applicable at point." + (let ((re "^[ \t]*#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$") + prop) + (save-excursion + (save-restriction + (widen) + (setq prop (org-entry-get nil "ARCHIVE" 'inherit)) + (cond + ((and prop (string-match "\\S-" prop)) + prop) + ((or (re-search-backward re nil t) + (re-search-forward re nil t)) + (match-string 1)) + (t org-archive-location)))))) + +;;;###autoload +(defun org-add-archive-files (files) + "Splice the archive files into the list of files. +This implies visiting all these files and finding out what the +archive file is." + (org-uniquify + (apply + 'append + (mapcar + (lambda (f) + (if (not (file-exists-p f)) + nil + (with-current-buffer (org-get-agenda-file-buffer f) + (cons f (org-all-archive-files))))) + files)))) + +(defun org-all-archive-files () + "Get a list of all archive files used in the current buffer." + (let ((case-fold-search t) + files) + (org-with-wide-buffer + (goto-char (point-min)) + (while (re-search-forward + "^[ \t]*\\(#\\+\\|:\\)ARCHIVE:[ \t]+\\(.*\\)" + nil t) + (when (save-match-data + (if (eq (match-string 1) ":") (org-at-property-p) + (eq (org-element-type (org-element-at-point)) 'keyword))) + (let ((file (org-extract-archive-file + (match-string-no-properties 2)))) + (when (and (org-string-nw-p file) (file-exists-p file)) + (push file files)))))) + (setq files (nreverse files)) + (let ((file (org-extract-archive-file))) + (when (and (org-string-nw-p file) (file-exists-p file)) + (push file files))) + files)) + +(defun org-extract-archive-file (&optional location) + "Extract and expand the file name from archive LOCATION. +if LOCATION is not given, the value of `org-archive-location' is used." + (setq location (or location org-archive-location)) + (if (string-match "\\(.*\\)::\\(.*\\)" location) + (if (= (match-beginning 1) (match-end 1)) + (buffer-file-name (buffer-base-buffer)) + (expand-file-name + (format (match-string 1 location) + (file-name-nondirectory + (buffer-file-name (buffer-base-buffer)))))))) + +(defun org-extract-archive-heading (&optional location) + "Extract the heading from archive LOCATION. +if LOCATION is not given, the value of `org-archive-location' is used." + (setq location (or location org-archive-location)) + (if (string-match "\\(.*\\)::\\(.*\\)" location) + (format (match-string 2 location) + (file-name-nondirectory + (buffer-file-name (buffer-base-buffer)))))) + +;;;###autoload +(defun org-archive-subtree (&optional find-done) + "Move the current subtree to the archive. +The archive can be a certain top-level heading in the current +file, or in a different file. The tree will be moved to that +location, the subtree heading be marked DONE, and the current +time will be added. + +When called with a single prefix argument FIND-DONE, find whole +trees without any open TODO items and archive them (after getting +confirmation from the user). When called with a double prefix +argument, find whole trees with timestamps before today and +archive them (after getting confirmation from the user). If the +cursor is not at a headline when these commands are called, try +all level 1 trees. If the cursor is on a headline, only try the +direct children of this heading." + (interactive "P") + (if (and (org-region-active-p) org-loop-over-headlines-in-active-region) + (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level) + 'region-start-level 'region)) + org-loop-over-headlines-in-active-region) + (org-map-entries + `(progn (setq org-map-continue-from (progn (org-back-to-heading) (point))) + (org-archive-subtree ,find-done)) + org-loop-over-headlines-in-active-region + cl (if (org-invisible-p) (org-end-of-subtree nil t)))) + (cond + ((equal find-done '(4)) (org-archive-all-done)) + ((equal find-done '(16)) (org-archive-all-old)) + (t + ;; Save all relevant TODO keyword-relatex variables + (let* ((tr-org-todo-keywords-1 org-todo-keywords-1) + (tr-org-todo-kwd-alist org-todo-kwd-alist) + (tr-org-done-keywords org-done-keywords) + (tr-org-todo-regexp org-todo-regexp) + (tr-org-todo-line-regexp org-todo-line-regexp) + (tr-org-odd-levels-only org-odd-levels-only) + (this-buffer (current-buffer)) + (time (format-time-string + (substring (cdr org-time-stamp-formats) 1 -1))) + (file (abbreviate-file-name + (or (buffer-file-name (buffer-base-buffer)) + (error "No file associated to buffer")))) + (location (org-get-local-archive-location)) + (afile (or (org-extract-archive-file location) + (error "Invalid `org-archive-location'"))) + (heading (org-extract-archive-heading location)) + (infile-p (equal file (abbreviate-file-name (or afile "")))) + (newfile-p (and (org-string-nw-p afile) + (not (file-exists-p afile)))) + (buffer (cond ((not (org-string-nw-p afile)) this-buffer) + ((find-buffer-visiting afile)) + ((find-file-noselect afile)) + (t (error "Cannot access file \"%s\"" afile)))) + level datetree-date datetree-subheading-p) + (when (string-match "\\`datetree/" heading) + ;; Replace with ***, to represent the 3 levels of headings the + ;; datetree has. + (setq heading (replace-regexp-in-string "\\`datetree/" "***" heading)) + (setq datetree-subheading-p (> (length heading) 3)) + (setq datetree-date (org-date-to-gregorian + (or (org-entry-get nil "CLOSED" t) time)))) + (if (and (> (length heading) 0) + (string-match "^\\*+" heading)) + (setq level (match-end 0)) + (setq heading nil level 0)) + (save-excursion + (org-back-to-heading t) + ;; Get context information that will be lost by moving the + ;; tree. See `org-archive-save-context-info'. + (let* ((all-tags (org-get-tags-at)) + (local-tags (org-get-tags)) + (inherited-tags (org-delete-all local-tags all-tags)) + (context + `((category . ,(org-get-category nil 'force-refresh)) + (file . ,file) + (itags . ,(mapconcat #'identity inherited-tags " ")) + (ltags . ,(mapconcat #'identity local-tags " ")) + (olpath . ,(mapconcat #'identity + (org-get-outline-path) + "/")) + (time . ,time) + (todo . ,(org-entry-get (point) "TODO"))))) + ;; We first only copy, in case something goes wrong + ;; we need to protect `this-command', to avoid kill-region sets it, + ;; which would lead to duplication of subtrees + (let (this-command) (org-copy-subtree 1 nil t)) + (set-buffer buffer) + ;; Enforce Org mode for the archive buffer + (if (not (derived-mode-p 'org-mode)) + ;; Force the mode for future visits. + (let ((org-insert-mode-line-in-empty-file t) + (org-inhibit-startup t)) + (call-interactively 'org-mode))) + (when (and newfile-p org-archive-file-header-format) + (goto-char (point-max)) + (insert (format org-archive-file-header-format + (buffer-file-name this-buffer)))) + (when datetree-date + (require 'org-datetree) + (org-datetree-find-date-create datetree-date) + (org-narrow-to-subtree)) + ;; Force the TODO keywords of the original buffer + (let ((org-todo-line-regexp tr-org-todo-line-regexp) + (org-todo-keywords-1 tr-org-todo-keywords-1) + (org-todo-kwd-alist tr-org-todo-kwd-alist) + (org-done-keywords tr-org-done-keywords) + (org-todo-regexp tr-org-todo-regexp) + (org-todo-line-regexp tr-org-todo-line-regexp) + (org-odd-levels-only + (if (local-variable-p 'org-odd-levels-only (current-buffer)) + org-odd-levels-only + tr-org-odd-levels-only))) + (goto-char (point-min)) + (outline-show-all) + (if (and heading (not (and datetree-date (not datetree-subheading-p)))) + (progn + (if (re-search-forward + (concat "^" (regexp-quote heading) + "[ \t]*\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\($\\|\r\\)") + nil t) + (goto-char (match-end 0)) + ;; Heading not found, just insert it at the end + (goto-char (point-max)) + (or (bolp) (insert "\n")) + ;; datetrees don't need too much spacing + (insert (if datetree-date "" "\n") heading "\n") + (end-of-line 0)) + ;; Make the subtree visible + (outline-show-subtree) + (if org-archive-reversed-order + (progn + (org-back-to-heading t) + (outline-next-heading)) + (org-end-of-subtree t)) + (skip-chars-backward " \t\r\n") + (and (looking-at "[ \t\r\n]*") + ;; datetree archives don't need so much spacing. + (replace-match (if datetree-date "\n" "\n\n")))) + ;; No specific heading, just go to end of file, or to the + ;; beginning, depending on `org-archive-reversed-order'. + (if org-archive-reversed-order + (progn + (goto-char (point-min)) + (unless (org-at-heading-p) (outline-next-heading)) + (insert "\n") (backward-char 1)) + (goto-char (point-max)) + ;; Subtree narrowing can let the buffer end on + ;; a headline. `org-paste-subtree' then deletes it. + ;; To prevent this, make sure visible part of buffer + ;; always terminates on a new line, while limiting + ;; number of blank lines in a date tree. + (unless (and datetree-date (bolp)) (insert "\n")))) + ;; Paste + (org-paste-subtree (org-get-valid-level level (and heading 1))) + ;; Shall we append inherited tags? + (and inherited-tags + (or (and (eq org-archive-subtree-add-inherited-tags 'infile) + infile-p) + (eq org-archive-subtree-add-inherited-tags t)) + (org-set-tags-to all-tags)) + ;; Mark the entry as done + (when (and org-archive-mark-done + (let ((case-fold-search nil)) + (looking-at org-todo-line-regexp)) + (or (not (match-end 2)) + (not (member (match-string 2) org-done-keywords)))) + (let (org-log-done org-todo-log-states) + (org-todo + (car (or (member org-archive-mark-done org-done-keywords) + org-done-keywords))))) + + ;; Add the context info. + (dolist (item org-archive-save-context-info) + (let ((value (cdr (assq item context)))) + (when (org-string-nw-p value) + (org-entry-put + (point) + (concat "ARCHIVE_" (upcase (symbol-name item))) + value)))) + (widen)))) + ;; Here we are back in the original buffer. Everything seems + ;; to have worked. So now run hooks, cut the tree and finish + ;; up. + (run-hooks 'org-archive-hook) + (let (this-command) (org-cut-subtree)) + (when (featurep 'org-inlinetask) + (org-inlinetask-remove-END-maybe)) + (setq org-markers-to-move nil) + (message "Subtree archived %s" + (if (eq this-buffer buffer) + (concat "under heading: " heading) + (concat "in file: " (abbreviate-file-name afile))))))) + (org-reveal) + (if (looking-at "^[ \t]*$") + (outline-next-visible-heading 1)))) + +;;;###autoload +(defun org-archive-to-archive-sibling () + "Archive the current heading by moving it under the archive sibling. + +The archive sibling is a sibling of the heading with the heading name +`org-archive-sibling-heading' and an `org-archive-tag' tag. If this +sibling does not exist, it will be created at the end of the subtree. + +Archiving time is retained in the ARCHIVE_TIME node property." + (interactive) + (if (and (org-region-active-p) org-loop-over-headlines-in-active-region) + (let ((cl (when (eq org-loop-over-headlines-in-active-region 'start-level) + 'region-start-level 'region)) + org-loop-over-headlines-in-active-region) + (org-map-entries + '(progn (setq org-map-continue-from + (progn (org-back-to-heading) + (if (looking-at (concat "^.*:" org-archive-tag ":.*$")) + (org-end-of-subtree t) + (point)))) + (when (org-at-heading-p) + (org-archive-to-archive-sibling))) + org-loop-over-headlines-in-active-region + cl (if (org-invisible-p) (org-end-of-subtree nil t)))) + (save-restriction + (widen) + (let (b e pos leader level) + (org-back-to-heading t) + (looking-at org-outline-regexp) + (setq leader (match-string 0) + level (funcall outline-level)) + (setq pos (point-marker)) + (condition-case nil + (outline-up-heading 1 t) + (error (setq e (point-max)) (goto-char (point-min)))) + (setq b (point)) + (unless e + (condition-case nil + (org-end-of-subtree t t) + (error (goto-char (point-max)))) + (setq e (point))) + (goto-char b) + (unless (re-search-forward + (concat "^" (regexp-quote leader) + "[ \t]*" + org-archive-sibling-heading + "[ \t]*:" + org-archive-tag ":") e t) + (goto-char e) + (or (bolp) (newline)) + (insert leader org-archive-sibling-heading "\n") + (beginning-of-line 0) + (org-toggle-tag org-archive-tag 'on)) + (beginning-of-line 1) + (if org-archive-reversed-order + (outline-next-heading) + (org-end-of-subtree t t)) + (save-excursion + (goto-char pos) + (let ((this-command this-command)) (org-cut-subtree))) + (org-paste-subtree (org-get-valid-level level 1)) + (org-set-property + "ARCHIVE_TIME" + (format-time-string + (substring (cdr org-time-stamp-formats) 1 -1))) + (outline-up-heading 1 t) + (outline-hide-subtree) + (org-cycle-show-empty-lines 'folded) + (goto-char pos))) + (org-reveal) + (if (looking-at "^[ \t]*$") + (outline-next-visible-heading 1)))) + +(defun org-archive-all-done (&optional tag) + "Archive sublevels of the current tree without open TODO items. +If the cursor is not on a headline, try all level 1 trees. If +it is on a headline, try all direct children. +When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag." + (org-archive-all-matches + (lambda (_beg end) + (let ((case-fold-search nil)) + (unless (re-search-forward org-not-done-heading-regexp end t) + "no open TODO items"))) + tag)) + +(defun org-archive-all-old (&optional tag) + "Archive sublevels of the current tree with timestamps prior to today. +If the cursor is not on a headline, try all level 1 trees. If +it is on a headline, try all direct children. +When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag." + (org-archive-all-matches + (lambda (_beg end) + (let (ts) + (and (re-search-forward org-ts-regexp end t) + (setq ts (match-string 0)) + (< (org-time-stamp-to-now ts) 0) + (if (not (looking-at + (concat "--\\(" org-ts-regexp "\\)"))) + (concat "old timestamp " ts) + (setq ts (concat "old timestamp " ts (match-string 0))) + (and (< (org-time-stamp-to-now (match-string 1)) 0) + ts))))) + tag)) + +(defun org-archive-all-matches (predicate &optional tag) + "Archive sublevels of the current tree that match PREDICATE. + +PREDICATE is a function of two arguments, BEG and END, which +specify the beginning and end of the headline being considered. +It is called with point positioned at BEG. The headline will be +archived if PREDICATE returns non-nil. If the return value of +PREDICATE is a string, it should describe the reason for +archiving the heading. + +If the cursor is not on a headline, try all level 1 trees. If it +is on a headline, try all direct children. When TAG is non-nil, +don't move trees, but mark them with the ARCHIVE tag." + (let ((rea (concat ".*:" org-archive-tag ":")) re1 + (begm (make-marker)) + (endm (make-marker)) + (question (if tag "Set ARCHIVE tag? " + "Move subtree to archive? ")) + reason beg end (cntarch 0)) + (if (org-at-heading-p) + (progn + (setq re1 (concat "^" (regexp-quote + (make-string + (+ (- (match-end 0) (match-beginning 0) 1) + (if org-odd-levels-only 2 1)) + ?*)) + " ")) + (move-marker begm (point)) + (move-marker endm (org-end-of-subtree t))) + (setq re1 "^* ") + (move-marker begm (point-min)) + (move-marker endm (point-max))) + (save-excursion + (goto-char begm) + (while (re-search-forward re1 endm t) + (setq beg (match-beginning 0) + end (save-excursion (org-end-of-subtree t) (point))) + (goto-char beg) + (if (not (setq reason (funcall predicate beg end))) + (goto-char end) + (goto-char beg) + (if (and (or (not tag) (not (looking-at rea))) + (y-or-n-p + (if (stringp reason) + (concat question "(" reason ")") + question))) + (progn + (if tag + (org-toggle-tag org-archive-tag 'on) + (org-archive-subtree)) + (setq cntarch (1+ cntarch))) + (goto-char end))))) + (message "%d trees archived" cntarch))) + +;;;###autoload +(defun org-toggle-archive-tag (&optional find-done) + "Toggle the archive tag for the current headline. +With prefix ARG, check all children of current headline and offer tagging +the children that do not contain any open TODO items." + (interactive "P") + (if (and (org-region-active-p) org-loop-over-headlines-in-active-region) + (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level) + 'region-start-level 'region)) + org-loop-over-headlines-in-active-region) + (org-map-entries + `(org-toggle-archive-tag ,find-done) + org-loop-over-headlines-in-active-region + cl (if (org-invisible-p) (org-end-of-subtree nil t)))) + (if find-done + (org-archive-all-done 'tag) + (let (set) + (save-excursion + (org-back-to-heading t) + (setq set (org-toggle-tag org-archive-tag)) + (when set (org-flag-subtree t))) + (and set (beginning-of-line 1)) + (message "Subtree %s" (if set "archived" "unarchived")))))) + +(defun org-archive-set-tag () + "Set the ARCHIVE tag." + (interactive) + (if (and (org-region-active-p) org-loop-over-headlines-in-active-region) + (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level) + 'region-start-level 'region)) + org-loop-over-headlines-in-active-region) + (org-map-entries + 'org-archive-set-tag + org-loop-over-headlines-in-active-region + cl (if (org-invisible-p) (org-end-of-subtree nil t)))) + (org-toggle-tag org-archive-tag 'on))) + +;;;###autoload +(defun org-archive-subtree-default () + "Archive the current subtree with the default command. +This command is set with the variable `org-archive-default-command'." + (interactive) + (call-interactively org-archive-default-command)) + +;;;###autoload +(defun org-archive-subtree-default-with-confirmation () + "Archive the current subtree with the default command. +This command is set with the variable `org-archive-default-command'." + (interactive) + (if (y-or-n-p "Archive this subtree or entry? ") + (call-interactively org-archive-default-command) + (error "Abort"))) + +(provide 'org-archive) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-archive.el ends here diff --git a/elpa/org-9.1.14/org-attach.el b/elpa/org-9.1.14/org-attach.el new file mode 100644 index 00000000..86516e27 --- /dev/null +++ b/elpa/org-9.1.14/org-attach.el @@ -0,0 +1,589 @@ +;;; org-attach.el --- Manage file attachments to Org tasks -*- lexical-binding: t; -*- + +;; Copyright (C) 2008-2018 Free Software Foundation, Inc. + +;; Author: John Wiegley +;; Keywords: org data task + +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; See the Org manual for information on how to use it. +;; +;; Attachments are managed in a special directory called "data", which +;; lives in the same directory as the org file itself. If this data +;; directory is initialized as a Git repository, then org-attach will +;; automatically commit changes when it sees them. +;; +;; Attachment directories are identified using a UUID generated for the +;; task which has the attachments. These are added as property to the +;; task when necessary, and should not be deleted or changed by the +;; user, ever. UUIDs are generated by a mechanism defined in the variable +;; `org-id-method'. + +;;; Code: + +(require 'cl-lib) +(require 'org) +(require 'org-id) +(require 'vc-git) + +(declare-function dired-dwim-target-directory "dired-aux") + +(defgroup org-attach nil + "Options concerning entry attachments in Org mode." + :tag "Org Attach" + :group 'org) + +(defcustom org-attach-directory "data/" + "The directory where attachments are stored. +If this is a relative path, it will be interpreted relative to the directory +where the Org file lives." + :group 'org-attach + :type 'directory) + +(defcustom org-attach-commit t + "If non-nil commit attachments with git. +This is only done if the Org file is in a git repository." + :group 'org-attach + :type 'boolean + :version "26.1" + :package-version '(Org . "9.0")) + +(defcustom org-attach-git-annex-cutoff (* 32 1024) + "If non-nil, files larger than this will be annexed instead of stored." + :group 'org-attach + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "None" nil) + (integer :tag "Bytes"))) + +(defcustom org-attach-auto-tag "ATTACH" + "Tag that will be triggered automatically when an entry has an attachment." + :group 'org-attach + :type '(choice + (const :tag "None" nil) + (string :tag "Tag"))) + +(defcustom org-attach-file-list-property "Attachments" + "The property used to keep a list of attachment belonging to this entry. +This is not really needed, so you may set this to nil if you don't want it. +Also, for entries where children inherit the directory, the list of +attachments is not kept in this property." + :group 'org-attach + :type '(choice + (const :tag "None" nil) + (string :tag "Tag"))) + +(defcustom org-attach-method 'cp + "The preferred method to attach a file. +Allowed values are: + +mv rename the file to move it into the attachment directory +cp copy the file +ln create a hard link. Note that this is not supported + on all systems, and then the result is not defined. +lns create a symbol link. Note that this is not supported + on all systems, and then the result is not defined." + :group 'org-attach + :type '(choice + (const :tag "Copy" cp) + (const :tag "Move/Rename" mv) + (const :tag "Hard Link" ln) + (const :tag "Symbol Link" lns))) + +(defcustom org-attach-expert nil + "Non-nil means do not show the splash buffer with the attach dispatcher." + :group 'org-attach + :type 'boolean) + +(defcustom org-attach-allow-inheritance t + "Non-nil means allow attachment directories be inherited." + :group 'org-attach + :type 'boolean) + +(defvar org-attach-inherited nil + "Indicates if the last access to the attachment directory was inherited.") + +(defcustom org-attach-store-link-p nil + "Non-nil means store a link to a file when attaching it." + :group 'org-attach + :version "24.1" + :type '(choice + (const :tag "Don't store link" nil) + (const :tag "Link to origin location" t) + (const :tag "Link to the attach-dir location" attached))) + +(defcustom org-attach-archive-delete nil + "Non-nil means attachments are deleted upon archiving a subtree. +When set to `query', ask the user instead." + :group 'org-attach + :version "26.1" + :package-version '(Org . "8.3") + :type '(choice + (const :tag "Never delete attachments" nil) + (const :tag "Always delete attachments" t) + (const :tag "Query the user" query))) + +(defcustom org-attach-annex-auto-get 'ask + "Confirmation preference for automatically getting annex files. +If \\='ask, prompt using `y-or-n-p'. If t, always get. If nil, never get." + :group 'org-attach + :package-version '(Org . "9.0") + :version "26.1" + :type '(choice + (const :tag "confirm with `y-or-n-p'" ask) + (const :tag "always get from annex if necessary" t) + (const :tag "never get from annex" nil))) + +;;;###autoload +(defun org-attach () + "The dispatcher for attachment commands. +Shows a list of commands and prompts for another key to execute a command." + (interactive) + (let (c marker) + (when (eq major-mode 'org-agenda-mode) + (setq marker (or (get-text-property (point) 'org-hd-marker) + (get-text-property (point) 'org-marker))) + (unless marker + (error "No task in current line"))) + (save-excursion + (when marker + (set-buffer (marker-buffer marker)) + (goto-char marker)) + (org-back-to-heading t) + (save-excursion + (save-window-excursion + (unless org-attach-expert + (with-output-to-temp-buffer "*Org Attach*" + (princ "Select an Attachment Command: + +a Select a file and attach it to the task, using `org-attach-method'. +c/m/l/y Attach a file using copy/move/link/symbolic-link method. +u Attach a file from URL (downloading it). +n Create a new attachment, as an Emacs buffer. +z Synchronize the current task with its attachment + directory, in case you added attachments yourself. + +o Open current task's attachments. +O Like \"o\", but force opening in Emacs. +f Open current task's attachment directory. +F Like \"f\", but force using dired in Emacs. + +d Delete one attachment, you will be prompted for a file name. +D Delete all of a task's attachments. A safer way is + to open the directory in dired and delete from there. + +s Set a specific attachment directory for this entry or reset to default. +i Make children of the current entry inherit its attachment directory."))) + (org-fit-window-to-buffer (get-buffer-window "*Org Attach*")) + (message "Select command: [acmlzoOfFdD]") + (setq c (read-char-exclusive)) + (and (get-buffer "*Org Attach*") (kill-buffer "*Org Attach*")))) + (cond + ((memq c '(?a ?\C-a)) (call-interactively 'org-attach-attach)) + ((memq c '(?c ?\C-c)) + (let ((org-attach-method 'cp)) (call-interactively 'org-attach-attach))) + ((memq c '(?m ?\C-m)) + (let ((org-attach-method 'mv)) (call-interactively 'org-attach-attach))) + ((memq c '(?l ?\C-l)) + (let ((org-attach-method 'ln)) (call-interactively 'org-attach-attach))) + ((memq c '(?y ?\C-y)) + (let ((org-attach-method 'lns)) (call-interactively 'org-attach-attach))) + ((memq c '(?u ?\C-u)) + (let ((org-attach-method 'url)) (call-interactively 'org-attach-url))) + ((memq c '(?n ?\C-n)) (call-interactively 'org-attach-new)) + ((memq c '(?z ?\C-z)) (call-interactively 'org-attach-sync)) + ((memq c '(?o ?\C-o)) (call-interactively 'org-attach-open)) + ((eq c ?O) (call-interactively 'org-attach-open-in-emacs)) + ((memq c '(?f ?\C-f)) (call-interactively 'org-attach-reveal)) + ((memq c '(?F)) (call-interactively 'org-attach-reveal-in-emacs)) + ((memq c '(?d ?\C-d)) (call-interactively + 'org-attach-delete-one)) + ((eq c ?D) (call-interactively 'org-attach-delete-all)) + ((eq c ?q) (message "Abort")) + ((memq c '(?s ?\C-s)) (call-interactively + 'org-attach-set-directory)) + ((memq c '(?i ?\C-i)) (call-interactively + 'org-attach-set-inherit)) + (t (error "No such attachment command %c" c)))))) + +(defun org-attach-dir (&optional create-if-not-exists-p) + "Return the directory associated with the current entry. +This first checks for a local property ATTACH_DIR, and then for an inherited +property ATTACH_DIR_INHERIT. If neither exists, the default mechanism +using the entry ID will be invoked to access the unique directory for the +current entry. +If the directory does not exist and CREATE-IF-NOT-EXISTS-P is non-nil, +the directory and (if necessary) the corresponding ID will be created." + (let (attach-dir uuid) + (setq org-attach-inherited (org-entry-get nil "ATTACH_DIR_INHERIT")) + (cond + ((setq attach-dir (org-entry-get nil "ATTACH_DIR")) + (org-attach-check-absolute-path attach-dir)) + ((and org-attach-allow-inheritance + (org-entry-get nil "ATTACH_DIR_INHERIT" t)) + (setq attach-dir + (org-with-wide-buffer + (if (marker-position org-entry-property-inherited-from) + (goto-char org-entry-property-inherited-from) + (org-back-to-heading t)) + (let (org-attach-allow-inheritance) + (org-attach-dir create-if-not-exists-p)))) + (org-attach-check-absolute-path attach-dir) + (setq org-attach-inherited t)) + (t ; use the ID + (org-attach-check-absolute-path nil) + (setq uuid (org-id-get (point) create-if-not-exists-p)) + (when (or uuid create-if-not-exists-p) + (unless uuid (error "ID retrieval/creation failed")) + (setq attach-dir (expand-file-name + (format "%s/%s" + (substring uuid 0 2) + (substring uuid 2)) + (expand-file-name org-attach-directory)))))) + (when attach-dir + (if (and create-if-not-exists-p + (not (file-directory-p attach-dir))) + (make-directory attach-dir t)) + (and (file-exists-p attach-dir) + attach-dir)))) + +(defun org-attach-check-absolute-path (dir) + "Check if we have enough information to root the attachment directory. +When DIR is given, check also if it is already absolute. Otherwise, +assume that it will be relative, and check if `org-attach-directory' is +absolute, or if at least the current buffer has a file name. +Throw an error if we cannot root the directory." + (or (and dir (file-name-absolute-p dir)) + (file-name-absolute-p org-attach-directory) + (buffer-file-name (buffer-base-buffer)) + (error "Need absolute `org-attach-directory' to attach in buffers without filename"))) + +(defun org-attach-set-directory (&optional arg) + "Set the ATTACH_DIR node property and ask to move files there. +The property defines the directory that is used for attachments +of the entry. When called with `\\[universal-argument]', reset \ +the directory to +the default ID based one." + (interactive "P") + (let ((old (org-attach-dir)) + (new + (progn + (if arg (org-entry-delete nil "ATTACH_DIR") + (let ((dir (read-directory-name + "Attachment directory: " + (org-entry-get nil + "ATTACH_DIR" + (and org-attach-allow-inheritance t))))) + (org-entry-put nil "ATTACH_DIR" dir))) + (org-attach-dir t)))) + (unless (or (string= old new) + (not old)) + (when (yes-or-no-p "Copy over attachments from old directory? ") + (copy-directory old new t nil t)) + (when (yes-or-no-p (concat "Delete " old)) + (delete-directory old t))))) + +(defun org-attach-set-inherit () + "Set the ATTACH_DIR_INHERIT property of the current entry. +The property defines the directory that is used for attachments +of the entry and any children that do not explicitly define (by setting +the ATTACH_DIR property) their own attachment directory." + (interactive) + (org-entry-put nil "ATTACH_DIR_INHERIT" "t") + (message "Children will inherit attachment directory")) + +(defun org-attach-use-annex () + "Return non-nil if git annex can be used." + (let ((git-dir (vc-git-root (expand-file-name org-attach-directory)))) + (and org-attach-git-annex-cutoff + (or (file-exists-p (expand-file-name "annex" git-dir)) + (file-exists-p (expand-file-name ".git/annex" git-dir)))))) + +(defun org-attach-annex-get-maybe (path) + "Call git annex get PATH (via shell) if using git annex. +Signals an error if the file content is not available and it was not retrieved." + (let* ((default-directory (expand-file-name org-attach-directory)) + (path-relative (file-relative-name path))) + (when (and (org-attach-use-annex) + (not + (string-equal + "found" + (shell-command-to-string + (format "git annex find --format=found --in=here %s" + (shell-quote-argument path-relative)))))) + (let ((should-get + (if (eq org-attach-annex-auto-get 'ask) + (y-or-n-p (format "Run git annex get %s? " path-relative)) + org-attach-annex-auto-get))) + (if should-get + (progn (message "Running git annex get \"%s\"." path-relative) + (call-process "git" nil nil nil "annex" "get" path-relative)) + (error "File %s stored in git annex but it is not available, and was not retrieved" + path)))))) + +(defun org-attach-commit () + "Commit changes to git if `org-attach-directory' is properly initialized. +This checks for the existence of a \".git\" directory in that directory." + (let* ((dir (expand-file-name org-attach-directory)) + (git-dir (vc-git-root dir)) + (use-annex (org-attach-use-annex)) + (changes 0)) + (when (and git-dir (executable-find "git")) + (with-temp-buffer + (cd dir) + (dolist (new-or-modified + (split-string + (shell-command-to-string + "git ls-files -zmo --exclude-standard") "\0" t)) + (if (and use-annex + (>= (nth 7 (file-attributes new-or-modified)) + org-attach-git-annex-cutoff)) + (call-process "git" nil nil nil "annex" "add" new-or-modified) + (call-process "git" nil nil nil "add" new-or-modified)) + (cl-incf changes)) + (dolist (deleted + (split-string + (shell-command-to-string "git ls-files -z --deleted") "\0" t)) + (call-process "git" nil nil nil "rm" deleted) + (cl-incf changes)) + (when (> changes 0) + (shell-command "git commit -m 'Synchronized attachments'")))))) + +(defun org-attach-tag (&optional off) + "Turn the autotag on or (if OFF is set) off." + (when org-attach-auto-tag + (save-excursion + (org-back-to-heading t) + (org-toggle-tag org-attach-auto-tag (if off 'off 'on))))) + +(defun org-attach-untag () + "Turn the autotag off." + (org-attach-tag 'off)) + +(defun org-attach-store-link (file) + "Add a link to `org-stored-link' when attaching a file. +Only do this when `org-attach-store-link-p' is non-nil." + (setq org-stored-links + (cons (list (org-attach-expand-link file) + (file-name-nondirectory file)) + org-stored-links))) + +(defun org-attach-url (url) + (interactive "MURL of the file to attach: \n") + (org-attach-attach url)) + +(defun org-attach-attach (file &optional visit-dir method) + "Move/copy/link FILE into the attachment directory of the current task. +If VISIT-DIR is non-nil, visit the directory with dired. +METHOD may be `cp', `mv', `ln', `lns' or `url' default taken from +`org-attach-method'." + (interactive + (list + (read-file-name "File to keep as an attachment:" + (or (progn + (require 'dired-aux) + (dired-dwim-target-directory)) + default-directory)) + current-prefix-arg + nil)) + (setq method (or method org-attach-method)) + (let ((basename (file-name-nondirectory file))) + (when (and org-attach-file-list-property (not org-attach-inherited)) + (org-entry-add-to-multivalued-property + (point) org-attach-file-list-property basename)) + (let* ((attach-dir (org-attach-dir t)) + (fname (expand-file-name basename attach-dir))) + (cond + ((eq method 'mv) (rename-file file fname)) + ((eq method 'cp) (copy-file file fname)) + ((eq method 'ln) (add-name-to-file file fname)) + ((eq method 'lns) (make-symbolic-link file fname)) + ((eq method 'url) (url-copy-file file fname))) + (when org-attach-commit + (org-attach-commit)) + (org-attach-tag) + (cond ((eq org-attach-store-link-p 'attached) + (org-attach-store-link fname)) + ((eq org-attach-store-link-p t) + (org-attach-store-link file))) + (if visit-dir + (dired attach-dir) + (message "File %S is now a task attachment." basename))))) + +(defun org-attach-attach-cp () + "Attach a file by copying it." + (interactive) + (let ((org-attach-method 'cp)) (call-interactively 'org-attach-attach))) +(defun org-attach-attach-mv () + "Attach a file by moving (renaming) it." + (interactive) + (let ((org-attach-method 'mv)) (call-interactively 'org-attach-attach))) +(defun org-attach-attach-ln () + "Attach a file by creating a hard link to it. +Beware that this does not work on systems that do not support hard links. +On some systems, this apparently does copy the file instead." + (interactive) + (let ((org-attach-method 'ln)) (call-interactively 'org-attach-attach))) +(defun org-attach-attach-lns () + "Attach a file by creating a symbolic link to it. + +Beware that this does not work on systems that do not support symbolic links. +On some systems, this apparently does copy the file instead." + (interactive) + (let ((org-attach-method 'lns)) (call-interactively 'org-attach-attach))) + +(defun org-attach-new (file) + "Create a new attachment FILE for the current task. +The attachment is created as an Emacs buffer." + (interactive "sCreate attachment named: ") + (when (and org-attach-file-list-property (not org-attach-inherited)) + (org-entry-add-to-multivalued-property + (point) org-attach-file-list-property file)) + (let ((attach-dir (org-attach-dir t))) + (org-attach-tag) + (find-file (expand-file-name file attach-dir)) + (message "New attachment %s" file))) + +(defun org-attach-delete-one (&optional file) + "Delete a single attachment." + (interactive) + (let* ((attach-dir (org-attach-dir t)) + (files (org-attach-file-list attach-dir)) + (file (or file + (completing-read + "Delete attachment: " + (mapcar (lambda (f) + (list (file-name-nondirectory f))) + files))))) + (setq file (expand-file-name file attach-dir)) + (unless (file-exists-p file) + (error "No such attachment: %s" file)) + (delete-file file) + (when org-attach-commit + (org-attach-commit)))) + +(defun org-attach-delete-all (&optional force) + "Delete all attachments from the current task. +This actually deletes the entire attachment directory. +A safer way is to open the directory in dired and delete from there." + (interactive "P") + (when (and org-attach-file-list-property (not org-attach-inherited)) + (org-entry-delete (point) org-attach-file-list-property)) + (let ((attach-dir (org-attach-dir))) + (when + (and attach-dir + (or force + (y-or-n-p "Are you sure you want to remove all attachments of this entry? "))) + (shell-command (format "rm -fr %s" attach-dir)) + (message "Attachment directory removed") + (when org-attach-commit + (org-attach-commit)) + (org-attach-untag)))) + +(defun org-attach-sync () + "Synchronize the current tasks with its attachments. +This can be used after files have been added externally." + (interactive) + (when org-attach-commit + (org-attach-commit)) + (when (and org-attach-file-list-property (not org-attach-inherited)) + (org-entry-delete (point) org-attach-file-list-property)) + (let ((attach-dir (org-attach-dir))) + (when attach-dir + (let ((files (org-attach-file-list attach-dir))) + (org-attach-tag (not files)) + (when org-attach-file-list-property + (dolist (file files) + (unless (string-match "^\\.\\.?\\'" file) + (org-entry-add-to-multivalued-property + (point) org-attach-file-list-property file)))))))) + +(defun org-attach-file-list (dir) + "Return a list of files in the attachment directory. +This ignores files ending in \"~\"." + (delq nil + (mapcar (lambda (x) (if (string-match "^\\.\\.?\\'" x) nil x)) + (directory-files dir nil "[^~]\\'")))) + +(defun org-attach-reveal (&optional if-exists) + "Show the attachment directory of the current task. +This will attempt to use an external program to show the directory." + (interactive "P") + (let ((attach-dir (org-attach-dir (not if-exists)))) + (and attach-dir (org-open-file attach-dir)))) + +(defun org-attach-reveal-in-emacs () + "Show the attachment directory of the current task in dired." + (interactive) + (let ((attach-dir (org-attach-dir t))) + (dired attach-dir))) + +(defun org-attach-open (&optional in-emacs) + "Open an attachment of the current task. +If there are more than one attachment, you will be prompted for the file name. +This command will open the file using the settings in `org-file-apps' +and in the system-specific variants of this variable. +If IN-EMACS is non-nil, force opening in Emacs." + (interactive "P") + (let* ((attach-dir (org-attach-dir t)) + (files (org-attach-file-list attach-dir)) + (file (if (= (length files) 1) + (car files) + (completing-read "Open attachment: " + (mapcar #'list files) nil t))) + (path (expand-file-name file attach-dir))) + (org-attach-annex-get-maybe path) + (org-open-file path in-emacs))) + +(defun org-attach-open-in-emacs () + "Open attachment, force opening in Emacs. +See `org-attach-open'." + (interactive) + (org-attach-open 'in-emacs)) + +(defun org-attach-expand (file) + "Return the full path to the current entry's attachment file FILE. +Basically, this adds the path to the attachment directory." + (expand-file-name file (org-attach-dir))) + +(defun org-attach-expand-link (file) + "Return a file link pointing to the current entry's attachment file FILE. +Basically, this adds the path to the attachment directory, and a \"file:\" +prefix." + (concat "file:" (org-attach-expand file))) + +(defun org-attach-archive-delete-maybe () + "Maybe delete subtree attachments when archiving. +This function is called by `org-archive-hook'. The option +`org-attach-archive-delete' controls its behavior." + (when (if (eq org-attach-archive-delete 'query) + (yes-or-no-p "Delete all attachments? ") + org-attach-archive-delete) + (org-attach-delete-all t))) + +(add-hook 'org-archive-hook 'org-attach-archive-delete-maybe) + +(provide 'org-attach) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-attach.el ends here diff --git a/elpa/org-9.1.14/org-autoloads.el b/elpa/org-9.1.14/org-autoloads.el new file mode 100644 index 00000000..caa8e04c --- /dev/null +++ b/elpa/org-9.1.14/org-autoloads.el @@ -0,0 +1,1543 @@ +;;; org-autoloads.el --- automatically extracted autoloads +;; +;;; Code: + +(add-to-list 'load-path (directory-file-name + (or (file-name-directory #$) (car load-path)))) + + +;;;### (autoloads nil "ob-C" "ob-C.el" (0 0 0 0)) +;;; Generated autoloads from ob-C.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-C" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-J" "ob-J.el" (0 0 0 0)) +;;; Generated autoloads from ob-J.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-J" '("obj-" "org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-R" "ob-R.el" (0 0 0 0)) +;;; Generated autoloads from ob-R.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-R" '("ob-R-" "org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-abc" "ob-abc.el" (0 0 0 0)) +;;; Generated autoloads from ob-abc.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-abc" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-asymptote" "ob-asymptote.el" (0 0 0 0)) +;;; Generated autoloads from ob-asymptote.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-asymptote" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-awk" "ob-awk.el" (0 0 0 0)) +;;; Generated autoloads from ob-awk.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-awk" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-calc" "ob-calc.el" (0 0 0 0)) +;;; Generated autoloads from ob-calc.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-calc" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-clojure" "ob-clojure.el" (0 0 0 0)) +;;; Generated autoloads from ob-clojure.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-clojure" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-comint" "ob-comint.el" (0 0 0 0)) +;;; Generated autoloads from ob-comint.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-comint" '("org-babel-comint-"))) + +;;;*** + +;;;### (autoloads nil "ob-coq" "ob-coq.el" (0 0 0 0)) +;;; Generated autoloads from ob-coq.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-coq" '("org-babel-" "coq-program-name"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ob-core" "ob-core.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ob-core.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-core" '("org-"))) + +;;;*** + +;;;### (autoloads nil "ob-css" "ob-css.el" (0 0 0 0)) +;;; Generated autoloads from ob-css.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-css" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-ditaa" "ob-ditaa.el" (0 0 0 0)) +;;; Generated autoloads from ob-ditaa.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ditaa" '("org-"))) + +;;;*** + +;;;### (autoloads nil "ob-dot" "ob-dot.el" (0 0 0 0)) +;;; Generated autoloads from ob-dot.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-dot" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-ebnf" "ob-ebnf.el" (0 0 0 0)) +;;; Generated autoloads from ob-ebnf.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ebnf" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-emacs-lisp" "ob-emacs-lisp.el" (0 0 0 0)) +;;; Generated autoloads from ob-emacs-lisp.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-emacs-lisp" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-eval" "ob-eval.el" (0 0 0 0)) +;;; Generated autoloads from ob-eval.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-eval" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-exp" "ob-exp.el" (0 0 0 0)) +;;; Generated autoloads from ob-exp.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-exp" '("org-"))) + +;;;*** + +;;;### (autoloads nil "ob-forth" "ob-forth.el" (0 0 0 0)) +;;; Generated autoloads from ob-forth.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-forth" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-fortran" "ob-fortran.el" (0 0 0 0)) +;;; Generated autoloads from ob-fortran.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-fortran" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-gnuplot" "ob-gnuplot.el" (0 0 0 0)) +;;; Generated autoloads from ob-gnuplot.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-gnuplot" '("org-babel-" "*org-babel-gnuplot-"))) + +;;;*** + +;;;### (autoloads nil "ob-groovy" "ob-groovy.el" (0 0 0 0)) +;;; Generated autoloads from ob-groovy.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-groovy" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-haskell" "ob-haskell.el" (0 0 0 0)) +;;; Generated autoloads from ob-haskell.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-haskell" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-hledger" "ob-hledger.el" (0 0 0 0)) +;;; Generated autoloads from ob-hledger.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-hledger" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-io" "ob-io.el" (0 0 0 0)) +;;; Generated autoloads from ob-io.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-io" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-java" "ob-java.el" (0 0 0 0)) +;;; Generated autoloads from ob-java.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-java" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-js" "ob-js.el" (0 0 0 0)) +;;; Generated autoloads from ob-js.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-js" '("org-babel-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ob-keys" "ob-keys.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ob-keys.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-keys" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-latex" "ob-latex.el" (0 0 0 0)) +;;; Generated autoloads from ob-latex.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-latex" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-ledger" "ob-ledger.el" (0 0 0 0)) +;;; Generated autoloads from ob-ledger.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ledger" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-lilypond" "ob-lilypond.el" (0 0 0 0)) +;;; Generated autoloads from ob-lilypond.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-lilypond" '("org-babel-" "lilypond-mode"))) + +;;;*** + +;;;### (autoloads nil "ob-lisp" "ob-lisp.el" (0 0 0 0)) +;;; Generated autoloads from ob-lisp.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-lisp" '("org-babel-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ob-lob" "ob-lob.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ob-lob.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-lob" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-lua" "ob-lua.el" (0 0 0 0)) +;;; Generated autoloads from ob-lua.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-lua" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-makefile" "ob-makefile.el" (0 0 0 0)) +;;; Generated autoloads from ob-makefile.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-makefile" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-maxima" "ob-maxima.el" (0 0 0 0)) +;;; Generated autoloads from ob-maxima.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-maxima" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-mscgen" "ob-mscgen.el" (0 0 0 0)) +;;; Generated autoloads from ob-mscgen.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-mscgen" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-ocaml" "ob-ocaml.el" (0 0 0 0)) +;;; Generated autoloads from ob-ocaml.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ocaml" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-octave" "ob-octave.el" (0 0 0 0)) +;;; Generated autoloads from ob-octave.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-octave" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-org" "ob-org.el" (0 0 0 0)) +;;; Generated autoloads from ob-org.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-org" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-perl" "ob-perl.el" (0 0 0 0)) +;;; Generated autoloads from ob-perl.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-perl" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-picolisp" "ob-picolisp.el" (0 0 0 0)) +;;; Generated autoloads from ob-picolisp.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-picolisp" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-plantuml" "ob-plantuml.el" (0 0 0 0)) +;;; Generated autoloads from ob-plantuml.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-plantuml" '("org-"))) + +;;;*** + +;;;### (autoloads nil "ob-processing" "ob-processing.el" (0 0 0 0)) +;;; Generated autoloads from ob-processing.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-processing" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-python" "ob-python.el" (0 0 0 0)) +;;; Generated autoloads from ob-python.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-python" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-ref" "ob-ref.el" (0 0 0 0)) +;;; Generated autoloads from ob-ref.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ref" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-ruby" "ob-ruby.el" (0 0 0 0)) +;;; Generated autoloads from ob-ruby.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-ruby" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-sass" "ob-sass.el" (0 0 0 0)) +;;; Generated autoloads from ob-sass.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-sass" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-scheme" "ob-scheme.el" (0 0 0 0)) +;;; Generated autoloads from ob-scheme.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-scheme" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-screen" "ob-screen.el" (0 0 0 0)) +;;; Generated autoloads from ob-screen.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-screen" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-sed" "ob-sed.el" (0 0 0 0)) +;;; Generated autoloads from ob-sed.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-sed" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-shell" "ob-shell.el" (0 0 0 0)) +;;; Generated autoloads from ob-shell.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-shell" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-shen" "ob-shen.el" (0 0 0 0)) +;;; Generated autoloads from ob-shen.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-shen" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-sql" "ob-sql.el" (0 0 0 0)) +;;; Generated autoloads from ob-sql.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-sql" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-sqlite" "ob-sqlite.el" (0 0 0 0)) +;;; Generated autoloads from ob-sqlite.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-sqlite" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-stan" "ob-stan.el" (0 0 0 0)) +;;; Generated autoloads from ob-stan.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-stan" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-table" "ob-table.el" (0 0 0 0)) +;;; Generated autoloads from ob-table.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-table" '("org-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ob-tangle" "ob-tangle.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ob-tangle.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-tangle" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "ob-vala" "ob-vala.el" (0 0 0 0)) +;;; Generated autoloads from ob-vala.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ob-vala" '("org-babel-"))) + +;;;*** + +;;;### (autoloads nil "org" "org.el" (0 0 0 0)) +;;; Generated autoloads from org.el + +(autoload 'org-babel-do-load-languages "org" "\ +Load the languages defined in `org-babel-load-languages'. + +\(fn SYM VALUE)" nil nil) + +(autoload 'org-babel-load-file "org" "\ +Load Emacs Lisp source code blocks in the Org FILE. +This function exports the source code using `org-babel-tangle' +and then loads the resulting file using `load-file'. With prefix +arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp +file to byte-code before it is loaded. + +\(fn FILE &optional COMPILE)" t nil) + +(autoload 'org-version "org" "\ +Show the Org version. +Interactively, or when MESSAGE is non-nil, show it in echo area. +With prefix argument, or when HERE is non-nil, insert it at point. +In non-interactive uses, a reduced version string is output unless +FULL is given. + +\(fn &optional HERE FULL MESSAGE)" t nil) + +(autoload 'turn-on-orgtbl "org" "\ +Unconditionally turn on `orgtbl-mode'. + +\(fn)" nil nil) + +(autoload 'org-clock-persistence-insinuate "org" "\ +Set up hooks for clock persistence. + +\(fn)" nil nil) + +(autoload 'org-mode "org" "\ +Outline-based notes management and organizer, alias +\"Carsten's outline-mode for keeping track of everything.\" + +Org mode develops organizational tasks around a NOTES file which +contains information about projects as plain text. Org mode is +implemented on top of Outline mode, which is ideal to keep the content +of large files well structured. It supports ToDo items, deadlines and +time stamps, which magically appear in the diary listing of the Emacs +calendar. Tables are easily created with a built-in table editor. +Plain text URL-like links connect to websites, emails (VM), Usenet +messages (Gnus), BBDB entries, and any files related to the project. +For printing and sharing of notes, an Org file (or a part of it) +can be exported as a structured ASCII or HTML file. + +The following commands are available: + +\\{org-mode-map} + +\(fn)" t nil) + +(autoload 'org-cycle "org" "\ +TAB-action and visibility cycling for Org mode. + +This is the command invoked in Org mode by the `TAB' key. Its main +purpose is outline visibility cycling, but it also invokes other actions +in special contexts. + +When this function is called with a `\\[universal-argument]' prefix, rotate the entire +buffer through 3 states (global cycling) + 1. OVERVIEW: Show only top-level headlines. + 2. CONTENTS: Show all headlines of all levels, but no body text. + 3. SHOW ALL: Show everything. + +With a `\\[universal-argument] \\[universal-argument]' prefix argument, switch to the startup visibility, +determined by the variable `org-startup-folded', and by any VISIBILITY +properties in the buffer. + +With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' prefix argument, show the entire buffer, including +any drawers. + +When inside a table, re-align the table and move to the next field. + +When point is at the beginning of a headline, rotate the subtree started +by this line through 3 different states (local cycling) + 1. FOLDED: Only the main headline is shown. + 2. CHILDREN: The main headline and the direct children are shown. + From this state, you can move to one of the children + and zoom in further. + 3. SUBTREE: Show the entire subtree, including body text. +If there is no subtree, switch directly from CHILDREN to FOLDED. + +When point is at the beginning of an empty headline and the variable +`org-cycle-level-after-item/entry-creation' is set, cycle the level +of the headline by demoting and promoting it to likely levels. This +speeds up creation document structure by pressing `TAB' once or several +times right after creating a new headline. + +When there is a numeric prefix, go up to a heading with level ARG, do +a `show-subtree' and return to the previous cursor position. If ARG +is negative, go up that many levels. + +When point is not at the beginning of a headline, execute the global +binding for `TAB', which is re-indenting the line. See the option +`org-cycle-emulate-tab' for details. + +As a special case, if point is at the beginning of the buffer and there is +no headline in line 1, this function will act as if called with prefix arg +\(`\\[universal-argument] TAB', same as `S-TAB') also when called without prefix arg, but only +if the variable `org-cycle-global-at-bob' is t. + +\(fn &optional ARG)" t nil) + +(autoload 'org-global-cycle "org" "\ +Cycle the global visibility. For details see `org-cycle'. +With `\\[universal-argument]' prefix ARG, switch to startup visibility. +With a numeric prefix, show all headlines up to that level. + +\(fn &optional ARG)" t nil) +(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp) + +(autoload 'orgstruct-mode "org" "\ +Toggle the minor mode `orgstruct-mode'. +This mode is for using Org mode structure commands in other +modes. The following keys behave as if Org mode were active, if +the cursor is on a headline, or on a plain list item (both as +defined by Org mode). + +\(fn &optional ARG)" t nil) + +(autoload 'turn-on-orgstruct "org" "\ +Unconditionally turn on `orgstruct-mode'. + +\(fn)" nil nil) + +(autoload 'turn-on-orgstruct++ "org" "\ +Unconditionally turn on `orgstruct++-mode'. + +\(fn)" nil nil) + +(autoload 'org-run-like-in-org-mode "org" "\ +Run a command, pretending that the current buffer is in Org mode. +This will temporarily bind local variables that are typically bound in +Org mode to the values they have in Org mode, and then interactively +call CMD. + +\(fn CMD)" nil nil) + +(autoload 'org-store-link "org" "\ +Store an org-link to the current location. +\\ +This link is added to `org-stored-links' and can later be inserted +into an Org buffer with `org-insert-link' (`\\[org-insert-link]'). + +For some link types, a `\\[universal-argument]' prefix ARG is interpreted. A single +`\\[universal-argument]' negates `org-context-in-file-links' for file links or +`org-gnus-prefer-web-links' for links to Usenet articles. + +A `\\[universal-argument] \\[universal-argument]' prefix ARG forces skipping storing functions that are not +part of Org core. + +A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' prefix ARG forces storing a link for each line in the +active region. + +\(fn ARG)" t nil) + +(autoload 'org-insert-link-global "org" "\ +Insert a link like Org mode does. +This command can be called in any mode to insert a link in Org syntax. + +\(fn)" t nil) + +(autoload 'org-open-at-point-global "org" "\ +Follow a link or time-stamp like Org mode does. +This command can be called in any mode to follow an external link +or a time-stamp that has Org mode syntax. Its behavior is +undefined when called on internal links (e.g., fuzzy links). +Raise an error when there is nothing to follow. + +\(fn)" t nil) + +(autoload 'org-open-link-from-string "org" "\ +Open a link in the string S, as if it was in Org mode. + +\(fn S &optional ARG REFERENCE-BUFFER)" t nil) + +(autoload 'org-switchb "org" "\ +Switch between Org buffers. + +With `\\[universal-argument]' prefix, restrict available buffers to files. + +With `\\[universal-argument] \\[universal-argument]' prefix, restrict available buffers to agenda files. + +\(fn &optional ARG)" t nil) + +(autoload 'org-cycle-agenda-files "org" "\ +Cycle through the files in `org-agenda-files'. +If the current buffer visits an agenda file, find the next one in the list. +If the current buffer does not, find the first agenda file. + +\(fn)" t nil) + +(autoload 'org-submit-bug-report "org" "\ +Submit a bug report on Org via mail. + +Don't hesitate to report any problems or inaccurate documentation. + +If you don't have setup sending mail from (X)Emacs, please copy the +output buffer into your mail program, as it gives us important +information about your Org version and configuration. + +\(fn)" t nil) + +(autoload 'org-reload "org" "\ +Reload all Org Lisp files. +With prefix arg UNCOMPILED, load the uncompiled versions. + +\(fn &optional UNCOMPILED)" t nil) + +(autoload 'org-customize "org" "\ +Call the customize function with org as argument. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org" '("org" "turn-on-org-cdlatex"))) + +;;;*** + +;;;### (autoloads nil "org-agenda" "org-agenda.el" (0 0 0 0)) +;;; Generated autoloads from org-agenda.el + +(autoload 'org-toggle-sticky-agenda "org-agenda" "\ +Toggle `org-agenda-sticky'. + +\(fn &optional ARG)" t nil) + +(autoload 'org-agenda "org-agenda" "\ +Dispatch agenda commands to collect entries to the agenda buffer. +Prompts for a command to execute. Any prefix arg will be passed +on to the selected command. The default selections are: + +a Call `org-agenda-list' to display the agenda for current day or week. +t Call `org-todo-list' to display the global todo list. +T Call `org-todo-list' to display the global todo list, select only + entries with a specific TODO keyword (the user gets a prompt). +m Call `org-tags-view' to display headlines with tags matching + a condition (the user is prompted for the condition). +M Like `m', but select only TODO entries, no ordinary headlines. +e Export views to associated files. +s Search entries for keywords. +S Search entries for keywords, only with TODO keywords. +/ Multi occur across all agenda files and also files listed + in `org-agenda-text-search-extra-files'. +< Restrict agenda commands to buffer, subtree, or region. + Press several times to get the desired effect. +> Remove a previous restriction. +# List \"stuck\" projects. +! Configure what \"stuck\" means. +C Configure custom agenda commands. + +More commands can be added by configuring the variable +`org-agenda-custom-commands'. In particular, specific tags and TODO keyword +searches can be pre-defined in this way. + +If the current buffer is in Org mode and visiting a file, you can also +first press `<' once to indicate that the agenda should be temporarily +\(until the next use of `\\[org-agenda]') restricted to the current file. +Pressing `<' twice means to restrict to the current subtree or region +\(if active). + +\(fn &optional ARG ORG-KEYS RESTRICTION)" t nil) + +(autoload 'org-batch-agenda "org-agenda" "\ +Run an agenda command in batch mode and send the result to STDOUT. +If CMD-KEY is a string of length 1, it is used as a key in +`org-agenda-custom-commands' and triggers this command. If it is a +longer string it is used as a tags/todo match string. +Parameters are alternating variable names and values that will be bound +before running the agenda command. + +\(fn CMD-KEY &rest PARAMETERS)" nil t) + +(autoload 'org-batch-agenda-csv "org-agenda" "\ +Run an agenda command in batch mode and send the result to STDOUT. +If CMD-KEY is a string of length 1, it is used as a key in +`org-agenda-custom-commands' and triggers this command. If it is a +longer string it is used as a tags/todo match string. +Parameters are alternating variable names and values that will be bound +before running the agenda command. + +The output gives a line for each selected agenda item. Each +item is a list of comma-separated values, like this: + +category,head,type,todo,tags,date,time,extra,priority-l,priority-n + +category The category of the item +head The headline, without TODO kwd, TAGS and PRIORITY +type The type of the agenda entry, can be + todo selected in TODO match + tagsmatch selected in tags match + diary imported from diary + deadline a deadline on given date + scheduled scheduled on given date + timestamp entry has timestamp on given date + closed entry was closed on given date + upcoming-deadline warning about deadline + past-scheduled forwarded scheduled item + block entry has date block including g. date +todo The todo keyword, if any +tags All tags including inherited ones, separated by colons +date The relevant date, like 2007-2-14 +time The time, like 15:00-16:50 +extra Sting with extra planning info +priority-l The priority letter if any was given +priority-n The computed numerical priority +agenda-day The day in the agenda where this is listed + +\(fn CMD-KEY &rest PARAMETERS)" nil t) + +(autoload 'org-store-agenda-views "org-agenda" "\ +Store agenda views. + +\(fn &rest PARAMETERS)" t nil) + +(autoload 'org-batch-store-agenda-views "org-agenda" "\ +Run all custom agenda commands that have a file argument. + +\(fn &rest PARAMETERS)" nil t) + +(autoload 'org-agenda-list "org-agenda" "\ +Produce a daily/weekly view from all files in variable `org-agenda-files'. +The view will be for the current day or week, but from the overview buffer +you will be able to go to other days/weeks. + +With a numeric prefix argument in an interactive call, the agenda will +span ARG days. Lisp programs should instead specify SPAN to change +the number of days. SPAN defaults to `org-agenda-span'. + +START-DAY defaults to TODAY, or to the most recent match for the weekday +given in `org-agenda-start-on-weekday'. + +When WITH-HOUR is non-nil, only include scheduled and deadline +items if they have an hour specification like [h]h:mm. + +\(fn &optional ARG START-DAY SPAN WITH-HOUR)" t nil) + +(autoload 'org-search-view "org-agenda" "\ +Show all entries that contain a phrase or words or regular expressions. + +With optional prefix argument TODO-ONLY, only consider entries that are +TODO entries. The argument STRING can be used to pass a default search +string into this function. If EDIT-AT is non-nil, it means that the +user should get a chance to edit this string, with cursor at position +EDIT-AT. + +The search string can be viewed either as a phrase that should be found as +is, or it can be broken into a number of snippets, each of which must match +in a Boolean way to select an entry. The default depends on the variable +`org-agenda-search-view-always-boolean'. +Even if this is turned off (the default) you can always switch to +Boolean search dynamically by preceding the first word with \"+\" or \"-\". + +The default is a direct search of the whole phrase, where each space in +the search string can expand to an arbitrary amount of whitespace, +including newlines. + +If using a Boolean search, the search string is split on whitespace and +each snippet is searched separately, with logical AND to select an entry. +Words prefixed with a minus must *not* occur in the entry. Words without +a prefix or prefixed with a plus must occur in the entry. Matching is +case-insensitive. Words are enclosed by word delimiters (i.e. they must +match whole words, not parts of a word) if +`org-agenda-search-view-force-full-words' is set (default is nil). + +Boolean search snippets enclosed by curly braces are interpreted as +regular expressions that must or (when preceded with \"-\") must not +match in the entry. Snippets enclosed into double quotes will be taken +as a whole, to include whitespace. + +- If the search string starts with an asterisk, search only in headlines. +- If (possibly after the leading star) the search string starts with an + exclamation mark, this also means to look at TODO entries only, an effect + that can also be achieved with a prefix argument. +- If (possibly after star and exclamation mark) the search string starts + with a colon, this will mean that the (non-regexp) snippets of the + Boolean search must match as full words. + +This command searches the agenda files, and in addition the files +listed in `org-agenda-text-search-extra-files' unless a restriction lock +is active. + +\(fn &optional TODO-ONLY STRING EDIT-AT)" t nil) + +(autoload 'org-todo-list "org-agenda" "\ +Show all (not done) TODO entries from all agenda file in a single list. +The prefix arg can be used to select a specific TODO keyword and limit +the list to these. When using `\\[universal-argument]', you will be prompted +for a keyword. A numeric prefix directly selects the Nth keyword in +`org-todo-keywords-1'. + +\(fn &optional ARG)" t nil) + +(autoload 'org-tags-view "org-agenda" "\ +Show all headlines for all `org-agenda-files' matching a TAGS criterion. +The prefix arg TODO-ONLY limits the search to TODO entries. + +\(fn &optional TODO-ONLY MATCH)" t nil) + +(autoload 'org-agenda-list-stuck-projects "org-agenda" "\ +Create agenda view for projects that are stuck. +Stuck projects are project that have no next actions. For the definitions +of what a project is and how to check if it stuck, customize the variable +`org-stuck-projects'. + +\(fn &rest IGNORE)" t nil) + +(autoload 'org-diary "org-agenda" "\ +Return diary information from org files. +This function can be used in a \"sexp\" diary entry in the Emacs calendar. +It accesses org files and extracts information from those files to be +listed in the diary. The function accepts arguments specifying what +items should be listed. For a list of arguments allowed here, see the +variable `org-agenda-entry-types'. + +The call in the diary file should look like this: + + &%%(org-diary) ~/path/to/some/orgfile.org + +Use a separate line for each org file to check. Or, if you omit the file name, +all files listed in `org-agenda-files' will be checked automatically: + + &%%(org-diary) + +If you don't give any arguments (as in the example above), the default value +of `org-agenda-entry-types' is used: (:deadline :scheduled :timestamp :sexp). +So the example above may also be written as + + &%%(org-diary :deadline :timestamp :sexp :scheduled) + +The function expects the lisp variables `entry' and `date' to be provided +by the caller, because this is how the calendar works. Don't use this +function from a program - use `org-agenda-get-day-entries' instead. + +\(fn &rest ARGS)" nil nil) + +(autoload 'org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item "org-agenda" "\ +Do we have a reason to ignore this TODO entry because it has a time stamp? + +\(fn &optional END)" nil nil) + +(autoload 'org-agenda-set-restriction-lock "org-agenda" "\ +Set restriction lock for agenda, to current subtree or file. +Restriction will be the file if TYPE is `file', or if type is the +universal prefix \\='(4), or if the cursor is before the first headline +in the file. Otherwise, restriction will be to the current subtree. + +\(fn &optional TYPE)" t nil) + +(autoload 'org-calendar-goto-agenda "org-agenda" "\ +Compute the Org agenda for the calendar date displayed at the cursor. +This is a command that has to be installed in `calendar-mode-map'. + +\(fn)" t nil) + +(autoload 'org-agenda-to-appt "org-agenda" "\ +Activate appointments found in `org-agenda-files'. + +With a `\\[universal-argument]' prefix, refresh the list of appointments. + +If FILTER is t, interactively prompt the user for a regular +expression, and filter out entries that don't match it. + +If FILTER is a string, use this string as a regular expression +for filtering entries out. + +If FILTER is a function, filter out entries against which +calling the function returns nil. This function takes one +argument: an entry from `org-agenda-get-day-entries'. + +FILTER can also be an alist with the car of each cell being +either `headline' or `category'. For example: + + \\='((headline \"IMPORTANT\") + (category \"Work\")) + +will only add headlines containing IMPORTANT or headlines +belonging to the \"Work\" category. + +ARGS are symbols indicating what kind of entries to consider. +By default `org-agenda-to-appt' will use :deadline*, :scheduled* +\(i.e., deadlines and scheduled items with a hh:mm specification) +and :timestamp entries. See the docstring of `org-diary' for +details and examples. + +If an entry has a APPT_WARNTIME property, its value will be used +to override `appt-message-warning-time'. + +\(fn &optional REFRESH FILTER &rest ARGS)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-agenda" '("org-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-archive" +;;;;;; "org-archive.el" (0 0 0 0)) +;;; Generated autoloads from org-archive.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-archive" '("org-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-attach" "org-attach.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-attach.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-attach" '("org-attach-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-bbdb" "org-bbdb.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-bbdb.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-bbdb" '("org-bbdb-"))) + +;;;*** + +;;;### (autoloads nil "org-bibtex" "org-bibtex.el" (0 0 0 0)) +;;; Generated autoloads from org-bibtex.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-bibtex" '("org-"))) + +;;;*** + +;;;### (autoloads nil "org-capture" "org-capture.el" (0 0 0 0)) +;;; Generated autoloads from org-capture.el + +(autoload 'org-capture-string "org-capture" "\ +Capture STRING with the template selected by KEYS. + +\(fn STRING &optional KEYS)" t nil) + +(autoload 'org-capture "org-capture" "\ +Capture something. +\\ +This will let you select a template from `org-capture-templates', and +then file the newly captured information. The text is immediately +inserted at the target location, and an indirect buffer is shown where +you can edit it. Pressing `\\[org-capture-finalize]' brings you back to the previous +state of Emacs, so that you can continue your work. + +When called interactively with a `\\[universal-argument]' prefix argument GOTO, don't +capture anything, just go to the file/headline where the selected +template stores its notes. + +With a `\\[universal-argument] \\[universal-argument]' prefix argument, go to the last note stored. + +When called with a `C-0' (zero) prefix, insert a template at point. + +When called with a `C-1' (one) prefix, force prompting for a date when +a datetree entry is made. + +ELisp programs can set KEYS to a string associated with a template +in `org-capture-templates'. In this case, interactive selection +will be bypassed. + +If `org-capture-use-agenda-date' is non-nil, capturing from the +agenda will use the date at point as the default date. Then, a +`C-1' prefix will tell the capture process to use the HH:MM time +of the day at point (if any) or the current HH:MM time. + +\(fn &optional GOTO KEYS)" t nil) + +(autoload 'org-capture-import-remember-templates "org-capture" "\ +Set `org-capture-templates' to be similar to `org-remember-templates'. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-capture" '("org-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-clock" "org-clock.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-clock.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-clock" '("org-"))) + +;;;*** + +;;;### (autoloads nil "org-colview" "org-colview.el" (0 0 0 0)) +;;; Generated autoloads from org-colview.el + +(autoload 'org-columns-remove-overlays "org-colview" "\ +Remove all currently active column overlays. + +\(fn)" t nil) + +(autoload 'org-columns-get-format-and-top-level "org-colview" "\ + + +\(fn)" nil nil) + +(autoload 'org-columns "org-colview" "\ +Turn on column view on an Org mode file. + +Column view applies to the whole buffer if point is before the +first headline. Otherwise, it applies to the first ancestor +setting \"COLUMNS\" property. If there is none, it defaults to +the current headline. With a `\\[universal-argument]' prefix argument, turn on column +view for the whole buffer unconditionally. + +When COLUMNS-FMT-STRING is non-nil, use it as the column format. + +\(fn &optional GLOBAL COLUMNS-FMT-STRING)" t nil) + +(autoload 'org-columns-compute "org-colview" "\ +Summarize the values of PROPERTY hierarchically. +Also update existing values for PROPERTY according to the first +column specification. + +\(fn PROPERTY)" t nil) + +(autoload 'org-dblock-write:columnview "org-colview" "\ +Write the column view table. +PARAMS is a property list of parameters: + +:id the :ID: property of the entry where the columns view + should be built. When the symbol `local', call locally. + When `global' call column view with the cursor at the beginning + of the buffer (usually this means that the whole buffer switches + to column view). When \"file:path/to/file.org\", invoke column + view at the start of that file. Otherwise, the ID is located + using `org-id-find'. +:hlines When t, insert a hline before each item. When a number, insert + a hline before each level <= that number. +:indent When non-nil, indent each ITEM field according to its level. +:vlines When t, make each column a colgroup to enforce vertical lines. +:maxlevel When set to a number, don't capture headlines below this level. +:skip-empty-rows + When t, skip rows where all specifiers other than ITEM are empty. +:width apply widths specified in columns format using specifiers. +:format When non-nil, specify the column view format to use. + +\(fn PARAMS)" nil nil) + +(autoload 'org-columns-insert-dblock "org-colview" "\ +Create a dynamic block capturing a column view table. + +\(fn)" t nil) + +(autoload 'org-agenda-columns "org-colview" "\ +Turn on or update column view in the agenda. + +\(fn)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-colview" '("org-"))) + +;;;*** + +;;;### (autoloads nil "org-compat" "org-compat.el" (0 0 0 0)) +;;; Generated autoloads from org-compat.el + +(autoload 'org-check-version "org-compat" "\ +Try very hard to provide sensible version strings. + +\(fn)" nil t) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-compat" '("org-"))) + +;;;*** + +;;;### (autoloads nil "org-crypt" "org-crypt.el" (0 0 0 0)) +;;; Generated autoloads from org-crypt.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-crypt" '("org-"))) + +;;;*** + +;;;### (autoloads nil "org-ctags" "org-ctags.el" (0 0 0 0)) +;;; Generated autoloads from org-ctags.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-ctags" '("org-ctags-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-datetree" +;;;;;; "org-datetree.el" (0 0 0 0)) +;;; Generated autoloads from org-datetree.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-datetree" '("org-datetree-"))) + +;;;*** + +;;;### (autoloads nil "org-docview" "org-docview.el" (0 0 0 0)) +;;; Generated autoloads from org-docview.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-docview" '("org-docview-"))) + +;;;*** + +;;;### (autoloads nil "org-duration" "org-duration.el" (0 0 0 0)) +;;; Generated autoloads from org-duration.el + +(autoload 'org-duration-set-regexps "org-duration" "\ +Set duration related regexps. + +\(fn)" t nil) + +(autoload 'org-duration-p "org-duration" "\ +Non-nil when string S is a time duration. + +\(fn S)" nil nil) + +(autoload 'org-duration-to-minutes "org-duration" "\ +Return number of minutes of DURATION string. + +When optional argument CANONICAL is non-nil, ignore +`org-duration-units' and use standard time units value. + +A bare number is translated into minutes. The empty string is +translated into 0.0. + +Return value as a float. Raise an error if duration format is +not recognized. + +\(fn DURATION &optional CANONICAL)" nil nil) + +(autoload 'org-duration-from-minutes "org-duration" "\ +Return duration string for a given number of MINUTES. + +Format duration according to `org-duration-format' or FMT, when +non-nil. + +When optional argument CANONICAL is non-nil, ignore +`org-duration-units' and use standard time units value. + +Raise an error if expected format is unknown. + +\(fn MINUTES &optional FMT CANONICAL)" nil nil) + +(autoload 'org-duration-h:mm-only-p "org-duration" "\ +Non-nil when every duration in TIMES has \"H:MM\" or \"H:MM:SS\" format. + +TIMES is a list of duration strings. + +Return nil if any duration is expressed with units, as defined in +`org-duration-units'. Otherwise, if any duration is expressed +with \"H:MM:SS\" format, return `h:mm:ss'. Otherwise, return +`h:mm'. + +\(fn TIMES)" nil nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-duration" '("org-duration-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-element" +;;;;;; "org-element.el" (0 0 0 0)) +;;; Generated autoloads from org-element.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-element" '("org-element-"))) + +;;;*** + +;;;### (autoloads nil "org-entities" "org-entities.el" (0 0 0 0)) +;;; Generated autoloads from org-entities.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-entities" '("org-entit"))) + +;;;*** + +;;;### (autoloads nil "org-eshell" "org-eshell.el" (0 0 0 0)) +;;; Generated autoloads from org-eshell.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-eshell" '("org-eshell-"))) + +;;;*** + +;;;### (autoloads nil "org-eww" "org-eww.el" (0 0 0 0)) +;;; Generated autoloads from org-eww.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-eww" '("org-eww-"))) + +;;;*** + +;;;### (autoloads nil "org-faces" "org-faces.el" (0 0 0 0)) +;;; Generated autoloads from org-faces.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-faces" '("org-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-feed" "org-feed.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-feed.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-feed" '("org-feed-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-footnote" +;;;;;; "org-footnote.el" (0 0 0 0)) +;;; Generated autoloads from org-footnote.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-footnote" '("org-footnote-"))) + +;;;*** + +;;;### (autoloads nil "org-gnus" "org-gnus.el" (0 0 0 0)) +;;; Generated autoloads from org-gnus.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-gnus" '("org-gnus-"))) + +;;;*** + +;;;### (autoloads nil "org-habit" "org-habit.el" (0 0 0 0)) +;;; Generated autoloads from org-habit.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-habit" '("org-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-id" "org-id.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-id.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-id" '("org-id-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-indent" "org-indent.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-indent.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-indent" '("org-"))) + +;;;*** + +;;;### (autoloads nil "org-info" "org-info.el" (0 0 0 0)) +;;; Generated autoloads from org-info.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-info" '("org-info-"))) + +;;;*** + +;;;### (autoloads nil "org-inlinetask" "org-inlinetask.el" (0 0 0 +;;;;;; 0)) +;;; Generated autoloads from org-inlinetask.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-inlinetask" '("org-inlinetask-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-irc" "org-irc.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-irc.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-irc" '("org-irc-"))) + +;;;*** + +;;;### (autoloads nil "org-lint" "org-lint.el" (0 0 0 0)) +;;; Generated autoloads from org-lint.el + +(autoload 'org-lint "org-lint" "\ +Check current Org buffer for syntax mistakes. + +By default, run all checkers. With a `\\[universal-argument]' prefix ARG, select one +category of checkers only. With a `\\[universal-argument] \\[universal-argument]' prefix, run one precise +checker by its name. + +ARG can also be a list of checker names, as symbols, to run. + +\(fn &optional ARG)" t nil) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-lint" '("org-lint-"))) + +;;;*** + +;;;### (autoloads nil "org-list" "org-list.el" (0 0 0 0)) +;;; Generated autoloads from org-list.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-list" '("org-"))) + +;;;*** + +;;;### (autoloads nil "org-macro" "org-macro.el" (0 0 0 0)) +;;; Generated autoloads from org-macro.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-macro" '("org-macro-"))) + +;;;*** + +;;;### (autoloads nil "org-macs" "org-macs.el" (0 0 0 0)) +;;; Generated autoloads from org-macs.el + +(autoload 'org-load-noerror-mustsuffix "org-macs" "\ +Load FILE with optional arguments NOERROR and MUSTSUFFIX. + +\(fn FILE)" nil t) + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-macs" '("org-"))) + +;;;*** + +;;;### (autoloads nil "org-mhe" "org-mhe.el" (0 0 0 0)) +;;; Generated autoloads from org-mhe.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-mhe" '("org-mhe-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-mobile" "org-mobile.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-mobile.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-mobile" '("org-mobile-"))) + +;;;*** + +;;;### (autoloads nil "org-mouse" "org-mouse.el" (0 0 0 0)) +;;; Generated autoloads from org-mouse.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-mouse" '("org-mouse-"))) + +;;;*** + +;;;### (autoloads nil "org-pcomplete" "org-pcomplete.el" (0 0 0 0)) +;;; Generated autoloads from org-pcomplete.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-pcomplete" '("org-" "pcomplete/org-mode/"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-plot" "org-plot.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-plot.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-plot" '("org-plot"))) + +;;;*** + +;;;### (autoloads nil "org-protocol" "org-protocol.el" (0 0 0 0)) +;;; Generated autoloads from org-protocol.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-protocol" '("org-protocol-"))) + +;;;*** + +;;;### (autoloads nil "org-rmail" "org-rmail.el" (0 0 0 0)) +;;; Generated autoloads from org-rmail.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-rmail" '("org-rmail-"))) + +;;;*** + +;;;### (autoloads nil "org-src" "org-src.el" (0 0 0 0)) +;;; Generated autoloads from org-src.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-src" '("org-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-table" "org-table.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-table.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-table" '("org"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "org-timer" "org-timer.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from org-timer.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-timer" '("org-timer-"))) + +;;;*** + +;;;### (autoloads nil "org-version" "org-version.el" (0 0 0 0)) +;;; Generated autoloads from org-version.el + +(autoload 'org-release "org-version" "\ +The release version of Org. +Inserted by installing Org mode or when a release is made. + +\(fn)" nil nil) + +(autoload 'org-git-version "org-version" "\ +The Git version of Org mode. +Inserted by installing Org or when a release is made. + +\(fn)" nil nil) + +(defvar org-odt-data-dir "/usr/share/emacs/etc/org" "\ +The location of ODT styles.") + +;;;*** + +;;;### (autoloads nil "org-w3m" "org-w3m.el" (0 0 0 0)) +;;; Generated autoloads from org-w3m.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "org-w3m" '("org-w3m-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox" "ox.el" (0 +;;;;;; 0 0 0)) +;;; Generated autoloads from ox.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox" '("org-export-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-ascii" "ox-ascii.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-ascii.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-ascii" '("org-ascii-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-beamer" "ox-beamer.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-beamer.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-beamer" '("org-beamer-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-html" "ox-html.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-html.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-html" '("org-html-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-icalendar" +;;;;;; "ox-icalendar.el" (0 0 0 0)) +;;; Generated autoloads from ox-icalendar.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-icalendar" '("org-icalendar-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-latex" "ox-latex.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-latex.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-latex" '("org-latex-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-man" "ox-man.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-man.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-man" '("org-man-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-md" "ox-md.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-md.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-md" '("org-md-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-odt" "ox-odt.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-odt.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-odt" '("org-odt-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-org" "ox-org.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-org.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-org" '("org-org-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-publish" "ox-publish.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-publish.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-publish" '("org-publish-"))) + +;;;*** + +;;;### (autoloads "actual autoloads are elsewhere" "ox-texinfo" "ox-texinfo.el" +;;;;;; (0 0 0 0)) +;;; Generated autoloads from ox-texinfo.el + +(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "ox-texinfo" '("org-texinfo-"))) + +;;;*** + +;;;### (autoloads nil nil ("ob-core.el" "ob-keys.el" "ob-lob.el" +;;;;;; "ob-matlab.el" "ob-tangle.el" "ob.el" "org-archive.el" "org-attach.el" +;;;;;; "org-bbdb.el" "org-clock.el" "org-datetree.el" "org-element.el" +;;;;;; "org-feed.el" "org-footnote.el" "org-id.el" "org-indent.el" +;;;;;; "org-install.el" "org-irc.el" "org-loaddefs.el" "org-mobile.el" +;;;;;; "org-pkg.el" "org-plot.el" "org-table.el" "org-timer.el" +;;;;;; "ox-ascii.el" "ox-beamer.el" "ox-html.el" "ox-icalendar.el" +;;;;;; "ox-latex.el" "ox-man.el" "ox-md.el" "ox-odt.el" "ox-org.el" +;;;;;; "ox-publish.el" "ox-texinfo.el" "ox.el") (0 0 0 0)) + +;;;*** + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; org-autoloads.el ends here diff --git a/elpa/org-9.1.14/org-bbdb.el b/elpa/org-9.1.14/org-bbdb.el new file mode 100644 index 00000000..5d36379b --- /dev/null +++ b/elpa/org-9.1.14/org-bbdb.el @@ -0,0 +1,541 @@ +;;; org-bbdb.el --- Support for links to BBDB entries -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Authors: Carsten Dominik +;; Thomas Baumann +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file implements links to BBDB database entries from within Org. +;; Org mode loads this module by default - if this is not what you want, +;; configure the variable `org-modules'. + +;; It also implements an interface (based on Ivar Rummelhoff's +;; bbdb-anniv.el) for those Org users, who do not use the diary +;; but who do want to include the anniversaries stored in the BBDB +;; into the org-agenda. If you already include the `diary' into the +;; agenda, you might want to prefer to include the anniversaries in +;; the diary using bbdb-anniv.el. +;; +;; Put the following in /somewhere/at/home/diary.org and make sure +;; that this file is in `org-agenda-files'. +;; +;; %%(org-bbdb-anniversaries) +;; +;; For example my diary.org looks like: +;; * Anniversaries +;; #+CATEGORY: Anniv +;; %%(org-bbdb-anniversaries) +;; +;; +;; To add an anniversary to a BBDB record, press `C-o' in the record. +;; You will be prompted for the field name, in this case it must be +;; "anniversary". If this is the first time you are using this field, +;; you need to confirm that it should be created. +;; +;; The format of an anniversary field stored in BBDB is the following +;; (items in {} are optional): +;; +;; YYYY-MM-DD{ CLASS-OR-FORMAT-STRING} +;; {\nYYYY-MM-DD CLASS-OR-FORMAT-STRING}... +;; +;; CLASS-OR-FORMAT-STRING is one of two things: +;; +;; - an identifier for a class of anniversaries (eg. birthday or +;; wedding) from `org-bbdb-anniversary-format-alist' which then +;; defines the format string for this class +;; - the (format) string displayed in the diary. +;; +;; You can enter multiple anniversaries for a single BBDB record by +;; separating them with a newline character. At the BBDB prompt for +;; the field value, type `C-q C-j' to enter a newline between two +;; anniversaries. +;; +;; If you omit the CLASS-OR-FORMAT-STRING entirely, it defaults to the +;; value of `org-bbdb-default-anniversary-format' ("birthday" by +;; default). +;; +;; The substitutions in the format string are (in order): +;; - the name of the record containing this anniversary +;; - the number of years +;; - an ordinal suffix (st, nd, rd, th) for the year +;; +;; See the documentation of `org-bbdb-anniversary-format-alist' for +;; further options. +;; +;; Example +;; +;; 1973-06-22 +;; 20??-??-?? wedding +;; 1998-03-12 %s created bbdb-anniv.el %d years ago +;; +;; From Org's agenda, you can use `C-c C-o' to jump to the BBDB +;; link from which the entry at point originates. +;; +;;; Code: + +(require 'org) +(require 'cl-lib) + +;; Declare external functions and variables + +(declare-function bbdb "ext:bbdb-com" (string elidep)) +(declare-function bbdb-company "ext:bbdb-com" (string elidep)) +(declare-function bbdb-current-record "ext:bbdb-com" + (&optional planning-on-modifying)) +(declare-function bbdb-name "ext:bbdb-com" (string elidep)) +(declare-function bbdb-completing-read-record "ext:bbdb-com" + (prompt &optional omit-records)) +(declare-function bbdb-record-field "ext:bbdb" (record field)) +(declare-function bbdb-record-getprop "ext:bbdb" (record property)) +(declare-function bbdb-record-name "ext:bbdb" (record)) +(declare-function bbdb-records "ext:bbdb" + (&optional dont-check-disk already-in-db-buffer)) +(declare-function bbdb-split "ext:bbdb" (string separators)) +(declare-function bbdb-string-trim "ext:bbdb" (string)) +(declare-function bbdb-record-get-field "ext:bbdb" (record field)) +(declare-function bbdb-search-name "ext:bbdb-com" (regexp &optional layout)) +(declare-function bbdb-search-organization "ext:bbdb-com" (regexp &optional layout)) + +;; `bbdb-record-note' was part of BBDB v3.x +(declare-function bbdb-record-note "ext:bbdb" (record label)) +;; `bbdb-record-xfield' replaces it in recent BBDB v3.x+ +(declare-function bbdb-record-xfield "ext:bbdb" (record label)) + +(declare-function calendar-leap-year-p "calendar" (year)) +(declare-function diary-ordinal-suffix "diary-lib" (n)) + +(with-no-warnings (defvar date)) ;; unprefixed, from calendar.el + +;; Customization + +(defgroup org-bbdb-anniversaries nil + "Customizations for including anniversaries from BBDB into Agenda." + :group 'org-bbdb) + +(defcustom org-bbdb-default-anniversary-format "birthday" + "Default anniversary class." + :type 'string + :group 'org-bbdb-anniversaries + :require 'bbdb) + +(defcustom org-bbdb-general-anniversary-description-after 7 + "When to switch anniversary descriptions to a more general format. + +Anniversary descriptions include the point in time, when the +anniversary appears. This is, in its most general form, just the +date of the anniversary. Or more specific terms, like \"today\", +\"tomorrow\" or \"in n days\" are used to describe the time span. + +If the anniversary happens in less than that number of days, the +specific description is used. Otherwise, the general one is +used." + :group 'org-bbdb-anniversaries + :version "26.1" + :package-version '(Org . "9.1") + :type 'integer + :require 'bbdb + :safe #'integerp) + +(defcustom org-bbdb-anniversary-format-alist + '(("birthday" . + (lambda (name years suffix) + (concat "Birthday: [[bbdb:" name "][" name " (" + (format "%s" years) ; handles numbers as well as strings + suffix ")]]"))) + ("wedding" . + (lambda (name years suffix) + (concat "[[bbdb:" name "][" name "'s " + (format "%s" years) + suffix " wedding anniversary]]")))) + "How different types of anniversaries should be formatted. +An alist of elements (STRING . FORMAT) where STRING is the name of an +anniversary class and format is either: +1) A format string with the following substitutions (in order): + - the name of the record containing this anniversary + - the number of years + - an ordinal suffix (st, nd, rd, th) for the year + +2) A function to be called with three arguments: NAME YEARS SUFFIX + (string int string) returning a string for the diary or nil. + +3) An Emacs Lisp form that should evaluate to a string (or nil) in the + scope of variables NAME, YEARS and SUFFIX (among others)." + :type '(alist :key-type (string :tag "Class") + :value-type (function :tag "Function")) + :group 'org-bbdb-anniversaries + :require 'bbdb) + +(defcustom org-bbdb-anniversary-field 'anniversary + "The BBDB field which contains anniversaries. +The anniversaries are stored in the following format + +YYYY-MM-DD Class-or-Format-String + +where class is one of the customized classes for anniversaries; +birthday and wedding are predefined. Format-String can take three +substitutions 1) the name of the record containing this +anniversary, 2) the number of years, and 3) an ordinal suffix for +the year. + +Multiple anniversaries can be separated by \\n." + :type 'symbol + :group 'org-bbdb-anniversaries + :require 'bbdb) + +(defcustom org-bbdb-extract-date-fun 'org-bbdb-anniv-extract-date + "How to retrieve `month date year' from the anniversary field. + +Customize if you have already filled your BBDB with dates +different from YYYY-MM-DD. The function must return a list (month +date year)." + :type 'function + :group 'org-bbdb-anniversaries + :require 'bbdb) + +;; Install the link type +(org-link-set-parameters "bbdb" + :follow #'org-bbdb-open + :export #'org-bbdb-export + :complete #'org-bbdb-complete-link + :store #'org-bbdb-store-link) + +;; Implementation +(defun org-bbdb-store-link () + "Store a link to a BBDB database entry." + (when (eq major-mode 'bbdb-mode) + ;; This is BBDB, we make this link! + (let* ((rec (bbdb-current-record)) + (name (bbdb-record-name rec)) + (company (if (fboundp 'bbdb-record-getprop) + (bbdb-record-getprop rec 'company) + (car (bbdb-record-field rec 'organization)))) + (link (concat "bbdb:" name))) + (org-store-link-props :type "bbdb" :name name :company company + :link link :description name) + link))) + +(defun org-bbdb-export (path desc format) + "Create the export version of a BBDB link specified by PATH or DESC. +If exporting to either HTML or LaTeX FORMAT the link will be +italicized, in all other cases it is left unchanged." + (when (string= desc (format "bbdb:%s" path)) + (setq desc path)) + (cond + ((eq format 'html) (format "%s" desc)) + ((eq format 'latex) (format "\\textit{%s}" desc)) + ((eq format 'odt) + (format "%s" desc)) + (t desc))) + +(defun org-bbdb-open (name) + "Follow a BBDB link to NAME." + (require 'bbdb-com) + (let ((inhibit-redisplay (not debug-on-error))) + (if (fboundp 'bbdb-name) + (org-bbdb-open-old name) + (org-bbdb-open-new name)))) + +(defun org-bbdb-open-old (name) + (catch 'exit + ;; Exact match on name + (bbdb-name (concat "\\`" name "\\'") nil) + (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil)) + ;; Exact match on name + (bbdb-company (concat "\\`" name "\\'") nil) + (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil)) + ;; Partial match on name + (bbdb-name name nil) + (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil)) + ;; Partial match on company + (bbdb-company name nil) + (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil)) + ;; General match including network address and notes + (bbdb name nil) + (when (= 0 (buffer-size (get-buffer "*BBDB*"))) + (delete-window (get-buffer-window "*BBDB*")) + (error "No matching BBDB record")))) + +(defun org-bbdb-open-new (name) + (catch 'exit + ;; Exact match on name + (bbdb-search-name (concat "\\`" name "\\'") nil) + (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil)) + ;; Exact match on name + (bbdb-search-organization (concat "\\`" name "\\'") nil) + (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil)) + ;; Partial match on name + (bbdb-search-name name nil) + (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil)) + ;; Partial match on company + (bbdb-search-organization name nil) + (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil)) + ;; General match including network address and notes + (bbdb name nil) + (when (= 0 (buffer-size (get-buffer "*BBDB*"))) + (delete-window (get-buffer-window "*BBDB*")) + (error "No matching BBDB record")))) + +(defun org-bbdb-anniv-extract-date (time-str) + "Convert YYYY-MM-DD to (month date year). +Argument TIME-STR is the value retrieved from BBDB. If YYYY- is omitted +it will be considered unknown." + (pcase (org-split-string time-str "-") + (`(,a ,b nil) (list (string-to-number a) (string-to-number b) nil)) + (`(,a ,b ,c) (list (string-to-number b) + (string-to-number c) + (string-to-number a))))) + +(defun org-bbdb-anniv-split (str) + "Split multiple entries in the BBDB anniversary field. +Argument STR is the anniversary field in BBDB." + (let ((pos (string-match "[ \t]" str))) + (if pos (list (substring str 0 pos) + (bbdb-string-trim (substring str pos))) + (list str nil)))) + +(defvar org-bbdb-anniv-hash nil + "A hash holding anniversaries extracted from BBDB. +The hash table is created on first use.") + +(defvar org-bbdb-updated-p t + "This is non-nil if BBDB has been updated since we last built the hash.") + +(defun org-bbdb-make-anniv-hash () + "Create a hash with anniversaries extracted from BBDB, for fast access. +The anniversaries are assumed to be stored `org-bbdb-anniversary-field'." + (let ((old-bbdb (fboundp 'bbdb-record-getprop)) + (record-func (if (fboundp 'bbdb-record-xfield) + 'bbdb-record-xfield + 'bbdb-record-note)) + split tmp annivs) + (clrhash org-bbdb-anniv-hash) + (dolist (rec (bbdb-records)) + (when (setq annivs (if old-bbdb + (bbdb-record-getprop + rec org-bbdb-anniversary-field) + (funcall record-func + rec org-bbdb-anniversary-field))) + (setq annivs (if old-bbdb + (bbdb-split annivs "\n") + ;; parameter order is reversed in new bbdb + (bbdb-split "\n" annivs))) + (while annivs + (setq split (org-bbdb-anniv-split (pop annivs))) + (pcase-let ((`(,m ,d ,y) (funcall org-bbdb-extract-date-fun + (car split)))) + (setq tmp (gethash (list m d) org-bbdb-anniv-hash)) + (puthash (list m d) (cons (list y + (bbdb-record-name rec) + (cadr split)) + tmp) + org-bbdb-anniv-hash)))))) + (setq org-bbdb-updated-p nil)) + +(defun org-bbdb-updated (_rec) + "Record the fact that BBDB has been updated. +This is used by Org to re-create the anniversary hash table." + (setq org-bbdb-updated-p t)) + +(add-hook 'bbdb-after-change-hook 'org-bbdb-updated) + +;;;###autoload +(defun org-bbdb-anniversaries () + "Extract anniversaries from BBDB for display in the agenda." + (require 'bbdb) + (require 'diary-lib) + (unless (hash-table-p org-bbdb-anniv-hash) + (setq org-bbdb-anniv-hash + (make-hash-table :test 'equal :size 366))) + + (when (or org-bbdb-updated-p + (= 0 (hash-table-count org-bbdb-anniv-hash))) + (org-bbdb-make-anniv-hash)) + + (let* ((m (car date)) ; month + (d (nth 1 date)) ; day + (y (nth 2 date)) ; year + (annivs (gethash (list m d) org-bbdb-anniv-hash)) + (text ()) + rec recs) + + ;; we don't want to miss people born on Feb. 29th + (when (and (= m 3) (= d 1) + (not (null (gethash (list 2 29) org-bbdb-anniv-hash))) + (not (calendar-leap-year-p y))) + (setq recs (gethash (list 2 29) org-bbdb-anniv-hash)) + (while (setq rec (pop recs)) + (push rec annivs))) + + (when annivs + (while (setq rec (pop annivs)) + (when rec + (let* ((class (or (nth 2 rec) + org-bbdb-default-anniversary-format)) + (form (or (cdr (assoc-string + class org-bbdb-anniversary-format-alist t)) + class)) ; (as format string) + (name (nth 1 rec)) + (years (if (eq (car rec) nil) + "unknown" + (- y (car rec)))) + (suffix (if (eq (car rec) nil) + "" + (diary-ordinal-suffix years))) + (tmp (cond + ((functionp form) + (funcall form name years suffix)) + ((listp form) (eval form)) + (t (format form name years suffix))))) + (org-add-props tmp nil 'org-bbdb-name name) + (if text + (setq text (append text (list tmp))) + (setq text (list tmp))))) + )) + text)) + +;;; Return list of anniversaries for today and the next n-1 (default: n=7) days. +;;; This is meant to be used in an org file instead of org-bbdb-anniversaries: +;;; +;;; %%(org-bbdb-anniversaries-future) +;;; +;;; or +;;; +;;; %%(org-bbdb-anniversaries-future 3) +;;; +;;; to override the 7-day default. + +(defun org-bbdb-date-list (d n) + "Return a list of dates in (m d y) format from the given date D to n-1 days hence." + (let ((abs (calendar-absolute-from-gregorian d))) + (mapcar (lambda (i) (calendar-gregorian-from-absolute (+ abs i))) + (number-sequence 0 (1- n))))) + +(defun org-bbdb-anniversary-description (agenda-date anniv-date) + "Return a string used to incorporate into an agenda anniversary entry. +The calculation of the anniversary description string is based on +the difference between the anniversary date, given as ANNIV-DATE, +and the date on which the entry appears in the agenda, given as +AGENDA-DATE. This makes it possible to have different entries +for the same event depending on if it occurs in the next few days +or far away in the future." + (let ((delta (- (calendar-absolute-from-gregorian anniv-date) + (calendar-absolute-from-gregorian agenda-date)))) + + (cond + ((= delta 0) " -- today\\&") + ((= delta 1) " -- tomorrow\\&") + ((< delta org-bbdb-general-anniversary-description-after) (format " -- in %d days\\&" delta)) + ((pcase-let ((`(,month ,day ,year) anniv-date)) + (format " -- %d-%02d-%02d\\&" year month day)))))) + + +(defun org-bbdb-anniversaries-future (&optional n) + "Return list of anniversaries for today and the next n-1 days (default n=7)." + (let ((n (or n 7))) + (when (<= n 0) + (error "The (optional) argument of `org-bbdb-anniversaries-future' \ +must be positive")) + (let ( + ;; List of relevant dates. + (dates (org-bbdb-date-list date n)) + ;; Function to annotate text of each element of l with the + ;; anniversary date d. + (annotate-descriptions + (lambda (agenda-date d l) + (mapcar (lambda (x) + ;; The assumption here is that x is a bbdb link + ;; of the form [[bbdb:name][description]]. + ;; This function rather arbitrarily modifies + ;; the description by adding the date to it in + ;; a fixed format. + (let ((desc (org-bbdb-anniversary-description + agenda-date d))) + (string-match "]]" x) + (replace-match desc nil nil x))) + l)))) + ;; Map a function that generates anniversaries for each date + ;; over the dates and nconc the results into a single list. When + ;; it is no longer necessary to support older versions of Emacs, + ;; this can be done with a cl-mapcan; for now, we use the (apply + ;; #'nconc ...) method for compatibility. + (apply #'nconc + (mapcar + (lambda (d) + (let ((agenda-date date) + (date d)) + ;; Rebind 'date' so that org-bbdb-anniversaries will + ;; be fooled into giving us the list for the given + ;; date and then annotate the descriptions for that + ;; date. + (funcall annotate-descriptions agenda-date d (org-bbdb-anniversaries)))) + dates))))) + +(defun org-bbdb-complete-link () + "Read a bbdb link with name completion." + (require 'bbdb-com) + (let ((rec (bbdb-completing-read-record "Name: "))) + (concat "bbdb:" + (bbdb-record-name (if (listp rec) + (car rec) + rec))))) + +(defun org-bbdb-anniv-export-ical () + "Extract anniversaries from BBDB and convert them to icalendar format." + (require 'bbdb) + (require 'diary-lib) + (unless (hash-table-p org-bbdb-anniv-hash) + (setq org-bbdb-anniv-hash + (make-hash-table :test 'equal :size 366))) + (when (or org-bbdb-updated-p + (= 0 (hash-table-count org-bbdb-anniv-hash))) + (org-bbdb-make-anniv-hash)) + (maphash 'org-bbdb-format-vevent org-bbdb-anniv-hash)) + +(defun org-bbdb-format-vevent (key recs) + (let (rec categ) + (while (setq rec (pop recs)) + (setq categ (or (nth 2 rec) org-bbdb-default-anniversary-format)) + (princ (format "BEGIN:VEVENT +UID: ANNIV-%4i%02i%02i-%s +DTSTART:%4i%02i%02i +SUMMARY:%s +DESCRIPTION:%s +CATEGORIES:%s +RRULE:FREQ=YEARLY +END:VEVENT\n" + (nth 0 rec) (nth 0 key) (nth 1 key) + (mapconcat 'identity + (org-split-string (nth 1 rec) "[^a-zA-Z0-90]+") + "-") + (nth 0 rec) (nth 0 key) (nth 1 key) + (nth 1 rec) + (concat (capitalize categ) " " (nth 1 rec)) + categ))))) + +(provide 'org-bbdb) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-bbdb.el ends here diff --git a/elpa/org-9.1.14/org-bibtex.el b/elpa/org-9.1.14/org-bibtex.el new file mode 100644 index 00000000..9dab0b46 --- /dev/null +++ b/elpa/org-9.1.14/org-bibtex.el @@ -0,0 +1,748 @@ +;;; org-bibtex.el --- Org links to BibTeX entries -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2007-2018 Free Software Foundation, Inc. +;; +;; Authors: Bastien Guerry +;; Carsten Dominik +;; Eric Schulte +;; Keywords: org, wp, capture +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;; +;;; Commentary: +;; +;; This file implements links to database entries in BibTeX files. +;; Instead of defining a special link prefix, it uses the normal file +;; links combined with a custom search mechanism to find entries +;; by reference key. And it constructs a nice description tag for +;; the link that contains the author name, the year and a short title. +;; +;; It also stores detailed information about the entry so that +;; capture templates can access and enter this information easily. +;; +;; The available properties for each entry are listed here: +;; +;; :author :publisher :volume :pages +;; :editor :url :number :journal +;; :title :year :series :address +;; :booktitle :month :annote :abstract +;; :key :btype +;; +;; Here is an example of a capture template that use some of this +;; information (:author :year :title :journal :pages): +;; +;; (setq org-capture-templates +;; '((?b "* READ %?\n\n%a\n\n%:author (%:year): %:title\n \ +;; In %:journal, %:pages."))) +;; +;; Let's say you want to capture this BibTeX entry: +;; +;; @Article{dolev83, +;; author = {Danny Dolev and Andrew C. Yao}, +;; title = {On the security of public-key protocols}, +;; journal = {IEEE Transaction on Information Theory}, +;; year = 1983, +;; volume = 2, +;; number = 29, +;; pages = {198--208}, +;; month = {Mars} +;; } +;; +;; M-x `org-capture' on this entry will produce this buffer: +;; +;; ===================================================================== +;; * READ <== [point here] +;; +;; [[file:file.bib::dolev83][Dolev & Yao 1983: security of public key protocols]] +;; +;; Danny Dolev and Andrew C. Yao (1983): On the security of public-key protocols +;; In IEEE Transaction on Information Theory, 198--208. +;; ===================================================================== +;; +;; Additionally, the following functions are now available for storing +;; bibtex entries within Org documents. +;; +;; - Run `org-bibtex' to export the current file to a .bib. +;; +;; - Run `org-bibtex-check' or `org-bibtex-check-all' to check and +;; fill in missing field of either the current, or all headlines +;; +;; - Run `org-bibtex-create' to add a bibtex entry +;; +;; - Use `org-bibtex-read' to read a bibtex entry after `point' or in +;; the active region, then call `org-bibtex-write' in a .org file to +;; insert a heading for the read bibtex entry +;; +;; - All Bibtex information is taken from the document compiled by +;; Andrew Roberts from the Bibtex manual, available at +;; http://www.andy-roberts.net/res/writing/latex/bibentries.pdf +;; +;;; History: +;; +;; The link creation part has been part of Org for a long time. +;; +;; Creating better capture template information was inspired by a request +;; of Austin Frank: http://article.gmane.org/gmane.emacs.orgmode/4112 +;; and then implemented by Bastien Guerry. +;; +;; Eric Schulte eventually added the functions for translating between +;; Org headlines and Bibtex entries, and for fleshing out the Bibtex +;; fields of existing Org headlines. +;; +;; Org mode loads this module by default - if this is not what you want, +;; configure the variable `org-modules'. + +;;; Code: + +(require 'org) +(require 'bibtex) +(require 'cl-lib) +(require 'org-compat) + +(defvar org-agenda-overriding-header) +(defvar org-agenda-search-view-always-boolean) +(defvar org-bibtex-description nil) ; dynamically scoped from org.el +(defvar org-id-locations) + +(declare-function bibtex-beginning-of-entry "bibtex" ()) +(declare-function bibtex-generate-autokey "bibtex" ()) +(declare-function bibtex-parse-entry "bibtex" (&optional content)) +(declare-function bibtex-url "bibtex" (&optional pos no-browse)) + + +;;; Bibtex data +(defvar org-bibtex-types + '((:article + (:description . "An article from a journal or magazine") + (:required :author :title :journal :year) + (:optional :volume :number :pages :month :note)) + (:book + (:description . "A book with an explicit publisher") + (:required (:editor :author) :title :publisher :year) + (:optional (:volume :number) :series :address :edition :month :note)) + (:booklet + (:description . "A work that is printed and bound, but without a named publisher or sponsoring institution.") + (:required :title) + (:optional :author :howpublished :address :month :year :note)) + (:conference + (:description . "") + (:required :author :title :booktitle :year) + (:optional :editor :pages :organization :publisher :address :month :note)) + (:inbook + (:description . "A part of a book, which may be a chapter (or section or whatever) and/or a range of pages.") + (:required (:author :editor) :title (:chapter :pages) :publisher :year) + (:optional :crossref (:volume :number) :series :type :address :edition :month :note)) + (:incollection + (:description . "A part of a book having its own title.") + (:required :author :title :booktitle :publisher :year) + (:optional :crossref :editor (:volume :number) :series :type :chapter :pages :address :edition :month :note)) + (:inproceedings + (:description . "An article in a conference proceedings") + (:required :author :title :booktitle :year) + (:optional :crossref :editor (:volume :number) :series :pages :address :month :organization :publisher :note)) + (:manual + (:description . "Technical documentation.") + (:required :title) + (:optional :author :organization :address :edition :month :year :note)) + (:mastersthesis + (:description . "A Master’s thesis.") + (:required :author :title :school :year) + (:optional :type :address :month :note)) + (:misc + (:description . "Use this type when nothing else fits.") + (:required) + (:optional :author :title :howpublished :month :year :note)) + (:phdthesis + (:description . "A PhD thesis.") + (:required :author :title :school :year) + (:optional :type :address :month :note)) + (:proceedings + (:description . "The proceedings of a conference.") + (:required :title :year) + (:optional :editor (:volume :number) :series :address :month :organization :publisher :note)) + (:techreport + (:description . "A report published by a school or other institution.") + (:required :author :title :institution :year) + (:optional :type :address :month :note)) + (:unpublished + (:description . "A document having an author and title, but not formally published.") + (:required :author :title :note) + (:optional :month :year))) + "Bibtex entry types with required and optional parameters.") + +(defvar org-bibtex-fields + '((:address . "Usually the address of the publisher or other type of institution. For major publishing houses, van Leunen recommends omitting the information entirely. For small publishers, on the other hand, you can help the reader by giving the complete address.") + (:annote . "An annotation. It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography.") + (:author . "The name(s) of the author(s), in the format described in the LaTeX book. Remember, all names are separated with the and keyword, and not commas.") + (:booktitle . "Title of a book, part of which is being cited. See the LaTeX book for how to type titles. For book entries, use the title field instead.") + (:chapter . "A chapter (or section or whatever) number.") + (:crossref . "The database key of the entry being cross referenced.") + (:edition . "The edition of a book for example, 'Second'. This should be an ordinal, and should have the first letter capitalized, as shown here; the standard styles convert to lower case when necessary.") + (:editor . "Name(s) of editor(s), typed as indicated in the LaTeX book. If there is also an author field, then the editor field gives the editor of the book or collection in which the reference appears.") + (:howpublished . "How something strange has been published. The first word should be capitalized.") + (:institution . "The sponsoring institution of a technical report.") + (:journal . "A journal name.") + (:key . "Used for alphabetizing, cross-referencing, and creating a label when the author information is missing. This field should not be confused with the key that appears in the \\cite command and at the beginning of the database entry.") + (:month . "The month in which the work was published or, for an unpublished work, in which it was written. You should use the standard three-letter abbreviation,") + (:note . "Any additional information that can help the reader. The first word should be capitalized.") + (:number . "Any additional information that can help the reader. The first word should be capitalized.") + (:organization . "The organization that sponsors a conference or that publishes a manual.") + (:pages . "One or more page numbers or range of numbers, such as 42-111 or 7,41,73-97 or 43+ (the ‘+’ in this last example indicates pages following that don’t form simple range). BibTEX requires double dashes for page ranges (--).") + (:publisher . "The publisher’s name.") + (:school . "The name of the school where a thesis was written.") + (:series . "The name of a series or set of books. When citing an entire book, the title field gives its title and an optional series field gives the name of a series or multi-volume set in which the book is published.") + (:title . "The work’s title, typed as explained in the LaTeX book.") + (:type . "The type of a technical report for example, 'Research Note'.") + (:volume . "The volume of a journal or multi-volume book.") + (:year . "The year of publication or, for an unpublished work, the year it was written. Generally it should consist of four numerals, such as 1984, although the standard styles can handle any year whose last four nonpunctuation characters are numerals, such as '(about 1984)'")) + "Bibtex fields with descriptions.") + +(defvar org-bibtex-entries nil + "List to hold parsed bibtex entries.") + +(defcustom org-bibtex-autogen-keys nil + "Set to a truth value to use `bibtex-generate-autokey' to generate keys." + :group 'org-bibtex + :version "24.1" + :type 'boolean) + +(defcustom org-bibtex-prefix nil + "Optional prefix for all bibtex property names. +For example setting to `BIB_' would allow interoperability with fireforg." + :group 'org-bibtex + :version "24.1" + :type '(choice + (const nil) + (string))) + +(defcustom org-bibtex-treat-headline-as-title t + "Treat headline text as title if title property is absent. +If an entry is missing a title property, use the headline text as +the property. If this value is t, `org-bibtex-check' will ignore +a missing title field." + :group 'org-bibtex + :version "24.1" + :type 'boolean) + +(defcustom org-bibtex-headline-format-function + (lambda (entry) (cdr (assq :title entry))) + "Function returning the headline text for `org-bibtex-write'. +It should take a single argument, the bibtex entry (an alist as +returned by `org-bibtex-read'). The default value simply returns +the entry title." + :group 'org-bibtex + :version "26.1" + :package-version '(Org . "9.1") + :type 'function) + +(defcustom org-bibtex-export-arbitrary-fields nil + "When converting to bibtex allow fields not defined in `org-bibtex-fields'. +This only has effect if `org-bibtex-prefix' is defined, so as to +ensure that other org-properties, such as CATEGORY or LOGGING are +not placed in the exported bibtex entry." + :group 'org-bibtex + :version "24.1" + :type 'boolean) + +(defcustom org-bibtex-key-property "CUSTOM_ID" + "Property that holds the bibtex key. +By default, this is CUSTOM_ID, which enables easy linking to +bibtex headlines from within an org file. This can be set to ID +to enable global links, but only with great caution, as global +IDs must be unique." + :group 'org-bibtex + :version "24.1" + :type 'string) + +(defcustom org-bibtex-tags nil + "List of tag(s) that should be added to new bib entries." + :group 'org-bibtex + :version "24.1" + :type '(repeat :tag "Tag" (string))) + +(defcustom org-bibtex-tags-are-keywords nil + "Convert the value of the keywords field to tags and vice versa. + +When non-nil, comma-separated entries in a bibtex entry's keywords +field will be converted to Org tags. Note: spaces will be escaped +with underscores, and characters that are not permitted in Org +tags will be removed. + +When non-nil, local tags in an Org entry will be exported as +a comma-separated string of keywords when exported to bibtex. +If `org-bibtex-inherit-tags' is non-nil, inherited tags will also +be exported as keywords. Tags defined in `org-bibtex-tags' or +`org-bibtex-no-export-tags' will not be exported." + :group 'org-bibtex + :version "24.1" + :type 'boolean) + +(defcustom org-bibtex-no-export-tags nil + "List of tag(s) that should not be converted to keywords. +This variable is relevant only if `org-bibtex-tags-are-keywords' +is non-nil." + :group 'org-bibtex + :version "24.1" + :type '(repeat :tag "Tag" (string))) + +(defcustom org-bibtex-inherit-tags nil + "Controls whether inherited tags are converted to bibtex keywords. +It is relevant only if `org-bibtex-tags-are-keywords' is non-nil. +Tag inheritance itself is controlled by `org-use-tag-inheritance' +and `org-exclude-tags-from-inheritance'." + :group 'org-bibtex + :version "26.1" + :package-version '(Org . "8.3") + :type 'boolean) + +(defcustom org-bibtex-type-property-name "btype" + "Property in which to store bibtex entry type (e.g., article)." + :group 'org-bibtex + :version "24.1" + :type 'string) + + +;;; Utility functions +(defun org-bibtex-get (property) + (let ((it (let ((org-special-properties + (delete "FILE" (copy-sequence org-special-properties)))) + (or + (org-entry-get (point) (upcase property)) + (org-entry-get (point) (concat org-bibtex-prefix + (upcase property))))))) + (when it (org-trim it)))) + +(defun org-bibtex-put (property value) + (let ((prop (upcase (if (keywordp property) + (substring (symbol-name property) 1) + property)))) + (org-set-property + (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix) + prop) + value))) + +(defun org-bibtex-headline () + "Return a bibtex entry of the given headline as a string." + (letrec ((val (lambda (key lst) (cdr (assoc key lst)))) + (to (lambda (string) (intern (concat ":" string)))) + (from (lambda (key) (substring (symbol-name key) 1))) + (flatten (lambda (&rest lsts) + (apply #'append (mapcar + (lambda (e) + (if (listp e) (apply flatten e) (list e))) + lsts)))) + (id (org-bibtex-get org-bibtex-key-property)) + (type (org-bibtex-get org-bibtex-type-property-name)) + (tags (when org-bibtex-tags-are-keywords + (delq nil + (mapcar + (lambda (tag) + (unless (member tag + (append org-bibtex-tags + org-bibtex-no-export-tags)) + tag)) + (if org-bibtex-inherit-tags + (org-get-tags-at) + (org-get-local-tags-at))))))) + (when type + (let ((entry (format + "@%s{%s,\n%s\n}\n" type id + (mapconcat + (lambda (pair) + (format " %s={%s}" (car pair) (cdr pair))) + (remove nil + (if (and org-bibtex-export-arbitrary-fields + org-bibtex-prefix) + (mapcar + (lambda (kv) + (let ((key (car kv)) (val0 (cdr kv))) + (when (and + (string-match org-bibtex-prefix key) + (not (string= + (downcase (concat org-bibtex-prefix + org-bibtex-type-property-name)) + (downcase key)))) + (cons (downcase (replace-regexp-in-string + org-bibtex-prefix "" key)) + val0)))) + (org-entry-properties nil 'standard)) + (mapcar + (lambda (field) + (let ((value (or (org-bibtex-get (funcall from field)) + (and (eq :title field) + (nth 4 (org-heading-components)))))) + (when value (cons (funcall from field) value)))) + (funcall flatten + (funcall val :required (funcall val (funcall to type) org-bibtex-types)) + (funcall val :optional (funcall val (funcall to type) org-bibtex-types)))))) + ",\n")))) + (with-temp-buffer + (insert entry) + (when tags + (bibtex-beginning-of-entry) + (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t) + (progn (goto-char (match-end 1)) (insert ", ")) + (search-forward ",\n" nil t) + (insert " keywords={},\n") + (search-backward "}," nil t)) + (insert (mapconcat #'identity tags ", "))) + (buffer-string)))))) + +(defun org-bibtex-ask (field) + (unless (assoc field org-bibtex-fields) + (error "Field:%s is not known" field)) + (save-window-excursion + (let* ((name (substring (symbol-name field) 1)) + (buf-name (format "*Bibtex Help %s*" name))) + (with-output-to-temp-buffer buf-name + (princ (cdr (assoc field org-bibtex-fields)))) + (with-current-buffer buf-name (visual-line-mode 1)) + (org-fit-window-to-buffer (get-buffer-window buf-name)) + (let ((result (read-from-minibuffer (format "%s: " name)))) + (when (> (length result) 0) result))))) + +(defun org-bibtex-autokey () + "Generate an autokey for the current headline." + (org-bibtex-put org-bibtex-key-property + (if org-bibtex-autogen-keys + (let* ((entry (org-bibtex-headline)) + (key + (with-temp-buffer + (insert entry) + (bibtex-generate-autokey)))) + ;; test for duplicate IDs if using global ID + (when (and + (equal org-bibtex-key-property "ID") + (featurep 'org-id) + (hash-table-p org-id-locations) + (gethash key org-id-locations)) + (warn "Another entry has the same ID")) + key) + (read-from-minibuffer "id: ")))) + +(defun org-bibtex-fleshout (type &optional optional) + "Fleshout current heading, ensuring all required fields are present. +With optional argument OPTIONAL, also prompt for optional fields." + (let ((val (lambda (key lst) (cdr (assoc key lst)))) + (keyword (lambda (name) (intern (concat ":" (downcase name))))) + (name (lambda (keyword) (substring (symbol-name keyword) 1)))) + (dolist (field (append + (if org-bibtex-treat-headline-as-title + (remove :title (funcall val :required (funcall val type org-bibtex-types))) + (funcall val :required (funcall val type org-bibtex-types))) + (when optional (funcall val :optional (funcall val type org-bibtex-types))))) + (when (consp field) ; or'd pair of fields e.g., (:editor :author) + (let ((present (nth 0 (remove + nil + (mapcar + (lambda (f) + (when (org-bibtex-get (funcall name f)) f)) + field))))) + (setf field (or present (funcall keyword + (completing-read + "Field: " (mapcar name field))))))) + (let ((name (funcall name field))) + (unless (org-bibtex-get name) + (let ((prop (org-bibtex-ask field))) + (when prop (org-bibtex-put name prop))))))) + (when (and type (assoc type org-bibtex-types) + (not (org-bibtex-get org-bibtex-key-property))) + (org-bibtex-autokey))) + + +;;; Bibtex link functions +(org-link-set-parameters "bibtex" + :follow #'org-bibtex-open + :store #'org-bibtex-store-link) + +(defun org-bibtex-open (path) + "Visit the bibliography entry on PATH." + (let* ((search (when (string-match "::\\(.+\\)\\'" path) + (match-string 1 path))) + (path (substring path 0 (match-beginning 0)))) + (org-open-file path t nil search))) + +(defun org-bibtex-store-link () + "Store a link to a BibTeX entry." + (when (eq major-mode 'bibtex-mode) + (let* ((search (org-create-file-search-in-bibtex)) + (link (concat "file:" (abbreviate-file-name buffer-file-name) + "::" search)) + (entry (mapcar ; repair strings enclosed in "..." or {...} + (lambda(c) + (if (string-match + "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c)) + (cons (car c) (match-string 1 (cdr c))) c)) + (save-excursion + (bibtex-beginning-of-entry) + (bibtex-parse-entry))))) + (org-store-link-props + :key (cdr (assoc "=key=" entry)) + :author (or (cdr (assoc "author" entry)) "[no author]") + :editor (or (cdr (assoc "editor" entry)) "[no editor]") + :title (or (cdr (assoc "title" entry)) "[no title]") + :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]") + :journal (or (cdr (assoc "journal" entry)) "[no journal]") + :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]") + :pages (or (cdr (assoc "pages" entry)) "[no pages]") + :url (or (cdr (assoc "url" entry)) "[no url]") + :year (or (cdr (assoc "year" entry)) "[no year]") + :month (or (cdr (assoc "month" entry)) "[no month]") + :address (or (cdr (assoc "address" entry)) "[no address]") + :volume (or (cdr (assoc "volume" entry)) "[no volume]") + :number (or (cdr (assoc "number" entry)) "[no number]") + :annote (or (cdr (assoc "annote" entry)) "[no annotation]") + :series (or (cdr (assoc "series" entry)) "[no series]") + :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]") + :btype (or (cdr (assoc "=type=" entry)) "[no type]") + :type "bibtex" + :link link + :description org-bibtex-description)))) + +(defun org-create-file-search-in-bibtex () + "Create the search string and description for a BibTeX database entry." + ;; Make a good description for this entry, using names, year and the title + ;; Put it into the `description' variable which is dynamically scoped. + (let ((bibtex-autokey-names 1) + (bibtex-autokey-names-stretch 1) + (bibtex-autokey-name-case-convert-function 'identity) + (bibtex-autokey-name-separator " & ") + (bibtex-autokey-additional-names " et al.") + (bibtex-autokey-year-length 4) + (bibtex-autokey-name-year-separator " ") + (bibtex-autokey-titlewords 3) + (bibtex-autokey-titleword-separator " ") + (bibtex-autokey-titleword-case-convert-function 'identity) + (bibtex-autokey-titleword-length 'infty) + (bibtex-autokey-year-title-separator ": ")) + (setq org-bibtex-description (bibtex-generate-autokey))) + ;; Now parse the entry, get the key and return it. + (save-excursion + (bibtex-beginning-of-entry) + (cdr (assoc "=key=" (bibtex-parse-entry))))) + +(defun org-execute-file-search-in-bibtex (s) + "Find the link search string S as a key for a database entry." + (when (eq major-mode 'bibtex-mode) + ;; Yes, we want to do the search in this file. + ;; We construct a regexp that searches for "@entrytype{" followed by the key + (goto-char (point-min)) + (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*" + (regexp-quote s) "[ \t\n]*,") nil t) + (goto-char (match-beginning 0))) + (if (and (match-beginning 0) (equal current-prefix-arg '(16))) + ;; Use double prefix to indicate that any web link should be browsed + (let ((b (current-buffer)) (p (point))) + ;; Restore the window configuration because we just use the web link + (set-window-configuration org-window-config-before-follow-link) + (with-current-buffer b + (goto-char p) + (bibtex-url))) + (recenter 0)) ; Move entry start to beginning of window + ;; return t to indicate that the search is done. + t)) + +;; Finally add the link search function to the right hook. +(add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex) + + +;;; Bibtex <-> Org headline translation functions +(defun org-bibtex (filename) + "Export each headline in the current file to a bibtex entry. +Headlines are exported using `org-bibtex-headline'." + (interactive + (list (read-file-name + "Bibtex file: " nil nil nil + (let ((file (buffer-file-name (buffer-base-buffer)))) + (and file + (file-name-nondirectory + (concat (file-name-sans-extension file) ".bib"))))))) + (let ((error-point + (catch 'bib + (let ((bibtex-entries + (remove nil (org-map-entries + (lambda () + (condition-case nil + (org-bibtex-headline) + (error (throw 'bib (point))))))))) + (with-temp-file filename + (insert (mapconcat #'identity bibtex-entries "\n"))) + (message "Successfully exported %d BibTeX entries to %s" + (length bibtex-entries) filename) nil)))) + (when error-point + (goto-char error-point) + (message "Bibtex error at %S" (nth 4 (org-heading-components)))))) + +(defun org-bibtex-check (&optional optional) + "Check the current headline for required fields. +With prefix argument OPTIONAL also prompt for optional fields." + (interactive "P") + (save-restriction + (org-narrow-to-subtree) + (let ((type (let ((name (org-bibtex-get org-bibtex-type-property-name))) + (when name (intern (concat ":" name)))))) + (when type (org-bibtex-fleshout type optional))))) + +(defun org-bibtex-check-all (&optional optional) + "Check all headlines in the current file. +With prefix argument OPTIONAL also prompt for optional fields." + (interactive) (org-map-entries (lambda () (org-bibtex-check optional)))) + +(defun org-bibtex-create (&optional arg nonew) + "Create a new entry at the given level. +With a prefix arg, query for optional fields as well. +If nonew is t, add data to the headline of the entry at point." + (interactive "P") + (let* ((type (completing-read + "Type: " (mapcar (lambda (type) + (substring (symbol-name (car type)) 1)) + org-bibtex-types) + nil nil (when nonew + (org-bibtex-get org-bibtex-type-property-name)))) + (type (if (keywordp type) type (intern (concat ":" type)))) + (org-bibtex-treat-headline-as-title (if nonew nil t))) + (unless (assoc type org-bibtex-types) + (error "Type:%s is not known" type)) + (if nonew + (org-back-to-heading) + (org-insert-heading) + (let ((title (org-bibtex-ask :title))) + (insert title) + (org-bibtex-put "TITLE" title))) + (org-bibtex-put org-bibtex-type-property-name + (substring (symbol-name type) 1)) + (org-bibtex-fleshout type arg) + (dolist (tag org-bibtex-tags) (org-toggle-tag tag 'on)))) + +(defun org-bibtex-create-in-current-entry (&optional arg) + "Add bibliographical data to the current entry. +With a prefix arg, query for optional fields." + (interactive "P") + (org-bibtex-create arg t)) + +(defun org-bibtex-read () + "Read a bibtex entry and save to `org-bibtex-entries'. +This uses `bibtex-parse-entry'." + (interactive) + (let ((keyword (lambda (str) (intern (concat ":" (downcase str))))) + (clean-space (lambda (str) (replace-regexp-in-string + "[[:space:]\n\r]+" " " str))) + (strip-delim + (lambda (str) ; strip enclosing "..." and {...} + (dolist (pair '((34 . 34) (123 . 125))) + (when (and (> (length str) 1) + (= (aref str 0) (car pair)) + (= (aref str (1- (length str))) (cdr pair))) + (setf str (substring str 1 (1- (length str)))))) str))) + (push (mapcar + (lambda (pair) + (cons (let ((field (funcall keyword (car pair)))) + (pcase field + (:=type= :type) + (:=key= :key) + (_ field))) + (funcall clean-space (funcall strip-delim (cdr pair))))) + (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry))) + org-bibtex-entries))) + +(defun org-bibtex-read-buffer (buffer) + "Read all bibtex entries in BUFFER and save to `org-bibtex-entries'. +Return the number of saved entries." + (interactive "bBuffer: ") + (let ((start-length (length org-bibtex-entries))) + (with-current-buffer buffer + (save-excursion + (goto-char (point-max)) + (while (not (= (point) (point-min))) + (backward-char 1) + (org-bibtex-read) + (bibtex-beginning-of-entry)))) + (let ((added (- (length org-bibtex-entries) start-length))) + (message "Parsed %d entries" added) + added))) + +(defun org-bibtex-read-file (file) + "Read FILE with `org-bibtex-read-buffer'." + (interactive "fFile: ") + (org-bibtex-read-buffer (find-file-noselect file 'nowarn 'rawfile))) + +(defun org-bibtex-write () + "Insert a heading built from the first element of `org-bibtex-entries'." + (interactive) + (when (= (length org-bibtex-entries) 0) + (error "No entries in `org-bibtex-entries'")) + (let* ((entry (pop org-bibtex-entries)) + (org-special-properties nil) ; avoids errors with `org-entry-put' + (val (lambda (field) (cdr (assoc field entry)))) + (togtag (lambda (tag) (org-toggle-tag tag 'on)))) + (org-insert-heading) + (insert (funcall org-bibtex-headline-format-function entry)) + (org-bibtex-put "TITLE" (funcall val :title)) + (org-bibtex-put org-bibtex-type-property-name + (downcase (funcall val :type))) + (dolist (pair entry) + (pcase (car pair) + (:title nil) + (:type nil) + (:key (org-bibtex-put org-bibtex-key-property (cdr pair))) + (:keywords (if org-bibtex-tags-are-keywords + (dolist (kw (split-string (cdr pair) ", *")) + (funcall + togtag + (replace-regexp-in-string + "[^[:alnum:]_@#%]" "" + (replace-regexp-in-string "[ \t]+" "_" kw)))) + (org-bibtex-put (car pair) (cdr pair)))) + (_ (org-bibtex-put (car pair) (cdr pair))))) + (mapc togtag org-bibtex-tags))) + +(defun org-bibtex-yank () + "If kill ring holds a bibtex entry yank it as an Org headline." + (interactive) + (let (entry) + (with-temp-buffer (yank 1) (setf entry (org-bibtex-read))) + (if entry + (org-bibtex-write) + (error "Yanked text does not appear to contain a BibTeX entry")))) + +(defun org-bibtex-import-from-file (file) + "Read bibtex entries from FILE and insert as Org headlines after point." + (interactive "fFile: ") + (dotimes (_ (org-bibtex-read-file file)) + (save-excursion (org-bibtex-write)) + (re-search-forward org-property-end-re) + (open-line 1) (forward-char 1))) + +(defun org-bibtex-export-to-kill-ring () + "Export current headline to kill ring as bibtex entry." + (interactive) + (let ((result (org-bibtex-headline))) + (kill-new result) result)) + +(defun org-bibtex-search (string) + "Search for bibliographical entries in agenda files. +This function relies `org-search-view' to locate results." + (interactive "sSearch string: ") + (let ((org-agenda-overriding-header "Bib search results:") + (org-agenda-search-view-always-boolean t)) + (org-search-view nil + (format "%s +{:%s%s:}" + string (or org-bibtex-prefix "") + org-bibtex-type-property-name)))) + +(provide 'org-bibtex) + +;;; org-bibtex.el ends here diff --git a/elpa/org-9.1.14/org-capture.el b/elpa/org-9.1.14/org-capture.el new file mode 100644 index 00000000..cd54491f --- /dev/null +++ b/elpa/org-9.1.14/org-capture.el @@ -0,0 +1,1960 @@ +;;; org-capture.el --- Fast note taking in Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file contains an alternative implementation of the functionality +;; that used to be provided by org-remember.el. The implementation is more +;; streamlined, can produce more target types (e.g. plain list items or +;; table lines). Also, it does not use a temporary buffer for editing +;; the captured entry - instead it uses an indirect buffer that visits +;; the new entry already in the target buffer (this was an idea by Samuel +;; Wales). John Wiegley's excellent `remember.el' is not needed anymore +;; for this implementation, even though we borrow heavily from its ideas. + +;; This implementation heavily draws on ideas by James TD Smith and +;; Samuel Wales, and, of cause, uses John Wiegley's remember.el as inspiration. + +;;; TODO + +;; - find a clever way to not always insert an annotation maybe a +;; predicate function that can check for conditions for %a to be +;; used. This could be one of the properties. + +;; - Should there be plist members that arrange for properties to be +;; asked for, like James proposed in his RFC? + +;;; Code: + +(require 'cl-lib) +(require 'org) + +(declare-function org-at-encrypted-entry-p "org-crypt" ()) +(declare-function org-clock-update-mode-line "org-clock" (&optional refresh)) +(declare-function org-datetree-find-date-create "org-datetree" (date &optional keep-restriction)) +(declare-function org-decrypt-entry "org-crypt" ()) +(declare-function org-encrypt-entry "org-crypt" ()) +(declare-function org-table-analyze "org-table" ()) +(declare-function org-table-current-dline "org-table" ()) +(declare-function org-table-goto-line "org-table" (N)) + +(defvar org-end-time-was-given) +(defvar org-remember-default-headline) +(defvar org-remember-templates) +(defvar org-table-hlines) +(defvar org-table-current-begin-pos) +(defvar dired-buffers) + +(defvar org-capture-clock-was-started nil + "Internal flag, noting if the clock was started.") + +(defvar org-capture-last-stored-marker (make-marker) + "Marker pointing to the entry most recently stored with `org-capture'.") + +;; The following variable is scoped dynamically by org-protocol +;; to indicate that the link properties have already been stored +(defvar org-capture-link-is-already-stored nil) + +(defvar org-capture-is-refiling nil + "Non-nil when capture process is refiling an entry.") + +(defvar org-capture--prompt-history-table (make-hash-table :test #'equal) + "Hash table for all history lists per prompt.") + +(defvar org-capture--prompt-history nil + "History list for prompt placeholders.") + +(defgroup org-capture nil + "Options concerning capturing new entries." + :tag "Org Capture" + :group 'org) + +(defun org-capture-upgrade-templates (templates) + "Update the template list to the new format. +TEMPLATES is a template list, as in `org-capture-templates'. The +new format unifies all the date/week tree targets into one that +also allows for an optional outline path to specify a target." + (let ((modified-templates + (mapcar + (lambda (entry) + (pcase entry + ;; Match templates with an obsolete "tree" target type. Replace + ;; it with common `file+olp-datetree'. Add new properties + ;; (i.e., `:time-prompt' and `:tree-type') if needed. + (`(,key ,desc ,type (file+datetree . ,path) ,tpl . ,props) + `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl ,@props)) + (`(,key ,desc ,type (file+datetree+prompt . ,path) ,tpl . ,props) + `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl + :time-prompt t ,@props)) + (`(,key ,desc ,type (file+weektree . ,path) ,tpl . ,props) + `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl + :tree-type week ,@props)) + (`(,key ,desc ,type (file+weektree+prompt . ,path) ,tpl . ,props) + `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl + :tree-type week :time-prompt t ,@props)) + ;; Other templates are left unchanged. + (_ entry))) + templates))) + (unless (equal modified-templates templates) + (message "Deprecated date/weektree capture templates changed to `file+olp+datetree'.")) + modified-templates)) + +(defcustom org-capture-templates nil + "Templates for the creation of new entries. + +Each entry is a list with the following items: + +keys The keys that will select the template, as a string, characters + only, for example \"a\" for a template to be selected with a + single key, or \"bt\" for selection with two keys. When using + several keys, keys using the same prefix key must be together + in the list and preceded by a 2-element entry explaining the + prefix key, for example + + (\"b\" \"Templates for marking stuff to buy\") + + The \"C\" key is used by default for quick access to the + customization of the template variable. But if you want to use + that key for a template, you can. + +description A short string describing the template, will be shown during + selection. + +type The type of entry. Valid types are: + entry an Org node, with a headline. Will be filed + as the child of the target entry or as a + top-level entry. + item a plain list item, will be placed in the + first plain list at the target + location. + checkitem a checkbox item. This differs from the + plain list item only is so far as it uses a + different default template. + table-line a new line in the first table at target location. + plain text to be inserted as it is. + +target Specification of where the captured item should be placed. + In Org files, targets usually define a node. Entries will + become children of this node, other types will be added to the + table or list in the body of this node. + + Most target specifications contain a file name. If that file + name is the empty string, it defaults to `org-default-notes-file'. + A file can also be given as a variable or as a function called + with no argument. When an absolute path is not specified for a + target, it is taken as relative to `org-directory'. + + Valid values are: + + (file \"path/to/file\") + Text will be placed at the beginning or end of that file + + (id \"id of existing Org entry\") + File as child of this entry, or in the body of the entry + + (file+headline \"path/to/file\" \"node headline\") + Fast configuration if the target heading is unique in the file + + (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...) + For non-unique headings, the full outline path is safer + + (file+regexp \"path/to/file\" \"regexp to find location\") + File to the entry matching regexp + + (file+olp+datetree \"path/to/file\" \"Level 1 heading\" ...) + Will create a heading in a date tree for today's date. + If no heading is given, the tree will be on top level. + To prompt for date instead of using TODAY, use the + :time-prompt property. To create a week-tree, use the + :tree-type property. + + (file+function \"path/to/file\" function-finding-location) + A function to find the right location in the file + + (clock) + File to the entry that is currently being clocked + + (function function-finding-location) + Most general way: write your own function which both visits + the file and moves point to the right location + +template The template for creating the capture item. If you leave this + empty, an appropriate default template will be used. See below + for more details. Instead of a string, this may also be one of + + (file \"/path/to/template-file\") + (function function-returning-the-template) + + in order to get a template from a file, or dynamically + from a function. + +The rest of the entry is a property list of additional options. Recognized +properties are: + + :prepend Normally newly captured information will be appended at + the target location (last child, last table line, + last list item...). Setting this property will + change that. + + :immediate-finish When set, do not offer to edit the information, just + file it away immediately. This makes sense if the + template only needs information that can be added + automatically. + + :jump-to-captured When set, jump to the captured entry when finished. + + :empty-lines Set this to the number of lines the should be inserted + before and after the new item. Default 0, only common + other value is 1. + + :empty-lines-before Set this to the number of lines the should be inserted + before the new item. Overrides :empty-lines for the + number lines inserted before. + + :empty-lines-after Set this to the number of lines the should be inserted + after the new item. Overrides :empty-lines for the + number of lines inserted after. + + :clock-in Start the clock in this item. + + :clock-keep Keep the clock running when filing the captured entry. + + :clock-resume Start the interrupted clock when finishing the capture. + Note that :clock-keep has precedence over :clock-resume. + When setting both to t, the current clock will run and + the previous one will not be resumed. + + :time-prompt Prompt for a date/time to be used for date/week trees + and when filling the template. + + :tree-type When `week', make a week tree instead of the month tree. + + :unnarrowed Do not narrow the target buffer, simply show the + full buffer. Default is to narrow it so that you + only see the new stuff. + + :table-line-pos Specification of the location in the table where the + new line should be inserted. It should be a string like + \"II-3\", meaning that the new line should become the + third line before the second horizontal separator line. + + :kill-buffer If the target file was not yet visited by a buffer when + capture was invoked, kill the buffer again after capture + is finalized. + +The template defines the text to be inserted. Often this is an +Org mode entry (so the first line should start with a star) that +will be filed as a child of the target headline. It can also be +freely formatted text. Furthermore, the following %-escapes will +be replaced with content and expanded: + + %[pathname] Insert the contents of the file given by + `pathname'. These placeholders are expanded at the very + beginning of the process so they can be used to extend the + current template. + %(sexp) Evaluate elisp `(sexp)' and replace it with the results. + Only placeholders pre-existing within the template, or + introduced with %[pathname] are expanded this way. Since this + happens after expanding non-interactive %-escapes, those can + be used to fill the expression. + %<...> The result of format-time-string on the ... format specification. + %t Time stamp, date only. The time stamp is the current time, + except when called from agendas with `\\[org-agenda-capture]' or + with `org-capture-use-agenda-date' set. + %T Time stamp as above, with date and time. + %u, %U Like the above, but inactive time stamps. + %i Initial content, copied from the active region. If %i is + indented, the entire inserted text will be indented as well. + %a Annotation, normally the link created with `org-store-link'. + %A Like %a, but prompt for the description part. + %l Like %a, but only insert the literal link. + %c Current kill ring head. + %x Content of the X clipboard. + %k Title of currently clocked task. + %K Link to currently clocked task. + %n User name (taken from the variable `user-full-name'). + %f File visited by current buffer when org-capture was called. + %F Full path of the file or directory visited by current buffer. + %:keyword Specific information for certain link types, see below. + %^g Prompt for tags, with completion on tags in target file. + %^G Prompt for tags, with completion on all tags in all agenda files. + %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U. + You may define a prompt like: %^{Please specify birthday}t. + The default date is that of %t, see above. + %^C Interactive selection of which kill or clip to use. + %^L Like %^C, but insert as link. + %^{prop}p Prompt the user for a value for property `prop'. + %^{prompt} Prompt the user for a string and replace this sequence with it. + A default value and a completion table ca be specified like this: + %^{prompt|default|completion2|completion3|...}. + %? After completing the template, position cursor here. + %\\1 ... %\\N Insert the text entered at the nth %^{prompt}, where N + is a number, starting from 1. + +Apart from these general escapes, you can access information specific to +the link type that is created. For example, calling `org-capture' in emails +or in Gnus will record the author and the subject of the message, which you +can access with \"%:from\" and \"%:subject\", respectively. Here is a +complete list of what is recorded for each link type. + +Link type | Available information +------------------------+------------------------------------------------------ +bbdb | %:type %:name %:company +vm, wl, mh, mew, rmail, | %:type %:subject %:message-id +gnus | %:from %:fromname %:fromaddress + | %:to %:toname %:toaddress + | %:fromto (either \"to NAME\" or \"from NAME\") + | %:date %:date-timestamp (as active timestamp) + | %:date-timestamp-inactive (as inactive timestamp) +gnus | %:group, for messages also all email fields +eww, w3, w3m | %:type %:url +info | %:type %:file %:node +calendar | %:type %:date + +When you need to insert a literal percent sign in the template, +you can escape ambiguous cases with a backward slash, e.g., \\%i." + :group 'org-capture + :version "24.1" + :set (lambda (s v) (set s (org-capture-upgrade-templates v))) + :type + (let ((file-variants '(choice :tag "Filename " + (file :tag "Literal") + (function :tag "Function") + (variable :tag "Variable") + (sexp :tag "Form")))) + `(repeat + (choice :value ("" "" entry (file "~/org/notes.org") "") + (list :tag "Multikey description" + (string :tag "Keys ") + (string :tag "Description")) + (list :tag "Template entry" + (string :tag "Keys ") + (string :tag "Description ") + (choice :tag "Capture Type " :value entry + (const :tag "Org entry" entry) + (const :tag "Plain list item" item) + (const :tag "Checkbox item" checkitem) + (const :tag "Plain text" plain) + (const :tag "Table line" table-line)) + (choice :tag "Target location" + (list :tag "File" + (const :format "" file) + ,file-variants) + (list :tag "ID" + (const :format "" id) + (string :tag " ID")) + (list :tag "File & Headline" + (const :format "" file+headline) + ,file-variants + (string :tag " Headline")) + (list :tag "File & Outline path" + (const :format "" file+olp) + ,file-variants + (repeat :tag "Outline path" :inline t + (string :tag "Headline"))) + (list :tag "File & Regexp" + (const :format "" file+regexp) + ,file-variants + (regexp :tag " Regexp")) + (list :tag "File [ & Outline path ] & Date tree" + (const :format "" file+olp+datetree) + ,file-variants + (option (repeat :tag "Outline path" :inline t + (string :tag "Headline")))) + (list :tag "File & function" + (const :format "" file+function) + ,file-variants + (sexp :tag " Function")) + (list :tag "Current clocking task" + (const :format "" clock)) + (list :tag "Function" + (const :format "" function) + (sexp :tag " Function"))) + (choice :tag "Template " + (string) + (list :tag "File" + (const :format "" file) + (file :tag "Template file")) + (list :tag "Function" + (const :format "" function) + (function :tag "Template function"))) + (plist :inline t + ;; Give the most common options as checkboxes + :options (((const :format "%v " :prepend) (const t)) + ((const :format "%v " :immediate-finish) (const t)) + ((const :format "%v " :jump-to-captured) (const t)) + ((const :format "%v " :empty-lines) (const 1)) + ((const :format "%v " :empty-lines-before) (const 1)) + ((const :format "%v " :empty-lines-after) (const 1)) + ((const :format "%v " :clock-in) (const t)) + ((const :format "%v " :clock-keep) (const t)) + ((const :format "%v " :clock-resume) (const t)) + ((const :format "%v " :time-prompt) (const t)) + ((const :format "%v " :tree-type) (const week)) + ((const :format "%v " :unnarrowed) (const t)) + ((const :format "%v " :table-line-pos) (string)) + ((const :format "%v " :kill-buffer) (const t))))))))) + +(defcustom org-capture-before-finalize-hook nil + "Hook that is run right before a capture process is finalized. +The capture buffer is still current when this hook runs and it is +widened to the entire buffer." + :group 'org-capture + :version "24.1" + :type 'hook) + +(defcustom org-capture-after-finalize-hook nil + "Hook that is run right after a capture process is finalized. +Suitable for window cleanup." + :group 'org-capture + :version "24.1" + :type 'hook) + +(defcustom org-capture-prepare-finalize-hook nil + "Hook that is run before the finalization starts. +The capture buffer is current and still narrowed." + :group 'org-capture + :version "24.1" + :type 'hook) + +(defcustom org-capture-bookmark t + "When non-nil, add a bookmark pointing at the last stored +position when capturing." + :group 'org-capture + :version "24.3" + :type 'boolean) + +;;; The property list for keeping information about the capture process + +(defvar org-capture-plist nil + "Plist for the current capture process, global, to avoid having to pass it.") + +(defvar org-capture-current-plist nil + "Local variable holding the plist in a capture buffer. +This is used to store the plist for use when finishing a capture process +because another such process might have changed the global variable by then. + +Each time a new capture buffer has been set up, the global `org-capture-plist' +is copied to this variable, which is local in the indirect buffer.") + +(defvar org-capture-clock-keep nil + "Local variable to store the value of the :clock-keep parameter. +This is needed in case org-capture-finalize is called interactively.") + +(defun org-capture-put (&rest stuff) + "Add properties to the capture property list `org-capture-plist'." + (while stuff + (setq org-capture-plist (plist-put org-capture-plist + (pop stuff) (pop stuff))))) +(defun org-capture-get (prop &optional local) + "Get properties from the capture property list `org-capture-plist'. +When LOCAL is set, use the local variable `org-capture-current-plist', +this is necessary after initialization of the capture process, +to avoid conflicts with other active capture processes." + (plist-get (if local org-capture-current-plist org-capture-plist) prop)) + +(defun org-capture-member (prop &optional local) + "Is PROP a property in `org-capture-plist'. +When LOCAL is set, use the local variable `org-capture-current-plist', +this is necessary after initialization of the capture process, +to avoid conflicts with other active capture processes." + (plist-get (if local org-capture-current-plist org-capture-plist) prop)) + +;;; The minor mode + +(defvar org-capture-mode-map (make-sparse-keymap) + "Keymap for `org-capture-mode', a minor mode. +Use this map to set additional keybindings for when Org mode is used +for a capture buffer.") + +(defvar org-capture-mode-hook nil + "Hook for the minor `org-capture-mode'.") + +(define-minor-mode org-capture-mode + "Minor mode for special key bindings in a capture buffer. + +Turning on this mode runs the normal hook `org-capture-mode-hook'." + nil " Rem" org-capture-mode-map + (setq-local + header-line-format + (substitute-command-keys + "\\Capture buffer. Finish \ +`\\[org-capture-finalize]', refile `\\[org-capture-refile]', \ +abort `\\[org-capture-kill]'."))) +(define-key org-capture-mode-map "\C-c\C-c" 'org-capture-finalize) +(define-key org-capture-mode-map "\C-c\C-k" 'org-capture-kill) +(define-key org-capture-mode-map "\C-c\C-w" 'org-capture-refile) + +;;; The main commands + +(defvar org-capture-initial nil) +(defvar org-capture-entry nil) + +;;;###autoload +(defun org-capture-string (string &optional keys) + "Capture STRING with the template selected by KEYS." + (interactive "sInitial text: \n") + (let ((org-capture-initial string) + (org-capture-entry (org-capture-select-template keys))) + (org-capture))) + +(defcustom org-capture-templates-contexts nil + "Alist of capture templates and valid contexts. + +For example, if you have a capture template \"c\" and you want +this template to be accessible only from `message-mode' buffers, +use this: + + \\='((\"c\" ((in-mode . \"message-mode\")))) + +Here are the available contexts definitions: + + in-file: command displayed only in matching files + in-mode: command displayed only in matching modes + not-in-file: command not displayed in matching files + not-in-mode: command not displayed in matching modes + in-buffer: command displayed only in matching buffers +not-in-buffer: command not displayed in matching buffers + [function]: a custom function taking no argument + +If you define several checks, the agenda command will be +accessible if there is at least one valid check. + +You can also bind a key to another capture template depending on +contextual rules. + + \\='((\"c\" \"d\" ((in-mode . \"message-mode\")))) + +Here it means: in `message-mode buffers', use \"c\" as the +key for the capture template otherwise associated with \"d\". +\(The template originally associated with \"d\" is not displayed +to avoid duplicates.)" + :version "24.3" + :group 'org-capture + :type '(repeat (list :tag "Rule" + (string :tag " Capture key") + (string :tag "Replace by template") + (repeat :tag "Available when" + (choice + (cons :tag "Condition" + (choice + (const :tag "In file" in-file) + (const :tag "Not in file" not-in-file) + (const :tag "In buffer" in-buffer) + (const :tag "Not in buffer" not-in-buffer) + (const :tag "In mode" in-mode) + (const :tag "Not in mode" not-in-mode)) + (regexp)) + (function :tag "Custom function")))))) + +(defcustom org-capture-use-agenda-date nil + "Non-nil means use the date at point when capturing from agendas. +When nil, you can still capture using the date at point with +`\\[org-agenda-capture]'." + :group 'org-capture + :version "24.3" + :type 'boolean) + +;;;###autoload +(defun org-capture (&optional goto keys) + "Capture something. +\\ +This will let you select a template from `org-capture-templates', and +then file the newly captured information. The text is immediately +inserted at the target location, and an indirect buffer is shown where +you can edit it. Pressing `\\[org-capture-finalize]' brings you back to the \ +previous +state of Emacs, so that you can continue your work. + +When called interactively with a `\\[universal-argument]' prefix argument \ +GOTO, don't +capture anything, just go to the file/headline where the selected +template stores its notes. + +With a `\\[universal-argument] \\[universal-argument]' prefix argument, go to \ +the last note stored. + +When called with a `C-0' (zero) prefix, insert a template at point. + +When called with a `C-1' (one) prefix, force prompting for a date when +a datetree entry is made. + +ELisp programs can set KEYS to a string associated with a template +in `org-capture-templates'. In this case, interactive selection +will be bypassed. + +If `org-capture-use-agenda-date' is non-nil, capturing from the +agenda will use the date at point as the default date. Then, a +`C-1' prefix will tell the capture process to use the HH:MM time +of the day at point (if any) or the current HH:MM time." + (interactive "P") + (when (and org-capture-use-agenda-date + (eq major-mode 'org-agenda-mode)) + (setq org-overriding-default-time + (org-get-cursor-date (equal goto 1)))) + (cond + ((equal goto '(4)) (org-capture-goto-target)) + ((equal goto '(16)) (org-capture-goto-last-stored)) + (t + (let* ((orig-buf (current-buffer)) + (annotation (if (and (boundp 'org-capture-link-is-already-stored) + org-capture-link-is-already-stored) + (plist-get org-store-link-plist :annotation) + (ignore-errors (org-store-link nil)))) + (entry (or org-capture-entry (org-capture-select-template keys))) + initial) + (setq initial (or org-capture-initial + (and (org-region-active-p) + (buffer-substring (point) (mark))))) + (when (stringp initial) + (remove-text-properties 0 (length initial) '(read-only t) initial)) + (when (stringp annotation) + (remove-text-properties 0 (length annotation) + '(read-only t) annotation)) + (cond + ((equal entry "C") + (customize-variable 'org-capture-templates)) + ((equal entry "q") + (user-error "Abort")) + (t + (org-capture-set-plist entry) + (org-capture-get-template) + (org-capture-put :original-buffer orig-buf + :original-file (or (buffer-file-name orig-buf) + (and (featurep 'dired) + (car (rassq orig-buf + dired-buffers)))) + :original-file-nondirectory + (and (buffer-file-name orig-buf) + (file-name-nondirectory + (buffer-file-name orig-buf))) + :annotation annotation + :initial initial + :return-to-wconf (current-window-configuration) + :default-time + (or org-overriding-default-time + (org-current-time))) + (org-capture-set-target-location) + (condition-case error + (org-capture-put :template (org-capture-fill-template)) + ((error quit) + (if (get-buffer "*Capture*") (kill-buffer "*Capture*")) + (error "Capture abort: %s" error))) + + (setq org-capture-clock-keep (org-capture-get :clock-keep)) + (if (equal goto 0) + ;;insert at point + (org-capture-insert-template-here) + (condition-case error + (org-capture-place-template + (eq (car (org-capture-get :target)) 'function)) + ((error quit) + (if (and (buffer-base-buffer (current-buffer)) + (string-prefix-p "CAPTURE-" (buffer-name))) + (kill-buffer (current-buffer))) + (set-window-configuration (org-capture-get :return-to-wconf)) + (error "Capture template `%s': %s" + (org-capture-get :key) + (nth 1 error)))) + (if (and (derived-mode-p 'org-mode) + (org-capture-get :clock-in)) + (condition-case nil + (progn + (if (org-clock-is-active) + (org-capture-put :interrupted-clock + (copy-marker org-clock-marker))) + (org-clock-in) + (setq-local org-capture-clock-was-started t)) + (error + "Could not start the clock in this capture buffer"))) + (if (org-capture-get :immediate-finish) + (org-capture-finalize))))))))) + +(defun org-capture-get-template () + "Get the template from a file or a function if necessary." + (let ((txt (org-capture-get :template)) file) + (cond + ((and (listp txt) (eq (car txt) 'file)) + (if (file-exists-p + (setq file (expand-file-name (nth 1 txt) org-directory))) + (setq txt (org-file-contents file)) + (setq txt (format "* Template file %s not found" (nth 1 txt))))) + ((and (listp txt) (eq (car txt) 'function)) + (if (fboundp (nth 1 txt)) + (setq txt (funcall (nth 1 txt))) + (setq txt (format "* Template function %s not found" (nth 1 txt))))) + ((not txt) (setq txt "")) + ((stringp txt)) + (t (setq txt "* Invalid capture template"))) + (org-capture-put :template txt))) + +(defun org-capture-finalize (&optional stay-with-capture) + "Finalize the capture process. +With prefix argument STAY-WITH-CAPTURE, jump to the location of the +captured item after finalizing." + (interactive "P") + (when (org-capture-get :jump-to-captured) + (setq stay-with-capture t)) + (unless (and org-capture-mode + (buffer-base-buffer (current-buffer))) + (error "This does not seem to be a capture buffer for Org mode")) + + (run-hooks 'org-capture-prepare-finalize-hook) + + ;; Did we start the clock in this capture buffer? + (when (and org-capture-clock-was-started + org-clock-marker + (eq (marker-buffer org-clock-marker) (buffer-base-buffer)) + (>= org-clock-marker (point-min)) + (< org-clock-marker (point-max))) + ;; Looks like the clock we started is still running. + (if org-capture-clock-keep + ;; User may have completed clocked heading from the template. + ;; Refresh clock mode line. + (org-clock-update-mode-line t) + ;; Clock out. Possibly resume interrupted clock. + (let (org-log-note-clock-out) (org-clock-out)) + (when (and (org-capture-get :clock-resume 'local) + (markerp (org-capture-get :interrupted-clock 'local)) + (buffer-live-p (marker-buffer + (org-capture-get :interrupted-clock 'local)))) + (let ((clock-in-task (org-capture-get :interrupted-clock 'local))) + (org-with-point-at clock-in-task (org-clock-in))) + (message "Interrupted clock has been resumed")))) + + (let ((abort-note nil)) + ;; Store the size of the capture buffer + (org-capture-put :captured-entry-size (- (point-max) (point-min))) + (widen) + ;; Store the insertion point in the target buffer + (org-capture-put :insertion-point (point)) + + (if org-note-abort + (let ((beg (org-capture-get :begin-marker 'local)) + (end (org-capture-get :end-marker 'local))) + (if (not (and beg end)) (setq abort-note 'dirty) + (setq abort-note t) + (org-with-wide-buffer (kill-region beg end)))) + + ;; Postprocessing: Update Statistics cookies, do the sorting + (when (derived-mode-p 'org-mode) + (save-excursion + (when (ignore-errors (org-back-to-heading)) + (org-update-parent-todo-statistics) + (org-update-checkbox-count))) + ;; FIXME Here we should do the sorting + ;; If we have added a table line, maybe recompute? + (when (and (eq (org-capture-get :type 'local) 'table-line) + (org-at-table-p)) + (if (org-table-get-stored-formulas) + (org-table-recalculate 'all) ;; FIXME: Should we iterate??? + (org-table-align)))) + ;; Store this place as the last one where we stored something + ;; Do the marking in the base buffer, so that it makes sense after + ;; the indirect buffer has been killed. + (org-capture-store-last-position) + + ;; Run the hook + (run-hooks 'org-capture-before-finalize-hook)) + + (when (org-capture-get :decrypted) + (save-excursion + (goto-char (org-capture-get :decrypted)) + (org-encrypt-entry))) + + ;; Kill the indirect buffer + (save-buffer) + (let ((return-wconf (org-capture-get :return-to-wconf 'local)) + (new-buffer (org-capture-get :new-buffer 'local)) + (kill-buffer (org-capture-get :kill-buffer 'local)) + (base-buffer (buffer-base-buffer (current-buffer)))) + + ;; Kill the indirect buffer + (kill-buffer (current-buffer)) + + ;; Narrow back the target buffer to its previous state + (with-current-buffer (org-capture-get :buffer) + (let ((reg (org-capture-get :initial-target-region)) + (pos (org-capture-get :initial-target-position)) + (ipt (org-capture-get :insertion-point)) + (size (org-capture-get :captured-entry-size))) + (if (not reg) + (widen) + (cond ((< ipt (car reg)) + ;; insertion point is before the narrowed region + (narrow-to-region (+ size (car reg)) (+ size (cdr reg)))) + ((> ipt (cdr reg)) + ;; insertion point is after the narrowed region + (narrow-to-region (car reg) (cdr reg))) + (t + ;; insertion point is within the narrowed region + (narrow-to-region (car reg) (+ size (cdr reg))))) + ;; now place back the point at its original position + (if (< ipt (car reg)) + (goto-char (+ size pos)) + (goto-char (if (< ipt pos) (+ size pos) pos)))))) + + ;; Kill the target buffer if that is desired + (when (and base-buffer new-buffer kill-buffer) + (with-current-buffer base-buffer (save-buffer)) + (kill-buffer base-buffer)) + + ;; Restore the window configuration before capture + (set-window-configuration return-wconf)) + + (run-hooks 'org-capture-after-finalize-hook) + ;; Special cases + (cond + (abort-note + (cl-case abort-note + (clean + (message "Capture process aborted and target buffer cleaned up")) + (dirty + (error "Capture process aborted, but target buffer could not be \ +cleaned up correctly")))) + (stay-with-capture + (org-capture-goto-last-stored))) + ;; Return if we did store something + (not abort-note))) + +(defun org-capture-refile () + "Finalize the current capture and then refile the entry. +Refiling is done from the base buffer, because the indirect buffer is then +already gone. Any prefix argument will be passed to the refile command." + (interactive) + (unless (eq (org-capture-get :type 'local) 'entry) + (user-error "Refiling from a capture buffer makes only sense \ +for `entry'-type templates")) + (let* ((base (or (buffer-base-buffer) (current-buffer))) + (pos (make-marker)) + (org-capture-is-refiling t) + (kill-buffer (org-capture-get :kill-buffer 'local)) + (jump-to-captured (org-capture-get :jump-to-captured 'local))) + ;; Since `org-capture-finalize' may alter buffer contents (e.g., + ;; empty lines) around entry, use a marker to refer to the + ;; headline to be refiled. Place the marker in the base buffer, + ;; as the current indirect one is going to be killed. + (set-marker pos (save-excursion (org-back-to-heading t) (point)) base) + ;; `org-capture-finalize' calls `org-capture-goto-last-stored' too + ;; early. We want to wait for the refiling to be over, so we + ;; control when the latter function is called. + (org-capture-put :kill-buffer nil :jump-to-captured nil) + (unwind-protect + (progn + (org-capture-finalize) + (save-window-excursion + (with-current-buffer base + (org-with-wide-buffer + (goto-char pos) + (call-interactively 'org-refile)))) + (when kill-buffer (kill-buffer base)) + (when jump-to-captured (org-capture-goto-last-stored))) + (set-marker pos nil)))) + +(defun org-capture-kill () + "Abort the current capture process." + (interactive) + ;; FIXME: This does not do the right thing, we need to remove the + ;; new stuff by hand it is easy: undo, then kill the buffer + (let ((org-note-abort t) + (org-capture-before-finalize-hook nil)) + (org-capture-finalize))) + +(defun org-capture-goto-last-stored () + "Go to the location where the last capture note was stored." + (interactive) + (org-goto-marker-or-bmk org-capture-last-stored-marker + (plist-get org-bookmark-names-plist + :last-capture)) + (message "This is the last note stored by a capture process")) + +;;; Supporting functions for handling the process + +(defun org-capture-put-target-region-and-position () + "Store the initial region with `org-capture-put'." + (org-capture-put + :initial-target-region + ;; Check if the buffer is currently narrowed + (when (org-buffer-narrowed-p) + (cons (point-min) (point-max)))) + ;; store the current point + (org-capture-put :initial-target-position (point))) + +(defvar org-time-was-given) ; dynamically scoped parameter +(defun org-capture-set-target-location (&optional target) + "Find TARGET buffer and position. +Store them in the capture property list." + (let ((target-entry-p t)) + (save-excursion + (pcase (or target (org-capture-get :target)) + (`(file ,path) + (set-buffer (org-capture-target-buffer path)) + (org-capture-put-target-region-and-position) + (widen) + (setq target-entry-p nil)) + (`(id ,id) + (pcase (org-id-find id) + (`(,path . ,position) + (set-buffer (org-capture-target-buffer path)) + (widen) + (org-capture-put-target-region-and-position) + (goto-char position)) + (_ (error "Cannot find target ID \"%s\"" id)))) + (`(file+headline ,path ,headline) + (set-buffer (org-capture-target-buffer path)) + ;; Org expects the target file to be in Org mode, otherwise + ;; it throws an error. However, the default notes files + ;; should work out of the box. In this case, we switch it to + ;; Org mode. + (unless (derived-mode-p 'org-mode) + (org-display-warning + (format "Capture requirement: switching buffer %S to Org mode" + (current-buffer))) + (org-mode)) + (org-capture-put-target-region-and-position) + (widen) + (goto-char (point-min)) + (if (re-search-forward (format org-complex-heading-regexp-format + (regexp-quote headline)) + nil t) + (beginning-of-line) + (goto-char (point-max)) + (unless (bolp) (insert "\n")) + (insert "* " headline "\n") + (beginning-of-line 0))) + (`(file+olp ,path . ,outline-path) + (let ((m (org-find-olp (cons (org-capture-expand-file path) + outline-path)))) + (set-buffer (marker-buffer m)) + (org-capture-put-target-region-and-position) + (widen) + (goto-char m) + (set-marker m nil))) + (`(file+regexp ,path ,regexp) + (set-buffer (org-capture-target-buffer path)) + (org-capture-put-target-region-and-position) + (widen) + (goto-char (point-min)) + (if (not (re-search-forward regexp nil t)) + (error "No match for target regexp in file %s" path) + (goto-char (if (org-capture-get :prepend) + (match-beginning 0) + (match-end 0))) + (org-capture-put :exact-position (point)) + (setq target-entry-p + (and (derived-mode-p 'org-mode) (org-at-heading-p))))) + (`(file+olp+datetree ,path . ,outline-path) + (let ((m (if outline-path + (org-find-olp (cons (org-capture-expand-file path) + outline-path)) + (set-buffer (org-capture-target-buffer path)) + (point-marker)))) + (set-buffer (marker-buffer m)) + (org-capture-put-target-region-and-position) + (widen) + (goto-char m) + (set-marker m nil) + (require 'org-datetree) + (org-capture-put-target-region-and-position) + (widen) + ;; Make a date/week tree entry, with the current date (or + ;; yesterday, if we are extending dates for a couple of hours) + (funcall + (if (eq (org-capture-get :tree-type) 'week) + #'org-datetree-find-iso-week-create + #'org-datetree-find-date-create) + (calendar-gregorian-from-absolute + (cond + (org-overriding-default-time + ;; Use the overriding default time. + (time-to-days org-overriding-default-time)) + ((or (org-capture-get :time-prompt) + (equal current-prefix-arg 1)) + ;; Prompt for date. + (let ((prompt-time (org-read-date + nil t nil "Date for tree entry:" + (current-time)))) + (org-capture-put + :default-time + (cond ((and (or (not (boundp 'org-time-was-given)) + (not org-time-was-given)) + (not (= (time-to-days prompt-time) (org-today)))) + ;; Use 00:00 when no time is given for another + ;; date than today? + (apply #'encode-time + (append `(0 0 ,org-extend-today-until) + (cl-cdddr (decode-time prompt-time))))) + ((string-match "\\([^ ]+\\)--?[^ ]+[ ]+\\(.*\\)" + org-read-date-final-answer) + ;; Replace any time range by its start. + (apply #'encode-time + (org-read-date-analyze + (replace-match "\\1 \\2" nil nil + org-read-date-final-answer) + prompt-time (decode-time prompt-time)))) + (t prompt-time))) + (time-to-days prompt-time))) + (t + ;; Current date, possibly corrected for late night + ;; workers. + (org-today)))) + ;; the following is the keep-restriction argument for + ;; org-datetree-find-date-create + (if outline-path 'subtree-at-point)))) + (`(file+function ,path ,function) + (set-buffer (org-capture-target-buffer path)) + (org-capture-put-target-region-and-position) + (widen) + (funcall function) + (org-capture-put :exact-position (point)) + (setq target-entry-p + (and (derived-mode-p 'org-mode) (org-at-heading-p)))) + (`(function ,fun) + (funcall fun) + (org-capture-put :exact-position (point)) + (setq target-entry-p + (and (derived-mode-p 'org-mode) (org-at-heading-p)))) + (`(clock) + (if (and (markerp org-clock-hd-marker) + (marker-buffer org-clock-hd-marker)) + (progn (set-buffer (marker-buffer org-clock-hd-marker)) + (org-capture-put-target-region-and-position) + (widen) + (goto-char org-clock-hd-marker)) + (error "No running clock that could be used as capture target"))) + (target (error "Invalid capture target specification: %S" target))) + + (org-capture-put :buffer (current-buffer) + :pos (point) + :target-entry-p target-entry-p + :decrypted + (and (featurep 'org-crypt) + (org-at-encrypted-entry-p) + (save-excursion + (org-decrypt-entry) + (and (org-back-to-heading t) (point)))))))) + +(defun org-capture-expand-file (file) + "Expand functions, symbols and file names for FILE. +When FILE is a function, call it. When it is a form, evaluate +it. When it is a variable, return its value. When it is +a string, treat it as a file name, possibly expanding it +according to `org-directory', and return it. If it is the empty +string, however, return `org-default-notes-file'. In any other +case, raise an error." + (let ((location (cond ((equal file "") org-default-notes-file) + ((stringp file) (expand-file-name file org-directory)) + ((functionp file) (funcall file)) + ((and (symbolp file) (boundp file)) (symbol-value file)) + (t nil)))) + (or (org-string-nw-p location) + (error "Invalid file location: %S" location)))) + +(defun org-capture-target-buffer (file) + "Get a buffer for FILE. +FILE is a generalized file location, as handled by +`org-capture-expand-file'." + (let ((file (org-capture-expand-file file))) + (or (org-find-base-buffer-visiting file) + (progn (org-capture-put :new-buffer t) + (find-file-noselect file))))) + +(defun org-capture-place-template (&optional inhibit-wconf-store) + "Insert the template at the target location, and display the buffer. +When `inhibit-wconf-store', don't store the window configuration, as it +may have been stored before." + (unless inhibit-wconf-store + (org-capture-put :return-to-wconf (current-window-configuration))) + (delete-other-windows) + (org-switch-to-buffer-other-window + (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE")) + (widen) + (outline-show-all) + (goto-char (org-capture-get :pos)) + (setq-local outline-level 'org-outline-level) + (pcase (org-capture-get :type) + ((or `nil `entry) (org-capture-place-entry)) + (`table-line (org-capture-place-table-line)) + (`plain (org-capture-place-plain-text)) + (`item (org-capture-place-item)) + (`checkitem (org-capture-place-item))) + (org-capture-mode 1) + (setq-local org-capture-current-plist org-capture-plist)) + +(defun org-capture-place-entry () + "Place the template as a new Org entry." + (let ((reversed? (org-capture-get :prepend)) + (level 1)) + (when (org-capture-get :exact-position) + (goto-char (org-capture-get :exact-position))) + (cond + ;; Insert as a child of the current entry. + ((org-capture-get :target-entry-p) + (setq level (org-get-valid-level + (if (org-at-heading-p) (org-outline-level) 1) + 1)) + (if reversed? (outline-next-heading) (org-end-of-subtree t t))) + ;; Insert as a top-level entry at the beginning of the file. + (reversed? + (goto-char (point-min)) + (unless (org-at-heading-p) (outline-next-heading))) + ;; Otherwise, insert as a top-level entry at the end of the file. + (t (goto-char (point-max)))) + (unless (bolp) (insert "\n")) + (org-capture-empty-lines-before) + (let ((beg (point)) + (template (org-capture-get :template))) + (org-capture-verify-tree template) + (org-paste-subtree level template 'for-yank) + (org-capture-empty-lines-after) + (org-capture-position-for-last-stored beg) + (unless (org-at-heading-p) (outline-next-heading)) + (let ((end (point))) + (org-capture-mark-kill-region beg end) + (org-capture-narrow beg end) + (when (or (re-search-backward "%\\?" beg t) + (re-search-forward "%\\?" end t)) + (replace-match "")))))) + +(defun org-capture-place-item () + "Place the template as a new plain list item." + (let* ((txt (org-capture-get :template)) + (target-entry-p (org-capture-get :target-entry-p)) + (ind 0) + beg end) + (if (org-capture-get :exact-position) + (goto-char (org-capture-get :exact-position)) + (cond + ((not target-entry-p) + ;; Insert as top-level entry, either at beginning or at end of file + (setq beg (point-min) end (point-max))) + (t + (setq beg (1+ (point-at-eol)) + end (save-excursion (outline-next-heading) (point))))) + (setq ind nil) + (if (org-capture-get :prepend) + (progn + (goto-char beg) + (when (org-list-search-forward (org-item-beginning-re) end t) + (goto-char (match-beginning 0)) + (setq ind (org-get-indentation)))) + (goto-char end) + (when (org-list-search-backward (org-item-beginning-re) beg t) + (setq ind (org-get-indentation)) + (org-end-of-item))) + (unless ind (goto-char end))) + ;; Remove common indentation + (setq txt (org-remove-indentation txt)) + ;; Make sure this is indeed an item + (unless (string-match (concat "\\`" (org-item-re)) txt) + (setq txt (concat "- " + (mapconcat 'identity (split-string txt "\n") + "\n ")))) + ;; Prepare surrounding empty lines. + (unless (bolp) (insert "\n")) + (org-capture-empty-lines-before) + (setq beg (point)) + (unless (eolp) (save-excursion (insert "\n"))) + (unless ind + (org-indent-line) + (setq ind (org-get-indentation)) + (delete-region beg (point))) + ;; Set the correct indentation, depending on context + (setq ind (make-string ind ?\ )) + (setq txt (concat ind + (mapconcat 'identity (split-string txt "\n") + (concat "\n" ind)) + "\n")) + ;; Insert item. + (insert txt) + (org-capture-empty-lines-after) + (org-capture-position-for-last-stored beg) + (setq end (point)) + (org-capture-mark-kill-region beg end) + (org-capture-narrow beg end) + (if (or (re-search-backward "%\\?" beg t) + (re-search-forward "%\\?" end t)) + (replace-match "")))) + +(defun org-capture-place-table-line () + "Place the template as a table line." + (require 'org-table) + (let* ((txt (org-capture-get :template)) + (target-entry-p (org-capture-get :target-entry-p)) + (table-line-pos (org-capture-get :table-line-pos)) + beg end) + (cond + ((org-capture-get :exact-position) + (goto-char (org-capture-get :exact-position))) + ((not target-entry-p) + ;; Table is not necessarily under a heading + (setq beg (point-min) end (point-max))) + (t + ;; WE are at a heading, limit search to the body + (setq beg (1+ (point-at-eol)) + end (save-excursion (outline-next-heading) (point))))) + (if (re-search-forward org-table-dataline-regexp end t) + (let ((b (org-table-begin)) (e (org-table-end)) (case-fold-search t)) + (goto-char e) + (if (looking-at "[ \t]*#\\+tblfm:") + (forward-line 1)) + (narrow-to-region b (point))) + (goto-char end) + (insert "\n| |\n|----|\n| |\n") + (narrow-to-region (1+ end) (point))) + ;; We are narrowed to the table, or to an empty line if there was no table + + ;; Check if the template is good + (if (not (string-match org-table-dataline-regexp txt)) + (setq txt "| %?Bad template |\n")) + (if (functionp table-line-pos) + (setq table-line-pos (funcall table-line-pos)) + (setq table-line-pos (eval table-line-pos))) + (cond + ((and table-line-pos + (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos)) + (goto-char (point-min)) + ;; we have a complex line specification + (let ((ll (ignore-errors + (save-match-data (org-table-analyze)) + (aref org-table-hlines + (- (match-end 1) (match-beginning 1))))) + (delta (string-to-number (match-string 2 table-line-pos)))) + ;; The user wants a special position in the table + (unless ll + (error "Invalid table line specification \"%s\"" table-line-pos)) + (goto-char org-table-current-begin-pos) + (forward-line (+ ll delta (if (< delta 0) 0 -1))) + (org-table-insert-row 'below) + (beginning-of-line 1) + (delete-region (point) (1+ (point-at-eol))) + (setq beg (point)) + (insert txt) + (setq end (point)))) + ((org-capture-get :prepend) + (goto-char (point-min)) + (re-search-forward org-table-hline-regexp nil t) + (beginning-of-line 1) + (re-search-forward org-table-dataline-regexp nil t) + (beginning-of-line 1) + (setq beg (point)) + (org-table-insert-row) + (beginning-of-line 1) + (delete-region (point) (1+ (point-at-eol))) + (insert txt) + (setq end (point))) + (t + (goto-char (point-max)) + (re-search-backward org-table-dataline-regexp nil t) + (beginning-of-line 1) + (org-table-insert-row 'below) + (beginning-of-line 1) + (delete-region (point) (1+ (point-at-eol))) + (setq beg (point)) + (insert txt) + (setq end (point)))) + (goto-char beg) + (org-capture-position-for-last-stored 'table-line) + (if (or (re-search-backward "%\\?" beg t) + (re-search-forward "%\\?" end t)) + (replace-match "")) + (org-table-align))) + +(defun org-capture-place-plain-text () + "Place the template plainly. +If the target locator points at an Org node, place the template into +the text of the entry, before the first child. If not, place the +template at the beginning or end of the file. +Of course, if exact position has been required, just put it there." + (let* ((txt (org-capture-get :template)) + beg end) + (cond + ((org-capture-get :exact-position) + (goto-char (org-capture-get :exact-position))) + ((and (org-capture-get :target-entry-p) + (bolp) + (looking-at org-outline-regexp)) + ;; we should place the text into this entry + (if (org-capture-get :prepend) + ;; Skip meta data and drawers + (org-end-of-meta-data t) + ;; go to ent of the entry text, before the next headline + (outline-next-heading))) + (t + ;; beginning or end of file + (goto-char (if (org-capture-get :prepend) (point-min) (point-max))))) + (or (bolp) (newline)) + (org-capture-empty-lines-before) + (setq beg (point)) + (insert txt) + (org-capture-empty-lines-after) + (org-capture-position-for-last-stored beg) + (setq end (point)) + (org-capture-mark-kill-region beg (1- end)) + (org-capture-narrow beg (1- end)) + (if (or (re-search-backward "%\\?" beg t) + (re-search-forward "%\\?" end t)) + (replace-match "")))) + +(defun org-capture-mark-kill-region (beg end) + "Mark the region that will have to be killed when aborting capture." + (let ((m1 (copy-marker beg)) + (m2 (copy-marker end t))) + (org-capture-put :begin-marker m1) + (org-capture-put :end-marker m2))) + +(defun org-capture-position-for-last-stored (where) + "Memorize the position that should later become the position of last capture." + (cond + ((integerp where) + (org-capture-put :position-for-last-stored + (move-marker (make-marker) where + (or (buffer-base-buffer (current-buffer)) + (current-buffer))))) + ((eq where 'table-line) + (org-capture-put :position-for-last-stored + (list 'table-line + (org-table-current-dline)))) + (t (error "This should not happen")))) + +(defun org-capture-store-last-position () + "Store the last-captured position." + (let* ((where (org-capture-get :position-for-last-stored 'local)) + (pos (cond + ((markerp where) + (prog1 (marker-position where) + (move-marker where nil))) + ((and (listp where) (eq (car where) 'table-line)) + (if (org-at-table-p) + (save-excursion + (org-table-goto-line (nth 1 where)) + (point-at-bol)) + (point)))))) + (with-current-buffer (buffer-base-buffer (current-buffer)) + (org-with-point-at pos + (when org-capture-bookmark + (let ((bookmark (plist-get org-bookmark-names-plist :last-capture))) + (when bookmark (with-demoted-errors (bookmark-set bookmark))))) + (move-marker org-capture-last-stored-marker (point)))))) + +(defun org-capture-narrow (beg end) + "Narrow, unless configuration says not to narrow." + (unless (org-capture-get :unnarrowed) + (narrow-to-region beg end) + (goto-char beg))) + +(defun org-capture-empty-lines-before (&optional n) + "Set the correct number of empty lines before the insertion point. +Point will be after the empty lines, so insertion can directly be done." + (setq n (or n (org-capture-get :empty-lines-before) + (org-capture-get :empty-lines) 0)) + (let ((pos (point))) + (org-back-over-empty-lines) + (delete-region (point) pos) + (if (> n 0) (newline n)))) + +(defun org-capture-empty-lines-after (&optional n) + "Set the correct number of empty lines after the inserted string. +Point will remain at the first line after the inserted text." + (setq n (or n (org-capture-get :empty-lines-after) + (org-capture-get :empty-lines) 0)) + (org-back-over-empty-lines) + (while (looking-at "[ \t]*\n") (replace-match "")) + (let ((pos (point))) + (if (> n 0) (newline n)) + (goto-char pos))) + +(defvar org-clock-marker) ; Defined in org.el + +(defun org-capture-insert-template-here () + "Insert the capture template at point." + (let* ((template (org-capture-get :template)) + (type (org-capture-get :type)) + beg end pp) + (unless (bolp) (insert "\n")) + (setq beg (point)) + (cond + ((and (eq type 'entry) (derived-mode-p 'org-mode)) + (org-capture-verify-tree (org-capture-get :template)) + (org-paste-subtree nil template t)) + ((and (memq type '(item checkitem)) + (derived-mode-p 'org-mode) + (save-excursion (skip-chars-backward " \t\n") + (setq pp (point)) + (org-in-item-p))) + (goto-char pp) + (org-insert-item) + (skip-chars-backward " ") + (skip-chars-backward "-+*0123456789).") + (delete-region (point) (point-at-eol)) + (setq beg (point)) + (org-remove-indentation template) + (insert template) + (org-capture-empty-lines-after) + (goto-char beg) + (org-list-repair) + (org-end-of-item)) + (t + (insert template) + (org-capture-empty-lines-after) + (skip-chars-forward " \t\n") + (unless (eobp) (beginning-of-line)))) + (setq end (point)) + (goto-char beg) + (when (re-search-forward "%\\?" end t) + (replace-match "")))) + +(defun org-capture-set-plist (entry) + "Initialize the property list from the template definition." + (setq org-capture-plist (copy-sequence (nthcdr 5 entry))) + (org-capture-put :key (car entry) :description (nth 1 entry) + :target (nth 3 entry)) + (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry))) + (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt)))) + ;; The template may be empty or omitted for special types. + ;; Here we insert the default templates for such cases. + (cond + ((eq type 'item) (setq txt "- %?")) + ((eq type 'checkitem) (setq txt "- [ ] %?")) + ((eq type 'table-line) (setq txt "| %? |")) + ((member type '(nil entry)) (setq txt "* %?\n %a")))) + (org-capture-put :template txt :type type))) + +(defun org-capture-goto-target (&optional template-key) + "Go to the target location of a capture template. +The user is queried for the template." + (interactive) + (let ((entry (org-capture-select-template template-key))) + (unless entry (error "No capture template selected")) + (org-capture-set-plist entry) + (org-capture-set-target-location) + (pop-to-buffer-same-window (org-capture-get :buffer)) + (goto-char (org-capture-get :pos)))) + +(defun org-capture-get-indirect-buffer (&optional buffer prefix) + "Make an indirect buffer for a capture process. +Use PREFIX as a prefix for the name of the indirect buffer." + (setq buffer (or buffer (current-buffer))) + (let ((n 1) (base (buffer-name buffer)) bname) + (setq bname (concat prefix "-" base)) + (while (buffer-live-p (get-buffer bname)) + (setq bname (concat prefix "-" (number-to-string (cl-incf n)) "-" base))) + (condition-case nil + (make-indirect-buffer buffer bname 'clone) + (error + (let ((buf (make-indirect-buffer buffer bname))) + (with-current-buffer buf (org-mode)) + buf))))) + +(defun org-capture-verify-tree (tree) + "Throw error if TREE is not a valid tree." + (unless (org-kill-is-subtree-p tree) + (error "Template is not a valid Org entry or tree"))) + +(defun org-mks (table title &optional prompt specials) + "Select a member of an alist with multiple keys. + +TABLE is the alist which should contain entries where the car is a string. +There should be two types of entries. + +1. prefix descriptions like (\"a\" \"Description\") + This indicates that `a' is a prefix key for multi-letter selection, and + that there are entries following with keys like \"ab\", \"ax\"... + +2. Select-able members must have more than two elements, with the first + being the string of keys that lead to selecting it, and the second a + short description string of the item. + +The command will then make a temporary buffer listing all entries +that can be selected with a single key, and all the single key +prefixes. When you press the key for a single-letter entry, it is selected. +When you press a prefix key, the commands (and maybe further prefixes) +under this key will be shown and offered for selection. + +TITLE will be placed over the selection in the temporary buffer, +PROMPT will be used when prompting for a key. SPECIAL is an +alist with (\"key\" \"description\") entries. When one of these +is selected, only the bare key is returned." + (save-window-excursion + (let ((inhibit-quit t) + (buffer (org-switch-to-buffer-other-window "*Org Select*")) + (prompt (or prompt "Select: ")) + current) + (unwind-protect + (catch 'exit + (while t + (erase-buffer) + (insert title "\n\n") + (let ((des-keys nil) + (allowed-keys '("\C-g")) + (cursor-type nil)) + ;; Populate allowed keys and descriptions keys + ;; available with CURRENT selector. + (let ((re (format "\\`%s\\(.\\)\\'" + (if current (regexp-quote current) ""))) + (prefix (if current (concat current " ") ""))) + (dolist (entry table) + (pcase entry + ;; Description. + (`(,(and key (pred (string-match re))) ,desc) + (let ((k (match-string 1 key))) + (push k des-keys) + (push k allowed-keys) + (insert prefix "[" k "]" "..." " " desc "..." "\n"))) + ;; Usable entry. + (`(,(and key (pred (string-match re))) ,desc . ,_) + (let ((k (match-string 1 key))) + (insert prefix "[" k "]" " " desc "\n") + (push k allowed-keys))) + (_ nil)))) + ;; Insert special entries, if any. + (when specials + (insert "----------------------------------------------------\ +---------------------------\n") + (pcase-dolist (`(,key ,description) specials) + (insert (format "[%s] %s\n" key description)) + (push key allowed-keys))) + ;; Display UI and let user select an entry or + ;; a sub-level prefix. + (goto-char (point-min)) + (unless (pos-visible-in-window-p (point-max)) + (org-fit-window-to-buffer)) + (message prompt) + (let ((pressed (char-to-string (read-char-exclusive)))) + (while (not (member pressed allowed-keys)) + (message "Invalid key `%s'" pressed) (sit-for 1) + (message prompt) + (setq pressed (char-to-string (read-char-exclusive)))) + (setq current (concat current pressed)) + (cond + ((equal pressed "\C-g") (user-error "Abort")) + ;; Selection is a prefix: open a new menu. + ((member pressed des-keys)) + ;; Selection matches an association: return it. + ((let ((entry (assoc current table))) + (and entry (throw 'exit entry)))) + ;; Selection matches a special entry: return the + ;; selection prefix. + ((assoc current specials) (throw 'exit current)) + (t (error "No entry available"))))))) + (when buffer (kill-buffer buffer)))))) + +;;; The template code +(defun org-capture-select-template (&optional keys) + "Select a capture template. +Lisp programs can force the template by setting KEYS to a string." + (let ((org-capture-templates + (or (org-contextualize-keys + (org-capture-upgrade-templates org-capture-templates) + org-capture-templates-contexts) + '(("t" "Task" entry (file+headline "" "Tasks") + "* TODO %?\n %u\n %a"))))) + (if keys + (or (assoc keys org-capture-templates) + (error "No capture template referred to by \"%s\" keys" keys)) + (org-mks org-capture-templates + "Select a capture template\n=========================" + "Template key: " + '(("C" "Customize org-capture-templates") + ("q" "Abort")))))) + +(defvar org-capture--clipboards nil + "List various clipboards values.") + +(defun org-capture-fill-template (&optional template initial annotation) + "Fill a template and return the filled template as a string. +The template may still contain \"%?\" for cursor positioning." + (let* ((template (or template (org-capture-get :template))) + (buffer (org-capture-get :buffer)) + (file (buffer-file-name (or (buffer-base-buffer buffer) buffer))) + (time (let* ((c (or (org-capture-get :default-time) (current-time))) + (d (decode-time c))) + (if (< (nth 2 d) org-extend-today-until) + (encode-time 0 59 23 (1- (nth 3 d)) (nth 4 d) (nth 5 d)) + c))) + (v-t (format-time-string (org-time-stamp-format nil) time)) + (v-T (format-time-string (org-time-stamp-format t) time)) + (v-u (format-time-string (org-time-stamp-format nil t) time)) + (v-U (format-time-string (org-time-stamp-format t t) time)) + (v-c (and kill-ring (current-kill 0))) + (v-x (or (org-get-x-clipboard 'PRIMARY) + (org-get-x-clipboard 'CLIPBOARD) + (org-get-x-clipboard 'SECONDARY) + "")) ;ensure it is a string + ;; `initial' and `annotation' might have been passed. But if + ;; the property list has them, we prefer those values. + (v-i (or (plist-get org-store-link-plist :initial) + (and (stringp initial) (org-no-properties initial)) + (org-capture-get :initial) + "")) + (v-a + (let ((a (or (plist-get org-store-link-plist :annotation) + annotation + (org-capture-get :annotation) + ""))) + ;; Is the link empty? Then we do not want it... + (if (equal a "[[]]") "" a))) + (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]") + (v-A (if (and v-a (string-match l-re v-a)) + (replace-match "[[\\1][%^{Link description}]]" nil nil v-a) + v-a)) + (v-l (if (and v-a (string-match l-re v-a)) + (replace-match "\\1" nil nil v-a) + v-a)) + (v-n user-full-name) + (v-k (if (marker-buffer org-clock-marker) + (org-no-properties org-clock-heading) + "")) + (v-K (if (marker-buffer org-clock-marker) + (org-make-link-string + (format "%s::*%s" + (buffer-file-name (marker-buffer org-clock-marker)) + v-k) + v-k) + "")) + (v-f (or (org-capture-get :original-file-nondirectory) "")) + (v-F (or (org-capture-get :original-file) "")) + (org-capture--clipboards + (delq nil + (list v-i + (org-get-x-clipboard 'PRIMARY) + (org-get-x-clipboard 'CLIPBOARD) + (org-get-x-clipboard 'SECONDARY) + v-c)))) + + (setq org-store-link-plist (plist-put org-store-link-plist :annotation v-a)) + (setq org-store-link-plist (plist-put org-store-link-plist :initial v-i)) + + (unless template + (setq template "") + (message "no template") (ding) + (sit-for 1)) + (save-window-excursion + (org-switch-to-buffer-other-window (get-buffer-create "*Capture*")) + (erase-buffer) + (setq buffer-file-name nil) + (setq mark-active nil) + (insert template) + (goto-char (point-min)) + + ;; %[] insert contents of a file. + (save-excursion + (while (re-search-forward "%\\[\\(.+\\)\\]" nil t) + (let ((filename (expand-file-name (match-string 1))) + (beg (copy-marker (match-beginning 0))) + (end (copy-marker (match-end 0)))) + (unless (org-capture-escaped-%) + (delete-region beg end) + (set-marker beg nil) + (set-marker end nil) + (condition-case error + (insert-file-contents filename) + (error + (insert (format "%%![couldn not insert %s: %s]" + filename + error)))))))) + + ;; Mark %() embedded elisp for later evaluation. + (org-capture-expand-embedded-elisp 'mark) + + ;; Expand non-interactive templates. + (let ((regexp "%\\(:[-a-za-z]+\\|<\\([^>\n]+\\)>\\|[aAcfFikKlntTuUx]\\)")) + (save-excursion + (while (re-search-forward regexp nil t) + ;; `org-capture-escaped-%' may modify buffer and cripple + ;; match-data. Use markers instead. Ditto for other + ;; templates. + (let ((pos (copy-marker (match-beginning 0))) + (end (copy-marker (match-end 0))) + (value (match-string 1)) + (time-string (match-string 2))) + (unless (org-capture-escaped-%) + (delete-region pos end) + (set-marker pos nil) + (set-marker end nil) + (let* ((inside-sexp? (org-capture-inside-embedded-elisp-p)) + (replacement + (pcase (string-to-char value) + (?< (format-time-string time-string time)) + (?: + (or (plist-get org-store-link-plist (intern value)) + "")) + (?i + (if inside-sexp? v-i + ;; Outside embedded Lisp, repeat leading + ;; characters before initial place holder + ;; every line. + (let ((lead (buffer-substring-no-properties + (line-beginning-position) (point)))) + (replace-regexp-in-string "\n\\(.\\)" + (concat lead "\\1") + v-i nil nil 1)))) + (?a v-a) + (?A v-A) + (?c v-c) + (?f v-f) + (?F v-F) + (?k v-k) + (?K v-K) + (?l v-l) + (?n v-n) + (?t v-t) + (?T v-T) + (?u v-u) + (?U v-U) + (?x v-x)))) + (insert + (if inside-sexp? + ;; Escape sensitive characters. + (replace-regexp-in-string "[\\\"]" "\\\\\\&" replacement) + replacement)))))))) + + ;; Expand %() embedded Elisp. Limit to Sexp originally marked. + (org-capture-expand-embedded-elisp) + + ;; Expand interactive templates. This is the last step so that + ;; template is mostly expanded when prompting happens. Turn on + ;; Org mode and set local variables. This is to support + ;; completion in interactive prompts. + (let ((org-inhibit-startup t)) (org-mode)) + (org-clone-local-variables buffer "\\`org-") + (let (strings) ; Stores interactive answers. + (save-excursion + (let ((regexp "%\\^\\(?:{\\([^}]*\\)}\\)?\\([CgGLptTuU]\\)?")) + (while (re-search-forward regexp nil t) + (let* ((items (and (match-end 1) + (save-match-data + (split-string (match-string-no-properties 1) + "|")))) + (key (match-string 2)) + (beg (copy-marker (match-beginning 0))) + (end (copy-marker (match-end 0))) + (prompt (nth 0 items)) + (default (nth 1 items)) + (completions (nthcdr 2 items))) + (unless (org-capture-escaped-%) + (delete-region beg end) + (set-marker beg nil) + (set-marker end nil) + (pcase key + ((or "G" "g") + (let* ((org-last-tags-completion-table + (org-global-tags-completion-table + (cond ((equal key "G") (org-agenda-files)) + (file (list file)) + (t nil)))) + (org-add-colon-after-tag-completion t) + (ins (mapconcat + #'identity + (org-split-string + (completing-read + (if prompt (concat prompt ": ") "Tags: ") + 'org-tags-completion-function nil nil nil + 'org-tags-history) + "[^[:alnum:]_@#%]+") + ":"))) + (when (org-string-nw-p ins) + (unless (eq (char-before) ?:) (insert ":")) + (insert ins) + (unless (eq (char-after) ?:) (insert ":")) + (and (org-at-heading-p) + (let ((org-ignore-region t)) + (org-set-tags nil 'align)))))) + ((or "C" "L") + (let ((insert-fun (if (equal key "C") #'insert + (lambda (s) (org-insert-link 0 s))))) + (pcase org-capture--clipboards + (`nil nil) + (`(,value) (funcall insert-fun value)) + (`(,first-value . ,_) + (funcall insert-fun + (read-string "Clipboard/kill value: " + first-value + 'org-capture--clipboards + first-value))) + (_ (error "Invalid `org-capture--clipboards' value: %S" + org-capture--clipboards))))) + ("p" (org-set-property prompt nil)) + ((or "t" "T" "u" "U") + ;; These are the date/time related ones. + (let* ((upcase? (equal (upcase key) key)) + (org-end-time-was-given nil) + (time (org-read-date upcase? t nil prompt))) + (org-insert-time-stamp + time (or org-time-was-given upcase?) + (member key '("u" "U")) + nil nil (list org-end-time-was-given)))) + (`nil + ;; Load history list for current prompt. + (setq org-capture--prompt-history + (gethash prompt org-capture--prompt-history-table)) + (push (org-completing-read + (concat (or prompt "Enter string") + (and default (format " [%s]" default)) + ": ") + completions + nil nil nil 'org-capture--prompt-history default) + strings) + (insert (car strings)) + ;; Save updated history list for current prompt. + (puthash prompt org-capture--prompt-history + org-capture--prompt-history-table)) + (_ + (error "Unknown template placeholder: \"%%^%s\"" + key)))))))) + + ;; Replace %n escapes with nth %^{...} string. + (setq strings (nreverse strings)) + (save-excursion + (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t) + (unless (org-capture-escaped-%) + (replace-match + (nth (1- (string-to-number (match-string 1))) strings) + nil t))))) + + ;; Make sure there are no empty lines before the text, and that + ;; it ends with a newline character. + (skip-chars-forward " \t\n") + (delete-region (point-min) (line-beginning-position)) + (goto-char (point-max)) + (skip-chars-backward " \t\n") + (delete-region (point) (point-max)) + (insert "\n") + + ;; Return the expanded template and kill the capture buffer. + (untabify (point-min) (point-max)) + (set-buffer-modified-p nil) + (prog1 (buffer-substring-no-properties (point-min) (point-max)) + (kill-buffer (current-buffer)))))) + +(defun org-capture-escaped-% () + "Non-nil if % was escaped. +If yes, unescape it now. Assume match-data contains the +placeholder to check." + (save-excursion + (goto-char (match-beginning 0)) + (let ((n (abs (skip-chars-backward "\\\\")))) + (delete-char (/ (1+ n) 2)) + (= (% n 2) 1)))) + +(defun org-capture-expand-embedded-elisp (&optional mark) + "Evaluate embedded elisp %(sexp) and replace with the result. +When optional MARK argument is non-nil, mark Sexp with a text +property (`org-embedded-elisp') for later evaluation. Only +marked Sexp are evaluated when this argument is nil." + (save-excursion + (goto-char (point-min)) + (while (re-search-forward "%(" nil t) + (cond + ((get-text-property (match-beginning 0) 'org-embedded-elisp) + (goto-char (match-beginning 0)) + (let ((template-start (point))) + (forward-char 1) + (let* ((sexp (read (current-buffer))) + (result (org-eval + (org-capture--expand-keyword-in-embedded-elisp + sexp)))) + (delete-region template-start (point)) + (cond + ((not result) nil) + ((stringp result) (insert result)) + (t (error + "Capture template sexp `%s' must evaluate to string or nil" + sexp)))))) + ((not mark) nil) + ;; Only mark valid and non-escaped sexp. + ((org-capture-escaped-%) nil) + (t + (let ((end (with-syntax-table emacs-lisp-mode-syntax-table + (ignore-errors (scan-sexps (1- (point)) 1))))) + (when end + (put-text-property (- (point) 2) end 'org-embedded-elisp t)))))))) + +(defun org-capture--expand-keyword-in-embedded-elisp (attr) + "Recursively replace capture link keywords in ATTR sexp. +Such keywords are prefixed with \"%:\". See +`org-capture-template' for more information." + (cond ((consp attr) + (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr)) + ((symbolp attr) + (let* ((attr-symbol (symbol-name attr)) + (key (and (string-match "%\\(:.*\\)" attr-symbol) + (intern (match-string 1 attr-symbol))))) + (or (plist-get org-store-link-plist key) + attr))) + (t attr))) + +(defun org-capture-inside-embedded-elisp-p () + "Non-nil if point is inside of embedded elisp %(sexp). +Assume sexps have been marked with +`org-capture-expand-embedded-elisp' beforehand." + (get-text-property (point) 'org-embedded-elisp)) + +;;;###autoload +(defun org-capture-import-remember-templates () + "Set `org-capture-templates' to be similar to `org-remember-templates'." + (interactive) + (when (and (yes-or-no-p + "Import old remember templates into org-capture-templates? ") + (yes-or-no-p + "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? ")) + (require 'org-remember) + (setq org-capture-templates + (mapcar + (lambda (entry) + (let ((desc (car entry)) + (key (char-to-string (nth 1 entry))) + (template (nth 2 entry)) + (file (or (nth 3 entry) org-default-notes-file)) + (position (or (nth 4 entry) org-remember-default-headline)) + (type 'entry) + (prepend org-reverse-note-order) + immediate target jump-to-captured) + (cond + ((member position '(top bottom)) + (setq target (list 'file file) + prepend (eq position 'top))) + ((eq position 'date-tree) + (setq target (list 'file+datetree file) + prepend nil)) + (t (setq target (list 'file+headline file position)))) + + (when (string-match "%!" template) + (setq template (replace-match "" t t template) + immediate t)) + + (when (string-match "%&" template) + (setq jump-to-captured t)) + + (append (list key desc type target template) + (if prepend '(:prepend t)) + (if immediate '(:immediate-finish t)) + (if jump-to-captured '(:jump-to-captured t))))) + + org-remember-templates)))) + + +(provide 'org-capture) + +;;; org-capture.el ends here diff --git a/elpa/org-9.1.14/org-clock.el b/elpa/org-9.1.14/org-clock.el new file mode 100644 index 00000000..ff32e28d --- /dev/null +++ b/elpa/org-9.1.14/org-clock.el @@ -0,0 +1,2976 @@ +;;; org-clock.el --- The time clocking code for Org mode -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file contains the time clocking code for Org mode + +;;; Code: + +(require 'cl-lib) +(require 'org) + +(declare-function calendar-iso-to-absolute "cal-iso" (date)) +(declare-function notifications-notify "notifications" (&rest params)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-type "org-element" (element)) +(declare-function org-table-goto-line "org-table" (n)) + +(defvar org-frame-title-format-backup frame-title-format) +(defvar org-time-stamp-formats) + + +(defgroup org-clock nil + "Options concerning clocking working time in Org mode." + :tag "Org Clock" + :group 'org-progress) + +(defcustom org-clock-into-drawer t + "Non-nil when clocking info should be wrapped into a drawer. + +When non-nil, clocking info will be inserted into the same drawer +as log notes (see variable `org-log-into-drawer'), if it exists, +or \"LOGBOOK\" otherwise. If necessary, the drawer will be +created. + +When an integer, the drawer is created only when the number of +clocking entries in an item reaches or exceeds this value. + +When a string, it becomes the name of the drawer, ignoring the +log notes drawer altogether. + +Do not check directly this variable in a Lisp program. Call +function `org-clock-into-drawer' instead." + :group 'org-todo + :group 'org-clock + :version "26.1" + :package-version '(Org . "8.3") + :type '(choice + (const :tag "Always" t) + (const :tag "Only when drawer exists" nil) + (integer :tag "When at least N clock entries") + (const :tag "Into LOGBOOK drawer" "LOGBOOK") + (string :tag "Into Drawer named..."))) + +(defun org-clock-into-drawer () + "Value of `org-clock-into-drawer'. but let properties overrule. + +If the current entry has or inherits a CLOCK_INTO_DRAWER +property, it will be used instead of the default value. + +Return value is either a string, an integer, or nil." + (let ((p (org-entry-get nil "CLOCK_INTO_DRAWER" 'inherit t))) + (cond ((equal p "nil") nil) + ((equal p "t") (or (org-log-into-drawer) "LOGBOOK")) + ((org-string-nw-p p) + (if (string-match-p "\\`[0-9]+\\'" p) (string-to-number p) p)) + ((org-string-nw-p org-clock-into-drawer)) + ((integerp org-clock-into-drawer) org-clock-into-drawer) + ((not org-clock-into-drawer) nil) + ((org-log-into-drawer)) + (t "LOGBOOK")))) + +(defcustom org-clock-out-when-done t + "When non-nil, clock will be stopped when the clocked entry is marked DONE. +\\\ +DONE here means any DONE-like state. +A nil value means clock will keep running until stopped explicitly with +`\\[org-clock-out]', or until the clock is started in a different item. +Instead of t, this can also be a list of TODO states that should trigger +clocking out." + :group 'org-clock + :type '(choice + (const :tag "No" nil) + (const :tag "Yes, when done" t) + (repeat :tag "State list" + (string :tag "TODO keyword")))) + +(defcustom org-clock-rounding-minutes 0 + "Rounding minutes when clocking in or out. +The default value is 0 so that no rounding is done. +When set to a non-integer value, use the car of +`org-time-stamp-rounding-minutes', like for setting a time-stamp. + +E.g. if `org-clock-rounding-minutes' is set to 5, time is 14:47 +and you clock in: then the clock starts at 14:45. If you clock +out within the next 5 minutes, the clock line will be removed; +if you clock out 8 minutes after your clocked in, the clock +out time will be 14:50." + :group 'org-clock + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (integer :tag "Minutes (0 for no rounding)") + (symbol :tag "Use `org-time-stamp-rounding-minutes'" 'same-as-time-stamp))) + +(defcustom org-clock-out-remove-zero-time-clocks nil + "Non-nil means remove the clock line when the resulting time is zero." + :group 'org-clock + :type 'boolean) + +(defcustom org-clock-in-switch-to-state nil + "Set task to a special todo state while clocking it. +The value should be the state to which the entry should be +switched. If the value is a function, it must take one +parameter (the current TODO state of the item) and return the +state to switch it to." + :group 'org-clock + :group 'org-todo + :type '(choice + (const :tag "Don't force a state" nil) + (string :tag "State") + (symbol :tag "Function"))) + +(defcustom org-clock-out-switch-to-state nil + "Set task to a special todo state after clocking out. +The value should be the state to which the entry should be +switched. If the value is a function, it must take one +parameter (the current TODO state of the item) and return the +state to switch it to." + :group 'org-clock + :group 'org-todo + :type '(choice + (const :tag "Don't force a state" nil) + (string :tag "State") + (symbol :tag "Function"))) + +(defcustom org-clock-history-length 5 + "Number of clock tasks to remember in history." + :group 'org-clock + :type 'integer) + +(defcustom org-clock-goto-may-find-recent-task t + "Non-nil means `org-clock-goto' can go to recent task if no active clock." + :group 'org-clock + :type 'boolean) + +(defcustom org-clock-heading-function nil + "When non-nil, should be a function to create `org-clock-heading'. +This is the string shown in the mode line when a clock is running. +The function is called with point at the beginning of the headline." + :group 'org-clock + :type '(choice (const nil) (function))) + +(defcustom org-clock-string-limit 0 + "Maximum length of clock strings in the mode line. 0 means no limit." + :group 'org-clock + :type 'integer) + +(defcustom org-clock-in-resume nil + "If non-nil, resume clock when clocking into task with open clock. +When clocking into a task with a clock entry which has not been closed, +the clock can be resumed from that point." + :group 'org-clock + :type 'boolean) + +(defcustom org-clock-persist nil + "When non-nil, save the running clock when Emacs is closed. +The clock is resumed when Emacs restarts. +When this is t, both the running clock, and the entire clock +history are saved. When this is the symbol `clock', only the +running clock is saved. When this is the symbol `history', only +the clock history is saved. + +When Emacs restarts with saved clock information, the file containing +the running clock as well as all files mentioned in the clock history +will be visited. + +All this depends on running `org-clock-persistence-insinuate' in your +Emacs initialization file." + :group 'org-clock + :type '(choice + (const :tag "Just the running clock" clock) + (const :tag "Just the history" history) + (const :tag "Clock and history" t) + (const :tag "No persistence" nil))) + +(defcustom org-clock-persist-file (convert-standard-filename + (concat user-emacs-directory "org-clock-save.el")) + "File to save clock data to." + :group 'org-clock + :type 'string) + +(defcustom org-clock-persist-query-save nil + "When non-nil, ask before saving the current clock on exit." + :group 'org-clock + :type 'boolean) + +(defcustom org-clock-persist-query-resume t + "When non-nil, ask before resuming any stored clock during load." + :group 'org-clock + :type 'boolean) + +(defcustom org-clock-sound nil + "Sound to use for notifications. +Possible values are: + +nil No sound played +t Standard Emacs beep +file name Play this sound file, fall back to beep" + :group 'org-clock + :type '(choice + (const :tag "No sound" nil) + (const :tag "Standard beep" t) + (file :tag "Play sound file"))) + +(defcustom org-clock-mode-line-total 'auto + "Default setting for the time included for the mode line clock. +This can be overruled locally using the CLOCK_MODELINE_TOTAL property. +Allowed values are: + +current Only the time in the current instance of the clock +today All time clocked into this task today +repeat All time clocked into this task since last repeat +all All time ever recorded for this task +auto Automatically, either `all', or `repeat' for repeating tasks" + :group 'org-clock + :type '(choice + (const :tag "Current clock" current) + (const :tag "Today's task time" today) + (const :tag "Since last repeat" repeat) + (const :tag "All task time" all) + (const :tag "Automatically, `all' or since `repeat'" auto))) + +(defvaralias 'org-task-overrun-text 'org-clock-task-overrun-text) +(defcustom org-clock-task-overrun-text nil + "Extra mode line text to indicate that the clock is overrun. +The can be nil to indicate that instead of adding text, the clock time +should get a different face (`org-mode-line-clock-overrun'). +When this is a string, it is prepended to the clock string as an indication, +also using the face `org-mode-line-clock-overrun'." + :group 'org-clock + :version "24.1" + :type '(choice + (const :tag "Just mark the time string" nil) + (string :tag "Text to prepend"))) + +(defcustom org-show-notification-handler nil + "Function or program to send notification with. +The function or program will be called with the notification +string as argument." + :group 'org-clock + :type '(choice + (const nil) + (string :tag "Program") + (function :tag "Function"))) + +(defgroup org-clocktable nil + "Options concerning the clock table in Org mode." + :tag "Org Clock Table" + :group 'org-clock) + +(defcustom org-clocktable-defaults + (list + :maxlevel 2 + :lang (or (bound-and-true-p org-export-default-language) "en") + :scope 'file + :block nil + :wstart 1 + :mstart 1 + :tstart nil + :tend nil + :step nil + :stepskip0 nil + :fileskip0 nil + :tags nil + :emphasize nil + :link nil + :narrow '40! + :indent t + :formula nil + :timestamp nil + :level nil + :tcolumns nil + :formatter nil) + "Default properties for clock tables." + :group 'org-clock + :version "24.1" + :type 'plist) + +(defcustom org-clock-clocktable-formatter 'org-clocktable-write-default + "Function to turn clocking data into a table. +For more information, see `org-clocktable-write-default'." + :group 'org-clocktable + :version "24.1" + :type 'function) + +;; FIXME: translate es and nl last string "Clock summary at" +(defcustom org-clock-clocktable-language-setup + '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at") + ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at") + ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à") + ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at") + ("de" "Datei" "E" "Zeitstempel" "Kopfzeile" "Dauer" "GESAMT" + "Gesamtdauer" "Dateizeit" "Erstellt am")) + "Terms used in clocktable, translated to different languages." + :group 'org-clocktable + :version "24.1" + :type 'alist) + +(defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file) + "Default properties for new clocktables. +These will be inserted into the BEGIN line, to make it easy for users to +play with them." + :group 'org-clocktable + :type 'plist) + +(defcustom org-clock-idle-time nil + "When non-nil, resolve open clocks if the user is idle more than X minutes." + :group 'org-clock + :type '(choice + (const :tag "Never" nil) + (integer :tag "After N minutes"))) + +(defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running + "When to automatically resolve open clocks found in Org buffers." + :group 'org-clock + :type '(choice + (const :tag "Never" nil) + (const :tag "Always" t) + (const :tag "When no clock is running" when-no-clock-is-running))) + +(defcustom org-clock-report-include-clocking-task nil + "When non-nil, include the current clocking task time in clock reports." + :group 'org-clock + :version "24.1" + :type 'boolean) + +(defcustom org-clock-resolve-expert nil + "Non-nil means do not show the splash buffer with the clock resolver." + :group 'org-clock + :version "24.1" + :type 'boolean) + +(defcustom org-clock-continuously nil + "Non-nil means to start clocking from the last clock-out time, if any." + :type 'boolean + :version "24.1" + :group 'org-clock) + +(defcustom org-clock-total-time-cell-format "*%s*" + "Format string for the total time cells." + :group 'org-clock + :version "24.1" + :type 'string) + +(defcustom org-clock-file-time-cell-format "*%s*" + "Format string for the file time cells." + :group 'org-clock + :version "24.1" + :type 'string) + +(defcustom org-clock-clocked-in-display 'mode-line + "When clocked in for a task, Org can display the current +task and accumulated time in the mode line and/or frame title. +Allowed values are: + +both displays in both mode line and frame title +mode-line displays only in mode line (default) +frame-title displays only in frame title +nil current clock is not displayed" + :group 'org-clock + :type '(choice + (const :tag "Mode line" mode-line) + (const :tag "Frame title" frame-title) + (const :tag "Both" both) + (const :tag "None" nil))) + +(defcustom org-clock-frame-title-format '(t org-mode-line-string) + "The value for `frame-title-format' when clocking in. + +When `org-clock-clocked-in-display' is set to `frame-title' +or `both', clocking in will replace `frame-title-format' with +this value. Clocking out will restore `frame-title-format'. + +`org-frame-title-string' is a format string using the same +specifications than `frame-title-format', which see." + :version "24.1" + :group 'org-clock + :type 'sexp) + +(defcustom org-clock-x11idle-program-name "x11idle" + "Name of the program which prints X11 idle time in milliseconds. + +You can find x11idle.c in the contrib/scripts directory of the +Org git distribution. Or, you can do: + + sudo apt-get install xprintidle + +if you are using Debian." + :group 'org-clock + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-clock-goto-before-context 2 + "Number of lines of context to display before currently clocked-in entry. +This applies when using `org-clock-goto'." + :group 'org-clock + :type 'integer) + +(defcustom org-clock-display-default-range 'thisyear + "Default range when displaying clocks with `org-clock-display'. +Valid values are: `today', `yesterday', `thisweek', `lastweek', +`thismonth', `lastmonth', `thisyear', `lastyear' and `untilnow'." + :group 'org-clock + :type '(choice (const today) + (const yesterday) + (const thisweek) + (const lastweek) + (const thismonth) + (const lastmonth) + (const thisyear) + (const lastyear) + (const untilnow) + (const :tag "Select range interactively" interactive)) + :safe #'symbolp) + +(defvar org-clock-in-prepare-hook nil + "Hook run when preparing the clock. +This hook is run before anything happens to the task that +you want to clock in. For example, you can use this hook +to add an effort property.") +(defvar org-clock-in-hook nil + "Hook run when starting the clock.") +(defvar org-clock-out-hook nil + "Hook run when stopping the current clock.") + +(defvar org-clock-cancel-hook nil + "Hook run when canceling the current clock.") +(defvar org-clock-goto-hook nil + "Hook run when selecting the currently clocked-in entry.") +(defvar org-clock-has-been-used nil + "Has the clock been used during the current Emacs session?") + +(defvar org-clock-stored-history nil + "Clock history, populated by `org-clock-load'") +(defvar org-clock-stored-resume-clock nil + "Clock to resume, saved by `org-clock-load'") + +;;; The clock for measuring work time. + +(defvar org-mode-line-string "") +(put 'org-mode-line-string 'risky-local-variable t) + +(defvar org-clock-mode-line-timer nil) +(defvar org-clock-idle-timer nil) +(defvar org-clock-heading) ; defined in org.el +(defvar org-clock-start-time "") + +(defvar org-clock-leftover-time nil + "If non-nil, user canceled a clock; this is when leftover time started.") + +(defvar org-clock-effort "" + "Effort estimate of the currently clocking task.") + +(defvar org-clock-total-time nil + "Holds total time, spent previously on currently clocked item. +This does not include the time in the currently running clock.") + +(defvar org-clock-history nil + "List of marker pointing to recent clocked tasks.") + +(defvar org-clock-default-task (make-marker) + "Marker pointing to the default task that should clock time. +The clock can be made to switch to this task after clocking out +of a different task.") + +(defvar org-clock-interrupted-task (make-marker) + "Marker pointing to the task that has been interrupted by the current clock.") + +(defvar org-clock-mode-line-map (make-sparse-keymap)) +(define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto) +(define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu) + +(defun org-clock--translate (s language) + "Translate string S into using string LANGUAGE. +Assume S in the English term to translate. Return S as-is if it +cannot be translated." + (or (nth (pcase s + ("File" 1) ("L" 2) ("Timestamp" 3) ("Headline" 4) ("Time" 5) + ("ALL" 6) ("Total time" 7) ("File time" 8) ("Clock summary at" 9)) + (assoc-string language org-clock-clocktable-language-setup t)) + s)) + +(defun org-clock--mode-line-heading () + "Return currently clocked heading, formatted for mode line." + (cond ((functionp org-clock-heading-function) + (funcall org-clock-heading-function)) + ((org-before-first-heading-p) "???") + (t (replace-regexp-in-string + org-bracket-link-analytic-regexp "\\5" + (org-no-properties (org-get-heading t t t t)))))) + +(defun org-clock-menu () + (interactive) + (popup-menu + '("Clock" + ["Clock out" org-clock-out t] + ["Change effort estimate" org-clock-modify-effort-estimate t] + ["Go to clock entry" org-clock-goto t] + ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]))) + +(defun org-clock-history-push (&optional pos buffer) + "Push a marker to the clock history." + (setq org-clock-history-length (max 1 (min 35 org-clock-history-length))) + (let ((m (move-marker (make-marker) + (or pos (point)) (org-base-buffer + (or buffer (current-buffer))))) + n l) + (while (setq n (member m org-clock-history)) + (move-marker (car n) nil)) + (setq org-clock-history + (delq nil + (mapcar (lambda (x) (if (marker-buffer x) x nil)) + org-clock-history))) + (when (>= (setq l (length org-clock-history)) org-clock-history-length) + (setq org-clock-history + (nreverse + (nthcdr (- l org-clock-history-length -1) + (nreverse org-clock-history))))) + (push m org-clock-history))) + +(defun org-clock-save-markers-for-cut-and-paste (beg end) + "Save relative positions of markers in region." + (org-check-and-save-marker org-clock-marker beg end) + (org-check-and-save-marker org-clock-hd-marker beg end) + (org-check-and-save-marker org-clock-default-task beg end) + (org-check-and-save-marker org-clock-interrupted-task beg end) + (dolist (m org-clock-history) + (org-check-and-save-marker m beg end))) + +(defun org-clock-drawer-name () + "Return clock drawer's name for current entry, or nil." + (let ((drawer (org-clock-into-drawer))) + (cond ((integerp drawer) + (let ((log-drawer (org-log-into-drawer))) + (if (stringp log-drawer) log-drawer "LOGBOOK"))) + ((stringp drawer) drawer) + (t nil)))) + +(defun org-clocking-buffer () + "Return the clocking buffer if we are currently clocking a task or nil." + (marker-buffer org-clock-marker)) + +(defun org-clocking-p () + "Return t when clocking a task." + (not (equal (org-clocking-buffer) nil))) + +(defvar org-clock-before-select-task-hook nil + "Hook called in task selection just before prompting the user.") + +(defun org-clock-select-task (&optional prompt) + "Select a task that was recently associated with clocking. +Return marker position of the selected task. Raise an error if +there is no recent clock to choose from." + (let (och chl sel-list rpl (i 0) s) + ;; Remove successive dups from the clock history to consider + (dolist (c org-clock-history) + (unless (equal c (car och)) (push c och))) + (setq och (reverse och) chl (length och)) + (if (zerop chl) + (user-error "No recent clock") + (save-window-excursion + (org-switch-to-buffer-other-window + (get-buffer-create "*Clock Task Select*")) + (erase-buffer) + (when (marker-buffer org-clock-default-task) + (insert (org-add-props "Default Task\n" nil 'face 'bold)) + (setq s (org-clock-insert-selection-line ?d org-clock-default-task)) + (push s sel-list)) + (when (marker-buffer org-clock-interrupted-task) + (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold)) + (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task)) + (push s sel-list)) + (when (org-clocking-p) + (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold)) + (setq s (org-clock-insert-selection-line ?c org-clock-marker)) + (push s sel-list)) + (insert (org-add-props "Recent Tasks\n" nil 'face 'bold)) + (dolist (m och) + (when (marker-buffer m) + (setq i (1+ i) + s (org-clock-insert-selection-line + (if (< i 10) + (+ i ?0) + (+ i (- ?A 10))) m)) + (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s)))) + (push s sel-list))) + (run-hooks 'org-clock-before-select-task-hook) + (goto-char (point-min)) + ;; Set min-height relatively to circumvent a possible but in + ;; `fit-window-to-buffer' + (fit-window-to-buffer nil nil (if (< chl 10) chl (+ 5 chl))) + (message (or prompt "Select task for clocking:")) + (setq cursor-type nil rpl (read-char-exclusive)) + (kill-buffer) + (cond + ((eq rpl ?q) nil) + ((eq rpl ?x) nil) + ((assoc rpl sel-list) (cdr (assoc rpl sel-list))) + (t (user-error "Invalid task choice %c" rpl))))))) + +(defun org-clock-insert-selection-line (i marker) + "Insert a line for the clock selection menu. +And return a cons cell with the selection character integer and the marker +pointing to it." + (when (marker-buffer marker) + (let (cat task heading prefix) + (with-current-buffer (org-base-buffer (marker-buffer marker)) + (org-with-wide-buffer + (ignore-errors + (goto-char marker) + (setq cat (org-get-category) + heading (org-get-heading 'notags) + prefix (save-excursion + (org-back-to-heading t) + (looking-at org-outline-regexp) + (match-string 0)) + task (substring + (org-fontify-like-in-org-mode + (concat prefix heading) + org-odd-levels-only) + (length prefix)))))) + (when (and cat task) + (insert (format "[%c] %-12s %s\n" i cat task)) + (cons i marker))))) + +(defvar org-clock-task-overrun nil + "Internal flag indicating if the clock has overrun the planned time.") +(defvar org-clock-update-period 60 + "Number of seconds between mode line clock string updates.") + +(defun org-clock-get-clock-string () + "Form a clock-string, that will be shown in the mode line. +If an effort estimate was defined for the current item, use +01:30/01:50 format (clocked/estimated). +If not, show simply the clocked time like 01:50." + (let ((clocked-time (org-clock-get-clocked-time))) + (if org-clock-effort + (let* ((effort-in-minutes (org-duration-to-minutes org-clock-effort)) + (work-done-str + (propertize (org-duration-from-minutes clocked-time) + 'face + (if (and org-clock-task-overrun + (not org-clock-task-overrun-text)) + 'org-mode-line-clock-overrun + 'org-mode-line-clock))) + (effort-str (org-duration-from-minutes effort-in-minutes))) + (format (propertize " [%s/%s] (%s)" 'face 'org-mode-line-clock) + work-done-str effort-str org-clock-heading)) + (format (propertize " [%s] (%s)" 'face 'org-mode-line-clock) + (org-duration-from-minutes clocked-time) + org-clock-heading)))) + +(defun org-clock-get-last-clock-out-time () + "Get the last clock-out time for the current subtree." + (save-excursion + (let ((end (save-excursion (org-end-of-subtree)))) + (when (re-search-forward (concat org-clock-string + ".*\\]--\\(\\[[^]]+\\]\\)") end t) + (org-time-string-to-time (match-string 1)))))) + +(defun org-clock-update-mode-line (&optional refresh) + "Update mode line with clock information. +When optional argument is non-nil, refresh cached heading." + (if org-clock-effort + (org-clock-notify-once-if-expired) + (setq org-clock-task-overrun nil)) + (when refresh (setq org-clock-heading (org-clock--mode-line-heading))) + (setq org-mode-line-string + (propertize + (let ((clock-string (org-clock-get-clock-string)) + (help-text "Org mode clock is running.\nmouse-1 shows a \ +menu\nmouse-2 will jump to task")) + (if (and (> org-clock-string-limit 0) + (> (length clock-string) org-clock-string-limit)) + (propertize + (substring clock-string 0 org-clock-string-limit) + 'help-echo (concat help-text ": " org-clock-heading)) + (propertize clock-string 'help-echo help-text))) + 'local-map org-clock-mode-line-map + 'mouse-face 'mode-line-highlight)) + (if (and org-clock-task-overrun org-clock-task-overrun-text) + (setq org-mode-line-string + (concat (propertize + org-clock-task-overrun-text + 'face 'org-mode-line-clock-overrun) org-mode-line-string))) + (force-mode-line-update)) + +(defun org-clock-get-clocked-time () + "Get the clocked time for the current item in minutes. +The time returned includes the time spent on this task in +previous clocking intervals." + (let ((currently-clocked-time + (floor (- (float-time) + (float-time org-clock-start-time)) 60))) + (+ currently-clocked-time (or org-clock-total-time 0)))) + +(defun org-clock-modify-effort-estimate (&optional value) + "Add to or set the effort estimate of the item currently being clocked. +VALUE can be a number of minutes, or a string with format hh:mm or mm. +When the string starts with a + or a - sign, the current value of the effort +property will be changed by that amount. If the effort value is expressed +as an `org-effort-durations' (e.g. \"3h\"), the modified value will be +converted to a hh:mm duration. + +This command will update the \"Effort\" property of the currently +clocked item, and the value displayed in the mode line." + (interactive) + (if (org-clock-is-active) + (let ((current org-clock-effort) sign) + (unless value + ;; Prompt user for a value or a change + (setq value + (read-string + (format "Set effort (hh:mm or mm%s): " + (if current + (format ", prefix + to add to %s" org-clock-effort) + ""))))) + (when (stringp value) + ;; A string. See if it is a delta + (setq sign (string-to-char value)) + (if (member sign '(?- ?+)) + (setq current (org-duration-to-minutes current) + value (substring value 1)) + (setq current 0)) + (setq value (org-duration-to-minutes value)) + (if (equal ?- sign) + (setq value (- current value)) + (if (equal ?+ sign) (setq value (+ current value))))) + (setq value (max 0 value) + org-clock-effort (org-duration-from-minutes value)) + (org-entry-put org-clock-marker "Effort" org-clock-effort) + (org-clock-update-mode-line) + (message "Effort is now %s" org-clock-effort)) + (message "Clock is not currently active"))) + +(defvar org-clock-notification-was-shown nil + "Shows if we have shown notification already.") + +(defun org-clock-notify-once-if-expired () + "Show notification if we spent more time than we estimated before. +Notification is shown only once." + (when (org-clocking-p) + (let ((effort-in-minutes (org-duration-to-minutes org-clock-effort)) + (clocked-time (org-clock-get-clocked-time))) + (if (setq org-clock-task-overrun + (if (or (null effort-in-minutes) (zerop effort-in-minutes)) + nil + (>= clocked-time effort-in-minutes))) + (unless org-clock-notification-was-shown + (setq org-clock-notification-was-shown t) + (org-notify + (format-message "Task `%s' should be finished by now. (%s)" + org-clock-heading org-clock-effort) + org-clock-sound)) + (setq org-clock-notification-was-shown nil))))) + +(defun org-notify (notification &optional play-sound) + "Send a NOTIFICATION and maybe PLAY-SOUND. +If PLAY-SOUND is non-nil, it overrides `org-clock-sound'." + (org-show-notification notification) + (if play-sound (org-clock-play-sound play-sound))) + +(defun org-show-notification (notification) + "Show notification. +Use `org-show-notification-handler' if defined, +use libnotify if available, or fall back on a message." + (cond ((functionp org-show-notification-handler) + (funcall org-show-notification-handler notification)) + ((stringp org-show-notification-handler) + (start-process "emacs-timer-notification" nil + org-show-notification-handler notification)) + ((fboundp 'notifications-notify) + (notifications-notify + :title "Org mode message" + :body notification + ;; FIXME how to link to the Org icon? + ;; :app-icon "~/.emacs.d/icons/mail.png" + :urgency 'low)) + ((executable-find "notify-send") + (start-process "emacs-timer-notification" nil + "notify-send" notification)) + ;; Maybe the handler will send a message, so only use message as + ;; a fall back option + (t (message "%s" notification)))) + +(defun org-clock-play-sound (&optional clock-sound) + "Play sound as configured by `org-clock-sound'. +Use alsa's aplay tool if available. +If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'." + (let ((org-clock-sound (or clock-sound org-clock-sound))) + (cond + ((not org-clock-sound)) + ((eq org-clock-sound t) (beep t) (beep t)) + ((stringp org-clock-sound) + (let ((file (expand-file-name org-clock-sound))) + (if (file-exists-p file) + (if (executable-find "aplay") + (start-process "org-clock-play-notification" nil + "aplay" file) + (condition-case nil + (play-sound-file file) + (error (beep t) (beep t)))))))))) + +(defvar org-clock-mode-line-entry nil + "Information for the mode line about the running clock.") + +(defun org-find-open-clocks (file) + "Search through the given file and find all open clocks." + (let ((buf (or (get-file-buffer file) + (find-file-noselect file))) + (org-clock-re (concat org-clock-string " \\(\\[.*?\\]\\)$")) + clocks) + (with-current-buffer buf + (save-excursion + (goto-char (point-min)) + (while (re-search-forward org-clock-re nil t) + (push (cons (copy-marker (match-end 1) t) + (org-time-string-to-time (match-string 1))) clocks)))) + clocks)) + +(defsubst org-is-active-clock (clock) + "Return t if CLOCK is the currently active clock." + (and (org-clock-is-active) + (= org-clock-marker (car clock)))) + +(defmacro org-with-clock-position (clock &rest forms) + "Evaluate FORMS with CLOCK as the current active clock." + `(with-current-buffer (marker-buffer (car ,clock)) + (org-with-wide-buffer + (goto-char (car ,clock)) + (beginning-of-line) + ,@forms))) +(def-edebug-spec org-with-clock-position (form body)) +(put 'org-with-clock-position 'lisp-indent-function 1) + +(defmacro org-with-clock (clock &rest forms) + "Evaluate FORMS with CLOCK as the current active clock. +This macro also protects the current active clock from being altered." + `(org-with-clock-position ,clock + (let ((org-clock-start-time (cdr ,clock)) + (org-clock-total-time) + (org-clock-history) + (org-clock-effort) + (org-clock-marker (car ,clock)) + (org-clock-hd-marker (save-excursion + (org-back-to-heading t) + (point-marker)))) + ,@forms))) +(def-edebug-spec org-with-clock (form body)) +(put 'org-with-clock 'lisp-indent-function 1) + +(defsubst org-clock-clock-in (clock &optional resume start-time) + "Clock in to the clock located by CLOCK. +If necessary, clock-out of the currently active clock." + (org-with-clock-position clock + (let ((org-clock-in-resume (or resume org-clock-in-resume))) + (org-clock-in nil start-time)))) + +(defsubst org-clock-clock-out (clock &optional fail-quietly at-time) + "Clock out of the clock located by CLOCK." + (let ((temp (copy-marker (car clock) + (marker-insertion-type (car clock))))) + (if (org-is-active-clock clock) + (org-clock-out nil fail-quietly at-time) + (org-with-clock clock + (org-clock-out nil fail-quietly at-time))) + (setcar clock temp))) + +(defsubst org-clock-clock-cancel (clock) + "Cancel the clock located by CLOCK." + (let ((temp (copy-marker (car clock) + (marker-insertion-type (car clock))))) + (if (org-is-active-clock clock) + (org-clock-cancel) + (org-with-clock clock + (org-clock-cancel))) + (setcar clock temp))) + +(defvar org-clock-clocking-in nil) +(defvar org-clock-resolving-clocks nil) +(defvar org-clock-resolving-clocks-due-to-idleness nil) + +(defun org-clock-resolve-clock (clock resolve-to clock-out-time + &optional close-p restart-p fail-quietly) + "Resolve `CLOCK' given the time `RESOLVE-TO', and the present. +`CLOCK' is a cons cell of the form (MARKER START-TIME)." + (let ((org-clock-resolving-clocks t)) + (cond + ((null resolve-to) + (org-clock-clock-cancel clock) + (if (and restart-p (not org-clock-clocking-in)) + (org-clock-clock-in clock))) + + ((eq resolve-to 'now) + (if restart-p + (error "RESTART-P is not valid here")) + (if (or close-p org-clock-clocking-in) + (org-clock-clock-out clock fail-quietly) + (unless (org-is-active-clock clock) + (org-clock-clock-in clock t)))) + + ((not (time-less-p resolve-to (current-time))) + (error "RESOLVE-TO must refer to a time in the past")) + + (t + (if restart-p + (error "RESTART-P is not valid here")) + (org-clock-clock-out clock fail-quietly (or clock-out-time + resolve-to)) + (unless org-clock-clocking-in + (if close-p + (setq org-clock-leftover-time (and (null clock-out-time) + resolve-to)) + (org-clock-clock-in clock nil (and clock-out-time + resolve-to)))))))) + +(defun org-clock-jump-to-current-clock (&optional effective-clock) + (interactive) + (let ((drawer (org-clock-into-drawer)) + (clock (or effective-clock (cons org-clock-marker + org-clock-start-time)))) + (unless (marker-buffer (car clock)) + (error "No clock is currently running")) + (org-with-clock clock (org-clock-goto)) + (with-current-buffer (marker-buffer (car clock)) + (goto-char (car clock)) + (when drawer + (org-with-wide-buffer + (let ((drawer-re (format "^[ \t]*:%s:[ \t]*$" + (regexp-quote (if (stringp drawer) drawer "LOGBOOK")))) + (beg (save-excursion (org-back-to-heading t) (point)))) + (catch 'exit + (while (re-search-backward drawer-re beg t) + (let ((element (org-element-at-point))) + (when (eq (org-element-type element) 'drawer) + (when (> (org-element-property :end element) (car clock)) + (org-flag-drawer nil element)) + (throw 'exit nil))))))))))) + +(defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly) + "Resolve an open Org clock. +An open clock was found, with `dangling' possibly being non-nil. +If this function was invoked with a prefix argument, non-dangling +open clocks are ignored. The given clock requires some sort of +user intervention to resolve it, either because a clock was left +dangling or due to an idle timeout. The clock resolution can +either be: + + (a) deleted, the user doesn't care about the clock + (b) restarted from the current time (if no other clock is open) + (c) closed, giving the clock X minutes + (d) closed and then restarted + (e) resumed, as if the user had never left + +The format of clock is (CONS MARKER START-TIME), where MARKER +identifies the buffer and position the clock is open at (and +thus, the heading it's under), and START-TIME is when the clock +was started." + (cl-assert clock) + (let* ((ch + (save-window-excursion + (save-excursion + (unless org-clock-resolving-clocks-due-to-idleness + (org-clock-jump-to-current-clock clock)) + (unless org-clock-resolve-expert + (with-output-to-temp-buffer "*Org Clock*" + (princ (format-message "Select a Clock Resolution Command: + +i/q Ignore this question; the same as keeping all the idle time. + +k/K Keep X minutes of the idle time (default is all). If this + amount is less than the default, you will be clocked out + that many minutes after the time that idling began, and then + clocked back in at the present time. + +g/G Indicate that you \"got back\" X minutes ago. This is quite + different from `k': it clocks you out from the beginning of + the idle period and clock you back in X minutes ago. + +s/S Subtract the idle time from the current clock. This is the + same as keeping 0 minutes. + +C Cancel the open timer altogether. It will be as though you + never clocked in. + +j/J Jump to the current clock, to make manual adjustments. + +For all these options, using uppercase makes your final state +to be CLOCKED OUT.")))) + (org-fit-window-to-buffer (get-buffer-window "*Org Clock*")) + (let (char-pressed) + (while (or (null char-pressed) + (and (not (memq char-pressed + '(?k ?K ?g ?G ?s ?S ?C + ?j ?J ?i ?q))) + (or (ding) t))) + (setq char-pressed + (read-char (concat (funcall prompt-fn clock) + " [jkKgGSscCiq]? ") + nil 45))) + (and (not (memq char-pressed '(?i ?q))) char-pressed))))) + (default + (floor (/ (float-time + (time-subtract (current-time) last-valid)) 60))) + (keep + (and (memq ch '(?k ?K)) + (read-number "Keep how many minutes? " default))) + (gotback + (and (memq ch '(?g ?G)) + (read-number "Got back how many minutes ago? " default))) + (subtractp (memq ch '(?s ?S))) + (barely-started-p (< (- (float-time last-valid) + (float-time (cdr clock))) 45)) + (start-over (and subtractp barely-started-p))) + (cond + ((memq ch '(?j ?J)) + (if (eq ch ?J) + (org-clock-resolve-clock clock 'now nil t nil fail-quietly)) + (org-clock-jump-to-current-clock clock)) + ((or (null ch) + (not (memq ch '(?k ?K ?g ?G ?s ?S ?C)))) + (message "")) + (t + (org-clock-resolve-clock + clock (cond + ((or (eq ch ?C) + ;; If the time on the clock was less than a minute before + ;; the user went away, and they've ask to subtract all the + ;; time... + start-over) + nil) + ((or subtractp + (and gotback (= gotback 0))) + last-valid) + ((or (and keep (= keep default)) + (and gotback (= gotback default))) + 'now) + (keep + (time-add last-valid (seconds-to-time (* 60 keep)))) + (gotback + (time-subtract (current-time) + (seconds-to-time (* 60 gotback)))) + (t + (error "Unexpected, please report this as a bug"))) + (and gotback last-valid) + (memq ch '(?K ?G ?S)) + (and start-over + (not (memq ch '(?K ?G ?S ?C)))) + fail-quietly))))) + +;;;###autoload +(defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid) + "Resolve all currently open Org clocks. +If `only-dangling-p' is non-nil, only ask to resolve dangling +\(i.e., not currently open and valid) clocks." + (interactive "P") + (unless org-clock-resolving-clocks + (let ((org-clock-resolving-clocks t)) + (dolist (file (org-files-list)) + (let ((clocks (org-find-open-clocks file))) + (dolist (clock clocks) + (let ((dangling (or (not (org-clock-is-active)) + (/= (car clock) org-clock-marker)))) + (if (or (not only-dangling-p) dangling) + (org-clock-resolve + clock + (or prompt-fn + (function + (lambda (clock) + (format + "Dangling clock started %d mins ago" + (floor (- (float-time) + (float-time (cdr clock))) + 60))))) + (or last-valid + (cdr clock))))))))))) + +(defun org-emacs-idle-seconds () + "Return the current Emacs idle time in seconds, or nil if not idle." + (let ((idle-time (current-idle-time))) + (if idle-time + (float-time idle-time) + 0))) + +(defun org-mac-idle-seconds () + "Return the current Mac idle time in seconds." + (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'"))) + +(defvar org-x11idle-exists-p + ;; Check that x11idle exists + (and (eq window-system 'x) + (eq 0 (call-process-shell-command + (format "command -v %s" org-clock-x11idle-program-name))) + ;; Check that x11idle can retrieve the idle time + ;; FIXME: Why "..-shell-command" rather than just `call-process'? + (eq 0 (call-process-shell-command org-clock-x11idle-program-name)))) + +(defun org-x11-idle-seconds () + "Return the current X11 idle time in seconds." + (/ (string-to-number (shell-command-to-string org-clock-x11idle-program-name)) 1000)) + +(defun org-user-idle-seconds () + "Return the number of seconds the user has been idle for. +This routine returns a floating point number." + (cond + ((eq system-type 'darwin) + (org-mac-idle-seconds)) + ((and (eq window-system 'x) org-x11idle-exists-p) + (org-x11-idle-seconds)) + (t + (org-emacs-idle-seconds)))) + +(defvar org-clock-user-idle-seconds) + +(defun org-resolve-clocks-if-idle () + "Resolve all currently open Org clocks. +This is performed after `org-clock-idle-time' minutes, to check +if the user really wants to stay clocked in after being idle for +so long." + (when (and org-clock-idle-time (not org-clock-resolving-clocks) + org-clock-marker (marker-buffer org-clock-marker)) + (let* ((org-clock-user-idle-seconds (org-user-idle-seconds)) + (org-clock-user-idle-start + (time-subtract (current-time) + (seconds-to-time org-clock-user-idle-seconds))) + (org-clock-resolving-clocks-due-to-idleness t)) + (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time)) + (org-clock-resolve + (cons org-clock-marker + org-clock-start-time) + (lambda (_) + (format "Clocked in & idle for %.1f mins" + (/ (float-time + (time-subtract (current-time) + org-clock-user-idle-start)) + 60.0))) + org-clock-user-idle-start))))) + +(defvar org-clock-current-task nil "Task currently clocked in.") +(defvar org-clock-out-time nil) ; store the time of the last clock-out +(defvar org--msg-extra) + +;;;###autoload +(defun org-clock-in (&optional select start-time) + "Start the clock on the current item. + +If necessary, clock-out of the currently active clock. + +With a `\\[universal-argument]' prefix argument SELECT, offer a list of \ +recently clocked +tasks to clock into. + +When SELECT is `\\[universal-argument] \ \\[universal-argument]', \ +clock into the current task and mark it as +the default task, a special task that will always be offered in the +clocking selection, associated with the letter `d'. + +When SELECT is `\\[universal-argument] \\[universal-argument] \ +\\[universal-argument]', clock in by using the last clock-out +time as the start time. See `org-clock-continuously' to make this +the default behavior." + (interactive "P") + (setq org-clock-notification-was-shown nil) + (org-refresh-effort-properties) + (catch 'abort + (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness) + (org-clocking-p))) + ts selected-task target-pos (org--msg-extra "") + (leftover (and (not org-clock-resolving-clocks) + org-clock-leftover-time))) + + (when (and org-clock-auto-clock-resolution + (or (not interrupting) + (eq t org-clock-auto-clock-resolution)) + (not org-clock-clocking-in) + (not org-clock-resolving-clocks)) + (setq org-clock-leftover-time nil) + (let ((org-clock-clocking-in t)) + (org-resolve-clocks))) ; check if any clocks are dangling + + (when (equal select '(64)) + ;; Set start-time to `org-clock-out-time' + (let ((org-clock-continuously t)) + (org-clock-in nil org-clock-out-time) + (throw 'abort nil))) + + (when (equal select '(4)) + (setq selected-task (org-clock-select-task "Clock-in on task: ")) + (if selected-task + (setq selected-task (copy-marker selected-task)) + (error "Abort"))) + + (when (equal select '(16)) + ;; Mark as default clocking task + (org-clock-mark-default-task)) + + (when interrupting + ;; We are interrupting the clocking of a different task. + ;; Save a marker to this task, so that we can go back. + ;; First check if we are trying to clock into the same task! + (when (save-excursion + (unless selected-task + (org-back-to-heading t)) + (and (equal (marker-buffer org-clock-hd-marker) + (if selected-task + (marker-buffer selected-task) + (current-buffer))) + (= (marker-position org-clock-hd-marker) + (if selected-task + (marker-position selected-task) + (point))) + (equal org-clock-current-task (nth 4 (org-heading-components))))) + (message "Clock continues in \"%s\"" org-clock-heading) + (throw 'abort nil)) + (move-marker org-clock-interrupted-task + (marker-position org-clock-marker) + (marker-buffer org-clock-marker)) + (let ((org-clock-clocking-in t)) + (org-clock-out nil t))) + + ;; Clock in at which position? + (setq target-pos + (if (and (eobp) (not (org-at-heading-p))) + (point-at-bol 0) + (point))) + (save-excursion + (when (and selected-task (marker-buffer selected-task)) + ;; There is a selected task, move to the correct buffer + ;; and set the new target position. + (set-buffer (org-base-buffer (marker-buffer selected-task))) + (setq target-pos (marker-position selected-task)) + (move-marker selected-task nil)) + (org-with-wide-buffer + (goto-char target-pos) + (org-back-to-heading t) + (or interrupting (move-marker org-clock-interrupted-task nil)) + (run-hooks 'org-clock-in-prepare-hook) + (org-clock-history-push) + (setq org-clock-current-task (nth 4 (org-heading-components))) + (cond ((functionp org-clock-in-switch-to-state) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp)) + (let ((newstate (funcall org-clock-in-switch-to-state + (match-string 2)))) + (when newstate (org-todo newstate)))) + ((and org-clock-in-switch-to-state + (not (looking-at (concat org-outline-regexp "[ \t]*" + org-clock-in-switch-to-state + "\\>")))) + (org-todo org-clock-in-switch-to-state))) + (setq org-clock-heading (org-clock--mode-line-heading)) + (org-clock-find-position org-clock-in-resume) + (cond + ((and org-clock-in-resume + (looking-at + (concat "^[ \t]*" org-clock-string + " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}" + " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$"))) + (message "Matched %s" (match-string 1)) + (setq ts (concat "[" (match-string 1) "]")) + (goto-char (match-end 1)) + (setq org-clock-start-time + (apply 'encode-time + (org-parse-time-string (match-string 1)))) + (setq org-clock-effort (org-entry-get (point) org-effort-property)) + (setq org-clock-total-time (org-clock-sum-current-item + (org-clock-get-sum-start)))) + ((eq org-clock-in-resume 'auto-restart) + ;; called from org-clock-load during startup, + ;; do not interrupt, but warn! + (message "Cannot restart clock because task does not contain unfinished clock") + (ding) + (sit-for 2) + (throw 'abort nil)) + (t + (insert-before-markers "\n") + (backward-char 1) + (org-indent-line) + (when (and (save-excursion + (end-of-line 0) + (org-in-item-p))) + (beginning-of-line 1) + (indent-line-to (- (org-get-indentation) 2))) + (insert org-clock-string " ") + (setq org-clock-effort (org-entry-get (point) org-effort-property)) + (setq org-clock-total-time (org-clock-sum-current-item + (org-clock-get-sum-start))) + (setq org-clock-start-time + (or (and org-clock-continuously org-clock-out-time) + (and leftover + (y-or-n-p + (format + "You stopped another clock %d mins ago; start this one from then? " + (/ (- (float-time + (org-current-time org-clock-rounding-minutes t)) + (float-time leftover)) + 60))) + leftover) + start-time + (org-current-time org-clock-rounding-minutes t))) + (setq ts (org-insert-time-stamp org-clock-start-time + 'with-hm 'inactive)))) + (move-marker org-clock-marker (point) (buffer-base-buffer)) + (move-marker org-clock-hd-marker + (save-excursion (org-back-to-heading t) (point)) + (buffer-base-buffer)) + (setq org-clock-has-been-used t) + ;; add to mode line + (when (or (eq org-clock-clocked-in-display 'mode-line) + (eq org-clock-clocked-in-display 'both)) + (or global-mode-string (setq global-mode-string '(""))) + (or (memq 'org-mode-line-string global-mode-string) + (setq global-mode-string + (append global-mode-string '(org-mode-line-string))))) + ;; add to frame title + (when (or (eq org-clock-clocked-in-display 'frame-title) + (eq org-clock-clocked-in-display 'both)) + (setq frame-title-format org-clock-frame-title-format)) + (org-clock-update-mode-line) + (when org-clock-mode-line-timer + (cancel-timer org-clock-mode-line-timer) + (setq org-clock-mode-line-timer nil)) + (when org-clock-clocked-in-display + (setq org-clock-mode-line-timer + (run-with-timer org-clock-update-period + org-clock-update-period + 'org-clock-update-mode-line))) + (when org-clock-idle-timer + (cancel-timer org-clock-idle-timer) + (setq org-clock-idle-timer nil)) + (setq org-clock-idle-timer + (run-with-timer 60 60 'org-resolve-clocks-if-idle)) + (message "Clock starts at %s - %s" ts org--msg-extra) + (run-hooks 'org-clock-in-hook)))))) + +;;;###autoload +(defun org-clock-in-last (&optional arg) + "Clock in the last closed clocked item. +When already clocking in, send a warning. +With a universal prefix argument, select the task you want to +clock in from the last clocked in tasks. +With two universal prefix arguments, start clocking using the +last clock-out time, if any. +With three universal prefix arguments, interactively prompt +for a todo state to switch to, overriding the existing value +`org-clock-in-switch-to-state'." + (interactive "P") + (if (equal arg '(4)) (org-clock-in arg) + (let ((start-time (if (or org-clock-continuously (equal arg '(16))) + (or org-clock-out-time + (org-current-time org-clock-rounding-minutes t)) + (org-current-time org-clock-rounding-minutes t)))) + (if (null org-clock-history) + (message "No last clock") + (let ((org-clock-in-switch-to-state + (if (and (not org-clock-current-task) (equal arg '(64))) + (completing-read "Switch to state: " + (and org-clock-history + (with-current-buffer + (marker-buffer (car org-clock-history)) + org-todo-keywords-1))) + org-clock-in-switch-to-state)) + (already-clocking org-clock-current-task)) + (org-clock-clock-in (list (car org-clock-history)) nil start-time) + (or already-clocking + ;; Don't display a message if we are already clocking in + (message "Clocking back: %s (in %s)" + org-clock-current-task + (buffer-name (marker-buffer org-clock-marker))))))))) + +(defun org-clock-mark-default-task () + "Mark current task as default task." + (interactive) + (save-excursion + (org-back-to-heading t) + (move-marker org-clock-default-task (point)))) + +(defun org-clock-get-sum-start () + "Return the time from which clock times should be counted. + +This is for the currently running clock as it is displayed in the +mode line. This function looks at the properties LAST_REPEAT and +in particular CLOCK_MODELINE_TOTAL and the corresponding variable +`org-clock-mode-line-total' and then decides which time to use. + +The time is always returned as UTC." + (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL" 'selective) + (symbol-name org-clock-mode-line-total))) + (lr (org-entry-get nil "LAST_REPEAT"))) + (cond + ((equal cmt "current") + (setq org--msg-extra "showing time in current clock instance") + (current-time)) + ((equal cmt "today") + (setq org--msg-extra "showing today's task time.") + (let* ((dt (decode-time)) + (hour (nth 2 dt)) + (day (nth 3 dt))) + (if (< hour org-extend-today-until) (setf (nth 3 dt) (1- day))) + (setf (nth 2 dt) org-extend-today-until) + (apply #'encode-time (append (list 0 0) (nthcdr 2 dt))))) + ((or (equal cmt "all") + (and (or (not cmt) (equal cmt "auto")) + (not lr))) + (setq org--msg-extra "showing entire task time.") + nil) + ((or (equal cmt "repeat") + (and (or (not cmt) (equal cmt "auto")) + lr)) + (setq org--msg-extra "showing task time since last repeat.") + (and lr (org-time-string-to-time lr))) + (t nil)))) + +(defun org-clock-find-position (find-unclosed) + "Find the location where the next clock line should be inserted. +When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock +line and position cursor in that line." + (org-back-to-heading t) + (catch 'exit + (let* ((beg (line-beginning-position)) + (end (save-excursion (outline-next-heading) (point))) + (org-clock-into-drawer (org-clock-into-drawer)) + (drawer (org-clock-drawer-name))) + ;; Look for a running clock if FIND-UNCLOSED in non-nil. + (when find-unclosed + (let ((open-clock-re + (concat "^[ \t]*" + org-clock-string + " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}" + " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$"))) + (while (re-search-forward open-clock-re end t) + (let ((element (org-element-at-point))) + (when (and (eq (org-element-type element) 'clock) + (eq (org-element-property :status element) 'running)) + (beginning-of-line) + (throw 'exit t)))))) + ;; Look for an existing clock drawer. + (when drawer + (goto-char beg) + (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))) + (while (re-search-forward drawer-re end t) + (let ((element (org-element-at-point))) + (when (eq (org-element-type element) 'drawer) + (let ((cend (org-element-property :contents-end element))) + (if (and (not org-log-states-order-reversed) cend) + (goto-char cend) + (forward-line)) + (throw 'exit t))))))) + (goto-char beg) + (let ((clock-re (concat "^[ \t]*" org-clock-string)) + (count 0) + positions) + ;; Count the CLOCK lines and store their positions. + (save-excursion + (while (re-search-forward clock-re end t) + (let ((element (org-element-at-point))) + (when (eq (org-element-type element) 'clock) + (setq positions (cons (line-beginning-position) positions) + count (1+ count)))))) + (cond + ((null positions) + ;; Skip planning line and property drawer, if any. + (org-end-of-meta-data) + (unless (bolp) (insert "\n")) + ;; Create a new drawer if necessary. + (when (and org-clock-into-drawer + (or (not (wholenump org-clock-into-drawer)) + (< org-clock-into-drawer 2))) + (let ((beg (point))) + (insert ":" drawer ":\n:END:\n") + (org-indent-region beg (point)) + (goto-char beg) + (org-flag-drawer t) + (forward-line)))) + ;; When a clock drawer needs to be created because of the + ;; number of clock items or simply if it is missing, collect + ;; all clocks in the section and wrap them within the drawer. + ((if (wholenump org-clock-into-drawer) + (>= (1+ count) org-clock-into-drawer) + drawer) + ;; Skip planning line and property drawer, if any. + (org-end-of-meta-data) + (let ((beg (point))) + (insert + (mapconcat + (lambda (p) + (save-excursion + (goto-char p) + (org-trim (delete-and-extract-region + (save-excursion (skip-chars-backward " \r\t\n") + (line-beginning-position 2)) + (line-beginning-position 2))))) + positions "\n") + "\n:END:\n") + (let ((end (point-marker))) + (goto-char beg) + (save-excursion (insert ":" drawer ":\n")) + (org-flag-drawer t) + (org-indent-region (point) end) + (forward-line) + (unless org-log-states-order-reversed + (goto-char end) + (beginning-of-line -1)) + (set-marker end nil)))) + (org-log-states-order-reversed (goto-char (car (last positions)))) + (t (goto-char (car positions)))))))) + +;;;###autoload +(defun org-clock-out (&optional switch-to-state fail-quietly at-time) + "Stop the currently running clock. +Throw an error if there is no running clock and FAIL-QUIETLY is nil. +With a universal prefix, prompt for a state to switch the clocked out task +to, overriding the existing value of `org-clock-out-switch-to-state'." + (interactive "P") + (catch 'exit + (when (not (org-clocking-p)) + (setq global-mode-string + (delq 'org-mode-line-string global-mode-string)) + (setq frame-title-format org-frame-title-format-backup) + (force-mode-line-update) + (if fail-quietly (throw 'exit t) (user-error "No active clock"))) + (let ((org-clock-out-switch-to-state + (if switch-to-state + (completing-read "Switch to state: " + (with-current-buffer + (marker-buffer org-clock-marker) + org-todo-keywords-1) + nil t "DONE") + org-clock-out-switch-to-state)) + (now (org-current-time org-clock-rounding-minutes)) + ts te s h m remove) + (setq org-clock-out-time now) + (save-excursion ; Do not replace this with `with-current-buffer'. + (with-no-warnings (set-buffer (org-clocking-buffer))) + (save-restriction + (widen) + (goto-char org-clock-marker) + (beginning-of-line 1) + (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp)) + (equal (match-string 1) org-clock-string)) + (setq ts (match-string 2)) + (if fail-quietly (throw 'exit nil) (error "Clock start time is gone"))) + (goto-char (match-end 0)) + (delete-region (point) (point-at-eol)) + (insert "--") + (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive)) + (setq s (- (float-time + (apply #'encode-time (org-parse-time-string te))) + (float-time + (apply #'encode-time (org-parse-time-string ts)))) + h (floor (/ s 3600)) + s (- s (* 3600 h)) + m (floor (/ s 60)) + s (- s (* 60 s))) + (insert " => " (format "%2d:%02d" h m)) + (move-marker org-clock-marker nil) + (move-marker org-clock-hd-marker nil) + ;; Possibly remove zero time clocks. However, do not add + ;; a note associated to the CLOCK line in this case. + (cond ((and org-clock-out-remove-zero-time-clocks + (= (+ h m) 0)) + (setq remove t) + (delete-region (line-beginning-position) + (line-beginning-position 2))) + (org-log-note-clock-out + (org-add-log-setup + 'clock-out nil nil nil + (concat "# Task: " (org-get-heading t) "\n\n")))) + (when org-clock-mode-line-timer + (cancel-timer org-clock-mode-line-timer) + (setq org-clock-mode-line-timer nil)) + (when org-clock-idle-timer + (cancel-timer org-clock-idle-timer) + (setq org-clock-idle-timer nil)) + (setq global-mode-string + (delq 'org-mode-line-string global-mode-string)) + (setq frame-title-format org-frame-title-format-backup) + (when org-clock-out-switch-to-state + (save-excursion + (org-back-to-heading t) + (let ((org-clock-out-when-done nil)) + (cond + ((functionp org-clock-out-switch-to-state) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp)) + (let ((newstate (funcall org-clock-out-switch-to-state + (match-string 2)))) + (when newstate (org-todo newstate)))) + ((and org-clock-out-switch-to-state + (not (looking-at (concat org-outline-regexp "[ \t]*" + org-clock-out-switch-to-state + "\\>")))) + (org-todo org-clock-out-switch-to-state)))))) + (force-mode-line-update) + (message (concat "Clock stopped at %s after " + (org-duration-from-minutes (+ (* 60 h) m)) "%s") + te (if remove " => LINE REMOVED" "")) + (run-hooks 'org-clock-out-hook) + (unless (org-clocking-p) + (setq org-clock-current-task nil))))))) + +(add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer) + +(defun org-clock-remove-empty-clock-drawer () + "Remove empty clock drawers in current subtree." + (save-excursion + (org-back-to-heading t) + (org-map-tree + (lambda () + (let ((drawer (org-clock-drawer-name)) + (case-fold-search t)) + (when drawer + (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer))) + (end (save-excursion (outline-next-heading)))) + (while (re-search-forward re end t) + (org-remove-empty-drawer-at (point)))))))))) + +(defun org-clock-timestamps-up (&optional n) + "Increase CLOCK timestamps at cursor. +Optional argument N tells to change by that many units." + (interactive "P") + (org-clock-timestamps-change 'up n)) + +(defun org-clock-timestamps-down (&optional n) + "Increase CLOCK timestamps at cursor. +Optional argument N tells to change by that many units." + (interactive "P") + (org-clock-timestamps-change 'down n)) + +(defun org-clock-timestamps-change (updown &optional n) + "Change CLOCK timestamps synchronously at cursor. +UPDOWN tells whether to change `up' or `down'. +Optional argument N tells to change by that many units." + (let ((tschange (if (eq updown 'up) 'org-timestamp-up + 'org-timestamp-down)) + (timestamp? (org-at-timestamp-p 'lax)) + ts1 begts1 ts2 begts2 updatets1 tdiff) + (when timestamp? + (save-excursion + (move-beginning-of-line 1) + (re-search-forward org-ts-regexp3 nil t) + (setq ts1 (match-string 0) begts1 (match-beginning 0)) + (when (re-search-forward org-ts-regexp3 nil t) + (setq ts2 (match-string 0) begts2 (match-beginning 0)))) + ;; Are we on the second timestamp? + (if (<= begts2 (point)) (setq updatets1 t)) + (if (not ts2) + ;; fall back on org-timestamp-up if there is only one + (funcall tschange n) + (funcall tschange n) + (let ((ts (if updatets1 ts2 ts1)) + (begts (if updatets1 begts1 begts2))) + (setq tdiff + (time-subtract + (org-time-string-to-time org-last-changed-timestamp) + (org-time-string-to-time ts))) + (save-excursion + (goto-char begts) + (org-timestamp-change + (round (/ (float-time tdiff) + (pcase timestamp? + (`minute 60) + (`hour 3600) + (`day (* 24 3600)) + (`month (* 24 3600 31)) + (`year (* 24 3600 365.2))))) + timestamp? 'updown))))))) + +;;;###autoload +(defun org-clock-cancel () + "Cancel the running clock by removing the start timestamp." + (interactive) + (when (not (org-clocking-p)) + (setq global-mode-string + (delq 'org-mode-line-string global-mode-string)) + (setq frame-title-format org-frame-title-format-backup) + (force-mode-line-update) + (error "No active clock")) + (save-excursion ; Do not replace this with `with-current-buffer'. + (with-no-warnings (set-buffer (org-clocking-buffer))) + (goto-char org-clock-marker) + (if (looking-back (concat "^[ \t]*" org-clock-string ".*") + (line-beginning-position)) + (progn (delete-region (1- (point-at-bol)) (point-at-eol)) + (org-remove-empty-drawer-at (point))) + (message "Clock gone, cancel the timer anyway") + (sit-for 2))) + (move-marker org-clock-marker nil) + (move-marker org-clock-hd-marker nil) + (setq global-mode-string + (delq 'org-mode-line-string global-mode-string)) + (setq frame-title-format org-frame-title-format-backup) + (force-mode-line-update) + (message "Clock canceled") + (run-hooks 'org-clock-cancel-hook)) + +;;;###autoload +(defun org-clock-goto (&optional select) + "Go to the currently clocked-in entry, or to the most recently clocked one. +With prefix arg SELECT, offer recently clocked tasks for selection." + (interactive "@P") + (let* ((recent nil) + (m (cond + (select + (or (org-clock-select-task "Select task to go to: ") + (error "No task selected"))) + ((org-clocking-p) org-clock-marker) + ((and org-clock-goto-may-find-recent-task + (car org-clock-history) + (marker-buffer (car org-clock-history))) + (setq recent t) + (car org-clock-history)) + (t (error "No active or recent clock task"))))) + (pop-to-buffer-same-window (marker-buffer m)) + (if (or (< m (point-min)) (> m (point-max))) (widen)) + (goto-char m) + (org-show-entry) + (org-back-to-heading t) + (org-cycle-hide-drawers 'children) + (recenter org-clock-goto-before-context) + (org-reveal) + (if recent + (message "No running clock, this is the most recently clocked task")) + (run-hooks 'org-clock-goto-hook))) + +(defvar-local org-clock-file-total-minutes nil + "Holds the file total time in minutes, after a call to `org-clock-sum'.") + +;;;###autoload +(defun org-clock-sum-today (&optional headline-filter) + "Sum the times for each subtree for today." + (let ((range (org-clock-special-range 'today))) + (org-clock-sum (car range) (cadr range) + headline-filter :org-clock-minutes-today))) + +(defun org-clock-sum-custom (&optional headline-filter range propname) + "Sum the times for each subtree for today." + (let ((r (or (and (symbolp range) (org-clock-special-range range)) + (org-clock-special-range + (intern (completing-read + "Range: " + '("today" "yesterday" "thisweek" "lastweek" + "thismonth" "lastmonth" "thisyear" "lastyear" + "interactive") + nil t)))))) + (org-clock-sum (car r) (cadr r) + headline-filter (or propname :org-clock-minutes-custom)))) + +;;;###autoload +(defun org-clock-sum (&optional tstart tend headline-filter propname) + "Sum the times for each subtree. +Puts the resulting times in minutes as a text property on each headline. +TSTART and TEND can mark a time range to be considered. +HEADLINE-FILTER is a zero-arg function that, if specified, is called for +each headline in the time range with point at the headline. Headlines for +which HEADLINE-FILTER returns nil are excluded from the clock summation. +PROPNAME lets you set a custom text property instead of :org-clock-minutes." + (org-with-silent-modifications + (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*" + org-clock-string + "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)")) + (lmax 30) + (ltimes (make-vector lmax 0)) + (level 0) + (tstart (cond ((stringp tstart) (org-time-string-to-seconds tstart)) + ((consp tstart) (float-time tstart)) + (t tstart))) + (tend (cond ((stringp tend) (org-time-string-to-seconds tend)) + ((consp tend) (float-time tend)) + (t tend))) + (t1 0) + time) + (remove-text-properties (point-min) (point-max) + `(,(or propname :org-clock-minutes) t + :org-clock-force-headline-inclusion t)) + (save-excursion + (goto-char (point-max)) + (while (re-search-backward re nil t) + (cond + ((match-end 2) + ;; Two time stamps. + (let* ((ts (float-time + (apply #'encode-time + (save-match-data + (org-parse-time-string (match-string 2)))))) + (te (float-time + (apply #'encode-time + (org-parse-time-string (match-string 3))))) + (dt (- (if tend (min te tend) te) + (if tstart (max ts tstart) ts)))) + (when (> dt 0) (cl-incf t1 (floor (/ dt 60)))))) + ((match-end 4) + ;; A naked time. + (setq t1 (+ t1 (string-to-number (match-string 5)) + (* 60 (string-to-number (match-string 4)))))) + (t ;A headline + ;; Add the currently clocking item time to the total. + (when (and org-clock-report-include-clocking-task + (eq (org-clocking-buffer) (current-buffer)) + (eq (marker-position org-clock-hd-marker) (point)) + tstart + tend + (>= (float-time org-clock-start-time) tstart) + (<= (float-time org-clock-start-time) tend)) + (let ((time (floor (- (float-time) + (float-time org-clock-start-time)) + 60))) + (setq t1 (+ t1 time)))) + (let* ((headline-forced + (get-text-property (point) + :org-clock-force-headline-inclusion)) + (headline-included + (or (null headline-filter) + (save-excursion + (save-match-data (funcall headline-filter)))))) + (setq level (- (match-end 1) (match-beginning 1))) + (when (>= level lmax) + (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax))) + (when (or (> t1 0) (> (aref ltimes level) 0)) + (when (or headline-included headline-forced) + (if headline-included + (cl-loop for l from 0 to level do + (aset ltimes l (+ (aref ltimes l) t1)))) + (setq time (aref ltimes level)) + (goto-char (match-beginning 0)) + (put-text-property (point) (point-at-eol) + (or propname :org-clock-minutes) time) + (when headline-filter + (save-excursion + (save-match-data + (while (org-up-heading-safe) + (put-text-property + (point) (line-end-position) + :org-clock-force-headline-inclusion t)))))) + (setq t1 0) + (cl-loop for l from level to (1- lmax) do + (aset ltimes l 0))))))) + (setq org-clock-file-total-minutes (aref ltimes 0)))))) + +(defun org-clock-sum-current-item (&optional tstart) + "Return time, clocked on current item in total." + (save-excursion + (save-restriction + (org-narrow-to-subtree) + (org-clock-sum tstart) + org-clock-file-total-minutes))) + +;;;###autoload +(defun org-clock-display (&optional arg) + "Show subtree times in the entire buffer. + +By default, show the total time for the range defined in +`org-clock-display-default-range'. With `\\[universal-argument]' \ +prefix, show +the total time for today instead. + +With `\\[universal-argument] \\[universal-argument]' prefix, \ +use a custom range, entered at prompt. + +With `\\[universal-argument] \ \\[universal-argument] \ +\\[universal-argument]' prefix, display the total time in the +echo area. + +Use `\\[org-clock-remove-overlays]' to remove the subtree times." + (interactive "P") + (org-clock-remove-overlays) + (let* ((todayp (equal arg '(4))) + (customp (member arg '((16) today yesterday + thisweek lastweek thismonth + lastmonth thisyear lastyear + untilnow interactive))) + (prop (cond ((not arg) :org-clock-minutes-default) + (todayp :org-clock-minutes-today) + (customp :org-clock-minutes-custom) + (t :org-clock-minutes)))) + (cond ((not arg) (org-clock-sum-custom + nil org-clock-display-default-range prop)) + (todayp (org-clock-sum-today)) + (customp (org-clock-sum-custom nil arg)) + (t (org-clock-sum))) + (unless (equal arg '(64)) + (save-excursion + (goto-char (point-min)) + (let ((p nil)) + (while (or (and (equal (setq p (point)) (point-min)) + (get-text-property p prop)) + (setq p (next-single-property-change (point) prop))) + (goto-char p) + (let ((time (get-text-property p prop))) + (when time (org-clock-put-overlay time))))) + ;; Arrange to remove the overlays upon next change. + (when org-remove-highlights-with-change + (add-hook 'before-change-functions 'org-clock-remove-overlays + nil 'local)))) + (let* ((h (/ org-clock-file-total-minutes 60)) + (m (- org-clock-file-total-minutes (* 60 h)))) + (message (concat (format "Total file time%s: " + (cond (todayp " for today") + (customp " (custom)") + (t ""))) + (org-duration-from-minutes + org-clock-file-total-minutes) + " (%d hours and %d minutes)") + h m)))) + +(defvar-local org-clock-overlays nil) + +(defun org-clock-put-overlay (time) + "Put an overlays on the current line, displaying TIME. +This creates a new overlay and stores it in `org-clock-overlays', so that it +will be easy to remove." + (let (ov tx) + (beginning-of-line) + (let ((case-fold-search nil)) + (when (looking-at org-complex-heading-regexp) + (goto-char (match-beginning 4)))) + (setq ov (make-overlay (point) (point-at-eol)) + tx (concat (buffer-substring-no-properties (point) (match-end 4)) + (org-add-props + (make-string + (max 0 (- (- 60 (current-column)) + (- (match-end 4) (match-beginning 4)) + (length (org-get-at-bol 'line-prefix)))) + ?\·) + '(face shadow)) + (org-add-props + (format " %9s " (org-duration-from-minutes time)) + '(face org-clock-overlay)) + "")) + (overlay-put ov 'display tx) + (push ov org-clock-overlays))) + +;;;###autoload +(defun org-clock-remove-overlays (&optional _beg _end noremove) + "Remove the occur highlights from the buffer. +If NOREMOVE is nil, remove this function from the +`before-change-functions' in the current buffer." + (interactive) + (unless org-inhibit-highlight-removal + (mapc #'delete-overlay org-clock-overlays) + (setq org-clock-overlays nil) + (unless noremove + (remove-hook 'before-change-functions + 'org-clock-remove-overlays 'local)))) + +(defvar org-state) ;; dynamically scoped into this function +(defun org-clock-out-if-current () + "Clock out if the current entry contains the running clock. +This is used to stop the clock after a TODO entry is marked DONE, +and is only done if the variable `org-clock-out-when-done' is not nil." + (when (and (org-clocking-p) + org-clock-out-when-done + (marker-buffer org-clock-marker) + (or (and (eq t org-clock-out-when-done) + (member org-state org-done-keywords)) + (and (listp org-clock-out-when-done) + (member org-state org-clock-out-when-done))) + (equal (or (buffer-base-buffer (org-clocking-buffer)) + (org-clocking-buffer)) + (or (buffer-base-buffer (current-buffer)) + (current-buffer))) + (< (point) org-clock-marker) + (> (save-excursion (outline-next-heading) (point)) + org-clock-marker)) + ;; Clock out, but don't accept a logging message for this. + (let ((org-log-note-clock-out nil) + (org-clock-out-switch-to-state nil)) + (org-clock-out)))) + +(add-hook 'org-after-todo-state-change-hook + 'org-clock-out-if-current) + +;;;###autoload +(defun org-clock-get-clocktable (&rest props) + "Get a formatted clocktable with parameters according to PROPS. +The table is created in a temporary buffer, fully formatted and +fontified, and then returned." + ;; Set the defaults + (setq props (plist-put props :name "clocktable")) + (unless (plist-member props :maxlevel) + (setq props (plist-put props :maxlevel 2))) + (unless (plist-member props :scope) + (setq props (plist-put props :scope 'agenda))) + (with-temp-buffer + (org-mode) + (org-create-dblock props) + (org-update-dblock) + (org-font-lock-ensure) + (forward-line 2) + (buffer-substring (point) (progn + (re-search-forward "^[ \t]*#\\+END" nil t) + (point-at-bol))))) + +;;;###autoload +(defun org-clock-report (&optional arg) + "Update or create a table containing a report about clocked time. + +If point is inside an existing clocktable block, update it. +Otherwise, insert a new one. + +The new table inherits its properties from the variable +`org-clock-clocktable-default-properties'. The scope of the +clocktable, when not specified in the previous variable, is +`subtree' when the function is called from within a subtree, and +`file' elsewhere. + +When called with a prefix argument, move to the first clock table +in the buffer and update it." + (interactive "P") + (org-clock-remove-overlays) + (when arg + (org-find-dblock "clocktable") + (org-show-entry)) + (pcase (org-in-clocktable-p) + (`nil + (org-create-dblock + (org-combine-plists + (list :scope (if (org-before-first-heading-p) 'file 'subtree)) + org-clock-clocktable-default-properties + '(:name "clocktable")))) + (start (goto-char start))) + (org-update-dblock)) + +(defun org-day-of-week (day month year) + "Returns the day of the week as an integer." + (nth 6 + (decode-time + (date-to-time + (format "%d-%02d-%02dT00:00:00" year month day))))) + +(defun org-quarter-to-date (quarter year) + "Get the date (week day year) of the first day of a given quarter." + (let (startday) + (cond + ((= quarter 1) + (setq startday (org-day-of-week 1 1 year)) + (cond + ((= startday 0) + (list 52 7 (- year 1))) + ((= startday 6) + (list 52 6 (- year 1))) + ((<= startday 4) + (list 1 startday year)) + ((> startday 4) + (list 53 startday (- year 1))) + ) + ) + ((= quarter 2) + (setq startday (org-day-of-week 1 4 year)) + (cond + ((= startday 0) + (list 13 startday year)) + ((< startday 4) + (list 14 startday year)) + ((>= startday 4) + (list 13 startday year)) + ) + ) + ((= quarter 3) + (setq startday (org-day-of-week 1 7 year)) + (cond + ((= startday 0) + (list 26 startday year)) + ((< startday 4) + (list 27 startday year)) + ((>= startday 4) + (list 26 startday year)) + ) + ) + ((= quarter 4) + (setq startday (org-day-of-week 1 10 year)) + (cond + ((= startday 0) + (list 39 startday year)) + ((<= startday 4) + (list 40 startday year)) + ((> startday 4) + (list 39 startday year))))))) + +(defun org-clock-special-range (key &optional time as-strings wstart mstart) + "Return two times bordering a special time range. + +KEY is a symbol specifying the range and can be one of `today', +`yesterday', `thisweek', `lastweek', `thismonth', `lastmonth', +`thisyear', `lastyear' or `untilnow'. If set to `interactive', +user is prompted for range boundaries. It can be a string or an +integer. + +By default, a week starts Monday 0:00 and ends Sunday 24:00. The +range is determined relative to TIME, which defaults to current +time. + +The return value is a list containing two internal times, one for +the beginning of the range and one for its end, like the ones +returned by `current time' or `encode-time' and a string used to +display information. If AS-STRINGS is non-nil, the returned +times will be formatted strings. + +If WSTART is non-nil, use this number to specify the starting day +of a week (monday is 1). If MSTART is non-nil, use this number +to specify the starting day of a month (1 is the first day of the +month). If you can combine both, the month starting day will +have priority." + (let* ((tm (decode-time time)) + (m (nth 1 tm)) + (h (nth 2 tm)) + (d (nth 3 tm)) + (month (nth 4 tm)) + (y (nth 5 tm)) + (dow (nth 6 tm)) + (skey (format "%s" key)) + (shift 0) + (q (cond ((>= month 10) 4) + ((>= month 7) 3) + ((>= month 4) 2) + (t 1))) + m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq) + (cond + ((string-match "\\`[0-9]+\\'" skey) + (setq y (string-to-number skey) month 1 d 1 key 'year)) + ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey) + (setq y (string-to-number (match-string 1 skey)) + month (string-to-number (match-string 2 skey)) + d 1 + key 'month)) + ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey) + (require 'cal-iso) + (let ((date (calendar-gregorian-from-absolute + (calendar-iso-to-absolute + (list (string-to-number (match-string 2 skey)) + 1 + (string-to-number (match-string 1 skey))))))) + (setq d (nth 1 date) + month (car date) + y (nth 2 date) + dow 1 + key 'week))) + ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey) + (require 'cal-iso) + (setq q (string-to-number (match-string 2 skey))) + (let ((date (calendar-gregorian-from-absolute + (calendar-iso-to-absolute + (org-quarter-to-date + q (string-to-number (match-string 1 skey))))))) + (setq d (nth 1 date) + month (car date) + y (nth 2 date) + dow 1 + key 'quarter))) + ((string-match + "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'" + skey) + (setq y (string-to-number (match-string 1 skey)) + month (string-to-number (match-string 2 skey)) + d (string-to-number (match-string 3 skey)) + key 'day)) + ((string-match "\\([-+][0-9]+\\)\\'" skey) + (setq shift (string-to-number (match-string 1 skey)) + key (intern (substring skey 0 (match-beginning 1)))) + (when (and (memq key '(quarter thisq)) (> shift 0)) + (error "Looking forward with quarters isn't implemented")))) + (when (= shift 0) + (pcase key + (`yesterday (setq key 'today shift -1)) + (`lastweek (setq key 'week shift -1)) + (`lastmonth (setq key 'month shift -1)) + (`lastyear (setq key 'year shift -1)) + (`lastq (setq key 'quarter shift -1)))) + ;; Prepare start and end times depending on KEY's type. + (pcase key + ((or `day `today) (setq m 0 h 0 h1 24 d (+ d shift))) + ((or `week `thisweek) + (let* ((ws (or wstart 1)) + (diff (+ (* -7 shift) (if (= dow 0) (- 7 ws) (- dow ws))))) + (setq m 0 h 0 d (- d diff) d1 (+ 7 d)))) + ((or `month `thismonth) + (setq h 0 m 0 d (or mstart 1) month (+ month shift) month1 (1+ month))) + ((or `quarter `thisq) + ;; Compute if this shift remains in this year. If not, compute + ;; how many years and quarters we have to shift (via floor*) and + ;; compute the shifted years, months and quarters. + (cond + ((< (+ (- q 1) shift) 0) ; Shift not in this year. + (let* ((interval (* -1 (+ (- q 1) shift))) + ;; Set tmp to ((years to shift) (quarters to shift)). + (tmp (cl-floor interval 4))) + ;; Due to the use of floor, 0 quarters actually means 4. + (if (= 0 (nth 1 tmp)) + (setq shiftedy (- y (nth 0 tmp)) + shiftedm 1 + shiftedq 1) + (setq shiftedy (- y (+ 1 (nth 0 tmp))) + shiftedm (- 13 (* 3 (nth 1 tmp))) + shiftedq (- 5 (nth 1 tmp))))) + (setq m 0 h 0 d 1 month shiftedm month1 (+ 3 shiftedm) y shiftedy)) + ((> (+ q shift) 0) ; Shift is within this year. + (setq shiftedq (+ q shift)) + (setq shiftedy y) + (let ((qshift (* 3 (1- (+ q shift))))) + (setq m 0 h 0 d 1 month (+ 1 qshift) month1 (+ 4 qshift)))))) + ((or `year `thisyear) + (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y))) + ((or `interactive `untilnow)) ; Special cases, ignore them. + (_ (user-error "No such time block %s" key))) + ;; Format start and end times according to AS-STRINGS. + (let* ((start (pcase key + (`interactive (org-read-date nil t nil "Range start? ")) + ;; In theory, all clocks started after the dawn of + ;; humanity. + (`untilnow (encode-time 0 0 0 0 0 -50000)) + (_ (encode-time 0 m h d month y)))) + (end (pcase key + (`interactive (org-read-date nil t nil "Range end? ")) + (`untilnow (current-time)) + (_ (encode-time 0 + (or m1 m) + (or h1 h) + (or d1 d) + (or month1 month) + (or y1 y))))) + (text + (pcase key + ((or `day `today) (format-time-string "%A, %B %d, %Y" start)) + ((or `week `thisweek) (format-time-string "week %G-W%V" start)) + ((or `month `thismonth) (format-time-string "%B %Y" start)) + ((or `year `thisyear) (format-time-string "the year %Y" start)) + ((or `quarter `thisq) + (concat (org-count-quarter shiftedq) + " quarter of " (number-to-string shiftedy))) + (`interactive "(Range interactively set)") + (`untilnow "now")))) + (if (not as-strings) (list start end text) + (let ((f (cdr org-time-stamp-formats))) + (list (format-time-string f start) + (format-time-string f end) + text)))))) + +(defun org-count-quarter (n) + (cond + ((= n 1) "1st") + ((= n 2) "2nd") + ((= n 3) "3rd") + ((= n 4) "4th"))) + +;;;###autoload +(defun org-clocktable-shift (dir n) + "Try to shift the :block date of the clocktable at point. +Point must be in the #+BEGIN: line of a clocktable, or this function +will throw an error. +DIR is a direction, a symbol `left', `right', `up', or `down'. +Both `left' and `down' shift the block toward the past, `up' and `right' +push it toward the future. +N is the number of shift steps to take. The size of the step depends on +the currently selected interval size." + (setq n (prefix-numeric-value n)) + (and (memq dir '(left down)) (setq n (- n))) + (save-excursion + (goto-char (point-at-bol)) + (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)")) + (error "Line needs a :block definition before this command works") + (let* ((b (match-beginning 1)) (e (match-end 1)) + (s (match-string 1)) + block shift ins y mw d date wp m) + (cond + ((equal s "yesterday") (setq s "today-1")) + ((equal s "lastweek") (setq s "thisweek-1")) + ((equal s "lastmonth") (setq s "thismonth-1")) + ((equal s "lastyear") (setq s "thisyear-1")) + ((equal s "lastq") (setq s "thisq-1"))) + + (cond + ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s) + (setq block (match-string 1 s) + shift (if (match-end 2) + (string-to-number (match-string 2 s)) + 0)) + (setq shift (+ shift n)) + (setq ins (if (= shift 0) block (format "%s%+d" block shift)))) + ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s) + ;; 1 1 2 3 3 4 4 5 6 6 5 2 + (setq y (string-to-number (match-string 1 s)) + wp (and (match-end 3) (match-string 3 s)) + mw (and (match-end 4) (string-to-number (match-string 4 s))) + d (and (match-end 6) (string-to-number (match-string 6 s)))) + (cond + (d (setq ins (format-time-string + "%Y-%m-%d" + (encode-time 0 0 0 (+ d n) m y)))) + ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0)) + (require 'cal-iso) + (setq date (calendar-gregorian-from-absolute + (calendar-iso-to-absolute (list (+ mw n) 1 y)))) + (setq ins (format-time-string + "%G-W%V" + (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date))))) + ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0)) + (require 'cal-iso) + ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year + (if (> (+ mw n) 4) + (setq mw 0 + y (+ 1 y)) + ()) + ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year + (if (= (+ mw n) 0) + (setq mw 5 + y (- y 1)) + ()) + (setq date (calendar-gregorian-from-absolute + (calendar-iso-to-absolute (org-quarter-to-date (+ mw n) y)))) + (setq ins (format-time-string + (concat (number-to-string y) "-Q" (number-to-string (+ mw n))) + (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date))))) + (mw + (setq ins (format-time-string + "%Y-%m" + (encode-time 0 0 0 1 (+ mw n) y)))) + (y + (setq ins (number-to-string (+ y n)))))) + (t (error "Cannot shift clocktable block"))) + (when ins + (goto-char b) + (insert ins) + (delete-region (point) (+ (point) (- e b))) + (beginning-of-line 1) + (org-update-dblock) + t))))) + +;;;###autoload +(defun org-dblock-write:clocktable (params) + "Write the standard clocktable." + (setq params (org-combine-plists org-clocktable-defaults params)) + (catch 'exit + (let* ((scope (plist-get params :scope)) + (files (pcase scope + (`agenda + (org-agenda-files t)) + (`agenda-with-archives + (org-add-archive-files (org-agenda-files t))) + (`file-with-archives + (and buffer-file-name + (org-add-archive-files (list buffer-file-name)))) + ((pred functionp) (funcall scope)) + ((pred consp) scope) + (_ (or (buffer-file-name) (current-buffer))))) + (block (plist-get params :block)) + (ts (plist-get params :tstart)) + (te (plist-get params :tend)) + (ws (plist-get params :wstart)) + (ms (plist-get params :mstart)) + (step (plist-get params :step)) + (formatter (or (plist-get params :formatter) + org-clock-clocktable-formatter + 'org-clocktable-write-default)) + cc) + ;; Check if we need to do steps + (when block + ;; Get the range text for the header + (setq cc (org-clock-special-range block nil t ws ms) + ts (car cc) + te (nth 1 cc))) + (when step + ;; Write many tables, in steps + (unless (or block (and ts te)) + (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'")) + (org-clocktable-steps params) + (throw 'exit nil)) + + (org-agenda-prepare-buffers (if (consp files) files (list files))) + + (let ((origin (point)) + (tables + (if (consp files) + (mapcar (lambda (file) + (with-current-buffer (find-buffer-visiting file) + (save-excursion + (save-restriction + (org-clock-get-table-data file params))))) + files) + ;; Get the right restriction for the scope. + (save-restriction + (cond + ((not scope)) ;use the restriction as it is now + ((eq scope 'file) (widen)) + ((eq scope 'subtree) (org-narrow-to-subtree)) + ((eq scope 'tree) + (while (org-up-heading-safe)) + (org-narrow-to-subtree)) + ((and (symbolp scope) + (string-match "\\`tree\\([0-9]+\\)\\'" + (symbol-name scope))) + (let ((level (string-to-number + (match-string 1 (symbol-name scope))))) + (catch 'exit + (while (org-up-heading-safe) + (looking-at org-outline-regexp) + (when (<= (org-reduced-level (funcall outline-level)) + level) + (throw 'exit nil)))) + (org-narrow-to-subtree)))) + (list (org-clock-get-table-data nil params))))) + (multifile + ;; Even though `file-with-archives' can consist of + ;; multiple files, we consider this is one extended file + ;; instead. + (and (consp files) (not (eq scope 'file-with-archives))))) + + (funcall formatter + origin + tables + (org-combine-plists params `(:multifile ,multifile))))))) + +(defun org-clocktable-write-default (ipos tables params) + "Write out a clock table at position IPOS in the current buffer. +TABLES is a list of tables with clocking data as produced by +`org-clock-get-table-data'. PARAMS is the parameter property list obtained +from the dynamic block definition." + ;; This function looks quite complicated, mainly because there are a + ;; lot of options which can add or remove columns. I have massively + ;; commented this function, the I hope it is understandable. If + ;; someone wants to write their own special formatter, this maybe + ;; much easier because there can be a fixed format with a + ;; well-defined number of columns... + (let* ((lang (or (plist-get params :lang) "en")) + (multifile (plist-get params :multifile)) + (block (plist-get params :block)) + (sort (plist-get params :sort)) + (header (plist-get params :header)) + (link (plist-get params :link)) + (maxlevel (or (plist-get params :maxlevel) 3)) + (emph (plist-get params :emphasize)) + (compact? (plist-get params :compact)) + (narrow (or (plist-get params :narrow) (and compact? '40!))) + (level? (and (not compact?) (plist-get params :level))) + (timestamp (plist-get params :timestamp)) + (properties (plist-get params :properties)) + (time-columns + (if (or compact? (< maxlevel 2)) 1 + ;; Deepest headline level is a hard limit for the number + ;; of time columns. + (let ((levels + (cl-mapcan + (lambda (table) + (pcase table + (`(,_ ,(and (pred wholenump) (pred (/= 0))) ,entries) + (mapcar #'car entries)))) + tables))) + (min maxlevel + (or (plist-get params :tcolumns) 100) + (if (null levels) 1 (apply #'max levels)))))) + (indent (or compact? (plist-get params :indent))) + (formula (plist-get params :formula)) + (case-fold-search t) + (total-time (apply #'+ (mapcar #'cadr tables))) + recalc narrow-cut-p) + + (when (and narrow (integerp narrow) link) + ;; We cannot have both integer narrow and link. + (message "Using hard narrowing in clocktable to allow for links") + (setq narrow (intern (format "%d!" narrow)))) + + (pcase narrow + ((or `nil (pred integerp)) nil) ;nothing to do + ((and (pred symbolp) + (guard (string-match-p "\\`[0-9]+!\\'" (symbol-name narrow)))) + (setq narrow-cut-p t) + (setq narrow (string-to-number (symbol-name narrow)))) + (_ (error "Invalid value %s of :narrow property in clock table" narrow))) + + ;; Now we need to output this table stuff. + (goto-char ipos) + + ;; Insert the text *before* the actual table. + (insert-before-markers + (or header + ;; Format the standard header. + (format "#+CAPTION: %s %s%s\n" + (org-clock--translate "Clock summary at" lang) + (format-time-string (org-time-stamp-format t t)) + (if block + (let ((range-text + (nth 2 (org-clock-special-range + block nil t + (plist-get params :wstart) + (plist-get params :mstart))))) + (format ", for %s." range-text)) + "")))) + + ;; Insert the narrowing line + (when (and narrow (integerp narrow) (not narrow-cut-p)) + (insert-before-markers + "|" ;table line starter + (if multifile "|" "") ;file column, maybe + (if level? "|" "") ;level column, maybe + (if timestamp "|" "") ;timestamp column, maybe + (if properties ;properties columns, maybe + (make-string (length properties) ?|) + "") + (format "<%d>| |\n" narrow))) ;headline and time columns + + ;; Insert the table header line + (insert-before-markers + "|" ;table line starter + (if multifile ;file column, maybe + (concat (org-clock--translate "File" lang) "|") + "") + (if level? ;level column, maybe + (concat (org-clock--translate "L" lang) "|") + "") + (if timestamp ;timestamp column, maybe + (concat (org-clock--translate "Timestamp" lang) "|") + "") + (if properties ;properties columns, maybe + (concat (mapconcat #'identity properties "|") "|") + "") + (concat (org-clock--translate "Headline" lang)"|") + (concat (org-clock--translate "Time" lang) "|") + (make-string (max 0 (1- time-columns)) ?|) ;other time columns + (if (eq formula '%) "%|\n" "\n")) + + ;; Insert the total time in the table + (insert-before-markers + "|-\n" ;a hline + "|" ;table line starter + (if multifile (format "| %s " (org-clock--translate "ALL" lang)) "") + ;file column, maybe + (if level? "|" "") ;level column, maybe + (if timestamp "|" "") ;timestamp column, maybe + (make-string (length properties) ?|) ;properties columns, maybe + (concat (format org-clock-total-time-cell-format + (org-clock--translate "Total time" lang)) + "| ") + (format org-clock-total-time-cell-format + (org-duration-from-minutes (or total-time 0))) ;time + "|" + (make-string (max 0 (1- time-columns)) ?|) + (cond ((not (eq formula '%)) "") + ((or (not total-time) (= total-time 0)) "0.0|") + (t "100.0|")) + "\n") + + ;; Now iterate over the tables and insert the data but only if any + ;; time has been collected. + (when (and total-time (> total-time 0)) + (pcase-dolist (`(,file-name ,file-time ,entries) tables) + (when (or (and file-time (> file-time 0)) + (not (plist-get params :fileskip0))) + (insert-before-markers "|-\n") ;hline at new file + ;; First the file time, if we have multiple files. + (when multifile + ;; Summarize the time collected from this file. + (insert-before-markers + (format (concat "| %s %s | %s%s" + (format org-clock-file-time-cell-format + (org-clock--translate "File time" lang)) + " | *%s*|\n") + (file-name-nondirectory file-name) + (if level? "| " "") ;level column, maybe + (if timestamp "| " "") ;timestamp column, maybe + (if properties ;properties columns, maybe + (make-string (length properties) ?|) + "") + (org-duration-from-minutes file-time)))) ;time + + ;; Get the list of node entries and iterate over it + (when (> maxlevel 0) + (pcase-dolist (`(,level ,headline ,ts ,time ,props) entries) + (when narrow-cut-p + (setq headline + (if (and (string-match + (format "\\`%s\\'" org-bracket-link-regexp) + headline) + (match-end 3)) + (format "[[%s][%s]]" + (match-string 1 headline) + (org-shorten-string (match-string 3 headline) + narrow)) + (org-shorten-string headline narrow)))) + (cl-flet ((format-field (f) (format (cond ((not emph) "%s |") + ((= level 1) "*%s* |") + ((= level 2) "/%s/ |") + (t "%s |")) + f))) + (insert-before-markers + "|" ;start the table line + (if multifile "|" "") ;free space for file name column? + (if level? (format "%d|" level) "") ;level, maybe + (if timestamp (concat ts "|") "") ;timestamp, maybe + (if properties ;properties columns, maybe + (concat (mapconcat (lambda (p) (or (cdr (assoc p props)) "")) + properties + "|") + "|") + "") + (if indent ;indentation + (org-clocktable-indent-string level) + "") + (format-field headline) + ;; Empty fields for higher levels. + (make-string (max 0 (1- (min time-columns level))) ?|) + (format-field (org-duration-from-minutes time)) + (make-string (max 0 (- time-columns level)) ?|) + (if (eq formula '%) + (format "%.1f |" (* 100 (/ time (float total-time)))) + "") + "\n"))))))) + (delete-char -1) + (cond + ;; Possibly rescue old formula? + ((or (not formula) (eq formula '%)) + (let ((contents (org-string-nw-p (plist-get params :content)))) + (when (and contents (string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents)) + (setq recalc t) + (insert "\n" (match-string 1 contents)) + (beginning-of-line 0)))) + ;; Insert specified formula line. + ((stringp formula) + (insert "\n#+TBLFM: " formula) + (setq recalc t)) + (t + (user-error "Invalid :formula parameter in clocktable"))) + ;; Back to beginning, align the table, recalculate if necessary. + (goto-char ipos) + (skip-chars-forward "^|") + (org-table-align) + (when org-hide-emphasis-markers + ;; We need to align a second time. + (org-table-align)) + (when sort + (save-excursion + (org-table-goto-line 3) + (org-table-goto-column (car sort)) + (org-table-sort-lines nil (cdr sort)))) + (when recalc (org-table-recalculate 'all)) + total-time)) + +(defun org-clocktable-indent-string (level) + "Return indentation string according to LEVEL. +LEVEL is an integer. Indent by two spaces per level above 1." + (if (= level 1) "" + (concat "\\_" (make-string (* 2 (1- level)) ?\s)))) + +(defun org-clocktable-steps (params) + "Step through the range to make a number of clock tables." + (let* ((ts (plist-get params :tstart)) + (te (plist-get params :tend)) + (ws (plist-get params :wstart)) + (ms (plist-get params :mstart)) + (step0 (plist-get params :step)) + (step (cdr (assq step0 '((day . 86400) (week . 604800))))) + (stepskip0 (plist-get params :stepskip0)) + (block (plist-get params :block)) + cc tsb) + (when block + (setq cc (org-clock-special-range block nil t ws ms) + ts (car cc) + te (nth 1 cc))) + (cond + ((numberp ts) + ;; If ts is a number, it's an absolute day number from + ;; org-agenda. + (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute ts))) + (setq ts (float-time (encode-time 0 0 0 day month year))))) + (ts + (setq ts (float-time (apply #'encode-time (org-parse-time-string ts)))))) + (cond + ((numberp te) + ;; Likewise for te. + (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute te))) + (setq te (float-time (encode-time 0 0 0 day month year))))) + (te + (setq te (float-time (apply #'encode-time (org-parse-time-string te)))))) + (setq tsb + (if (eq step0 'week) + (let ((dow (nth 6 (decode-time (seconds-to-time ts))))) + (if (<= dow ws) ts + (- ts (* 86400 (- dow ws))))) + ts)) + (while (< tsb te) + (unless (bolp) (insert "\n")) + (let ((start-time (seconds-to-time (max tsb ts)))) + (cl-incf tsb (let ((dow (nth 6 (decode-time (seconds-to-time tsb))))) + (if (or (eq step0 'day) + (= dow ws)) + step + (* 86400 (- ws dow))))) + (insert "\n" + (if (eq step0 'day) "Daily report: " + "Weekly report starting on: ") + (format-time-string (org-time-stamp-format nil t) start-time) + "\n") + (let ((table-begin (line-beginning-position 0)) + (step-time + (org-dblock-write:clocktable + (org-combine-plists + params + (list + :header "" :step nil :block nil + :tstart (format-time-string (org-time-stamp-format t t) + start-time) + :tend (format-time-string (org-time-stamp-format t t) + (seconds-to-time (min te tsb)))))))) + (re-search-forward "^[ \t]*#\\+END:") + (when (and stepskip0 (equal step-time 0)) + ;; Remove the empty table + (delete-region (line-beginning-position) table-begin)))) + (end-of-line 0)))) + +(defun org-clock-get-table-data (file params) + "Get the clocktable data for file FILE, with parameters PARAMS. +FILE is only for identification - this function assumes that +the correct buffer is current, and that the wanted restriction is +in place. +The return value will be a list with the file name and the total +file time (in minutes) as 1st and 2nd elements. The third element +of this list will be a list of headline entries. Each entry has the +following structure: + + (LEVEL HEADLINE TIMESTAMP TIME PROPERTIES) + +LEVEL: The level of the headline, as an integer. This will be + the reduced level, so 1,2,3,... even if only odd levels + are being used. +HEADLINE: The text of the headline. Depending on PARAMS, this may + already be formatted like a link. +TIMESTAMP: If PARAMS require it, this will be a time stamp found in the + entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive, + in this sequence. +TIME: The sum of all time spend in this tree, in minutes. This time + will of cause be restricted to the time block and tags match + specified in PARAMS. +PROPERTIES: The list properties specified in the `:properties' parameter + along with their value, as an alist following the pattern + (NAME . VALUE)." + (let* ((maxlevel (or (plist-get params :maxlevel) 3)) + (timestamp (plist-get params :timestamp)) + (ts (plist-get params :tstart)) + (te (plist-get params :tend)) + (ws (plist-get params :wstart)) + (ms (plist-get params :mstart)) + (block (plist-get params :block)) + (link (plist-get params :link)) + (tags (plist-get params :tags)) + (properties (plist-get params :properties)) + (inherit-property-p (plist-get params :inherit-props)) + (matcher (and tags (cdr (org-make-tags-matcher tags)))) + cc st p tbl) + + (setq org-clock-file-total-minutes nil) + (when block + (setq cc (org-clock-special-range block nil t ws ms) + ts (car cc) + te (nth 1 cc))) + (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts))) + (when (integerp te) (setq te (calendar-gregorian-from-absolute te))) + (when (and ts (listp ts)) + (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts)))) + (when (and te (listp te)) + (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te)))) + ;; Now the times are strings we can parse. + (if ts (setq ts (org-matcher-time ts))) + (if te (setq te (org-matcher-time te))) + (save-excursion + (org-clock-sum ts te + (when matcher + `(lambda () + (let* ((tags-list (org-get-tags-at)) + (org-scanner-tags tags-list) + (org-trust-scanner-tags t)) + (funcall ,matcher nil tags-list nil))))) + (goto-char (point-min)) + (setq st t) + (while (or (and (bobp) (prog1 st (setq st nil)) + (get-text-property (point) :org-clock-minutes) + (setq p (point-min))) + (setq p (next-single-property-change + (point) :org-clock-minutes))) + (goto-char p) + (let ((time (get-text-property p :org-clock-minutes))) + (when (and time (> time 0) (org-at-heading-p)) + (let ((level (org-reduced-level (org-current-level)))) + (when (<= level maxlevel) + (let* ((headline (org-get-heading t t t t)) + (hdl + (if (not link) headline + (let ((search + (org-make-org-heading-search-string headline))) + (org-make-link-string + (if (not (buffer-file-name)) search + (format "file:%s::%s" (buffer-file-name) search)) + ;; Prune statistics cookies. Replace + ;; links with their description, or + ;; a plain link if there is none. + (org-trim + (org-link-display-format + (replace-regexp-in-string + "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" + headline))))))) + (tsp + (and timestamp + (cl-some (lambda (p) (org-entry-get (point) p)) + '("SCHEDULED" "DEADLINE" "TIMESTAMP" + "TIMESTAMP_IA")))) + (props + (and properties + (delq nil + (mapcar + (lambda (p) + (let ((v (org-entry-get + (point) p inherit-property-p))) + (and v (cons p v)))) + properties))))) + (push (list level hdl tsp time props) tbl))))))) + (list file org-clock-file-total-minutes (nreverse tbl))))) + +;; Saving and loading the clock + +(defvar org-clock-loaded nil + "Was the clock file loaded?") + +;;;###autoload +(defun org-clock-update-time-maybe () + "If this is a CLOCK line, update it and return t. +Otherwise, return nil." + (interactive) + (save-excursion + (beginning-of-line 1) + (skip-chars-forward " \t") + (when (looking-at org-clock-string) + (let ((re (concat "[ \t]*" org-clock-string + " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]" + "\\([ \t]*=>.*\\)?\\)?")) + ts te h m s neg) + (cond + ((not (looking-at re)) + nil) + ((not (match-end 2)) + (when (and (equal (marker-buffer org-clock-marker) (current-buffer)) + (> org-clock-marker (point)) + (<= org-clock-marker (point-at-eol))) + ;; The clock is running here + (setq org-clock-start-time + (apply 'encode-time + (org-parse-time-string (match-string 1)))) + (org-clock-update-mode-line))) + (t + (and (match-end 4) (delete-region (match-beginning 4) (match-end 4))) + (end-of-line 1) + (setq ts (match-string 1) + te (match-string 3)) + (setq s (- (float-time + (apply #'encode-time (org-parse-time-string te))) + (float-time + (apply #'encode-time (org-parse-time-string ts)))) + neg (< s 0) + s (abs s) + h (floor (/ s 3600)) + s (- s (* 3600 h)) + m (floor (/ s 60)) + s (- s (* 60 s))) + (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m)) + t)))))) + +(defun org-clock-save () + "Persist various clock-related data to disk. +The details of what will be saved are regulated by the variable +`org-clock-persist'." + (when (and org-clock-persist + (or org-clock-loaded + org-clock-has-been-used + (not (file-exists-p org-clock-persist-file)))) + (with-temp-file org-clock-persist-file + (insert (format ";; %s - %s at %s\n" + (file-name-nondirectory org-clock-persist-file) + (system-name) + (format-time-string (org-time-stamp-format t)))) + ;; Store clock to be resumed. + (when (and (memq org-clock-persist '(t clock)) + (let ((b (org-base-buffer (org-clocking-buffer)))) + (and (buffer-live-p b) + (buffer-file-name b) + (or (not org-clock-persist-query-save) + (y-or-n-p (format "Save current clock (%s) " + org-clock-heading)))))) + (insert + (format "(setq org-clock-stored-resume-clock '(%S . %d))\n" + (buffer-file-name (org-base-buffer (org-clocking-buffer))) + (marker-position org-clock-marker)))) + ;; Store clocked task history. Tasks are stored reversed to + ;; make reading simpler. + (when (and (memq org-clock-persist '(t history)) + org-clock-history) + (insert + (format "(setq org-clock-stored-history '(%s))\n" + (mapconcat + (lambda (m) + (let ((b (org-base-buffer (marker-buffer m)))) + (when (and (buffer-live-p b) + (buffer-file-name b)) + (format "(%S . %d)" + (buffer-file-name b) + (marker-position m))))) + (reverse org-clock-history) + " "))))))) + +(defun org-clock-load () + "Load clock-related data from disk, maybe resuming a stored clock." + (when (and org-clock-persist (not org-clock-loaded)) + (if (not (file-readable-p org-clock-persist-file)) + (message "Not restoring clock data; %S not found" org-clock-persist-file) + (message "Restoring clock data") + ;; Load history. + (load-file org-clock-persist-file) + (setq org-clock-loaded t) + (pcase-dolist (`(,(and file (pred file-exists-p)) . ,position) + org-clock-stored-history) + (org-clock-history-push position (find-file-noselect file))) + ;; Resume clock. + (pcase org-clock-stored-resume-clock + (`(,(and file (pred file-exists-p)) . ,position) + (with-current-buffer (find-file-noselect file) + (when (or (not org-clock-persist-query-resume) + (y-or-n-p (format "Resume clock (%s) " + (save-excursion + (goto-char position) + (org-get-heading t t))))) + (goto-char position) + (let ((org-clock-in-resume 'auto-restart) + (org-clock-auto-clock-resolution nil)) + (org-clock-in) + (when (org-invisible-p) (org-show-context)))))) + (_ nil))))) + +;; Suggested bindings +(org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate) + +(provide 'org-clock) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; coding: utf-8 +;; End: + +;;; org-clock.el ends here diff --git a/elpa/org-9.1.14/org-colview.el b/elpa/org-9.1.14/org-colview.el new file mode 100644 index 00000000..cb5c091d --- /dev/null +++ b/elpa/org-9.1.14/org-colview.el @@ -0,0 +1,1636 @@ +;;; org-colview.el --- Column View in Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file contains the column view for Org. + +;;; Code: + +(require 'cl-lib) +(require 'org) + +(declare-function org-agenda-redo "org-agenda" (&optional all)) +(declare-function org-agenda-do-context-action "org-agenda" ()) +(declare-function org-clock-sum-today "org-clock" (&optional headline-filter)) +(declare-function org-element-extract-element "org-element" (element)) +(declare-function org-element-interpret-data "org-element" (data)) +(declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated)) +(declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-restriction "org-element" (element)) +(declare-function org-element-type "org-element" (element)) + +(defvar org-agenda-columns-add-appointments-to-effort-sum) +(defvar org-agenda-columns-compute-summary-properties) +(defvar org-agenda-columns-show-summaries) +(defvar org-agenda-view-columns-initially) +(defvar org-inlinetask-min-level) + + +;;; Configuration + +(defcustom org-columns-modify-value-for-display-function nil + "Function that modifies values for display in column view. +For example, it can be used to cut out a certain part from a time stamp. +The function must take 2 arguments: + +column-title The title of the column (*not* the property name) +value The value that should be modified. + +The function should return the value that should be displayed, +or nil if the normal value should be used." + :group 'org-properties + :type '(choice (const nil) (function))) + +(defcustom org-columns-summary-types nil + "Alist between operators and summarize functions. + +Each association follows the pattern (LABEL . SUMMARIZE) where + + LABEL is a string used in #+COLUMNS definition describing the + summary type. It can contain any character but \"}\". It is + case-sensitive. + + SUMMARIZE is a function called with two arguments. The first + argument is a non-empty list of values, as non-empty strings. + The second one is a format string or nil. It has to return + a string summarizing the list of values. + +Note that the return value can become one value for an higher +order summary, so the function is expected to handle its own +output. + +Types defined in this variable take precedence over those defined +in `org-columns-summary-types-default', which see." + :group 'org-properties + :version "26.1" + :package-version '(Org . "9.0") + :type '(alist :key-type (string :tag " Label") + :value-type (function :tag "Summarize"))) + + + +;;; Column View + +(defvar-local org-columns-overlays nil + "Holds the list of current column overlays.") + +(defvar-local org-columns-current-fmt nil + "Local variable, holds the currently active column format.") + +(defvar-local org-columns-current-fmt-compiled nil + "Local variable, holds the currently active column format. +This is the compiled version of the format.") + +(defvar-local org-columns-current-maxwidths nil + "Currently active maximum column widths, as a vector.") + +(defvar-local org-columns-begin-marker nil + "Points to the position where last a column creation command was called.") + +(defvar-local org-columns-top-level-marker nil + "Points to the position where current columns region starts.") + +(defvar org-columns--time 0.0 + "Number of seconds since the epoch, as a floating point number.") + +(defvar org-columns-map (make-sparse-keymap) + "The keymap valid in column display.") + +(defconst org-columns-summary-types-default + '(("+" . org-columns--summary-sum) + ("$" . org-columns--summary-currencies) + ("X" . org-columns--summary-checkbox) + ("X/" . org-columns--summary-checkbox-count) + ("X%" . org-columns--summary-checkbox-percent) + ("max" . org-columns--summary-max) + ("mean" . org-columns--summary-mean) + ("min" . org-columns--summary-min) + (":" . org-columns--summary-sum-times) + (":max" . org-columns--summary-max-time) + (":mean" . org-columns--summary-mean-time) + (":min" . org-columns--summary-min-time) + ("@max" . org-columns--summary-max-age) + ("@mean" . org-columns--summary-mean-age) + ("@min" . org-columns--summary-min-age) + ("est+" . org-columns--summary-estimate)) + "Map operators to summarize functions. +See `org-columns-summary-types' for details.") + +(defun org-columns-content () + "Switch to contents view while in columns view." + (interactive) + (org-overview) + (org-content)) + +(org-defkey org-columns-map "c" 'org-columns-content) +(org-defkey org-columns-map "o" 'org-overview) +(org-defkey org-columns-map "e" 'org-columns-edit-value) +(org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo) +(org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle) +(org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link) +(org-defkey org-columns-map "v" 'org-columns-show-value) +(org-defkey org-columns-map "q" 'org-columns-quit) +(org-defkey org-columns-map "r" 'org-columns-redo) +(org-defkey org-columns-map "g" 'org-columns-redo) +(org-defkey org-columns-map [left] 'backward-char) +(org-defkey org-columns-map "\M-b" 'backward-char) +(org-defkey org-columns-map "a" 'org-columns-edit-allowed) +(org-defkey org-columns-map "s" 'org-columns-edit-attributes) +(org-defkey org-columns-map "\M-f" + (lambda () (interactive) (goto-char (1+ (point))))) +(org-defkey org-columns-map [right] + (lambda () (interactive) (goto-char (1+ (point))))) +(org-defkey org-columns-map [down] + (lambda () (interactive) + (let ((col (current-column))) + (beginning-of-line 2) + (while (and (org-invisible-p2) (not (eobp))) + (beginning-of-line 2)) + (move-to-column col) + (if (eq major-mode 'org-agenda-mode) + (org-agenda-do-context-action))))) +(org-defkey org-columns-map [up] + (lambda () (interactive) + (let ((col (current-column))) + (beginning-of-line 0) + (while (and (org-invisible-p2) (not (bobp))) + (beginning-of-line 0)) + (move-to-column col) + (if (eq major-mode 'org-agenda-mode) + (org-agenda-do-context-action))))) +(org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value) +(org-defkey org-columns-map "n" 'org-columns-next-allowed-value) +(org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value) +(org-defkey org-columns-map "p" 'org-columns-previous-allowed-value) +(org-defkey org-columns-map "<" 'org-columns-narrow) +(org-defkey org-columns-map ">" 'org-columns-widen) +(org-defkey org-columns-map [(meta right)] 'org-columns-move-right) +(org-defkey org-columns-map [(meta left)] 'org-columns-move-left) +(org-defkey org-columns-map [(shift meta right)] 'org-columns-new) +(org-defkey org-columns-map [(shift meta left)] 'org-columns-delete) +(dotimes (i 10) + (org-defkey org-columns-map (number-to-string i) + `(lambda () (interactive) + (org-columns-next-allowed-value nil ,i)))) + +(easy-menu-define org-columns-menu org-columns-map "Org Column Menu" + '("Column" + ["Edit property" org-columns-edit-value t] + ["Next allowed value" org-columns-next-allowed-value t] + ["Previous allowed value" org-columns-previous-allowed-value t] + ["Show full value" org-columns-show-value t] + ["Edit allowed values" org-columns-edit-allowed t] + "--" + ["Edit column attributes" org-columns-edit-attributes t] + ["Increase column width" org-columns-widen t] + ["Decrease column width" org-columns-narrow t] + "--" + ["Move column right" org-columns-move-right t] + ["Move column left" org-columns-move-left t] + ["Add column" org-columns-new t] + ["Delete column" org-columns-delete t] + "--" + ["CONTENTS" org-columns-content t] + ["OVERVIEW" org-overview t] + ["Refresh columns display" org-columns-redo t] + "--" + ["Open link" org-columns-open-link t] + "--" + ["Quit" org-columns-quit t])) + +(defun org-columns--displayed-value (spec value) + "Return displayed value for specification SPEC in current entry. +SPEC is a column format specification as stored in +`org-columns-current-fmt-compiled'. VALUE is the real value to +display, as a string." + (or (and (functionp org-columns-modify-value-for-display-function) + (funcall org-columns-modify-value-for-display-function + (nth 1 spec) ;column name + value)) + (pcase spec + (`("ITEM" . ,_) + (concat (make-string (1- (org-current-level)) + (if org-hide-leading-stars ?\s ?*)) + "* " + (org-columns-compact-links value))) + (`(,_ ,_ ,_ ,_ nil) value) + ;; If PRINTF is set, assume we are displaying a number and + ;; obey to the format string. + (`(,_ ,_ ,_ ,_ ,printf) (format printf (string-to-number value))) + (_ (error "Invalid column specification format: %S" spec))))) + +(defun org-columns--collect-values (&optional compiled-fmt) + "Collect values for columns on the current line. + +Return a list of triplets (SPEC VALUE DISPLAYED) suitable for +`org-columns--display-here'. + +This function assumes `org-columns-current-fmt-compiled' is +initialized is set in the current buffer. However, it is +possible to override it with optional argument COMPILED-FMT." + (let ((summaries (get-text-property (point) 'org-summaries))) + (mapcar + (lambda (spec) + (pcase spec + (`(,p . ,_) + (let* ((v (or (cdr (assoc spec summaries)) + (org-entry-get (point) p 'selective t) + (and compiled-fmt ;assume `org-agenda-columns' + ;; Effort property is not defined. Try + ;; to use appointment duration. + org-agenda-columns-add-appointments-to-effort-sum + (string= p (upcase org-effort-property)) + (get-text-property (point) 'duration) + (propertize (org-duration-from-minutes + (get-text-property (point) 'duration)) + 'face 'org-warning)) + ""))) + (list spec v (org-columns--displayed-value spec v)))))) + (or compiled-fmt org-columns-current-fmt-compiled)))) + +(defun org-columns--set-widths (cache) + "Compute the maximum column widths from the format and CACHE. +This function sets `org-columns-current-maxwidths' as a vector of +integers greater than 0." + (setq org-columns-current-maxwidths + (apply #'vector + (mapcar + (lambda (spec) + (pcase spec + (`(,_ ,_ ,(and width (pred wholenump)) . ,_) width) + (`(,_ ,name . ,_) + ;; No width is specified in the columns format. + ;; Compute it by checking all possible values for + ;; PROPERTY. + (let ((width (length name))) + (dolist (entry cache width) + (let ((value (nth 2 (assoc spec (cdr entry))))) + (setq width (max (length value) width)))))))) + org-columns-current-fmt-compiled)))) + +(defun org-columns--new-overlay (beg end &optional string face) + "Create a new column overlay and add it to the list." + (let ((ov (make-overlay beg end))) + (overlay-put ov 'face (or face 'secondary-selection)) + (org-overlay-display ov string face) + (push ov org-columns-overlays) + ov)) + +(defun org-columns--summarize (operator) + "Return summary function associated to string OPERATOR." + (if (not operator) nil + (cdr (or (assoc operator org-columns-summary-types) + (assoc operator org-columns-summary-types-default) + (error "Unknown %S operator" operator))))) + +(defun org-columns--overlay-text (value fmt width property original) + "Return text " + (format fmt + (let ((v (org-columns-add-ellipses value width))) + (pcase property + ("PRIORITY" + (propertize v 'face (org-get-priority-face original))) + ("TAGS" + (if (not org-tags-special-faces-re) + (propertize v 'face 'org-tag) + (replace-regexp-in-string + org-tags-special-faces-re + (lambda (m) (propertize m 'face (org-get-tag-face m))) + v nil nil 1))) + ("TODO" (propertize v 'face (org-get-todo-face original))) + (_ v))))) + +(defun org-columns--display-here (columns &optional dateline) + "Overlay the current line with column display. +COLUMNS is an alist (SPEC VALUE DISPLAYED). Optional argument +DATELINE is non-nil when the face used should be +`org-agenda-column-dateline'." + (save-excursion + (beginning-of-line) + (let* ((level-face (and (looking-at "\\(\\**\\)\\(\\* \\)") + (org-get-level-face 2))) + (ref-face (or level-face + (and (eq major-mode 'org-agenda-mode) + (org-get-at-bol 'face)) + 'default)) + (color (list :foreground (face-attribute ref-face :foreground))) + (font (list :height (face-attribute 'default :height) + :family (face-attribute 'default :family))) + (face (list color font 'org-column ref-face)) + (face1 (list color font 'org-agenda-column-dateline ref-face))) + ;; Each column is an overlay on top of a character. So there has + ;; to be at least as many characters available on the line as + ;; columns to display. + (let ((columns (length org-columns-current-fmt-compiled)) + (chars (- (line-end-position) (line-beginning-position)))) + (when (> columns chars) + (save-excursion + (end-of-line) + (let ((inhibit-read-only t)) + (insert (make-string (- columns chars) ?\s)))))) + ;; Display columns. Create and install the overlay for the + ;; current column on the next character. + (let ((i 0) + (last (1- (length columns)))) + (dolist (column columns) + (pcase column + (`(,spec ,original ,value) + (let* ((property (car spec)) + (width (aref org-columns-current-maxwidths i)) + (fmt (format (if (= i last) "%%-%d.%ds |" + "%%-%d.%ds | ") + width width)) + (ov (org-columns--new-overlay + (point) (1+ (point)) + (org-columns--overlay-text + value fmt width property original) + (if dateline face1 face)))) + (overlay-put ov 'keymap org-columns-map) + (overlay-put ov 'org-columns-key property) + (overlay-put ov 'org-columns-value original) + (overlay-put ov 'org-columns-value-modified value) + (overlay-put ov 'org-columns-format fmt) + (overlay-put ov 'line-prefix "") + (overlay-put ov 'wrap-prefix "") + (forward-char)))) + (cl-incf i))) + ;; Make the rest of the line disappear. + (let ((ov (org-columns--new-overlay (point) (line-end-position)))) + (overlay-put ov 'invisible t) + (overlay-put ov 'keymap org-columns-map) + (overlay-put ov 'line-prefix "") + (overlay-put ov 'wrap-prefix "")) + (let ((ov (make-overlay (1- (line-end-position)) + (line-beginning-position 2)))) + (overlay-put ov 'keymap org-columns-map) + (push ov org-columns-overlays)) + (org-with-silent-modifications + (let ((inhibit-read-only t)) + (put-text-property + (line-end-position 0) + (line-beginning-position 2) + 'read-only + (substitute-command-keys + "Type \\`\\[org-columns-edit-value]' \ +to edit property"))))))) + +(defun org-columns-add-ellipses (string width) + "Truncate STRING with WIDTH characters, with ellipses." + (cond + ((<= (length string) width) string) + ((<= width (length org-columns-ellipses)) + (substring org-columns-ellipses 0 width)) + (t (concat (substring string 0 (- width (length org-columns-ellipses))) + org-columns-ellipses)))) + +(defvar org-columns-full-header-line-format nil + "The full header line format, will be shifted by horizontal scrolling." ) +(defvar org-previous-header-line-format nil + "The header line format before column view was turned on.") +(defvar org-columns-inhibit-recalculation nil + "Inhibit recomputing of columns on column view startup.") +(defvar org-columns-flyspell-was-active nil + "Remember the state of `flyspell-mode' before column view. +Flyspell-mode can cause problems in columns view, so it is turned off +for the duration of the command.") + +(defvar header-line-format) +(defvar org-columns-previous-hscroll 0) + +(defun org-columns--display-here-title () + "Overlay the newline before the current line with the table title." + (interactive) + (let ((title "") + (i 0)) + (dolist (column org-columns-current-fmt-compiled) + (pcase column + (`(,property ,name . ,_) + (let* ((width (aref org-columns-current-maxwidths i)) + (fmt (format "%%-%d.%ds | " width width))) + (setq title (concat title (format fmt (or name property))))))) + (cl-incf i)) + (setq-local org-previous-header-line-format header-line-format) + (setq org-columns-full-header-line-format + (concat + (org-add-props " " nil 'display '(space :align-to 0)) + (org-add-props (substring title 0 -1) nil 'face 'org-column-title))) + (setq org-columns-previous-hscroll -1) + (add-hook 'post-command-hook 'org-columns-hscroll-title nil 'local))) + +(defun org-columns-hscroll-title () + "Set the `header-line-format' so that it scrolls along with the table." + (sit-for .0001) ; need to force a redisplay to update window-hscroll + (when (not (= (window-hscroll) org-columns-previous-hscroll)) + (setq header-line-format + (concat (substring org-columns-full-header-line-format 0 1) + (substring org-columns-full-header-line-format + (1+ (window-hscroll)))) + org-columns-previous-hscroll (window-hscroll)) + (force-mode-line-update))) + +(defvar org-colview-initial-truncate-line-value nil + "Remember the value of `truncate-lines' across colview.") + +;;;###autoload +(defun org-columns-remove-overlays () + "Remove all currently active column overlays." + (interactive) + (when org-columns-overlays + (when (local-variable-p 'org-previous-header-line-format) + (setq header-line-format org-previous-header-line-format) + (kill-local-variable 'org-previous-header-line-format) + (remove-hook 'post-command-hook 'org-columns-hscroll-title 'local)) + (set-marker org-columns-begin-marker nil) + (when (markerp org-columns-top-level-marker) + (set-marker org-columns-top-level-marker nil)) + (org-with-silent-modifications + (mapc #'delete-overlay org-columns-overlays) + (setq org-columns-overlays nil) + (let ((inhibit-read-only t)) + (remove-text-properties (point-min) (point-max) '(read-only t)))) + (when org-columns-flyspell-was-active + (flyspell-mode 1)) + (when (local-variable-p 'org-colview-initial-truncate-line-value) + (setq truncate-lines org-colview-initial-truncate-line-value)))) + +(defun org-columns-compact-links (s) + "Replace [[link][desc]] with [desc] or [link]." + (while (string-match org-bracket-link-regexp s) + (setq s (replace-match + (concat "[" (match-string (if (match-end 3) 3 1) s) "]") + t t s))) + s) + +(defun org-columns-show-value () + "Show the full value of the property." + (interactive) + (let ((value (get-char-property (point) 'org-columns-value))) + (message "Value is: %s" (or value "")))) + +(defvar org-agenda-columns-active) ;; defined in org-agenda.el + +(defun org-columns-quit () + "Remove the column overlays and in this way exit column editing." + (interactive) + (org-with-silent-modifications + (org-columns-remove-overlays) + (let ((inhibit-read-only t)) + (remove-text-properties (point-min) (point-max) '(read-only t)))) + (if (not (eq major-mode 'org-agenda-mode)) + (setq org-columns-current-fmt nil) + (setq org-agenda-columns-active nil) + (message + "Modification not yet reflected in Agenda buffer, use `r' to refresh"))) + +(defun org-columns-check-computed () + "Throw an error if current column value is computed." + (let ((spec (nth (current-column) org-columns-current-fmt-compiled))) + (and + (nth 3 spec) + (assoc spec (get-text-property (line-beginning-position) 'org-summaries)) + (error "This value is computed from the entry's children")))) + +(defun org-columns-todo (&optional _arg) + "Change the TODO state during column view." + (interactive "P") + (org-columns-edit-value "TODO")) + +(defun org-columns-set-tags-or-toggle (&optional _arg) + "Toggle checkbox at point, or set tags for current headline." + (interactive "P") + (if (string-match "\\`\\[[ xX-]\\]\\'" + (get-char-property (point) 'org-columns-value)) + (org-columns-next-allowed-value) + (org-columns-edit-value "TAGS"))) + +(defvar org-agenda-overriding-columns-format nil + "When set, overrides any other format definition for the agenda. +Don't set this, this is meant for dynamic scoping.") + +(defun org-columns-edit-value (&optional key) + "Edit the value of the property at point in column view. +Where possible, use the standard interface for changing this line." + (interactive) + (org-columns-check-computed) + (let* ((col (current-column)) + (bol (line-beginning-position)) + (eol (line-end-position)) + (pom (or (get-text-property bol 'org-hd-marker) (point))) + (key (or key (get-char-property (point) 'org-columns-key))) + (org-columns--time (float-time (current-time))) + (action + (pcase key + ("CLOCKSUM" + (error "This special column cannot be edited")) + ("ITEM" + (lambda () (org-with-point-at pom (org-edit-headline)))) + ("TODO" + (lambda () + (org-with-point-at pom (call-interactively #'org-todo)))) + ("PRIORITY" + (lambda () + (org-with-point-at pom + (call-interactively #'org-priority)))) + ("TAGS" + (lambda () + (org-with-point-at pom + (let ((org-fast-tag-selection-single-key + (if (eq org-fast-tag-selection-single-key 'expert) + t + org-fast-tag-selection-single-key))) + (call-interactively #'org-set-tags))))) + ("DEADLINE" + (lambda () + (org-with-point-at pom (call-interactively #'org-deadline)))) + ("SCHEDULED" + (lambda () + (org-with-point-at pom (call-interactively #'org-schedule)))) + ("BEAMER_ENV" + (lambda () + (org-with-point-at pom + (call-interactively #'org-beamer-select-environment)))) + (_ + (let* ((allowed (org-property-get-allowed-values pom key 'table)) + (value (get-char-property (point) 'org-columns-value)) + (nval (org-trim + (if (null allowed) (read-string "Edit: " value) + (completing-read + "Value: " allowed nil + (not (get-text-property + 0 'org-unrestricted (caar allowed)))))))) + (and (not (equal nval value)) + (lambda () (org-entry-put pom key nval)))))))) + (cond + ((null action)) + ((eq major-mode 'org-agenda-mode) + (org-columns--call action) + ;; The following let preserves the current format, and makes + ;; sure that in only a single file things need to be updated. + (let* ((org-agenda-overriding-columns-format org-columns-current-fmt) + (buffer (marker-buffer pom)) + (org-agenda-contributing-files + (list (with-current-buffer buffer + (buffer-file-name (buffer-base-buffer)))))) + (org-agenda-columns))) + (t + (let ((inhibit-read-only t)) + (org-with-silent-modifications + (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))) + (org-columns--call action)) + ;; Some properties can modify headline (e.g., "TODO"), and + ;; possible shuffle overlays. Make sure they are still all at + ;; the right place on the current line. + (let ((org-columns-inhibit-recalculation)) (org-columns-redo)) + (org-columns-update key) + (org-move-to-column col))))) + +(defun org-columns-edit-allowed () + "Edit the list of allowed values for the current property." + (interactive) + (let* ((pom (or (org-get-at-bol 'org-marker) + (org-get-at-bol 'org-hd-marker) + (point))) + (key (concat (or (get-char-property (point) 'org-columns-key) + (user-error "No column to edit at point")) + "_ALL")) + (allowed (org-entry-get pom key t)) + (new-value (read-string "Allowed: " allowed))) + ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.???? + ;; FIXME: Write back to #+PROPERTY setting if that is needed. + (org-entry-put + (cond ((marker-position org-entry-property-inherited-from) + org-entry-property-inherited-from) + ((marker-position org-columns-top-level-marker) + org-columns-top-level-marker) + (t pom)) + key new-value))) + +(defun org-columns--call (fun) + "Call function FUN while preserving heading visibility. +FUN is a function called with no argument." + (let ((hide-body (and (/= (line-end-position) (point-max)) + (save-excursion + (move-beginning-of-line 2) + (org-at-heading-p t))))) + (unwind-protect (funcall fun) + (when hide-body (outline-hide-entry))))) + +(defun org-columns-previous-allowed-value () + "Switch to the previous allowed value for this column." + (interactive) + (org-columns-next-allowed-value t)) + +(defun org-columns-next-allowed-value (&optional previous nth) + "Switch to the next allowed value for this column. +When PREVIOUS is set, go to the previous value. When NTH is +an integer, select that value." + (interactive) + (org-columns-check-computed) + (let* ((column (current-column)) + (key (get-char-property (point) 'org-columns-key)) + (value (get-char-property (point) 'org-columns-value)) + (pom (or (get-text-property (line-beginning-position) 'org-hd-marker) + (point))) + (allowed + (let ((all + (or (org-property-get-allowed-values pom key) + (pcase (nth column org-columns-current-fmt-compiled) + (`(,_ ,_ ,_ ,(or "X" "X/" "X%") ,_) '("[ ]" "[X]"))) + (org-colview-construct-allowed-dates value)))) + (if previous (reverse all) all)))) + (when (equal key "ITEM") (error "Cannot edit item headline from here")) + (unless (or allowed (member key '("SCHEDULED" "DEADLINE" "CLOCKSUM"))) + (error "Allowed values for this property have not been defined")) + (let* ((l (length allowed)) + (new + (cond + ((member key '("SCHEDULED" "DEADLINE" "CLOCKSUM")) + (if previous 'earlier 'later)) + ((integerp nth) + (when (> (abs nth) l) + (user-error "Only %d allowed values for property `%s'" l key)) + (nth (mod (1- nth) l) allowed)) + ((member value allowed) + (when (= l 1) (error "Only one allowed value for this property")) + (or (nth 1 (member value allowed)) (car allowed))) + (t (car allowed)))) + (action (lambda () (org-entry-put pom key new)))) + (cond + ((eq major-mode 'org-agenda-mode) + (org-columns--call action) + ;; The following let preserves the current format, and makes + ;; sure that in only a single file things need to be updated. + (let* ((org-agenda-overriding-columns-format org-columns-current-fmt) + (buffer (marker-buffer pom)) + (org-agenda-contributing-files + (list (with-current-buffer buffer + (buffer-file-name (buffer-base-buffer)))))) + (org-agenda-columns))) + (t + (let ((inhibit-read-only t)) + (remove-text-properties (line-end-position 0) (line-end-position) + '(read-only t)) + (org-columns--call action)) + ;; Some properties can modify headline (e.g., "TODO"), and + ;; possible shuffle overlays. Make sure they are still all at + ;; the right place on the current line. + (let ((org-columns-inhibit-recalculation)) (org-columns-redo)) + (org-columns-update key) + (org-move-to-column column)))))) + +(defun org-colview-construct-allowed-dates (s) + "Construct a list of three dates around the date in S. +This respects the format of the time stamp in S, active or non-active, +and also including time or not. S must be just a time stamp, no text +around it." + (when (and s (string-match (concat "^" org-ts-regexp3 "$") s)) + (let* ((time (org-parse-time-string s 'nodefaults)) + (active (equal (string-to-char s) ?<)) + (fmt (funcall (if (nth 1 time) 'cdr 'car) org-time-stamp-formats)) + time-before time-after) + (unless active (setq fmt (concat "[" (substring fmt 1 -1) "]"))) + (setf (car time) (or (car time) 0)) + (setf (nth 1 time) (or (nth 1 time) 0)) + (setf (nth 2 time) (or (nth 2 time) 0)) + (setq time-before (copy-sequence time)) + (setq time-after (copy-sequence time)) + (setf (nth 3 time-before) (1- (nth 3 time))) + (setf (nth 3 time-after) (1+ (nth 3 time))) + (mapcar (lambda (x) (format-time-string fmt (apply 'encode-time x))) + (list time-before time time-after))))) + +(defun org-columns-open-link (&optional arg) + (interactive "P") + (let ((value (get-char-property (point) 'org-columns-value))) + (org-open-link-from-string value arg))) + +;;;###autoload +(defun org-columns-get-format-and-top-level () + (let ((fmt (org-columns-get-format))) + (org-columns-goto-top-level) + fmt)) + +(defun org-columns-get-format (&optional fmt-string) + "Return columns format specifications. +When optional argument FMT-STRING is non-nil, use it as the +current specifications. This function also sets +`org-columns-current-fmt-compiled' and +`org-columns-current-fmt'." + (interactive) + (let ((format + (or fmt-string + (org-entry-get nil "COLUMNS" t) + (org-with-wide-buffer + (goto-char (point-min)) + (catch :found + (let ((case-fold-search t)) + (while (re-search-forward "^[ \t]*#\\+COLUMNS: .+$" nil t) + (let ((element (org-element-at-point))) + (when (eq (org-element-type element) 'keyword) + (throw :found (org-element-property :value element))))) + nil))) + org-columns-default-format))) + (setq org-columns-current-fmt format) + (org-columns-compile-format format) + format)) + +(defun org-columns-goto-top-level () + "Move to the beginning of the column view area. +Also sets `org-columns-top-level-marker' to the new position." + (unless (markerp org-columns-top-level-marker) + (setq org-columns-top-level-marker (make-marker))) + (goto-char + (move-marker + org-columns-top-level-marker + (cond ((org-before-first-heading-p) (point-min)) + ((org-entry-get nil "COLUMNS" t) org-entry-property-inherited-from) + (t (org-back-to-heading) (point)))))) + +;;;###autoload +(defun org-columns (&optional global columns-fmt-string) + "Turn on column view on an Org mode file. + +Column view applies to the whole buffer if point is before the +first headline. Otherwise, it applies to the first ancestor +setting \"COLUMNS\" property. If there is none, it defaults to +the current headline. With a `\\[universal-argument]' prefix \ +argument, turn on column +view for the whole buffer unconditionally. + +When COLUMNS-FMT-STRING is non-nil, use it as the column format." + (interactive "P") + (org-columns-remove-overlays) + (when global (goto-char (point-min))) + (if (markerp org-columns-begin-marker) + (move-marker org-columns-begin-marker (point)) + (setq org-columns-begin-marker (point-marker))) + (org-columns-goto-top-level) + ;; Initialize `org-columns-current-fmt' and + ;; `org-columns-current-fmt-compiled'. + (let ((org-columns--time (float-time (current-time)))) + (org-columns-get-format columns-fmt-string) + (unless org-columns-inhibit-recalculation (org-columns-compute-all)) + (save-excursion + (save-restriction + (when (and (not global) (org-at-heading-p)) + (narrow-to-region (point) (org-end-of-subtree t t))) + (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled) + (org-clock-sum)) + (when (assoc "CLOCKSUM_T" org-columns-current-fmt-compiled) + (org-clock-sum-today)) + (let ((cache + ;; Collect contents of columns ahead of time so as to + ;; compute their maximum width. + (org-map-entries + (lambda () (cons (point) (org-columns--collect-values))) + nil nil (and org-columns-skip-archived-trees 'archive)))) + (when cache + (org-columns--set-widths cache) + (org-columns--display-here-title) + (when (setq-local org-columns-flyspell-was-active + (bound-and-true-p flyspell-mode)) + (flyspell-mode 0)) + (unless (local-variable-p 'org-colview-initial-truncate-line-value) + (setq-local org-colview-initial-truncate-line-value + truncate-lines)) + (setq truncate-lines t) + (dolist (entry cache) + (goto-char (car entry)) + (org-columns--display-here (cdr entry))))))))) + +(defun org-columns-new (&optional spec &rest attributes) + "Insert a new column, to the left of the current column. +Interactively fill attributes for new column. When column format +specification SPEC is provided, edit it instead. + +When optional argument attributes can be a list of columns +specifications attributes to create the new column +non-interactively. See `org-columns-compile-format' for +details." + (interactive) + (let ((new (or attributes + (let ((prop + (completing-read + "Property: " + (mapcar #'list (org-buffer-property-keys t nil t)) + nil nil (nth 0 spec)))) + (list prop + (read-string (format "Column title [%s]: " prop) + (nth 1 spec)) + ;; Use `read-string' instead of `read-number' + ;; to allow empty width. + (let ((w (read-string + "Column width: " + (and (nth 2 spec) + (number-to-string (nth 2 spec)))))) + (and (org-string-nw-p w) (string-to-number w))) + (org-string-nw-p + (completing-read + "Summary: " + (delete-dups + (cons '("") ;Allow empty operator. + (mapcar (lambda (x) (list (car x))) + (append + org-columns-summary-types + org-columns-summary-types-default)))) + nil t (nth 3 spec))) + (org-string-nw-p + (read-string "Format: " (nth 4 spec)))))))) + (if spec + (progn (setcar spec (car new)) + (setcdr spec (cdr new))) + (push new (nthcdr (current-column) org-columns-current-fmt-compiled))) + (org-columns-store-format) + (org-columns-redo))) + +(defun org-columns-delete () + "Delete the column at point from columns view." + (interactive) + (let ((spec (nth (current-column) org-columns-current-fmt-compiled))) + (when (y-or-n-p (format "Are you sure you want to remove column %S? " + (nth 1 spec))) + (setq org-columns-current-fmt-compiled + (delq spec org-columns-current-fmt-compiled)) + (org-columns-store-format) + ;; This may leave a now wrong value in a node property. However + ;; updating it may prove counter-intuitive. See comments in + ;; `org-columns-move-right' for details. + (let ((org-columns-inhibit-recalculation t)) (org-columns-redo)) + (when (>= (current-column) (length org-columns-current-fmt-compiled)) + (backward-char))))) + +(defun org-columns-edit-attributes () + "Edit the attributes of the current column." + (interactive) + (org-columns-new (nth (current-column) org-columns-current-fmt-compiled))) + +(defun org-columns-widen (arg) + "Make the column wider by ARG characters." + (interactive "p") + (let* ((n (current-column)) + (entry (nth n org-columns-current-fmt-compiled)) + (width (aref org-columns-current-maxwidths n))) + (setq width (max 1 (+ width arg))) + (setcar (nthcdr 2 entry) width) + (org-columns-store-format) + (let ((org-columns-inhibit-recalculation t)) (org-columns-redo)))) + +(defun org-columns-narrow (arg) + "Make the column narrower by ARG characters." + (interactive "p") + (org-columns-widen (- arg))) + +(defun org-columns-move-right () + "Swap this column with the one to the right." + (interactive) + (let* ((n (current-column)) + (cell (nthcdr n org-columns-current-fmt-compiled)) + e) + (when (>= n (1- (length org-columns-current-fmt-compiled))) + (error "Cannot shift this column further to the right")) + (setq e (car cell)) + (setcar cell (car (cdr cell))) + (setcdr cell (cons e (cdr (cdr cell)))) + (org-columns-store-format) + ;; Do not compute again properties, since we're just moving + ;; columns around. It can put a property value a bit off when + ;; switching between an non-computed and a computed value for the + ;; same property, e.g. from "%A %A{+}" to "%A{+} %A". + ;; + ;; In this case, the value needs to be updated since the first + ;; column related to a property determines how its value is + ;; computed. However, (correctly) updating the value could be + ;; surprising, so we leave it as-is nonetheless. + (let ((org-columns-inhibit-recalculation t)) (org-columns-redo)) + (forward-char 1))) + +(defun org-columns-move-left () + "Swap this column with the one to the left." + (interactive) + (let* ((n (current-column))) + (when (= n 0) + (error "Cannot shift this column further to the left")) + (backward-char 1) + (org-columns-move-right) + (backward-char 1))) + +(defun org-columns-store-format () + "Store the text version of the current columns format. +The format is stored either in the COLUMNS property of the node +starting the current column display, or in a #+COLUMNS line of +the current buffer." + (let ((fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))) + (setq-local org-columns-current-fmt fmt) + (when org-columns-overlays + (org-with-point-at org-columns-top-level-marker + (if (and (org-at-heading-p) (org-entry-get nil "COLUMNS")) + (org-entry-put nil "COLUMNS" fmt) + (goto-char (point-min)) + (let ((case-fold-search t)) + ;; Try to replace the first COLUMNS keyword available. + (catch :found + (while (re-search-forward "^[ \t]*#\\+COLUMNS:\\(.*\\)" nil t) + (let ((element (save-match-data (org-element-at-point)))) + (when (and (eq (org-element-type element) 'keyword) + (equal (org-element-property :key element) + "COLUMNS")) + (replace-match (concat " " fmt) t t nil 1) + (throw :found nil)))) + ;; No COLUMNS keyword in the buffer. Insert one at the + ;; beginning, right before the first heading, if any. + (goto-char (point-min)) + (unless (org-at-heading-p t) (outline-next-heading)) + (let ((inhibit-read-only t)) + (insert-before-markers "#+COLUMNS: " fmt "\n")))) + (setq-local org-columns-default-format fmt)))))) + +(defun org-columns-update (property) + "Recompute PROPERTY, and update the columns display for it." + (org-columns-compute property) + (org-with-wide-buffer + (let ((p (upcase property))) + (dolist (ov org-columns-overlays) + (let ((key (overlay-get ov 'org-columns-key))) + (when (and key (equal key p) (overlay-start ov)) + (goto-char (overlay-start ov)) + (let* ((spec (nth (current-column) org-columns-current-fmt-compiled)) + (value + (or (cdr (assoc spec + (get-text-property (line-beginning-position) + 'org-summaries))) + (org-entry-get (point) key)))) + (when value + (let ((displayed (org-columns--displayed-value spec value)) + (format (overlay-get ov 'org-columns-format)) + (width + (aref org-columns-current-maxwidths (current-column)))) + (overlay-put ov 'org-columns-value value) + (overlay-put ov 'org-columns-value-modified displayed) + (overlay-put ov + 'display + (org-columns--overlay-text + displayed format width property value))))))))))) + +(defun org-columns-redo () + "Construct the column display again." + (interactive) + (when org-columns-overlays + (message "Recomputing columns...") + (org-with-point-at org-columns-begin-marker + (org-columns-remove-overlays) + (if (derived-mode-p 'org-mode) + ;; Since we already know the columns format, provide it + ;; instead of computing again. + (call-interactively #'org-columns org-columns-current-fmt) + (org-agenda-redo) + (call-interactively #'org-agenda-columns))) + (message "Recomputing columns...done"))) + +(defun org-columns-uncompile-format (compiled) + "Turn the compiled columns format back into a string representation. +COMPILED is an alist, as returned by +`org-columns-compile-format', which see." + (mapconcat + (lambda (spec) + (pcase spec + (`(,prop ,title ,width ,op ,printf) + (concat "%" + (and width (number-to-string width)) + prop + (and title (not (equal prop title)) (format "(%s)" title)) + (cond ((not op) nil) + (printf (format "{%s;%s}" op printf)) + (t (format "{%s}" op))))))) + compiled " ")) + +(defun org-columns-compile-format (fmt) + "Turn a column format string FMT into an alist of specifications. + +The alist has one entry for each column in the format. The elements of +that list are: +property the property name, as an upper-case string +title the title field for the columns, as a string +width the column width in characters, can be nil for automatic width +operator the summary operator, as a string, or nil +printf a printf format for computed values, as a string, or nil + +This function updates `org-columns-current-fmt-compiled'." + (setq org-columns-current-fmt-compiled nil) + (let ((start 0)) + (while (string-match + "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\ +\\(?:{\\([^}]+\\)}\\)?\\s-*" + fmt start) + (setq start (match-end 0)) + (let* ((width (and (match-end 1) (string-to-number (match-string 1 fmt)))) + (prop (match-string-no-properties 2 fmt)) + (title (or (match-string-no-properties 3 fmt) prop)) + (operator (match-string-no-properties 4 fmt))) + (push (if (not operator) (list (upcase prop) title width nil nil) + (let (printf) + (when (string-match ";" operator) + (setq printf (substring operator (match-end 0))) + (setq operator (substring operator 0 (match-beginning 0)))) + (list (upcase prop) title width operator printf))) + org-columns-current-fmt-compiled))) + (setq org-columns-current-fmt-compiled + (nreverse org-columns-current-fmt-compiled)))) + + +;;;; Column View Summary + +(defun org-columns--age-to-minutes (s) + "Turn age string S into a number of minutes. +An age is either computed from a given time-stamp, or indicated +as a canonical duration, i.e., using units defined in +`org-duration-canonical-units'." + (cond + ((string-match-p org-ts-regexp s) + (/ (- org-columns--time + (float-time (apply #'encode-time (org-parse-time-string s)))) + 60)) + ((org-duration-p s) (org-duration-to-minutes s t)) ;skip user units + (t (user-error "Invalid age: %S" s)))) + +(defun org-columns--format-age (minutes) + "Format MINUTES float as an age string." + (org-duration-from-minutes minutes + '(("d" . nil) ("h" . nil) ("min" . nil)) + t)) ;ignore user's custom units + +(defun org-columns--summary-apply-times (fun times) + "Apply FUN to time values TIMES. +Return the result as a duration." + (org-duration-from-minutes + (apply fun + (mapcar (lambda (time) + ;; Unlike to `org-duration-to-minutes' standard + ;; behavior, we want to consider plain numbers as + ;; hours. As a consequence, we treat them + ;; differently. + (if (string-match-p "\\`[0-9]+\\(?:\\.[0-9]*\\)?\\'" time) + (* 60 (string-to-number time)) + (org-duration-to-minutes time))) + times)) + (org-duration-h:mm-only-p times))) + +(defun org-columns--compute-spec (spec &optional update) + "Update tree according to SPEC. +SPEC is a column format specification. When optional argument +UPDATE is non-nil, summarized values can replace existing ones in +properties drawers." + (let* ((lmax (if (bound-and-true-p org-inlinetask-min-level) + org-inlinetask-min-level + 29)) ;Hard-code deepest level. + (lvals (make-vector (1+ lmax) nil)) + (level 0) + (inminlevel lmax) + (last-level lmax) + (property (car spec)) + (printf (nth 4 spec)) + (summarize (org-columns--summarize (nth 3 spec)))) + (org-with-wide-buffer + ;; Find the region to compute. + (goto-char org-columns-top-level-marker) + (goto-char (condition-case nil (org-end-of-subtree t) (error (point-max)))) + ;; Walk the tree from the back and do the computations. + (while (re-search-backward + org-outline-regexp-bol org-columns-top-level-marker t) + (unless (or (= level 0) (eq level inminlevel)) + (setq last-level level)) + (setq level (org-reduced-level (org-outline-level))) + (let* ((pos (match-beginning 0)) + (value (org-entry-get nil property)) + (value-set (org-string-nw-p value))) + (cond + ((< level last-level) + ;; Collect values from lower levels and inline tasks here + ;; and summarize them using SUMMARIZE. Store them in text + ;; property `org-summaries', in alist whose key is SPEC. + (let* ((summary + (and summarize + (let ((values (append (and (/= last-level inminlevel) + (aref lvals last-level)) + (aref lvals inminlevel)))) + (and values (funcall summarize values printf)))))) + ;; Leaf values are not summaries: do not mark them. + (when summary + (let* ((summaries-alist (get-text-property pos 'org-summaries)) + (old (assoc spec summaries-alist))) + (if old (setcdr old summary) + (push (cons spec summary) summaries-alist) + (org-with-silent-modifications + (add-text-properties + pos (1+ pos) (list 'org-summaries summaries-alist))))) + ;; When PROPERTY exists in current node, even if empty, + ;; but its value doesn't match the one computed, use + ;; the latter instead. + ;; + ;; Ignore leading or trailing white spaces that might + ;; have been introduced in summary, since those are not + ;; significant in properties value. + (let ((new-value (org-trim summary))) + (when (and update value (not (equal value new-value))) + (org-entry-put (point) property new-value)))) + ;; Add current to current level accumulator. + (when (or summary value-set) + (push (or summary value) (aref lvals level))) + ;; Clear accumulators for deeper levels. + (cl-loop for l from (1+ level) to lmax do (aset lvals l nil)))) + (value-set (push value (aref lvals level))) + (t nil))))))) + +;;;###autoload +(defun org-columns-compute (property) + "Summarize the values of PROPERTY hierarchically. +Also update existing values for PROPERTY according to the first +column specification." + (interactive) + (let ((main-flag t) + (upcase-prop (upcase property))) + (dolist (spec org-columns-current-fmt-compiled) + (pcase spec + (`(,(pred (equal upcase-prop)) . ,_) + (org-columns--compute-spec spec main-flag) + ;; Only the first summary can update the property value. + (when main-flag (setq main-flag nil))))))) + +(defun org-columns-compute-all () + "Compute all columns that have operators defined." + (org-with-silent-modifications + (remove-text-properties (point-min) (point-max) '(org-summaries t))) + (let ((org-columns--time (float-time (current-time))) + seen) + (dolist (spec org-columns-current-fmt-compiled) + (let ((property (car spec))) + ;; Property value is updated only the first time a given + ;; property is encountered. + (org-columns--compute-spec spec (not (member property seen))) + (push property seen))))) + +(defun org-columns--summary-sum (values printf) + "Compute the sum of VALUES. +When PRINTF is non-nil, use it to format the result." + (format (or printf "%s") (apply #'+ (mapcar #'string-to-number values)))) + +(defun org-columns--summary-currencies (values _) + "Compute the sum of VALUES, with two decimals." + (format "%.2f" (apply #'+ (mapcar #'string-to-number values)))) + +(defun org-columns--summary-checkbox (check-boxes _) + "Summarize CHECK-BOXES with a check-box." + (let ((done (cl-count "[X]" check-boxes :test #'equal)) + (all (length check-boxes))) + (cond ((= done all) "[X]") + ((> done 0) "[-]") + (t "[ ]")))) + +(defun org-columns--summary-checkbox-count (check-boxes _) + "Summarize CHECK-BOXES with a check-box cookie." + (format "[%d/%d]" + (cl-count-if (lambda (b) (or (equal b "[X]") + (string-match-p "\\[\\([1-9]\\)/\\1\\]" b))) + check-boxes) + (length check-boxes))) + +(defun org-columns--summary-checkbox-percent (check-boxes _) + "Summarize CHECK-BOXES with a check-box percent." + (format "[%d%%]" + (round (* 100.0 (cl-count-if (lambda (b) (member b '("[X]" "[100%]"))) + check-boxes)) + (length check-boxes)))) + +(defun org-columns--summary-min (values printf) + "Compute the minimum of VALUES. +When PRINTF is non-nil, use it to format the result." + (format (or printf "%s") + (apply #'min (mapcar #'string-to-number values)))) + +(defun org-columns--summary-max (values printf) + "Compute the maximum of VALUES. +When PRINTF is non-nil, use it to format the result." + (format (or printf "%s") + (apply #'max (mapcar #'string-to-number values)))) + +(defun org-columns--summary-mean (values printf) + "Compute the mean of VALUES. +When PRINTF is non-nil, use it to format the result." + (format (or printf "%s") + (/ (apply #'+ (mapcar #'string-to-number values)) + (float (length values))))) + +(defun org-columns--summary-sum-times (times _) + "Sum TIMES." + (org-columns--summary-apply-times #'+ times)) + +(defun org-columns--summary-min-time (times _) + "Compute the minimum time among TIMES." + (org-columns--summary-apply-times #'min times)) + +(defun org-columns--summary-max-time (times _) + "Compute the maximum time among TIMES." + (org-columns--summary-apply-times #'max times)) + +(defun org-columns--summary-mean-time (times _) + "Compute the mean time among TIMES." + (org-columns--summary-apply-times + (lambda (&rest values) (/ (apply #'+ values) (float (length values)))) + times)) + +(defun org-columns--summary-min-age (ages _) + "Compute the minimum time among AGES." + (org-columns--format-age + (apply #'min (mapcar #'org-columns--age-to-minutes ages)))) + +(defun org-columns--summary-max-age (ages _) + "Compute the maximum time among AGES." + (org-columns--format-age + (apply #'max (mapcar #'org-columns--age-to-minutes ages)))) + +(defun org-columns--summary-mean-age (ages _) + "Compute the minimum time among AGES." + (org-columns--format-age + (/ (apply #'+ (mapcar #'org-columns--age-to-minutes ages)) + (float (length ages))))) + +(defun org-columns--summary-estimate (estimates _) + "Combine a list of estimates, using mean and variance. +The mean and variance of the result will be the sum of the means +and variances (respectively) of the individual estimates." + (let ((mean 0) + (var 0)) + (dolist (e estimates) + (pcase (mapcar #'string-to-number (split-string e "-")) + (`(,low ,high) + (let ((m (/ (+ low high) 2.0))) + (cl-incf mean m) + (cl-incf var (- (/ (+ (* low low) (* high high)) 2.0) (* m m))))) + (`(,value) (cl-incf mean value)))) + (let ((sd (sqrt var))) + (format "%s-%s" + (format "%.0f" (- mean sd)) + (format "%.0f" (+ mean sd)))))) + + + +;;; Dynamic block for Column view + +(defun org-columns--capture-view (maxlevel skip-empty format local) + "Get the column view of the current buffer. + +MAXLEVEL sets the level limit. SKIP-EMPTY tells whether to skip +empty rows, an empty row being one where all the column view +specifiers but ITEM are empty. FORMAT is a format string for +columns, or nil. When LOCAL is non-nil, only capture headings in +current subtree. + +This function returns a list containing the title row and all +other rows. Each row is a list of fields, as strings, or +`hline'." + (org-columns (not local) format) + (goto-char org-columns-top-level-marker) + (let ((columns (length org-columns-current-fmt-compiled)) + (has-item (assoc "ITEM" org-columns-current-fmt-compiled)) + table) + (org-map-entries + (lambda () + (when (get-char-property (point) 'org-columns-key) + (let (row) + (dotimes (i columns) + (let* ((col (+ (line-beginning-position) i)) + (p (get-char-property col 'org-columns-key))) + (push (org-quote-vert + (get-char-property col + (if (string= p "ITEM") + 'org-columns-value + 'org-columns-value-modified))) + row))) + (unless (and skip-empty + (let ((r (delete-dups (remove "" row)))) + (or (null r) (and has-item (= (length r) 1))))) + (push (cons (org-reduced-level (org-current-level)) (nreverse row)) + table))))) + (and maxlevel (format "LEVEL<=%d" maxlevel)) + (and local 'tree) + 'archive 'comment) + (org-columns-quit) + ;; Add column titles and a horizontal rule in front of the table. + (cons (mapcar #'cadr org-columns-current-fmt-compiled) + (cons 'hline (nreverse table))))) + +(defun org-columns--clean-item (item) + "Remove sensitive contents from string ITEM. +This includes objects that may not be duplicated within +a document, e.g., a target, or those forbidden in tables, e.g., +an inline src-block." + (let ((data (org-element-parse-secondary-string + item (org-element-restriction 'headline)))) + (org-element-map data + '(footnote-reference inline-babel-call inline-src-block target + radio-target statistics-cookie) + #'org-element-extract-element) + (org-no-properties (org-element-interpret-data data)))) + +;;;###autoload +(defun org-dblock-write:columnview (params) + "Write the column view table. +PARAMS is a property list of parameters: + +:id the :ID: property of the entry where the columns view + should be built. When the symbol `local', call locally. + When `global' call column view with the cursor at the beginning + of the buffer (usually this means that the whole buffer switches + to column view). When \"file:path/to/file.org\", invoke column + view at the start of that file. Otherwise, the ID is located + using `org-id-find'. +:hlines When t, insert a hline before each item. When a number, insert + a hline before each level <= that number. +:indent When non-nil, indent each ITEM field according to its level. +:vlines When t, make each column a colgroup to enforce vertical lines. +:maxlevel When set to a number, don't capture headlines below this level. +:skip-empty-rows + When t, skip rows where all specifiers other than ITEM are empty. +:width apply widths specified in columns format using specifiers. +:format When non-nil, specify the column view format to use." + (let ((table + (let ((id (plist-get params :id)) + view-file view-pos) + (pcase id + (`global nil) + ((or `local `nil) (setq view-pos (point))) + ((and (let id-string (format "%s" id)) + (guard (string-match "^file:\\(.*\\)" id-string))) + (setq view-file (match-string-no-properties 1 id-string)) + (unless (file-exists-p view-file) + (user-error "No such file: %S" id-string))) + ((and (let idpos (org-find-entry-with-id id)) (guard idpos)) + (setq view-pos idpos)) + ((let `(,filename . ,position) (org-id-find id)) + (setq view-file filename) + (setq view-pos position)) + (_ (user-error "Cannot find entry with :ID: %s" id))) + (with-current-buffer (if view-file (get-file-buffer view-file) + (current-buffer)) + (org-with-wide-buffer + (when view-pos (goto-char view-pos)) + (org-columns--capture-view (plist-get params :maxlevel) + (plist-get params :skip-empty-rows) + (plist-get params :format) + view-pos)))))) + (when table + ;; Prune level information from the table. Also normalize + ;; headings: remove stars, add indentation entities, if + ;; required, and possibly precede some of them with a horizontal + ;; rule. + (let ((item-index + (let ((p (assoc "ITEM" org-columns-current-fmt-compiled))) + (and p (cl-position p + org-columns-current-fmt-compiled + :test #'equal)))) + (hlines (plist-get params :hlines)) + (indent (plist-get params :indent)) + new-table) + ;; Copy header and first rule. + (push (pop table) new-table) + (push (pop table) new-table) + (dolist (row table (setq table (nreverse new-table))) + (let ((level (car row))) + (when (and (not (eq (car new-table) 'hline)) + (or (eq hlines t) + (and (numberp hlines) (<= level hlines)))) + (push 'hline new-table)) + (when item-index + (let ((item (org-columns--clean-item (nth item-index (cdr row))))) + (setf (nth item-index (cdr row)) + (if (and indent (> level 1)) + (concat "\\_" (make-string (* 2 (1- level)) ?\s) item) + item)))) + (push (cdr row) new-table)))) + (when (plist-get params :width) + (setq table + (append table + (list + (mapcar (lambda (spec) + (let ((w (nth 2 spec))) + (if w (format "<%d>" (max 3 w)) ""))) + org-columns-current-fmt-compiled))))) + (when (plist-get params :vlines) + (setq table + (let ((size (length org-columns-current-fmt-compiled))) + (append (mapcar (lambda (x) (if (eq 'hline x) x (cons "" x))) + table) + (list (cons "/" (make-list size "<>"))))))) + (let ((content-lines (org-split-string (plist-get params :content) "\n")) + recalc) + ;; Insert affiliated keywords before the table. + (when content-lines + (while (string-match-p "\\`[ \t]*#\\+" (car content-lines)) + (insert (pop content-lines) "\n"))) + (save-excursion + ;; Insert table at point. + (insert + (mapconcat (lambda (row) + (if (eq row 'hline) "|-|" + (format "|%s|" (mapconcat #'identity row "|")))) + table + "\n")) + ;; Insert TBLFM lines following table. + (let ((case-fold-search t)) + (dolist (line content-lines) + (when (string-match-p "\\`[ \t]*#\\+TBLFM:" line) + (insert "\n" line) + (unless recalc (setq recalc t)))))) + (when recalc (org-table-recalculate 'all t)) + (org-table-align))))) + +;;;###autoload +(defun org-columns-insert-dblock () + "Create a dynamic block capturing a column view table." + (interactive) + (let ((id (completing-read + "Capture columns (local, global, entry with :ID: property) [local]: " + (append '(("global") ("local")) + (mapcar #'list (org-property-values "ID")))))) + (org-create-dblock + (list :name "columnview" + :hlines 1 + :id (cond ((string= id "global") 'global) + ((member id '("" "local")) 'local) + (id))))) + (org-update-dblock)) + + + +;;; Column view in the agenda + +;;;###autoload +(defun org-agenda-columns () + "Turn on or update column view in the agenda." + (interactive) + (org-columns-remove-overlays) + (if (markerp org-columns-begin-marker) + (move-marker org-columns-begin-marker (point)) + (setq org-columns-begin-marker (point-marker))) + (let* ((org-columns--time (float-time (current-time))) + (fmt + (cond + ((bound-and-true-p org-agenda-overriding-columns-format)) + ((let ((m (org-get-at-bol 'org-hd-marker))) + (and m + (or (org-entry-get m "COLUMNS" t) + (with-current-buffer (marker-buffer m) + org-columns-default-format))))) + ((and (local-variable-p 'org-columns-current-fmt) + org-columns-current-fmt)) + ((let ((m (next-single-property-change (point-min) 'org-hd-marker))) + (and m + (let ((m (get-text-property m 'org-hd-marker))) + (or (org-entry-get m "COLUMNS" t) + (with-current-buffer (marker-buffer m) + org-columns-default-format)))))) + (t org-columns-default-format))) + (compiled-fmt (org-columns-compile-format fmt))) + (setq org-columns-current-fmt fmt) + (when org-agenda-columns-compute-summary-properties + (org-agenda-colview-compute org-columns-current-fmt-compiled)) + (save-excursion + ;; Collect properties for each headline in current view. + (goto-char (point-min)) + (let (cache) + (while (not (eobp)) + (let ((m (org-get-at-bol 'org-hd-marker))) + (when m + (push (cons (line-beginning-position) + ;; `org-columns-current-fmt-compiled' is + ;; initialized but only set locally to the + ;; agenda buffer. Since current buffer is + ;; changing, we need to force the original + ;; compiled-fmt there. + (org-with-point-at m + (org-columns--collect-values compiled-fmt))) + cache))) + (forward-line)) + (when cache + (org-columns--set-widths cache) + (org-columns--display-here-title) + (when (setq-local org-columns-flyspell-was-active + (bound-and-true-p flyspell-mode)) + (flyspell-mode 0)) + (dolist (entry cache) + (goto-char (car entry)) + (org-columns--display-here (cdr entry))) + (when org-agenda-columns-show-summaries + (org-agenda-colview-summarize cache))))))) + +(defun org-agenda-colview-summarize (cache) + "Summarize the summarizable columns in column view in the agenda. +This will add overlays to the date lines, to show the summary for each day." + (let ((fmt (mapcar + (lambda (spec) + (pcase spec + (`(,property ,title ,width . ,_) + (if (member property '("CLOCKSUM" "CLOCKSUM_T")) + (list property title width ":" nil) + spec)))) + org-columns-current-fmt-compiled))) + ;; Ensure there's at least one summation column. + (when (cl-some (lambda (spec) (nth 3 spec)) fmt) + (goto-char (point-max)) + (catch :complete + (while t + (when (or (get-text-property (point) 'org-date-line) + (eq (get-text-property (point) 'face) + 'org-agenda-structure)) + ;; OK, this is a date line that should be used. + (let (entries) + (let (rest) + (dolist (c cache) + (if (> (car c) (point)) + (push c entries) + (push c rest))) + (setq cache rest)) + ;; ENTRIES contains entries below the current one. + ;; CACHE is the rest. Compute the summaries for the + ;; properties we want, set nil properties for the rest. + (when (setq entries (mapcar #'cdr entries)) + (org-columns--display-here + (mapcar + (lambda (spec) + (pcase spec + (`("ITEM" . ,_) + ;; Replace ITEM with current date. Preserve + ;; properties for fontification. + (let ((date (buffer-substring + (line-beginning-position) + (line-end-position)))) + (list spec date date))) + (`(,_ ,_ ,_ nil ,_) (list spec "" "")) + (`(,_ ,_ ,_ ,operator ,printf) + (let* ((summarize (org-columns--summarize operator)) + (values + ;; Use real values for summary, not + ;; those prepared for display. + (delq nil + (mapcar + (lambda (e) (org-string-nw-p + (nth 1 (assoc spec e)))) + entries))) + (final (if values + (funcall summarize values printf) + ""))) + (unless (equal final "") + (put-text-property 0 (length final) + 'face 'bold final)) + (list spec final final))))) + fmt) + 'dateline) + (setq-local org-agenda-columns-active t)))) + (if (bobp) (throw :complete t) (forward-line -1))))))) + +(defun org-agenda-colview-compute (fmt) + "Compute the relevant columns in the contributing source buffers." + (dolist (file org-agenda-contributing-files) + (let ((b (find-buffer-visiting file))) + (with-current-buffer (or (buffer-base-buffer b) b) + (org-with-wide-buffer + (org-with-silent-modifications + (remove-text-properties (point-min) (point-max) '(org-summaries t))) + (goto-char (point-min)) + (org-columns-get-format-and-top-level) + (dolist (spec fmt) + (let ((prop (car spec))) + (cond + ((equal prop "CLOCKSUM") (org-clock-sum)) + ((equal prop "CLOCKSUM_T") (org-clock-sum-today)) + ((and (nth 3 spec) + (let ((a (assoc prop org-columns-current-fmt-compiled))) + (equal (nth 3 a) (nth 3 spec)))) + (org-columns-compute prop)))))))))) + + +(provide 'org-colview) + +;;; org-colview.el ends here diff --git a/elpa/org-9.1.14/org-compat.el b/elpa/org-9.1.14/org-compat.el new file mode 100644 index 00000000..1fd408de --- /dev/null +++ b/elpa/org-9.1.14/org-compat.el @@ -0,0 +1,563 @@ +;;; org-compat.el --- Compatibility Code for Older Emacsen -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file contains code needed for compatibility with older +;; versions of GNU Emacs. + +;;; Code: + +(require 'cl-lib) +(require 'org-macs) + +(declare-function org-at-table.el-p "org" ()) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-type "org-element" (element)) +(declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading)) +(declare-function org-link-set-parameters "org" (type &rest rest)) +(declare-function org-table-end "org-table" (&optional table-type)) +(declare-function outline-next-heading "outline" ()) +(declare-function table--at-cell-p "table" (position &optional object at-column)) + +(defvar org-table-any-border-regexp) +(defvar org-table-dataline-regexp) +(defvar org-table-tab-recognizes-table.el) +(defvar org-table1-hline-regexp) + +;;; Emacs < 25.1 compatibility + +(when (< emacs-major-version 25) + (defalias 'outline-hide-entry 'hide-entry) + (defalias 'outline-hide-sublevels 'hide-sublevels) + (defalias 'outline-hide-subtree 'hide-subtree) + (defalias 'outline-show-all 'show-all) + (defalias 'outline-show-branches 'show-branches) + (defalias 'outline-show-children 'show-children) + (defalias 'outline-show-entry 'show-entry) + (defalias 'outline-show-subtree 'show-subtree) + (defalias 'xref-find-definitions 'find-tag) + (defalias 'format-message 'format) + (defalias 'gui-get-selection 'x-get-selection)) + +(unless (fboundp 'directory-name-p) + (defun directory-name-p (name) + "Return non-nil if NAME ends with a directory separator character." + (let ((len (length name)) + (lastc ?.)) + (if (> len 0) + (setq lastc (aref name (1- len)))) + (or (= lastc ?/) + (and (memq system-type '(windows-nt ms-dos)) + (= lastc ?\\)))))) + + +;;; Obsolete aliases (remove them after the next major release). + +;;;; XEmacs compatibility, now removed. +(define-obsolete-function-alias 'org-activate-mark 'activate-mark) +(define-obsolete-function-alias 'org-add-hook 'add-hook "Org 9.0") +(define-obsolete-function-alias 'org-bound-and-true-p 'bound-and-true-p "Org 9.0") +(define-obsolete-function-alias 'org-decompose-region 'decompose-region "Org 9.0") +(define-obsolete-function-alias 'org-defvaralias 'defvaralias "Org 9.0") +(define-obsolete-function-alias 'org-detach-overlay 'delete-overlay "Org 9.0") +(define-obsolete-function-alias 'org-file-equal-p 'file-equal-p "Org 9.0") +(define-obsolete-function-alias 'org-float-time 'float-time "Org 9.0") +(define-obsolete-function-alias 'org-indent-line-to 'indent-line-to "Org 9.0") +(define-obsolete-function-alias 'org-indent-to-column 'indent-to-column "Org 9.0") +(define-obsolete-function-alias 'org-looking-at-p 'looking-at-p "Org 9.0") +(define-obsolete-function-alias 'org-looking-back 'looking-back "Org 9.0") +(define-obsolete-function-alias 'org-match-string-no-properties 'match-string-no-properties "Org 9.0") +(define-obsolete-function-alias 'org-propertize 'propertize "Org 9.0") +(define-obsolete-function-alias 'org-select-frame-set-input-focus 'select-frame-set-input-focus "Org 9.0") + +(defmacro org-re (s) + "Replace posix classes in regular expression S." + (declare (debug (form)) + (obsolete "you can safely remove it." "Org 9.0")) + s) + +;;;; Functions from cl-lib that Org used to have its own implementation of. +(define-obsolete-function-alias 'org-count 'cl-count "Org 9.0") +(define-obsolete-function-alias 'org-every 'cl-every "Org 9.0") +(define-obsolete-function-alias 'org-find-if 'cl-find-if "Org 9.0") +(define-obsolete-function-alias 'org-reduce 'cl-reduce "Org 9.0") +(define-obsolete-function-alias 'org-remove-if 'cl-remove-if "Org 9.0") +(define-obsolete-function-alias 'org-remove-if-not 'cl-remove-if-not "Org 9.0") +(define-obsolete-function-alias 'org-some 'cl-some "Org 9.0") +(define-obsolete-function-alias 'org-floor* 'cl-floor "Org 9.0") + +(defun org-sublist (list start end) + "Return a section of LIST, from START to END. +Counting starts at 1." + (cl-subseq list (1- start) end)) +(make-obsolete 'org-sublist + "use cl-subseq (note the 0-based counting)." + "Org 9.0") + + +;;;; Functions available since Emacs 24.3 +(define-obsolete-function-alias 'org-buffer-narrowed-p 'buffer-narrowed-p "Org 9.0") +(define-obsolete-function-alias 'org-called-interactively-p 'called-interactively-p "Org 9.0") +(define-obsolete-function-alias 'org-char-to-string 'char-to-string "Org 9.0") +(define-obsolete-function-alias 'org-delete-directory 'delete-directory "Org 9.0") +(define-obsolete-function-alias 'org-format-seconds 'format-seconds "Org 9.0") +(define-obsolete-function-alias 'org-link-escape-browser 'url-encode-url "Org 9.0") +(define-obsolete-function-alias 'org-no-warnings 'with-no-warnings "Org 9.0") +(define-obsolete-function-alias 'org-number-sequence 'number-sequence "Org 9.0") +(define-obsolete-function-alias 'org-pop-to-buffer-same-window 'pop-to-buffer-same-window "Org 9.0") +(define-obsolete-function-alias 'org-string-match-p 'string-match-p "Org 9.0") + +;;;; Functions and variables from previous releases now obsolete. +(define-obsolete-function-alias 'org-element-remove-indentation + 'org-remove-indentation "Org 9.0") +(define-obsolete-variable-alias 'org-latex-create-formula-image-program + 'org-preview-latex-default-process "Org 9.0") +(define-obsolete-variable-alias 'org-latex-preview-ltxpng-directory + 'org-preview-latex-image-directory "Org 9.0") +(define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0") +(define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 9.0") +(define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp "Org 8.3") +(define-obsolete-function-alias 'org-image-file-name-regexp + 'image-file-name-regexp "Org 9.0") +(define-obsolete-function-alias 'org-completing-read-no-i + 'completing-read "Org 9.0") +(define-obsolete-function-alias 'org-icompleting-read + 'completing-read "Org 9.0") +(define-obsolete-function-alias 'org-iread-file-name 'read-file-name "Org 9.0") +(define-obsolete-function-alias 'org-days-to-time + 'org-time-stamp-to-now "Org 8.2") +(define-obsolete-variable-alias 'org-agenda-ignore-drawer-properties + 'org-agenda-ignore-properties "Org 9.0") +(define-obsolete-function-alias 'org-preview-latex-fragment + 'org-toggle-latex-fragment "Org 8.3") +(define-obsolete-function-alias 'org-export-get-genealogy + 'org-element-lineage "Org 9.0") +(define-obsolete-variable-alias 'org-latex-with-hyperref + 'org-latex-hyperref-template "Org 9.0") +(define-obsolete-variable-alias 'hfy-optimisations 'hfy-optimizations "Org 9.0") +(define-obsolete-variable-alias 'org-export-htmlized-org-css-url + 'org-org-htmlized-css-url "Org 8.2") +(define-obsolete-function-alias 'org-list-parse-list 'org-list-to-lisp "Org 9.0") +(define-obsolete-function-alias 'org-agenda-todayp + 'org-agenda-today-p "Org 9.0") +(define-obsolete-function-alias 'org-babel-examplize-region + 'org-babel-examplify-region "Org 9.0") +(define-obsolete-variable-alias 'org-babel-capitalize-example-region-markers + 'org-babel-uppercase-example-markers "Org 9.1") + +(define-obsolete-function-alias 'org-babel-trim 'org-trim "Org 9.0") +(define-obsolete-variable-alias 'org-html-style 'org-html-head "24.4") +(define-obsolete-function-alias 'org-insert-columns-dblock + 'org-columns-insert-dblock "Org 9.0") +(define-obsolete-variable-alias 'org-export-babel-evaluate + 'org-export-use-babel "Org 9.1") +(define-obsolete-function-alias 'org-activate-bracket-links + 'org-activate-links "Org 9.0") +(define-obsolete-function-alias 'org-activate-plain-links 'ignore "Org 9.0") +(define-obsolete-function-alias 'org-activate-angle-links 'ignore "Org 9.0") + +(defun org-in-fixed-width-region-p () + "Non-nil if point in a fixed-width region." + (save-match-data + (eq 'fixed-width (org-element-type (org-element-at-point))))) +(make-obsolete 'org-in-fixed-width-region-p + "use `org-element' library" + "Org 9.0") + +(defun org-compatible-face (inherits specs) + "Make a compatible face specification. +If INHERITS is an existing face and if the Emacs version supports +it, just inherit the face. If INHERITS is not given and SPECS +is, use SPECS to define the face." + (declare (indent 1)) + (if (facep inherits) + (list (list t :inherit inherits)) + specs)) +(make-obsolete 'org-compatible-face "you can remove it." "Org 9.0") + +(defun org-add-link-type (type &optional follow export) + "Add a new TYPE link. +FOLLOW and EXPORT are two functions. + +FOLLOW should take the link path as the single argument and do whatever +is necessary to follow the link, for example find a file or display +a mail message. + +EXPORT should format the link path for export to one of the export formats. +It should be a function accepting three arguments: + + path the path of the link, the text after the prefix (like \"http:\") + desc the description of the link, if any + format the export format, a symbol like `html' or `latex' or `ascii'. + +The function may use the FORMAT information to return different values +depending on the format. The return value will be put literally into +the exported file. If the return value is nil, this means Org should +do what it normally does with links which do not have EXPORT defined. + +Org mode has a built-in default for exporting links. If you are happy with +this default, there is no need to define an export function for the link +type. For a simple example of an export function, see `org-bbdb.el'. + +If TYPE already exists, update it with the arguments. +See `org-link-parameters' for documentation on the other parameters." + (org-link-set-parameters type :follow follow :export export) + (message "Created %s link." type)) + +(make-obsolete 'org-add-link-type "use `org-link-set-parameters' instead." "Org 9.0") + +(defun org-table-recognize-table.el () + "If there is a table.el table nearby, recognize it and move into it." + (when (and org-table-tab-recognizes-table.el (org-at-table.el-p)) + (beginning-of-line) + (unless (or (looking-at org-table-dataline-regexp) + (not (looking-at org-table1-hline-regexp))) + (forward-line) + (when (looking-at org-table-any-border-regexp) + (forward-line -2))) + (if (re-search-forward "|" (org-table-end t) t) + (progn + (require 'table) + (if (table--at-cell-p (point)) t + (message "recognizing table.el table...") + (table-recognize-table) + (message "recognizing table.el table...done"))) + (error "This should not happen")))) + +;; Not used by Org core since commit 6d1e3082, Feb 2010. +(make-obsolete 'org-table-recognize-table.el + "please notify the org mailing list if you use this function." + "Org 9.0") + +(defun org-remove-angle-brackets (s) + (org-unbracket-string "<" ">" s)) +(make-obsolete 'org-remove-angle-brackets 'org-unbracket-string "Org 9.0") + +(defun org-remove-double-quotes (s) + (org-unbracket-string "\"" "\"" s)) +(make-obsolete 'org-remove-double-quotes 'org-unbracket-string "Org 9.0") + +(defcustom org-publish-sitemap-file-entry-format "%t" + "Format string for site-map file entry. +You could use brackets to delimit on what part the link will be. + +%t is the title. +%a is the author. +%d is the date formatted using `org-publish-sitemap-date-format'." + :group 'org-export-publish + :type 'string) +(make-obsolete-variable + 'org-publish-sitemap-file-entry-format + "set `:sitemap-format-entry' in `org-publish-project-alist' instead." + "Org 9.1") + +(defvar org-agenda-skip-regexp) +(defun org-agenda-skip-entry-when-regexp-matches () + "Check if the current entry contains match for `org-agenda-skip-regexp'. +If yes, it returns the end position of this entry, causing agenda commands +to skip the entry but continuing the search in the subtree. This is a +function that can be put into `org-agenda-skip-function' for the duration +of a command." + (declare (obsolete "use `org-agenda-skip-if' instead." "Org 9.1")) + (let ((end (save-excursion (org-end-of-subtree t))) + skip) + (save-excursion + (setq skip (re-search-forward org-agenda-skip-regexp end t))) + (and skip end))) + +(defun org-agenda-skip-subtree-when-regexp-matches () + "Check if the current subtree contains match for `org-agenda-skip-regexp'. +If yes, it returns the end position of this tree, causing agenda commands +to skip this subtree. This is a function that can be put into +`org-agenda-skip-function' for the duration of a command." + (declare (obsolete "use `org-agenda-skip-if' instead." "Org 9.1")) + (let ((end (save-excursion (org-end-of-subtree t))) + skip) + (save-excursion + (setq skip (re-search-forward org-agenda-skip-regexp end t))) + (and skip end))) + +(defun org-agenda-skip-entry-when-regexp-matches-in-subtree () + "Check if the current subtree contains match for `org-agenda-skip-regexp'. +If yes, it returns the end position of the current entry (NOT the tree), +causing agenda commands to skip the entry but continuing the search in +the subtree. This is a function that can be put into +`org-agenda-skip-function' for the duration of a command. An important +use of this function is for the stuck project list." + (declare (obsolete "use `org-agenda-skip-if' instead." "Org 9.1")) + (let ((end (save-excursion (org-end-of-subtree t))) + (entry-end (save-excursion (outline-next-heading) (1- (point)))) + skip) + (save-excursion + (setq skip (re-search-forward org-agenda-skip-regexp end t))) + (and skip entry-end))) + +(define-obsolete-function-alias 'org-minutes-to-clocksum-string + 'org-duration-from-minutes "Org 9.1") + +(define-obsolete-function-alias 'org-hh:mm-string-to-minutes + 'org-duration-to-minutes "Org 9.1") + +(define-obsolete-function-alias 'org-duration-string-to-minutes + 'org-duration-to-minutes "Org 9.1") + +(make-obsolete-variable 'org-time-clocksum-format + "set `org-duration-format' instead." "Org 9.1") + +(make-obsolete-variable 'org-time-clocksum-use-fractional + "set `org-duration-format' instead." "Org 9.1") + +(make-obsolete-variable 'org-time-clocksum-fractional-format + "set `org-duration-format' instead." "Org 9.1") + +(make-obsolete-variable 'org-time-clocksum-use-effort-durations + "set `org-duration-units' instead." "Org 9.1") + +(define-obsolete-function-alias 'org-babel-number-p + 'org-babel--string-to-number "Org 9.0") + +(define-obsolete-variable-alias 'org-usenet-links-prefer-google + 'org-gnus-prefer-web-links "Org 9.1") + +(define-obsolete-variable-alias 'org-texinfo-def-table-markup + 'org-texinfo-table-default-markup "Org 9.1") + +;;; The function was made obsolete by commit 65399674d5 of 2013-02-22. +;;; This make-obsolete call was added 2016-09-01. +(make-obsolete 'org-capture-import-remember-templates + "use the `org-capture-templates' variable instead." + "Org 9.0") + + +;;;; Obsolete link types + +(eval-after-load 'org + '(progn + (org-link-set-parameters "file+emacs") ;since Org 9.0 + (org-link-set-parameters "file+sys"))) ;since Org 9.0 + + + +;;; Miscellaneous functions + +(defun org-version-check (version feature level) + (let* ((v1 (mapcar 'string-to-number (split-string version "[.]"))) + (v2 (mapcar 'string-to-number (split-string emacs-version "[.]"))) + (rmaj (or (nth 0 v1) 99)) + (rmin (or (nth 1 v1) 99)) + (rbld (or (nth 2 v1) 99)) + (maj (or (nth 0 v2) 0)) + (min (or (nth 1 v2) 0)) + (bld (or (nth 2 v2) 0))) + (if (or (< maj rmaj) + (and (= maj rmaj) + (< min rmin)) + (and (= maj rmaj) + (= min rmin) + (< bld rbld))) + (if (eq level :predicate) + ;; just return if we have the version + nil + (let ((msg (format "Emacs %s or greater is recommended for %s" + version feature))) + (display-warning 'org msg level) + t)) + t))) + +(defun org-get-x-clipboard (value) + "Get the value of the X or Windows clipboard." + (cond ((and (eq window-system 'x) + (fboundp 'gui-get-selection)) ;Silence byte-compiler. + (org-no-properties + (ignore-errors + (or (gui-get-selection value 'UTF8_STRING) + (gui-get-selection value 'COMPOUND_TEXT) + (gui-get-selection value 'STRING) + (gui-get-selection value 'TEXT))))) + ((and (eq window-system 'w32) (fboundp 'w32-get-clipboard-data)) + (w32-get-clipboard-data)))) + +(defun org-add-props (string plist &rest props) + "Add text properties to entire string, from beginning to end. +PLIST may be a list of properties, PROPS are individual properties and values +that will be added to PLIST. Returns the string that was modified." + (add-text-properties + 0 (length string) (if props (append plist props) plist) string) + string) +(put 'org-add-props 'lisp-indent-function 2) + +(defun org-fit-window-to-buffer (&optional window max-height min-height + shrink-only) + "Fit WINDOW to the buffer, but only if it is not a side-by-side window. +WINDOW defaults to the selected window. MAX-HEIGHT and MIN-HEIGHT are +passed through to `fit-window-to-buffer'. If SHRINK-ONLY is set, call +`shrink-window-if-larger-than-buffer' instead, the height limit is +ignored in this case." + (cond ((if (fboundp 'window-full-width-p) + (not (window-full-width-p window)) + ;; do nothing if another window would suffer + (> (frame-width) (window-width window)))) + ((and (fboundp 'fit-window-to-buffer) (not shrink-only)) + (fit-window-to-buffer window max-height min-height)) + ((fboundp 'shrink-window-if-larger-than-buffer) + (shrink-window-if-larger-than-buffer window))) + (or window (selected-window))) + +;; `set-transient-map' is only in Emacs >= 24.4 +(defalias 'org-set-transient-map + (if (fboundp 'set-transient-map) + 'set-transient-map + 'set-temporary-overlay-map)) + +;;; Region compatibility + +(defvar org-ignore-region nil + "Non-nil means temporarily disable the active region.") + +(defun org-region-active-p () + "Non-nil when the region active. +Unlike to `use-region-p', this function also checks +`org-ignore-region'." + (and (not org-ignore-region) (use-region-p))) + +(defun org-cursor-to-region-beginning () + (when (and (org-region-active-p) + (> (point) (region-beginning))) + (exchange-point-and-mark))) + +;;; Invisibility compatibility + +(defun org-remove-from-invisibility-spec (arg) + "Remove elements from `buffer-invisibility-spec'." + (if (fboundp 'remove-from-invisibility-spec) + (remove-from-invisibility-spec arg) + (if (consp buffer-invisibility-spec) + (setq buffer-invisibility-spec + (delete arg buffer-invisibility-spec))))) + +(defun org-in-invisibility-spec-p (arg) + "Is ARG a member of `buffer-invisibility-spec'?" + (if (consp buffer-invisibility-spec) + (member arg buffer-invisibility-spec))) + +(defun org-move-to-column (column &optional force _buffer) + "Move to column COLUMN. +Pass COLUMN and FORCE to `move-to-column'." + (let ((buffer-invisibility-spec + (if (listp buffer-invisibility-spec) + (remove '(org-filtered) buffer-invisibility-spec) + buffer-invisibility-spec))) + (move-to-column column force))) + +(defmacro org-find-library-dir (library) + `(file-name-directory (or (locate-library ,library) ""))) + +(defun org-count-lines (s) + "How many lines in string S?" + (let ((start 0) (n 1)) + (while (string-match "\n" s start) + (setq start (match-end 0) n (1+ n))) + (if (and (> (length s) 0) (= (aref s (1- (length s))) ?\n)) + (setq n (1- n))) + n)) + +(defun org-kill-new (string &rest args) + (remove-text-properties 0 (length string) '(line-prefix t wrap-prefix t) + string) + (apply 'kill-new string args)) + +;; `font-lock-ensure' is only available from 24.4.50 on +(defalias 'org-font-lock-ensure + (if (fboundp 'font-lock-ensure) + #'font-lock-ensure + (lambda (&optional _beg _end) + (with-no-warnings (font-lock-fontify-buffer))))) + +;; `file-local-name' was added in Emacs 26.1. +(defalias 'org-babel-local-file-name + (if (fboundp 'file-local-name) + 'file-local-name + (lambda (file) + "Return the local name component of FILE." + (or (file-remote-p file 'localname) file)))) + +(defmacro org-no-popups (&rest body) + "Suppress popup windows. +Let-bind some variables to nil around BODY to achieve the desired +effect, which variables to use depends on the Emacs version." + (if (org-version-check "24.2.50" "" :predicate) + `(let (pop-up-frames display-buffer-alist) + ,@body) + `(let (pop-up-frames special-display-buffer-names special-display-regexps special-display-function) + ,@body))) + +;;;###autoload +(defmacro org-check-version () + "Try very hard to provide sensible version strings." + (let* ((org-dir (org-find-library-dir "org")) + (org-version.el (concat org-dir "org-version.el")) + (org-fixup.el (concat org-dir "../mk/org-fixup.el"))) + (if (require 'org-version org-version.el 'noerror) + '(progn + (autoload 'org-release "org-version.el") + (autoload 'org-git-version "org-version.el")) + (if (require 'org-fixup org-fixup.el 'noerror) + '(org-fixup) + ;; provide fallback definitions and complain + (warn "Could not define org version correctly. Check installation!") + '(progn + (defun org-release () "N/A") + (defun org-git-version () "N/A !!check installation!!")))))) + +(defmacro org-with-silent-modifications (&rest body) + (if (fboundp 'with-silent-modifications) + `(with-silent-modifications ,@body) + `(org-unmodified ,@body))) +(def-edebug-spec org-with-silent-modifications (body)) + +;; Functions for Emacs < 24.4 compatibility +(defun org-define-error (name message) + "Define NAME as a new error signal. +MESSAGE is a string that will be output to the echo area if such +an error is signaled without being caught by a `condition-case'. +Implements `define-error' for older emacsen." + (if (fboundp 'define-error) (define-error name message) + (put name 'error-conditions + (copy-sequence (cons name (get 'error 'error-conditions)))))) + +(unless (fboundp 'string-suffix-p) + ;; From Emacs subr.el. + (defun string-suffix-p (suffix string &optional ignore-case) + "Return non-nil if SUFFIX is a suffix of STRING. +If IGNORE-CASE is non-nil, the comparison is done without paying +attention to case differences." + (let ((start-pos (- (length string) (length suffix)))) + (and (>= start-pos 0) + (eq t (compare-strings suffix nil nil + string start-pos nil ignore-case)))))) + +(provide 'org-compat) + +;;; org-compat.el ends here diff --git a/elpa/org-9.1.14/org-crypt.el b/elpa/org-9.1.14/org-crypt.el new file mode 100644 index 00000000..31850a40 --- /dev/null +++ b/elpa/org-9.1.14/org-crypt.el @@ -0,0 +1,275 @@ +;;; org-crypt.el --- Public Key Encryption for Org Entries -*- lexical-binding: t; -*- +;; Copyright (C) 2007-2018 Free Software Foundation, Inc. + +;; Emacs Lisp Archive Entry +;; Filename: org-crypt.el +;; Keywords: org-mode +;; Author: John Wiegley +;; Maintainer: Peter Jones +;; Description: Adds public key encryption to Org buffers +;; URL: http://www.newartisans.com/software/emacs.html +;; Compatibility: Emacs22 + +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; Right now this is just a set of functions to play with. It depends +;; on the epg library. Here's how you would use it: +;; +;; 1. To mark an entry for encryption, tag the heading with "crypt". +;; You can change the tag to any complex tag matching string by +;; setting the `org-crypt-tag-matcher' variable. +;; +;; 2. Set the encryption key to use in the `org-crypt-key' variable, +;; or use `M-x org-set-property' to set the property CRYPTKEY to +;; any address in your public keyring. The text of the entry (but +;; not its properties or headline) will be encrypted for this user. +;; For them to read it, the corresponding secret key must be +;; located in the secret key ring of the account where you try to +;; decrypt it. This makes it possible to leave secure notes that +;; only the intended recipient can read in a shared-org-mode-files +;; scenario. +;; If the key is not set, org-crypt will default to symmetric encryption. +;; +;; 3. To later decrypt an entry, use `org-decrypt-entries' or +;; `org-decrypt-entry'. It might be useful to bind this to a key, +;; like C-c C-/. I hope that in the future, C-c C-r can be might +;; overloaded to also decrypt an entry if it's encrypted, since +;; that fits nicely with the meaning of "reveal". +;; +;; 4. To automatically encrypt all necessary entries when saving a +;; file, call `org-crypt-use-before-save-magic' after loading +;; org-crypt.el. + +;;; Thanks: + +;; - Carsten Dominik +;; - Vitaly Ostanin + +(require 'org) + +;;; Code: + +(declare-function epg-decrypt-string "epg" (context cipher)) +(declare-function epg-list-keys "epg" (context &optional name mode)) +(declare-function epg-make-context "epg" + (&optional protocol armor textmode include-certs + cipher-algorithm digest-algorithm + compress-algorithm)) +(declare-function epg-encrypt-string "epg" + (context plain recipients &optional sign always-trust)) +(defvar epg-context) + + +(defgroup org-crypt nil + "Org Crypt." + :tag "Org Crypt" + :group 'org) + +(defcustom org-crypt-tag-matcher "crypt" + "The tag matcher used to find headings whose contents should be encrypted. + +See the \"Match syntax\" section of the org manual for more details." + :type 'string + :group 'org-crypt) + +(defcustom org-crypt-key "" + "The default key to use when encrypting the contents of a heading. + +This setting can also be overridden in the CRYPTKEY property." + :type 'string + :group 'org-crypt) + +(defcustom org-crypt-disable-auto-save 'ask + "What org-decrypt should do if `auto-save-mode' is enabled. + +t : Disable auto-save-mode for the current buffer + prior to decrypting an entry. + +nil : Leave auto-save-mode enabled. + This may cause data to be written to disk unencrypted! + +`ask' : Ask user whether or not to disable auto-save-mode + for the current buffer. + +`encrypt': Leave auto-save-mode enabled for the current buffer, + but automatically re-encrypt all decrypted entries + *before* auto-saving. + NOTE: This only works for entries which have a tag + that matches `org-crypt-tag-matcher'." + :group 'org-crypt + :version "24.1" + :type '(choice (const :tag "Always" t) + (const :tag "Never" nil) + (const :tag "Ask" ask) + (const :tag "Encrypt" encrypt))) + +(defun org-crypt-check-auto-save () + "Check whether auto-save-mode is enabled for the current buffer. + +`auto-save-mode' may cause leakage when decrypting entries, so +check whether it's enabled, and decide what to do about it. + +See `org-crypt-disable-auto-save'." + (when buffer-auto-save-file-name + (cond + ((or + (eq org-crypt-disable-auto-save t) + (and + (eq org-crypt-disable-auto-save 'ask) + (y-or-n-p "org-decrypt: auto-save-mode may cause leakage. Disable it for current buffer? "))) + (message "org-decrypt: Disabling auto-save-mode for %s" + (or (buffer-file-name) (current-buffer))) + ;; The argument to auto-save-mode has to be "-1", since + ;; giving a "nil" argument toggles instead of disabling. + (auto-save-mode -1)) + ((eq org-crypt-disable-auto-save nil) + (message "org-decrypt: Decrypting entry with auto-save-mode enabled. This may cause leakage.")) + ((eq org-crypt-disable-auto-save 'encrypt) + (message "org-decrypt: Enabling re-encryption on auto-save.") + (add-hook 'auto-save-hook + (lambda () + (message "org-crypt: Re-encrypting all decrypted entries due to auto-save.") + (org-encrypt-entries)) + nil t)) + (t nil)))) + +(defun org-crypt-key-for-heading () + "Return the encryption key for the current heading." + (save-excursion + (org-back-to-heading t) + (or (org-entry-get nil "CRYPTKEY" 'selective) + org-crypt-key + (and (boundp 'epa-file-encrypt-to) epa-file-encrypt-to) + (message "No crypt key set, using symmetric encryption.")))) + +(defun org-encrypt-string (str crypt-key) + "Return STR encrypted with CRYPT-KEY." + ;; Text and key have to be identical, otherwise we re-crypt. + (if (and (string= crypt-key (get-text-property 0 'org-crypt-key str)) + (string= (sha1 str) (get-text-property 0 'org-crypt-checksum str))) + (get-text-property 0 'org-crypt-text str) + (setq-local epg-context (epg-make-context nil t t)) + (epg-encrypt-string epg-context str (epg-list-keys epg-context crypt-key)))) + +(defun org-encrypt-entry () + "Encrypt the content of the current headline." + (interactive) + (require 'epg) + (org-with-wide-buffer + (org-back-to-heading t) + (setq-local epg-context (epg-make-context nil t t)) + (let ((start-heading (point))) + (org-end-of-meta-data) + (unless (looking-at-p "-----BEGIN PGP MESSAGE-----") + (let ((folded (org-invisible-p)) + (crypt-key (org-crypt-key-for-heading)) + (beg (point))) + (goto-char start-heading) + (org-end-of-subtree t t) + (org-back-over-empty-lines) + (let ((contents (delete-and-extract-region beg (point)))) + (condition-case err + (insert (org-encrypt-string contents crypt-key)) + ;; If encryption failed, make sure to insert back entry + ;; contents in the buffer. + (error (insert contents) (error (nth 1 err))))) + (when folded + (goto-char start-heading) + (outline-hide-subtree)) + nil))))) + +(defun org-decrypt-entry () + "Decrypt the content of the current headline." + (interactive) + (require 'epg) + (unless (org-before-first-heading-p) + (org-with-wide-buffer + (org-back-to-heading t) + (let ((heading-point (point)) + (heading-was-invisible-p + (save-excursion + (outline-end-of-heading) + (org-invisible-p)))) + (org-end-of-meta-data) + (when (looking-at "-----BEGIN PGP MESSAGE-----") + (org-crypt-check-auto-save) + (setq-local epg-context (epg-make-context nil t t)) + (let* ((end (save-excursion + (search-forward "-----END PGP MESSAGE-----") + (forward-line) + (point))) + (encrypted-text (buffer-substring-no-properties (point) end)) + (decrypted-text + (decode-coding-string + (epg-decrypt-string + epg-context + encrypted-text) + 'utf-8))) + ;; Delete region starting just before point, because the + ;; outline property starts at the \n of the heading. + (delete-region (1- (point)) end) + ;; Store a checksum of the decrypted and the encrypted + ;; text value. This allows reusing the same encrypted text + ;; if the text does not change, and therefore avoid a + ;; re-encryption process. + (insert "\n" (propertize decrypted-text + 'org-crypt-checksum (sha1 decrypted-text) + 'org-crypt-key (org-crypt-key-for-heading) + 'org-crypt-text encrypted-text)) + (when heading-was-invisible-p + (goto-char heading-point) + (org-flag-subtree t)) + nil)))))) + +(defun org-encrypt-entries () + "Encrypt all top-level entries in the current buffer." + (interactive) + (let ((org--matcher-tags-todo-only nil)) + (org-scan-tags + 'org-encrypt-entry + (cdr (org-make-tags-matcher org-crypt-tag-matcher)) + org--matcher-tags-todo-only))) + +(defun org-decrypt-entries () + "Decrypt all entries in the current buffer." + (interactive) + (let ((org--matcher-tags-todo-only nil)) + (org-scan-tags + 'org-decrypt-entry + (cdr (org-make-tags-matcher org-crypt-tag-matcher)) + org--matcher-tags-todo-only))) + +(defun org-at-encrypted-entry-p () + "Is the current entry encrypted?" + (unless (org-before-first-heading-p) + (save-excursion + (org-back-to-heading t) + (search-forward "-----BEGIN PGP MESSAGE-----" + (save-excursion (outline-next-heading)) t)))) + +(defun org-crypt-use-before-save-magic () + "Add a hook to automatically encrypt entries before a file is saved to disk." + (add-hook + 'org-mode-hook + (lambda () (add-hook 'before-save-hook 'org-encrypt-entries nil t)))) + +(add-hook 'org-reveal-start-hook 'org-decrypt-entry) + +(provide 'org-crypt) + +;;; org-crypt.el ends here diff --git a/elpa/org-9.1.14/org-ctags.el b/elpa/org-9.1.14/org-ctags.el new file mode 100644 index 00000000..72ea76fe --- /dev/null +++ b/elpa/org-9.1.14/org-ctags.el @@ -0,0 +1,533 @@ +;;; org-ctags.el - Integrate Emacs "tags" Facility with Org -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2007-2018 Free Software Foundation, Inc. + +;; Author: Paul Sexton + + +;; Keywords: org, wp +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;; +;; Synopsis +;; ======== +;; +;; Allows Org mode to make use of the Emacs `etags' system. Defines +;; tag destinations in Org files as any text between <>. This allows the tags-generation program `exuberant +;; ctags' to parse these files and create tag tables that record where +;; these destinations are found. Plain [[links]] in org mode files +;; which do not have <> within the same file +;; will then be interpreted as links to these 'tagged' destinations, +;; allowing seamless navigation between multiple Org files. Topics +;; can be created in any org mode file and will always be found by +;; plain links from other files. Other file types recognized by ctags +;; (source code files, latex files, etc) will also be available as +;; destinations for plain links, and similarly, Org links will be +;; available as tags from source files. Finally, the function +;; `org-ctags-find-tag-interactive' lets you choose any known tag, +;; using autocompletion, and quickly jump to it. +;; +;; Installation +;; ============ +;; +;; Install org mode +;; Ensure org-ctags.el is somewhere in your emacs load path. +;; Download and install Exuberant ctags -- "http://ctags.sourceforge.net/" +;; Edit your .emacs file (see next section) and load emacs. + +;; To put in your init file (.emacs): +;; ================================== +;; +;; Assuming you already have org mode installed and set up: +;; +;; (setq org-ctags-path-to-ctags "/path/to/ctags/executable") +;; (add-hook 'org-mode-hook +;; (lambda () +;; (define-key org-mode-map "\C-co" 'org-ctags-find-tag-interactive))) +;; +;; By default, with org-ctags loaded, org will first try and visit the tag +;; with the same name as the link; then, if unsuccessful, ask the user if +;; he/she wants to rebuild the 'TAGS' database and try again; then ask if +;; the user wishes to append 'tag' as a new toplevel heading at the end of +;; the buffer; and finally, defer to org's default behavior which is to +;; search the entire text of the current buffer for 'tag'. +;; +;; This behavior can be modified by changing the value of +;; ORG-CTAGS-OPEN-LINK-FUNCTIONS. For example I have the following in my +;; .emacs, which describes the same behavior as the above paragraph with +;; one difference: +;; +;; (setq org-ctags-open-link-functions +;; '(org-ctags-find-tag +;; org-ctags-ask-rebuild-tags-file-then-find-tag +;; org-ctags-ask-append-topic +;; org-ctags-fail-silently)) ; <-- prevents org default behavior +;; +;; +;; Usage +;; ===== +;; +;; When you click on a link "[[foo]]" and org cannot find a matching "<>" +;; in the current buffer, the tags facility will take over. The file TAGS in +;; the active directory is examined to see if the tags facility knows about +;; "<>" in any other files. If it does, the matching file will be opened +;; and the cursor will jump to the position of "<>" in that file. +;; +;; User-visible functions: +;; - `org-ctags-find-tag-interactive': type a tag (plain link) name and visit +;; it. With autocompletion. Bound to ctrl-O in the above setup. +;; - All the etags functions should work. These include: +;; +;; M-. `find-tag' -- finds the tag at point +;; +;; C-M-. find-tag based on regular expression +;; +;; M-x tags-search RET -- like C-M-. but searches through ENTIRE TEXT +;; of ALL the files referenced in the TAGS file. A quick way to +;; search through an entire 'project'. +;; +;; M-* "go back" from a tag jump. Like `org-mark-ring-goto'. +;; You may need to bind this key yourself with (eg) +;; (global-set-key (kbd "") 'pop-tag-mark) +;; +;; (see etags chapter in Emacs manual for more) +;; +;; +;; Keeping the TAGS file up to date +;; ================================ +;; +;; Tags mode has no way of knowing that you have created new tags by +;; typing in your Org buffer. New tags make it into the TAGS file in +;; 3 ways: +;; +;; 1. You re-run (org-ctags-create-tags "directory") to rebuild the file. +;; 2. You put the function `org-ctags-ask-rebuild-tags-file-then-find-tag' in +;; your `org-open-link-functions' list, as is done in the setup +;; above. This will cause the TAGS file to be rebuilt whenever a link +;; cannot be found. This may be slow with large file collections however. +;; 3. You run the following from the command line (all 1 line): +;; +;; ctags --langdef=orgmode --langmap=orgmode:.org +;; --regex-orgmode="/<<([^>]+)>>/\1/d,definition/" +;; -f /your/path/TAGS -e -R /your/path/*.org +;; +;; If you are paranoid, you might want to run (org-ctags-create-tags +;; "/path/to/org/files") at startup, by including the following toplevel form +;; in .emacs. However this can cause a pause of several seconds if ctags has +;; to scan lots of files. +;; +;; (progn +;; (message "-- rebuilding tags tables...") +;; (mapc 'org-ctags-create-tags tags-table-list)) + +;;; Code: + +(require 'org) + +(defgroup org-ctags nil + "Options concerning use of ctags within org mode." + :tag "Org-Ctags" + :group 'org-link) + +(defvar org-ctags-enabled-p t + "Activate ctags support in org mode?") + +(defvar org-ctags-tag-regexp "/<<([^>]+)>>/\\1/d,definition/" + "Regexp expression used by ctags external program. +The regexp matches tag destinations in Org files. +Format is: /REGEXP/TAGNAME/FLAGS,TAGTYPE/ +See the ctags documentation for more information.") + +(defcustom org-ctags-path-to-ctags + (if (executable-find "ctags-exuberant") "ctags-exuberant" "ctags") + "Name of the ctags executable file." + :group 'org-ctags + :version "24.1" + :type 'file) + +(defcustom org-ctags-open-link-functions + '(org-ctags-find-tag + org-ctags-ask-rebuild-tags-file-then-find-tag + org-ctags-ask-append-topic) + "List of functions to be prepended to ORG-OPEN-LINK-FUNCTIONS when ORG-CTAGS is active." + :group 'org-ctags + :version "24.1" + :type 'hook + :options '(org-ctags-find-tag + org-ctags-ask-rebuild-tags-file-then-find-tag + org-ctags-rebuild-tags-file-then-find-tag + org-ctags-ask-append-topic + org-ctags-append-topic + org-ctags-ask-visit-buffer-or-file + org-ctags-visit-buffer-or-file + org-ctags-fail-silently)) + + +(defvar org-ctags-tag-list nil + "List of all tags in the active TAGS file. +Created as a local variable in each buffer.") + +(defcustom org-ctags-new-topic-template + "* <<%t>>\n\n\n\n\n\n" + "Text to insert when creating a new org file via opening a hyperlink. +The following patterns are replaced in the string: + `%t' - replaced with the capitalized title of the hyperlink" + :group 'org-ctags + :version "24.1" + :type 'string) + + +(add-hook 'org-mode-hook + (lambda () + (when (and org-ctags-enabled-p + (buffer-file-name)) + ;; Make sure this file's directory is added to default + ;; directories in which to search for tags. + (let ((tags-filename + (expand-file-name + (concat (file-name-directory (buffer-file-name)) + "/TAGS")))) + (when (file-exists-p tags-filename) + (visit-tags-table tags-filename)))))) + + +(defadvice visit-tags-table (after org-ctags-load-tag-list activate compile) + (when (and org-ctags-enabled-p tags-file-name) + (setq-local org-ctags-tag-list + (org-ctags-all-tags-in-current-tags-table)))) + + +(defun org-ctags-enable () + (put 'org-mode 'find-tag-default-function 'org-ctags-find-tag-at-point) + (setq org-ctags-enabled-p t) + (dolist (fn org-ctags-open-link-functions) + (add-hook 'org-open-link-functions fn t))) + + +;;; General utility functions. =============================================== +;; These work outside org-ctags mode. + +(defun org-ctags-get-filename-for-tag (tag) + "TAG is a string. Search the active TAGS file for a matching tag. +If the tag is found, return a list containing the filename, line number, and +buffer position where the tag is found." + (interactive "sTag: ") + (unless tags-file-name + (call-interactively (visit-tags-table))) + (save-excursion + (visit-tags-table-buffer 'same) + (when tags-file-name + (with-current-buffer (get-file-buffer tags-file-name) + (goto-char (point-min)) + (cond + ((re-search-forward (format "^.*%s\\([0-9]+\\),\\([0-9]+\\)$" + (regexp-quote tag)) nil t) + (let ((line (string-to-number (match-string 1))) + (pos (string-to-number (match-string 2)))) + (cond + ((re-search-backward " \n\\(.*\\),[0-9]+\n") + (list (match-string 1) line pos)) + (t ; can't find a file name preceding the matched + ; tag?? + (error "Malformed TAGS file: %s" (buffer-name)))))) + (t ; tag not found + nil)))))) + + +(defun org-ctags-all-tags-in-current-tags-table () + "Read all tags defined in the active TAGS file, into a list of strings. +Return the list." + (interactive) + (let ((taglist nil)) + (unless tags-file-name + (call-interactively (visit-tags-table))) + (save-excursion + (visit-tags-table-buffer 'same) + (with-current-buffer (get-file-buffer tags-file-name) + (goto-char (point-min)) + (while (re-search-forward "^.*\\(.*\\)\\([0-9]+\\),\\([0-9]+\\)$" + nil t) + (push (substring-no-properties (match-string 1)) taglist))) + taglist))) + + +(defun org-ctags-string-search-and-replace (search replace string) + "Replace all instances of SEARCH with REPLACE in STRING." + (replace-regexp-in-string (regexp-quote search) replace string t t)) + + +;;; Internal functions ======================================================= + + +(defun org-ctags-open-file (name &optional title) + "Visit or create a file called `NAME.org', and insert a new topic. +The new topic will be titled NAME (or TITLE if supplied)." + (interactive "sFile name: ") + (condition-case v + (progn + (org-open-file name t) + (message "Opened file OK") + (goto-char (point-max)) + (insert (org-ctags-string-search-and-replace + "%t" (capitalize (or title name)) + org-ctags-new-topic-template)) + (message "Inserted new file text OK") + (org-mode-restart)) + (error (error "Error %S in org-ctags-open-file" v)))) + + +;;;; Misc interoperability with etags system ================================= + + +(defadvice xref-find-definitions + (before org-ctags-set-org-mark-before-finding-tag activate compile) + "Before trying to find a tag, save our current position on org mark ring." + (save-excursion + (when (and (derived-mode-p 'org-mode) org-ctags-enabled-p) + (org-mark-ring-push)))) + + + +(defun org-ctags-find-tag-at-point () + "Determine default tag to search for, based on text at point. +If there is no plausible default, return nil." + (let (from to bound) + (when (or (ignore-errors + ;; Look for hyperlink around `point'. + (save-excursion + (search-backward "[[") (setq from (+ 2 (point)))) + (save-excursion + (goto-char from) + (search-forward "]") (setq to (- (point) 1))) + (and (> to from) (>= (point) from) (<= (point) to))) + (progn + ;; Look at text around `point'. + (save-excursion + (skip-syntax-backward "w_") (setq from (point))) + (save-excursion + (skip-syntax-forward "w_") (setq to (point))) + (> to from)) + ;; Look between `line-beginning-position' and `point'. + (save-excursion + (and (setq bound (line-beginning-position)) + (skip-syntax-backward "^w_" bound) + (> (setq to (point)) bound) + (skip-syntax-backward "w_") + (setq from (point)))) + ;; Look between `point' and `line-end-position'. + (save-excursion + (and (setq bound (line-end-position)) + (skip-syntax-forward "^w_" bound) + (< (setq from (point)) bound) + (skip-syntax-forward "w_") + (setq to (point))))) + (buffer-substring-no-properties from to)))) + + +;;; Functions for use with 'org-open-link-functions' hook ================= + + +(defun org-ctags-find-tag (name) + "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS. +Look for a tag called `NAME' in the current TAGS table. If it is found, +visit the file and location where the tag is found." + (interactive "sTag: ") + (let ((old-buf (current-buffer)) + (old-pnt (point-marker)) + (old-mark (copy-marker (mark-marker)))) + (condition-case nil + (progn (xref-find-definitions name) + t) + (error + ;; only restore old location if find-tag raises error + (set-buffer old-buf) + (goto-char old-pnt) + (set-marker (mark-marker) old-mark) + nil)))) + + +(defun org-ctags-visit-buffer-or-file (name &optional create) + "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS. +Visit buffer named `NAME.org'. If there is no such buffer, visit the file +with the same name if it exists. If the file does not exist, then behavior +depends on the value of CREATE. + +If CREATE is nil (default), then return nil. Do not create a new file. +If CREATE is t, create the new file and visit it. +If CREATE is the symbol `ask', then ask the user if they wish to create +the new file." + (interactive) + (let ((filename (concat (substitute-in-file-name + (expand-file-name name)) + ".org"))) + (cond + ((get-buffer (concat name ".org")) + ;; Buffer is already open + (pop-to-buffer-same-window (get-buffer (concat name ".org")))) + ((file-exists-p filename) + ;; File exists but is not open --> open it + (message "Opening existing org file `%S'..." + filename) + (org-open-file filename t)) + ((or (eql create t) + (and (eql create 'ask) + (y-or-n-p (format-message + "File `%s.org' not found; create?" name)))) + (org-ctags-open-file filename name)) + (t ;; File does not exist, and we don't want to create it. + nil)))) + + +(defun org-ctags-ask-visit-buffer-or-file (name) + "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS. +Wrapper for org-ctags-visit-buffer-or-file, which ensures the user is +asked before creating a new file." + (org-ctags-visit-buffer-or-file name 'ask)) + + +(defun org-ctags-append-topic (name &optional narrowp) + "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS. +Append a new toplevel heading to the end of the current buffer. The +heading contains NAME surrounded by <>, thus making +the heading a destination for the tag `NAME'." + (interactive "sTopic: ") + (widen) + (goto-char (point-max)) + (newline 2) + (message "Adding topic in buffer %s" (buffer-name)) + (insert (org-ctags-string-search-and-replace + "%t" (capitalize name) org-ctags-new-topic-template)) + (backward-char 4) + (end-of-line) + (forward-line 2) + (when narrowp + ;;(org-tree-to-indirect-buffer 1) ;; opens new frame + (org-narrow-to-subtree)) + t) + + +(defun org-ctags-ask-append-topic (name &optional narrowp) + "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS. +Wrapper for org-ctags-append-topic, which first asks the user if they want +to append a new topic." + (if (y-or-n-p (format-message + "Topic `%s' not found; append to end of buffer?" name)) + (org-ctags-append-topic name narrowp) + nil)) + + +(defun org-ctags-rebuild-tags-file-then-find-tag (name) + "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS. +Like ORG-CTAGS-FIND-TAG, but calls the external ctags program first, +to rebuild (update) the TAGS file." + (unless tags-file-name + (call-interactively (visit-tags-table))) + (when (buffer-file-name) + (org-ctags-create-tags)) + (org-ctags-find-tag name)) + + +(defun org-ctags-ask-rebuild-tags-file-then-find-tag (name) + "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS. +Wrapper for org-ctags-rebuild-tags-file-then-find-tag." + (if (and (buffer-file-name) + (y-or-n-p + (format-message + "Tag `%s' not found. Rebuild table `%s/TAGS' and look again?" + name + (file-name-directory (buffer-file-name))))) + (org-ctags-rebuild-tags-file-then-find-tag name) + nil)) + + +(defun org-ctags-fail-silently (_name) + "This function is intended to be used in ORG-OPEN-LINK-FUNCTIONS. +Put as the last function in the list if you want to prevent Org's +default behavior of free text search." + t) + + +;;; User-visible functions =================================================== + + +(defun org-ctags-create-tags (&optional directory-name) + "(Re)create tags file in the directory of the active buffer. +The file will contain tag definitions for all the files in the +directory and its subdirectories which are recognized by ctags. +This will include files ending in `.org' as well as most other +source files (.C, .H, .EL, .LISP, etc). All the resulting tags +end up in one file, called TAGS, located in the directory. This +function may take several seconds to finish if the directory or +its subdirectories contain large numbers of taggable files." + (interactive) + (cl-assert (buffer-file-name)) + (let ((dir-name (or directory-name + (file-name-directory (buffer-file-name)))) + (exitcode nil)) + (save-excursion + (setq exitcode + (shell-command + (format (concat "%s --langdef=orgmode --langmap=orgmode:.org " + "--regex-orgmode=\"%s\" -f \"%s\" -e -R \"%s\"") + org-ctags-path-to-ctags + org-ctags-tag-regexp + (expand-file-name (concat dir-name "/TAGS")) + (expand-file-name (concat dir-name "/*"))))) + (cond + ((eql 0 exitcode) + (setq-local org-ctags-tag-list + (org-ctags-all-tags-in-current-tags-table))) + (t + ;; This seems to behave differently on Linux, so just ignore + ;; error codes for now + ;;(error "Calling ctags executable resulted in error code: %s" + ;; exitcode) + nil))))) + + +(defvar org-ctags-find-tag-history nil + "History of tags visited by org-ctags-find-tag-interactive.") + +(defun org-ctags-find-tag-interactive () + "Prompt for the name of a tag, with autocompletion, then visit the named tag. +Uses `ido-mode' if available. +If the user enters a string that does not match an existing tag, create +a new topic." + (interactive) + (let* ((completing-read-fn (if (fboundp 'ido-completing-read) + 'ido-completing-read + 'completing-read)) + (tag (funcall completing-read-fn "Topic: " org-ctags-tag-list + nil 'confirm nil 'org-ctags-find-tag-history))) + (when tag + (cond + ((member tag org-ctags-tag-list) + ;; Existing tag + (push tag org-ctags-find-tag-history) + (xref-find-definitions tag)) + (t + ;; New tag + (run-hook-with-args-until-success + 'org-open-link-functions tag)))))) + + +(org-ctags-enable) + +(provide 'org-ctags) + +;;; org-ctags.el ends here diff --git a/elpa/org-9.1.14/org-datetree.el b/elpa/org-9.1.14/org-datetree.el new file mode 100644 index 00000000..d00bad22 --- /dev/null +++ b/elpa/org-9.1.14/org-datetree.el @@ -0,0 +1,248 @@ +;;; org-datetree.el --- Create date entries in a tree -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file contains code to create entries in a tree where the top-level +;; nodes represent years, the level 2 nodes represent the months, and the +;; level 1 entries days. + +;;; Code: + +(require 'org) + +(defvar org-datetree-base-level 1 + "The level at which years should be placed in the date tree. +This is normally one, but if the buffer has an entry with a +DATE_TREE (or WEEK_TREE for ISO week entries) property (any +value), the date tree will become a subtree under that entry, so +the base level will be properly adjusted.") + +(defcustom org-datetree-add-timestamp nil + "When non-nil, add a time stamp matching date of entry. +Added time stamp is active unless value is `inactive'." + :group 'org-capture + :version "24.3" + :type '(choice + (const :tag "Do not add a time stamp" nil) + (const :tag "Add an inactive time stamp" inactive) + (const :tag "Add an active time stamp" active))) + +;;;###autoload +(defun org-datetree-find-date-create (d &optional keep-restriction) + "Find or create an entry for date D. +If KEEP-RESTRICTION is non-nil, do not widen the buffer. +When it is nil, the buffer will be widened to make sure an existing date +tree can be found. If it is the symbol `subtree-at-point', then the tree +will be built under the headline at point." + (setq-local org-datetree-base-level 1) + (save-restriction + (if (eq keep-restriction 'subtree-at-point) + (progn + (unless (org-at-heading-p) (error "Not at heading")) + (widen) + (org-narrow-to-subtree) + (setq-local org-datetree-base-level + (org-get-valid-level (org-current-level) 1))) + (unless keep-restriction (widen)) + ;; Support the old way of tree placement, using a property + (let ((prop (org-find-property "DATE_TREE"))) + (when prop + (goto-char prop) + (setq-local org-datetree-base-level + (org-get-valid-level (org-current-level) 1)) + (org-narrow-to-subtree)))) + (goto-char (point-min)) + (let ((year (calendar-extract-year d)) + (month (calendar-extract-month d)) + (day (calendar-extract-day d))) + (org-datetree--find-create + "^\\*+[ \t]+\\([12][0-9]\\{3\\}\\)\\(\\s-*?\ +\\([ \t]:[[:alnum:]:_@#%%]+:\\)?\\s-*$\\)" + year) + (org-datetree--find-create + "^\\*+[ \t]+%d-\\([01][0-9]\\) \\w+$" + year month) + (org-datetree--find-create + "^\\*+[ \t]+%d-%02d-\\([0123][0-9]\\) \\w+$" + year month day)))) + +;;;###autoload +(defun org-datetree-find-iso-week-create (d &optional keep-restriction) + "Find or create an ISO week entry for date D. +Compared to `org-datetree-find-date-create' this function creates +entries ordered by week instead of months. +When it is nil, the buffer will be widened to make sure an existing date +tree can be found. If it is the symbol `subtree-at-point', then the tree +will be built under the headline at point." + (setq-local org-datetree-base-level 1) + (save-restriction + (if (eq keep-restriction 'subtree-at-point) + (progn + (unless (org-at-heading-p) (error "Not at heading")) + (widen) + (org-narrow-to-subtree) + (setq-local org-datetree-base-level + (org-get-valid-level (org-current-level) 1))) + (unless keep-restriction (widen)) + ;; Support the old way of tree placement, using a property + (let ((prop (org-find-property "WEEK_TREE"))) + (when prop + (goto-char prop) + (setq-local org-datetree-base-level + (org-get-valid-level (org-current-level) 1)) + (org-narrow-to-subtree)))) + (goto-char (point-min)) + (require 'cal-iso) + (let* ((year (calendar-extract-year d)) + (month (calendar-extract-month d)) + (day (calendar-extract-day d)) + (time (encode-time 0 0 0 day month year)) + (iso-date (calendar-iso-from-absolute + (calendar-absolute-from-gregorian d))) + (weekyear (nth 2 iso-date)) + (week (nth 0 iso-date))) + ;; ISO 8601 week format is %G-W%V(-%u) + (org-datetree--find-create + "^\\*+[ \t]+\\([12][0-9]\\{3\\}\\)\\(\\s-*?\ +\\([ \t]:[[:alnum:]:_@#%%]+:\\)?\\s-*$\\)" + weekyear nil nil + (format-time-string "%G" time)) + (org-datetree--find-create + "^\\*+[ \t]+%d-W\\([0-5][0-9]\\)$" + weekyear week nil + (format-time-string "%G-W%V" time)) + ;; For the actual day we use the regular date instead of ISO week. + (org-datetree--find-create + "^\\*+[ \t]+%d-%02d-\\([0123][0-9]\\) \\w+$" + year month day)))) + +(defun org-datetree--find-create (regex year &optional month day insert) + "Find the datetree matched by REGEX for YEAR, MONTH, or DAY. +REGEX is passed to `format' with YEAR, MONTH, and DAY as +arguments. Match group 1 is compared against the specified date +component. If INSERT is non-nil and there is no match then it is +inserted into the buffer." + (when (or month day) + (org-narrow-to-subtree)) + (let ((re (format regex year month day)) + match) + (goto-char (point-min)) + (while (and (setq match (re-search-forward re nil t)) + (goto-char (match-beginning 1)) + (< (string-to-number (match-string 1)) (or day month year)))) + (cond + ((not match) + (goto-char (point-max)) + (unless (bolp) (insert "\n")) + (org-datetree-insert-line year month day insert)) + ((= (string-to-number (match-string 1)) (or day month year)) + (beginning-of-line)) + (t + (beginning-of-line) + (org-datetree-insert-line year month day insert))))) + +(defun org-datetree-insert-line (year &optional month day text) + (delete-region (save-excursion (skip-chars-backward " \t\n") (point)) (point)) + (insert "\n" (make-string org-datetree-base-level ?*) " \n") + (backward-char) + (when month (org-do-demote)) + (when day (org-do-demote)) + (if text + (insert text) + (insert (format "%d" year)) + (when month + (insert + (if day + (format-time-string "-%m-%d %A" (encode-time 0 0 0 day month year)) + (format-time-string "-%m %B" (encode-time 0 0 0 1 month year)))))) + (when (and day org-datetree-add-timestamp) + (save-excursion + (insert "\n") + (org-indent-line) + (org-insert-time-stamp + (encode-time 0 0 0 day month year) + nil + (eq org-datetree-add-timestamp 'inactive)))) + (beginning-of-line)) + +(defun org-datetree-file-entry-under (txt d) + "Insert a node TXT into the date tree under date D." + (org-datetree-find-date-create d) + (let ((level (org-get-valid-level (funcall outline-level) 1))) + (org-end-of-subtree t t) + (org-back-over-empty-lines) + (org-paste-subtree level txt))) + +(defun org-datetree-cleanup () + "Make sure all entries in the current tree are under the correct date. +It may be useful to restrict the buffer to the applicable portion +before running this command, even though the command tries to be smart." + (interactive) + (goto-char (point-min)) + (let ((dre (concat "\\<" org-deadline-string "\\>[ \t]*\\'")) + (sre (concat "\\<" org-scheduled-string "\\>[ \t]*\\'"))) + (while (re-search-forward org-ts-regexp nil t) + (catch 'next + (let ((tmp (buffer-substring + (max (line-beginning-position) + (- (match-beginning 0) org-ds-keyword-length)) + (match-beginning 0)))) + (when (or (string-suffix-p "-" tmp) + (string-match dre tmp) + (string-match sre tmp)) + (throw 'next nil)) + (let* ((dct (decode-time (org-time-string-to-time (match-string 0)))) + (date (list (nth 4 dct) (nth 3 dct) (nth 5 dct))) + (year (nth 2 date)) + (month (car date)) + (day (nth 1 date)) + (pos (point)) + (hdl-pos (progn (org-back-to-heading t) (point)))) + (unless (org-up-heading-safe) + ;; No parent, we are not in a date tree. + (goto-char pos) + (throw 'next nil)) + (unless (looking-at "\\*+[ \t]+[0-9]+-[0-1][0-9]-[0-3][0-9]") + ;; Parent looks wrong, we are not in a date tree. + (goto-char pos) + (throw 'next nil)) + (when (looking-at (format "\\*+[ \t]+%d-%02d-%02d" year month day)) + ;; At correct date already, do nothing. + (goto-char pos) + (throw 'next nil)) + ;; OK, we need to refile this entry. + (goto-char hdl-pos) + (org-cut-subtree) + (save-excursion + (save-restriction + (org-datetree-file-entry-under (current-kill 0) date))))))))) + +(provide 'org-datetree) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-datetree.el ends here diff --git a/elpa/org-9.1.14/org-docview.el b/elpa/org-9.1.14/org-docview.el new file mode 100644 index 00000000..a467212d --- /dev/null +++ b/elpa/org-9.1.14/org-docview.el @@ -0,0 +1,103 @@ +;;; org-docview.el --- Support for links to doc-view-mode buffers -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: Jan Böcker +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file implements links to open files in doc-view-mode. +;; Org mode loads this module by default - if this is not what you want, +;; configure the variable `org-modules'. + +;; The links take the form +;; +;; docview::: +;; +;; for example: [[docview:~/.elisp/org/doc/org.pdf::1][Org-Mode Manual]] +;; +;; Autocompletion for inserting links is supported; you will be +;; prompted for a file and a page number. +;; +;; If you use org-store-link in a doc-view mode buffer, the stored +;; link will point to the current page. + +;;; Code: + + +(require 'org) +(require 'doc-view) + +(declare-function doc-view-goto-page "doc-view" (page)) +(declare-function image-mode-window-get "image-mode" (prop &optional winprops)) + +(org-link-set-parameters "docview" + :follow #'org-docview-open + :export #'org-docview-export + :store #'org-docview-store-link) + +(defun org-docview-export (link description format) + "Export a docview link from Org files." + (let* ((path (if (string-match "\\(.+\\)::.+" link) (match-string 1 link) + link)) + (desc (or description link))) + (when (stringp path) + (setq path (org-link-escape (expand-file-name path))) + (cond + ((eq format 'html) (format "%s" path desc)) + ((eq format 'latex) (format "\\href{%s}{%s}" path desc)) + ((eq format 'ascii) (format "%s (%s)" desc path)) + (t path))))) + +(defun org-docview-open (link) + (string-match "\\(.*?\\)\\(?:::\\([0-9]+\\)\\)?$" link) + (let ((path (match-string 1 link)) + (page (and (match-beginning 2) + (string-to-number (match-string 2 link))))) + ;; Let Org mode open the file (in-emacs = 1) to ensure + ;; org-link-frame-setup is respected. + (org-open-file path 1) + (when page (doc-view-goto-page page)))) + +(defun org-docview-store-link () + "Store a link to a docview buffer." + (when (eq major-mode 'doc-view-mode) + ;; This buffer is in doc-view-mode + (let* ((path buffer-file-name) + (page (image-mode-window-get 'page)) + (link (concat "docview:" path "::" (number-to-string page)))) + (org-store-link-props + :type "docview" + :link link + :description path)))) + +(defun org-docview-complete-link () + "Use the existing file name completion for file. +Links to get the file name, then ask the user for the page number +and append it." + (concat (replace-regexp-in-string "^file:" "docview:" (org-file-complete-link)) + "::" + (read-from-minibuffer "Page:" "1"))) + + +(provide 'org-docview) + +;;; org-docview.el ends here diff --git a/elpa/org-9.1.14/org-duration.el b/elpa/org-9.1.14/org-duration.el new file mode 100644 index 00000000..1c962ba9 --- /dev/null +++ b/elpa/org-9.1.14/org-duration.el @@ -0,0 +1,448 @@ +;;; org-duration.el --- Library handling durations -*- lexical-binding: t; -*- + +;; Copyright (C) 2017-2018 Free Software Foundation, Inc. + +;; Author: Nicolas Goaziou +;; Keywords: outlines, hypermedia, calendar, wp + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;; This library provides tools to manipulate durations. A duration +;; can have multiple formats: +;; +;; - 3:12 +;; - 1:23:45 +;; - 1y 3d 3h 4min +;; - 3d 13:35 +;; - 2.35h +;; +;; More accurately, it consists of numbers and units, as defined in +;; variable `org-duration-units', separated with white spaces, and +;; a "H:MM" or "H:MM:SS" part. White spaces are tolerated between the +;; number and its relative unit. Variable `org-duration-format' +;; controls durations default representation. +;; +;; The library provides functions allowing to convert a duration to, +;; and from, a number of minutes: `org-duration-to-minutes' and +;; `org-duration-from-minutes'. It also provides two lesser tools: +;; `org-duration-p', and `org-duration-h:mm-only-p'. +;; +;; Users can set the number of minutes per unit, or define new units, +;; in `org-duration-units'. The library also supports canonical +;; duration, i.e., a duration that doesn't depend on user's settings, +;; through optional arguments. + +;;; Code: + +(require 'cl-lib) +(require 'org-macs) +(declare-function org-trim "org" (s &optional keep-lead)) + + +;;; Public variables + +(defconst org-duration-canonical-units + `(("min" . 1) + ("h" . 60) + ("d" . ,(* 60 24))) + "Canonical time duration units. +See `org-duration-units' for details.") + +(defcustom org-duration-units + `(("min" . 1) + ("h" . 60) + ("d" . ,(* 60 24)) + ("w" . ,(* 60 24 7)) + ("m" . ,(* 60 24 30)) + ("y" . ,(* 60 24 365.25))) + "Conversion factor to minutes for a duration. + +Each entry has the form (UNIT . MODIFIER). + +In a duration string, a number followed by UNIT is multiplied by +the specified number of MODIFIER to obtain a duration in minutes. + +For example, the following value + + \\=`((\"min\" . 1) + (\"h\" . 60) + (\"d\" . ,(* 60 8)) + (\"w\" . ,(* 60 8 5)) + (\"m\" . ,(* 60 8 5 4)) + (\"y\" . ,(* 60 8 5 4 10))) + +is meaningful if you work an average of 8 hours per day, 5 days +a week, 4 weeks a month and 10 months a year. + +When setting this variable outside the Customize interface, make +sure to call the following command: + + \\[org-duration-set-regexps]" + :group 'org-agenda + :version "26.1" + :package-version '(Org . "9.1") + :set (lambda (var val) (set-default var val) (org-duration-set-regexps)) + :initialize 'custom-initialize-changed + :type '(choice + (const :tag "H:MM" h:mm) + (const :tag "H:MM:SS" h:mm:ss) + (alist :key-type (string :tag "Unit") + :value-type (number :tag "Modifier")))) + +(defcustom org-duration-format '(("d" . nil) (special . h:mm)) + "Format definition for a duration. + +The value can be set to, respectively, the symbols `h:mm:ss' or +`h:mm', which means a duration is expressed as, respectively, +a \"H:MM:SS\" or \"H:MM\" string. + +Alternatively, the value can be a list of entries following the +pattern: + + (UNIT . REQUIRED?) + +UNIT is a unit string, as defined in `org-duration-units'. The +time duration is formatted using only the time components that +are specified here. + +Units with a zero value are skipped, unless REQUIRED? is non-nil. +In that case, the unit is always used. + +Eventually, the list can contain one of the following special +entries: + + (special . h:mm) + (special . h:mm:ss) + + Units shorter than an hour are ignored. The hours and + minutes part of the duration is expressed unconditionally + with H:MM, or H:MM:SS, pattern. + + (special . PRECISION) + + A duration is expressed with a single unit, PRECISION being + the number of decimal places to show. The unit chosen is the + first one required or with a non-zero integer part. If there + is no such unit, the smallest one is used. + +For example, + + ((\"d\" . nil) (\"h\" . t) (\"min\" . t)) + +means a duration longer than a day is expressed in days, hours +and minutes, whereas a duration shorter than a day is always +expressed in hours and minutes, even when shorter than an hour. + +On the other hand, the value + + ((\"d\" . nil) (\"min\" . nil)) + +means a duration longer than a day is expressed in days and +minutes, whereas a duration shorter than a day is expressed +entirely in minutes, even when longer than an hour. + +The following format + + ((\"d\" . nil) (special . h:mm)) + +means that any duration longer than a day is expressed with both +a \"d\" unit and a \"H:MM\" part, whereas a duration shorter than +a day is expressed only as a \"H:MM\" string. + +Eventually, + + ((\"d\" . nil) (\"h\" . nil) (special . 2)) + +expresses a duration longer than a day as a decimal number, with +a 2-digits fractional part, of \"d\" unit. A duration shorter +than a day uses \"h\" unit instead." + :group 'org-time + :group 'org-clock + :version "26.1" + :package-version '(Org . "9.1") + :type '(choice + (const :tag "Use H:MM" h:mm) + (const :tag "Use H:MM:SS" h:mm:ss) + (repeat :tag "Use units" + (choice + (cons :tag "Use units" + (string :tag "Unit") + (choice (const :tag "Skip when zero" nil) + (const :tag "Always used" t))) + (cons :tag "Use a single decimal unit" + (const special) + (integer :tag "Number of decimals")) + (cons :tag "Use both units and H:MM" + (const special) + (const h:mm)) + (cons :tag "Use both units and H:MM:SS" + (const special) + (const h:mm:ss)))))) + + +;;; Internal variables and functions + +(defconst org-duration--h:mm-re + "\\`[ \t]*[0-9]+\\(?::[0-9]\\{2\\}\\)\\{1,2\\}[ \t]*\\'" + "Regexp matching a duration expressed with H:MM or H:MM:SS format. +See `org-duration--h:mm:ss-re' to only match the latter. Hours +can use any number of digits.") + +(defconst org-duration--h:mm:ss-re + "\\`[ \t]*[0-9]+\\(?::[0-9]\\{2\\}\\)\\{2\\}[ \t]*\\'" + "Regexp matching a duration expressed H:MM:SS format. +See `org-duration--h:mm-re' to also support H:MM format. Hours +can use any number of digits.") + +(defvar org-duration--unit-re nil + "Regexp matching a duration with an unit. +Allowed units are defined in `org-duration-units'. Match group +1 contains the bare number. Match group 2 contains the unit.") + +(defvar org-duration--full-re nil + "Regexp matching a duration expressed with units. +Allowed units are defined in `org-duration-units'.") + +(defvar org-duration--mixed-re nil + "Regexp matching a duration expressed with units and H:MM or H:MM:SS format. +Allowed units are defined in `org-duration-units'. Match group +1 contains units part. Match group 2 contains H:MM or H:MM:SS +part.") + +(defun org-duration--modifier (unit &optional canonical) + "Return modifier associated to string UNIT. +When optional argument CANONICAL is non-nil, refer to +`org-duration-canonical-units' instead of `org-duration-units'." + (or (cdr (assoc unit (if canonical + org-duration-canonical-units + org-duration-units))) + (error "Unknown unit: %S" unit))) + + +;;; Public functions + +;;;###autoload +(defun org-duration-set-regexps () + "Set duration related regexps." + (interactive) + (setq org-duration--unit-re + (concat "\\([0-9]+\\(?:\\.[0-9]*\\)?\\)[ \t]*" + ;; Since user-defined units in `org-duration-units' + ;; can differ from canonical units in + ;; `org-duration-canonical-units', include both in + ;; regexp. + (regexp-opt (mapcar #'car (append org-duration-canonical-units + org-duration-units)) + t))) + (setq org-duration--full-re + (format "\\`[ \t]*%s\\(?:[ \t]+%s\\)*[ \t]*\\'" + org-duration--unit-re + org-duration--unit-re)) + (setq org-duration--mixed-re + (format "\\`[ \t]*\\(?1:%s\\(?:[ \t]+%s\\)*\\)[ \t]+\ +\\(?2:[0-9]+\\(?::[0-9][0-9]\\)\\{1,2\\}\\)[ \t]*\\'" + org-duration--unit-re + org-duration--unit-re))) + +;;;###autoload +(defun org-duration-p (s) + "Non-nil when string S is a time duration." + (and (stringp s) + (or (string-match-p org-duration--full-re s) + (string-match-p org-duration--mixed-re s) + (string-match-p org-duration--h:mm-re s)))) + +;;;###autoload +(defun org-duration-to-minutes (duration &optional canonical) + "Return number of minutes of DURATION string. + +When optional argument CANONICAL is non-nil, ignore +`org-duration-units' and use standard time units value. + +A bare number is translated into minutes. The empty string is +translated into 0.0. + +Return value as a float. Raise an error if duration format is +not recognized." + (cond + ((equal duration "") 0.0) + ((numberp duration) (float duration)) + ((string-match-p org-duration--h:mm-re duration) + (pcase-let ((`(,hours ,minutes ,seconds) + (mapcar #'string-to-number (split-string duration ":")))) + (+ (/ (or seconds 0) 60.0) minutes (* 60 hours)))) + ((string-match-p org-duration--full-re duration) + (let ((minutes 0) + (s 0)) + (while (string-match org-duration--unit-re duration s) + (setq s (match-end 0)) + (let ((value (string-to-number (match-string 1 duration))) + (unit (match-string 2 duration))) + (cl-incf minutes (* value (org-duration--modifier unit canonical))))) + (float minutes))) + ((string-match org-duration--mixed-re duration) + (let ((units-part (match-string 1 duration)) + (hms-part (match-string 2 duration))) + (+ (org-duration-to-minutes units-part) + (org-duration-to-minutes hms-part)))) + ((string-match-p "\\`[0-9]+\\(\\.[0-9]*\\)?\\'" duration) + (float (string-to-number duration))) + (t (error "Invalid duration format: %S" duration)))) + +;;;###autoload +(defun org-duration-from-minutes (minutes &optional fmt canonical) + "Return duration string for a given number of MINUTES. + +Format duration according to `org-duration-format' or FMT, when +non-nil. + +When optional argument CANONICAL is non-nil, ignore +`org-duration-units' and use standard time units value. + +Raise an error if expected format is unknown." + (pcase (or fmt org-duration-format) + (`h:mm + (let ((minutes (floor minutes))) + (format "%d:%02d" (/ minutes 60) (mod minutes 60)))) + (`h:mm:ss + (let* ((whole-minutes (floor minutes)) + (seconds (floor (* 60 (- minutes whole-minutes))))) + (format "%s:%02d" + (org-duration-from-minutes whole-minutes 'h:mm) + seconds))) + ((pred atom) (error "Invalid duration format specification: %S" fmt)) + ;; Mixed format. Call recursively the function on both parts. + ((and duration-format + (let `(special . ,(and mode (or `h:mm:ss `h:mm))) + (assq 'special duration-format))) + (let* ((truncated-format + ;; Remove "special" mode from duration format in order to + ;; recurse properly. Also remove units smaller or equal + ;; to an hour since H:MM part takes care of it. + (cl-remove-if-not + (lambda (pair) + (pcase pair + (`(,(and unit (pred stringp)) . ,_) + (> (org-duration--modifier unit canonical) 60)) + (_ nil))) + duration-format)) + (min-modifier ;smallest modifier above hour + (and truncated-format + (apply #'min + (mapcar (lambda (p) + (org-duration--modifier (car p) canonical)) + truncated-format))))) + (if (or (null min-modifier) (< minutes min-modifier)) + ;; There is not unit above the hour or the smallest unit + ;; above the hour is too large for the number of minutes we + ;; need to represent. Use H:MM or H:MM:SS syntax. + (org-duration-from-minutes minutes mode canonical) + ;; Represent minutes above hour using provided units and H:MM + ;; or H:MM:SS below. + (let* ((units-part (* min-modifier (/ (floor minutes) min-modifier))) + (minutes-part (- minutes units-part))) + (concat + (org-duration-from-minutes units-part truncated-format canonical) + " " + (org-duration-from-minutes minutes-part mode)))))) + ;; Units format. + (duration-format + (let* ((fractional + (let ((digits (cdr (assq 'special duration-format)))) + (and digits + (or (wholenump digits) + (error "Unknown formatting directive: %S" digits)) + (format "%%.%df" digits)))) + (selected-units + (sort (cl-remove-if + ;; Ignore special format cells. + (lambda (pair) (pcase pair (`(special . ,_) t) (_ nil))) + duration-format) + (lambda (a b) + (> (org-duration--modifier (car a) canonical) + (org-duration--modifier (car b) canonical)))))) + (cond + ;; Fractional duration: use first unit that is either required + ;; or smaller than MINUTES. + (fractional + (let* ((unit (car + (or (cl-find-if + (lambda (pair) + (pcase pair + (`(,u . ,req?) + (or req? + (<= (org-duration--modifier u canonical) + minutes))))) + selected-units) + ;; Fall back to smallest unit. + (org-last selected-units)))) + (modifier (org-duration--modifier unit canonical))) + (concat (format fractional (/ (float minutes) modifier)) unit))) + ;; Otherwise build duration string according to available + ;; units. + ((org-string-nw-p + (org-trim + (mapconcat + (lambda (units) + (pcase-let* ((`(,unit . ,required?) units) + (modifier (org-duration--modifier unit canonical))) + (cond ((<= modifier minutes) + (let ((value (if (integerp modifier) + (/ (floor minutes) modifier) + (floor (/ minutes modifier))))) + (cl-decf minutes (* value modifier)) + (format " %d%s" value unit))) + (required? (concat " 0" unit)) + (t "")))) + selected-units + "")))) + ;; No unit can properly represent MINUTES. Use the smallest + ;; one anyway. + (t + (pcase-let ((`((,unit . ,_)) (last selected-units))) + (concat "0" unit)))))))) + +;;;###autoload +(defun org-duration-h:mm-only-p (times) + "Non-nil when every duration in TIMES has \"H:MM\" or \"H:MM:SS\" format. + +TIMES is a list of duration strings. + +Return nil if any duration is expressed with units, as defined in +`org-duration-units'. Otherwise, if any duration is expressed +with \"H:MM:SS\" format, return `h:mm:ss'. Otherwise, return +`h:mm'." + (let (hms-flag) + (catch :exit + (dolist (time times) + (cond ((string-match-p org-duration--full-re time) + (throw :exit nil)) + ((string-match-p org-duration--mixed-re time) + (throw :exit nil)) + (hms-flag nil) + ((string-match-p org-duration--h:mm:ss-re time) + (setq hms-flag 'h:mm:ss)))) + (or hms-flag 'h:mm)))) + + +;;; Initialization + +(org-duration-set-regexps) + +(provide 'org-duration) +;;; org-duration.el ends here diff --git a/elpa/org-9.1.14/org-element.el b/elpa/org-9.1.14/org-element.el new file mode 100644 index 00000000..f4452ea3 --- /dev/null +++ b/elpa/org-9.1.14/org-element.el @@ -0,0 +1,5980 @@ +;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*- + +;; Copyright (C) 2012-2018 Free Software Foundation, Inc. + +;; Author: Nicolas Goaziou +;; Keywords: outlines, hypermedia, calendar, wp + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: +;; +;; See for details about +;; Org syntax. +;; +;; Lisp-wise, a syntax object can be represented as a list. +;; It follows the pattern (TYPE PROPERTIES CONTENTS), where: +;; TYPE is a symbol describing the object. +;; PROPERTIES is the property list attached to it. See docstring of +;; appropriate parsing function to get an exhaustive list. +;; CONTENTS is a list of syntax objects or raw strings contained +;; in the current object, when applicable. +;; +;; For the whole document, TYPE is `org-data' and PROPERTIES is nil. +;; +;; The first part of this file defines constants for the Org syntax, +;; while the second one provide accessors and setters functions. +;; +;; The next part implements a parser and an interpreter for each +;; element and object type in Org syntax. +;; +;; The following part creates a fully recursive buffer parser. It +;; also provides a tool to map a function to elements or objects +;; matching some criteria in the parse tree. Functions of interest +;; are `org-element-parse-buffer', `org-element-map' and, to a lesser +;; extent, `org-element-parse-secondary-string'. +;; +;; The penultimate part is the cradle of an interpreter for the +;; obtained parse tree: `org-element-interpret-data'. +;; +;; The library ends by furnishing `org-element-at-point' function, and +;; a way to give information about document structure around point +;; with `org-element-context'. A cache mechanism is also provided for +;; these functions. + + +;;; Code: + +(require 'org) +(require 'avl-tree) +(require 'cl-lib) + + + +;;; Definitions And Rules +;; +;; Define elements, greater elements and specify recursive objects, +;; along with the affiliated keywords recognized. Also set up +;; restrictions on recursive objects combinations. +;; +;; `org-element-update-syntax' builds proper syntax regexps according +;; to current setup. + +(defvar org-element-paragraph-separate nil + "Regexp to separate paragraphs in an Org buffer. +In the case of lines starting with \"#\" and \":\", this regexp +is not sufficient to know if point is at a paragraph ending. See +`org-element-paragraph-parser' for more information.") + +(defvar org-element--object-regexp nil + "Regexp possibly matching the beginning of an object. +This regexp allows false positives. Dedicated parser (e.g., +`org-export-bold-parser') will take care of further filtering. +Radio links are not matched by this regexp, as they are treated +specially in `org-element--object-lex'.") + +(defun org-element--set-regexps () + "Build variable syntax regexps." + (setq org-element-paragraph-separate + (concat "^\\(?:" + ;; Headlines, inlinetasks. + org-outline-regexp "\\|" + ;; Footnote definitions. + "\\[fn:[-_[:word:]]+\\]" "\\|" + ;; Diary sexps. + "%%(" "\\|" + "[ \t]*\\(?:" + ;; Empty lines. + "$" "\\|" + ;; Tables (any type). + "|" "\\|" + "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|" + ;; Comments, keyword-like or block-like constructs. + ;; Blocks and keywords with dual values need to be + ;; double-checked. + "#\\(?: \\|$\\|\\+\\(?:" + "BEGIN_\\S-+" "\\|" + "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)" + "\\|" + ;; Drawers (any type) and fixed-width areas. Drawers + ;; need to be double-checked. + ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|" + ;; Horizontal rules. + "-\\{5,\\}[ \t]*$" "\\|" + ;; LaTeX environments. + "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|" + ;; Clock lines. + (regexp-quote org-clock-string) "\\|" + ;; Lists. + (let ((term (pcase org-plain-list-ordered-item-terminator + (?\) ")") (?. "\\.") (_ "[.)]"))) + (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]"))) + (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)" + "\\(?:[ \t]\\|$\\)")) + "\\)\\)") + org-element--object-regexp + (mapconcat #'identity + (let ((link-types (regexp-opt (org-link-types)))) + (list + ;; Sub/superscript. + "\\(?:[_^][-{(*+.,[:alnum:]]\\)" + ;; Bold, code, italic, strike-through, underline + ;; and verbatim. + (concat "[*~=+_/]" + (format "[^%s]" + (nth 2 org-emphasis-regexp-components))) + ;; Plain links. + (concat "\\<" link-types ":") + ;; Objects starting with "[": regular link, + ;; footnote reference, statistics cookie, + ;; timestamp (inactive). + (concat "\\[\\(?:" + "fn:" "\\|" + "\\[" "\\|" + "[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}" "\\|" + "[0-9]*\\(?:%\\|/[0-9]*\\)\\]" + "\\)") + ;; Objects starting with "@": export snippets. + "@@" + ;; Objects starting with "{": macro. + "{{{" + ;; Objects starting with "<" : timestamp + ;; (active, diary), target, radio target and + ;; angular links. + (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)") + ;; Objects starting with "$": latex fragment. + "\\$" + ;; Objects starting with "\": line break, + ;; entity, latex fragment. + "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)" + ;; Objects starting with raw text: inline Babel + ;; source block, inline Babel call. + "\\(?:call\\|src\\)_")) + "\\|"))) + +(org-element--set-regexps) + +;;;###autoload +(defun org-element-update-syntax () + "Update parser internals." + (interactive) + (org-element--set-regexps) + (org-element-cache-reset 'all)) + +(defconst org-element-all-elements + '(babel-call center-block clock comment comment-block diary-sexp drawer + dynamic-block example-block export-block fixed-width + footnote-definition headline horizontal-rule inlinetask item + keyword latex-environment node-property paragraph plain-list + planning property-drawer quote-block section + special-block src-block table table-row verse-block) + "Complete list of element types.") + +(defconst org-element-greater-elements + '(center-block drawer dynamic-block footnote-definition headline inlinetask + item plain-list property-drawer quote-block section + special-block table) + "List of recursive element types aka Greater Elements.") + +(defconst org-element-all-objects + '(bold code entity export-snippet footnote-reference inline-babel-call + inline-src-block italic line-break latex-fragment link macro + radio-target statistics-cookie strike-through subscript superscript + table-cell target timestamp underline verbatim) + "Complete list of object types.") + +(defconst org-element-recursive-objects + '(bold footnote-reference italic link subscript radio-target strike-through + superscript table-cell underline) + "List of recursive object types.") + +(defconst org-element-object-containers + (append org-element-recursive-objects '(paragraph table-row verse-block)) + "List of object or element types that can directly contain objects.") + +(defconst org-element-affiliated-keywords + '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT" + "RESULTS" "SOURCE" "SRCNAME" "TBLNAME") + "List of affiliated keywords as strings. +By default, all keywords setting attributes (e.g., \"ATTR_LATEX\") +are affiliated keywords and need not to be in this list.") + +(defconst org-element-keyword-translation-alist + '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME") + ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME") + ("RESULT" . "RESULTS") ("HEADERS" . "HEADER")) + "Alist of usual translations for keywords. +The key is the old name and the value the new one. The property +holding their value will be named after the translated name.") + +(defconst org-element-multiple-keywords '("CAPTION" "HEADER") + "List of affiliated keywords that can occur more than once in an element. + +Their value will be consed into a list of strings, which will be +returned as the value of the property. + +This list is checked after translations have been applied. See +`org-element-keyword-translation-alist'. + +By default, all keywords setting attributes (e.g., \"ATTR_LATEX\") +allow multiple occurrences and need not to be in this list.") + +(defconst org-element-parsed-keywords '("CAPTION") + "List of affiliated keywords whose value can be parsed. + +Their value will be stored as a secondary string: a list of +strings and objects. + +This list is checked after translations have been applied. See +`org-element-keyword-translation-alist'.") + +(defconst org-element--parsed-properties-alist + (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k))))) + org-element-parsed-keywords) + "Alist of parsed keywords and associated properties. +This is generated from `org-element-parsed-keywords', which +see.") + +(defconst org-element-dual-keywords '("CAPTION" "RESULTS") + "List of affiliated keywords which can have a secondary value. + +In Org syntax, they can be written with optional square brackets +before the colons. For example, RESULTS keyword can be +associated to a hash value with the following: + + #+RESULTS[hash-string]: some-source + +This list is checked after translations have been applied. See +`org-element-keyword-translation-alist'.") + +(defconst org-element--affiliated-re + (format "[ \t]*#\\+\\(?:%s\\):[ \t]*" + (concat + ;; Dual affiliated keywords. + (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?" + (regexp-opt org-element-dual-keywords)) + "\\|" + ;; Regular affiliated keywords. + (format "\\(?1:%s\\)" + (regexp-opt + (cl-remove-if + (lambda (k) (member k org-element-dual-keywords)) + org-element-affiliated-keywords))) + "\\|" + ;; Export attributes. + "\\(?1:ATTR_[-_A-Za-z0-9]+\\)")) + "Regexp matching any affiliated keyword. + +Keyword name is put in match group 1. Moreover, if keyword +belongs to `org-element-dual-keywords', put the dual value in +match group 2. + +Don't modify it, set `org-element-affiliated-keywords' instead.") + +(defconst org-element-object-restrictions + (let* ((standard-set (remq 'table-cell org-element-all-objects)) + (standard-set-no-line-break (remq 'line-break standard-set))) + `((bold ,@standard-set) + (footnote-reference ,@standard-set) + (headline ,@standard-set-no-line-break) + (inlinetask ,@standard-set-no-line-break) + (italic ,@standard-set) + (item ,@standard-set-no-line-break) + (keyword ,@(remq 'footnote-reference standard-set)) + ;; Ignore all links in a link description. Also ignore + ;; radio-targets and line breaks. + (link bold code entity export-snippet inline-babel-call inline-src-block + italic latex-fragment macro statistics-cookie strike-through + subscript superscript underline verbatim) + (paragraph ,@standard-set) + ;; Remove any variable object from radio target as it would + ;; prevent it from being properly recognized. + (radio-target bold code entity italic latex-fragment strike-through + subscript superscript underline superscript) + (strike-through ,@standard-set) + (subscript ,@standard-set) + (superscript ,@standard-set) + ;; Ignore inline babel call and inline src block as formulas are + ;; possible. Also ignore line breaks and statistics cookies. + (table-cell bold code entity export-snippet footnote-reference italic + latex-fragment link macro radio-target strike-through + subscript superscript target timestamp underline verbatim) + (table-row table-cell) + (underline ,@standard-set) + (verse-block ,@standard-set))) + "Alist of objects restrictions. + +key is an element or object type containing objects and value is +a list of types that can be contained within an element or object +of such type. + +For example, in a `radio-target' object, one can only find +entities, latex-fragments, subscript, superscript and text +markup. + +This alist also applies to secondary string. For example, an +`headline' type element doesn't directly contain objects, but +still has an entry since one of its properties (`:title') does.") + +(defconst org-element-secondary-value-alist + '((headline :title) + (inlinetask :title) + (item :tag)) + "Alist between element types and locations of secondary values.") + +(defconst org-element--pair-round-table + (let ((table (make-syntax-table))) + (modify-syntax-entry ?\( "()" table) + (modify-syntax-entry ?\) ")(" table) + (dolist (char '(?\{ ?\} ?\[ ?\] ?\< ?\>) table) + (modify-syntax-entry char " " table))) + "Table used internally to pair only round brackets. +Other brackets are treated as spaces.") + +(defconst org-element--pair-square-table + (let ((table (make-syntax-table))) + (modify-syntax-entry ?\[ "(]" table) + (modify-syntax-entry ?\] ")[" table) + (dolist (char '(?\{ ?\} ?\( ?\) ?\< ?\>) table) + (modify-syntax-entry char " " table))) + "Table used internally to pair only square brackets. +Other brackets are treated as spaces.") + +(defconst org-element--pair-curly-table + (let ((table (make-syntax-table))) + (modify-syntax-entry ?\{ "(}" table) + (modify-syntax-entry ?\} "){" table) + (dolist (char '(?\[ ?\] ?\( ?\) ?\< ?\>) table) + (modify-syntax-entry char " " table))) + "Table used internally to pair only curly brackets. +Other brackets are treated as spaces.") + +(defun org-element--parse-paired-brackets (char) + "Parse paired brackets at point. +CHAR is the opening bracket to consider, as a character. Return +contents between brackets, as a string, or nil. Also move point +past the brackets." + (when (eq char (char-after)) + (let ((syntax-table (pcase char + (?\{ org-element--pair-curly-table) + (?\[ org-element--pair-square-table) + (?\( org-element--pair-round-table) + (_ nil))) + (pos (point))) + (when syntax-table + (with-syntax-table syntax-table + (let ((end (ignore-errors (scan-lists pos 1 0)))) + (when end + (goto-char end) + (buffer-substring-no-properties (1+ pos) (1- end))))))))) + + +;;; Accessors and Setters +;; +;; Provide four accessors: `org-element-type', `org-element-property' +;; `org-element-contents' and `org-element-restriction'. +;; +;; Setter functions allow modification of elements by side effect. +;; There is `org-element-put-property', `org-element-set-contents'. +;; These low-level functions are useful to build a parse tree. +;; +;; `org-element-adopt-elements', `org-element-set-element', +;; `org-element-extract-element' and `org-element-insert-before' are +;; high-level functions useful to modify a parse tree. +;; +;; `org-element-secondary-p' is a predicate used to know if a given +;; object belongs to a secondary string. `org-element-class' tells if +;; some parsed data is an element or an object, handling pseudo +;; elements and objects. `org-element-copy' returns an element or +;; object, stripping its parent property in the process. + +(defsubst org-element-type (element) + "Return type of ELEMENT. + +The function returns the type of the element or object provided. +It can also return the following special value: + `plain-text' for a string + `org-data' for a complete document + nil in any other case." + (cond + ((not (consp element)) (and (stringp element) 'plain-text)) + ((symbolp (car element)) (car element)))) + +(defsubst org-element-property (property element) + "Extract the value from the PROPERTY of an ELEMENT." + (if (stringp element) (get-text-property 0 property element) + (plist-get (nth 1 element) property))) + +(defsubst org-element-contents (element) + "Extract contents from an ELEMENT." + (cond ((not (consp element)) nil) + ((symbolp (car element)) (nthcdr 2 element)) + (t element))) + +(defsubst org-element-restriction (element) + "Return restriction associated to ELEMENT. +ELEMENT can be an element, an object or a symbol representing an +element or object type." + (cdr (assq (if (symbolp element) element (org-element-type element)) + org-element-object-restrictions))) + +(defsubst org-element-put-property (element property value) + "In ELEMENT set PROPERTY to VALUE. +Return modified element." + (if (stringp element) (org-add-props element nil property value) + (setcar (cdr element) (plist-put (nth 1 element) property value)) + element)) + +(defsubst org-element-set-contents (element &rest contents) + "Set ELEMENT's contents to CONTENTS. +Return ELEMENT." + (cond ((null element) contents) + ((not (symbolp (car element))) contents) + ((cdr element) (setcdr (cdr element) contents) element) + (t (nconc element contents)))) + +(defun org-element-secondary-p (object) + "Non-nil when OBJECT directly belongs to a secondary string. +Return value is the property name, as a keyword, or nil." + (let* ((parent (org-element-property :parent object)) + (properties (cdr (assq (org-element-type parent) + org-element-secondary-value-alist)))) + (catch 'exit + (dolist (p properties) + (and (memq object (org-element-property p parent)) + (throw 'exit p)))))) + +(defsubst org-element-class (datum &optional parent) + "Return class for ELEMENT, as a symbol. +Class is either `element' or `object'. Optional argument PARENT +is the element or object containing DATUM. It defaults to the +value of DATUM `:parent' property." + (let ((type (org-element-type datum)) + (parent (or parent (org-element-property :parent datum)))) + (cond + ;; Trivial cases. + ((memq type org-element-all-objects) 'object) + ((memq type org-element-all-elements) 'element) + ;; Special cases. + ((eq type 'org-data) 'element) + ((eq type 'plain-text) 'object) + ((not type) 'object) + ;; Pseudo object or elements. Make a guess about its class. + ;; Basically a pseudo object is contained within another object, + ;; a secondary string or a container element. + ((not parent) 'element) + (t + (let ((parent-type (org-element-type parent))) + (cond ((not parent-type) 'object) + ((memq parent-type org-element-object-containers) 'object) + ((org-element-secondary-p datum) 'object) + (t 'element))))))) + +(defsubst org-element-adopt-elements (parent &rest children) + "Append elements to the contents of another element. + +PARENT is an element or object. CHILDREN can be elements, +objects, or a strings. + +The function takes care of setting `:parent' property for CHILD. +Return parent element." + (if (not children) parent + ;; Link every child to PARENT. If PARENT is nil, it is a secondary + ;; string: parent is the list itself. + (dolist (child children) + (org-element-put-property child :parent (or parent children))) + ;; Add CHILDREN at the end of PARENT contents. + (when parent + (apply #'org-element-set-contents + parent + (nconc (org-element-contents parent) children))) + ;; Return modified PARENT element. + (or parent children))) + +(defun org-element-extract-element (element) + "Extract ELEMENT from parse tree. +Remove element from the parse tree by side-effect, and return it +with its `:parent' property stripped out." + (let ((parent (org-element-property :parent element)) + (secondary (org-element-secondary-p element))) + (if secondary + (org-element-put-property + parent secondary + (delq element (org-element-property secondary parent))) + (apply #'org-element-set-contents + parent + (delq element (org-element-contents parent)))) + ;; Return ELEMENT with its :parent removed. + (org-element-put-property element :parent nil))) + +(defun org-element-insert-before (element location) + "Insert ELEMENT before LOCATION in parse tree. +LOCATION is an element, object or string within the parse tree. +Parse tree is modified by side effect." + (let* ((parent (org-element-property :parent location)) + (property (org-element-secondary-p location)) + (siblings (if property (org-element-property property parent) + (org-element-contents parent))) + ;; Special case: LOCATION is the first element of an + ;; independent secondary string (e.g. :title property). Add + ;; ELEMENT in-place. + (specialp (and (not property) + (eq siblings parent) + (eq (car parent) location)))) + ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS. + (cond (specialp) + ((or (null siblings) (eq (car siblings) location)) + (push element siblings)) + ((null location) (nconc siblings (list element))) + (t + (let ((index (cl-position location siblings))) + (unless index (error "No location found to insert element")) + (push element (cdr (nthcdr (1- index) siblings)))))) + ;; Store SIBLINGS at appropriate place in parse tree. + (cond + (specialp (setcdr parent (copy-sequence parent)) (setcar parent element)) + (property (org-element-put-property parent property siblings)) + (t (apply #'org-element-set-contents parent siblings))) + ;; Set appropriate :parent property. + (org-element-put-property element :parent parent))) + +(defun org-element-set-element (old new) + "Replace element or object OLD with element or object NEW. +The function takes care of setting `:parent' property for NEW." + ;; Ensure OLD and NEW have the same parent. + (org-element-put-property new :parent (org-element-property :parent old)) + (if (or (memq (org-element-type old) '(plain-text nil)) + (memq (org-element-type new) '(plain-text nil))) + ;; We cannot replace OLD with NEW since one of them is not an + ;; object or element. We take the long path. + (progn (org-element-insert-before new old) + (org-element-extract-element old)) + ;; Since OLD is going to be changed into NEW by side-effect, first + ;; make sure that every element or object within NEW has OLD as + ;; parent. + (dolist (blob (org-element-contents new)) + (org-element-put-property blob :parent old)) + ;; Transfer contents. + (apply #'org-element-set-contents old (org-element-contents new)) + ;; Overwrite OLD's properties with NEW's. + (setcar (cdr old) (nth 1 new)) + ;; Transfer type. + (setcar old (car new)))) + +(defun org-element-create (type &optional props &rest children) + "Create a new element of type TYPE. +Optional argument PROPS, when non-nil, is a plist defining the +properties of the element. CHILDREN can be elements, objects or +strings." + (apply #'org-element-adopt-elements (list type props) children)) + +(defun org-element-copy (datum) + "Return a copy of DATUM. +DATUM is an element, object, string or nil. `:parent' property +is cleared and contents are removed in the process." + (when datum + (let ((type (org-element-type datum))) + (pcase type + (`org-data (list 'org-data nil)) + (`plain-text (substring-no-properties datum)) + (`nil (copy-sequence datum)) + (_ + (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil))))))) + + + +;;; Greater elements +;; +;; For each greater element type, we define a parser and an +;; interpreter. +;; +;; A parser returns the element or object as the list described above. +;; Most of them accepts no argument. Though, exceptions exist. Hence +;; every element containing a secondary string (see +;; `org-element-secondary-value-alist') will accept an optional +;; argument to toggle parsing of these secondary strings. Moreover, +;; `item' parser requires current list's structure as its first +;; element. +;; +;; An interpreter accepts two arguments: the list representation of +;; the element or object, and its contents. The latter may be nil, +;; depending on the element or object considered. It returns the +;; appropriate Org syntax, as a string. +;; +;; Parsing functions must follow the naming convention: +;; org-element-TYPE-parser, where TYPE is greater element's type, as +;; defined in `org-element-greater-elements'. +;; +;; Similarly, interpreting functions must follow the naming +;; convention: org-element-TYPE-interpreter. +;; +;; With the exception of `headline' and `item' types, greater elements +;; cannot contain other greater elements of their own type. +;; +;; Beside implementing a parser and an interpreter, adding a new +;; greater element requires tweaking `org-element--current-element'. +;; Moreover, the newly defined type must be added to both +;; `org-element-all-elements' and `org-element-greater-elements'. + + +;;;; Center Block + +(defun org-element-center-block-parser (limit affiliated) + "Parse a center block. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `center-block' and CDR is a plist +containing `:begin', `:end', `:contents-begin', `:contents-end', +`:post-blank' and `:post-affiliated' keywords. + +Assume point is at the beginning of the block." + (let ((case-fold-search t)) + (if (not (save-excursion + (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t))) + ;; Incomplete block: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (let ((block-end-line (match-beginning 0))) + (let* ((begin (car affiliated)) + (post-affiliated (point)) + ;; Empty blocks have no contents. + (contents-begin (progn (forward-line) + (and (< (point) block-end-line) + (point)))) + (contents-end (and contents-begin block-end-line)) + (pos-before-blank (progn (goto-char block-end-line) + (forward-line) + (point))) + (end (save-excursion + (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'center-block + (nconc + (list :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated)))))))) + +(defun org-element-center-block-interpreter (_ contents) + "Interpret a center-block element as Org syntax. +CONTENTS is the contents of the element." + (format "#+BEGIN_CENTER\n%s#+END_CENTER" contents)) + + +;;;; Drawer + +(defun org-element-drawer-parser (limit affiliated) + "Parse a drawer. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `drawer' and CDR is a plist containing +`:drawer-name', `:begin', `:end', `:contents-begin', +`:contents-end', `:post-blank' and `:post-affiliated' keywords. + +Assume point is at beginning of drawer." + (let ((case-fold-search t)) + (if (not (save-excursion (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))) + ;; Incomplete drawer: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (save-excursion + (let* ((drawer-end-line (match-beginning 0)) + (name (progn (looking-at org-drawer-regexp) + (match-string-no-properties 1))) + (begin (car affiliated)) + (post-affiliated (point)) + ;; Empty drawers have no contents. + (contents-begin (progn (forward-line) + (and (< (point) drawer-end-line) + (point)))) + (contents-end (and contents-begin drawer-end-line)) + (pos-before-blank (progn (goto-char drawer-end-line) + (forward-line) + (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'drawer + (nconc + (list :begin begin + :end end + :drawer-name name + :contents-begin contents-begin + :contents-end contents-end + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated)))))))) + +(defun org-element-drawer-interpreter (drawer contents) + "Interpret DRAWER element as Org syntax. +CONTENTS is the contents of the element." + (format ":%s:\n%s:END:" + (org-element-property :drawer-name drawer) + contents)) + + +;;;; Dynamic Block + +(defun org-element-dynamic-block-parser (limit affiliated) + "Parse a dynamic block. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `dynamic-block' and CDR is a plist +containing `:block-name', `:begin', `:end', `:contents-begin', +`:contents-end', `:arguments', `:post-blank' and +`:post-affiliated' keywords. + +Assume point is at beginning of dynamic block." + (let ((case-fold-search t)) + (if (not (save-excursion + (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t))) + ;; Incomplete block: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (let ((block-end-line (match-beginning 0))) + (save-excursion + (let* ((name (progn (looking-at org-dblock-start-re) + (match-string-no-properties 1))) + (arguments (match-string-no-properties 3)) + (begin (car affiliated)) + (post-affiliated (point)) + ;; Empty blocks have no contents. + (contents-begin (progn (forward-line) + (and (< (point) block-end-line) + (point)))) + (contents-end (and contents-begin block-end-line)) + (pos-before-blank (progn (goto-char block-end-line) + (forward-line) + (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'dynamic-block + (nconc + (list :begin begin + :end end + :block-name name + :arguments arguments + :contents-begin contents-begin + :contents-end contents-end + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated))))))))) + +(defun org-element-dynamic-block-interpreter (dynamic-block contents) + "Interpret DYNAMIC-BLOCK element as Org syntax. +CONTENTS is the contents of the element." + (format "#+BEGIN: %s%s\n%s#+END:" + (org-element-property :block-name dynamic-block) + (let ((args (org-element-property :arguments dynamic-block))) + (if args (concat " " args) "")) + contents)) + + +;;;; Footnote Definition + +(defconst org-element--footnote-separator + (concat org-outline-regexp-bol "\\|" + org-footnote-definition-re "\\|" + "^\\([ \t]*\n\\)\\{2,\\}") + "Regexp used as a footnote definition separator.") + +(defun org-element-footnote-definition-parser (limit affiliated) + "Parse a footnote definition. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `footnote-definition' and CDR is +a plist containing `:label', `:begin' `:end', `:contents-begin', +`:contents-end', `:post-blank' and `:post-affiliated' keywords. + +Assume point is at the beginning of the footnote definition." + (save-excursion + (let* ((label (progn (looking-at org-footnote-definition-re) + (match-string-no-properties 1))) + (begin (car affiliated)) + (post-affiliated (point)) + (end + (save-excursion + (end-of-line) + (cond + ((not + (re-search-forward org-element--footnote-separator limit t)) + limit) + ((eq ?\[ (char-after (match-beginning 0))) + ;; At a new footnote definition, make sure we end + ;; before any affiliated keyword above. + (forward-line -1) + (while (and (> (point) post-affiliated) + (looking-at-p org-element--affiliated-re)) + (forward-line -1)) + (line-beginning-position 2)) + ((eq ?* (char-after (match-beginning 0))) (match-beginning 0)) + (t (skip-chars-forward " \r\t\n" limit) + (if (= limit (point)) limit (line-beginning-position)))))) + (contents-begin + (progn (search-forward "]") + (skip-chars-forward " \r\t\n" end) + (cond ((= (point) end) nil) + ((= (line-beginning-position) post-affiliated) (point)) + (t (line-beginning-position))))) + (contents-end + (progn (goto-char end) + (skip-chars-backward " \r\t\n") + (line-beginning-position 2)))) + (list 'footnote-definition + (nconc + (list :label label + :begin begin + :end end + :contents-begin contents-begin + :contents-end (and contents-begin contents-end) + :post-blank (count-lines contents-end end) + :post-affiliated post-affiliated) + (cdr affiliated)))))) + +(defun org-element-footnote-definition-interpreter (footnote-definition contents) + "Interpret FOOTNOTE-DEFINITION element as Org syntax. +CONTENTS is the contents of the footnote-definition." + (concat (format "[fn:%s]" (org-element-property :label footnote-definition)) + " " + contents)) + + +;;;; Headline + +(defun org-element--get-node-properties () + "Return node properties associated to headline at point. +Upcase property names. It avoids confusion between properties +obtained through property drawer and default properties from the +parser (e.g. `:end' and :END:). Return value is a plist." + (save-excursion + (forward-line) + (when (looking-at-p org-planning-line-re) (forward-line)) + (when (looking-at org-property-drawer-re) + (forward-line) + (let ((end (match-end 0)) properties) + (while (< (line-end-position) end) + (looking-at org-property-re) + (push (match-string-no-properties 3) properties) + (push (intern (concat ":" (upcase (match-string 2)))) properties) + (forward-line)) + properties)))) + +(defun org-element--get-time-properties () + "Return time properties associated to headline at point. +Return value is a plist." + (save-excursion + (when (progn (forward-line) (looking-at org-planning-line-re)) + (let ((end (line-end-position)) plist) + (while (re-search-forward org-keyword-time-not-clock-regexp end t) + (goto-char (match-end 1)) + (skip-chars-forward " \t") + (let ((keyword (match-string 1)) + (time (org-element-timestamp-parser))) + (cond ((equal keyword org-scheduled-string) + (setq plist (plist-put plist :scheduled time))) + ((equal keyword org-deadline-string) + (setq plist (plist-put plist :deadline time))) + (t (setq plist (plist-put plist :closed time)))))) + plist)))) + +(defun org-element-headline-parser (limit &optional raw-secondary-p) + "Parse a headline. + +Return a list whose CAR is `headline' and CDR is a plist +containing `:raw-value', `:title', `:begin', `:end', +`:pre-blank', `:contents-begin' and `:contents-end', `:level', +`:priority', `:tags', `:todo-keyword',`:todo-type', `:scheduled', +`:deadline', `:closed', `:archivedp', `:commentedp' +`:footnote-section-p', `:post-blank' and `:post-affiliated' +keywords. + +The plist also contains any property set in the property drawer, +with its name in upper cases and colons added at the +beginning (e.g., `:CUSTOM_ID'). + +LIMIT is a buffer position bounding the search. + +When RAW-SECONDARY-P is non-nil, headline's title will not be +parsed as a secondary string, but as a plain string instead. + +Assume point is at beginning of the headline." + (save-excursion + (let* ((begin (point)) + (level (prog1 (org-reduced-level (skip-chars-forward "*")) + (skip-chars-forward " \t"))) + (todo (and org-todo-regexp + (let (case-fold-search) (looking-at (concat org-todo-regexp " "))) + (progn (goto-char (match-end 0)) + (skip-chars-forward " \t") + (match-string 1)))) + (todo-type + (and todo (if (member todo org-done-keywords) 'done 'todo))) + (priority (and (looking-at "\\[#.\\][ \t]*") + (progn (goto-char (match-end 0)) + (aref (match-string 0) 2)))) + (commentedp + (and (let (case-fold-search) (looking-at org-comment-string)) + (goto-char (match-end 0)))) + (title-start (point)) + (tags (when (re-search-forward + "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" + (line-end-position) + 'move) + (goto-char (match-beginning 0)) + (org-split-string (match-string 1) ":"))) + (title-end (point)) + (raw-value (org-trim + (buffer-substring-no-properties title-start title-end))) + (archivedp (member org-archive-tag tags)) + (footnote-section-p (and org-footnote-section + (string= org-footnote-section raw-value))) + (standard-props (org-element--get-node-properties)) + (time-props (org-element--get-time-properties)) + (end (min (save-excursion (org-end-of-subtree t t)) limit)) + (contents-begin (save-excursion + (forward-line) + (skip-chars-forward " \r\t\n" end) + (and (/= (point) end) (line-beginning-position)))) + (contents-end (and contents-begin + (progn (goto-char end) + (skip-chars-backward " \r\t\n") + (line-beginning-position 2))))) + (let ((headline + (list 'headline + (nconc + (list :raw-value raw-value + :begin begin + :end end + :pre-blank + (if (not contents-begin) 0 + (1- (count-lines begin contents-begin))) + :contents-begin contents-begin + :contents-end contents-end + :level level + :priority priority + :tags tags + :todo-keyword todo + :todo-type todo-type + :post-blank + (if contents-end + (count-lines contents-end end) + (1- (count-lines begin end))) + :footnote-section-p footnote-section-p + :archivedp archivedp + :commentedp commentedp + :post-affiliated begin) + time-props + standard-props)))) + (org-element-put-property + headline :title + (if raw-secondary-p raw-value + (org-element--parse-objects + (progn (goto-char title-start) + (skip-chars-forward " \t") + (point)) + (progn (goto-char title-end) + (skip-chars-backward " \t") + (point)) + nil + (org-element-restriction 'headline) + headline))))))) + +(defun org-element-headline-interpreter (headline contents) + "Interpret HEADLINE element as Org syntax. +CONTENTS is the contents of the element." + (let* ((level (org-element-property :level headline)) + (todo (org-element-property :todo-keyword headline)) + (priority (org-element-property :priority headline)) + (title (org-element-interpret-data + (org-element-property :title headline))) + (tags (let ((tag-list (org-element-property :tags headline))) + (and tag-list + (format ":%s:" (mapconcat #'identity tag-list ":"))))) + (commentedp (org-element-property :commentedp headline)) + (pre-blank (or (org-element-property :pre-blank headline) 0)) + (heading + (concat (make-string (if org-odd-levels-only (1- (* level 2)) level) + ?*) + (and todo (concat " " todo)) + (and commentedp (concat " " org-comment-string)) + (and priority (format " [#%c]" priority)) + " " + (if (and org-footnote-section + (org-element-property :footnote-section-p headline)) + org-footnote-section + title)))) + (concat + heading + ;; Align tags. + (when tags + (cond + ((zerop org-tags-column) (format " %s" tags)) + ((< org-tags-column 0) + (concat + (make-string + (max (- (+ org-tags-column (length heading) (length tags))) 1) + ?\s) + tags)) + (t + (concat + (make-string (max (- org-tags-column (length heading)) 1) ?\s) + tags)))) + (make-string (1+ pre-blank) ?\n) + contents))) + + +;;;; Inlinetask + +(defun org-element-inlinetask-parser (limit &optional raw-secondary-p) + "Parse an inline task. + +Return a list whose CAR is `inlinetask' and CDR is a plist +containing `:title', `:begin', `:end', `:pre-blank', +`:contents-begin' and `:contents-end', `:level', `:priority', +`:raw-value', `:tags', `:todo-keyword', `:todo-type', +`:scheduled', `:deadline', `:closed', `:post-blank' and +`:post-affiliated' keywords. + +The plist also contains any property set in the property drawer, +with its name in upper cases and colons added at the +beginning (e.g., `:CUSTOM_ID'). + +When optional argument RAW-SECONDARY-P is non-nil, inline-task's +title will not be parsed as a secondary string, but as a plain +string instead. + +Assume point is at beginning of the inline task." + (save-excursion + (let* ((begin (point)) + (level (prog1 (org-reduced-level (skip-chars-forward "*")) + (skip-chars-forward " \t"))) + (todo (and org-todo-regexp + (let (case-fold-search) (looking-at org-todo-regexp)) + (progn (goto-char (match-end 0)) + (skip-chars-forward " \t") + (match-string 0)))) + (todo-type (and todo + (if (member todo org-done-keywords) 'done 'todo))) + (priority (and (looking-at "\\[#.\\][ \t]*") + (progn (goto-char (match-end 0)) + (aref (match-string 0) 2)))) + (title-start (point)) + (tags (when (re-search-forward + "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" + (line-end-position) + 'move) + (goto-char (match-beginning 0)) + (org-split-string (match-string 1) ":"))) + (title-end (point)) + (raw-value (org-trim + (buffer-substring-no-properties title-start title-end))) + (task-end (save-excursion + (end-of-line) + (and (re-search-forward org-outline-regexp-bol limit t) + (looking-at-p "[ \t]*END[ \t]*$") + (line-beginning-position)))) + (standard-props (and task-end (org-element--get-node-properties))) + (time-props (and task-end (org-element--get-time-properties))) + (contents-begin (and task-end + (< (point) task-end) + (progn + (forward-line) + (skip-chars-forward " \t\n") + (line-beginning-position)))) + (contents-end (and contents-begin task-end)) + (end (progn (when task-end (goto-char task-end)) + (forward-line) + (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position)))) + (inlinetask + (list 'inlinetask + (nconc + (list :raw-value raw-value + :begin begin + :end end + :pre-blank + (if (not contents-begin) 0 + (1- (count-lines begin contents-begin))) + :contents-begin contents-begin + :contents-end contents-end + :level level + :priority priority + :tags tags + :todo-keyword todo + :todo-type todo-type + :post-blank (1- (count-lines (or task-end begin) end)) + :post-affiliated begin) + time-props + standard-props)))) + (org-element-put-property + inlinetask :title + (if raw-secondary-p raw-value + (org-element--parse-objects + (progn (goto-char title-start) + (skip-chars-forward " \t") + (point)) + (progn (goto-char title-end) + (skip-chars-backward " \t") + (point)) + nil + (org-element-restriction 'inlinetask) + inlinetask)))))) + +(defun org-element-inlinetask-interpreter (inlinetask contents) + "Interpret INLINETASK element as Org syntax. +CONTENTS is the contents of inlinetask." + (let* ((level (org-element-property :level inlinetask)) + (todo (org-element-property :todo-keyword inlinetask)) + (priority (org-element-property :priority inlinetask)) + (title (org-element-interpret-data + (org-element-property :title inlinetask))) + (tags (let ((tag-list (org-element-property :tags inlinetask))) + (and tag-list + (format ":%s:" (mapconcat 'identity tag-list ":"))))) + (task (concat (make-string level ?*) + (and todo (concat " " todo)) + (and priority (format " [#%c]" priority)) + (and title (concat " " title))))) + (concat task + ;; Align tags. + (when tags + (cond + ((zerop org-tags-column) (format " %s" tags)) + ((< org-tags-column 0) + (concat + (make-string + (max (- (+ org-tags-column (length task) (length tags))) 1) + ? ) + tags)) + (t + (concat + (make-string (max (- org-tags-column (length task)) 1) ? ) + tags)))) + ;; Prefer degenerate inlinetasks when there are no + ;; contents. + (when contents + (concat "\n" + contents + (make-string level ?*) " END"))))) + + +;;;; Item + +(defun org-element-item-parser (_ struct &optional raw-secondary-p) + "Parse an item. + +STRUCT is the structure of the plain list. + +Return a list whose CAR is `item' and CDR is a plist containing +`:bullet', `:begin', `:end', `:contents-begin', `:contents-end', +`:checkbox', `:counter', `:tag', `:structure', `:post-blank' and +`:post-affiliated' keywords. + +When optional argument RAW-SECONDARY-P is non-nil, item's tag, if +any, will not be parsed as a secondary string, but as a plain +string instead. + +Assume point is at the beginning of the item." + (save-excursion + (beginning-of-line) + (looking-at org-list-full-item-re) + (let* ((begin (point)) + (bullet (match-string-no-properties 1)) + (checkbox (let ((box (match-string 3))) + (cond ((equal "[ ]" box) 'off) + ((equal "[X]" box) 'on) + ((equal "[-]" box) 'trans)))) + (counter (let ((c (match-string 2))) + (save-match-data + (cond + ((not c) nil) + ((string-match "[A-Za-z]" c) + (- (string-to-char (upcase (match-string 0 c))) + 64)) + ((string-match "[0-9]+" c) + (string-to-number (match-string 0 c))))))) + (end (progn (goto-char (nth 6 (assq (point) struct))) + (if (bolp) (point) (line-beginning-position 2)))) + (contents-begin + (progn (goto-char + ;; Ignore tags in un-ordered lists: they are just + ;; a part of item's body. + (if (and (match-beginning 4) + (save-match-data (string-match "[.)]" bullet))) + (match-beginning 4) + (match-end 0))) + (skip-chars-forward " \r\t\n" end) + (cond ((= (point) end) nil) + ;; If first line isn't empty, contents really + ;; start at the text after item's meta-data. + ((= (line-beginning-position) begin) (point)) + (t (line-beginning-position))))) + (contents-end (and contents-begin + (progn (goto-char end) + (skip-chars-backward " \r\t\n") + (line-beginning-position 2)))) + (item + (list 'item + (list :bullet bullet + :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :checkbox checkbox + :counter counter + :structure struct + :post-blank (count-lines (or contents-end begin) end) + :post-affiliated begin)))) + (org-element-put-property + item :tag + (let ((raw (org-list-get-tag begin struct))) + (when raw + (if raw-secondary-p raw + (org-element--parse-objects + (match-beginning 4) (match-end 4) nil + (org-element-restriction 'item) + item)))))))) + +(defun org-element-item-interpreter (item contents) + "Interpret ITEM element as Org syntax. +CONTENTS is the contents of the element." + (let* ((bullet (let ((bullet (org-element-property :bullet item))) + (org-list-bullet-string + (cond ((not (string-match "[0-9a-zA-Z]" bullet)) "- ") + ((eq org-plain-list-ordered-item-terminator ?\)) "1)") + (t "1."))))) + (checkbox (org-element-property :checkbox item)) + (counter (org-element-property :counter item)) + (tag (let ((tag (org-element-property :tag item))) + (and tag (org-element-interpret-data tag)))) + ;; Compute indentation. + (ind (make-string (length bullet) 32)) + (item-starts-with-par-p + (eq (org-element-type (car (org-element-contents item))) + 'paragraph))) + ;; Indent contents. + (concat + bullet + (and counter (format "[@%d] " counter)) + (pcase checkbox + (`on "[X] ") + (`off "[ ] ") + (`trans "[-] ") + (_ nil)) + (and tag (format "%s :: " tag)) + (when contents + (let ((contents (replace-regexp-in-string + "\\(^\\)[ \t]*\\S-" ind contents nil nil 1))) + (if item-starts-with-par-p (org-trim contents) + (concat "\n" contents))))))) + + +;;;; Plain List + +(defun org-element--list-struct (limit) + ;; Return structure of list at point. Internal function. See + ;; `org-list-struct' for details. + (let ((case-fold-search t) + (top-ind limit) + (item-re (org-item-re)) + (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ ")) + items struct) + (save-excursion + (catch :exit + (while t + (cond + ;; At limit: end all items. + ((>= (point) limit) + (let ((end (progn (skip-chars-backward " \r\t\n") + (line-beginning-position 2)))) + (dolist (item items) (setcar (nthcdr 6 item) end))) + (throw :exit (sort (nconc items struct) #'car-less-than-car))) + ;; At list end: end all items. + ((looking-at org-list-end-re) + (dolist (item items) (setcar (nthcdr 6 item) (point))) + (throw :exit (sort (nconc items struct) #'car-less-than-car))) + ;; At a new item: end previous sibling. + ((looking-at item-re) + (let ((ind (save-excursion (skip-chars-forward " \t") + (current-column)))) + (setq top-ind (min top-ind ind)) + (while (and items (<= ind (nth 1 (car items)))) + (let ((item (pop items))) + (setcar (nthcdr 6 item) (point)) + (push item struct))) + (push (progn (looking-at org-list-full-item-re) + (let ((bullet (match-string-no-properties 1))) + (list (point) + ind + bullet + (match-string-no-properties 2) ; counter + (match-string-no-properties 3) ; checkbox + ;; Description tag. + (and (save-match-data + (string-match "[-+*]" bullet)) + (match-string-no-properties 4)) + ;; Ending position, unknown so far. + nil))) + items)) + (forward-line)) + ;; Skip empty lines. + ((looking-at "^[ \t]*$") (forward-line)) + ;; Skip inline tasks and blank lines along the way. + ((and inlinetask-re (looking-at inlinetask-re)) + (forward-line) + (let ((origin (point))) + (when (re-search-forward inlinetask-re limit t) + (if (looking-at-p "END[ \t]*$") (forward-line) + (goto-char origin))))) + ;; At some text line. Check if it ends any previous item. + (t + (let ((ind (save-excursion + (skip-chars-forward " \t") + (current-column))) + (end (save-excursion + (skip-chars-backward " \r\t\n") + (line-beginning-position 2)))) + (while (<= ind (nth 1 (car items))) + (let ((item (pop items))) + (setcar (nthcdr 6 item) end) + (push item struct) + (unless items + (throw :exit (sort struct #'car-less-than-car)))))) + ;; Skip blocks (any type) and drawers contents. + (cond + ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)") + (re-search-forward + (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1)) + limit t))) + ((and (looking-at org-drawer-regexp) + (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))) + (forward-line)))))))) + +(defun org-element-plain-list-parser (limit affiliated structure) + "Parse a plain list. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. STRUCTURE is the structure of the plain list being +parsed. + +Return a list whose CAR is `plain-list' and CDR is a plist +containing `:type', `:begin', `:end', `:contents-begin' and +`:contents-end', `:structure', `:post-blank' and +`:post-affiliated' keywords. + +Assume point is at the beginning of the list." + (save-excursion + (let* ((struct (or structure (org-element--list-struct limit))) + (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered) + ((nth 5 (assq (point) struct)) 'descriptive) + (t 'unordered))) + (contents-begin (point)) + (begin (car affiliated)) + (contents-end (let* ((item (assq contents-begin struct)) + (ind (nth 1 item)) + (pos (nth 6 item))) + (while (and (setq item (assq pos struct)) + (= (nth 1 item) ind)) + (setq pos (nth 6 item))) + pos)) + (end (progn (goto-char contents-end) + (skip-chars-forward " \r\t\n" limit) + (if (= (point) limit) limit (line-beginning-position))))) + ;; Return value. + (list 'plain-list + (nconc + (list :type type + :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :structure struct + :post-blank (count-lines contents-end end) + :post-affiliated contents-begin) + (cdr affiliated)))))) + +(defun org-element-plain-list-interpreter (_ contents) + "Interpret plain-list element as Org syntax. +CONTENTS is the contents of the element." + (with-temp-buffer + (insert contents) + (goto-char (point-min)) + (org-list-repair) + (buffer-string))) + + +;;;; Property Drawer + +(defun org-element-property-drawer-parser (limit) + "Parse a property drawer. + +LIMIT bounds the search. + +Return a list whose car is `property-drawer' and cdr is a plist +containing `:begin', `:end', `:contents-begin', `:contents-end', +`:post-blank' and `:post-affiliated' keywords. + +Assume point is at the beginning of the property drawer." + (save-excursion + (let ((case-fold-search t) + (begin (point)) + (contents-begin (line-beginning-position 2))) + (re-search-forward "^[ \t]*:END:[ \t]*$" limit t) + (let ((contents-end (and (> (match-beginning 0) contents-begin) + (match-beginning 0))) + (before-blank (progn (forward-line) (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'property-drawer + (list :begin begin + :end end + :contents-begin (and contents-end contents-begin) + :contents-end contents-end + :post-blank (count-lines before-blank end) + :post-affiliated begin)))))) + +(defun org-element-property-drawer-interpreter (_ contents) + "Interpret property-drawer element as Org syntax. +CONTENTS is the properties within the drawer." + (format ":PROPERTIES:\n%s:END:" contents)) + + +;;;; Quote Block + +(defun org-element-quote-block-parser (limit affiliated) + "Parse a quote block. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `quote-block' and CDR is a plist +containing `:begin', `:end', `:contents-begin', `:contents-end', +`:post-blank' and `:post-affiliated' keywords. + +Assume point is at the beginning of the block." + (let ((case-fold-search t)) + (if (not (save-excursion + (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t))) + ;; Incomplete block: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (let ((block-end-line (match-beginning 0))) + (save-excursion + (let* ((begin (car affiliated)) + (post-affiliated (point)) + ;; Empty blocks have no contents. + (contents-begin (progn (forward-line) + (and (< (point) block-end-line) + (point)))) + (contents-end (and contents-begin block-end-line)) + (pos-before-blank (progn (goto-char block-end-line) + (forward-line) + (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'quote-block + (nconc + (list :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated))))))))) + +(defun org-element-quote-block-interpreter (_ contents) + "Interpret quote-block element as Org syntax. +CONTENTS is the contents of the element." + (format "#+BEGIN_QUOTE\n%s#+END_QUOTE" contents)) + + +;;;; Section + +(defun org-element-section-parser (_) + "Parse a section. + +Return a list whose CAR is `section' and CDR is a plist +containing `:begin', `:end', `:contents-begin', `contents-end', +`:post-blank' and `:post-affiliated' keywords." + (save-excursion + ;; Beginning of section is the beginning of the first non-blank + ;; line after previous headline. + (let ((begin (point)) + (end (progn (org-with-limited-levels (outline-next-heading)) + (point))) + (pos-before-blank (progn (skip-chars-backward " \r\t\n") + (line-beginning-position 2)))) + (list 'section + (list :begin begin + :end end + :contents-begin begin + :contents-end pos-before-blank + :post-blank (count-lines pos-before-blank end) + :post-affiliated begin))))) + +(defun org-element-section-interpreter (_ contents) + "Interpret section element as Org syntax. +CONTENTS is the contents of the element." + contents) + + +;;;; Special Block + +(defun org-element-special-block-parser (limit affiliated) + "Parse a special block. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `special-block' and CDR is a plist +containing `:type', `:begin', `:end', `:contents-begin', +`:contents-end', `:post-blank' and `:post-affiliated' keywords. + +Assume point is at the beginning of the block." + (let* ((case-fold-search t) + (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)") + (match-string-no-properties 1)))) + (if (not (save-excursion + (re-search-forward + (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type)) + limit t))) + ;; Incomplete block: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (let ((block-end-line (match-beginning 0))) + (save-excursion + (let* ((begin (car affiliated)) + (post-affiliated (point)) + ;; Empty blocks have no contents. + (contents-begin (progn (forward-line) + (and (< (point) block-end-line) + (point)))) + (contents-end (and contents-begin block-end-line)) + (pos-before-blank (progn (goto-char block-end-line) + (forward-line) + (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'special-block + (nconc + (list :type type + :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated))))))))) + +(defun org-element-special-block-interpreter (special-block contents) + "Interpret SPECIAL-BLOCK element as Org syntax. +CONTENTS is the contents of the element." + (let ((block-type (org-element-property :type special-block))) + (format "#+BEGIN_%s\n%s#+END_%s" block-type contents block-type))) + + + +;;; Elements +;; +;; For each element, a parser and an interpreter are also defined. +;; Both follow the same naming convention used for greater elements. +;; +;; Also, as for greater elements, adding a new element type is done +;; through the following steps: implement a parser and an interpreter, +;; tweak `org-element--current-element' so that it recognizes the new +;; type and add that new type to `org-element-all-elements'. + + +;;;; Babel Call + +(defun org-element-babel-call-parser (limit affiliated) + "Parse a babel call. + +LIMIT bounds the search. AFFILIATED is a list of which car is +the buffer position at the beginning of the first affiliated +keyword and cdr is a plist of affiliated keywords along with +their value. + +Return a list whose car is `babel-call' and cdr is a plist +containing `:call', `:inside-header', `:arguments', +`:end-header', `:begin', `:end', `:value', `:post-blank' and +`:post-affiliated' as keywords." + (save-excursion + (let* ((begin (car affiliated)) + (post-affiliated (point)) + (before-blank (line-beginning-position 2)) + (value (progn (search-forward ":" before-blank t) + (skip-chars-forward " \t") + (org-trim + (buffer-substring-no-properties + (point) (line-end-position))))) + (call + (or (org-string-nw-p + (buffer-substring-no-properties + (point) (progn (skip-chars-forward "^[]()" before-blank) + (point)))))) + (inside-header (org-element--parse-paired-brackets ?\[)) + (arguments (org-string-nw-p + (org-element--parse-paired-brackets ?\())) + (end-header + (org-string-nw-p + (org-trim + (buffer-substring-no-properties (point) (line-end-position))))) + (end (progn (forward-line) + (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'babel-call + (nconc + (list :call call + :inside-header inside-header + :arguments arguments + :end-header end-header + :begin begin + :end end + :value value + :post-blank (count-lines before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated)))))) + +(defun org-element-babel-call-interpreter (babel-call _) + "Interpret BABEL-CALL element as Org syntax." + (concat "#+CALL: " + (org-element-property :call babel-call) + (let ((h (org-element-property :inside-header babel-call))) + (and h (format "[%s]" h))) + (concat "(" (org-element-property :arguments babel-call) ")") + (let ((h (org-element-property :end-header babel-call))) + (and h (concat " " h))))) + + +;;;; Clock + +(defun org-element-clock-parser (limit) + "Parse a clock. + +LIMIT bounds the search. + +Return a list whose CAR is `clock' and CDR is a plist containing +`:status', `:value', `:time', `:begin', `:end', `:post-blank' and +`:post-affiliated' as keywords." + (save-excursion + (let* ((case-fold-search nil) + (begin (point)) + (value (progn (search-forward org-clock-string (line-end-position) t) + (skip-chars-forward " \t") + (org-element-timestamp-parser))) + (duration (and (search-forward " => " (line-end-position) t) + (progn (skip-chars-forward " \t") + (looking-at "\\(\\S-+\\)[ \t]*$")) + (match-string-no-properties 1))) + (status (if duration 'closed 'running)) + (post-blank (let ((before-blank (progn (forward-line) (point)))) + (skip-chars-forward " \r\t\n" limit) + (skip-chars-backward " \t") + (unless (bolp) (end-of-line)) + (count-lines before-blank (point)))) + (end (point))) + (list 'clock + (list :status status + :value value + :duration duration + :begin begin + :end end + :post-blank post-blank + :post-affiliated begin))))) + +(defun org-element-clock-interpreter (clock _) + "Interpret CLOCK element as Org syntax." + (concat org-clock-string " " + (org-element-timestamp-interpreter + (org-element-property :value clock) nil) + (let ((duration (org-element-property :duration clock))) + (and duration + (concat " => " + (apply 'format + "%2s:%02s" + (org-split-string duration ":"))))))) + + +;;;; Comment + +(defun org-element-comment-parser (limit affiliated) + "Parse a comment. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `comment' and CDR is a plist +containing `:begin', `:end', `:value', `:post-blank', +`:post-affiliated' keywords. + +Assume point is at comment beginning." + (save-excursion + (let* ((begin (car affiliated)) + (post-affiliated (point)) + (value (prog2 (looking-at "[ \t]*# ?") + (buffer-substring-no-properties + (match-end 0) (line-end-position)) + (forward-line))) + (com-end + ;; Get comments ending. + (progn + (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)")) + ;; Accumulate lines without leading hash and first + ;; whitespace. + (setq value + (concat value + "\n" + (buffer-substring-no-properties + (match-end 0) (line-end-position)))) + (forward-line)) + (point))) + (end (progn (goto-char com-end) + (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'comment + (nconc + (list :begin begin + :end end + :value value + :post-blank (count-lines com-end end) + :post-affiliated post-affiliated) + (cdr affiliated)))))) + +(defun org-element-comment-interpreter (comment _) + "Interpret COMMENT element as Org syntax. +CONTENTS is nil." + (replace-regexp-in-string "^" "# " (org-element-property :value comment))) + + +;;;; Comment Block + +(defun org-element-comment-block-parser (limit affiliated) + "Parse an export block. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `comment-block' and CDR is a plist +containing `:begin', `:end', `:value', `:post-blank' and +`:post-affiliated' keywords. + +Assume point is at comment block beginning." + (let ((case-fold-search t)) + (if (not (save-excursion + (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t))) + ;; Incomplete block: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (let ((contents-end (match-beginning 0))) + (save-excursion + (let* ((begin (car affiliated)) + (post-affiliated (point)) + (contents-begin (progn (forward-line) (point))) + (pos-before-blank (progn (goto-char contents-end) + (forward-line) + (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position)))) + (value (buffer-substring-no-properties + contents-begin contents-end))) + (list 'comment-block + (nconc + (list :begin begin + :end end + :value value + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated))))))))) + +(defun org-element-comment-block-interpreter (comment-block _) + "Interpret COMMENT-BLOCK element as Org syntax." + (format "#+BEGIN_COMMENT\n%s#+END_COMMENT" + (org-element-normalize-string + (org-remove-indentation + (org-element-property :value comment-block))))) + + +;;;; Diary Sexp + +(defun org-element-diary-sexp-parser (limit affiliated) + "Parse a diary sexp. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `diary-sexp' and CDR is a plist +containing `:begin', `:end', `:value', `:post-blank' and +`:post-affiliated' keywords." + (save-excursion + (let ((begin (car affiliated)) + (post-affiliated (point)) + (value (progn (looking-at "\\(%%(.*\\)[ \t]*$") + (match-string-no-properties 1))) + (pos-before-blank (progn (forward-line) (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'diary-sexp + (nconc + (list :value value + :begin begin + :end end + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated)))))) + +(defun org-element-diary-sexp-interpreter (diary-sexp _) + "Interpret DIARY-SEXP as Org syntax." + (org-element-property :value diary-sexp)) + + +;;;; Example Block + +(defun org-element-example-block-parser (limit affiliated) + "Parse an example block. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `example-block' and CDR is a plist +containing `:begin', `:end', `:number-lines', `:preserve-indent', +`:retain-labels', `:use-labels', `:label-fmt', `:switches', +`:value', `:post-blank' and `:post-affiliated' keywords." + (let ((case-fold-search t)) + (if (not (save-excursion + (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t))) + ;; Incomplete block: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (let ((contents-end (match-beginning 0))) + (save-excursion + (let* ((switches + (progn + (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?") + (match-string-no-properties 1))) + ;; Switches analysis. + (number-lines + (and switches + (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>" + switches) + (cons + (if (equal (match-string 1 switches) "-") + 'new + 'continued) + (if (not (match-end 2)) 0 + ;; Subtract 1 to give number of lines before + ;; first line. + (1- (string-to-number (match-string 2 switches))))))) + (preserve-indent + (and switches (string-match "-i\\>" switches))) + ;; Should labels be retained in (or stripped from) example + ;; blocks? + (retain-labels + (or (not switches) + (not (string-match "-r\\>" switches)) + (and number-lines (string-match "-k\\>" switches)))) + ;; What should code-references use - labels or + ;; line-numbers? + (use-labels + (or (not switches) + (and retain-labels + (not (string-match "-k\\>" switches))))) + (label-fmt + (and switches + (string-match "-l +\"\\([^\"\n]+\\)\"" switches) + (match-string 1 switches))) + ;; Standard block parsing. + (begin (car affiliated)) + (post-affiliated (point)) + (contents-begin (line-beginning-position 2)) + (value (org-unescape-code-in-string + (buffer-substring-no-properties + contents-begin contents-end))) + (pos-before-blank (progn (goto-char contents-end) + (forward-line) + (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'example-block + (nconc + (list :begin begin + :end end + :value value + :switches switches + :number-lines number-lines + :preserve-indent preserve-indent + :retain-labels retain-labels + :use-labels use-labels + :label-fmt label-fmt + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated))))))))) + +(defun org-element-example-block-interpreter (example-block _) + "Interpret EXAMPLE-BLOCK element as Org syntax." + (let ((switches (org-element-property :switches example-block)) + (value (org-element-property :value example-block))) + (concat "#+BEGIN_EXAMPLE" (and switches (concat " " switches)) "\n" + (org-element-normalize-string + (org-escape-code-in-string + (if (or org-src-preserve-indentation + (org-element-property :preserve-indent example-block)) + value + (org-remove-indentation value)))) + "#+END_EXAMPLE"))) + + +;;;; Export Block + +(defun org-element-export-block-parser (limit affiliated) + "Parse an export block. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `export-block' and CDR is a plist +containing `:begin', `:end', `:type', `:value', `:post-blank' and +`:post-affiliated' keywords. + +Assume point is at export-block beginning." + (let* ((case-fold-search t)) + (if (not (save-excursion + (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t))) + ;; Incomplete block: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (save-excursion + (let* ((contents-end (match-beginning 0)) + (backend + (progn + (looking-at + "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$") + (match-string-no-properties 1))) + (begin (car affiliated)) + (post-affiliated (point)) + (contents-begin (progn (forward-line) (point))) + (pos-before-blank (progn (goto-char contents-end) + (forward-line) + (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position)))) + (value (org-unescape-code-in-string + (buffer-substring-no-properties contents-begin + contents-end)))) + (list 'export-block + (nconc + (list :type (and backend (upcase backend)) + :begin begin + :end end + :value value + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated)))))))) + +(defun org-element-export-block-interpreter (export-block _) + "Interpret EXPORT-BLOCK element as Org syntax." + (format "#+BEGIN_EXPORT %s\n%s#+END_EXPORT" + (org-element-property :type export-block) + (org-element-property :value export-block))) + + +;;;; Fixed-width + +(defun org-element-fixed-width-parser (limit affiliated) + "Parse a fixed-width section. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `fixed-width' and CDR is a plist +containing `:begin', `:end', `:value', `:post-blank' and +`:post-affiliated' keywords. + +Assume point is at the beginning of the fixed-width area." + (save-excursion + (let* ((begin (car affiliated)) + (post-affiliated (point)) + value + (end-area + (progn + (while (and (< (point) limit) + (looking-at "[ \t]*:\\( \\|$\\)")) + ;; Accumulate text without starting colons. + (setq value + (concat value + (buffer-substring-no-properties + (match-end 0) (point-at-eol)) + "\n")) + (forward-line)) + (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'fixed-width + (nconc + (list :begin begin + :end end + :value value + :post-blank (count-lines end-area end) + :post-affiliated post-affiliated) + (cdr affiliated)))))) + +(defun org-element-fixed-width-interpreter (fixed-width _) + "Interpret FIXED-WIDTH element as Org syntax." + (let ((value (org-element-property :value fixed-width))) + (and value + (replace-regexp-in-string + "^" ": " + (if (string-match "\n\\'" value) (substring value 0 -1) value))))) + + +;;;; Horizontal Rule + +(defun org-element-horizontal-rule-parser (limit affiliated) + "Parse an horizontal rule. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `horizontal-rule' and CDR is a plist +containing `:begin', `:end', `:post-blank' and `:post-affiliated' +keywords." + (save-excursion + (let ((begin (car affiliated)) + (post-affiliated (point)) + (post-hr (progn (forward-line) (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'horizontal-rule + (nconc + (list :begin begin + :end end + :post-blank (count-lines post-hr end) + :post-affiliated post-affiliated) + (cdr affiliated)))))) + +(defun org-element-horizontal-rule-interpreter (&rest _) + "Interpret HORIZONTAL-RULE element as Org syntax." + "-----") + + +;;;; Keyword + +(defun org-element-keyword-parser (limit affiliated) + "Parse a keyword at point. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `keyword' and CDR is a plist +containing `:key', `:value', `:begin', `:end', `:post-blank' and +`:post-affiliated' keywords." + (save-excursion + ;; An orphaned affiliated keyword is considered as a regular + ;; keyword. In this case AFFILIATED is nil, so we take care of + ;; this corner case. + (let ((begin (or (car affiliated) (point))) + (post-affiliated (point)) + (key (progn (looking-at "[ \t]*#\\+\\(\\S-+*\\):") + (upcase (match-string-no-properties 1)))) + (value (org-trim (buffer-substring-no-properties + (match-end 0) (point-at-eol)))) + (pos-before-blank (progn (forward-line) (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'keyword + (nconc + (list :key key + :value value + :begin begin + :end end + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated)))))) + +(defun org-element-keyword-interpreter (keyword _) + "Interpret KEYWORD element as Org syntax." + (format "#+%s: %s" + (org-element-property :key keyword) + (org-element-property :value keyword))) + + +;;;; Latex Environment + +(defconst org-element--latex-begin-environment + "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}" + "Regexp matching the beginning of a LaTeX environment. +The environment is captured by the first group. + +See also `org-element--latex-end-environment'.") + +(defconst org-element--latex-end-environment + "\\\\end{%s}[ \t]*$" + "Format string matching the ending of a LaTeX environment. +See also `org-element--latex-begin-environment'.") + +(defun org-element-latex-environment-parser (limit affiliated) + "Parse a LaTeX environment. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `latex-environment' and CDR is a plist +containing `:begin', `:end', `:value', `:post-blank' and +`:post-affiliated' keywords. + +Assume point is at the beginning of the latex environment." + (save-excursion + (let ((case-fold-search t) + (code-begin (point))) + (looking-at org-element--latex-begin-environment) + (if (not (re-search-forward (format org-element--latex-end-environment + (regexp-quote (match-string 1))) + limit t)) + ;; Incomplete latex environment: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (let* ((code-end (progn (forward-line) (point))) + (begin (car affiliated)) + (value (buffer-substring-no-properties code-begin code-end)) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'latex-environment + (nconc + (list :begin begin + :end end + :value value + :post-blank (count-lines code-end end) + :post-affiliated code-begin) + (cdr affiliated)))))))) + +(defun org-element-latex-environment-interpreter (latex-environment _) + "Interpret LATEX-ENVIRONMENT element as Org syntax." + (org-element-property :value latex-environment)) + + +;;;; Node Property + +(defun org-element-node-property-parser (limit) + "Parse a node-property at point. + +LIMIT bounds the search. + +Return a list whose CAR is `node-property' and CDR is a plist +containing `:key', `:value', `:begin', `:end', `:post-blank' and +`:post-affiliated' keywords." + (looking-at org-property-re) + (let ((case-fold-search t) + (begin (point)) + (key (match-string-no-properties 2)) + (value (match-string-no-properties 3)) + (end (save-excursion + (end-of-line) + (if (re-search-forward org-property-re limit t) + (line-beginning-position) + limit)))) + (list 'node-property + (list :key key + :value value + :begin begin + :end end + :post-blank 0 + :post-affiliated begin)))) + +(defun org-element-node-property-interpreter (node-property _) + "Interpret NODE-PROPERTY element as Org syntax." + (format org-property-format + (format ":%s:" (org-element-property :key node-property)) + (or (org-element-property :value node-property) ""))) + + +;;;; Paragraph + +(defun org-element-paragraph-parser (limit affiliated) + "Parse a paragraph. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `paragraph' and CDR is a plist +containing `:begin', `:end', `:contents-begin' and +`:contents-end', `:post-blank' and `:post-affiliated' keywords. + +Assume point is at the beginning of the paragraph." + (save-excursion + (let* ((begin (car affiliated)) + (contents-begin (point)) + (before-blank + (let ((case-fold-search t)) + (end-of-line) + ;; A matching `org-element-paragraph-separate' is not + ;; necessarily the end of the paragraph. In particular, + ;; drawers, blocks or LaTeX environments opening lines + ;; must be closed. Moreover keywords with a secondary + ;; value must belong to "dual keywords". + (while (not + (cond + ((not (and (re-search-forward + org-element-paragraph-separate limit 'move) + (progn (beginning-of-line) t)))) + ((looking-at org-drawer-regexp) + (save-excursion + (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))) + ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)") + (save-excursion + (re-search-forward + (format "^[ \t]*#\\+END_%s[ \t]*$" + (regexp-quote (match-string 1))) + limit t))) + ((looking-at org-element--latex-begin-environment) + (save-excursion + (re-search-forward + (format org-element--latex-end-environment + (regexp-quote (match-string 1))) + limit t))) + ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:") + (member-ignore-case (match-string 1) + org-element-dual-keywords)) + ;; Everything else is unambiguous. + (t))) + (end-of-line)) + (if (= (point) limit) limit + (goto-char (line-beginning-position))))) + (contents-end (save-excursion + (skip-chars-backward " \r\t\n" contents-begin) + (line-beginning-position 2))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'paragraph + (nconc + (list :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank (count-lines before-blank end) + :post-affiliated contents-begin) + (cdr affiliated)))))) + +(defun org-element-paragraph-interpreter (_ contents) + "Interpret paragraph element as Org syntax. +CONTENTS is the contents of the element." + contents) + + +;;;; Planning + +(defun org-element-planning-parser (limit) + "Parse a planning. + +LIMIT bounds the search. + +Return a list whose CAR is `planning' and CDR is a plist +containing `:closed', `:deadline', `:scheduled', `:begin', +`:end', `:post-blank' and `:post-affiliated' keywords." + (save-excursion + (let* ((case-fold-search nil) + (begin (point)) + (post-blank (let ((before-blank (progn (forward-line) (point)))) + (skip-chars-forward " \r\t\n" limit) + (skip-chars-backward " \t") + (unless (bolp) (end-of-line)) + (count-lines before-blank (point)))) + (end (point)) + closed deadline scheduled) + (goto-char begin) + (while (re-search-forward org-keyword-time-not-clock-regexp end t) + (goto-char (match-end 1)) + (skip-chars-forward " \t" end) + (let ((keyword (match-string 1)) + (time (org-element-timestamp-parser))) + (cond ((equal keyword org-closed-string) (setq closed time)) + ((equal keyword org-deadline-string) (setq deadline time)) + (t (setq scheduled time))))) + (list 'planning + (list :closed closed + :deadline deadline + :scheduled scheduled + :begin begin + :end end + :post-blank post-blank + :post-affiliated begin))))) + +(defun org-element-planning-interpreter (planning _) + "Interpret PLANNING element as Org syntax." + (mapconcat + #'identity + (delq nil + (list (let ((deadline (org-element-property :deadline planning))) + (when deadline + (concat org-deadline-string " " + (org-element-timestamp-interpreter deadline nil)))) + (let ((scheduled (org-element-property :scheduled planning))) + (when scheduled + (concat org-scheduled-string " " + (org-element-timestamp-interpreter scheduled nil)))) + (let ((closed (org-element-property :closed planning))) + (when closed + (concat org-closed-string " " + (org-element-timestamp-interpreter closed nil)))))) + " ")) + + +;;;; Src Block + +(defun org-element-src-block-parser (limit affiliated) + "Parse a src block. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `src-block' and CDR is a plist +containing `:language', `:switches', `:parameters', `:begin', +`:end', `:number-lines', `:retain-labels', `:use-labels', +`:label-fmt', `:preserve-indent', `:value', `:post-blank' and +`:post-affiliated' keywords. + +Assume point is at the beginning of the block." + (let ((case-fold-search t)) + (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$" + limit t))) + ;; Incomplete block: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (let ((contents-end (match-beginning 0))) + (save-excursion + (let* ((begin (car affiliated)) + (post-affiliated (point)) + ;; Get language as a string. + (language + (progn + (looking-at + "^[ \t]*#\\+BEGIN_SRC\ +\\(?: +\\(\\S-+\\)\\)?\ +\\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\ +\\(.*\\)[ \t]*$") + (match-string-no-properties 1))) + ;; Get switches. + (switches (match-string-no-properties 2)) + ;; Get parameters. + (parameters (match-string-no-properties 3)) + ;; Switches analysis. + (number-lines + (and switches + (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>" + switches) + (cons + (if (equal (match-string 1 switches) "-") + 'new + 'continued) + (if (not (match-end 2)) 0 + ;; Subtract 1 to give number of lines before + ;; first line. + (1- (string-to-number (match-string 2 switches))))))) + (preserve-indent (and switches + (string-match "-i\\>" switches))) + (label-fmt + (and switches + (string-match "-l +\"\\([^\"\n]+\\)\"" switches) + (match-string 1 switches))) + ;; Should labels be retained in (or stripped from) + ;; src blocks? + (retain-labels + (or (not switches) + (not (string-match "-r\\>" switches)) + (and number-lines (string-match "-k\\>" switches)))) + ;; What should code-references use - labels or + ;; line-numbers? + (use-labels + (or (not switches) + (and retain-labels + (not (string-match "-k\\>" switches))))) + ;; Retrieve code. + (value (org-unescape-code-in-string + (buffer-substring-no-properties + (line-beginning-position 2) contents-end))) + (pos-before-blank (progn (goto-char contents-end) + (forward-line) + (point))) + ;; Get position after ending blank lines. + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'src-block + (nconc + (list :language language + :switches (and (org-string-nw-p switches) + (org-trim switches)) + :parameters (and (org-string-nw-p parameters) + (org-trim parameters)) + :begin begin + :end end + :number-lines number-lines + :preserve-indent preserve-indent + :retain-labels retain-labels + :use-labels use-labels + :label-fmt label-fmt + :value value + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated))))))))) + +(defun org-element-src-block-interpreter (src-block _) + "Interpret SRC-BLOCK element as Org syntax." + (let ((lang (org-element-property :language src-block)) + (switches (org-element-property :switches src-block)) + (params (org-element-property :parameters src-block)) + (value + (let ((val (org-element-property :value src-block))) + (cond + ((or org-src-preserve-indentation + (org-element-property :preserve-indent src-block)) + val) + ((zerop org-edit-src-content-indentation) + (org-remove-indentation val)) + (t + (let ((ind (make-string org-edit-src-content-indentation ?\s))) + (replace-regexp-in-string + "^" ind (org-remove-indentation val)))))))) + (concat (format "#+BEGIN_SRC%s\n" + (concat (and lang (concat " " lang)) + (and switches (concat " " switches)) + (and params (concat " " params)))) + (org-element-normalize-string (org-escape-code-in-string value)) + "#+END_SRC"))) + + +;;;; Table + +(defun org-element-table-parser (limit affiliated) + "Parse a table at point. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `table' and CDR is a plist containing +`:begin', `:end', `:tblfm', `:type', `:contents-begin', +`:contents-end', `:value', `:post-blank' and `:post-affiliated' +keywords. + +Assume point is at the beginning of the table." + (save-excursion + (let* ((case-fold-search t) + (table-begin (point)) + (type (if (looking-at "[ \t]*|") 'org 'table.el)) + (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)" + (if (eq type 'org) "" "+"))) + (begin (car affiliated)) + (table-end + (if (re-search-forward end-re limit 'move) + (goto-char (match-beginning 0)) + (point))) + (tblfm (let (acc) + (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$") + (push (match-string-no-properties 1) acc) + (forward-line)) + acc)) + (pos-before-blank (point)) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'table + (nconc + (list :begin begin + :end end + :type type + :tblfm tblfm + ;; Only `org' tables have contents. `table.el' tables + ;; use a `:value' property to store raw table as + ;; a string. + :contents-begin (and (eq type 'org) table-begin) + :contents-end (and (eq type 'org) table-end) + :value (and (eq type 'table.el) + (buffer-substring-no-properties + table-begin table-end)) + :post-blank (count-lines pos-before-blank end) + :post-affiliated table-begin) + (cdr affiliated)))))) + +(defun org-element-table-interpreter (table contents) + "Interpret TABLE element as Org syntax. +CONTENTS is a string, if table's type is `org', or nil." + (if (eq (org-element-property :type table) 'table.el) + (org-remove-indentation (org-element-property :value table)) + (concat (with-temp-buffer (insert contents) + (org-table-align) + (buffer-string)) + (mapconcat (lambda (fm) (concat "#+TBLFM: " fm)) + (reverse (org-element-property :tblfm table)) + "\n")))) + + +;;;; Table Row + +(defun org-element-table-row-parser (_) + "Parse table row at point. + +Return a list whose CAR is `table-row' and CDR is a plist +containing `:begin', `:end', `:contents-begin', `:contents-end', +`:type', `:post-blank' and `:post-affiliated' keywords." + (save-excursion + (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard)) + (begin (point)) + ;; A table rule has no contents. In that case, ensure + ;; CONTENTS-BEGIN matches CONTENTS-END. + (contents-begin (and (eq type 'standard) (search-forward "|"))) + (contents-end (and (eq type 'standard) + (progn + (end-of-line) + (skip-chars-backward " \t") + (point)))) + (end (line-beginning-position 2))) + (list 'table-row + (list :type type + :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank 0 + :post-affiliated begin))))) + +(defun org-element-table-row-interpreter (table-row contents) + "Interpret TABLE-ROW element as Org syntax. +CONTENTS is the contents of the table row." + (if (eq (org-element-property :type table-row) 'rule) "|-" + (concat "|" contents))) + + +;;;; Verse Block + +(defun org-element-verse-block-parser (limit affiliated) + "Parse a verse block. + +LIMIT bounds the search. AFFILIATED is a list of which CAR is +the buffer position at the beginning of the first affiliated +keyword and CDR is a plist of affiliated keywords along with +their value. + +Return a list whose CAR is `verse-block' and CDR is a plist +containing `:begin', `:end', `:contents-begin', `:contents-end', +`:post-blank' and `:post-affiliated' keywords. + +Assume point is at beginning of the block." + (let ((case-fold-search t)) + (if (not (save-excursion + (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t))) + ;; Incomplete block: parse it as a paragraph. + (org-element-paragraph-parser limit affiliated) + (let ((contents-end (match-beginning 0))) + (save-excursion + (let* ((begin (car affiliated)) + (post-affiliated (point)) + (contents-begin (progn (forward-line) (point))) + (pos-before-blank (progn (goto-char contents-end) + (forward-line) + (point))) + (end (progn (skip-chars-forward " \r\t\n" limit) + (if (eobp) (point) (line-beginning-position))))) + (list 'verse-block + (nconc + (list :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank (count-lines pos-before-blank end) + :post-affiliated post-affiliated) + (cdr affiliated))))))))) + +(defun org-element-verse-block-interpreter (_ contents) + "Interpret verse-block element as Org syntax. +CONTENTS is verse block contents." + (format "#+BEGIN_VERSE\n%s#+END_VERSE" contents)) + + + +;;; Objects +;; +;; Unlike to elements, raw text can be found between objects. Hence, +;; `org-element--object-lex' is provided to find the next object in +;; buffer. +;; +;; Some object types (e.g., `italic') are recursive. Restrictions on +;; object types they can contain will be specified in +;; `org-element-object-restrictions'. +;; +;; Creating a new type of object requires to alter +;; `org-element--object-regexp' and `org-element--object-lex', add the +;; new type in `org-element-all-objects', and possibly add +;; restrictions in `org-element-object-restrictions'. + +;;;; Bold + +(defun org-element-bold-parser () + "Parse bold object at point, if any. + +When at a bold object, return a list whose car is `bold' and cdr +is a plist with `:begin', `:end', `:contents-begin' and +`:contents-end' and `:post-blank' keywords. Otherwise, return +nil. + +Assume point is at the first star marker." + (save-excursion + (unless (bolp) (backward-char 1)) + (when (looking-at org-emph-re) + (let ((begin (match-beginning 2)) + (contents-begin (match-beginning 4)) + (contents-end (match-end 4)) + (post-blank (progn (goto-char (match-end 2)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'bold + (list :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank post-blank)))))) + +(defun org-element-bold-interpreter (_ contents) + "Interpret bold object as Org syntax. +CONTENTS is the contents of the object." + (format "*%s*" contents)) + + +;;;; Code + +(defun org-element-code-parser () + "Parse code object at point, if any. + +When at a code object, return a list whose car is `code' and cdr +is a plist with `:value', `:begin', `:end' and `:post-blank' +keywords. Otherwise, return nil. + +Assume point is at the first tilde marker." + (save-excursion + (unless (bolp) (backward-char 1)) + (when (looking-at org-verbatim-re) + (let ((begin (match-beginning 2)) + (value (match-string-no-properties 4)) + (post-blank (progn (goto-char (match-end 2)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'code + (list :value value + :begin begin + :end end + :post-blank post-blank)))))) + +(defun org-element-code-interpreter (code _) + "Interpret CODE object as Org syntax." + (format "~%s~" (org-element-property :value code))) + + +;;;; Entity + +(defun org-element-entity-parser () + "Parse entity at point, if any. + +When at an entity, return a list whose car is `entity' and cdr +a plist with `:begin', `:end', `:latex', `:latex-math-p', +`:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and +`:post-blank' as keywords. Otherwise, return nil. + +Assume point is at the beginning of the entity." + (catch 'no-object + (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)") + (save-excursion + (let* ((value (or (org-entity-get (match-string 1)) + (throw 'no-object nil))) + (begin (match-beginning 0)) + (bracketsp (string= (match-string 2) "{}")) + (post-blank (progn (goto-char (match-end 1)) + (when bracketsp (forward-char 2)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'entity + (list :name (car value) + :latex (nth 1 value) + :latex-math-p (nth 2 value) + :html (nth 3 value) + :ascii (nth 4 value) + :latin1 (nth 5 value) + :utf-8 (nth 6 value) + :begin begin + :end end + :use-brackets-p bracketsp + :post-blank post-blank))))))) + +(defun org-element-entity-interpreter (entity _) + "Interpret ENTITY object as Org syntax." + (concat "\\" + (org-element-property :name entity) + (when (org-element-property :use-brackets-p entity) "{}"))) + + +;;;; Export Snippet + +(defun org-element-export-snippet-parser () + "Parse export snippet at point. + +When at an export snippet, return a list whose car is +`export-snippet' and cdr a plist with `:begin', `:end', +`:back-end', `:value' and `:post-blank' as keywords. Otherwise, +return nil. + +Assume point is at the beginning of the snippet." + (save-excursion + (let (contents-end) + (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):") + (setq contents-end + (save-match-data (goto-char (match-end 0)) + (re-search-forward "@@" nil t) + (match-beginning 0)))) + (let* ((begin (match-beginning 0)) + (back-end (match-string-no-properties 1)) + (value (buffer-substring-no-properties + (match-end 0) contents-end)) + (post-blank (skip-chars-forward " \t")) + (end (point))) + (list 'export-snippet + (list :back-end back-end + :value value + :begin begin + :end end + :post-blank post-blank))))))) + +(defun org-element-export-snippet-interpreter (export-snippet _) + "Interpret EXPORT-SNIPPET object as Org syntax." + (format "@@%s:%s@@" + (org-element-property :back-end export-snippet) + (org-element-property :value export-snippet))) + + +;;;; Footnote Reference + +(defun org-element-footnote-reference-parser () + "Parse footnote reference at point, if any. + +When at a footnote reference, return a list whose car is +`footnote-reference' and cdr a plist with `:label', `:type', +`:begin', `:end', `:content-begin', `:contents-end' and +`:post-blank' as keywords. Otherwise, return nil." + (when (looking-at org-footnote-re) + (let ((closing (with-syntax-table org-element--pair-square-table + (ignore-errors (scan-lists (point) 1 0))))) + (when closing + (save-excursion + (let* ((begin (point)) + (label (match-string-no-properties 1)) + (inner-begin (match-end 0)) + (inner-end (1- closing)) + (type (if (match-end 2) 'inline 'standard)) + (post-blank (progn (goto-char closing) + (skip-chars-forward " \t"))) + (end (point))) + (list 'footnote-reference + (list :label label + :type type + :begin begin + :end end + :contents-begin (and (eq type 'inline) inner-begin) + :contents-end (and (eq type 'inline) inner-end) + :post-blank post-blank)))))))) + +(defun org-element-footnote-reference-interpreter (footnote-reference contents) + "Interpret FOOTNOTE-REFERENCE object as Org syntax. +CONTENTS is its definition, when inline, or nil." + (format "[fn:%s%s]" + (or (org-element-property :label footnote-reference) "") + (if contents (concat ":" contents) ""))) + + +;;;; Inline Babel Call + +(defun org-element-inline-babel-call-parser () + "Parse inline babel call at point, if any. + +When at an inline babel call, return a list whose car is +`inline-babel-call' and cdr a plist with `:call', +`:inside-header', `:arguments', `:end-header', `:begin', `:end', +`:value' and `:post-blank' as keywords. Otherwise, return nil. + +Assume point is at the beginning of the babel call." + (save-excursion + (catch :no-object + (when (let ((case-fold-search nil)) + (looking-at "\\. Unlike to + ;; bracket links, follow RFC 3986 and remove any extra + ;; whitespace in URI. + ((looking-at org-angle-link-re) + (setq format 'angle) + (setq type (match-string-no-properties 1)) + (setq link-end (match-end 0)) + (setq raw-link + (buffer-substring-no-properties + (match-beginning 1) (match-end 2))) + (setq path (replace-regexp-in-string + "[ \t]*\n[ \t]*" "" (match-string-no-properties 2)))) + (t (throw 'no-object nil))) + ;; In any case, deduce end point after trailing white space from + ;; LINK-END variable. + (save-excursion + (setq post-blank + (progn (goto-char link-end) (skip-chars-forward " \t"))) + (setq end (point))) + ;; Special "file" type link processing. Extract opening + ;; application and search option, if any. Also normalize URI. + (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type) + (setq application (match-string 1 type) type "file") + (when (string-match "::\\(.*\\)\\'" path) + (setq search-option (match-string 1 path)) + (setq path (replace-match "" nil nil path))) + (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path))) + ;; Translate link, if `org-link-translation-function' is set. + (let ((trans (and (functionp org-link-translation-function) + (funcall org-link-translation-function type path)))) + (when trans + (setq type (car trans)) + (setq path (cdr trans)))) + (list 'link + (list :type type + :path path + :format format + :raw-link (or raw-link path) + :application application + :search-option search-option + :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank post-blank))))) + +(defun org-element-link-interpreter (link contents) + "Interpret LINK object as Org syntax. +CONTENTS is the contents of the object, or nil." + (let ((type (org-element-property :type link)) + (path (org-element-property :path link))) + (if (string= type "radio") path + (let ((fmt (pcase (org-element-property :format link) + ;; Links with contents and internal links have to + ;; use bracket syntax. Ignore `:format' in these + ;; cases. This is also the default syntax when the + ;; property is not defined, e.g., when the object + ;; was crafted by the user. + ((guard contents) + (format "[[%%s][%s]]" + ;; Since this is going to be used as + ;; a format string, escape percent signs + ;; in description. + (replace-regexp-in-string "%" "%%" contents))) + ((or `bracket + `nil + (guard (member type '("coderef" "custom-id" "fuzzy")))) + "[[%s]]") + ;; Otherwise, just obey to `:format'. + (`angle "<%s>") + (`plain "%s") + (f (error "Wrong `:format' value: %s" f))))) + (format fmt + (pcase type + ("coderef" (format "(%s)" path)) + ("custom-id" (concat "#" path)) + ("file" + (let ((app (org-element-property :application link)) + (opt (org-element-property :search-option link))) + (concat type (and app (concat "+" app)) ":" + path + (and opt (concat "::" opt))))) + ("fuzzy" path) + (_ (concat type ":" path)))))))) + + +;;;; Macro + +(defun org-element-macro-parser () + "Parse macro at point, if any. + +When at a macro, return a list whose car is `macro' and cdr +a plist with `:key', `:args', `:begin', `:end', `:value' and +`:post-blank' as keywords. Otherwise, return nil. + +Assume point is at the macro." + (save-excursion + (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\(([ \t\n]*\\([^\000]*?\\))\\)?}}}") + (let ((begin (point)) + (key (downcase (match-string-no-properties 1))) + (value (match-string-no-properties 0)) + (post-blank (progn (goto-char (match-end 0)) + (skip-chars-forward " \t"))) + (end (point)) + (args (let ((args (match-string-no-properties 3))) + (and args (org-macro-extract-arguments args))))) + (list 'macro + (list :key key + :value value + :args args + :begin begin + :end end + :post-blank post-blank)))))) + +(defun org-element-macro-interpreter (macro _) + "Interpret MACRO object as Org syntax." + (org-element-property :value macro)) + + +;;;; Radio-target + +(defun org-element-radio-target-parser () + "Parse radio target at point, if any. + +When at a radio target, return a list whose car is `radio-target' +and cdr a plist with `:begin', `:end', `:contents-begin', +`:contents-end', `:value' and `:post-blank' as keywords. +Otherwise, return nil. + +Assume point is at the radio target." + (save-excursion + (when (looking-at org-radio-target-regexp) + (let ((begin (point)) + (contents-begin (match-beginning 1)) + (contents-end (match-end 1)) + (value (match-string-no-properties 1)) + (post-blank (progn (goto-char (match-end 0)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'radio-target + (list :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank post-blank + :value value)))))) + +(defun org-element-radio-target-interpreter (_ contents) + "Interpret target object as Org syntax. +CONTENTS is the contents of the object." + (concat "<<<" contents ">>>")) + + +;;;; Statistics Cookie + +(defun org-element-statistics-cookie-parser () + "Parse statistics cookie at point, if any. + +When at a statistics cookie, return a list whose car is +`statistics-cookie', and cdr a plist with `:begin', `:end', +`:value' and `:post-blank' keywords. Otherwise, return nil. + +Assume point is at the beginning of the statistics-cookie." + (save-excursion + (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]") + (let* ((begin (point)) + (value (buffer-substring-no-properties + (match-beginning 0) (match-end 0))) + (post-blank (progn (goto-char (match-end 0)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'statistics-cookie + (list :begin begin + :end end + :value value + :post-blank post-blank)))))) + +(defun org-element-statistics-cookie-interpreter (statistics-cookie _) + "Interpret STATISTICS-COOKIE object as Org syntax." + (org-element-property :value statistics-cookie)) + + +;;;; Strike-Through + +(defun org-element-strike-through-parser () + "Parse strike-through object at point, if any. + +When at a strike-through object, return a list whose car is +`strike-through' and cdr is a plist with `:begin', `:end', +`:contents-begin' and `:contents-end' and `:post-blank' keywords. +Otherwise, return nil. + +Assume point is at the first plus sign marker." + (save-excursion + (unless (bolp) (backward-char 1)) + (when (looking-at org-emph-re) + (let ((begin (match-beginning 2)) + (contents-begin (match-beginning 4)) + (contents-end (match-end 4)) + (post-blank (progn (goto-char (match-end 2)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'strike-through + (list :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank post-blank)))))) + +(defun org-element-strike-through-interpreter (_ contents) + "Interpret strike-through object as Org syntax. +CONTENTS is the contents of the object." + (format "+%s+" contents)) + + +;;;; Subscript + +(defun org-element-subscript-parser () + "Parse subscript at point, if any. + +When at a subscript object, return a list whose car is +`subscript' and cdr a plist with `:begin', `:end', +`:contents-begin', `:contents-end', `:use-brackets-p' and +`:post-blank' as keywords. Otherwise, return nil. + +Assume point is at the underscore." + (save-excursion + (unless (bolp) (backward-char)) + (when (looking-at org-match-substring-regexp) + (let ((bracketsp (match-beginning 4)) + (begin (match-beginning 2)) + (contents-begin (or (match-beginning 4) + (match-beginning 3))) + (contents-end (or (match-end 4) (match-end 3))) + (post-blank (progn (goto-char (match-end 0)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'subscript + (list :begin begin + :end end + :use-brackets-p bracketsp + :contents-begin contents-begin + :contents-end contents-end + :post-blank post-blank)))))) + +(defun org-element-subscript-interpreter (subscript contents) + "Interpret SUBSCRIPT object as Org syntax. +CONTENTS is the contents of the object." + (format + (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s") + contents)) + + +;;;; Superscript + +(defun org-element-superscript-parser () + "Parse superscript at point, if any. + +When at a superscript object, return a list whose car is +`superscript' and cdr a plist with `:begin', `:end', +`:contents-begin', `:contents-end', `:use-brackets-p' and +`:post-blank' as keywords. Otherwise, return nil. + +Assume point is at the caret." + (save-excursion + (unless (bolp) (backward-char)) + (when (looking-at org-match-substring-regexp) + (let ((bracketsp (match-beginning 4)) + (begin (match-beginning 2)) + (contents-begin (or (match-beginning 4) + (match-beginning 3))) + (contents-end (or (match-end 4) (match-end 3))) + (post-blank (progn (goto-char (match-end 0)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'superscript + (list :begin begin + :end end + :use-brackets-p bracketsp + :contents-begin contents-begin + :contents-end contents-end + :post-blank post-blank)))))) + +(defun org-element-superscript-interpreter (superscript contents) + "Interpret SUPERSCRIPT object as Org syntax. +CONTENTS is the contents of the object." + (format + (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s") + contents)) + + +;;;; Table Cell + +(defun org-element-table-cell-parser () + "Parse table cell at point. +Return a list whose car is `table-cell' and cdr is a plist +containing `:begin', `:end', `:contents-begin', `:contents-end' +and `:post-blank' keywords." + (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)") + (let* ((begin (match-beginning 0)) + (end (match-end 0)) + (contents-begin (match-beginning 1)) + (contents-end (match-end 1))) + (list 'table-cell + (list :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank 0)))) + +(defun org-element-table-cell-interpreter (_ contents) + "Interpret table-cell element as Org syntax. +CONTENTS is the contents of the cell, or nil." + (concat " " contents " |")) + + +;;;; Target + +(defun org-element-target-parser () + "Parse target at point, if any. + +When at a target, return a list whose car is `target' and cdr +a plist with `:begin', `:end', `:value' and `:post-blank' as +keywords. Otherwise, return nil. + +Assume point is at the target." + (save-excursion + (when (looking-at org-target-regexp) + (let ((begin (point)) + (value (match-string-no-properties 1)) + (post-blank (progn (goto-char (match-end 0)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'target + (list :begin begin + :end end + :value value + :post-blank post-blank)))))) + +(defun org-element-target-interpreter (target _) + "Interpret TARGET object as Org syntax." + (format "<<%s>>" (org-element-property :value target))) + + +;;;; Timestamp + +(defconst org-element--timestamp-regexp + (concat org-ts-regexp-both + "\\|" + "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)" + "\\|" + "\\(?:<%%\\(?:([^>\n]+)\\)>\\)") + "Regexp matching any timestamp type object.") + +(defun org-element-timestamp-parser () + "Parse time stamp at point, if any. + +When at a time stamp, return a list whose car is `timestamp', and +cdr a plist with `:type', `:raw-value', `:year-start', +`:month-start', `:day-start', `:hour-start', `:minute-start', +`:year-end', `:month-end', `:day-end', `:hour-end', +`:minute-end', `:repeater-type', `:repeater-value', +`:repeater-unit', `:warning-type', `:warning-value', +`:warning-unit', `:begin', `:end' and `:post-blank' keywords. +Otherwise, return nil. + +Assume point is at the beginning of the timestamp." + (when (looking-at-p org-element--timestamp-regexp) + (save-excursion + (let* ((begin (point)) + (activep (eq (char-after) ?<)) + (raw-value + (progn + (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?") + (match-string-no-properties 0))) + (date-start (match-string-no-properties 1)) + (date-end (match-string 3)) + (diaryp (match-beginning 2)) + (post-blank (progn (goto-char (match-end 0)) + (skip-chars-forward " \t"))) + (end (point)) + (time-range + (and (not diaryp) + (string-match + "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)" + date-start) + (cons (string-to-number (match-string 2 date-start)) + (string-to-number (match-string 3 date-start))))) + (type (cond (diaryp 'diary) + ((and activep (or date-end time-range)) 'active-range) + (activep 'active) + ((or date-end time-range) 'inactive-range) + (t 'inactive))) + (repeater-props + (and (not diaryp) + (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)" + raw-value) + (list + :repeater-type + (let ((type (match-string 1 raw-value))) + (cond ((equal "++" type) 'catch-up) + ((equal ".+" type) 'restart) + (t 'cumulate))) + :repeater-value (string-to-number (match-string 2 raw-value)) + :repeater-unit + (pcase (string-to-char (match-string 3 raw-value)) + (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year))))) + (warning-props + (and (not diaryp) + (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value) + (list + :warning-type (if (match-string 1 raw-value) 'first 'all) + :warning-value (string-to-number (match-string 2 raw-value)) + :warning-unit + (pcase (string-to-char (match-string 3 raw-value)) + (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year))))) + year-start month-start day-start hour-start minute-start year-end + month-end day-end hour-end minute-end) + ;; Parse date-start. + (unless diaryp + (let ((date (org-parse-time-string date-start t))) + (setq year-start (nth 5 date) + month-start (nth 4 date) + day-start (nth 3 date) + hour-start (nth 2 date) + minute-start (nth 1 date)))) + ;; Compute date-end. It can be provided directly in time-stamp, + ;; or extracted from time range. Otherwise, it defaults to the + ;; same values as date-start. + (unless diaryp + (let ((date (and date-end (org-parse-time-string date-end t)))) + (setq year-end (or (nth 5 date) year-start) + month-end (or (nth 4 date) month-start) + day-end (or (nth 3 date) day-start) + hour-end (or (nth 2 date) (car time-range) hour-start) + minute-end (or (nth 1 date) (cdr time-range) minute-start)))) + (list 'timestamp + (nconc (list :type type + :raw-value raw-value + :year-start year-start + :month-start month-start + :day-start day-start + :hour-start hour-start + :minute-start minute-start + :year-end year-end + :month-end month-end + :day-end day-end + :hour-end hour-end + :minute-end minute-end + :begin begin + :end end + :post-blank post-blank) + repeater-props + warning-props)))))) + +(defun org-element-timestamp-interpreter (timestamp _) + "Interpret TIMESTAMP object as Org syntax." + (let* ((repeat-string + (concat + (pcase (org-element-property :repeater-type timestamp) + (`cumulate "+") (`catch-up "++") (`restart ".+")) + (let ((val (org-element-property :repeater-value timestamp))) + (and val (number-to-string val))) + (pcase (org-element-property :repeater-unit timestamp) + (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y")))) + (warning-string + (concat + (pcase (org-element-property :warning-type timestamp) + (`first "--") (`all "-")) + (let ((val (org-element-property :warning-value timestamp))) + (and val (number-to-string val))) + (pcase (org-element-property :warning-unit timestamp) + (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y")))) + (build-ts-string + ;; Build an Org timestamp string from TIME. ACTIVEP is + ;; non-nil when time stamp is active. If WITH-TIME-P is + ;; non-nil, add a time part. HOUR-END and MINUTE-END + ;; specify a time range in the timestamp. REPEAT-STRING is + ;; the repeater string, if any. + (lambda (time activep &optional with-time-p hour-end minute-end) + (let ((ts (format-time-string + (funcall (if with-time-p #'cdr #'car) + org-time-stamp-formats) + time))) + (when (and hour-end minute-end) + (string-match "[012]?[0-9]:[0-5][0-9]" ts) + (setq ts + (replace-match + (format "\\&-%02d:%02d" hour-end minute-end) + nil nil ts))) + (unless activep (setq ts (format "[%s]" (substring ts 1 -1)))) + (dolist (s (list repeat-string warning-string)) + (when (org-string-nw-p s) + (setq ts (concat (substring ts 0 -1) + " " + s + (substring ts -1))))) + ;; Return value. + ts))) + (type (org-element-property :type timestamp))) + (pcase type + ((or `active `inactive) + (let* ((minute-start (org-element-property :minute-start timestamp)) + (minute-end (org-element-property :minute-end timestamp)) + (hour-start (org-element-property :hour-start timestamp)) + (hour-end (org-element-property :hour-end timestamp)) + (time-range-p (and hour-start hour-end minute-start minute-end + (or (/= hour-start hour-end) + (/= minute-start minute-end))))) + (funcall + build-ts-string + (encode-time 0 + (or minute-start 0) + (or hour-start 0) + (org-element-property :day-start timestamp) + (org-element-property :month-start timestamp) + (org-element-property :year-start timestamp)) + (eq type 'active) + (and hour-start minute-start) + (and time-range-p hour-end) + (and time-range-p minute-end)))) + ((or `active-range `inactive-range) + (let ((minute-start (org-element-property :minute-start timestamp)) + (minute-end (org-element-property :minute-end timestamp)) + (hour-start (org-element-property :hour-start timestamp)) + (hour-end (org-element-property :hour-end timestamp))) + (concat + (funcall + build-ts-string (encode-time + 0 + (or minute-start 0) + (or hour-start 0) + (org-element-property :day-start timestamp) + (org-element-property :month-start timestamp) + (org-element-property :year-start timestamp)) + (eq type 'active-range) + (and hour-start minute-start)) + "--" + (funcall build-ts-string + (encode-time 0 + (or minute-end 0) + (or hour-end 0) + (org-element-property :day-end timestamp) + (org-element-property :month-end timestamp) + (org-element-property :year-end timestamp)) + (eq type 'active-range) + (and hour-end minute-end))))) + (_ (org-element-property :raw-value timestamp))))) + + +;;;; Underline + +(defun org-element-underline-parser () + "Parse underline object at point, if any. + +When at an underline object, return a list whose car is +`underline' and cdr is a plist with `:begin', `:end', +`:contents-begin' and `:contents-end' and `:post-blank' keywords. +Otherwise, return nil. + +Assume point is at the first underscore marker." + (save-excursion + (unless (bolp) (backward-char 1)) + (when (looking-at org-emph-re) + (let ((begin (match-beginning 2)) + (contents-begin (match-beginning 4)) + (contents-end (match-end 4)) + (post-blank (progn (goto-char (match-end 2)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'underline + (list :begin begin + :end end + :contents-begin contents-begin + :contents-end contents-end + :post-blank post-blank)))))) + +(defun org-element-underline-interpreter (_ contents) + "Interpret underline object as Org syntax. +CONTENTS is the contents of the object." + (format "_%s_" contents)) + + +;;;; Verbatim + +(defun org-element-verbatim-parser () + "Parse verbatim object at point, if any. + +When at a verbatim object, return a list whose car is `verbatim' +and cdr is a plist with `:value', `:begin', `:end' and +`:post-blank' keywords. Otherwise, return nil. + +Assume point is at the first equal sign marker." + (save-excursion + (unless (bolp) (backward-char 1)) + (when (looking-at org-verbatim-re) + (let ((begin (match-beginning 2)) + (value (match-string-no-properties 4)) + (post-blank (progn (goto-char (match-end 2)) + (skip-chars-forward " \t"))) + (end (point))) + (list 'verbatim + (list :value value + :begin begin + :end end + :post-blank post-blank)))))) + +(defun org-element-verbatim-interpreter (verbatim _) + "Interpret VERBATIM object as Org syntax." + (format "=%s=" (org-element-property :value verbatim))) + + + +;;; Parsing Element Starting At Point +;; +;; `org-element--current-element' is the core function of this section. +;; It returns the Lisp representation of the element starting at +;; point. +;; +;; `org-element--current-element' makes use of special modes. They +;; are activated for fixed element chaining (e.g., `plain-list' > +;; `item') or fixed conditional element chaining (e.g., `headline' > +;; `section'). Special modes are: `first-section', `item', +;; `node-property', `section' and `table-row'. + +(defun org-element--current-element (limit &optional granularity mode structure) + "Parse the element starting at point. + +Return value is a list like (TYPE PROPS) where TYPE is the type +of the element and PROPS a plist of properties associated to the +element. + +Possible types are defined in `org-element-all-elements'. + +LIMIT bounds the search. + +Optional argument GRANULARITY determines the depth of the +recursion. Allowed values are `headline', `greater-element', +`element', `object' or nil. When it is broader than `object' (or +nil), secondary values will not be parsed, since they only +contain objects. + +Optional argument MODE, when non-nil, can be either +`first-section', `section', `planning', `item', `node-property' +and `table-row'. + +If STRUCTURE isn't provided but MODE is set to `item', it will be +computed. + +This function assumes point is always at the beginning of the +element it has to parse." + (save-excursion + (let ((case-fold-search t) + ;; Determine if parsing depth allows for secondary strings + ;; parsing. It only applies to elements referenced in + ;; `org-element-secondary-value-alist'. + (raw-secondary-p (and granularity (not (eq granularity 'object))))) + (cond + ;; Item. + ((eq mode 'item) + (org-element-item-parser limit structure raw-secondary-p)) + ;; Table Row. + ((eq mode 'table-row) (org-element-table-row-parser limit)) + ;; Node Property. + ((eq mode 'node-property) (org-element-node-property-parser limit)) + ;; Headline. + ((org-with-limited-levels (org-at-heading-p)) + (org-element-headline-parser limit raw-secondary-p)) + ;; Sections (must be checked after headline). + ((eq mode 'section) (org-element-section-parser limit)) + ((eq mode 'first-section) + (org-element-section-parser + (or (save-excursion (org-with-limited-levels (outline-next-heading))) + limit))) + ;; Planning. + ((and (eq mode 'planning) + (eq ?* (char-after (line-beginning-position 0))) + (looking-at org-planning-line-re)) + (org-element-planning-parser limit)) + ;; Property drawer. + ((and (memq mode '(planning property-drawer)) + (eq ?* (char-after (line-beginning-position + (if (eq mode 'planning) 0 -1)))) + (looking-at org-property-drawer-re)) + (org-element-property-drawer-parser limit)) + ;; When not at bol, point is at the beginning of an item or + ;; a footnote definition: next item is always a paragraph. + ((not (bolp)) (org-element-paragraph-parser limit (list (point)))) + ;; Clock. + ((looking-at org-clock-line-re) (org-element-clock-parser limit)) + ;; Inlinetask. + ((org-at-heading-p) + (org-element-inlinetask-parser limit raw-secondary-p)) + ;; From there, elements can have affiliated keywords. + (t (let ((affiliated (org-element--collect-affiliated-keywords limit))) + (cond + ;; Jumping over affiliated keywords put point off-limits. + ;; Parse them as regular keywords. + ((and (cdr affiliated) (>= (point) limit)) + (goto-char (car affiliated)) + (org-element-keyword-parser limit nil)) + ;; LaTeX Environment. + ((looking-at org-element--latex-begin-environment) + (org-element-latex-environment-parser limit affiliated)) + ;; Drawer and Property Drawer. + ((looking-at org-drawer-regexp) + (org-element-drawer-parser limit affiliated)) + ;; Fixed Width + ((looking-at "[ \t]*:\\( \\|$\\)") + (org-element-fixed-width-parser limit affiliated)) + ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and + ;; Keywords. + ((looking-at "[ \t]*#") + (goto-char (match-end 0)) + (cond + ((looking-at "\\(?: \\|$\\)") + (beginning-of-line) + (org-element-comment-parser limit affiliated)) + ((looking-at "\\+BEGIN_\\(\\S-+\\)") + (beginning-of-line) + (funcall (pcase (upcase (match-string 1)) + ("CENTER" #'org-element-center-block-parser) + ("COMMENT" #'org-element-comment-block-parser) + ("EXAMPLE" #'org-element-example-block-parser) + ("EXPORT" #'org-element-export-block-parser) + ("QUOTE" #'org-element-quote-block-parser) + ("SRC" #'org-element-src-block-parser) + ("VERSE" #'org-element-verse-block-parser) + (_ #'org-element-special-block-parser)) + limit + affiliated)) + ((looking-at "\\+CALL:") + (beginning-of-line) + (org-element-babel-call-parser limit affiliated)) + ((looking-at "\\+BEGIN:? ") + (beginning-of-line) + (org-element-dynamic-block-parser limit affiliated)) + ((looking-at "\\+\\S-+:") + (beginning-of-line) + (org-element-keyword-parser limit affiliated)) + (t + (beginning-of-line) + (org-element-paragraph-parser limit affiliated)))) + ;; Footnote Definition. + ((looking-at org-footnote-definition-re) + (org-element-footnote-definition-parser limit affiliated)) + ;; Horizontal Rule. + ((looking-at "[ \t]*-\\{5,\\}[ \t]*$") + (org-element-horizontal-rule-parser limit affiliated)) + ;; Diary Sexp. + ((looking-at "%%(") + (org-element-diary-sexp-parser limit affiliated)) + ;; Table. + ((looking-at "[ \t]*\\(|\\|\\+\\(-+\\+\\)+[ \t]*$\\)") + (org-element-table-parser limit affiliated)) + ;; List. + ((looking-at (org-item-re)) + (org-element-plain-list-parser + limit affiliated + (or structure (org-element--list-struct limit)))) + ;; Default element: Paragraph. + (t (org-element-paragraph-parser limit affiliated))))))))) + + +;; Most elements can have affiliated keywords. When looking for an +;; element beginning, we want to move before them, as they belong to +;; that element, and, in the meantime, collect information they give +;; into appropriate properties. Hence the following function. + +(defun org-element--collect-affiliated-keywords (limit) + "Collect affiliated keywords from point down to LIMIT. + +Return a list whose CAR is the position at the first of them and +CDR a plist of keywords and values and move point to the +beginning of the first line after them. + +As a special case, if element doesn't start at the beginning of +the line (e.g., a paragraph starting an item), CAR is current +position of point and CDR is nil." + (if (not (bolp)) (list (point)) + (let ((case-fold-search t) + (origin (point)) + ;; RESTRICT is the list of objects allowed in parsed + ;; keywords value. + (restrict (org-element-restriction 'keyword)) + output) + (while (and (< (point) limit) (looking-at org-element--affiliated-re)) + (let* ((raw-kwd (upcase (match-string 1))) + ;; Apply translation to RAW-KWD. From there, KWD is + ;; the official keyword. + (kwd (or (cdr (assoc raw-kwd + org-element-keyword-translation-alist)) + raw-kwd)) + ;; Find main value for any keyword. + (value + (save-match-data + (org-trim + (buffer-substring-no-properties + (match-end 0) (line-end-position))))) + ;; PARSEDP is non-nil when keyword should have its + ;; value parsed. + (parsedp (member kwd org-element-parsed-keywords)) + ;; If KWD is a dual keyword, find its secondary + ;; value. Maybe parse it. + (dualp (member kwd org-element-dual-keywords)) + (dual-value + (and dualp + (let ((sec (match-string-no-properties 2))) + (if (or (not sec) (not parsedp)) sec + (save-match-data + (org-element--parse-objects + (match-beginning 2) (match-end 2) nil restrict)))))) + ;; Attribute a property name to KWD. + (kwd-sym (and kwd (intern (concat ":" (downcase kwd)))))) + ;; Now set final shape for VALUE. + (when parsedp + (setq value + (org-element--parse-objects + (match-end 0) + (progn (end-of-line) (skip-chars-backward " \t") (point)) + nil restrict))) + (when dualp + (setq value (and (or value dual-value) (cons value dual-value)))) + (when (or (member kwd org-element-multiple-keywords) + ;; Attributes can always appear on multiple lines. + (string-match "^ATTR_" kwd)) + (setq value (cons value (plist-get output kwd-sym)))) + ;; Eventually store the new value in OUTPUT. + (setq output (plist-put output kwd-sym value)) + ;; Move to next keyword. + (forward-line))) + ;; If affiliated keywords are orphaned: move back to first one. + ;; They will be parsed as a paragraph. + (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil)) + ;; Return value. + (cons origin output)))) + + + +;;; The Org Parser +;; +;; The two major functions here are `org-element-parse-buffer', which +;; parses Org syntax inside the current buffer, taking into account +;; region, narrowing, or even visibility if specified, and +;; `org-element-parse-secondary-string', which parses objects within +;; a given string. +;; +;; The (almost) almighty `org-element-map' allows applying a function +;; on elements or objects matching some type, and accumulating the +;; resulting values. In an export situation, it also skips unneeded +;; parts of the parse tree. + +(defun org-element-parse-buffer (&optional granularity visible-only) + "Recursively parse the buffer and return structure. +If narrowing is in effect, only parse the visible part of the +buffer. + +Optional argument GRANULARITY determines the depth of the +recursion. It can be set to the following symbols: + +`headline' Only parse headlines. +`greater-element' Don't recurse into greater elements except + headlines and sections. Thus, elements + parsed are the top-level ones. +`element' Parse everything but objects and plain text. +`object' Parse the complete buffer (default). + +When VISIBLE-ONLY is non-nil, don't parse contents of hidden +elements. + +An element or object is represented as a list with the +pattern (TYPE PROPERTIES CONTENTS), where : + + TYPE is a symbol describing the element or object. See + `org-element-all-elements' and `org-element-all-objects' for an + exhaustive list of such symbols. One can retrieve it with + `org-element-type' function. + + PROPERTIES is the list of attributes attached to the element or + object, as a plist. Although most of them are specific to the + element or object type, all types share `:begin', `:end', + `:post-blank' and `:parent' properties, which respectively + refer to buffer position where the element or object starts, + ends, the number of white spaces or blank lines after it, and + the element or object containing it. Properties values can be + obtained by using `org-element-property' function. + + CONTENTS is a list of elements, objects or raw strings + contained in the current element or object, when applicable. + One can access them with `org-element-contents' function. + +The Org buffer has `org-data' as type and nil as properties. +`org-element-map' function can be used to find specific elements +or objects within the parse tree. + +This function assumes that current major mode is `org-mode'." + (save-excursion + (goto-char (point-min)) + (org-skip-whitespace) + (org-element--parse-elements + (point-at-bol) (point-max) + ;; Start in `first-section' mode so text before the first + ;; headline belongs to a section. + 'first-section nil granularity visible-only (list 'org-data nil)))) + +(defun org-element-parse-secondary-string (string restriction &optional parent) + "Recursively parse objects in STRING and return structure. + +RESTRICTION is a symbol limiting the object types that will be +looked after. + +Optional argument PARENT, when non-nil, is the element or object +containing the secondary string. It is used to set correctly +`:parent' property within the string. + +If STRING is the empty string or nil, return nil." + (cond + ((not string) nil) + ((equal string "") nil) + (t (let ((local-variables (buffer-local-variables))) + (with-temp-buffer + (dolist (v local-variables) + (ignore-errors + (if (symbolp v) (makunbound v) + (set (make-local-variable (car v)) (cdr v))))) + (insert string) + (restore-buffer-modified-p nil) + (org-element--parse-objects + (point-min) (point-max) nil restriction parent)))))) + +(defun org-element-map + (data types fun &optional info first-match no-recursion with-affiliated) + "Map a function on selected elements or objects. + +DATA is a parse tree, an element, an object, a string, or a list +of such constructs. TYPES is a symbol or list of symbols of +elements or objects types (see `org-element-all-elements' and +`org-element-all-objects' for a complete list of types). FUN is +the function called on the matching element or object. It has to +accept one argument: the element or object itself. + +When optional argument INFO is non-nil, it should be a plist +holding export options. In that case, parts of the parse tree +not exportable according to that property list will be skipped. + +When optional argument FIRST-MATCH is non-nil, stop at the first +match for which FUN doesn't return nil, and return that value. + +Optional argument NO-RECURSION is a symbol or a list of symbols +representing elements or objects types. `org-element-map' won't +enter any recursive element or object whose type belongs to that +list. Though, FUN can still be applied on them. + +When optional argument WITH-AFFILIATED is non-nil, FUN will also +apply to matching objects within parsed affiliated keywords (see +`org-element-parsed-keywords'). + +Nil values returned from FUN do not appear in the results. + + +Examples: +--------- + +Assuming TREE is a variable containing an Org buffer parse tree, +the following example will return a flat list of all `src-block' +and `example-block' elements in it: + + (org-element-map tree \\='(example-block src-block) #\\='identity) + +The following snippet will find the first headline with a level +of 1 and a \"phone\" tag, and will return its beginning position: + + (org-element-map tree \\='headline + (lambda (hl) + (and (= (org-element-property :level hl) 1) + (member \"phone\" (org-element-property :tags hl)) + (org-element-property :begin hl))) + nil t) + +The next example will return a flat list of all `plain-list' type +elements in TREE that are not a sub-list themselves: + + (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list) + +Eventually, this example will return a flat list of all `bold' +type objects containing a `latex-snippet' type object, even +looking into captions: + + (org-element-map tree \\='bold + (lambda (b) + (and (org-element-map b \\='latex-snippet #\\='identity nil t) b)) + nil nil nil t)" + ;; Ensure TYPES and NO-RECURSION are a list, even of one element. + (let* ((types (if (listp types) types (list types))) + (no-recursion (if (listp no-recursion) no-recursion + (list no-recursion))) + ;; Recursion depth is determined by --CATEGORY. + (--category + (catch :--found + (let ((category 'greater-elements) + (all-objects (cons 'plain-text org-element-all-objects))) + (dolist (type types category) + (cond ((memq type all-objects) + ;; If one object is found, the function has + ;; to recurse into every object. + (throw :--found 'objects)) + ((not (memq type org-element-greater-elements)) + ;; If one regular element is found, the + ;; function has to recurse, at least, into + ;; every element it encounters. + (and (not (eq category 'elements)) + (setq category 'elements)))))))) + --acc) + (letrec ((--walk-tree + (lambda (--data) + ;; Recursively walk DATA. INFO, if non-nil, is a plist + ;; holding contextual information. + (let ((--type (org-element-type --data))) + (cond + ((not --data)) + ;; Ignored element in an export context. + ((and info (memq --data (plist-get info :ignore-list)))) + ;; List of elements or objects. + ((not --type) (mapc --walk-tree --data)) + ;; Unconditionally enter parse trees. + ((eq --type 'org-data) + (mapc --walk-tree (org-element-contents --data))) + (t + ;; Check if TYPE is matching among TYPES. If so, + ;; apply FUN to --DATA and accumulate return value + ;; into --ACC (or exit if FIRST-MATCH is non-nil). + (when (memq --type types) + (let ((result (funcall fun --data))) + (cond ((not result)) + (first-match (throw :--map-first-match result)) + (t (push result --acc))))) + ;; If --DATA has a secondary string that can contain + ;; objects with their type among TYPES, look inside. + (when (and (eq --category 'objects) (not (stringp --data))) + (dolist (p (cdr (assq --type + org-element-secondary-value-alist))) + (funcall --walk-tree (org-element-property p --data)))) + ;; If --DATA has any parsed affiliated keywords and + ;; WITH-AFFILIATED is non-nil, look for objects in + ;; them. + (when (and with-affiliated + (eq --category 'objects) + (eq (org-element-class --data) 'element)) + (dolist (kwd-pair org-element--parsed-properties-alist) + (let ((kwd (car kwd-pair)) + (value (org-element-property (cdr kwd-pair) --data))) + ;; Pay attention to the type of parsed + ;; keyword. In particular, preserve order for + ;; multiple keywords. + (cond + ((not value)) + ((member kwd org-element-dual-keywords) + (if (member kwd org-element-multiple-keywords) + (dolist (line (reverse value)) + (funcall --walk-tree (cdr line)) + (funcall --walk-tree (car line))) + (funcall --walk-tree (cdr value)) + (funcall --walk-tree (car value)))) + ((member kwd org-element-multiple-keywords) + (mapc --walk-tree (reverse value))) + (t (funcall --walk-tree value)))))) + ;; Determine if a recursion into --DATA is possible. + (cond + ;; --TYPE is explicitly removed from recursion. + ((memq --type no-recursion)) + ;; --DATA has no contents. + ((not (org-element-contents --data))) + ;; Looking for greater elements but --DATA is + ;; simply an element or an object. + ((and (eq --category 'greater-elements) + (not (memq --type org-element-greater-elements)))) + ;; Looking for elements but --DATA is an object. + ((and (eq --category 'elements) + (eq (org-element-class --data) 'object))) + ;; In any other case, map contents. + (t (mapc --walk-tree (org-element-contents --data)))))))))) + (catch :--map-first-match + (funcall --walk-tree data) + ;; Return value in a proper order. + (nreverse --acc))))) +(put 'org-element-map 'lisp-indent-function 2) + +;; The following functions are internal parts of the parser. +;; +;; The first one, `org-element--parse-elements' acts at the element's +;; level. +;; +;; The second one, `org-element--parse-objects' applies on all objects +;; of a paragraph or a secondary string. It calls +;; `org-element--object-lex' to find the next object in the current +;; container. + +(defsubst org-element--next-mode (type parentp) + "Return next special mode according to TYPE, or nil. +TYPE is a symbol representing the type of an element or object +containing next element if PARENTP is non-nil, or before it +otherwise. Modes can be either `first-section', `item', +`node-property', `planning', `property-drawer', `section', +`table-row' or nil." + (if parentp + (pcase type + (`headline 'section) + (`inlinetask 'planning) + (`plain-list 'item) + (`property-drawer 'node-property) + (`section 'planning) + (`table 'table-row)) + (pcase type + (`item 'item) + (`node-property 'node-property) + (`planning 'property-drawer) + (`table-row 'table-row)))) + +(defun org-element--parse-elements + (beg end mode structure granularity visible-only acc) + "Parse elements between BEG and END positions. + +MODE prioritizes some elements over the others. It can be set to +`first-section', `section', `planning', `item', `node-property' +or `table-row'. + +When value is `item', STRUCTURE will be used as the current list +structure. + +GRANULARITY determines the depth of the recursion. See +`org-element-parse-buffer' for more information. + +When VISIBLE-ONLY is non-nil, don't parse contents of hidden +elements. + +Elements are accumulated into ACC." + (save-excursion + (goto-char beg) + ;; Visible only: skip invisible parts at the beginning of the + ;; element. + (when (and visible-only (org-invisible-p2)) + (goto-char (min (1+ (org-find-visible)) end))) + ;; When parsing only headlines, skip any text before first one. + (when (and (eq granularity 'headline) (not (org-at-heading-p))) + (org-with-limited-levels (outline-next-heading))) + (let (elements) + (while (< (point) end) + ;; Find current element's type and parse it accordingly to + ;; its category. + (let* ((element (org-element--current-element + end granularity mode structure)) + (type (org-element-type element)) + (cbeg (org-element-property :contents-begin element))) + (goto-char (org-element-property :end element)) + ;; Visible only: skip invisible parts between siblings. + (when (and visible-only (org-invisible-p2)) + (goto-char (min (1+ (org-find-visible)) end))) + ;; Fill ELEMENT contents by side-effect. + (cond + ;; If element has no contents, don't modify it. + ((not cbeg)) + ;; Greater element: parse it between `contents-begin' and + ;; `contents-end'. Make sure GRANULARITY allows the + ;; recursion, or ELEMENT is a headline, in which case going + ;; inside is mandatory, in order to get sub-level headings. + ((and (memq type org-element-greater-elements) + (or (memq granularity '(element object nil)) + (and (eq granularity 'greater-element) + (eq type 'section)) + (eq type 'headline))) + (org-element--parse-elements + cbeg (org-element-property :contents-end element) + ;; Possibly switch to a special mode. + (org-element--next-mode type t) + (and (memq type '(item plain-list)) + (org-element-property :structure element)) + granularity visible-only element)) + ;; ELEMENT has contents. Parse objects inside, if + ;; GRANULARITY allows it. + ((memq granularity '(object nil)) + (org-element--parse-objects + cbeg (org-element-property :contents-end element) element + (org-element-restriction type)))) + (push (org-element-put-property element :parent acc) elements) + ;; Update mode. + (setq mode (org-element--next-mode type nil)))) + ;; Return result. + (apply #'org-element-set-contents acc (nreverse elements))))) + +(defun org-element--object-lex (restriction) + "Return next object in current buffer or nil. +RESTRICTION is a list of object types, as symbols, that should be +looked after. This function assumes that the buffer is narrowed +to an appropriate container (e.g., a paragraph)." + (if (memq 'table-cell restriction) (org-element-table-cell-parser) + (let* ((start (point)) + (limit + ;; Object regexp sometimes needs to have a peek at + ;; a character ahead. Therefore, when there is a hard + ;; limit, make it one more than the true beginning of the + ;; radio target. + (save-excursion + (cond ((not org-target-link-regexp) nil) + ((not (memq 'link restriction)) nil) + ((progn + (unless (bolp) (forward-char -1)) + (not (re-search-forward org-target-link-regexp nil t))) + nil) + ;; Since we moved backward, we do not want to + ;; match again an hypothetical 1-character long + ;; radio link before us. Realizing that this can + ;; only happen if such a radio link starts at + ;; beginning of line, we prevent this here. + ((and (= start (1+ (line-beginning-position))) + (= start (match-end 1))) + (and (re-search-forward org-target-link-regexp nil t) + (1+ (match-beginning 1)))) + (t (1+ (match-beginning 1)))))) + found) + (save-excursion + (while (and (not found) + (re-search-forward org-element--object-regexp limit 'move)) + (goto-char (match-beginning 0)) + (let ((result (match-string 0))) + (setq found + (cond + ((string-prefix-p "call_" result t) + (and (memq 'inline-babel-call restriction) + (org-element-inline-babel-call-parser))) + ((string-prefix-p "src_" result t) + (and (memq 'inline-src-block restriction) + (org-element-inline-src-block-parser))) + (t + (pcase (char-after) + (?^ (and (memq 'superscript restriction) + (org-element-superscript-parser))) + (?_ (or (and (memq 'subscript restriction) + (org-element-subscript-parser)) + (and (memq 'underline restriction) + (org-element-underline-parser)))) + (?* (and (memq 'bold restriction) + (org-element-bold-parser))) + (?/ (and (memq 'italic restriction) + (org-element-italic-parser))) + (?~ (and (memq 'code restriction) + (org-element-code-parser))) + (?= (and (memq 'verbatim restriction) + (org-element-verbatim-parser))) + (?+ (and (memq 'strike-through restriction) + (org-element-strike-through-parser))) + (?@ (and (memq 'export-snippet restriction) + (org-element-export-snippet-parser))) + (?{ (and (memq 'macro restriction) + (org-element-macro-parser))) + (?$ (and (memq 'latex-fragment restriction) + (org-element-latex-fragment-parser))) + (?< + (if (eq (aref result 1) ?<) + (or (and (memq 'radio-target restriction) + (org-element-radio-target-parser)) + (and (memq 'target restriction) + (org-element-target-parser))) + (or (and (memq 'timestamp restriction) + (org-element-timestamp-parser)) + (and (memq 'link restriction) + (org-element-link-parser))))) + (?\\ + (if (eq (aref result 1) ?\\) + (and (memq 'line-break restriction) + (org-element-line-break-parser)) + (or (and (memq 'entity restriction) + (org-element-entity-parser)) + (and (memq 'latex-fragment restriction) + (org-element-latex-fragment-parser))))) + (?\[ + (if (eq (aref result 1) ?\[) + (and (memq 'link restriction) + (org-element-link-parser)) + (or (and (memq 'footnote-reference restriction) + (org-element-footnote-reference-parser)) + (and (memq 'timestamp restriction) + (org-element-timestamp-parser)) + (and (memq 'statistics-cookie restriction) + (org-element-statistics-cookie-parser))))) + ;; This is probably a plain link. + (_ (and (memq 'link restriction) + (org-element-link-parser))))))) + (or (eobp) (forward-char)))) + (cond (found) + (limit (forward-char -1) + (org-element-link-parser)) ;radio link + (t nil)))))) + +(defun org-element--parse-objects (beg end acc restriction &optional parent) + "Parse objects between BEG and END and return recursive structure. + +Objects are accumulated in ACC. RESTRICTION is a list of object +successors which are allowed in the current object. + +ACC becomes the parent for all parsed objects. However, if ACC +is nil (i.e., a secondary string is being parsed) and optional +argument PARENT is non-nil, use it as the parent for all objects. +Eventually, if both ACC and PARENT are nil, the common parent is +the list of objects itself." + (save-excursion + (save-restriction + (narrow-to-region beg end) + (goto-char (point-min)) + (let (next-object contents) + (while (and (not (eobp)) + (setq next-object (org-element--object-lex restriction))) + ;; Text before any object. + (let ((obj-beg (org-element-property :begin next-object))) + (unless (= (point) obj-beg) + (let ((text (buffer-substring-no-properties (point) obj-beg))) + (push (if acc (org-element-put-property text :parent acc) text) + contents)))) + ;; Object... + (let ((obj-end (org-element-property :end next-object)) + (cont-beg (org-element-property :contents-begin next-object))) + (when acc (org-element-put-property next-object :parent acc)) + (push (if cont-beg + ;; Fill contents of NEXT-OBJECT if possible. + (org-element--parse-objects + cont-beg + (org-element-property :contents-end next-object) + next-object + (org-element-restriction next-object)) + next-object) + contents) + (goto-char obj-end))) + ;; Text after last object. + (unless (eobp) + (let ((text (buffer-substring-no-properties (point) end))) + (push (if acc (org-element-put-property text :parent acc) text) + contents))) + ;; Result. Set appropriate parent. + (if acc (apply #'org-element-set-contents acc (nreverse contents)) + (let* ((contents (nreverse contents)) + (parent (or parent contents))) + (dolist (datum contents contents) + (org-element-put-property datum :parent parent)))))))) + + + +;;; Towards A Bijective Process +;; +;; The parse tree obtained with `org-element-parse-buffer' is really +;; a snapshot of the corresponding Org buffer. Therefore, it can be +;; interpreted and expanded into a string with canonical Org syntax. +;; Hence `org-element-interpret-data'. +;; +;; The function relies internally on +;; `org-element--interpret-affiliated-keywords'. + +;;;###autoload +(defun org-element-interpret-data (data) + "Interpret DATA as Org syntax. +DATA is a parse tree, an element, an object or a secondary string +to interpret. Return Org syntax as a string." + (letrec ((fun + (lambda (data parent) + (let* ((type (org-element-type data)) + ;; Find interpreter for current object or + ;; element. If it doesn't exist (e.g. this is + ;; a pseudo object or element), return contents, + ;; if any. + (interpret + (let ((fun (intern + (format "org-element-%s-interpreter" type)))) + (if (fboundp fun) fun (lambda (_ contents) contents)))) + (results + (cond + ;; Secondary string. + ((not type) + (mapconcat (lambda (obj) (funcall fun obj parent)) + data + "")) + ;; Full Org document. + ((eq type 'org-data) + (mapconcat (lambda (obj) (funcall fun obj parent)) + (org-element-contents data) + "")) + ;; Plain text: return it. + ((stringp data) data) + ;; Element or object without contents. + ((not (org-element-contents data)) + (funcall interpret data nil)) + ;; Element or object with contents. + (t + (funcall + interpret + data + ;; Recursively interpret contents. + (mapconcat + (lambda (datum) (funcall fun datum data)) + (org-element-contents + (if (not (memq type '(paragraph verse-block))) + data + ;; Fix indentation of elements containing + ;; objects. We ignore `table-row' + ;; elements as they are one line long + ;; anyway. + (org-element-normalize-contents + data + ;; When normalizing first paragraph of + ;; an item or a footnote-definition, + ;; ignore first line's indentation. + (and (eq type 'paragraph) + (memq (org-element-type parent) + '(footnote-definition item)) + (eq data + (car (org-element-contents parent))))))) + "")))))) + (if (memq type '(org-data plain-text nil)) results + ;; Build white spaces. If no `:post-blank' property + ;; is specified, assume its value is 0. + (let ((blank (or (org-element-property :post-blank data) 0))) + (if (eq (org-element-class data parent) 'object) + (concat results (make-string blank ?\s)) + (concat (org-element--interpret-affiliated-keywords data) + (org-element-normalize-string results) + (make-string blank ?\n))))))))) + (funcall fun data nil))) + +(defun org-element--interpret-affiliated-keywords (element) + "Return ELEMENT's affiliated keywords as Org syntax. +If there is no affiliated keyword, return the empty string." + (let ((keyword-to-org + (function + (lambda (key value) + (let (dual) + (when (member key org-element-dual-keywords) + (setq dual (cdr value) value (car value))) + (concat "#+" key + (and dual + (format "[%s]" (org-element-interpret-data dual))) + ": " + (if (member key org-element-parsed-keywords) + (org-element-interpret-data value) + value) + "\n")))))) + (mapconcat + (lambda (prop) + (let ((value (org-element-property prop element)) + (keyword (upcase (substring (symbol-name prop) 1)))) + (when value + (if (or (member keyword org-element-multiple-keywords) + ;; All attribute keywords can have multiple lines. + (string-match "^ATTR_" keyword)) + (mapconcat (lambda (line) (funcall keyword-to-org keyword line)) + (reverse value) + "") + (funcall keyword-to-org keyword value))))) + ;; List all ELEMENT's properties matching an attribute line or an + ;; affiliated keyword, but ignore translated keywords since they + ;; cannot belong to the property list. + (cl-loop for prop in (nth 1 element) by 'cddr + when (let ((keyword (upcase (substring (symbol-name prop) 1)))) + (or (string-match "^ATTR_" keyword) + (and + (member keyword org-element-affiliated-keywords) + (not (assoc keyword + org-element-keyword-translation-alist))))) + collect prop) + ""))) + +;; Because interpretation of the parse tree must return the same +;; number of blank lines between elements and the same number of white +;; space after objects, some special care must be given to white +;; spaces. +;; +;; The first function, `org-element-normalize-string', ensures any +;; string different from the empty string will end with a single +;; newline character. +;; +;; The second function, `org-element-normalize-contents', removes +;; global indentation from the contents of the current element. + +(defun org-element-normalize-string (s) + "Ensure string S ends with a single newline character. + +If S isn't a string return it unchanged. If S is the empty +string, return it. Otherwise, return a new string with a single +newline character at its end." + (cond + ((not (stringp s)) s) + ((string= "" s) "") + (t (and (string-match "\\(\n[ \t]*\\)*\\'" s) + (replace-match "\n" nil nil s))))) + +(defun org-element-normalize-contents (element &optional ignore-first) + "Normalize plain text in ELEMENT's contents. + +ELEMENT must only contain plain text and objects. + +If optional argument IGNORE-FIRST is non-nil, ignore first line's +indentation to compute maximal common indentation. + +Return the normalized element that is element with global +indentation removed from its contents." + (letrec ((find-min-ind + ;; Return minimal common indentation within BLOB. This is + ;; done by walking recursively BLOB and updating MIN-IND + ;; along the way. FIRST-FLAG is non-nil when the next + ;; object is expected to be a string that doesn't start + ;; with a newline character. It happens for strings at + ;; the beginnings of the contents or right after a line + ;; break. + (lambda (blob first-flag min-ind) + (dolist (datum (org-element-contents blob) min-ind) + (when first-flag + (setq first-flag nil) + (cond + ;; Objects cannot start with spaces: in this + ;; case, indentation is 0. + ((not (stringp datum)) (throw :zero 0)) + ((not (string-match + "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum)) + (throw :zero 0)) + ((equal (match-string 2 datum) "\n") + (put-text-property + (match-beginning 1) (match-end 1) 'org-ind 'empty datum)) + (t + (let ((i (string-width (match-string 1 datum)))) + (put-text-property + (match-beginning 1) (match-end 1) 'org-ind i datum) + (setq min-ind (min i min-ind)))))) + (cond + ((stringp datum) + (let ((s 0)) + (while (string-match + "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s) + (setq s (match-end 1)) + (cond + ((equal (match-string 1 datum) "") + (unless (member (match-string 2 datum) '("" "\n")) + (throw :zero 0))) + ((equal (match-string 2 datum) "\n") + (put-text-property (match-beginning 1) (match-end 1) + 'org-ind 'empty datum)) + (t + (let ((i (string-width (match-string 1 datum)))) + (put-text-property (match-beginning 1) (match-end 1) + 'org-ind i datum) + (setq min-ind (min i min-ind)))))))) + ((eq (org-element-type datum) 'line-break) + (setq first-flag t)) + ((memq (org-element-type datum) org-element-recursive-objects) + (setq min-ind + (funcall find-min-ind datum first-flag min-ind))))))) + (min-ind + (catch :zero + (funcall find-min-ind + element (not ignore-first) most-positive-fixnum)))) + (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element + ;; Build ELEMENT back, replacing each string with the same + ;; string minus common indentation. + (letrec ((build + (lambda (datum) + ;; Return DATUM with all its strings indentation + ;; shortened from MIN-IND white spaces. + (setcdr + (cdr datum) + (mapcar + (lambda (object) + (cond + ((stringp object) + (with-temp-buffer + (insert object) + (let ((s (point-min))) + (while (setq s (text-property-not-all + s (point-max) 'org-ind nil)) + (goto-char s) + (let ((i (get-text-property s 'org-ind))) + (delete-region s (progn + (skip-chars-forward " \t") + (point))) + (when (integerp i) (indent-to (- i min-ind)))))) + (buffer-string))) + ((memq (org-element-type object) + org-element-recursive-objects) + (funcall build object)) + (t object))) + (org-element-contents datum))) + datum))) + (funcall build element))))) + + + +;;; Cache +;; +;; Implement a caching mechanism for `org-element-at-point' and +;; `org-element-context', which see. +;; +;; A single public function is provided: `org-element-cache-reset'. +;; +;; Cache is enabled by default, but can be disabled globally with +;; `org-element-use-cache'. `org-element-cache-sync-idle-time', +;; org-element-cache-sync-duration' and `org-element-cache-sync-break' +;; can be tweaked to control caching behavior. +;; +;; Internally, parsed elements are stored in an AVL tree, +;; `org-element--cache'. This tree is updated lazily: whenever +;; a change happens to the buffer, a synchronization request is +;; registered in `org-element--cache-sync-requests' (see +;; `org-element--cache-submit-request'). During idle time, requests +;; are processed by `org-element--cache-sync'. Synchronization also +;; happens when an element is required from the cache. In this case, +;; the process stops as soon as the needed element is up-to-date. +;; +;; A synchronization request can only apply on a synchronized part of +;; the cache. Therefore, the cache is updated at least to the +;; location where the new request applies. Thus, requests are ordered +;; from left to right and all elements starting before the first +;; request are correct. This property is used by functions like +;; `org-element--cache-find' to retrieve elements in the part of the +;; cache that can be trusted. +;; +;; A request applies to every element, starting from its original +;; location (or key, see below). When a request is processed, it +;; moves forward and may collide the next one. In this case, both +;; requests are merged into a new one that starts from that element. +;; As a consequence, the whole synchronization complexity does not +;; depend on the number of pending requests, but on the number of +;; elements the very first request will be applied on. +;; +;; Elements cannot be accessed through their beginning position, which +;; may or may not be up-to-date. Instead, each element in the tree is +;; associated to a key, obtained with `org-element--cache-key'. This +;; mechanism is robust enough to preserve total order among elements +;; even when the tree is only partially synchronized. + + +(defvar org-element-use-cache nil + "Non-nil when Org parser should cache its results. + +WARNING: for the time being, using cache sometimes triggers +freezes. Therefore, it is disabled by default. Activate it if +you want to help debugging the issue.") + +(defvar org-element-cache-sync-idle-time 0.6 + "Length, in seconds, of idle time before syncing cache.") + +(defvar org-element-cache-sync-duration (seconds-to-time 0.04) + "Maximum duration, as a time value, for a cache synchronization. +If the synchronization is not over after this delay, the process +pauses and resumes after `org-element-cache-sync-break' +seconds.") + +(defvar org-element-cache-sync-break (seconds-to-time 0.3) + "Duration, as a time value, of the pause between synchronizations. +See `org-element-cache-sync-duration' for more information.") + + +;;;; Data Structure + +(defvar org-element--cache nil + "AVL tree used to cache elements. +Each node of the tree contains an element. Comparison is done +with `org-element--cache-compare'. This cache is used in +`org-element-at-point'.") + +(defvar org-element--cache-sync-requests nil + "List of pending synchronization requests. + +A request is a vector with the following pattern: + + \[NEXT BEG END OFFSET PARENT PHASE] + +Processing a synchronization request consists of three phases: + + 0. Delete modified elements, + 1. Fill missing area in cache, + 2. Shift positions and re-parent elements after the changes. + +During phase 0, NEXT is the key of the first element to be +removed, BEG and END is buffer position delimiting the +modifications. Elements starting between them (inclusive) are +removed. So are elements whose parent is removed. PARENT, when +non-nil, is the parent of the first element to be removed. + +During phase 1, NEXT is the key of the next known element in +cache and BEG its beginning position. Parse buffer between that +element and the one before it in order to determine the parent of +the next element. Set PARENT to the element containing NEXT. + +During phase 2, NEXT is the key of the next element to shift in +the parse tree. All elements starting from this one have their +properties relatives to buffer positions shifted by integer +OFFSET and, if they belong to element PARENT, are adopted by it. + +PHASE specifies the phase number, as an integer.") + +(defvar org-element--cache-sync-timer nil + "Timer used for cache synchronization.") + +(defvar org-element--cache-sync-keys nil + "Hash table used to store keys during synchronization. +See `org-element--cache-key' for more information.") + +(defsubst org-element--cache-key (element) + "Return a unique key for ELEMENT in cache tree. + +Keys are used to keep a total order among elements in the cache. +Comparison is done with `org-element--cache-key-less-p'. + +When no synchronization is taking place, a key is simply the +beginning position of the element, or that position plus one in +the case of an first item (respectively row) in +a list (respectively a table). + +During a synchronization, the key is the one the element had when +the cache was synchronized for the last time. Elements added to +cache during the synchronization get a new key generated with +`org-element--cache-generate-key'. + +Such keys are stored in `org-element--cache-sync-keys'. The hash +table is cleared once the synchronization is complete." + (or (gethash element org-element--cache-sync-keys) + (let* ((begin (org-element-property :begin element)) + ;; Increase beginning position of items (respectively + ;; table rows) by one, so the first item can get + ;; a different key from its parent list (respectively + ;; table). + (key (if (memq (org-element-type element) '(item table-row)) + (1+ begin) + begin))) + (if org-element--cache-sync-requests + (puthash element key org-element--cache-sync-keys) + key)))) + +(defun org-element--cache-generate-key (lower upper) + "Generate a key between LOWER and UPPER. + +LOWER and UPPER are integers or lists, possibly empty. + +If LOWER and UPPER are equals, return LOWER. Otherwise, return +a unique key, as an integer or a list of integers, according to +the following rules: + + - LOWER and UPPER are compared level-wise until values differ. + + - If, at a given level, LOWER and UPPER differ from more than + 2, the new key shares all the levels above with LOWER and + gets a new level. Its value is the mean between LOWER and + UPPER: + + (1 2) + (1 4) --> (1 3) + + - If LOWER has no value to compare with, it is assumed that its + value is `most-negative-fixnum'. E.g., + + (1 1) + (1 1 2) + + is equivalent to + + (1 1 m) + (1 1 2) + + where m is `most-negative-fixnum'. Likewise, if UPPER is + short of levels, the current value is `most-positive-fixnum'. + + - If they differ from only one, the new key inherits from + current LOWER level and fork it at the next level. E.g., + + (2 1) + (3 3) + + is equivalent to + + (2 1) + (2 M) + + where M is `most-positive-fixnum'. + + - If the key is only one level long, it is returned as an + integer: + + (1 2) + (3 2) --> 2 + +When they are not equals, the function assumes that LOWER is +lesser than UPPER, per `org-element--cache-key-less-p'." + (if (equal lower upper) lower + (let ((lower (if (integerp lower) (list lower) lower)) + (upper (if (integerp upper) (list upper) upper)) + skip-upper key) + (catch 'exit + (while t + (let ((min (or (car lower) most-negative-fixnum)) + (max (cond (skip-upper most-positive-fixnum) + ((car upper)) + (t most-positive-fixnum)))) + (if (< (1+ min) max) + (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1)))) + (throw 'exit (if key (nreverse (cons mean key)) mean))) + (when (and (< min max) (not skip-upper)) + ;; When at a given level, LOWER and UPPER differ from + ;; 1, ignore UPPER altogether. Instead create a key + ;; between LOWER and the greatest key with the same + ;; prefix as LOWER so far. + (setq skip-upper t)) + (push min key) + (setq lower (cdr lower) upper (cdr upper))))))))) + +(defsubst org-element--cache-key-less-p (a b) + "Non-nil if key A is less than key B. +A and B are either integers or lists of integers, as returned by +`org-element--cache-key'." + (if (integerp a) (if (integerp b) (< a b) (<= a (car b))) + (if (integerp b) (< (car a) b) + (catch 'exit + (while (and a b) + (cond ((car-less-than-car a b) (throw 'exit t)) + ((car-less-than-car b a) (throw 'exit nil)) + (t (setq a (cdr a) b (cdr b))))) + ;; If A is empty, either keys are equal (B is also empty) and + ;; we return nil, or A is lesser than B (B is longer) and we + ;; return a non-nil value. + ;; + ;; If A is not empty, B is necessarily empty and A is greater + ;; than B (A is longer). Therefore, return nil. + (and (null a) b))))) + +(defun org-element--cache-compare (a b) + "Non-nil when element A is located before element B." + (org-element--cache-key-less-p (org-element--cache-key a) + (org-element--cache-key b))) + +(defsubst org-element--cache-root () + "Return root value in cache. +This function assumes `org-element--cache' is a valid AVL tree." + (avl-tree--node-left (avl-tree--dummyroot org-element--cache))) + + +;;;; Tools + +(defsubst org-element--cache-active-p () + "Non-nil when cache is active in current buffer." + (and org-element-use-cache + org-element--cache + (derived-mode-p 'org-mode))) + +(defun org-element--cache-find (pos &optional side) + "Find element in cache starting at POS or before. + +POS refers to a buffer position. + +When optional argument SIDE is non-nil, the function checks for +elements starting at or past POS instead. If SIDE is `both', the +function returns a cons cell where car is the first element +starting at or before POS and cdr the first element starting +after POS. + +The function can only find elements in the synchronized part of +the cache." + (let ((limit (and org-element--cache-sync-requests + (aref (car org-element--cache-sync-requests) 0))) + (node (org-element--cache-root)) + lower upper) + (while node + (let* ((element (avl-tree--node-data node)) + (begin (org-element-property :begin element))) + (cond + ((and limit + (not (org-element--cache-key-less-p + (org-element--cache-key element) limit))) + (setq node (avl-tree--node-left node))) + ((> begin pos) + (setq upper element + node (avl-tree--node-left node))) + ((< begin pos) + (setq lower element + node (avl-tree--node-right node))) + ;; We found an element in cache starting at POS. If `side' + ;; is `both' we also want the next one in order to generate + ;; a key in-between. + ;; + ;; If the element is the first row or item in a table or + ;; a plain list, we always return the table or the plain + ;; list. + ;; + ;; In any other case, we return the element found. + ((eq side 'both) + (setq lower element) + (setq node (avl-tree--node-right node))) + ((and (memq (org-element-type element) '(item table-row)) + (let ((parent (org-element-property :parent element))) + (and (= (org-element-property :begin element) + (org-element-property :contents-begin parent)) + (setq node nil + lower parent + upper parent))))) + (t + (setq node nil + lower element + upper element))))) + (pcase side + (`both (cons lower upper)) + (`nil lower) + (_ upper)))) + +(defun org-element--cache-put (element) + "Store ELEMENT in current buffer's cache, if allowed." + (when (org-element--cache-active-p) + (when org-element--cache-sync-requests + ;; During synchronization, first build an appropriate key for + ;; the new element so `avl-tree-enter' can insert it at the + ;; right spot in the cache. + (let ((keys (org-element--cache-find + (org-element-property :begin element) 'both))) + (puthash element + (org-element--cache-generate-key + (and (car keys) (org-element--cache-key (car keys))) + (cond ((cdr keys) (org-element--cache-key (cdr keys))) + (org-element--cache-sync-requests + (aref (car org-element--cache-sync-requests) 0)))) + org-element--cache-sync-keys))) + (avl-tree-enter org-element--cache element))) + +(defsubst org-element--cache-remove (element) + "Remove ELEMENT from cache. +Assume ELEMENT belongs to cache and that a cache is active." + (avl-tree-delete org-element--cache element)) + + +;;;; Synchronization + +(defsubst org-element--cache-set-timer (buffer) + "Set idle timer for cache synchronization in BUFFER." + (when org-element--cache-sync-timer + (cancel-timer org-element--cache-sync-timer)) + (setq org-element--cache-sync-timer + (run-with-idle-timer + (let ((idle (current-idle-time))) + (if idle (time-add idle org-element-cache-sync-break) + org-element-cache-sync-idle-time)) + nil + #'org-element--cache-sync + buffer))) + +(defsubst org-element--cache-interrupt-p (time-limit) + "Non-nil when synchronization process should be interrupted. +TIME-LIMIT is a time value or nil." + (and time-limit + (or (input-pending-p) + (time-less-p time-limit (current-time))))) + +(defsubst org-element--cache-shift-positions (element offset &optional props) + "Shift ELEMENT properties relative to buffer positions by OFFSET. + +Properties containing buffer positions are `:begin', `:end', +`:contents-begin', `:contents-end' and `:structure'. When +optional argument PROPS is a list of keywords, only shift +properties provided in that list. + +Properties are modified by side-effect." + (let ((properties (nth 1 element))) + ;; Shift `:structure' property for the first plain list only: it + ;; is the only one that really matters and it prevents from + ;; shifting it more than once. + (when (and (or (not props) (memq :structure props)) + (eq (org-element-type element) 'plain-list) + (not (eq (org-element-type (plist-get properties :parent)) + 'item))) + (dolist (item (plist-get properties :structure)) + (cl-incf (car item) offset) + (cl-incf (nth 6 item) offset))) + (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated)) + (let ((value (and (or (not props) (memq key props)) + (plist-get properties key)))) + (and value (plist-put properties key (+ offset value))))))) + +(defun org-element--cache-sync (buffer &optional threshold future-change) + "Synchronize cache with recent modification in BUFFER. + +When optional argument THRESHOLD is non-nil, do the +synchronization for all elements starting before or at threshold, +then exit. Otherwise, synchronize cache for as long as +`org-element-cache-sync-duration' or until Emacs leaves idle +state. + +FUTURE-CHANGE, when non-nil, is a buffer position where changes +not registered yet in the cache are going to happen. It is used +in `org-element--cache-submit-request', where cache is partially +updated before current modification are actually submitted." + (when (buffer-live-p buffer) + (with-current-buffer buffer + (let ((inhibit-quit t) request next) + (when org-element--cache-sync-timer + (cancel-timer org-element--cache-sync-timer)) + (catch 'interrupt + (while org-element--cache-sync-requests + (setq request (car org-element--cache-sync-requests) + next (nth 1 org-element--cache-sync-requests)) + (org-element--cache-process-request + request + (and next (aref next 0)) + threshold + (and (not threshold) + (time-add (current-time) + org-element-cache-sync-duration)) + future-change) + ;; Request processed. Merge current and next offsets and + ;; transfer ending position. + (when next + (cl-incf (aref next 3) (aref request 3)) + (aset next 2 (aref request 2))) + (setq org-element--cache-sync-requests + (cdr org-element--cache-sync-requests)))) + ;; If more requests are awaiting, set idle timer accordingly. + ;; Otherwise, reset keys. + (if org-element--cache-sync-requests + (org-element--cache-set-timer buffer) + (clrhash org-element--cache-sync-keys)))))) + +(defun org-element--cache-process-request + (request next threshold time-limit future-change) + "Process synchronization REQUEST for all entries before NEXT. + +REQUEST is a vector, built by `org-element--cache-submit-request'. + +NEXT is a cache key, as returned by `org-element--cache-key'. + +When non-nil, THRESHOLD is a buffer position. Synchronization +stops as soon as a shifted element begins after it. + +When non-nil, TIME-LIMIT is a time value. Synchronization stops +after this time or when Emacs exits idle state. + +When non-nil, FUTURE-CHANGE is a buffer position where changes +not registered yet in the cache are going to happen. See +`org-element--cache-submit-request' for more information. + +Throw `interrupt' if the process stops before completing the +request." + (catch 'quit + (when (= (aref request 5) 0) + ;; Phase 0. + ;; + ;; Delete all elements starting after BEG, but not after buffer + ;; position END or past element with key NEXT. Also delete + ;; elements contained within a previously removed element + ;; (stored in `last-container'). + ;; + ;; At each iteration, we start again at tree root since + ;; a deletion modifies structure of the balanced tree. + (catch 'end-phase + (while t + (when (org-element--cache-interrupt-p time-limit) + (throw 'interrupt nil)) + ;; Find first element in cache with key BEG or after it. + (let ((beg (aref request 0)) + (end (aref request 2)) + (node (org-element--cache-root)) + data data-key last-container) + (while node + (let* ((element (avl-tree--node-data node)) + (key (org-element--cache-key element))) + (cond + ((org-element--cache-key-less-p key beg) + (setq node (avl-tree--node-right node))) + ((org-element--cache-key-less-p beg key) + (setq data element + data-key key + node (avl-tree--node-left node))) + (t (setq data element + data-key key + node nil))))) + (if data + (let ((pos (org-element-property :begin data))) + (if (if (or (not next) + (org-element--cache-key-less-p data-key next)) + (<= pos end) + (and last-container + (let ((up data)) + (while (and up (not (eq up last-container))) + (setq up (org-element-property :parent up))) + up))) + (progn (when (and (not last-container) + (> (org-element-property :end data) + end)) + (setq last-container data)) + (org-element--cache-remove data)) + (aset request 0 data-key) + (aset request 1 pos) + (aset request 5 1) + (throw 'end-phase nil))) + ;; No element starting after modifications left in + ;; cache: further processing is futile. + (throw 'quit t)))))) + (when (= (aref request 5) 1) + ;; Phase 1. + ;; + ;; Phase 0 left a hole in the cache. Some elements after it + ;; could have parents within. For example, in the following + ;; buffer: + ;; + ;; - item + ;; + ;; + ;; Paragraph1 + ;; + ;; Paragraph2 + ;; + ;; if we remove a blank line between "item" and "Paragraph1", + ;; everything down to "Paragraph2" is removed from cache. But + ;; the paragraph now belongs to the list, and its `:parent' + ;; property no longer is accurate. + ;; + ;; Therefore we need to parse again elements in the hole, or at + ;; least in its last section, so that we can re-parent + ;; subsequent elements, during phase 2. + ;; + ;; Note that we only need to get the parent from the first + ;; element in cache after the hole. + ;; + ;; When next key is lesser or equal to the current one, delegate + ;; phase 1 processing to next request in order to preserve key + ;; order among requests. + (let ((key (aref request 0))) + (when (and next (not (org-element--cache-key-less-p key next))) + (let ((next-request (nth 1 org-element--cache-sync-requests))) + (aset next-request 0 key) + (aset next-request 1 (aref request 1)) + (aset next-request 5 1)) + (throw 'quit t))) + ;; Next element will start at its beginning position plus + ;; offset, since it hasn't been shifted yet. Therefore, LIMIT + ;; contains the real beginning position of the first element to + ;; shift and re-parent. + (let ((limit (+ (aref request 1) (aref request 3)))) + (cond ((and threshold (> limit threshold)) (throw 'interrupt nil)) + ((and future-change (>= limit future-change)) + ;; Changes are going to happen around this element and + ;; they will trigger another phase 1 request. Skip the + ;; current one. + (aset request 5 2)) + (t + (let ((parent (org-element--parse-to limit t time-limit))) + (aset request 4 parent) + (aset request 5 2)))))) + ;; Phase 2. + ;; + ;; Shift all elements starting from key START, but before NEXT, by + ;; OFFSET, and re-parent them when appropriate. + ;; + ;; Elements are modified by side-effect so the tree structure + ;; remains intact. + ;; + ;; Once THRESHOLD, if any, is reached, or once there is an input + ;; pending, exit. Before leaving, the current synchronization + ;; request is updated. + (let ((start (aref request 0)) + (offset (aref request 3)) + (parent (aref request 4)) + (node (org-element--cache-root)) + (stack (list nil)) + (leftp t) + exit-flag) + ;; No re-parenting nor shifting planned: request is over. + (when (and (not parent) (zerop offset)) (throw 'quit t)) + (while node + (let* ((data (avl-tree--node-data node)) + (key (org-element--cache-key data))) + (if (and leftp (avl-tree--node-left node) + (not (org-element--cache-key-less-p key start))) + (progn (push node stack) + (setq node (avl-tree--node-left node))) + (unless (org-element--cache-key-less-p key start) + ;; We reached NEXT. Request is complete. + (when (equal key next) (throw 'quit t)) + ;; Handle interruption request. Update current request. + (when (or exit-flag (org-element--cache-interrupt-p time-limit)) + (aset request 0 key) + (aset request 4 parent) + (throw 'interrupt nil)) + ;; Shift element. + (unless (zerop offset) + (org-element--cache-shift-positions data offset)) + (let ((begin (org-element-property :begin data))) + ;; Update PARENT and re-parent DATA, only when + ;; necessary. Propagate new structures for lists. + (while (and parent + (<= (org-element-property :end parent) begin)) + (setq parent (org-element-property :parent parent))) + (cond ((and (not parent) (zerop offset)) (throw 'quit nil)) + ((and parent + (let ((p (org-element-property :parent data))) + (or (not p) + (< (org-element-property :begin p) + (org-element-property :begin parent))))) + (org-element-put-property data :parent parent) + (let ((s (org-element-property :structure parent))) + (when (and s (org-element-property :structure data)) + (org-element-put-property data :structure s))))) + ;; Cache is up-to-date past THRESHOLD. Request + ;; interruption. + (when (and threshold (> begin threshold)) (setq exit-flag t)))) + (setq node (if (setq leftp (avl-tree--node-right node)) + (avl-tree--node-right node) + (pop stack)))))) + ;; We reached end of tree: synchronization complete. + t))) + +(defun org-element--parse-to (pos &optional syncp time-limit) + "Parse elements in current section, down to POS. + +Start parsing from the closest between the last known element in +cache or headline above. Return the smallest element containing +POS. + +When optional argument SYNCP is non-nil, return the parent of the +element containing POS instead. In that case, it is also +possible to provide TIME-LIMIT, which is a time value specifying +when the parsing should stop. The function throws `interrupt' if +the process stopped before finding the expected result." + (catch 'exit + (org-with-wide-buffer + (goto-char pos) + (let* ((cached (and (org-element--cache-active-p) + (org-element--cache-find pos nil))) + (begin (org-element-property :begin cached)) + element next mode) + (cond + ;; Nothing in cache before point: start parsing from first + ;; element following headline above, or first element in + ;; buffer. + ((not cached) + (when (org-with-limited-levels (outline-previous-heading)) + (setq mode 'planning) + (forward-line)) + (skip-chars-forward " \r\t\n") + (beginning-of-line)) + ;; Cache returned exact match: return it. + ((= pos begin) + (throw 'exit (if syncp (org-element-property :parent cached) cached))) + ;; There's a headline between cached value and POS: cached + ;; value is invalid. Start parsing from first element + ;; following the headline. + ((re-search-backward + (org-with-limited-levels org-outline-regexp-bol) begin t) + (forward-line) + (skip-chars-forward " \r\t\n") + (beginning-of-line) + (setq mode 'planning)) + ;; Check if CACHED or any of its ancestors contain point. + ;; + ;; If there is such an element, we inspect it in order to know + ;; if we return it or if we need to parse its contents. + ;; Otherwise, we just start parsing from current location, + ;; which is right after the top-most element containing + ;; CACHED. + ;; + ;; As a special case, if POS is at the end of the buffer, we + ;; want to return the innermost element ending there. + ;; + ;; Also, if we find an ancestor and discover that we need to + ;; parse its contents, make sure we don't start from + ;; `:contents-begin', as we would otherwise go past CACHED + ;; again. Instead, in that situation, we will resume parsing + ;; from NEXT, which is located after CACHED or its higher + ;; ancestor not containing point. + (t + (let ((up cached) + (pos (if (= (point-max) pos) (1- pos) pos))) + (goto-char (or (org-element-property :contents-begin cached) begin)) + (while (let ((end (org-element-property :end up))) + (and (<= end pos) + (goto-char end) + (setq up (org-element-property :parent up))))) + (cond ((not up)) + ((eobp) (setq element up)) + (t (setq element up next (point))))))) + ;; Parse successively each element until we reach POS. + (let ((end (or (org-element-property :end element) + (save-excursion + (org-with-limited-levels (outline-next-heading)) + (point)))) + (parent element)) + (while t + (when syncp + (cond ((= (point) pos) (throw 'exit parent)) + ((org-element--cache-interrupt-p time-limit) + (throw 'interrupt nil)))) + (unless element + (setq element (org-element--current-element + end 'element mode + (org-element-property :structure parent))) + (org-element-put-property element :parent parent) + (org-element--cache-put element)) + (let ((elem-end (org-element-property :end element)) + (type (org-element-type element))) + (cond + ;; Skip any element ending before point. Also skip + ;; element ending at point (unless it is also the end of + ;; buffer) since we're sure that another element begins + ;; after it. + ((and (<= elem-end pos) (/= (point-max) elem-end)) + (goto-char elem-end) + (setq mode (org-element--next-mode type nil))) + ;; A non-greater element contains point: return it. + ((not (memq type org-element-greater-elements)) + (throw 'exit element)) + ;; Otherwise, we have to decide if ELEMENT really + ;; contains POS. In that case we start parsing from + ;; contents' beginning. + ;; + ;; If POS is at contents' beginning but it is also at + ;; the beginning of the first item in a list or a table. + ;; In that case, we need to create an anchor for that + ;; list or table, so return it. + ;; + ;; Also, if POS is at the end of the buffer, no element + ;; can start after it, but more than one may end there. + ;; Arbitrarily, we choose to return the innermost of + ;; such elements. + ((let ((cbeg (org-element-property :contents-begin element)) + (cend (org-element-property :contents-end element))) + (when (or syncp + (and cbeg cend + (or (< cbeg pos) + (and (= cbeg pos) + (not (memq type '(plain-list table))))) + (or (> cend pos) + (and (= cend pos) (= (point-max) pos))))) + (goto-char (or next cbeg)) + (setq next nil + mode (org-element--next-mode type t) + parent element + end cend)))) + ;; Otherwise, return ELEMENT as it is the smallest + ;; element containing POS. + (t (throw 'exit element)))) + (setq element nil))))))) + + +;;;; Staging Buffer Changes + +(defconst org-element--cache-sensitive-re + (concat + org-outline-regexp-bol "\\|" + "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|" + "^[ \t]*\\(?:" + "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|" + "\\\\begin{[A-Za-z0-9*]+}" "\\|" + ":\\(?:\\w\\|[-_]\\)+:[ \t]*$" + "\\)") + "Regexp matching a sensitive line, structure wise. +A sensitive line is a headline, inlinetask, block, drawer, or +latex-environment boundary. When such a line is modified, +structure changes in the document may propagate in the whole +section, possibly making cache invalid.") + +(defvar org-element--cache-change-warning nil + "Non-nil when a sensitive line is about to be changed. +It is a symbol among nil, t and `headline'.") + +(defun org-element--cache-before-change (beg end) + "Request extension of area going to be modified if needed. +BEG and END are the beginning and end of the range of changed +text. See `before-change-functions' for more information." + (when (org-element--cache-active-p) + (org-with-wide-buffer + (goto-char beg) + (beginning-of-line) + (let ((bottom (save-excursion (goto-char end) (line-end-position)))) + (setq org-element--cache-change-warning + (save-match-data + (if (and (org-with-limited-levels (org-at-heading-p)) + (= (line-end-position) bottom)) + 'headline + (let ((case-fold-search t)) + (re-search-forward + org-element--cache-sensitive-re bottom t))))))))) + +(defun org-element--cache-after-change (beg end pre) + "Update buffer modifications for current buffer. +BEG and END are the beginning and end of the range of changed +text, and the length in bytes of the pre-change text replaced by +that range. See `after-change-functions' for more information." + (when (org-element--cache-active-p) + (org-with-wide-buffer + (goto-char beg) + (beginning-of-line) + (save-match-data + (let ((top (point)) + (bottom (save-excursion (goto-char end) (line-end-position)))) + ;; Determine if modified area needs to be extended, according + ;; to both previous and current state. We make a special + ;; case for headline editing: if a headline is modified but + ;; not removed, do not extend. + (when (pcase org-element--cache-change-warning + (`t t) + (`headline + (not (and (org-with-limited-levels (org-at-heading-p)) + (= (line-end-position) bottom)))) + (_ + (let ((case-fold-search t)) + (re-search-forward + org-element--cache-sensitive-re bottom t)))) + ;; Effectively extend modified area. + (org-with-limited-levels + (setq top (progn (goto-char top) + (when (outline-previous-heading) (forward-line)) + (point))) + (setq bottom (progn (goto-char bottom) + (if (outline-next-heading) (1- (point)) + (point)))))) + ;; Store synchronization request. + (let ((offset (- end beg pre))) + (org-element--cache-submit-request top (- bottom offset) offset))))) + ;; Activate a timer to process the request during idle time. + (org-element--cache-set-timer (current-buffer)))) + +(defun org-element--cache-for-removal (beg end offset) + "Return first element to remove from cache. + +BEG and END are buffer positions delimiting buffer modifications. +OFFSET is the size of the changes. + +Returned element is usually the first element in cache containing +any position between BEG and END. As an exception, greater +elements around the changes that are robust to contents +modifications are preserved and updated according to the +changes." + (let* ((elements (org-element--cache-find (1- beg) 'both)) + (before (car elements)) + (after (cdr elements))) + (if (not before) after + (let ((up before) + (robust-flag t)) + (while up + (if (let ((type (org-element-type up))) + (and (or (memq type '(center-block dynamic-block quote-block + special-block)) + ;; Drawers named "PROPERTIES" are probably + ;; a properties drawer being edited. Force + ;; parsing to check if editing is over. + (and (eq type 'drawer) + (not (string= + (org-element-property :drawer-name up) + "PROPERTIES")))) + (let ((cbeg (org-element-property :contents-begin up))) + (and cbeg + (<= cbeg beg) + (> (org-element-property :contents-end up) end))))) + ;; UP is a robust greater element containing changes. + ;; We only need to extend its ending boundaries. + (org-element--cache-shift-positions + up offset '(:contents-end :end)) + (setq before up) + (when robust-flag (setq robust-flag nil))) + (setq up (org-element-property :parent up))) + ;; We're at top level element containing ELEMENT: if it's + ;; altered by buffer modifications, it is first element in + ;; cache to be removed. Otherwise, that first element is the + ;; following one. + ;; + ;; As a special case, do not remove BEFORE if it is a robust + ;; container for current changes. + (if (or (< (org-element-property :end before) beg) robust-flag) after + before))))) + +(defun org-element--cache-submit-request (beg end offset) + "Submit a new cache synchronization request for current buffer. +BEG and END are buffer positions delimiting the minimal area +where cache data should be removed. OFFSET is the size of the +change, as an integer." + (let ((next (car org-element--cache-sync-requests)) + delete-to delete-from) + (if (and next + (zerop (aref next 5)) + (> (setq delete-to (+ (aref next 2) (aref next 3))) end) + (<= (setq delete-from (aref next 1)) end)) + ;; Current changes can be merged with first sync request: we + ;; can save a partial cache synchronization. + (progn + (cl-incf (aref next 3) offset) + ;; If last change happened within area to be removed, extend + ;; boundaries of robust parents, if any. Otherwise, find + ;; first element to remove and update request accordingly. + (if (> beg delete-from) + (let ((up (aref next 4))) + (while up + (org-element--cache-shift-positions + up offset '(:contents-end :end)) + (setq up (org-element-property :parent up)))) + (let ((first (org-element--cache-for-removal beg delete-to offset))) + (when first + (aset next 0 (org-element--cache-key first)) + (aset next 1 (org-element-property :begin first)) + (aset next 4 (org-element-property :parent first)))))) + ;; Ensure cache is correct up to END. Also make sure that NEXT, + ;; if any, is no longer a 0-phase request, thus ensuring that + ;; phases are properly ordered. We need to provide OFFSET as + ;; optional parameter since current modifications are not known + ;; yet to the otherwise correct part of the cache (i.e, before + ;; the first request). + (when next (org-element--cache-sync (current-buffer) end beg)) + (let ((first (org-element--cache-for-removal beg end offset))) + (if first + (push (let ((beg (org-element-property :begin first)) + (key (org-element--cache-key first))) + (cond + ;; When changes happen before the first known + ;; element, re-parent and shift the rest of the + ;; cache. + ((> beg end) (vector key beg nil offset nil 1)) + ;; Otherwise, we find the first non robust + ;; element containing END. All elements between + ;; FIRST and this one are to be removed. + ((let ((first-end (org-element-property :end first))) + (and (> first-end end) + (vector key beg first-end offset first 0)))) + (t + (let* ((element (org-element--cache-find end)) + (end (org-element-property :end element)) + (up element)) + (while (and (setq up (org-element-property :parent up)) + (>= (org-element-property :begin up) beg)) + (setq end (org-element-property :end up) + element up)) + (vector key beg end offset element 0))))) + org-element--cache-sync-requests) + ;; No element to remove. No need to re-parent either. + ;; Simply shift additional elements, if any, by OFFSET. + (when org-element--cache-sync-requests + (cl-incf (aref (car org-element--cache-sync-requests) 3) + offset))))))) + + +;;;; Public Functions + +;;;###autoload +(defun org-element-cache-reset (&optional all) + "Reset cache in current buffer. +When optional argument ALL is non-nil, reset cache in all Org +buffers." + (interactive "P") + (dolist (buffer (if all (buffer-list) (list (current-buffer)))) + (with-current-buffer buffer + (when (and org-element-use-cache (derived-mode-p 'org-mode)) + (setq-local org-element--cache + (avl-tree-create #'org-element--cache-compare)) + (setq-local org-element--cache-sync-keys + (make-hash-table :weakness 'key :test #'eq)) + (setq-local org-element--cache-change-warning nil) + (setq-local org-element--cache-sync-requests nil) + (setq-local org-element--cache-sync-timer nil) + (add-hook 'before-change-functions + #'org-element--cache-before-change nil t) + (add-hook 'after-change-functions + #'org-element--cache-after-change nil t))))) + +;;;###autoload +(defun org-element-cache-refresh (pos) + "Refresh cache at position POS." + (when (org-element--cache-active-p) + (org-element--cache-sync (current-buffer) pos) + (org-element--cache-submit-request pos pos 0) + (org-element--cache-set-timer (current-buffer)))) + + + +;;; The Toolbox +;; +;; The first move is to implement a way to obtain the smallest element +;; containing point. This is the job of `org-element-at-point'. It +;; basically jumps back to the beginning of section containing point +;; and proceed, one element after the other, with +;; `org-element--current-element' until the container is found. Note: +;; When using `org-element-at-point', secondary values are never +;; parsed since the function focuses on elements, not on objects. +;; +;; At a deeper level, `org-element-context' lists all elements and +;; objects containing point. +;; +;; `org-element-nested-p' and `org-element-swap-A-B' may be used +;; internally by navigation and manipulation tools. + + +;;;###autoload +(defun org-element-at-point () + "Determine closest element around point. + +Return value is a list like (TYPE PROPS) where TYPE is the type +of the element and PROPS a plist of properties associated to the +element. + +Possible types are defined in `org-element-all-elements'. +Properties depend on element or object type, but always include +`:begin', `:end', `:parent' and `:post-blank' properties. + +As a special case, if point is at the very beginning of the first +item in a list or sub-list, returned element will be that list +instead of the item. Likewise, if point is at the beginning of +the first row of a table, returned element will be the table +instead of the first row. + +When point is at the end of the buffer, return the innermost +element ending there." + (org-with-wide-buffer + (let ((origin (point))) + (end-of-line) + (skip-chars-backward " \r\t\n") + (cond + ;; Within blank lines at the beginning of buffer, return nil. + ((bobp) nil) + ;; Within blank lines right after a headline, return that + ;; headline. + ((org-with-limited-levels (org-at-heading-p)) + (beginning-of-line) + (org-element-headline-parser (point-max) t)) + ;; Otherwise parse until we find element containing ORIGIN. + (t + (when (org-element--cache-active-p) + (if (not org-element--cache) (org-element-cache-reset) + (org-element--cache-sync (current-buffer) origin))) + (org-element--parse-to origin)))))) + +;;;###autoload +(defun org-element-context (&optional element) + "Return smallest element or object around point. + +Return value is a list like (TYPE PROPS) where TYPE is the type +of the element or object and PROPS a plist of properties +associated to it. + +Possible types are defined in `org-element-all-elements' and +`org-element-all-objects'. Properties depend on element or +object type, but always include `:begin', `:end', `:parent' and +`:post-blank'. + +As a special case, if point is right after an object and not at +the beginning of any other object, return that object. + +Optional argument ELEMENT, when non-nil, is the closest element +containing point, as returned by `org-element-at-point'. +Providing it allows for quicker computation." + (catch 'objects-forbidden + (org-with-wide-buffer + (let* ((pos (point)) + (element (or element (org-element-at-point))) + (type (org-element-type element)) + (post (org-element-property :post-affiliated element))) + ;; If point is inside an element containing objects or + ;; a secondary string, narrow buffer to the container and + ;; proceed with parsing. Otherwise, return ELEMENT. + (cond + ;; At a parsed affiliated keyword, check if we're inside main + ;; or dual value. + ((and post (< pos post)) + (beginning-of-line) + (let ((case-fold-search t)) (looking-at org-element--affiliated-re)) + (cond + ((not (member-ignore-case (match-string 1) + org-element-parsed-keywords)) + (throw 'objects-forbidden element)) + ((< (match-end 0) pos) + (narrow-to-region (match-end 0) (line-end-position))) + ((and (match-beginning 2) + (>= pos (match-beginning 2)) + (< pos (match-end 2))) + (narrow-to-region (match-beginning 2) (match-end 2))) + (t (throw 'objects-forbidden element))) + ;; Also change type to retrieve correct restrictions. + (setq type 'keyword)) + ;; At an item, objects can only be located within tag, if any. + ((eq type 'item) + (let ((tag (org-element-property :tag element))) + (if (or (not tag) (/= (line-beginning-position) post)) + (throw 'objects-forbidden element) + (beginning-of-line) + (search-forward tag (line-end-position)) + (goto-char (match-beginning 0)) + (if (and (>= pos (point)) (< pos (match-end 0))) + (narrow-to-region (point) (match-end 0)) + (throw 'objects-forbidden element))))) + ;; At an headline or inlinetask, objects are in title. + ((memq type '(headline inlinetask)) + (let ((case-fold-search nil)) + (goto-char (org-element-property :begin element)) + (looking-at org-complex-heading-regexp) + (let ((end (match-end 4))) + (if (not end) (throw 'objects-forbidden element) + (goto-char (match-beginning 4)) + (when (looking-at org-comment-string) + (goto-char (match-end 0))) + (if (>= (point) end) (throw 'objects-forbidden element) + (narrow-to-region (point) end)))))) + ;; At a paragraph, a table-row or a verse block, objects are + ;; located within their contents. + ((memq type '(paragraph table-row verse-block)) + (let ((cbeg (org-element-property :contents-begin element)) + (cend (org-element-property :contents-end element))) + ;; CBEG is nil for table rules. + (if (and cbeg cend (>= pos cbeg) + (or (< pos cend) (and (= pos cend) (eobp)))) + (narrow-to-region cbeg cend) + (throw 'objects-forbidden element)))) + (t (throw 'objects-forbidden element))) + (goto-char (point-min)) + (let ((restriction (org-element-restriction type)) + (parent element) + last) + (catch 'exit + (while t + (let ((next (org-element--object-lex restriction))) + (when next (org-element-put-property next :parent parent)) + ;; Process NEXT, if any, in order to know if we need to + ;; skip it, return it or move into it. + (if (or (not next) (> (org-element-property :begin next) pos)) + (throw 'exit (or last parent)) + (let ((end (org-element-property :end next)) + (cbeg (org-element-property :contents-begin next)) + (cend (org-element-property :contents-end next))) + (cond + ;; Skip objects ending before point. Also skip + ;; objects ending at point unless it is also the + ;; end of buffer, since we want to return the + ;; innermost object. + ((and (<= end pos) (/= (point-max) end)) + (goto-char end) + ;; For convenience, when object ends at POS, + ;; without any space, store it in LAST, as we + ;; will return it if no object starts here. + (when (and (= end pos) + (not (memq (char-before) '(?\s ?\t)))) + (setq last next))) + ;; If POS is within a container object, move into + ;; that object. + ((and cbeg cend + (>= pos cbeg) + (or (< pos cend) + ;; At contents' end, if there is no + ;; space before point, also move into + ;; object, for consistency with + ;; convenience feature above. + (and (= pos cend) + (or (= (point-max) pos) + (not (memq (char-before pos) + '(?\s ?\t))))))) + (goto-char cbeg) + (narrow-to-region (point) cend) + (setq parent next) + (setq restriction (org-element-restriction next))) + ;; Otherwise, return NEXT. + (t (throw 'exit next))))))))))))) + +(defun org-element-lineage (blob &optional types with-self) + "List all ancestors of a given element or object. + +BLOB is an object or element. + +When optional argument TYPES is a list of symbols, return the +first element or object in the lineage whose type belongs to that +list. + +When optional argument WITH-SELF is non-nil, lineage includes +BLOB itself as the first element, and TYPES, if provided, also +apply to it. + +When BLOB is obtained through `org-element-context' or +`org-element-at-point', only ancestors from its section can be +found. There is no such limitation when BLOB belongs to a full +parse tree." + (let ((up (if with-self blob (org-element-property :parent blob))) + ancestors) + (while (and up (not (memq (org-element-type up) types))) + (unless types (push up ancestors)) + (setq up (org-element-property :parent up))) + (if types up (nreverse ancestors)))) + +(defun org-element-nested-p (elem-A elem-B) + "Non-nil when elements ELEM-A and ELEM-B are nested." + (let ((beg-A (org-element-property :begin elem-A)) + (beg-B (org-element-property :begin elem-B)) + (end-A (org-element-property :end elem-A)) + (end-B (org-element-property :end elem-B))) + (or (and (>= beg-A beg-B) (<= end-A end-B)) + (and (>= beg-B beg-A) (<= end-B end-A))))) + +(defun org-element-swap-A-B (elem-A elem-B) + "Swap elements ELEM-A and ELEM-B. +Assume ELEM-B is after ELEM-A in the buffer. Leave point at the +end of ELEM-A." + (goto-char (org-element-property :begin elem-A)) + ;; There are two special cases when an element doesn't start at bol: + ;; the first paragraph in an item or in a footnote definition. + (let ((specialp (not (bolp)))) + ;; Only a paragraph without any affiliated keyword can be moved at + ;; ELEM-A position in such a situation. Note that the case of + ;; a footnote definition is impossible: it cannot contain two + ;; paragraphs in a row because it cannot contain a blank line. + (if (and specialp + (or (not (eq (org-element-type elem-B) 'paragraph)) + (/= (org-element-property :begin elem-B) + (org-element-property :contents-begin elem-B)))) + (error "Cannot swap elements")) + ;; In a special situation, ELEM-A will have no indentation. We'll + ;; give it ELEM-B's (which will in, in turn, have no indentation). + (let* ((ind-B (when specialp + (goto-char (org-element-property :begin elem-B)) + (org-get-indentation))) + (beg-A (org-element-property :begin elem-A)) + (end-A (save-excursion + (goto-char (org-element-property :end elem-A)) + (skip-chars-backward " \r\t\n") + (point-at-eol))) + (beg-B (org-element-property :begin elem-B)) + (end-B (save-excursion + (goto-char (org-element-property :end elem-B)) + (skip-chars-backward " \r\t\n") + (point-at-eol))) + ;; Store inner overlays responsible for visibility status. + ;; We also need to store their boundaries as they will be + ;; removed from buffer. + (overlays + (cons + (delq nil + (mapcar (lambda (o) + (and (>= (overlay-start o) beg-A) + (<= (overlay-end o) end-A) + (list o (overlay-start o) (overlay-end o)))) + (overlays-in beg-A end-A))) + (delq nil + (mapcar (lambda (o) + (and (>= (overlay-start o) beg-B) + (<= (overlay-end o) end-B) + (list o (overlay-start o) (overlay-end o)))) + (overlays-in beg-B end-B))))) + ;; Get contents. + (body-A (buffer-substring beg-A end-A)) + (body-B (delete-and-extract-region beg-B end-B))) + (goto-char beg-B) + (when specialp + (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B)) + (indent-to-column ind-B)) + (insert body-A) + ;; Restore ex ELEM-A overlays. + (let ((offset (- beg-B beg-A))) + (dolist (o (car overlays)) + (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset))) + (goto-char beg-A) + (delete-region beg-A end-A) + (insert body-B) + ;; Restore ex ELEM-B overlays. + (dolist (o (cdr overlays)) + (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset)))) + (goto-char (org-element-property :end elem-B))))) + + +(provide 'org-element) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-element.el ends here diff --git a/elpa/org-9.1.14/org-entities.el b/elpa/org-9.1.14/org-entities.el new file mode 100644 index 00000000..e291b521 --- /dev/null +++ b/elpa/org-9.1.14/org-entities.el @@ -0,0 +1,599 @@ +;;; org-entities.el --- Support for Special Entities -*- lexical-binding: t; -*- + +;; Copyright (C) 2010-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik , +;; Ulf Stegemann +;; Keywords: outlines, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;;; Code: + +(declare-function org-toggle-pretty-entities "org" ()) +(declare-function org-table-align "org-table" ()) + +(defgroup org-entities nil + "Options concerning entities in Org mode." + :tag "Org Entities" + :group 'org) + +(defun org-entities--user-safe-p (v) + "Non-nil if V is a safe value for `org-entities-user'." + (pcase v + (`nil t) + (`(,(and (pred stringp) + (pred (string-match-p "\\`[a-zA-Z][a-zA-Z0-9]*\\'"))) + ,(pred stringp) ,(pred booleanp) ,(pred stringp) + ,(pred stringp) ,(pred stringp) ,(pred stringp)) + t) + (_ nil))) + +(defcustom org-entities-user nil + "User-defined entities used in Org to produce special characters. +Each entry in this list is a list of strings. It associates the name +of the entity that can be inserted into an Org file as \\name with the +appropriate replacements for the different export backends. The order +of the fields is the following + +name As a string, without the leading backslash. +LaTeX replacement In ready LaTeX, no further processing will take place. +LaTeX mathp Either t or nil. When t this entity needs to be in + math mode. +HTML replacement In ready HTML, no further processing will take place. + Usually this will be an &...; entity. +ASCII replacement Plain ASCII, no extensions. +Latin1 replacement Use the special characters available in latin1. +utf-8 replacement Use the special characters available in utf-8. + +If you define new entities here that require specific LaTeX +packages to be loaded, add these packages to `org-latex-packages-alist'." + :group 'org-entities + :version "24.1" + :type '(repeat + (list + (string :tag "name ") + (string :tag "LaTeX ") + (boolean :tag "Require LaTeX math?") + (string :tag "HTML ") + (string :tag "ASCII ") + (string :tag "Latin1") + (string :tag "utf-8 "))) + :safe #'org-entities--user-safe-p) + +(defconst org-entities + (append + '("* Letters" + "** Latin" + ("Agrave" "\\`{A}" nil "À" "A" "À" "À") + ("agrave" "\\`{a}" nil "à" "a" "à" "à") + ("Aacute" "\\'{A}" nil "Á" "A" "Á" "Á") + ("aacute" "\\'{a}" nil "á" "a" "á" "á") + ("Acirc" "\\^{A}" nil "Â" "A" "Â" "Â") + ("acirc" "\\^{a}" nil "â" "a" "â" "â") + ("Amacr" "\\bar{A}" nil "Ā" "A" "Ã" "Ã") + ("amacr" "\\bar{a}" nil "ā" "a" "ã" "ã") + ("Atilde" "\\~{A}" nil "Ã" "A" "Ã" "Ã") + ("atilde" "\\~{a}" nil "ã" "a" "ã" "ã") + ("Auml" "\\\"{A}" nil "Ä" "Ae" "Ä" "Ä") + ("auml" "\\\"{a}" nil "ä" "ae" "ä" "ä") + ("Aring" "\\AA{}" nil "Å" "A" "Å" "Å") + ("AA" "\\AA{}" nil "Å" "A" "Å" "Å") + ("aring" "\\aa{}" nil "å" "a" "Ã¥" "Ã¥") + ("AElig" "\\AE{}" nil "Æ" "AE" "Æ" "Æ") + ("aelig" "\\ae{}" nil "æ" "ae" "æ" "æ") + ("Ccedil" "\\c{C}" nil "Ç" "C" "Ç" "Ç") + ("ccedil" "\\c{c}" nil "ç" "c" "ç" "ç") + ("Egrave" "\\`{E}" nil "È" "E" "È" "È") + ("egrave" "\\`{e}" nil "è" "e" "è" "è") + ("Eacute" "\\'{E}" nil "É" "E" "É" "É") + ("eacute" "\\'{e}" nil "é" "e" "é" "é") + ("Ecirc" "\\^{E}" nil "Ê" "E" "Ê" "Ê") + ("ecirc" "\\^{e}" nil "ê" "e" "ê" "ê") + ("Euml" "\\\"{E}" nil "Ë" "E" "Ë" "Ë") + ("euml" "\\\"{e}" nil "ë" "e" "ë" "ë") + ("Igrave" "\\`{I}" nil "Ì" "I" "Ì" "Ì") + ("igrave" "\\`{i}" nil "ì" "i" "ì" "ì") + ("Iacute" "\\'{I}" nil "Í" "I" "Í" "Í") + ("iacute" "\\'{i}" nil "í" "i" "í" "í") + ("Icirc" "\\^{I}" nil "Î" "I" "Î" "Î") + ("icirc" "\\^{i}" nil "î" "i" "î" "î") + ("Iuml" "\\\"{I}" nil "Ï" "I" "Ï" "Ï") + ("iuml" "\\\"{i}" nil "ï" "i" "ï" "ï") + ("Ntilde" "\\~{N}" nil "Ñ" "N" "Ñ" "Ñ") + ("ntilde" "\\~{n}" nil "ñ" "n" "ñ" "ñ") + ("Ograve" "\\`{O}" nil "Ò" "O" "Ò" "Ò") + ("ograve" "\\`{o}" nil "ò" "o" "ò" "ò") + ("Oacute" "\\'{O}" nil "Ó" "O" "Ó" "Ó") + ("oacute" "\\'{o}" nil "ó" "o" "ó" "ó") + ("Ocirc" "\\^{O}" nil "Ô" "O" "Ô" "Ô") + ("ocirc" "\\^{o}" nil "ô" "o" "ô" "ô") + ("Otilde" "\\~{O}" nil "Õ" "O" "Õ" "Õ") + ("otilde" "\\~{o}" nil "õ" "o" "õ" "õ") + ("Ouml" "\\\"{O}" nil "Ö" "Oe" "Ö" "Ö") + ("ouml" "\\\"{o}" nil "ö" "oe" "ö" "ö") + ("Oslash" "\\O" nil "Ø" "O" "Ø" "Ø") + ("oslash" "\\o{}" nil "ø" "o" "ø" "ø") + ("OElig" "\\OE{}" nil "Œ" "OE" "OE" "Œ") + ("oelig" "\\oe{}" nil "œ" "oe" "oe" "œ") + ("Scaron" "\\v{S}" nil "Š" "S" "S" "Å ") + ("scaron" "\\v{s}" nil "š" "s" "s" "Å¡") + ("szlig" "\\ss{}" nil "ß" "ss" "ß" "ß") + ("Ugrave" "\\`{U}" nil "Ù" "U" "Ù" "Ù") + ("ugrave" "\\`{u}" nil "ù" "u" "ù" "ù") + ("Uacute" "\\'{U}" nil "Ú" "U" "Ú" "Ú") + ("uacute" "\\'{u}" nil "ú" "u" "ú" "ú") + ("Ucirc" "\\^{U}" nil "Û" "U" "Û" "Û") + ("ucirc" "\\^{u}" nil "û" "u" "û" "û") + ("Uuml" "\\\"{U}" nil "Ü" "Ue" "Ü" "Ü") + ("uuml" "\\\"{u}" nil "ü" "ue" "ü" "ü") + ("Yacute" "\\'{Y}" nil "Ý" "Y" "Ý" "Ý") + ("yacute" "\\'{y}" nil "ý" "y" "ý" "ý") + ("Yuml" "\\\"{Y}" nil "Ÿ" "Y" "Y" "Ÿ") + ("yuml" "\\\"{y}" nil "ÿ" "y" "ÿ" "ÿ") + + "** Latin (special face)" + ("fnof" "\\textit{f}" nil "ƒ" "f" "f" "ƒ") + ("real" "\\Re" t "ℜ" "R" "R" "ℜ") + ("image" "\\Im" t "ℑ" "I" "I" "ℑ") + ("weierp" "\\wp" t "℘" "P" "P" "℘") + ("ell" "\\ell" t "ℓ" "ell" "ell" "ℓ") + ("imath" "\\imath" t "ı" "[dotless i]" "dotless i" "ı") + ("jmath" "\\jmath" t "ȷ" "[dotless j]" "dotless j" "È·") + + "** Greek" + ("Alpha" "A" nil "Α" "Alpha" "Alpha" "Α") + ("alpha" "\\alpha" t "α" "alpha" "alpha" "α") + ("Beta" "B" nil "Β" "Beta" "Beta" "Β") + ("beta" "\\beta" t "β" "beta" "beta" "β") + ("Gamma" "\\Gamma" t "Γ" "Gamma" "Gamma" "Γ") + ("gamma" "\\gamma" t "γ" "gamma" "gamma" "γ") + ("Delta" "\\Delta" t "Δ" "Delta" "Delta" "Δ") + ("delta" "\\delta" t "δ" "delta" "delta" "δ") + ("Epsilon" "E" nil "Ε" "Epsilon" "Epsilon" "Ε") + ("epsilon" "\\epsilon" t "ε" "epsilon" "epsilon" "ε") + ("varepsilon" "\\varepsilon" t "ε" "varepsilon" "varepsilon" "ε") + ("Zeta" "Z" nil "Ζ" "Zeta" "Zeta" "Ζ") + ("zeta" "\\zeta" t "ζ" "zeta" "zeta" "ζ") + ("Eta" "H" nil "Η" "Eta" "Eta" "Η") + ("eta" "\\eta" t "η" "eta" "eta" "η") + ("Theta" "\\Theta" t "Θ" "Theta" "Theta" "Θ") + ("theta" "\\theta" t "θ" "theta" "theta" "θ") + ("thetasym" "\\vartheta" t "ϑ" "theta" "theta" "ϑ") + ("vartheta" "\\vartheta" t "ϑ" "theta" "theta" "ϑ") + ("Iota" "I" nil "Ι" "Iota" "Iota" "Ι") + ("iota" "\\iota" t "ι" "iota" "iota" "ι") + ("Kappa" "K" nil "Κ" "Kappa" "Kappa" "Κ") + ("kappa" "\\kappa" t "κ" "kappa" "kappa" "κ") + ("Lambda" "\\Lambda" t "Λ" "Lambda" "Lambda" "Λ") + ("lambda" "\\lambda" t "λ" "lambda" "lambda" "λ") + ("Mu" "M" nil "Μ" "Mu" "Mu" "Μ") + ("mu" "\\mu" t "μ" "mu" "mu" "μ") + ("nu" "\\nu" t "ν" "nu" "nu" "ν") + ("Nu" "N" nil "Ν" "Nu" "Nu" "Ν") + ("Xi" "\\Xi" t "Ξ" "Xi" "Xi" "Ξ") + ("xi" "\\xi" t "ξ" "xi" "xi" "ξ") + ("Omicron" "O" nil "Ο" "Omicron" "Omicron" "Ο") + ("omicron" "\\textit{o}" nil "ο" "omicron" "omicron" "ο") + ("Pi" "\\Pi" t "Π" "Pi" "Pi" "Π") + ("pi" "\\pi" t "π" "pi" "pi" "π") + ("Rho" "P" nil "Ρ" "Rho" "Rho" "Ρ") + ("rho" "\\rho" t "ρ" "rho" "rho" "ρ") + ("Sigma" "\\Sigma" t "Σ" "Sigma" "Sigma" "Σ") + ("sigma" "\\sigma" t "σ" "sigma" "sigma" "σ") + ("sigmaf" "\\varsigma" t "ς" "sigmaf" "sigmaf" "ς") + ("varsigma" "\\varsigma" t "ς" "varsigma" "varsigma" "ς") + ("Tau" "T" nil "Τ" "Tau" "Tau" "Τ") + ("Upsilon" "\\Upsilon" t "Υ" "Upsilon" "Upsilon" "Î¥") + ("upsih" "\\Upsilon" t "ϒ" "upsilon" "upsilon" "ϒ") + ("upsilon" "\\upsilon" t "υ" "upsilon" "upsilon" "υ") + ("Phi" "\\Phi" t "Φ" "Phi" "Phi" "Φ") + ("phi" "\\phi" t "φ" "phi" "phi" "ɸ") + ("varphi" "\\varphi" t "ϕ" "varphi" "varphi" "φ") + ("Chi" "X" nil "Χ" "Chi" "Chi" "Χ") + ("chi" "\\chi" t "χ" "chi" "chi" "χ") + ("acutex" "\\acute x" t "´x" "'x" "'x" "𝑥́") + ("Psi" "\\Psi" t "Ψ" "Psi" "Psi" "Ψ") + ("psi" "\\psi" t "ψ" "psi" "psi" "ψ") + ("tau" "\\tau" t "τ" "tau" "tau" "τ") + ("Omega" "\\Omega" t "Ω" "Omega" "Omega" "Ω") + ("omega" "\\omega" t "ω" "omega" "omega" "ω") + ("piv" "\\varpi" t "ϖ" "omega-pi" "omega-pi" "ϖ") + ("varpi" "\\varpi" t "ϖ" "omega-pi" "omega-pi" "ϖ") + ("partial" "\\partial" t "∂" "[partial differential]" "[partial differential]" "∂") + + "** Hebrew" + ("alefsym" "\\aleph" t "ℵ" "aleph" "aleph" "ℵ") + ("aleph" "\\aleph" t "ℵ" "aleph" "aleph" "ℵ") + ("gimel" "\\gimel" t "ℷ" "gimel" "gimel" "ℷ") + ("beth" "\\beth" t "ℶ" "beth" "beth" "ב") + ("dalet" "\\daleth" t "ℸ" "dalet" "dalet" "ד") + + "** Dead languages" + ("ETH" "\\DH{}" nil "Ð" "D" "Ð" "Ð") + ("eth" "\\dh{}" nil "ð" "dh" "ð" "ð") + ("THORN" "\\TH{}" nil "Þ" "TH" "Þ" "Þ") + ("thorn" "\\th{}" nil "þ" "th" "þ" "þ") + + "* Punctuation" + "** Dots and Marks" + ("dots" "\\dots{}" nil "…" "..." "..." "…") + ("cdots" "\\cdots{}" t "⋯" "..." "..." "⋯") + ("hellip" "\\dots{}" nil "…" "..." "..." "…") + ("middot" "\\textperiodcentered{}" nil "·" "." "·" "·") + ("iexcl" "!`" nil "¡" "!" "¡" "¡") + ("iquest" "?`" nil "¿" "?" "¿" "¿") + + "** Dash-like" + ("shy" "\\-" nil "­" "" "" "") + ("ndash" "--" nil "–" "-" "-" "–") + ("mdash" "---" nil "—" "--" "--" "—") + + "** Quotations" + ("quot" "\\textquotedbl{}" nil """ "\"" "\"" "\"") + ("acute" "\\textasciiacute{}" nil "´" "'" "´" "´") + ("ldquo" "\\textquotedblleft{}" nil "“" "\"" "\"" "“") + ("rdquo" "\\textquotedblright{}" nil "”" "\"" "\"" "”") + ("bdquo" "\\quotedblbase{}" nil "„" "\"" "\"" "„") + ("lsquo" "\\textquoteleft{}" nil "‘" "`" "`" "‘") + ("rsquo" "\\textquoteright{}" nil "’" "'" "'" "’") + ("sbquo" "\\quotesinglbase{}" nil "‚" "," "," "‚") + ("laquo" "\\guillemotleft{}" nil "«" "<<" "«" "«") + ("raquo" "\\guillemotright{}" nil "»" ">>" "»" "»") + ("lsaquo" "\\guilsinglleft{}" nil "‹" "<" "<" "‹") + ("rsaquo" "\\guilsinglright{}" nil "›" ">" ">" "›") + + "* Other" + "** Misc. (often used)" + ("circ" "\\^{}" nil "ˆ" "^" "^" "∘") + ("vert" "\\vert{}" t "|" "|" "|" "|") + ("vbar" "|" nil "|" "|" "|" "|") + ("brvbar" "\\textbrokenbar{}" nil "¦" "|" "¦" "¦") + ("S" "\\S" nil "§" "paragraph" "§" "§") + ("sect" "\\S" nil "§" "paragraph" "§" "§") + ("amp" "\\&" nil "&" "&" "&" "&") + ("lt" "\\textless{}" nil "<" "<" "<" "<") + ("gt" "\\textgreater{}" nil ">" ">" ">" ">") + ("tilde" "\\textasciitilde{}" nil "~" "~" "~" "~") + ("slash" "/" nil "/" "/" "/" "/") + ("plus" "+" nil "+" "+" "+" "+") + ("under" "\\_" nil "_" "_" "_" "_") + ("equal" "=" nil "=" "=" "=" "=") + ("asciicirc" "\\textasciicircum{}" nil "^" "^" "^" "^") + ("dagger" "\\textdagger{}" nil "†" "[dagger]" "[dagger]" "†") + ("dag" "\\dag{}" nil "†" "[dagger]" "[dagger]" "†") + ("Dagger" "\\textdaggerdbl{}" nil "‡" "[doubledagger]" "[doubledagger]" "‡") + ("ddag" "\\ddag{}" nil "‡" "[doubledagger]" "[doubledagger]" "‡") + + "** Whitespace" + ("nbsp" "~" nil " " " " "\x00A0" "\x00A0") + ("ensp" "\\hspace*{.5em}" nil " " " " " " " ") + ("emsp" "\\hspace*{1em}" nil " " " " " " " ") + ("thinsp" "\\hspace*{.2em}" nil " " " " " " " ") + + "** Currency" + ("curren" "\\textcurrency{}" nil "¤" "curr." "¤" "¤") + ("cent" "\\textcent{}" nil "¢" "cent" "¢" "¢") + ("pound" "\\pounds{}" nil "£" "pound" "£" "£") + ("yen" "\\textyen{}" nil "¥" "yen" "Â¥" "Â¥") + ("euro" "\\texteuro{}" nil "€" "EUR" "EUR" "€") + ("EUR" "\\texteuro{}" nil "€" "EUR" "EUR" "€") + ("dollar" "\\$" nil "$" "$" "$" "$") + ("USD" "\\$" nil "$" "$" "$" "$") + + "** Property Marks" + ("copy" "\\textcopyright{}" nil "©" "(c)" "©" "©") + ("reg" "\\textregistered{}" nil "®" "(r)" "®" "®") + ("trade" "\\texttrademark{}" nil "™" "TM" "TM" "™") + + "** Science et al." + ("minus" "\\minus" t "−" "-" "-" "−") + ("pm" "\\textpm{}" nil "±" "+-" "±" "±") + ("plusmn" "\\textpm{}" nil "±" "+-" "±" "±") + ("times" "\\texttimes{}" nil "×" "*" "×" "×") + ("frasl" "/" nil "⁄" "/" "/" "⁄") + ("colon" "\\colon" t ":" ":" ":" ":") + ("div" "\\textdiv{}" nil "÷" "/" "÷" "÷") + ("frac12" "\\textonehalf{}" nil "½" "1/2" "½" "½") + ("frac14" "\\textonequarter{}" nil "¼" "1/4" "¼" "¼") + ("frac34" "\\textthreequarters{}" nil "¾" "3/4" "¾" "¾") + ("permil" "\\textperthousand{}" nil "‰" "per thousand" "per thousand" "‰") + ("sup1" "\\textonesuperior{}" nil "¹" "^1" "¹" "¹") + ("sup2" "\\texttwosuperior{}" nil "²" "^2" "²" "²") + ("sup3" "\\textthreesuperior{}" nil "³" "^3" "³" "³") + ("radic" "\\sqrt{\\,}" t "√" "[square root]" "[square root]" "√") + ("sum" "\\sum" t "∑" "[sum]" "[sum]" "∑") + ("prod" "\\prod" t "∏" "[product]" "[n-ary product]" "∏") + ("micro" "\\textmu{}" nil "µ" "micro" "µ" "µ") + ("macr" "\\textasciimacron{}" nil "¯" "[macron]" "¯" "¯") + ("deg" "\\textdegree{}" nil "°" "degree" "°" "°") + ("prime" "\\prime" t "′" "'" "'" "′") + ("Prime" "\\prime{}\\prime" t "″" "''" "''" "″") + ("infin" "\\infty" t "∞" "[infinity]" "[infinity]" "∞") + ("infty" "\\infty" t "∞" "[infinity]" "[infinity]" "∞") + ("prop" "\\propto" t "∝" "[proportional to]" "[proportional to]" "∝") + ("propto" "\\propto" t "∝" "[proportional to]" "[proportional to]" "∝") + ("not" "\\textlnot{}" nil "¬" "[angled dash]" "¬" "¬") + ("neg" "\\neg{}" t "¬" "[angled dash]" "¬" "¬") + ("land" "\\land" t "∧" "[logical and]" "[logical and]" "∧") + ("wedge" "\\wedge" t "∧" "[logical and]" "[logical and]" "∧") + ("lor" "\\lor" t "∨" "[logical or]" "[logical or]" "∨") + ("vee" "\\vee" t "∨" "[logical or]" "[logical or]" "∨") + ("cap" "\\cap" t "∩" "[intersection]" "[intersection]" "∩") + ("cup" "\\cup" t "∪" "[union]" "[union]" "∪") + ("smile" "\\smile" t "⌣" "[cup product]" "[cup product]" "⌣") + ("frown" "\\frown" t "⌢" "[Cap product]" "[cap product]" "⌢") + ("int" "\\int" t "∫" "[integral]" "[integral]" "∫") + ("therefore" "\\therefore" t "∴" "[therefore]" "[therefore]" "∴") + ("there4" "\\therefore" t "∴" "[therefore]" "[therefore]" "∴") + ("because" "\\because" t "∵" "[because]" "[because]" "∵") + ("sim" "\\sim" t "∼" "~" "~" "∼") + ("cong" "\\cong" t "≅" "[approx. equal to]" "[approx. equal to]" "≅") + ("simeq" "\\simeq" t "≅" "[approx. equal to]" "[approx. equal to]" "≅") + ("asymp" "\\asymp" t "≈" "[almost equal to]" "[almost equal to]" "≈") + ("approx" "\\approx" t "≈" "[almost equal to]" "[almost equal to]" "≈") + ("ne" "\\ne" t "≠" "[not equal to]" "[not equal to]" "≠") + ("neq" "\\neq" t "≠" "[not equal to]" "[not equal to]" "≠") + ("equiv" "\\equiv" t "≡" "[identical to]" "[identical to]" "≡") + + ("triangleq" "\\triangleq" t "≜" "[defined to]" "[defined to]" "≜") + ("le" "\\le" t "≤" "<=" "<=" "≤") + ("leq" "\\le" t "≤" "<=" "<=" "≤") + ("ge" "\\ge" t "≥" ">=" ">=" "≥") + ("geq" "\\ge" t "≥" ">=" ">=" "≥") + ("lessgtr" "\\lessgtr" t "≶" "[less than or greater than]" "[less than or greater than]" "≶") + ("lesseqgtr" "\\lesseqgtr" t "⋚" "[less than or equal or greater than or equal]" "[less than or equal or greater than or equal]" "⋚") + ("ll" "\\ll" t "≪" "<<" "<<" "≪") + ("Ll" "\\lll" t "⋘" "<<<" "<<<" "⋘") + ("lll" "\\lll" t "⋘" "<<<" "<<<" "⋘") + ("gg" "\\gg" t "≫" ">>" ">>" "≫") + ("Gg" "\\ggg" t "⋙" ">>>" ">>>" "⋙") + ("ggg" "\\ggg" t "⋙" ">>>" ">>>" "⋙") + ("prec" "\\prec" t "≺" "[precedes]" "[precedes]" "≺") + ("preceq" "\\preceq" t "≼" "[precedes or equal]" "[precedes or equal]" "≼") + ("preccurlyeq" "\\preccurlyeq" t "≼" "[precedes or equal]" "[precedes or equal]" "≼") + ("succ" "\\succ" t "≻" "[succeeds]" "[succeeds]" "≻") + ("succeq" "\\succeq" t "≽" "[succeeds or equal]" "[succeeds or equal]" "≽") + ("succcurlyeq" "\\succcurlyeq" t "≽" "[succeeds or equal]" "[succeeds or equal]" "≽") + ("sub" "\\subset" t "⊂" "[subset of]" "[subset of]" "⊂") + ("subset" "\\subset" t "⊂" "[subset of]" "[subset of]" "⊂") + ("sup" "\\supset" t "⊃" "[superset of]" "[superset of]" "⊃") + ("supset" "\\supset" t "⊃" "[superset of]" "[superset of]" "⊃") + ("nsub" "\\not\\subset" t "⊄" "[not a subset of]" "[not a subset of" "⊄") + ("sube" "\\subseteq" t "⊆" "[subset of or equal to]" "[subset of or equal to]" "⊆") + ("nsup" "\\not\\supset" t "⊅" "[not a superset of]" "[not a superset of]" "⊅") + ("supe" "\\supseteq" t "⊇" "[superset of or equal to]" "[superset of or equal to]" "⊇") + ("setminus" "\\setminus" t "∖" "\" "\" "â§µ") + ("forall" "\\forall" t "∀" "[for all]" "[for all]" "∀") + ("exist" "\\exists" t "∃" "[there exists]" "[there exists]" "∃") + ("exists" "\\exists" t "∃" "[there exists]" "[there exists]" "∃") + ("nexist" "\\nexists" t "∃" "[there does not exists]" "[there does not exists]" "∄") + ("nexists" "\\nexists" t "∃" "[there does not exists]" "[there does not exists]" "∄") + ("empty" "\\empty" t "∅" "[empty set]" "[empty set]" "∅") + ("emptyset" "\\emptyset" t "∅" "[empty set]" "[empty set]" "∅") + ("isin" "\\in" t "∈" "[element of]" "[element of]" "∈") + ("in" "\\in" t "∈" "[element of]" "[element of]" "∈") + ("notin" "\\notin" t "∉" "[not an element of]" "[not an element of]" "∉") + ("ni" "\\ni" t "∋" "[contains as member]" "[contains as member]" "∋") + ("nabla" "\\nabla" t "∇" "[nabla]" "[nabla]" "∇") + ("ang" "\\angle" t "∠" "[angle]" "[angle]" "∠") + ("angle" "\\angle" t "∠" "[angle]" "[angle]" "∠") + ("perp" "\\perp" t "⊥" "[up tack]" "[up tack]" "⊥") + ("parallel" "\\parallel" t "∥" "||" "||" "∥") + ("sdot" "\\cdot" t "⋅" "[dot]" "[dot]" "⋅") + ("cdot" "\\cdot" t "⋅" "[dot]" "[dot]" "⋅") + ("lceil" "\\lceil" t "⌈" "[left ceiling]" "[left ceiling]" "⌈") + ("rceil" "\\rceil" t "⌉" "[right ceiling]" "[right ceiling]" "⌉") + ("lfloor" "\\lfloor" t "⌊" "[left floor]" "[left floor]" "⌊") + ("rfloor" "\\rfloor" t "⌋" "[right floor]" "[right floor]" "⌋") + ("lang" "\\langle" t "⟨" "<" "<" "⟨") + ("rang" "\\rangle" t "⟩" ">" ">" "⟩") + ("langle" "\\langle" t "⟨" "<" "<" "⟨") + ("rangle" "\\rangle" t "⟩" ">" ">" "⟩") + ("hbar" "\\hbar" t "ℏ" "hbar" "hbar" "ℏ") + ("mho" "\\mho" t "℧" "mho" "mho" "℧") + + "** Arrows" + ("larr" "\\leftarrow" t "←" "<-" "<-" "←") + ("leftarrow" "\\leftarrow" t "←" "<-" "<-" "←") + ("gets" "\\gets" t "←" "<-" "<-" "←") + ("lArr" "\\Leftarrow" t "⇐" "<=" "<=" "⇐") + ("Leftarrow" "\\Leftarrow" t "⇐" "<=" "<=" "⇐") + ("uarr" "\\uparrow" t "↑" "[uparrow]" "[uparrow]" "↑") + ("uparrow" "\\uparrow" t "↑" "[uparrow]" "[uparrow]" "↑") + ("uArr" "\\Uparrow" t "⇑" "[dbluparrow]" "[dbluparrow]" "⇑") + ("Uparrow" "\\Uparrow" t "⇑" "[dbluparrow]" "[dbluparrow]" "⇑") + ("rarr" "\\rightarrow" t "→" "->" "->" "→") + ("to" "\\to" t "→" "->" "->" "→") + ("rightarrow" "\\rightarrow" t "→" "->" "->" "→") + ("rArr" "\\Rightarrow" t "⇒" "=>" "=>" "⇒") + ("Rightarrow" "\\Rightarrow" t "⇒" "=>" "=>" "⇒") + ("darr" "\\downarrow" t "↓" "[downarrow]" "[downarrow]" "↓") + ("downarrow" "\\downarrow" t "↓" "[downarrow]" "[downarrow]" "↓") + ("dArr" "\\Downarrow" t "⇓" "[dbldownarrow]" "[dbldownarrow]" "⇓") + ("Downarrow" "\\Downarrow" t "⇓" "[dbldownarrow]" "[dbldownarrow]" "⇓") + ("harr" "\\leftrightarrow" t "↔" "<->" "<->" "↔") + ("leftrightarrow" "\\leftrightarrow" t "↔" "<->" "<->" "↔") + ("hArr" "\\Leftrightarrow" t "⇔" "<=>" "<=>" "⇔") + ("Leftrightarrow" "\\Leftrightarrow" t "⇔" "<=>" "<=>" "⇔") + ("crarr" "\\hookleftarrow" t "↵" "<-'" "<-'" "↵") + ("hookleftarrow" "\\hookleftarrow" t "↵" "<-'" "<-'" "↵") + + "** Function names" + ("arccos" "\\arccos" t "arccos" "arccos" "arccos" "arccos") + ("arcsin" "\\arcsin" t "arcsin" "arcsin" "arcsin" "arcsin") + ("arctan" "\\arctan" t "arctan" "arctan" "arctan" "arctan") + ("arg" "\\arg" t "arg" "arg" "arg" "arg") + ("cos" "\\cos" t "cos" "cos" "cos" "cos") + ("cosh" "\\cosh" t "cosh" "cosh" "cosh" "cosh") + ("cot" "\\cot" t "cot" "cot" "cot" "cot") + ("coth" "\\coth" t "coth" "coth" "coth" "coth") + ("csc" "\\csc" t "csc" "csc" "csc" "csc") + ("deg" "\\deg" t "°" "deg" "deg" "deg") + ("det" "\\det" t "det" "det" "det" "det") + ("dim" "\\dim" t "dim" "dim" "dim" "dim") + ("exp" "\\exp" t "exp" "exp" "exp" "exp") + ("gcd" "\\gcd" t "gcd" "gcd" "gcd" "gcd") + ("hom" "\\hom" t "hom" "hom" "hom" "hom") + ("inf" "\\inf" t "inf" "inf" "inf" "inf") + ("ker" "\\ker" t "ker" "ker" "ker" "ker") + ("lg" "\\lg" t "lg" "lg" "lg" "lg") + ("lim" "\\lim" t "lim" "lim" "lim" "lim") + ("liminf" "\\liminf" t "liminf" "liminf" "liminf" "liminf") + ("limsup" "\\limsup" t "limsup" "limsup" "limsup" "limsup") + ("ln" "\\ln" t "ln" "ln" "ln" "ln") + ("log" "\\log" t "log" "log" "log" "log") + ("max" "\\max" t "max" "max" "max" "max") + ("min" "\\min" t "min" "min" "min" "min") + ("Pr" "\\Pr" t "Pr" "Pr" "Pr" "Pr") + ("sec" "\\sec" t "sec" "sec" "sec" "sec") + ("sin" "\\sin" t "sin" "sin" "sin" "sin") + ("sinh" "\\sinh" t "sinh" "sinh" "sinh" "sinh") + ("sup" "\\sup" t "⊃" "sup" "sup" "sup") + ("tan" "\\tan" t "tan" "tan" "tan" "tan") + ("tanh" "\\tanh" t "tanh" "tanh" "tanh" "tanh") + + "** Signs & Symbols" + ("bull" "\\textbullet{}" nil "•" "*" "*" "•") + ("bullet" "\\textbullet{}" nil "•" "*" "*" "•") + ("star" "\\star" t "*" "*" "*" "⋆") + ("lowast" "\\ast" t "∗" "*" "*" "∗") + ("ast" "\\ast" t "∗" "*" "*" "*") + ("odot" "\\odot" t "o" "[circled dot]" "[circled dot]" "ʘ") + ("oplus" "\\oplus" t "⊕" "[circled plus]" "[circled plus]" "⊕") + ("otimes" "\\otimes" t "⊗" "[circled times]" "[circled times]" "⊗") + ("check" "\\checkmark" t "✓" "[checkmark]" "[checkmark]" "✓") + ("checkmark" "\\checkmark" t "✓" "[checkmark]" "[checkmark]" "✓") + + "** Miscellaneous (seldom used)" + ("para" "\\P{}" nil "¶" "[pilcrow]" "¶" "¶") + ("ordf" "\\textordfeminine{}" nil "ª" "_a_" "ª" "ª") + ("ordm" "\\textordmasculine{}" nil "º" "_o_" "º" "º") + ("cedil" "\\c{}" nil "¸" "[cedilla]" "¸" "¸") + ("oline" "\\overline{~}" t "‾" "[overline]" "¯" "‾") + ("uml" "\\textasciidieresis{}" nil "¨" "[diaeresis]" "¨" "¨") + ("zwnj" "\\/{}" nil "‌" "" "" "‌") + ("zwj" "" nil "‍" "" "" "‍") + ("lrm" "" nil "‎" "" "" "‎") + ("rlm" "" nil "‏" "" "" "‏") + + "** Smilies" + ("smiley" "\\ddot\\smile" t "☺" ":-)" ":-)" "☺") + ("blacksmile" "\\ddot\\smile" t "☻" ":-)" ":-)" "☻") + ("sad" "\\ddot\\frown" t "☹" ":-(" ":-(" "☹") + ("frowny" "\\ddot\\frown" t "☹" ":-(" ":-(" "☹") + + "** Suits" + ("clubs" "\\clubsuit" t "♣" "[clubs]" "[clubs]" "♣") + ("clubsuit" "\\clubsuit" t "♣" "[clubs]" "[clubs]" "♣") + ("spades" "\\spadesuit" t "♠" "[spades]" "[spades]" "♠") + ("spadesuit" "\\spadesuit" t "♠" "[spades]" "[spades]" "♠") + ("hearts" "\\heartsuit" t "♥" "[hearts]" "[hearts]" "♥") + ("heartsuit" "\\heartsuit" t "♥" "[hearts]" "[hearts]" "♥") + ("diams" "\\diamondsuit" t "♦" "[diamonds]" "[diamonds]" "◆") + ("diamondsuit" "\\diamondsuit" t "♦" "[diamonds]" "[diamonds]" "◆") + ("diamond" "\\diamondsuit" t "⋄" "[diamond]" "[diamond]" "◆") + ("Diamond" "\\diamondsuit" t "⋄" "[diamond]" "[diamond]" "◆") + ("loz" "\\lozenge" t "◊" "[lozenge]" "[lozenge]" "â§«")) + ;; Add "\_ "-entity family for spaces. + (let (space-entities html-spaces (entity "_")) + (dolist (n (number-sequence 1 20) (nreverse space-entities)) + (let ((spaces (make-string n ?\s))) + (push (list (setq entity (concat entity " ")) + (format "\\hspace*{%sem}" (* n .5)) + nil + (setq html-spaces (concat " " html-spaces)) + spaces + spaces + (make-string n ?\x2002)) + space-entities))))) + "Default entities used in Org mode to produce special characters. +For details see `org-entities-user'.") + +(defsubst org-entity-get (name) + "Get the proper association for NAME from the entity lists. +This first checks the user list, then the built-in list." + (or (assoc name org-entities-user) + (assoc name org-entities))) + +;; Helpfunctions to create a table for orgmode.org/worg/org-symbols.org + +(defun org-entities-create-table () + "Create an Org mode table with all entities." + (interactive) + (let ((pos (point))) + (insert "|Name|LaTeX code|LaTeX|HTML code |HTML|ASCII|Latin1|UTF-8\n|-\n") + (dolist (e org-entities) + (pcase e + (`(,name ,latex ,mathp ,html ,ascii ,latin ,utf8) + (if (equal ascii "|") (setq ascii "\\vert")) + (if (equal latin "|") (setq latin "\\vert")) + (if (equal utf8 "|") (setq utf8 "\\vert")) + (if (equal ascii "=>") (setq ascii "= >")) + (if (equal latin "=>") (setq latin "= >")) + (insert "|" name + "|" (format "=%s=" latex) + "|" (format (if mathp "$%s$" "$\\mbox{%s}$") latex) + "|" (format "=%s=" html) "|" html + "|" ascii "|" latin "|" utf8 + "|\n")))) + (goto-char pos) + (org-table-align))) + +(defvar org-pretty-entities) ;; declare defcustom from org +(defun org-entities-help () + "Create a Help buffer with all available entities." + (interactive) + (with-output-to-temp-buffer "*Org Entity Help*" + (princ "Org mode entities\n=================\n\n") + (let ((ll (append '("* User-defined additions (variable org-entities-user)") + org-entities-user + org-entities)) + (lastwasstring t) + (head (concat + "\n" + " Symbol Org entity LaTeX code HTML code\n" + " -----------------------------------------------------------\n"))) + (dolist (e ll) + (pcase e + (`(,name ,latex ,_ ,html ,_ ,_ ,utf8) + (when lastwasstring + (princ head) + (setq lastwasstring nil)) + (princ (format " %-8s \\%-16s %-22s %-13s\n" + utf8 name latex html))) + ((pred stringp) + (princ e) + (princ "\n") + (setq lastwasstring t)))))) + (with-current-buffer "*Org Entity Help*" + (org-mode) + (when org-pretty-entities + (org-toggle-pretty-entities))) + (select-window (get-buffer-window "*Org Entity Help*"))) + + +(provide 'org-entities) + +;; Local variables: +;; coding: utf-8 +;; End: + +;;; org-entities.el ends here diff --git a/elpa/org-9.1.14/org-eshell.el b/elpa/org-9.1.14/org-eshell.el new file mode 100644 index 00000000..8a2e8af5 --- /dev/null +++ b/elpa/org-9.1.14/org-eshell.el @@ -0,0 +1,66 @@ +;;; org-eshell.el - Support for Links to Working Directories in Eshell -*- lexical-binding: t; -*- + +;; Copyright (C) 2011-2018 Free Software Foundation, Inc. + +;; Author: Konrad Hinsen + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: + +;;; Code: + +(require 'org) +(require 'eshell) +(require 'esh-mode) + +(org-link-set-parameters "eshell" + :follow #'org-eshell-open + :store #'org-eshell-store-link) + +(defun org-eshell-open (link) + "Switch to am eshell buffer and execute a command line. + The link can be just a command line (executed in the default + eshell buffer) or a command line prefixed by a buffer name + followed by a colon." + (let* ((buffer-and-command + (if (string-match "\\([A-Za-z0-9-+*]+\\):\\(.*\\)" link) + (list (match-string 1 link) + (match-string 2 link)) + (list eshell-buffer-name link))) + (eshell-buffer-name (car buffer-and-command)) + (command (cadr buffer-and-command))) + (if (get-buffer eshell-buffer-name) + (pop-to-buffer-same-window eshell-buffer-name) + (eshell)) + (goto-char (point-max)) + (eshell-kill-input) + (insert command) + (eshell-send-input))) + +(defun org-eshell-store-link () + "Store a link that, when opened, switches back to the current eshell buffer + and the current working directory." + (when (eq major-mode 'eshell-mode) + (let* ((command (concat "cd " dired-directory)) + (link (concat (buffer-name) ":" command))) + (org-store-link-props + :link (concat "eshell:" link) + :description command)))) + +(provide 'org-eshell) + +;;; org-eshell.el ends here diff --git a/elpa/org-9.1.14/org-eww.el b/elpa/org-9.1.14/org-eww.el new file mode 100644 index 00000000..34c4fca6 --- /dev/null +++ b/elpa/org-9.1.14/org-eww.el @@ -0,0 +1,176 @@ +;;; org-eww.el --- Store url and kill from Eww mode for Org -*- lexical-binding: t -*- + +;; Copyright (C) 2014-2018 Free Software Foundation, Inc. + +;; Author: Marco Wahl a +;; Keywords: link, eww +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + + +;;; Commentary: + +;; When this module is active `org-store-link' (often on key C-c l) in +;; an EWW buffer stores a link to the current url of the eww buffer. + +;; In an EWW buffer function `org-eww-copy-for-org-mode' kills either +;; a region or the whole buffer if no region is set and transforms the +;; text on the fly so that it can be pasted into an Org buffer with +;; hot links. + +;; C-c C-x C-w (and also C-c C-x M-w) trigger +;; `org-eww-copy-for-org-mode'. + +;; Hint: A lot of code of this module comes from module org-w3m which +;; has been written by Andy Steward based on the idea of Richard +;; Riley. Thanks! + +;; Potential: Since the code for w3m and eww is so similar one could +;; try to refactor. + + +;;; Code: +(require 'org) +(require 'cl-lib) + +(defvar eww-current-title) +(defvar eww-current-url) +(defvar eww-data) +(defvar eww-mode-map) + +(declare-function eww-current-url "eww") + + +;; Store Org-link in eww-mode buffer +(org-link-set-parameters "eww" :follow #'eww :store #'org-eww-store-link) +(defun org-eww-store-link () + "Store a link to the url of an EWW buffer." + (when (eq major-mode 'eww-mode) + (org-store-link-props + :type "eww" + :link (if (< emacs-major-version 25) + eww-current-url + (eww-current-url)) + :url (url-view-url t) + :description (if (< emacs-major-version 25) + (or eww-current-title eww-current-url) + (or (plist-get eww-data :title) + (eww-current-url)))))) + + +;; Some auxiliary functions concerning links in eww buffers +(defun org-eww-goto-next-url-property-change () + "Move to the start of next link if exists. +Otherwise point is not moved. Return point." + (goto-char + (or (next-single-property-change (point) 'shr-url) + (point)))) + +(defun org-eww-has-further-url-property-change-p () + "Non-nil if there is a next url property change." + (save-excursion + (not (eq (point) (org-eww-goto-next-url-property-change))))) + +(defun org-eww-url-below-point () + "Return the url below point if there is an url; otherwise, return nil." + (get-text-property (point) 'shr-url)) + + +(defun org-eww-copy-for-org-mode () + "Copy current buffer content or active region with `org-mode' style links. +This will encode `link-title' and `link-location' with +`org-make-link-string' and insert the transformed text into the +kill ring, so that it can be yanked into an Org mode buffer with +links working correctly. + +Further lines starting with a star get quoted with a comma to +keep the structure of the Org file." + (interactive) + (let* ((regionp (org-region-active-p)) + (transform-start (point-min)) + (transform-end (point-max)) + return-content + link-location link-title + temp-position out-bound) + (when regionp + (setq transform-start (region-beginning)) + (setq transform-end (region-end)) + ;; Deactivate mark if current mark is activate. + (when (fboundp 'deactivate-mark) (deactivate-mark))) + (message "Transforming links...") + (save-excursion + (goto-char transform-start) + (while (and (not out-bound) ; still inside region to copy + (org-eww-has-further-url-property-change-p)) ; there is a next link + ;; Store current point before jump next anchor. + (setq temp-position (point)) + ;; Move to next anchor when current point is not at anchor. + (or (org-eww-url-below-point) + (org-eww-goto-next-url-property-change)) + (cl-assert + (org-eww-url-below-point) t + "program logic error: point must have an url below but it hasn't") + (if (<= (point) transform-end) ; if point is inside transform bound + (progn + ;; Get content between two links. + (when (< temp-position (point)) + (setq return-content (concat return-content + (buffer-substring + temp-position (point))))) + ;; Get link location at current point. + (setq link-location (org-eww-url-below-point)) + ;; Get link title at current point. + (setq link-title + (buffer-substring + (point) + (org-eww-goto-next-url-property-change))) + ;; concat `org-mode' style url to `return-content'. + (setq return-content + (concat return-content + (if (org-string-nw-p link-location) + ;; Hint: link-location is different + ;; for form-elements. + (org-make-link-string link-location link-title) + link-title)))) + (goto-char temp-position) ; reset point before jump next anchor + (setq out-bound t))) ; for break out `while' loop + ;; Add the rest until end of the region to be copied. + (when (< (point) transform-end) + (setq return-content + (concat return-content + (buffer-substring (point) transform-end)))) + ;; Quote lines starting with *. + (org-kill-new (replace-regexp-in-string "^\\*" ",*" return-content)) + (message "Transforming links...done, use C-y to insert text into Org mode file")))) + + +;; Additional keys for eww-mode + +(defun org-eww-extend-eww-keymap () + (define-key eww-mode-map "\C-c\C-x\M-w" 'org-eww-copy-for-org-mode) + (define-key eww-mode-map "\C-c\C-x\C-w" 'org-eww-copy-for-org-mode)) + +(when (and (boundp 'eww-mode-map) + (keymapp eww-mode-map)) ; eww is already up. + (org-eww-extend-eww-keymap)) + +(add-hook 'eww-mode-hook #'org-eww-extend-eww-keymap) + + +(provide 'org-eww) + +;;; org-eww.el ends here diff --git a/elpa/org-9.1.14/org-faces.el b/elpa/org-9.1.14/org-faces.el new file mode 100644 index 00000000..750ada1e --- /dev/null +++ b/elpa/org-9.1.14/org-faces.el @@ -0,0 +1,653 @@ +;;; org-faces.el --- Face definitions -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: + +;; This file contains the face definitions for Org. + +;;; Code: + +(defgroup org-faces nil + "Faces in Org mode." + :tag "Org Faces" + :group 'org-appearance) + +(defface org-default '((t :inherit default)) + "Face used for default text." + :group 'org-faces) + +(defface org-hide + '((((background light)) (:foreground "white")) + (((background dark)) (:foreground "black"))) + "Face used to hide leading stars in headlines. +The foreground color of this face should be equal to the background +color of the frame." + :group 'org-faces) + +(defface org-level-1 '((t :inherit outline-1)) + "Face used for level 1 headlines." + :group 'org-faces) + +(defface org-level-2 '((t :inherit outline-2)) + "Face used for level 2 headlines." + :group 'org-faces) + +(defface org-level-3 '((t :inherit outline-3)) + "Face used for level 3 headlines." + :group 'org-faces) + +(defface org-level-4 '((t :inherit outline-4)) + "Face used for level 4 headlines." + :group 'org-faces) + +(defface org-level-5 '((t :inherit outline-5)) + "Face used for level 5 headlines." + :group 'org-faces) + +(defface org-level-6 '((t :inherit outline-6)) + "Face used for level 6 headlines." + :group 'org-faces) + +(defface org-level-7 '((t :inherit outline-7)) + "Face used for level 7 headlines." + :group 'org-faces) + +(defface org-level-8 '((t :inherit outline-8)) + "Face used for level 8 headlines." + :group 'org-faces) + +(defface org-special-keyword '((t :inherit font-lock-keyword-face)) + "Face used for special keywords." + :group 'org-faces) + +(defface org-drawer ;Copied from `font-lock-function-name-face' + '((((class color) (min-colors 88) (background light)) (:foreground "Blue1")) + (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue")) + (((class color) (min-colors 16) (background light)) (:foreground "Blue")) + (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue")) + (((class color) (min-colors 8)) (:foreground "blue" :bold t)) + (t (:bold t))) + "Face used for drawers." + :group 'org-faces) + +(defface org-property-value nil + "Face used for the value of a property." + :group 'org-faces) + +(defface org-column + '((((class color) (min-colors 16) (background light)) + (:background "grey90" :weight normal :slant normal :strike-through nil + :underline nil)) + (((class color) (min-colors 16) (background dark)) + (:background "grey30" :weight normal :slant normal :strike-through nil + :underline nil)) + (((class color) (min-colors 8)) + (:background "cyan" :foreground "black" + :weight normal :slant normal :strike-through nil + :underline nil)) + (t (:inverse-video t))) + "Face for column display of entry properties. +This is actually only part of the face definition for the text in column view. +The following faces apply, with this priority. + +1. The color of the reference face. This is normally the level fact that + is used in the outline. In agenda-mode, it will be the face of the + first character in the line. The color is explicitly retained to + make sure that the column line still looks a bit like the structure + line it is masking. + +2. The `org-column' face. + +3. The remaining properties of the reference face. + +Since column view works by putting overlays with a display property +over individual characters in the buffer, the face of the underlining +character (this might for example be the a TODO keyword) might still +shine through in some properties. So when your column view looks +funny, with \"random\" colors, weight, strike-through, try to explicitly +set the properties in the `org-column' face. For example, set +:underline to nil, or the :slant to `normal'." + :group 'org-faces) + +(defface org-column-title + '((((class color) (min-colors 16) (background light)) + (:background "grey90" :underline t :weight bold)) + (((class color) (min-colors 16) (background dark)) + (:background "grey30" :underline t :weight bold)) + (((class color) (min-colors 8)) + (:background "cyan" :foreground "black" :underline t :weight bold)) + (t (:inverse-video t))) + "Face for column display of entry properties." + :group 'org-faces) + +(defface org-agenda-column-dateline '((t :inherit org-column)) + "Face used in agenda column view for datelines with summaries." + :group 'org-faces) + +(defface org-warning '((t :inherit font-lock-warning-face)) + "Face for deadlines and TODO keywords." + :group 'org-faces) + +(defface org-archived '((t :inherit shadow)) + "Face for headline with the ARCHIVE tag." + :group 'org-faces) + +(defface org-link '((t :inherit link)) + "Face for links." + :group 'org-faces) + +(defface org-footnote + '((((class color) (background light)) (:foreground "Purple" :underline t)) + (((class color) (background dark)) (:foreground "Cyan" :underline t)) + (t (:underline t))) + "Face for footnotes." + :group 'org-faces) + +(defface org-ellipsis + '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t)) + (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t)) + (t (:strike-through t))) + "Face for the ellipsis in folded text." + :group 'org-faces) + +(defface org-target + '((((class color) (background light)) (:underline t)) + (((class color) (background dark)) (:underline t)) + (t (:underline t))) + "Face for link targets." + :group 'org-faces) + +(defface org-date + '((((class color) (background light)) (:foreground "Purple" :underline t)) + (((class color) (background dark)) (:foreground "Cyan" :underline t)) + (t (:underline t))) + "Face for date/time stamps." + :group 'org-faces) + +(defface org-date-selected + '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :inverse-video t)) + (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :inverse-video t)) + (((class color) (min-colors 8) (background light)) (:foreground "red" :inverse-video t)) + (((class color) (min-colors 8) (background dark)) (:foreground "red" :inverse-video t)) + (t (:inverse-video t))) + "Face for highlighting the calendar day when using `org-read-date'. +Using a bold face here might cause discrepancies while displaying the +calendar." + :group 'org-faces) + +(defface org-sexp-date + '((((class color) (background light)) (:foreground "Purple")) + (((class color) (background dark)) (:foreground "Cyan")) + (t (:underline t))) + "Face for diary-like sexp date specifications." + :group 'org-faces) + +(defface org-tag '((t (:bold t))) + "Default face for tags. +Note that the variable `org-tag-faces' can be used to overrule this face for +specific tags." + :group 'org-faces) + +(defface org-list-dt '((t (:bold t))) + "Default face for definition terms in lists." + :group 'org-faces) + +(defface org-todo ;Copied from `font-lock-warning-face' + '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t)) + (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t)) + (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t)) + (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t)) + (t (:inverse-video t :bold t))) + "Face for TODO keywords." + :group 'org-faces) + +(defface org-done ;Copied from `font-lock-type-face' + '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t)) + (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t)) + (((class color) (min-colors 8)) (:foreground "green")) + (t (:bold t))) + "Face used for todo keywords that indicate DONE items." + :group 'org-faces) + +(defface org-agenda-done ;Copied from `font-lock-type-face' + '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen")) + (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen")) + (((class color) (min-colors 8)) (:foreground "green")) + (t (:bold nil))) + "Face used in agenda, to indicate lines switched to DONE. +This face is used to de-emphasize items that where brightly colored in the +agenda because they were things to do, or overdue. The DONE state itself +is of course immediately visible, but for example a passed deadline is +\(by default) very bright read. This face could be simply the default face +of the frame, for example." + :group 'org-faces) + +(defface org-headline-done ;Copied from `font-lock-string-face' + '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown")) + (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon")) + (((class color) (min-colors 8) (background light)) (:bold nil))) + "Face used to indicate that a headline is DONE. +This face is only used if `org-fontify-done-headline' is set. If applies +to the part of the headline after the DONE keyword." + :group 'org-faces) + +(defcustom org-faces-easy-properties + '((todo . :foreground) (tag . :foreground) (priority . :foreground)) + "The property changes by easy faces. +This is an alist, the keys show the area of application, the values +can be `:foreground' or `:background'. A color string for special +keywords will then be interpreted as either foreground or background +color." + :group 'org-faces + :group 'org-todo + :version "24.1" + :type '(repeat + (cons (choice (const todo) (const tag) (const priority)) + (choice (const :foreground) (const :background))))) + +(defcustom org-todo-keyword-faces nil + "Faces for specific TODO keywords. +This is a list of cons cells, with TODO keywords in the car +and faces in the cdr. The face can be a symbol, a color +as a string (in which case the rest is inherited from the `org-todo' face), +or a property list of attributes, like + (:foreground \"blue\" :weight bold :underline t). +If it is a color string, the variable `org-faces-easy-properties' +determines if it is a foreground or a background color." + :group 'org-faces + :group 'org-todo + :type '(repeat + (cons + (string :tag "Keyword") + (choice :tag "Face " + (string :tag "Color") + (sexp :tag "Face"))))) + +(defface org-priority '((t :inherit font-lock-keyword-face)) + "Face used for priority cookies." + :group 'org-faces) + +(defcustom org-priority-faces nil + "Faces for specific Priorities. +This is a list of cons cells, with priority character in the car +and faces in the cdr. The face can be a symbol, a color +as a string, or a property list of attributes, like + (:foreground \"blue\" :weight bold :underline t). +If it is a color string, the variable `org-faces-easy-properties' +determines if it is a foreground or a background color." + :group 'org-faces + :group 'org-todo + :type '(repeat + (cons + (character :tag "Priority") + (choice :tag "Face " + (string :tag "Color") + (sexp :tag "Face"))))) + +(defvar org-tags-special-faces-re nil) +(defun org-set-tag-faces (var value) + (set var value) + (if (not value) + (setq org-tags-special-faces-re nil) + (setq org-tags-special-faces-re + (concat ":\\(" (mapconcat 'car value "\\|") "\\):")))) + +(defface org-checkbox '((t :inherit bold)) + "Face for checkboxes." + :group 'org-faces) + +(defface org-checkbox-statistics-todo '((t (:inherit org-todo))) + "Face used for unfinished checkbox statistics." + :group 'org-faces) + +(defface org-checkbox-statistics-done '((t (:inherit org-done))) + "Face used for finished checkbox statistics." + :group 'org-faces) + +(defcustom org-tag-faces nil + "Faces for specific tags. +This is a list of cons cells, with tags in the car and faces in the cdr. +The face can be a symbol, a foreground color (in which case the rest is +inherited from the `org-tag' face) or a property list of attributes, +like (:foreground \"blue\" :weight bold :underline t). +If you set this variable through customize, it will immediately be effective +in new buffers and in modified lines. +If you set it with Lisp, a restart of Emacs is required to activate the +changes." + :group 'org-faces + :group 'org-tags + :set 'org-set-tag-faces + :type '(repeat + (cons + (string :tag "Tag ") + (choice :tag "Face" + (string :tag "Foreground color") + (sexp :tag "Face"))))) + +(defface org-table ;Copied from `font-lock-function-name-face' + '((((class color) (min-colors 88) (background light)) (:foreground "Blue1")) + (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue")) + (((class color) (min-colors 16) (background light)) (:foreground "Blue")) + (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue")) + (((class color) (min-colors 8) (background light)) (:foreground "blue")) + (((class color) (min-colors 8) (background dark)))) + "Face used for tables." + :group 'org-faces) + +(defface org-formula + '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick")) + (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1")) + (((class color) (min-colors 8) (background light)) (:foreground "red")) + (((class color) (min-colors 8) (background dark)) (:foreground "red")) + (t (:bold t :italic t))) + "Face for formulas." + :group 'org-faces) + +(defface org-code '((t :inherit shadow)) + "Face for fixed-width text like code snippets." + :group 'org-faces + :version "22.1") + +(defface org-meta-line '((t :inherit font-lock-comment-face)) + "Face for meta lines starting with \"#+\"." + :group 'org-faces + :version "22.1") + +(defface org-document-title + '((((class color) (background light)) (:foreground "midnight blue" :weight bold)) + (((class color) (background dark)) (:foreground "pale turquoise" :weight bold)) + (t (:weight bold))) + "Face for document title, i.e. that which follows the #+TITLE: keyword." + :group 'org-faces) + +(defface org-document-info + '((((class color) (background light)) (:foreground "midnight blue")) + (((class color) (background dark)) (:foreground "pale turquoise")) + (t nil)) + "Face for document date, author and email; i.e. that which +follows a #+DATE:, #+AUTHOR: or #+EMAIL: keyword." + :group 'org-faces) + +(defface org-document-info-keyword '((t :inherit shadow)) + "Face for #+TITLE:, #+AUTHOR:, #+EMAIL: and #+DATE: keywords." + :group 'org-faces) + +(defface org-block '((t :inherit shadow)) + "Face text in #+begin ... #+end blocks. +For source-blocks `org-src-block-faces' takes precedence. +See also `org-fontify-quote-and-verse-blocks'." + :group 'org-faces + :version "26.1") + +(defface org-block-begin-line '((t (:inherit org-meta-line))) + "Face used for the line delimiting the begin of source blocks." + :group 'org-faces) + +(defface org-block-end-line '((t (:inherit org-block-begin-line))) + "Face used for the line delimiting the end of source blocks." + :group 'org-faces) + +(defface org-verbatim '((t (:inherit shadow))) + "Face for fixed-with text like code snippets" + :group 'org-faces + :version "22.1") + +(defface org-quote '((t (:inherit org-block))) + "Face for #+BEGIN_QUOTE ... #+END_QUOTE blocks." + :group 'org-faces) + +(defface org-verse '((t (:inherit org-block))) + "Face for #+BEGIN_VERSE ... #+END_VERSE blocks." + :group 'org-faces) + +(defcustom org-fontify-quote-and-verse-blocks nil + "Non-nil means, add a special face to #+begin_quote and #+begin_verse block. +When nil, format these as normal Org. This is the default, because the +content of these blocks will still be treated as Org syntax." + :group 'org-faces + :version "24.1" + :type 'boolean) + +(defface org-clock-overlay ;Copied from `secondary-selection' + '((((class color) (min-colors 88) (background light)) + (:background "LightGray" :foreground "black")) + (((class color) (min-colors 88) (background dark)) + (:background "SkyBlue4" :foreground "white")) + (((class color) (min-colors 16) (background light)) + (:background "gray" :foreground "black")) + (((class color) (min-colors 16) (background dark)) + (:background "SkyBlue4" :foreground "white")) + (((class color) (min-colors 8)) + (:background "cyan" :foreground "black")) + (t (:inverse-video t))) + "Basic face for displaying the secondary selection." + :group 'org-faces) + +(defface org-agenda-structure ;Copied from `font-lock-function-name-face' + '((((class color) (min-colors 88) (background light)) (:foreground "Blue1")) + (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue")) + (((class color) (min-colors 16) (background light)) (:foreground "Blue")) + (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue")) + (((class color) (min-colors 8)) (:foreground "blue" :bold t)) + (t (:bold t))) + "Face used in agenda for captions and dates." + :group 'org-faces) + +(defface org-agenda-date '((t (:inherit org-agenda-structure))) + "Face used in agenda for normal days." + :group 'org-faces) + +(defface org-agenda-date-today + '((t (:inherit org-agenda-date :weight bold :italic t))) + "Face used in agenda for today." + :group 'org-faces) + +(defface org-agenda-clocking '((t (:inherit secondary-selection))) + "Face marking the current clock item in the agenda." + :group 'org-faces) + +(defface org-agenda-date-weekend '((t (:inherit org-agenda-date :weight bold))) + "Face used in agenda for weekend days. + +See the variable `org-agenda-weekend-days' for a definition of +which days belong to the weekend." + :group 'org-faces) + +(defface org-scheduled + '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen")) + (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen")) + (((class color) (min-colors 8)) (:foreground "green")) + (t (:bold t :italic t))) + "Face for items scheduled for a certain day." + :group 'org-faces) + +(defface org-scheduled-today + '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen")) + (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen")) + (((class color) (min-colors 8)) (:foreground "green")) + (t (:bold t :italic t))) + "Face for items scheduled for a certain day." + :group 'org-faces) + +(defface org-agenda-dimmed-todo-face + '((((background light)) (:foreground "grey50")) + (((background dark)) (:foreground "grey50"))) + "Face used to dim blocked tasks in the agenda." + :group 'org-faces) + +(defface org-scheduled-previously + '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick")) + (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1")) + (((class color) (min-colors 8) (background light)) (:foreground "red")) + (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t)) + (t (:bold t))) + "Face for items scheduled previously, and not yet done." + :group 'org-faces) + +(defface org-upcoming-deadline + '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick")) + (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1")) + (((class color) (min-colors 8) (background light)) (:foreground "red")) + (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t)) + (t (:bold t))) + "Face for items scheduled previously, and not yet done." + :group 'org-faces) + +(defcustom org-agenda-deadline-faces + '((1.0 . org-warning) + (0.5 . org-upcoming-deadline) + (0.0 . default)) + "Faces for showing deadlines in the agenda. +This is a list of cons cells. The cdr of each cell is a face to be used, +and it can also just be like \\='(:foreground \"yellow\"). +Each car is a fraction of the head-warning time that must have passed for +this the face in the cdr to be used for display. The numbers must be +given in descending order. The head-warning time is normally taken +from `org-deadline-warning-days', but can also be specified in the deadline +timestamp itself, like this: + + DEADLINE: <2007-08-13 Mon -8d> + +You may use d for days, w for weeks, m for months and y for years. Months +and years will only be treated in an approximate fashion (30.4 days for a +month and 365.24 days for a year)." + :group 'org-faces + :group 'org-agenda-daily/weekly + :type '(repeat + (cons + (number :tag "Fraction of head-warning time passed") + (sexp :tag "Face")))) + +(defface org-agenda-restriction-lock + '((((class color) (min-colors 88) (background light)) (:background "#eeeeee")) + (((class color) (min-colors 88) (background dark)) (:background "#1C1C1C")) + (((class color) (min-colors 16) (background light)) (:background "#eeeeee")) + (((class color) (min-colors 16) (background dark)) (:background "#1C1C1C")) + (((class color) (min-colors 8)) (:background "cyan" :foreground "black")) + (t (:inverse-video t))) + "Face for showing the agenda restriction lock." + :group 'org-faces) + +(defface org-agenda-filter-tags '((t :inherit mode-line)) + "Face for tag(s) in the mode-line when filtering the agenda." + :group 'org-faces) + +(defface org-agenda-filter-regexp '((t :inherit mode-line)) + "Face for regexp(s) in the mode-line when filtering the agenda." + :group 'org-faces) + +(defface org-agenda-filter-category '((t :inherit mode-line)) + "Face for categories in the mode-line when filtering the agenda." + :group 'org-faces) + +(defface org-agenda-filter-effort '((t :inherit mode-line)) + "Face for effort in the mode-line when filtering the agenda." + :group 'org-faces) + +(defface org-time-grid ;Copied from `font-lock-variable-name-face' + '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod")) + (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod")) + (((class color) (min-colors 8)) (:foreground "yellow" :weight light))) + "Face used for time grids." + :group 'org-faces) + +(defface org-agenda-current-time '((t (:inherit org-time-grid))) + "Face used to show the current time in the time grid." + :group 'org-faces) + +(defface org-agenda-diary '((t :inherit default)) + "Face used for agenda entries that come from the Emacs diary." + :group 'org-faces) + +(defface org-agenda-calendar-event '((t :inherit default)) + "Face used to show events and appointments in the agenda." + :group 'org-faces) + +(defface org-agenda-calendar-sexp '((t :inherit default)) + "Face used to show events computed from a S-expression." + :group 'org-faces) + +(defconst org-level-faces + '(org-level-1 org-level-2 org-level-3 org-level-4 + org-level-5 org-level-6 org-level-7 org-level-8)) + +(defcustom org-n-level-faces (length org-level-faces) + "The number of different faces to be used for headlines. +Org mode defines 8 different headline faces, so this can be at most 8. +If it is less than 8, the level-1 face gets re-used for level N+1 etc." + :type 'integer + :group 'org-faces) + +(defcustom org-cycle-level-faces t + "Non-nil means level styles cycle after level `org-n-level-faces'. +Then so level org-n-level-faces+1 is styled like level 1. +If nil, then all levels >=org-n-level-faces are styled like +level org-n-level-faces" + :group 'org-appearance + :group 'org-faces + :version "24.1" + :type 'boolean) + +(defface org-latex-and-related + (let ((font (cond ((assq :inherit custom-face-attributes) + '(:inherit underline)) + (t '(:underline t))))) + `((((class grayscale) (background light)) + (:foreground "DimGray" ,@font)) + (((class grayscale) (background dark)) + (:foreground "LightGray" ,@font)) + (((class color) (background light)) + (:foreground "SaddleBrown")) + (((class color) (background dark)) + (:foreground "burlywood")) + (t (,@font)))) + "Face used to highlight LaTeX data, entities and sub/superscript." + :group 'org-faces + :version "24.4" + :package-version '(Org . "8.0")) + +(defface org-macro '((t :inherit org-latex-and-related)) + "Face for macros." + :group 'org-faces + :version "24.4" + :package-version '(Org . "8.0")) + +(defface org-tag-group '((t :inherit org-tag)) + "Face for group tags." + :group 'org-faces + :version "24.4" + :package-version '(Org . "8.0")) + +(defface org-mode-line-clock '((t (:inherit mode-line))) + "Face used for clock display in mode line." + :group 'org-faces) + +(defface org-mode-line-clock-overrun + '((t (:inherit mode-line :background "red"))) + "Face used for clock display for overrun tasks in mode line." + :group 'org-faces) + +(provide 'org-faces) + +;;; org-faces.el ends here diff --git a/elpa/org-9.1.14/org-feed.el b/elpa/org-9.1.14/org-feed.el new file mode 100644 index 00000000..fde19e63 --- /dev/null +++ b/elpa/org-9.1.14/org-feed.el @@ -0,0 +1,720 @@ +;;; org-feed.el --- Add RSS feed items to Org files -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Commentary: +;; +;; This module allows entries to be created and changed in an Org mode +;; file triggered by items in an RSS feed. The basic functionality +;; is geared toward simply adding new items found in a feed as +;; outline nodes to an Org file. Using hooks, arbitrary actions can +;; be triggered for new or changed items. +;; +;; Selecting feeds and target locations +;; ------------------------------------ +;; +;; This module is configured through a single variable, `org-feed-alist'. +;; Here is an example, using a notes/tasks feed from reQall.com. +;; +;; (setq org-feed-alist +;; '(("ReQall" +;; "http://www.reqall.com/user/feeds/rss/a1b2c3....." +;; "~/org/feeds.org" "ReQall Entries") +;; +;; With this setup, the command `M-x org-feed-update-all' will +;; collect new entries in the feed at the given URL and create +;; entries as subheadings under the "ReQall Entries" heading in the +;; file "~/org/feeds.org". Each feed should normally have its own +;; heading - however see the `:drawer' parameter. +;; +;; Besides these standard elements that need to be specified for each +;; feed, keyword-value pairs can set additional options. For example, +;; to de-select transitional entries with a title containing +;; +;; "reQall is typing what you said", +;; +;; you could use the `:filter' argument: +;; +;; (setq org-feed-alist +;; '(("ReQall" +;; "http://www.reqall.com/user/feeds/rss/a1b2c3....." +;; "~/org/feeds.org" "ReQall Entries" +;; :filter my-reqall-filter))) +;; +;; (defun my-reqall-filter (e) +;; (if (string-match "reQall is typing what you said" +;; (plist-get e :title)) +;; nil +;; e)) +;; +;; See the docstring for `org-feed-alist' for more details. +;; +;; +;; Keeping track of previously added entries +;; ----------------------------------------- +;; +;; Since Org allows you to delete, archive, or move outline nodes, +;; org-feed.el needs to keep track of which feed items have been handled +;; before, so that they will not be handled again. For this, org-feed.el +;; stores information in a special drawer, FEEDSTATUS, under the heading +;; that received the input of the feed. +;; +;; +;; Acknowledgments +;; --------------- +;; +;; org-feed.el is based on ideas by Brad Bozarth who implemented a +;; similar mechanism using shell and awk scripts. + +;;; Code: + +(require 'org) +(require 'sha1) + +(declare-function url-retrieve-synchronously "url" + (url &optional silent inhibit-cookies timeout)) +(declare-function xml-node-children "xml" (node)) +(declare-function xml-get-children "xml" (node child-name)) +(declare-function xml-get-attribute "xml" (node attribute)) +(declare-function xml-get-attribute-or-nil "xml" (node attribute)) +(declare-function xml-substitute-special "xml" (string)) + +(declare-function org-capture-escaped-% "org-capture" ()) +(declare-function org-capture-expand-embedded-elisp "org-capture" (&optional mark)) +(declare-function org-capture-inside-embedded-elisp-p "org-capture" ()) + +(defgroup org-feed nil + "Options concerning RSS feeds as inputs for Org files." + :tag "Org Feed" + :group 'org) + +(defcustom org-feed-alist nil + "Alist specifying RSS feeds that should create inputs for Org. +Each entry in this list specified an RSS feed tat should be queried +to create inbox items in Org. Each entry is a list with the following items: + +name a custom name for this feed +URL the Feed URL +file the target Org file where entries should be listed, when + nil the target becomes the current buffer (may be an + indirect buffer) each time the feed update is invoked +headline the headline under which entries should be listed + +Additional arguments can be given using keyword-value pairs. Many of these +specify functions that receive one or a list of \"entries\" as their single +argument. An entry is a property list that describes a feed item. The +property list has properties for each field in the item, for example `:title' +for the `' field and `:pubDate' for the publication date. In addition, +it contains the following properties: + +`:item-full-text' the full text in the <item> tag +`:guid-permalink' t when the guid property is a permalink + +Here are the keyword-value pair allows in `org-feed-alist'. + +:drawer drawer-name + The name of the drawer for storing feed information. The default is + \"FEEDSTATUS\". Using different drawers for different feeds allows + several feeds to target the same inbox heading. + +:filter filter-function + A function to select interesting entries in the feed. It gets a single + entry as parameter. It should return the entry if it is relevant, or + nil if it is not. + +:template template-string + The default action on new items in the feed is to add them as children + under the headline for the feed. The template describes how the entry + should be formatted. If not given, it defaults to + `org-feed-default-template'. + +:formatter formatter-function + Instead of relying on a template, you may specify a function to format + the outline node to be inserted as a child. This function gets passed + a property list describing a single feed item, and it should return a + string that is a properly formatted Org outline node of level 1. + +:new-handler function + If adding new items as children to the outline is not what you want + to do with new items, define a handler function that is called with + a list of all new items in the feed, each one represented as a property + list. The handler should do what needs to be done, and org-feed will + mark all items given to this handler as \"handled\", i.e. they will not + be passed to this handler again in future readings of the feed. + When the handler is called, point will be at the feed headline. + +:changed-handler function + This function gets passed a list of all entries that have been + handled before, but are now still in the feed and have *changed* + since last handled (as evidenced by a different sha1 hash). + When the handler is called, point will be at the feed headline. + +:parse-feed function + This function gets passed a buffer, and should return a list + of entries, each being a property list containing the + `:guid' and `:item-full-text' keys. The default is + `org-feed-parse-rss-feed'; `org-feed-parse-atom-feed' is an + alternative. + +:parse-entry function + This function gets passed an entry as returned by the parse-feed + function, and should return the entry with interesting properties added. + The default is `org-feed-parse-rss-entry'; `org-feed-parse-atom-entry' + is an alternative." + :group 'org-feed + :type '(repeat + (list :value ("" "http://" "" "") + (string :tag "Name") + (string :tag "Feed URL") + (file :tag "File for inbox") + (string :tag "Headline for inbox") + (repeat :inline t + (choice + (list :inline t :tag "Filter" + (const :filter) + (symbol :tag "Filter Function")) + (list :inline t :tag "Template" + (const :template) + (string :tag "Template")) + (list :inline t :tag "Formatter" + (const :formatter) + (symbol :tag "Formatter Function")) + (list :inline t :tag "New items handler" + (const :new-handler) + (symbol :tag "Handler Function")) + (list :inline t :tag "Changed items" + (const :changed-handler) + (symbol :tag "Handler Function")) + (list :inline t :tag "Parse Feed" + (const :parse-feed) + (symbol :tag "Parse Feed Function")) + (list :inline t :tag "Parse Entry" + (const :parse-entry) + (symbol :tag "Parse Entry Function")) + ))))) + +(defcustom org-feed-drawer "FEEDSTATUS" + "The name of the drawer for feed status information. +Each feed may also specify its own drawer name using the `:drawer' +parameter in `org-feed-alist'." + :group 'org-feed + :type '(string :tag "Drawer Name")) + +(defcustom org-feed-default-template "\n* %h\n %U\n %description\n %a\n" + "Template for the Org node created from RSS feed items. +This is just the default, each feed can specify its own. +Any fields from the feed item can be interpolated into the template with +%name, for example %title, %description, %pubDate etc. In addition, the +following special escapes are valid as well: + +%h The title, or the first line of the description +%t The date as a stamp, either from <pubDate> (if present), or + the current date +%T Date and time +%u,%U Like %t,%T, but inactive time stamps +%a A link, from <guid> if that is a permalink, else from <link> +%(sexp) Evaluate elisp `(sexp)' and replace with the result, the simple + %-escapes above can be used as arguments, e.g. %(capitalize \\\"%h\\\")" + :group 'org-feed + :type '(string :tag "Template")) + +(defcustom org-feed-save-after-adding t + "Non-nil means save buffer after adding new feed items." + :group 'org-feed + :type 'boolean) + +(defcustom org-feed-retrieve-method 'url-retrieve-synchronously + "The method to be used to retrieve a feed URL. +This can be `curl' or `wget' to call these external programs, or it can be +an Emacs Lisp function that will return a buffer containing the content +of the file pointed to by the URL." + :group 'org-feed + :type '(choice + (const :tag "Internally with url.el" url-retrieve-synchronously) + (const :tag "Externally with curl" curl) + (const :tag "Externally with wget" wget) + (function :tag "Function"))) + +(defcustom org-feed-before-adding-hook nil + "Hook that is run before adding new feed items to a file. +You might want to commit the file in its current state to version control, +for example." + :group 'org-feed + :type 'hook) + +(defcustom org-feed-after-adding-hook nil + "Hook that is run after new items have been added to a file. +Depending on `org-feed-save-after-adding', the buffer will already +have been saved." + :group 'org-feed + :type 'hook) + +(defvar org-feed-buffer "*Org feed*" + "The buffer used to retrieve a feed.") + +;;;###autoload +(defun org-feed-update-all () + "Get inbox items from all feeds in `org-feed-alist'." + (interactive) + (let ((entries 0) + (errors 0) + (total-feeds (length org-feed-alist))) + (dolist (feed org-feed-alist) + (let ((items (ignore-errors (org-feed-update feed)))) + (if items (cl-incf entries items) + (cl-incf errors)))) + (message "%s from %d %s%s" + (pcase entries + (0 "No new entries") + (1 "1 new entry") + (_ (format "%d new entries" entries))) + total-feeds + (if (= total-feeds 1) "feed" "feeds") + (if (= 0 errors) "" (format " (unavailable feeds: %d)" errors))))) + +;;;###autoload +(defun org-feed-update (feed &optional retrieve-only) + "Get inbox items from FEED. +FEED can be a string with an association in `org-feed-alist', or +it can be a list structured like an entry in `org-feed-alist'." + (interactive (list (org-completing-read "Feed name: " org-feed-alist))) + (if (stringp feed) (setq feed (assoc feed org-feed-alist))) + (unless feed + (error "No such feed in `org-feed-alist")) + (catch 'exit + (let ((name (car feed)) + (url (nth 1 feed)) + (file (or (nth 2 feed) (buffer-file-name (or (buffer-base-buffer) + (current-buffer))))) + (headline (nth 3 feed)) + (filter (nth 1 (memq :filter feed))) + (formatter (nth 1 (memq :formatter feed))) + (new-handler (nth 1 (memq :new-handler feed))) + (changed-handler (nth 1 (memq :changed-handler feed))) + (template (or (nth 1 (memq :template feed)) + org-feed-default-template)) + (drawer (or (nth 1 (memq :drawer feed)) + org-feed-drawer)) + (parse-feed (or (nth 1 (memq :parse-feed feed)) + 'org-feed-parse-rss-feed)) + (parse-entry (or (nth 1 (memq :parse-entry feed)) + 'org-feed-parse-rss-entry)) + feed-buffer inbox-pos new-formatted + entries old-status status new changed guid-alist guid olds) + (setq feed-buffer (org-feed-get-feed url)) + (unless (and feed-buffer (bufferp (get-buffer feed-buffer))) + (error "Cannot get feed %s" name)) + (when retrieve-only + (throw 'exit feed-buffer)) + (setq entries (funcall parse-feed feed-buffer)) + (ignore-errors (kill-buffer feed-buffer)) + (save-excursion + (save-window-excursion + (setq inbox-pos (org-feed-goto-inbox-internal file headline)) + (setq old-status (org-feed-read-previous-status inbox-pos drawer)) + ;; Add the "handled" status to the appropriate entries + (setq entries (mapcar (lambda (e) + (setq e + (plist-put e :handled + (nth 1 (assoc + (plist-get e :guid) + old-status))))) + entries)) + ;; Find out which entries are new and which are changed + (dolist (e entries) + (if (not (plist-get e :handled)) + (push e new) + (setq olds (nth 2 (assoc (plist-get e :guid) old-status))) + (if (and olds + (not (string= (sha1 + (plist-get e :item-full-text)) + olds))) + (push e changed)))) + + ;; Parse the relevant entries fully + (setq new (mapcar parse-entry new) + changed (mapcar parse-entry changed)) + + ;; Run the filter + (when filter + (setq new (delq nil (mapcar filter new)) + changed (delq nil (mapcar filter new)))) + + (when (not (or new changed)) + (message "No new items in feed %s" name) + (throw 'exit 0)) + + ;; Get alist based on guid, to look up entries + (setq guid-alist + (append + (mapcar (lambda (e) (list (plist-get e :guid) e)) new) + (mapcar (lambda (e) (list (plist-get e :guid) e)) changed))) + + ;; Construct the new status + (setq status + (mapcar + (lambda (e) + (setq guid (plist-get e :guid)) + (list guid + ;; things count as handled if we handle them now, + ;; or if they were handled previously + (if (assoc guid guid-alist) t (plist-get e :handled)) + ;; A hash, to detect changes + (sha1 (plist-get e :item-full-text)))) + entries)) + + ;; Handle new items in the feed + (when new + (if new-handler + (progn + (goto-char inbox-pos) + (funcall new-handler new)) + ;; No custom handler, do the default adding + ;; Format the new entries into an alist with GUIDs in the car + (setq new-formatted + (mapcar + (lambda (e) (org-feed-format-entry e template formatter)) + new))) + + ;; Insert the new items + (org-feed-add-items inbox-pos new-formatted)) + + ;; Handle changed items in the feed + (when (and changed-handler changed) + (goto-char inbox-pos) + (funcall changed-handler changed)) + + ;; Write the new status + ;; We do this only now, in case something goes wrong above, so + ;; that would would end up with a status that does not reflect + ;; which items truely have been handled + (org-feed-write-status inbox-pos drawer status) + + ;; Normalize the visibility of the inbox tree + (goto-char inbox-pos) + (outline-hide-subtree) + (org-show-children) + (org-cycle-hide-drawers 'children) + + ;; Hooks and messages + (when org-feed-save-after-adding (save-buffer)) + (message "Added %d new item%s from feed %s to file %s, heading %s" + (length new) (if (> (length new) 1) "s" "") + name + (file-name-nondirectory file) headline) + (run-hooks 'org-feed-after-adding-hook) + (length new)))))) + +;;;###autoload +(defun org-feed-goto-inbox (feed) + "Go to the inbox that captures the feed named FEED." + (interactive + (list (if (= (length org-feed-alist) 1) + (car org-feed-alist) + (org-completing-read "Feed name: " org-feed-alist)))) + (if (stringp feed) (setq feed (assoc feed org-feed-alist))) + (unless feed + (error "No such feed in `org-feed-alist")) + (org-feed-goto-inbox-internal (nth 2 feed) (nth 3 feed))) + +;;;###autoload +(defun org-feed-show-raw-feed (feed) + "Show the raw feed buffer of a feed." + (interactive + (list (if (= (length org-feed-alist) 1) + (car org-feed-alist) + (org-completing-read "Feed name: " org-feed-alist)))) + (if (stringp feed) (setq feed (assoc feed org-feed-alist))) + (unless feed + (error "No such feed in `org-feed-alist")) + (pop-to-buffer-same-window + (org-feed-update feed 'retrieve-only)) + (goto-char (point-min))) + +(defun org-feed-goto-inbox-internal (file heading) + "Find or create HEADING in FILE. +Switch to that buffer, and return the position of that headline." + (find-file file) + (widen) + (goto-char (point-min)) + (if (re-search-forward + (concat "^\\*+[ \t]+" heading "[ \t]*\\(:.*?:[ \t]*\\)?$") + nil t) + (goto-char (match-beginning 0)) + (goto-char (point-max)) + (insert "\n\n* " heading "\n\n") + (org-back-to-heading t)) + (point)) + +(defun org-feed-read-previous-status (pos drawer) + "Get the alist of old GUIDs from the entry at POS. +This will find DRAWER and extract the alist." + (save-excursion + (goto-char pos) + (let ((end (save-excursion (org-end-of-subtree t t)))) + (if (re-search-forward + (concat "^[ \t]*:" drawer ":[ \t]*\n\\([^\000]*?\\)\n[ \t]*:END:") + end t) + (read (match-string 1)) + nil)))) + +(defun org-feed-write-status (pos drawer status) + "Write the feed STATUS to DRAWER in entry at POS." + (save-excursion + (goto-char pos) + (let ((end (save-excursion (org-end-of-subtree t t)))) + (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*\n") + end t) + (progn + (goto-char (match-end 0)) + (delete-region (point) + (save-excursion + (and (re-search-forward "^[ \t]*:END:" nil t) + (match-beginning 0))))) + (outline-next-heading) + (insert " :" drawer ":\n :END:\n") + (beginning-of-line 0)) + (insert (pp-to-string status))))) + +(defun org-feed-add-items (pos entries) + "Add the formatted items to the headline as POS." + (let (entry level) + (save-excursion + (goto-char pos) + (unless (looking-at org-complex-heading-regexp) + (error "Wrong position")) + (setq level (org-get-valid-level (length (match-string 1)) 1)) + (org-end-of-subtree t t) + (skip-chars-backward " \t\n") + (beginning-of-line 2) + (setq pos (point)) + (while (setq entry (pop entries)) + (org-paste-subtree level entry 'yank)) + (org-mark-ring-push pos)))) + +(defun org-feed-format-entry (entry template formatter) + "Format ENTRY so that it can be inserted into an Org file. +ENTRY is a property list. This function adds a `:formatted-for-org' property +and returns the full property list. +If that property is already present, nothing changes." + (require 'org-capture) + (if formatter (funcall formatter entry) + (let* ((dlines + (org-split-string (or (plist-get entry :description) "???") + "\n")) + (time (or (if (plist-get entry :pubDate) + (org-read-date t t (plist-get entry :pubDate))) + (current-time))) + (v-h (or (plist-get entry :title) (car dlines) "???")) + (v-t (format-time-string (org-time-stamp-format nil nil) time)) + (v-T (format-time-string (org-time-stamp-format t nil) time)) + (v-u (format-time-string (org-time-stamp-format nil t) time)) + (v-U (format-time-string (org-time-stamp-format t t) time)) + (v-a (let ((tmp (or (and (plist-get entry :guid-permalink) + (plist-get entry :guid)) + (plist-get entry :link)))) + (if tmp (format "[[%s]]\n" tmp ) "")))) + (with-temp-buffer + (insert template) + (goto-char (point-min)) + + ;; Mark %() embedded elisp for later evaluation. + (org-capture-expand-embedded-elisp 'mark) + + ;; Simple %-escapes. `org-capture-escaped-%' may modify + ;; buffer and cripple match-data. Use markers instead. + (while (re-search-forward "%\\([a-zA-Z]+\\)" nil t) + (let ((key (match-string 1)) + (beg (copy-marker (match-beginning 0))) + (end (copy-marker (match-end 0)))) + (unless (org-capture-escaped-%) + (delete-region beg end) + (set-marker beg nil) + (set-marker end nil) + (let ((replacement + (pcase key + ("h" v-h) + ("t" v-t) + ("T" v-T) + ("u" v-u) + ("U" v-U) + ("a" v-a) + (name + (let ((v (plist-get entry (intern (concat ":" name))))) + (save-excursion + (save-match-data + (beginning-of-line) + (if (looking-at + (concat "^\\([ \t]*\\)%" name "[ \t]*$")) + (org-feed-make-indented-block + v (org-get-indentation)) + v)))))))) + (when replacement + (insert + ;; Escape string delimiters within embedded lisp. + (if (org-capture-inside-embedded-elisp-p) + (replace-regexp-in-string "\"" "\\\\\"" replacement) + replacement))))))) + + ;; %() embedded elisp + (org-capture-expand-embedded-elisp) + + (decode-coding-string + (buffer-string) (detect-coding-region (point-min) (point-max) t)))))) + +(defun org-feed-make-indented-block (s n) + "Add indentation of N spaces to a multiline string S." + (if (not (string-match "\n" s)) + s + (mapconcat 'identity + (org-split-string s "\n") + (concat "\n" (make-string n ?\ ))))) + +(defun org-feed-skip-http-headers (buffer) + "Remove HTTP headers from BUFFER, and return it. +Assumes headers are indeed present!" + (with-current-buffer buffer + (widen) + (goto-char (point-min)) + (search-forward "\n\n") + (delete-region (point-min) (point)) + buffer)) + +(defun org-feed-get-feed (url) + "Get the RSS feed file at URL and return the buffer." + (cond + ((eq org-feed-retrieve-method 'url-retrieve-synchronously) + (org-feed-skip-http-headers (url-retrieve-synchronously url))) + ((eq org-feed-retrieve-method 'curl) + (ignore-errors (kill-buffer org-feed-buffer)) + (call-process "curl" nil org-feed-buffer nil "--silent" url) + org-feed-buffer) + ((eq org-feed-retrieve-method 'wget) + (ignore-errors (kill-buffer org-feed-buffer)) + (call-process "wget" nil org-feed-buffer nil "-q" "-O" "-" url) + org-feed-buffer) + ((functionp org-feed-retrieve-method) + (funcall org-feed-retrieve-method url)))) + +(defun org-feed-parse-rss-feed (buffer) + "Parse BUFFER for RSS feed entries. +Returns a list of entries, with each entry a property list, +containing the properties `:guid' and `:item-full-text'." + (require 'xml) + (let ((case-fold-search t) + entries beg end item guid entry) + (with-current-buffer buffer + (widen) + (goto-char (point-min)) + (while (re-search-forward "<item\\>.*?>" nil t) + (setq beg (point) + end (and (re-search-forward "</item>" nil t) + (match-beginning 0))) + (setq item (buffer-substring beg end) + guid (if (string-match "<guid\\>.*?>\\([^\000]*?\\)</guid>" item) + (xml-substitute-special (match-string-no-properties 1 item)))) + (setq entry (list :guid guid :item-full-text item)) + (push entry entries) + (widen) + (goto-char end)) + (nreverse entries)))) + +(defun org-feed-parse-rss-entry (entry) + "Parse the `:item-full-text' field for xml tags and create new properties." + (require 'xml) + (with-temp-buffer + (insert (plist-get entry :item-full-text)) + (goto-char (point-min)) + (while (re-search-forward "<\\([a-zA-Z]+\\>\\).*?>\\([^\000]*?\\)</\\1>" + nil t) + (setq entry (plist-put entry + (intern (concat ":" (match-string 1))) + (xml-substitute-special (match-string 2))))) + (goto-char (point-min)) + (unless (re-search-forward "isPermaLink[ \t]*=[ \t]*\"false\"" nil t) + (setq entry (plist-put entry :guid-permalink t)))) + entry) + +(defun org-feed-parse-atom-feed (buffer) + "Parse BUFFER for Atom feed entries. +Returns a list of entries, with each entry a property list, +containing the properties `:guid' and `:item-full-text'. + +The `:item-full-text' property actually contains the sexp +formatted as a string, not the original XML data." + (require 'xml) + (with-current-buffer buffer + (widen) + (let ((feed (car (xml-parse-region (point-min) (point-max))))) + (mapcar + (lambda (entry) + (list + :guid (car (xml-node-children (car (xml-get-children entry 'id)))) + :item-full-text (prin1-to-string entry))) + (xml-get-children feed 'entry))))) + +(defun org-feed-parse-atom-entry (entry) + "Parse the `:item-full-text' as a sexp and create new properties." + (let ((xml (car (read-from-string (plist-get entry :item-full-text))))) + ;; Get first <link href='foo'/>. + (setq entry (plist-put entry :link + (xml-get-attribute + (car (xml-get-children xml 'link)) + 'href))) + ;; Add <title/> as :title. + (setq entry (plist-put entry :title + (xml-substitute-special + (car (xml-node-children + (car (xml-get-children xml 'title))))))) + (let* ((content (car (xml-get-children xml 'content))) + (type (xml-get-attribute-or-nil content 'type))) + (when content + (cond + ((string= type "text") + ;; We like plain text. + (setq entry (plist-put entry :description + (xml-substitute-special + (car (xml-node-children content)))))) + ((string= type "html") + ;; TODO: convert HTML to Org markup. + (setq entry (plist-put entry :description + (xml-substitute-special + (car (xml-node-children content)))))) + ((string= type "xhtml") + ;; TODO: convert XHTML to Org markup. + (setq entry (plist-put entry :description + (prin1-to-string + (xml-node-children content))))) + (t + (setq entry (plist-put entry :description + (format-message + "Unknown `%s' content." type))))))) + entry)) + +(provide 'org-feed) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-feed.el ends here diff --git a/elpa/org-9.1.14/org-footnote.el b/elpa/org-9.1.14/org-footnote.el new file mode 100644 index 00000000..c6376ca5 --- /dev/null +++ b/elpa/org-9.1.14/org-footnote.el @@ -0,0 +1,1005 @@ +;;; org-footnote.el --- Footnote support in Org -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file contains the code dealing with footnotes in Org mode. + +;;; Code: + +;;;; Declarations + +(require 'cl-lib) +(require 'org-macs) +(require 'org-compat) + +(declare-function org-at-comment-p "org" ()) +(declare-function org-at-heading-p "org" (&optional ignored)) +(declare-function org-back-over-empty-lines "org" ()) +(declare-function org-edit-footnote-reference "org-src" ()) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-class "org-element" (datum &optional parent)) +(declare-function org-element-context "org-element" (&optional element)) +(declare-function org-element-lineage "org-element" (blob &optional types with-self)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-type "org-element" (element)) +(declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading)) +(declare-function org-fill-paragraph "org" (&optional justify region)) +(declare-function org-in-block-p "org" (names)) +(declare-function org-in-regexp "org" (re &optional nlines visually)) +(declare-function org-in-verbatim-emphasis "org" ()) +(declare-function org-inside-LaTeX-fragment-p "org" ()) +(declare-function org-inside-latex-macro-p "org" ()) +(declare-function org-mark-ring-push "org" (&optional pos buffer)) +(declare-function org-show-context "org" (&optional key)) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function outline-next-heading "outline") + +(defvar electric-indent-mode) +(defvar org-blank-before-new-entry) ; defined in org.el +(defvar org-bracket-link-regexp) ; defined in org.el +(defvar org-complex-heading-regexp) ; defined in org.el +(defvar org-odd-levels-only) ; defined in org.el +(defvar org-outline-regexp) ; defined in org.el +(defvar org-outline-regexp-bol) ; defined in org.el + + +;;;; Constants + +(defconst org-footnote-re + "\\[fn:\\(?:\\(?1:[-_[:word:]]+\\)?\\(:\\)\\|\\(?1:[-_[:word:]]+\\)\\]\\)" + "Regular expression for matching footnotes. +Match group 1 contains footnote's label. It is nil for anonymous +footnotes. Match group 2 is non-nil only when footnote is +inline, i.e., it contains its own definition.") + +(defconst org-footnote-definition-re "^\\[fn:\\([-_[:word:]]+\\)\\]" + "Regular expression matching the definition of a footnote. +Match group 1 contains definition's label.") + +(defconst org-footnote-forbidden-blocks '("comment" "example" "export" "src") + "Names of blocks where footnotes are not allowed.") + + +;;;; Customization + +(defgroup org-footnote nil + "Footnotes in Org mode." + :tag "Org Footnote" + :group 'org) + +(defcustom org-footnote-section "Footnotes" + "Outline heading containing footnote definitions. + +This can be nil, to place footnotes locally at the end of the +current outline node. If can also be the name of a special +outline heading under which footnotes should be put. + +This variable defines the place where Org puts the definition +automatically, i.e. when creating the footnote, and when sorting +the notes. However, by hand you may place definitions +*anywhere*. + +If this is a string, during export, all subtrees starting with +this heading will be ignored. + +If you don't use the customize interface to change this variable, +you will need to run the following command after the change: + + `\\[universal-argument] \\[org-element-cache-reset]'" + :group 'org-footnote + :initialize 'custom-initialize-default + :set (lambda (var val) + (set var val) + (when (fboundp 'org-element-cache-reset) + (org-element-cache-reset 'all))) + :type '(choice + (string :tag "Collect footnotes under heading") + (const :tag "Define footnotes locally" nil))) + +(defcustom org-footnote-define-inline nil + "Non-nil means define footnotes inline, at reference location. +When nil, footnotes will be defined in a special section near +the end of the document. When t, the [fn:label:definition] notation +will be used to define the footnote at the reference position." + :group 'org-footnote + :type 'boolean) + +(defcustom org-footnote-auto-label t + "Non-nil means define automatically new labels for footnotes. +Possible values are: + +nil Prompt the user for each label. +t Create unique labels of the form [fn:1], [fn:2], etc. +confirm Like t, but let the user edit the created value. + The label can be removed from the minibuffer to create + an anonymous footnote. +random Automatically generate a unique, random label." + :group 'org-footnote + :type '(choice + (const :tag "Prompt for label" nil) + (const :tag "Create automatic [fn:N]" t) + (const :tag "Offer automatic [fn:N] for editing" confirm) + (const :tag "Create a random label" random))) + +(defcustom org-footnote-auto-adjust nil + "Non-nil means automatically adjust footnotes after insert/delete. +When this is t, after each insertion or deletion of a footnote, +simple fn:N footnotes will be renumbered, and all footnotes will be sorted. +If you want to have just sorting or just renumbering, set this variable +to `sort' or `renumber'. + +The main values of this variable can be set with in-buffer options: + +#+STARTUP: fnadjust +#+STARTUP: nofnadjust" + :group 'org-footnote + :type '(choice + (const :tag "No adjustment" nil) + (const :tag "Renumber" renumber) + (const :tag "Sort" sort) + (const :tag "Renumber and Sort" t))) + +(defcustom org-footnote-fill-after-inline-note-extraction nil + "Non-nil means fill paragraphs after extracting footnotes. +When extracting inline footnotes, the lengths of lines can change a lot. +When this option is set, paragraphs from which an inline footnote has been +extracted will be filled again." + :group 'org-footnote + :type 'boolean) + + +;;;; Predicates + +(defun org-footnote-in-valid-context-p () + "Is point in a context where footnotes are allowed?" + (save-match-data + (not (or (org-at-comment-p) + (org-inside-LaTeX-fragment-p) + ;; Avoid literal example. + (org-in-verbatim-emphasis) + (save-excursion + (beginning-of-line) + (looking-at "[ \t]*:[ \t]+")) + ;; Avoid forbidden blocks. + (org-in-block-p org-footnote-forbidden-blocks))))) + +(defun org-footnote-at-reference-p () + "Is the cursor at a footnote reference? + +If so, return a list containing its label, beginning and ending +positions, and the definition, when inlined." + (when (and (org-footnote-in-valid-context-p) + (or (looking-at org-footnote-re) + (org-in-regexp org-footnote-re) + (save-excursion (re-search-backward org-footnote-re nil t))) + (/= (match-beginning 0) (line-beginning-position))) + (let* ((beg (match-beginning 0)) + (label (match-string-no-properties 1)) + ;; Inline footnotes don't end at (match-end 0) as + ;; `org-footnote-re' stops just after the second colon. + ;; Find the real ending with `scan-sexps', so Org doesn't + ;; get fooled by unrelated closing square brackets. + (end (ignore-errors (scan-sexps beg 1)))) + ;; Point is really at a reference if it's located before true + ;; ending of the footnote. + (when (and end + (< (point) end) + ;; Verify match isn't a part of a link. + (not (save-excursion + (goto-char beg) + (let ((linkp + (save-match-data + (org-in-regexp org-bracket-link-regexp)))) + (and linkp (< (point) (cdr linkp)))))) + ;; Verify point doesn't belong to a LaTeX macro. + (not (org-inside-latex-macro-p))) + (list label beg end + ;; Definition: ensure this is an inline footnote first. + (and (match-end 2) + (org-trim + (buffer-substring-no-properties + (match-end 0) (1- end))))))))) + +(defun org-footnote-at-definition-p () + "Is point within a footnote definition? + +This matches only pure definitions like [1] or [fn:name] at the +beginning of a line. It does not match references like +\[fn:name:definition], where the footnote text is included and +defined locally. + +The return value will be nil if not at a footnote definition, and +a list with label, start, end and definition of the footnote +otherwise." + (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p)) + (save-excursion + (end-of-line) + ;; Footnotes definitions are separated by new headlines, another + ;; footnote definition or 2 blank lines. + (let ((lim (save-excursion + (re-search-backward + (concat org-outline-regexp-bol + "\\|^\\([ \t]*\n\\)\\{2,\\}") nil t)))) + (when (re-search-backward org-footnote-definition-re lim t) + (let ((label (match-string-no-properties 1)) + (beg (match-beginning 0)) + (beg-def (match-end 0)) + (end (if (progn + (end-of-line) + (re-search-forward + (concat org-outline-regexp-bol "\\|" + org-footnote-definition-re "\\|" + "^\\([ \t]*\n\\)\\{2,\\}") nil 'move)) + (match-beginning 0) + (point)))) + (list label beg end + (org-trim (buffer-substring-no-properties beg-def end))))))))) + + +;;;; Internal functions + +(defun org-footnote--allow-reference-p () + "Non-nil when a footnote reference can be inserted at point." + ;; XXX: This is similar to `org-footnote-in-valid-context-p' but + ;; more accurate and usually faster, except in some corner cases. + ;; It may replace it after doing proper benchmarks as it would be + ;; used in fontification. + (unless (bolp) + (let* ((context (org-element-context)) + (type (org-element-type context))) + (cond + ;; No footnote reference in attributes. + ((let ((post (org-element-property :post-affiliated context))) + (and post (< (point) post))) + nil) + ;; Paragraphs and blank lines at top of document are fine. + ((memq type '(nil paragraph))) + ;; So are contents of verse blocks. + ((eq type 'verse-block) + (and (>= (point) (org-element-property :contents-begin context)) + (< (point) (org-element-property :contents-end context)))) + ;; In an headline or inlinetask, point must be either on the + ;; heading itself or on the blank lines below. + ((memq type '(headline inlinetask)) + (or (not (org-at-heading-p)) + (and (save-excursion + (beginning-of-line) + (and (let ((case-fold-search t)) + (not (looking-at-p "\\*+ END[ \t]*$"))) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp)))) + (match-beginning 4) + (>= (point) (match-beginning 4)) + (or (not (match-beginning 5)) + (< (point) (match-beginning 5)))))) + ;; White spaces after an object or blank lines after an element + ;; are OK. + ((>= (point) + (save-excursion (goto-char (org-element-property :end context)) + (skip-chars-backward " \r\t\n") + (if (eq (org-element-class context) 'object) (point) + (1+ (line-beginning-position 2)))))) + ;; Other elements are invalid. + ((eq (org-element-class context) 'element) nil) + ;; Just before object is fine. + ((= (point) (org-element-property :begin context))) + ;; Within recursive object too, but not in a link. + ((eq type 'link) nil) + ((let ((cbeg (org-element-property :contents-begin context)) + (cend (org-element-property :contents-end context))) + (and cbeg (>= (point) cbeg) (<= (point) cend)))))))) + +(defun org-footnote--clear-footnote-section () + "Remove all footnote sections in buffer and create a new one. +New section is created at the end of the buffer, before any file +local variable definition. Leave point within the new section." + (when org-footnote-section + (goto-char (point-min)) + (let ((regexp + (format "^\\*+ +%s[ \t]*$" + (regexp-quote org-footnote-section)))) + (while (re-search-forward regexp nil t) + (delete-region + (match-beginning 0) + (progn (org-end-of-subtree t t) + (if (not (eobp)) (point) + (org-footnote--goto-local-insertion-point) + (skip-chars-forward " \t\n") + (if (eobp) (point) (line-beginning-position))))))) + (goto-char (point-max)) + (org-footnote--goto-local-insertion-point) + (when (and (cdr (assq 'heading org-blank-before-new-entry)) + (zerop (save-excursion (org-back-over-empty-lines)))) + (insert "\n")) + (insert "* " org-footnote-section "\n"))) + +(defun org-footnote--set-label (label) + "Set label of footnote at point to string LABEL. +Assume point is at the beginning of the reference or definition +to rename." + (forward-char 4) + (cond ((eq (char-after) ?:) (insert label)) + ((looking-at "\\([-_[:word:]]+\\)") (replace-match label nil nil nil 1)) + (t nil))) + +(defun org-footnote--collect-references (&optional anonymous) + "Collect all labeled footnote references in current buffer. + +Return an alist where associations follow the pattern + + (LABEL MARKER TOP-LEVEL SIZE) + +with + + LABEL the label of the of the definition, + MARKER a marker pointing to its beginning, + TOP-LEVEL a boolean, nil when the footnote is contained within + another one, + SIZE the length of the inline definition, in characters, + or nil for non-inline references. + +When optional ANONYMOUS is non-nil, also collect anonymous +references. In such cases, LABEL is nil. + +References are sorted according to a deep-reading order." + (org-with-wide-buffer + (goto-char (point-min)) + (let ((regexp (if anonymous org-footnote-re "\\[fn:[-_[:word:]]+[]:]")) + references nested) + (save-excursion + (while (re-search-forward regexp nil t) + ;; Ignore definitions. + (unless (and (eq (char-before) ?\]) + (= (line-beginning-position) (match-beginning 0))) + ;; Ensure point is within the reference before parsing it. + (backward-char) + (let ((object (org-element-context))) + (when (eq (org-element-type object) 'footnote-reference) + (let* ((label (org-element-property :label object)) + (begin (org-element-property :begin object)) + (size + (and (eq (org-element-property :type object) 'inline) + (- (org-element-property :contents-end object) + (org-element-property :contents-begin object))))) + (let ((d (org-element-lineage object '(footnote-definition)))) + (push (list label (copy-marker begin) (not d) size) + references) + (when d + ;; Nested references are stored in alist NESTED. + ;; Associations there follow the pattern + ;; + ;; (DEFINITION-LABEL . REFERENCES) + (let* ((def-label (org-element-property :label d)) + (labels (assoc def-label nested))) + (if labels (push label (cdr labels)) + (push (list def-label label) nested))))))))))) + ;; Sort the list of references. Nested footnotes have priority + ;; over top-level ones. + (letrec ((ordered nil) + (add-reference + (lambda (ref allow-nested) + (when (or allow-nested (nth 2 ref)) + (push ref ordered) + (dolist (r (mapcar (lambda (l) (assoc l references)) + (reverse + (cdr (assoc (nth 0 ref) nested))))) + (funcall add-reference r t)))))) + (dolist (r (reverse references) (nreverse ordered)) + (funcall add-reference r nil)))))) + +(defun org-footnote--collect-definitions (&optional delete) + "Collect all footnote definitions in current buffer. + +Return an alist where associations follow the pattern + + (LABEL . DEFINITION) + +with LABEL and DEFINITION being, respectively, the label and the +definition of the footnote, as strings. + +When optional argument DELETE is non-nil, delete the definition +while collecting them." + (org-with-wide-buffer + (goto-char (point-min)) + (let (definitions seen) + (while (re-search-forward org-footnote-definition-re nil t) + (backward-char) + (let ((element (org-element-at-point))) + (let ((label (org-element-property :label element))) + (when (and (eq (org-element-type element) 'footnote-definition) + (not (member label seen))) + (push label seen) + (let* ((beg (progn + (goto-char (org-element-property :begin element)) + (skip-chars-backward " \r\t\n") + (if (bobp) (point) (line-beginning-position 2)))) + (end (progn + (goto-char (org-element-property :end element)) + (skip-chars-backward " \r\t\n") + (line-beginning-position 2))) + (def (org-trim (buffer-substring-no-properties beg end)))) + (push (cons label def) definitions) + (when delete (delete-region beg end))))))) + definitions))) + +(defun org-footnote--goto-local-insertion-point () + "Find insertion point for footnote, just before next outline heading. +Assume insertion point is within currently accessible part of the buffer." + (org-with-limited-levels (outline-next-heading)) + ;; Skip file local variables. See `modify-file-local-variable'. + (when (eobp) + (let ((case-fold-search t)) + (re-search-backward "^[ \t]*# +Local Variables:" + (max (- (point-max) 3000) (point-min)) + t))) + (skip-chars-backward " \t\n") + (forward-line) + (unless (bolp) (insert "\n"))) + + +;;;; Navigation + +(defun org-footnote-get-next-reference (&optional label backward limit) + "Return complete reference of the next footnote. + +If LABEL is provided, get the next reference of that footnote. If +BACKWARD is non-nil, find previous reference instead. LIMIT is +the buffer position bounding the search. + +Return value is a list like those provided by `org-footnote-at-reference-p'. +If no footnote is found, return nil." + (save-excursion + (let* ((label-fmt (if label (format "\\[fn:%s[]:]" label) org-footnote-re))) + (catch 'exit + (while t + (unless (funcall (if backward #'re-search-backward #'re-search-forward) + label-fmt limit t) + (throw 'exit nil)) + (unless backward (backward-char)) + (let ((ref (org-footnote-at-reference-p))) + (when ref (throw 'exit ref)))))))) + +(defun org-footnote-next-reference-or-definition (limit) + "Move point to next footnote reference or definition. + +LIMIT is the buffer position bounding the search. + +Return value is a list like those provided by +`org-footnote-at-reference-p' or `org-footnote-at-definition-p'. +If no footnote is found, return nil." + (let* (ref (origin (point))) + (catch 'exit + (while t + (unless (re-search-forward org-footnote-re limit t) + (goto-char origin) + (throw 'exit nil)) + ;; Beware: with non-inline footnotes point will be just after + ;; the closing square bracket. + (backward-char) + (cond + ((setq ref (org-footnote-at-reference-p)) + (throw 'exit ref)) + ;; Definition: also grab the last square bracket, matched in + ;; `org-footnote-re' for non-inline footnotes. + ((save-match-data (org-footnote-at-definition-p)) + (let ((end (match-end 0))) + (throw 'exit + (list nil (match-beginning 0) + (if (eq (char-before end) ?\]) end (1+ end))))))))))) + +(defun org-footnote-goto-definition (label &optional location) + "Move point to the definition of the footnote LABEL. + +LOCATION, when non-nil specifies the buffer position of the +definition. + +Throw an error if there is no definition or if it cannot be +reached from current narrowed part of buffer. Return a non-nil +value if point was successfully moved." + (interactive "sLabel: ") + (let* ((label (org-footnote-normalize-label label)) + (def-start (or location (nth 1 (org-footnote-get-definition label))))) + (cond + ((not def-start) + (user-error "Cannot find definition of footnote %s" label)) + ((or (> def-start (point-max)) (< def-start (point-min))) + (user-error "Definition is outside narrowed part of buffer"))) + (org-mark-ring-push) + (goto-char def-start) + (looking-at (format "\\[fn:%s[]:] ?" (regexp-quote label))) + (goto-char (match-end 0)) + (org-show-context 'link-search) + (when (derived-mode-p 'org-mode) + (message "%s" (substitute-command-keys + "Edit definition and go back with \ +`\\[org-mark-ring-goto]' or, if unique, with `\\[org-ctrl-c-ctrl-c]'."))) + t)) + +(defun org-footnote-goto-previous-reference (label) + "Find the first closest (to point) reference of footnote with label LABEL." + (interactive "sLabel: ") + (org-mark-ring-push) + (let ((label (org-footnote-normalize-label label)) + ref) + (save-excursion + (setq ref (or (org-footnote-get-next-reference label t) + (org-footnote-get-next-reference label) + (save-restriction + (widen) + (or + (org-footnote-get-next-reference label t) + (org-footnote-get-next-reference label)))))) + (if (not ref) + (error "Cannot find reference of footnote %s" label) + (goto-char (nth 1 ref)) + (org-show-context 'link-search)))) + + +;;;; Getters + +(defun org-footnote-normalize-label (label) + "Return LABEL without \"fn:\" prefix. +If LABEL is the empty string or constituted of white spaces only, +return nil instead." + (pcase (org-trim label) + ("" nil) + ((pred (string-prefix-p "fn:")) (substring label 3)) + (_ label))) + +(defun org-footnote-get-definition (label) + "Return label, boundaries and definition of the footnote LABEL." + (let* ((label (regexp-quote (org-footnote-normalize-label label))) + (re (format "^\\[fn:%s\\]\\|.\\[fn:%s:" label label))) + (org-with-wide-buffer + (goto-char (point-min)) + (catch 'found + (while (re-search-forward re nil t) + (let* ((datum (progn (backward-char) (org-element-context))) + (type (org-element-type datum))) + (when (memq type '(footnote-definition footnote-reference)) + (throw 'found + (list + label + (org-element-property :begin datum) + (org-element-property :end datum) + (let ((cbeg (org-element-property :contents-begin datum))) + (if (not cbeg) "" + (replace-regexp-in-string + "[ \t\n]*\\'" + "" + (buffer-substring-no-properties + cbeg + (org-element-property :contents-end datum)))))))))) + nil)))) + +(defun org-footnote-all-labels () + "List all defined footnote labels used throughout the buffer. +This function ignores narrowing, if any." + (org-with-wide-buffer + (goto-char (point-min)) + (let (all) + (while (re-search-forward org-footnote-re nil t) + (backward-char) + (let ((context (org-element-context))) + (when (memq (org-element-type context) + '(footnote-definition footnote-reference)) + (let ((label (org-element-property :label context))) + (when label (cl-pushnew label all :test #'equal)))))) + all))) + +(defun org-footnote-unique-label (&optional current) + "Return a new unique footnote label. + +The function returns the first numeric label currently unused. + +Optional argument CURRENT is the list of labels active in the +buffer." + (let ((current (or current (org-footnote-all-labels)))) + (let ((count 1)) + (while (member (number-to-string count) current) + (cl-incf count)) + (number-to-string count)))) + + +;;;; Adding, Deleting Footnotes + +(defun org-footnote-new () + "Insert a new footnote. +This command prompts for a label. If this is a label referencing an +existing label, only insert the label. If the footnote label is empty +or new, let the user edit the definition of the footnote." + (interactive) + (unless (org-footnote--allow-reference-p) + (user-error "Cannot insert a footnote here")) + (let* ((all (org-footnote-all-labels)) + (label + (if (eq org-footnote-auto-label 'random) + (format "%x" (random most-positive-fixnum)) + (org-footnote-normalize-label + (let ((propose (org-footnote-unique-label all))) + (if (eq org-footnote-auto-label t) propose + (completing-read + "Label (leave empty for anonymous): " + (mapcar #'list all) nil nil + (and (eq org-footnote-auto-label 'confirm) propose)))))))) + (cond ((not label) + (insert "[fn::]") + (backward-char 1)) + ((member label all) + (insert "[fn:" label "]") + (message "New reference to existing note")) + (org-footnote-define-inline + (insert "[fn:" label ":]") + (backward-char 1) + (org-footnote-auto-adjust-maybe)) + (t + (insert "[fn:" label "]") + (let ((p (org-footnote-create-definition label))) + ;; `org-footnote-goto-definition' needs to be called + ;; after `org-footnote-auto-adjust-maybe'. Otherwise + ;; both label and location of the definition are lost. + ;; On the contrary, it needs to be called before + ;; `org-edit-footnote-reference' so that the remote + ;; editing buffer can display the correct label. + (if (ignore-errors (org-footnote-goto-definition label p)) + (org-footnote-auto-adjust-maybe) + ;; Definition was created outside current scope: edit + ;; it remotely. + (org-footnote-auto-adjust-maybe) + (org-edit-footnote-reference))))))) + +(defun org-footnote-create-definition (label) + "Start the definition of a footnote with label LABEL. +Return buffer position at the beginning of the definition. This +function doesn't move point." + (let ((label (org-footnote-normalize-label label)) + electric-indent-mode) ; Prevent wrong indentation. + (org-with-wide-buffer + (cond + ((not org-footnote-section) (org-footnote--goto-local-insertion-point)) + ((save-excursion + (goto-char (point-min)) + (re-search-forward + (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section) "[ \t]*$") + nil t)) + (goto-char (match-end 0)) + (forward-line) + (unless (bolp) (insert "\n"))) + (t (org-footnote--clear-footnote-section))) + (when (zerop (org-back-over-empty-lines)) (insert "\n")) + (insert "[fn:" label "] \n") + (line-beginning-position 0)))) + +(defun org-footnote-delete-references (label) + "Delete every reference to footnote LABEL. +Return the number of footnotes removed." + (save-excursion + (goto-char (point-min)) + (let (ref (nref 0)) + (while (setq ref (org-footnote-get-next-reference label)) + (goto-char (nth 1 ref)) + (delete-region (nth 1 ref) (nth 2 ref)) + (cl-incf nref)) + nref))) + +(defun org-footnote-delete-definitions (label) + "Delete every definition of the footnote LABEL. +Return the number of footnotes removed." + (save-excursion + (goto-char (point-min)) + (let ((def-re (format "^\\[fn:%s\\]" (regexp-quote label))) + (ndef 0)) + (while (re-search-forward def-re nil t) + (pcase (org-footnote-at-definition-p) + (`(,_ ,start ,end ,_) + ;; Remove the footnote, and all blank lines before it. + (delete-region (progn + (goto-char start) + (skip-chars-backward " \r\t\n") + (if (bobp) (point) (line-beginning-position 2))) + (progn + (goto-char end) + (skip-chars-backward " \r\t\n") + (if (bobp) (point) (line-beginning-position 2)))) + (cl-incf ndef)))) + ndef))) + +(defun org-footnote-delete (&optional label) + "Delete the footnote at point. +This will remove the definition (even multiple definitions if they exist) +and all references of a footnote label. + +If LABEL is non-nil, delete that footnote instead." + (catch 'done + (let* ((nref 0) (ndef 0) x + ;; 1. Determine LABEL of footnote at point. + (label (cond + ;; LABEL is provided as argument. + (label) + ;; Footnote reference at point. If the footnote is + ;; anonymous, delete it and exit instead. + ((setq x (org-footnote-at-reference-p)) + (or (car x) + (progn + (delete-region (nth 1 x) (nth 2 x)) + (message "Anonymous footnote removed") + (throw 'done t)))) + ;; Footnote definition at point. + ((setq x (org-footnote-at-definition-p)) + (car x)) + (t (error "Don't know which footnote to remove"))))) + ;; 2. Now that LABEL is non-nil, find every reference and every + ;; definition, and delete them. + (setq nref (org-footnote-delete-references label) + ndef (org-footnote-delete-definitions label)) + ;; 3. Verify consistency of footnotes and notify user. + (org-footnote-auto-adjust-maybe) + (message "%d definition(s) of and %d reference(s) of footnote %s removed" + ndef nref label)))) + + +;;;; Sorting, Renumbering, Normalizing + +(defun org-footnote-renumber-fn:N () + "Order numbered footnotes into a sequence in the document." + (interactive) + (let ((references (org-footnote--collect-references))) + (unwind-protect + (let* ((c 0) + (references (cl-remove-if-not + (lambda (r) (string-match-p "\\`[0-9]+\\'" (car r))) + references)) + (alist (mapcar (lambda (l) (cons l (number-to-string (cl-incf c)))) + (delete-dups (mapcar #'car references))))) + (org-with-wide-buffer + ;; Re-number references. + (dolist (ref references) + (goto-char (nth 1 ref)) + (org-footnote--set-label (cdr (assoc (nth 0 ref) alist)))) + ;; Re-number definitions. + (goto-char (point-min)) + (while (re-search-forward "^\\[fn:\\([0-9]+\\)\\]" nil t) + (replace-match (or (cdr (assoc (match-string 1) alist)) + ;; Un-referenced definitions get + ;; higher numbers. + (number-to-string (cl-incf c))) + nil nil nil 1)))) + (dolist (r references) (set-marker (nth 1 r) nil))))) + +(defun org-footnote-sort () + "Rearrange footnote definitions in the current buffer. +Sort footnote definitions so they match order of footnote +references. Also relocate definitions at the end of their +relative section or within a single footnote section, according +to `org-footnote-section'. Inline definitions are ignored." + (let ((references (org-footnote--collect-references))) + (unwind-protect + (let ((definitions (org-footnote--collect-definitions 'delete))) + (org-with-wide-buffer + (org-footnote--clear-footnote-section) + ;; Insert footnote definitions at the appropriate location, + ;; separated by a blank line. Each definition is inserted + ;; only once throughout the buffer. + (let (inserted) + (dolist (cell references) + (let ((label (car cell)) + (nested (not (nth 2 cell))) + (inline (nth 3 cell))) + (unless (or (member label inserted) inline) + (push label inserted) + (unless (or org-footnote-section nested) + ;; If `org-footnote-section' is non-nil, or + ;; reference is nested, point is already at the + ;; correct position. Otherwise, move at the + ;; appropriate location within the section + ;; containing the reference. + (goto-char (nth 1 cell)) + (org-footnote--goto-local-insertion-point)) + (insert "\n" + (or (cdr (assoc label definitions)) + (format "[fn:%s] DEFINITION NOT FOUND." label)) + "\n")))) + ;; Insert un-referenced footnote definitions at the end. + (let ((unreferenced + (cl-remove-if (lambda (d) (member (car d) inserted)) + definitions))) + (dolist (d unreferenced) (insert "\n" (cdr d) "\n")))))) + ;; Clear dangling markers in the buffer. + (dolist (r references) (set-marker (nth 1 r) nil))))) + +(defun org-footnote-normalize () + "Turn every footnote in buffer into a numbered one." + (interactive) + (let ((references (org-footnote--collect-references 'anonymous))) + (unwind-protect + (let ((n 0) + (translations nil) + (definitions nil)) + (org-with-wide-buffer + ;; Update label for reference. We need to do this before + ;; clearing definitions in order to rename nested footnotes + ;; before they are deleted. + (dolist (cell references) + (let* ((label (car cell)) + (anonymous (not label)) + (new + (cond + ;; In order to differentiate anonymous + ;; references from regular ones, set their + ;; labels to integers, not strings. + (anonymous (setcar cell (cl-incf n))) + ((cdr (assoc label translations))) + (t (let ((l (number-to-string (cl-incf n)))) + (push (cons label l) translations) + l))))) + (goto-char (nth 1 cell)) ; Move to reference's start. + (org-footnote--set-label + (if anonymous (number-to-string new) new)) + (let ((size (nth 3 cell))) + ;; Transform inline footnotes into regular references + ;; and retain their definition for later insertion as + ;; a regular footnote definition. + (when size + (let ((def (concat + (format "[fn:%s] " new) + (org-trim + (substring + (delete-and-extract-region + (point) (+ (point) size 1)) + 1))))) + (push (cons (if anonymous new label) def) definitions) + (when org-footnote-fill-after-inline-note-extraction + (org-fill-paragraph))))))) + ;; Collect definitions. Update labels according to ALIST. + (let ((definitions + (nconc definitions + (org-footnote--collect-definitions 'delete))) + (inserted)) + (org-footnote--clear-footnote-section) + (dolist (cell references) + (let* ((label (car cell)) + (anonymous (integerp label)) + (pos (nth 1 cell))) + ;; Move to appropriate location, if required. When + ;; there is a footnote section or reference is + ;; nested, point is already at the expected location. + (unless (or org-footnote-section (not (nth 2 cell))) + (goto-char pos) + (org-footnote--goto-local-insertion-point)) + ;; Insert new definition once label is updated. + (unless (member label inserted) + (push label inserted) + (let ((stored (cdr (assoc label definitions))) + ;; Anonymous footnotes' label is already + ;; up-to-date. + (new (if anonymous label + (cdr (assoc label translations))))) + (insert "\n" + (cond + ((not stored) + (format "[fn:%s] DEFINITION NOT FOUND." new)) + (anonymous stored) + (t + (replace-regexp-in-string + "\\`\\[fn:\\(.*?\\)\\]" new stored nil nil 1))) + "\n"))))) + ;; Insert un-referenced footnote definitions at the end. + (let ((unreferenced + (cl-remove-if (lambda (d) (member (car d) inserted)) + definitions))) + (dolist (d unreferenced) + (insert "\n" + (replace-regexp-in-string + org-footnote-definition-re + (format "[fn:%d]" (cl-incf n)) + (cdr d)) + "\n")))))) + ;; Clear dangling markers. + (dolist (r references) (set-marker (nth 1 r) nil))))) + +(defun org-footnote-auto-adjust-maybe () + "Renumber and/or sort footnotes according to user settings." + (when (memq org-footnote-auto-adjust '(t renumber)) + (org-footnote-renumber-fn:N)) + (when (memq org-footnote-auto-adjust '(t sort)) + (let ((label (car (org-footnote-at-definition-p)))) + (org-footnote-sort) + (when label + (goto-char (point-min)) + (and (re-search-forward (format "^\\[fn:%s\\]" (regexp-quote label)) + nil t) + (progn (insert " ") + (just-one-space))))))) + + +;;;; End-user interface + +;;;###autoload +(defun org-footnote-action (&optional special) + "Do the right thing for footnotes. + +When at a footnote reference, jump to the definition. + +When at a definition, jump to the references if they exist, offer +to create them otherwise. + +When neither at definition or reference, create a new footnote, +interactively if possible. + +With prefix arg SPECIAL, or when no footnote can be created, +offer additional commands in a menu." + (interactive "P") + (let* ((context (and (not special) (org-element-context))) + (type (org-element-type context))) + (cond + ;; On white space after element, insert a new footnote. + ((and context + (> (point) + (save-excursion + (goto-char (org-element-property :end context)) + (skip-chars-backward " \t") + (point)))) + (org-footnote-new)) + ((eq type 'footnote-reference) + (let ((label (org-element-property :label context))) + (cond + ;; Anonymous footnote: move point at the beginning of its + ;; definition. + ((not label) + (goto-char (org-element-property :contents-begin context))) + ;; Check if a definition exists: then move to it. + ((let ((p (nth 1 (org-footnote-get-definition label)))) + (when p (org-footnote-goto-definition label p)))) + ;; No definition exists: offer to create it. + ((yes-or-no-p (format "No definition for %s. Create one? " label)) + (let ((p (org-footnote-create-definition label))) + (or (ignore-errors (org-footnote-goto-definition label p)) + ;; Since definition was created outside current scope, + ;; edit it remotely. + (org-edit-footnote-reference))))))) + ((eq type 'footnote-definition) + (org-footnote-goto-previous-reference + (org-element-property :label context))) + ((or special (not (org-footnote--allow-reference-p))) + (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | [n]ormalize | \ +\[d]elete") + (pcase (read-char-exclusive) + (?s (org-footnote-sort)) + (?r (org-footnote-renumber-fn:N)) + (?S (org-footnote-renumber-fn:N) + (org-footnote-sort)) + (?n (org-footnote-normalize)) + (?d (org-footnote-delete)) + (char (error "No such footnote command %c" char)))) + (t (org-footnote-new))))) + + +(provide 'org-footnote) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-footnote.el ends here diff --git a/elpa/org-9.1.14/org-gnus.el b/elpa/org-9.1.14/org-gnus.el new file mode 100644 index 00000000..a53b343e --- /dev/null +++ b/elpa/org-9.1.14/org-gnus.el @@ -0,0 +1,268 @@ +;;; org-gnus.el --- Support for Links to Gnus Groups and Messages -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Tassilo Horn <tassilo at member dot fsf dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file implements links to Gnus groups and messages from within Org. +;; Org mode loads this module by default - if this is not what you want, +;; configure the variable `org-modules'. + +;;; Code: + +(require 'gnus-sum) +(require 'gnus-util) +(require 'nnheader) +(require 'nnir) +(require 'org) + + +;;; Declare external functions and variables + +(declare-function gnus-activate-group "gnus-start" (group &optional scan dont-check method dont-sub-check)) +(declare-function gnus-find-method-for-group "gnus" (group &optional info)) +(declare-function gnus-article-show-summary "gnus-art" ()) +(declare-function gnus-group-group-name "gnus-group") +(declare-function gnus-group-jump-to-group "gnus-group" (group &optional prompt)) +(declare-function gnus-group-read-group "gnus-group" (&optional all no-article group select-articles)) +(declare-function message-fetch-field "message" (header &optional not-all)) +(declare-function message-generate-headers "message" (headers)) +(declare-function message-narrow-to-headers "message") +(declare-function message-tokenize-header "message" (header &optional separator)) +(declare-function message-unquote-tokens "message" (elems)) +(declare-function nnvirtual-map-article "nnvirtual" (article)) + +(defvar gnus-newsgroup-name) +(defvar gnus-summary-buffer) +(defvar gnus-other-frame-object) + + +;;; Customization variables + +(defcustom org-gnus-prefer-web-links nil + "If non-nil, `org-store-link' creates web links to Google groups or Gmane. +\\<org-mode-map>When nil, Gnus will be used for such links. +Using a prefix argument to the command `\\[org-store-link]' (`org-store-link') +negates this setting for the duration of the command." + :group 'org-link-store + :type 'boolean) + +(defcustom org-gnus-no-server nil + "Should Gnus be started using `gnus-no-server'?" + :group 'org-gnus + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + + +;;; Install the link type + +(org-link-set-parameters "gnus" + :follow #'org-gnus-open + :store #'org-gnus-store-link) + +;;; Implementation + +(defun org-gnus-group-link (group) + "Create a link to the Gnus group GROUP. +If GROUP is a newsgroup and `org-gnus-prefer-web-links' is +non-nil, create a link to groups.google.com or gmane.org. +Otherwise create a link to the group inside Gnus. + +If `org-store-link' was called with a prefix arg the meaning of +`org-gnus-prefer-web-links' is reversed." + (let ((unprefixed-group (replace-regexp-in-string "^[^:]+:" "" group))) + (if (and (string-prefix-p "nntp" group) ;; Only for nntp groups + (org-xor current-prefix-arg + org-gnus-prefer-web-links)) + (concat (if (string-match "gmane" unprefixed-group) + "http://news.gmane.org/" + "http://groups.google.com/group/") + unprefixed-group) + (concat "gnus:" group)))) + +(defun org-gnus-article-link (group newsgroups message-id x-no-archive) + "Create a link to a Gnus article. +The article is specified by its MESSAGE-ID. Additional +parameters are the Gnus GROUP, the NEWSGROUPS the article was +posted to and the X-NO-ARCHIVE header value of that article. + +If GROUP is a newsgroup and `org-gnus-prefer-web-links' is +non-nil, create a link to groups.google.com or gmane.org. +Otherwise create a link to the article inside Gnus. + +If `org-store-link' was called with a prefix arg the meaning of +`org-gnus-prefer-web-links' is reversed." + (if (and (org-xor current-prefix-arg org-gnus-prefer-web-links) + newsgroups ;; Make web links only for nntp groups + (not x-no-archive)) ;; and if X-No-Archive isn't set. + (format (if (string-match "gmane\\." newsgroups) + "http://mid.gmane.org/%s" + "http://groups.google.com/groups/search?as_umsgid=%s") + (org-fixup-message-id-for-http message-id)) + (concat "gnus:" group "#" message-id))) + +(defun org-gnus-store-link () + "Store a link to a Gnus folder or message." + (pcase major-mode + (`gnus-group-mode + (let ((group (gnus-group-group-name))) + (when group + (org-store-link-props :type "gnus" :group group) + (let ((description (org-gnus-group-link group))) + (org-add-link-props :link description :description description) + description)))) + ((or `gnus-summary-mode `gnus-article-mode) + (let* ((group + (pcase (gnus-find-method-for-group gnus-newsgroup-name) + (`(nnvirtual . ,_) + (save-excursion + (car (nnvirtual-map-article (gnus-summary-article-number))))) + (`(nnir . ,_) + (save-excursion + (nnir-article-group (gnus-summary-article-number)))) + (_ gnus-newsgroup-name))) + (header (if (eq major-mode 'gnus-article-mode) + ;; When in an article, first move to summary + ;; buffer, with point on the summary of the + ;; current article before extracting headers. + (save-window-excursion + (save-excursion + (gnus-article-show-summary) + (gnus-summary-article-header))) + (gnus-summary-article-header))) + (from (mail-header-from header)) + (message-id (org-unbracket-string "<" ">" (mail-header-id header))) + (date (org-trim (mail-header-date header))) + ;; Remove text properties of subject string to avoid Emacs + ;; bug #3506. + (subject (org-no-properties + (copy-sequence (mail-header-subject header)))) + (to (cdr (assq 'To (mail-header-extra header)))) + newsgroups x-no-archive) + ;; Fetching an article is an expensive operation; newsgroup and + ;; x-no-archive are only needed for web links. + (when (org-xor current-prefix-arg org-gnus-prefer-web-links) + ;; Make sure the original article buffer is up-to-date. + (save-window-excursion (gnus-summary-select-article)) + (setq to (or to (gnus-fetch-original-field "To"))) + (setq newsgroups (gnus-fetch-original-field "Newsgroups")) + (setq x-no-archive (gnus-fetch-original-field "x-no-archive"))) + (org-store-link-props :type "gnus" :from from :date date :subject subject + :message-id message-id :group group :to to) + (let ((link (org-gnus-article-link + group newsgroups message-id x-no-archive)) + (description (org-email-link-description))) + (org-add-link-props :link link :description description) + link))) + (`message-mode + (setq org-store-link-plist nil) ;reset + (save-excursion + (save-restriction + (message-narrow-to-headers) + (unless (message-fetch-field "Message-ID") + (message-generate-headers '(Message-ID))) + (goto-char (point-min)) + (re-search-forward "^Message-ID:" nil t) + (put-text-property (line-beginning-position) (line-end-position) + 'message-deletable nil) + (let ((gcc (org-last (message-unquote-tokens + (message-tokenize-header + (mail-fetch-field "gcc" nil t) " ,")))) + (id (org-unbracket-string "<" ">" + (mail-fetch-field "Message-ID"))) + (to (mail-fetch-field "To")) + (from (mail-fetch-field "From")) + (subject (mail-fetch-field "Subject")) + newsgroup xarchive) ;those are always nil for gcc + (unless gcc (error "Can not create link: No Gcc header found")) + (org-store-link-props :type "gnus" :from from :subject subject + :message-id id :group gcc :to to) + (let ((link (org-gnus-article-link gcc newsgroup id xarchive)) + (description (org-email-link-description))) + (org-add-link-props :link link :description description) + link))))))) + +(defun org-gnus-open-nntp (path) + "Follow the nntp: link specified by PATH." + (let* ((spec (split-string path "/")) + (server (split-string (nth 2 spec) "@")) + (group (nth 3 spec)) + (article (nth 4 spec))) + (org-gnus-follow-link + (format "nntp+%s:%s" (or (cdr server) (car server)) group) + article))) + +(defun org-gnus-open (path) + "Follow the Gnus message or folder link specified by PATH." + (unless (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path) + (error "Error in Gnus link %S" path)) + (let ((group (match-string-no-properties 1 path)) + (article (match-string-no-properties 3 path))) + (org-gnus-follow-link group article))) + +(defun org-gnus-follow-link (&optional group article) + "Follow a Gnus link to GROUP and ARTICLE." + (require 'gnus) + (funcall (cdr (assq 'gnus org-link-frame-setup))) + (when gnus-other-frame-object (select-frame gnus-other-frame-object)) + (let ((group (org-no-properties group)) + (article (org-no-properties article))) + (cond + ((and group article) + (gnus-activate-group group) + (condition-case nil + (let ((msg "Couldn't follow Gnus link. Summary couldn't be opened.")) + (pcase (gnus-find-method-for-group group) + (`(nndoc . ,_) + (if (gnus-group-read-group t nil group) + (gnus-summary-goto-article article nil t) + (message msg))) + (_ + (let ((articles 1) + group-opened) + (while (and (not group-opened) + ;; Stop on integer overflows. + (> articles 0)) + (setq group-opened (gnus-group-read-group articles t group)) + (setq articles (if (< articles 16) + (1+ articles) + (* articles 2)))) + (if group-opened + (gnus-summary-goto-article article nil t) + (message msg)))))) + (quit + (message "Couldn't follow Gnus link. The linked group is empty.")))) + (group (gnus-group-jump-to-group group))))) + +(defun org-gnus-no-new-news () + "Like `\\[gnus]' but doesn't check for new news." + (cond ((gnus-alive-p) nil) + (org-gnus-no-server (gnus-no-server)) + (t (gnus)))) + +(provide 'org-gnus) + + +;;; org-gnus.el ends here diff --git a/elpa/org-9.1.14/org-habit.el b/elpa/org-9.1.14/org-habit.el new file mode 100644 index 00000000..375714e3 --- /dev/null +++ b/elpa/org-9.1.14/org-habit.el @@ -0,0 +1,442 @@ +;;; org-habit.el --- The habit tracking code for Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. + +;; Author: John Wiegley <johnw at gnu dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file contains the habit tracking code for Org mode + +;;; Code: + +(require 'cl-lib) +(require 'org) +(require 'org-agenda) + +(defgroup org-habit nil + "Options concerning habit tracking in Org mode." + :tag "Org Habit" + :group 'org-progress) + +(defcustom org-habit-graph-column 40 + "The absolute column at which to insert habit consistency graphs. +Note that consistency graphs will overwrite anything else in the buffer." + :group 'org-habit + :type 'integer) + +(defcustom org-habit-preceding-days 21 + "Number of days before today to appear in consistency graphs." + :group 'org-habit + :type 'integer) + +(defcustom org-habit-following-days 7 + "Number of days after today to appear in consistency graphs." + :group 'org-habit + :type 'integer) + +(defcustom org-habit-show-habits t + "If non-nil, show habits in agenda buffers." + :group 'org-habit + :type 'boolean) + +(defcustom org-habit-show-habits-only-for-today t + "If non-nil, only show habits on today's agenda, and not for future days. +Note that even when shown for future days, the graph is always +relative to the current effective date." + :group 'org-habit + :type 'boolean) + +(defcustom org-habit-show-all-today nil + "If non-nil, will show the consistency graph of all habits on +today's agenda, even if they are not scheduled." + :group 'org-habit + :type 'boolean) + +(defcustom org-habit-today-glyph ?! + "Glyph character used to identify today." + :group 'org-habit + :version "24.1" + :type 'character) + +(defcustom org-habit-completed-glyph ?* + "Glyph character used to show completed days on which a task was done." + :group 'org-habit + :version "24.1" + :type 'character) + +(defcustom org-habit-show-done-always-green nil + "Non-nil means DONE days will always be green in the consistency graph. +It will be green even if it was done after the deadline." + :group 'org-habit + :type 'boolean) + +(defface org-habit-clear-face + '((((background light)) (:background "#8270f9")) + (((background dark)) (:background "blue"))) + "Face for days on which a task shouldn't be done yet." + :group 'org-habit + :group 'org-faces) +(defface org-habit-clear-future-face + '((((background light)) (:background "#d6e4fc")) + (((background dark)) (:background "midnightblue"))) + "Face for future days on which a task shouldn't be done yet." + :group 'org-habit + :group 'org-faces) + +(defface org-habit-ready-face + '((((background light)) (:background "#4df946")) + (((background dark)) (:background "forestgreen"))) + "Face for days on which a task should start to be done." + :group 'org-habit + :group 'org-faces) +(defface org-habit-ready-future-face + '((((background light)) (:background "#acfca9")) + (((background dark)) (:background "darkgreen"))) + "Face for days on which a task should start to be done." + :group 'org-habit + :group 'org-faces) + +(defface org-habit-alert-face + '((((background light)) (:background "#f5f946")) + (((background dark)) (:background "gold"))) + "Face for days on which a task is due." + :group 'org-habit + :group 'org-faces) +(defface org-habit-alert-future-face + '((((background light)) (:background "#fafca9")) + (((background dark)) (:background "darkgoldenrod"))) + "Face for days on which a task is due." + :group 'org-habit + :group 'org-faces) + +(defface org-habit-overdue-face + '((((background light)) (:background "#f9372d")) + (((background dark)) (:background "firebrick"))) + "Face for days on which a task is overdue." + :group 'org-habit + :group 'org-faces) +(defface org-habit-overdue-future-face + '((((background light)) (:background "#fc9590")) + (((background dark)) (:background "darkred"))) + "Face for days on which a task is overdue." + :group 'org-habit + :group 'org-faces) + +(defun org-habit-duration-to-days (ts) + (if (string-match "\\([0-9]+\\)\\([dwmy]\\)" ts) + ;; lead time is specified. + (floor (* (string-to-number (match-string 1 ts)) + (cdr (assoc (match-string 2 ts) + '(("d" . 1) ("w" . 7) + ("m" . 30.4) ("y" . 365.25)))))) + (error "Invalid duration string: %s" ts))) + +(defun org-is-habit-p (&optional pom) + "Is the task at POM or point a habit?" + (string= "habit" (org-entry-get (or pom (point)) "STYLE"))) + +(defun org-habit-parse-todo (&optional pom) + "Parse the TODO surrounding point for its habit-related data. +Returns a list with the following elements: + + 0: Scheduled date for the habit (may be in the past) + 1: \".+\"-style repeater for the schedule, in days + 2: Optional deadline (nil if not present) + 3: If deadline, the repeater for the deadline, otherwise nil + 4: A list of all the past dates this todo was mark closed + 5: Repeater type as a string + +This list represents a \"habit\" for the rest of this module." + (save-excursion + (if pom (goto-char pom)) + (cl-assert (org-is-habit-p (point))) + (let* ((scheduled (org-get-scheduled-time (point))) + (scheduled-repeat (org-get-repeat (org-entry-get (point) "SCHEDULED"))) + (end (org-entry-end-position)) + (habit-entry (org-no-properties (nth 4 (org-heading-components)))) + closed-dates deadline dr-days sr-days sr-type) + (if scheduled + (setq scheduled (time-to-days scheduled)) + (error "Habit %s has no scheduled date" habit-entry)) + (unless scheduled-repeat + (error + "Habit `%s' has no scheduled repeat period or has an incorrect one" + habit-entry)) + (setq sr-days (org-habit-duration-to-days scheduled-repeat) + sr-type (progn (string-match "[\\.+]?\\+" scheduled-repeat) + (match-string-no-properties 0 scheduled-repeat))) + (unless (> sr-days 0) + (error "Habit %s scheduled repeat period is less than 1d" habit-entry)) + (when (string-match "/\\([0-9]+[dwmy]\\)" scheduled-repeat) + (setq dr-days (org-habit-duration-to-days + (match-string-no-properties 1 scheduled-repeat))) + (if (<= dr-days sr-days) + (error "Habit %s deadline repeat period is less than or equal to scheduled (%s)" + habit-entry scheduled-repeat)) + (setq deadline (+ scheduled (- dr-days sr-days)))) + (org-back-to-heading t) + (let* ((maxdays (+ org-habit-preceding-days org-habit-following-days)) + (reversed org-log-states-order-reversed) + (search (if reversed 're-search-forward 're-search-backward)) + (limit (if reversed end (point))) + (count 0) + (re (format + "^[ \t]*-[ \t]+\\(?:State \"%s\".*%s%s\\)" + (regexp-opt org-done-keywords) + org-ts-regexp-inactive + (let ((value (cdr (assq 'done org-log-note-headings)))) + (if (not value) "" + (concat "\\|" + (org-replace-escapes + (regexp-quote value) + `(("%d" . ,org-ts-regexp-inactive) + ("%D" . ,org-ts-regexp) + ("%s" . "\"\\S-+\"") + ("%S" . "\"\\S-+\"") + ("%t" . ,org-ts-regexp-inactive) + ("%T" . ,org-ts-regexp) + ("%u" . ".*?") + ("%U" . ".*?"))))))))) + (unless reversed (goto-char end)) + (while (and (< count maxdays) (funcall search re limit t)) + (push (time-to-days + (org-time-string-to-time + (or (match-string-no-properties 1) + (match-string-no-properties 2)))) + closed-dates) + (setq count (1+ count)))) + (list scheduled sr-days deadline dr-days closed-dates sr-type)))) + +(defsubst org-habit-scheduled (habit) + (nth 0 habit)) +(defsubst org-habit-scheduled-repeat (habit) + (nth 1 habit)) +(defsubst org-habit-deadline (habit) + (let ((deadline (nth 2 habit))) + (or deadline + (if (nth 3 habit) + (+ (org-habit-scheduled habit) + (1- (org-habit-scheduled-repeat habit))) + (org-habit-scheduled habit))))) +(defsubst org-habit-deadline-repeat (habit) + (or (nth 3 habit) + (org-habit-scheduled-repeat habit))) +(defsubst org-habit-done-dates (habit) + (nth 4 habit)) +(defsubst org-habit-repeat-type (habit) + (nth 5 habit)) + +(defsubst org-habit-get-priority (habit &optional moment) + "Determine the relative priority of a habit. +This must take into account not just urgency, but consistency as well." + (let ((pri 1000) + (now (if moment (time-to-days moment) (org-today))) + (scheduled (org-habit-scheduled habit)) + (deadline (org-habit-deadline habit))) + ;; add 10 for every day past the scheduled date, and subtract for every + ;; day before it + (setq pri (+ pri (* (- now scheduled) 10))) + ;; add 50 if the deadline is today + (if (and (/= scheduled deadline) + (= now deadline)) + (setq pri (+ pri 50))) + ;; add 100 for every day beyond the deadline date, and subtract 10 for + ;; every day before it + (let ((slip (- now (1- deadline)))) + (if (> slip 0) + (setq pri (+ pri (* slip 100))) + (setq pri (+ pri (* slip 10))))) + pri)) + +(defun org-habit-get-faces (habit &optional now-days scheduled-days donep) + "Return faces for HABIT relative to NOW-DAYS and SCHEDULED-DAYS. +NOW-DAYS defaults to the current time's days-past-the-epoch if nil. +SCHEDULED-DAYS defaults to the habit's actual scheduled days if nil. + +Habits are assigned colors on the following basis: + Blue Task is before the scheduled date. + Green Task is on or after scheduled date, but before the + end of the schedule's repeat period. + Yellow If the task has a deadline, then it is after schedule's + repeat period, but before the deadline. + Orange The task has reached the deadline day, or if there is + no deadline, the end of the schedule's repeat period. + Red The task has gone beyond the deadline day or the + schedule's repeat period." + (let* ((scheduled (or scheduled-days (org-habit-scheduled habit))) + (s-repeat (org-habit-scheduled-repeat habit)) + (d-repeat (org-habit-deadline-repeat habit)) + (deadline (if scheduled-days + (+ scheduled-days (- d-repeat s-repeat)) + (org-habit-deadline habit))) + (m-days (or now-days (time-to-days (current-time))))) + (cond + ((< m-days scheduled) + '(org-habit-clear-face . org-habit-clear-future-face)) + ((< m-days deadline) + '(org-habit-ready-face . org-habit-ready-future-face)) + ((= m-days deadline) + (if donep + '(org-habit-ready-face . org-habit-ready-future-face) + '(org-habit-alert-face . org-habit-alert-future-face))) + ((and org-habit-show-done-always-green donep) + '(org-habit-ready-face . org-habit-ready-future-face)) + (t '(org-habit-overdue-face . org-habit-overdue-future-face))))) + +(defun org-habit-build-graph (habit starting current ending) + "Build a graph for the given HABIT, from STARTING to ENDING. +CURRENT gives the current time between STARTING and ENDING, for +the purpose of drawing the graph. It need not be the actual +current time." + (let* ((all-done-dates (sort (org-habit-done-dates habit) #'<)) + (done-dates all-done-dates) + (scheduled (org-habit-scheduled habit)) + (s-repeat (org-habit-scheduled-repeat habit)) + (start (time-to-days starting)) + (now (time-to-days current)) + (end (time-to-days ending)) + (graph (make-string (1+ (- end start)) ?\s)) + (index 0) + last-done-date) + (while (and done-dates (< (car done-dates) start)) + (setq last-done-date (car done-dates) + done-dates (cdr done-dates))) + (while (< start end) + (let* ((in-the-past-p (< start now)) + (todayp (= start now)) + (donep (and done-dates (= start (car done-dates)))) + (faces + (if (and in-the-past-p + (not last-done-date) + (not (< scheduled now))) + '(org-habit-clear-face . org-habit-clear-future-face) + (org-habit-get-faces + habit start + (and in-the-past-p + last-done-date + ;; Compute scheduled time for habit at the time + ;; START was current. + (let ((type (org-habit-repeat-type habit))) + (cond + ;; At the last done date, use current + ;; scheduling in all cases. + ((null done-dates) scheduled) + ((equal type ".+") (+ last-done-date s-repeat)) + ((equal type "+") + ;; Since LAST-DONE-DATE, each done mark + ;; shifted scheduled date by S-REPEAT. + (- scheduled (* (length done-dates) s-repeat))) + (t + ;; Compute the scheduled time after the + ;; first repeat. This is the closest time + ;; past FIRST-DONE which can reach SCHEDULED + ;; by a number of S-REPEAT hops. + ;; + ;; Then, play TODO state change history from + ;; the beginning in order to find current + ;; scheduled time. + (let* ((first-done (car all-done-dates)) + (s (let ((shift (mod (- scheduled first-done) + s-repeat))) + (+ (if (= shift 0) s-repeat shift) + first-done)))) + (if (= first-done last-done-date) s + (catch :exit + (dolist (done (cdr all-done-dates) s) + ;; Each repeat shifts S by any + ;; number of S-REPEAT hops it takes + ;; to get past DONE, with a minimum + ;; of one hop. + (cl-incf s (* (1+ (/ (max (- done s) 0) + s-repeat)) + s-repeat)) + (when (= done last-done-date) + (throw :exit s)))))))))) + donep))) + markedp face) + (if donep + (let ((done-time (time-add + starting + (days-to-time + (- start (time-to-days starting)))))) + + (aset graph index org-habit-completed-glyph) + (setq markedp t) + (put-text-property + index (1+ index) 'help-echo + (format-time-string (org-time-stamp-format) done-time) graph) + (while (and done-dates + (= start (car done-dates))) + (setq last-done-date (car done-dates) + done-dates (cdr done-dates)))) + (if todayp + (aset graph index org-habit-today-glyph))) + (setq face (if (or in-the-past-p todayp) + (car faces) + (cdr faces))) + (if (and in-the-past-p + (not (eq face 'org-habit-overdue-face)) + (not markedp)) + (setq face (cdr faces))) + (put-text-property index (1+ index) 'face face graph)) + (setq start (1+ start) + index (1+ index))) + graph)) + +(defun org-habit-insert-consistency-graphs (&optional line) + "Insert consistency graph for any habitual tasks." + (let ((inhibit-read-only t) + (buffer-invisibility-spec '(org-link)) + (moment (time-subtract (current-time) + (list 0 (* 3600 org-extend-today-until) 0)))) + (save-excursion + (goto-char (if line (point-at-bol) (point-min))) + (while (not (eobp)) + (let ((habit (get-text-property (point) 'org-habit-p))) + (when habit + (move-to-column org-habit-graph-column t) + (delete-char (min (+ 1 org-habit-preceding-days + org-habit-following-days) + (- (line-end-position) (point)))) + (insert-before-markers + (org-habit-build-graph + habit + (time-subtract moment (days-to-time org-habit-preceding-days)) + moment + (time-add moment (days-to-time org-habit-following-days)))))) + (forward-line))))) + +(defun org-habit-toggle-habits () + "Toggle display of habits in an agenda buffer." + (interactive) + (org-agenda-check-type t 'agenda) + (setq org-habit-show-habits (not org-habit-show-habits)) + (org-agenda-redo) + (org-agenda-set-mode-name) + (message "Habits turned %s" + (if org-habit-show-habits "on" "off"))) + +(org-defkey org-agenda-mode-map "K" 'org-habit-toggle-habits) + +(provide 'org-habit) + +;;; org-habit.el ends here diff --git a/elpa/org-9.1.14/org-id.el b/elpa/org-9.1.14/org-id.el new file mode 100644 index 00000000..26b203ff --- /dev/null +++ b/elpa/org-9.1.14/org-id.el @@ -0,0 +1,684 @@ +;;; org-id.el --- Global identifiers for Org entries -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2008-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file implements globally unique identifiers for Org entries. +;; Identifiers are stored in the entry as an :ID: property. Functions +;; are provided that create and retrieve such identifiers, and that find +;; entries based on the identifier. + +;; Identifiers consist of a prefix (default "Org" given by the variable +;; `org-id-prefix') and a unique part that can be created by a number +;; of different methods, see the variable `org-id-method'. +;; Org has a builtin method that uses a compact encoding of the creation +;; time of the ID, with microsecond accuracy. This virtually +;; guarantees globally unique identifiers, even if several people are +;; creating IDs at the same time in files that will eventually be used +;; together. +;; +;; By default Org uses UUIDs as global unique identifiers. +;; +;; This file defines the following API: +;; +;; org-id-get-create +;; Create an ID for the entry at point if it does not yet have one. +;; Returns the ID (old or new). This function can be used +;; interactively, with prefix argument the creation of a new ID is +;; forced, even if there was an old one. +;; +;; org-id-get +;; Get the ID property of an entry. Using appropriate arguments +;; to the function, it can also create the ID for this entry. +;; +;; org-id-goto +;; Command to go to a specific ID, this command can be used +;; interactively. +;; +;; org-id-get-with-outline-path-completion +;; Retrieve the ID of an entry, using outline path completion. +;; This function can work for multiple files. +;; +;; org-id-get-with-outline-drilling +;; Retrieve the ID of an entry, using outline path completion. +;; This function only works for the current file. +;; +;; org-id-find +;; Find the location of an entry with specific id. +;; + +;;; Code: + +(require 'org) + +(declare-function message-make-fqdn "message" ()) + +;;; Customization + +(defgroup org-id nil + "Options concerning global entry identifiers in Org mode." + :tag "Org ID" + :group 'org) + +(defcustom org-id-link-to-org-use-id nil + "Non-nil means storing a link to an Org file will use entry IDs. +\\<org-mode-map>\ + +The variable can have the following values: + +t Create an ID if needed to make a link to the current entry. + +create-if-interactive + If `org-store-link' is called directly (interactively, as a user + command), do create an ID to support the link. But when doing the + job for capture, only use the ID if it already exists. The + purpose of this setting is to avoid proliferation of unwanted + IDs, just because you happen to be in an Org file when you + call `org-capture' that automatically and preemptively creates a + link. If you do want to get an ID link in a capture template to + an entry not having an ID, create it first by explicitly creating + a link to it, using `\\[org-store-link]' first. + +create-if-interactive-and-no-custom-id + Like create-if-interactive, but do not create an ID if there is + a CUSTOM_ID property defined in the entry. + +use-existing + Use existing ID, do not create one. + +nil Never use an ID to make a link, instead link using a text search for + the headline text." + :group 'org-link-store + :group 'org-id + :version "24.3" + :type '(choice + (const :tag "Create ID to make link" t) + (const :tag "Create if storing link interactively" + create-if-interactive) + (const :tag "Create if storing link interactively and no CUSTOM_ID is present" + create-if-interactive-and-no-custom-id) + (const :tag "Only use existing" use-existing) + (const :tag "Do not use ID to create link" nil))) + +(defcustom org-id-uuid-program "uuidgen" + "The uuidgen program." + :group 'org-id + :type 'string) + +(defcustom org-id-method 'uuid + "The method that should be used to create new IDs. + +An ID will consist of the optional prefix specified in `org-id-prefix', +and a unique part created by the method this variable specifies. + +Allowed values are: + +org Org's own internal method, using an encoding of the current time to + microsecond accuracy, and optionally the current domain of the + computer. See the variable `org-id-include-domain'. + +uuid Create random (version 4) UUIDs. If the program defined in + `org-id-uuid-program' is available it is used to create the ID. + Otherwise an internal functions is used." + :group 'org-id + :type '(choice + (const :tag "Org's internal method" org) + (const :tag "external: uuidgen" uuid))) + +(defcustom org-id-prefix nil + "The prefix for IDs. + +This may be a string, or it can be nil to indicate that no prefix is required. +When a string, the string should have no space characters as IDs are expected +to have no space characters in them." + :group 'org-id + :type '(choice + (const :tag "No prefix") + (string :tag "Prefix"))) + +(defcustom org-id-include-domain nil + "Non-nil means add the domain name to new IDs. +This ensures global uniqueness of IDs, and is also suggested by +RFC 2445 in combination with RFC 822. This is only relevant if +`org-id-method' is `org'. When uuidgen is used, the domain will never +be added. +The default is to not use this because we have no really good way to get +the true domain, and Org entries will normally not be shared with enough +people to make this necessary." + :group 'org-id + :type 'boolean) + +(defcustom org-id-track-globally t + "Non-nil means track IDs through files, so that links work globally. +This work by maintaining a hash table for IDs and writing this table +to disk when exiting Emacs. Because of this, it works best if you use +a single Emacs process, not many. + +When nil, IDs are not tracked. Links to IDs will still work within +a buffer, but not if the entry is located in another file. +IDs can still be used if the entry with the id is in the same file as +the link." + :group 'org-id + :type 'boolean) + +(defcustom org-id-locations-file (convert-standard-filename + (concat user-emacs-directory ".org-id-locations")) + "The file for remembering in which file an ID was defined. +This variable is only relevant when `org-id-track-globally' is set." + :group 'org-id + :type 'file) + +(defvar org-id-locations nil + "List of files with IDs in those files.") + +(defvar org-id-files nil + "List of files that contain IDs.") + +(defcustom org-id-extra-files 'org-agenda-text-search-extra-files + "Files to be searched for IDs, besides the agenda files. +When Org reparses files to remake the list of files and IDs it is tracking, +it will normally scan the agenda files, the archives related to agenda files, +any files that are listed as ID containing in the current register, and +any Org file currently visited by Emacs. +You can list additional files here. +This variable is only relevant when `org-id-track-globally' is set." + :group 'org-id + :type + '(choice + (symbol :tag "Variable") + (repeat :tag "List of files" + (file)))) + +(defcustom org-id-search-archives t + "Non-nil means search also the archive files of agenda files for entries. +This is a possibility to reduce overhead, but it means that entries moved +to the archives can no longer be found by ID. +This variable is only relevant when `org-id-track-globally' is set." + :group 'org-id + :type 'boolean) + +;;; The API functions + +;;;###autoload +(defun org-id-get-create (&optional force) + "Create an ID for the current entry and return it. +If the entry already has an ID, just return it. +With optional argument FORCE, force the creation of a new ID." + (interactive "P") + (when force + (org-entry-put (point) "ID" nil)) + (org-id-get (point) 'create)) + +;;;###autoload +(defun org-id-copy () + "Copy the ID of the entry at point to the kill ring. +Create an ID if necessary." + (interactive) + (org-kill-new (org-id-get nil 'create))) + +;;;###autoload +(defun org-id-get (&optional pom create prefix) + "Get the ID property of the entry at point-or-marker POM. +If POM is nil, refer to the entry at point. +If the entry does not have an ID, the function returns nil. +However, when CREATE is non nil, create an ID if none is present already. +PREFIX will be passed through to `org-id-new'. +In any case, the ID of the entry is returned." + (org-with-point-at pom + (let ((id (org-entry-get nil "ID"))) + (cond + ((and id (stringp id) (string-match "\\S-" id)) + id) + (create + (setq id (org-id-new prefix)) + (org-entry-put pom "ID" id) + (org-id-add-location id (buffer-file-name (buffer-base-buffer))) + id))))) + +;;;###autoload +(defun org-id-get-with-outline-path-completion (&optional targets) + "Use `outline-path-completion' to retrieve the ID of an entry. +TARGETS may be a setting for `org-refile-targets' to define +eligible headlines. When omitted, all headlines in the current +file are eligible. This function returns the ID of the entry. +If necessary, the ID is created." + (let* ((org-refile-targets (or targets '((nil . (:maxlevel . 10))))) + (org-refile-use-outline-path + (if (caar org-refile-targets) 'file t)) + (org-refile-target-verify-function nil) + (spos (org-refile-get-location "Entry")) + (pom (and spos (move-marker (make-marker) (nth 3 spos) + (get-file-buffer (nth 1 spos)))))) + (prog1 (org-id-get pom 'create) + (move-marker pom nil)))) + +;;;###autoload +(defun org-id-get-with-outline-drilling () + "Use an outline-cycling interface to retrieve the ID of an entry. +This only finds entries in the current buffer, using `org-get-location'. +It returns the ID of the entry. If necessary, the ID is created." + (let* ((spos (org-get-location (current-buffer) org-goto-help)) + (pom (and spos (move-marker (make-marker) (car spos))))) + (prog1 (org-id-get pom 'create) + (move-marker pom nil)))) + +;;;###autoload +(defun org-id-goto (id) + "Switch to the buffer containing the entry with id ID. +Move the cursor to that entry in that buffer." + (interactive "sID: ") + (let ((m (org-id-find id 'marker))) + (unless m + (error "Cannot find entry with ID \"%s\"" id)) + (pop-to-buffer-same-window (marker-buffer m)) + (goto-char m) + (move-marker m nil) + (org-show-context))) + +;;;###autoload +(defun org-id-find (id &optional markerp) + "Return the location of the entry with the id ID. +The return value is a cons cell (file-name . position), or nil +if there is no entry with that ID. +With optional argument MARKERP, return the position as a new marker." + (cond + ((symbolp id) (setq id (symbol-name id))) + ((numberp id) (setq id (number-to-string id)))) + (let ((file (org-id-find-id-file id)) + org-agenda-new-buffers where) + (when file + (setq where (org-id-find-id-in-file id file markerp))) + (unless where + (org-id-update-id-locations nil t) + (setq file (org-id-find-id-file id)) + (when file + (setq where (org-id-find-id-in-file id file markerp)))) + where)) + +;;; Internal functions + +;; Creating new IDs + +;;;###autoload +(defun org-id-new (&optional prefix) + "Create a new globally unique ID. + +An ID consists of two parts separated by a colon: +- a prefix +- a unique part that will be created according to `org-id-method'. + +PREFIX can specify the prefix, the default is given by the variable +`org-id-prefix'. However, if PREFIX is the symbol `none', don't use any +prefix even if `org-id-prefix' specifies one. + +So a typical ID could look like \"Org:4nd91V40HI\"." + (let* ((prefix (if (eq prefix 'none) + "" + (concat (or prefix org-id-prefix) ":"))) + unique) + (if (equal prefix ":") (setq prefix "")) + (cond + ((memq org-id-method '(uuidgen uuid)) + (setq unique (org-trim (shell-command-to-string org-id-uuid-program))) + (unless (org-uuidgen-p unique) + (setq unique (org-id-uuid)))) + ((eq org-id-method 'org) + (let* ((etime (org-reverse-string (org-id-time-to-b36))) + (postfix (if org-id-include-domain + (progn + (require 'message) + (concat "@" (message-make-fqdn)))))) + (setq unique (concat etime postfix)))) + (t (error "Invalid `org-id-method'"))) + (concat prefix unique))) + +(defun org-id-uuid () + "Return string with random (version 4) UUID." + (let ((rnd (md5 (format "%s%s%s%s%s%s%s" + (random) + (current-time) + (user-uid) + (emacs-pid) + (user-full-name) + user-mail-address + (recent-keys))))) + (format "%s-%s-4%s-%s%s-%s" + (substring rnd 0 8) + (substring rnd 8 12) + (substring rnd 13 16) + (format "%x" + (logior + #b10000000 + (logand + #b10111111 + (string-to-number + (substring rnd 16 18) 16)))) + (substring rnd 18 20) + (substring rnd 20 32)))) + +(defun org-id-int-to-b36-one-digit (i) + "Turn an integer between 0 and 61 into a single character 0..9, A..Z, a..z." + (cond + ((< i 10) (+ ?0 i)) + ((< i 36) (+ ?a i -10)) + (t (error "Larger that 35")))) + +(defun org-id-b36-to-int-one-digit (i) + "Turn a character 0..9, A..Z, a..z into a number 0..61. +The input I may be a character, or a single-letter string." + (and (stringp i) (setq i (string-to-char i))) + (cond + ((and (>= i ?0) (<= i ?9)) (- i ?0)) + ((and (>= i ?a) (<= i ?z)) (+ (- i ?a) 10)) + (t (error "Invalid b36 letter")))) + +(defun org-id-int-to-b36 (i &optional length) + "Convert an integer to a base-36 number represented as a string." + (let ((s "")) + (while (> i 0) + (setq s (concat (char-to-string + (org-id-int-to-b36-one-digit (mod i 36))) s) + i (/ i 36))) + (setq length (max 1 (or length 1))) + (if (< (length s) length) + (setq s (concat (make-string (- length (length s)) ?0) s))) + s)) + +(defun org-id-b36-to-int (s) + "Convert a base-36 string into the corresponding integer." + (let ((r 0)) + (mapc (lambda (i) (setq r (+ (* r 36) (org-id-b36-to-int-one-digit i)))) + s) + r)) + +(defun org-id-time-to-b36 (&optional time) + "Encode TIME as a 10-digit string. +This string holds the time to micro-second accuracy, and can be decoded +using `org-id-decode'." + (setq time (or time (current-time))) + (concat (org-id-int-to-b36 (nth 0 time) 4) + (org-id-int-to-b36 (nth 1 time) 4) + (org-id-int-to-b36 (or (nth 2 time) 0) 4))) + +(defun org-id-decode (id) + "Split ID into the prefix and the time value that was used to create it. +The return value is (prefix . time) where PREFIX is nil or a string, +and time is the usual three-integer representation of time." + (let (prefix time parts) + (setq parts (org-split-string id ":")) + (if (= 2 (length parts)) + (setq prefix (car parts) time (nth 1 parts)) + (setq prefix nil time (nth 0 parts))) + (setq time (org-reverse-string time)) + (setq time (list (org-id-b36-to-int (substring time 0 4)) + (org-id-b36-to-int (substring time 4 8)) + (org-id-b36-to-int (substring time 8 12)))) + (cons prefix time))) + +;; Storing ID locations (files) + +;;;###autoload +(defun org-id-update-id-locations (&optional files silent) + "Scan relevant files for IDs. +Store the relation between files and corresponding IDs. +This will scan all agenda files, all associated archives, and all +files currently mentioned in `org-id-locations'. +When FILES is given, scan these files instead." + (interactive) + (if (not org-id-track-globally) + (error "Please turn on `org-id-track-globally' if you want to track IDs") + (let* ((org-id-search-archives + (or org-id-search-archives + (and (symbolp org-id-extra-files) + (symbol-value org-id-extra-files) + (member 'agenda-archives org-id-extra-files)))) + (files + (or files + (append + ;; Agenda files and all associated archives + (org-agenda-files t org-id-search-archives) + ;; Explicit extra files + (if (symbolp org-id-extra-files) + (symbol-value org-id-extra-files) + org-id-extra-files) + ;; Files associated with live Org buffers + (delq nil + (mapcar (lambda (b) + (with-current-buffer b + (and (derived-mode-p 'org-mode) (buffer-file-name)))) + (buffer-list))) + ;; All files known to have IDs + org-id-files))) + org-agenda-new-buffers + file nfiles tfile ids reg found id seen (ndup 0)) + (when (member 'agenda-archives files) + (setq files (delq 'agenda-archives (copy-sequence files)))) + (setq nfiles (length files)) + (while (setq file (pop files)) + (unless silent + (message "Finding ID locations (%d/%d files): %s" + (- nfiles (length files)) nfiles file)) + (setq tfile (file-truename file)) + (when (and (file-exists-p file) (not (member tfile seen))) + (push tfile seen) + (setq ids nil) + (with-current-buffer (org-get-agenda-file-buffer file) + (save-excursion + (save-restriction + (widen) + (goto-char (point-min)) + (while (re-search-forward "^[ \t]*:ID:[ \t]+\\(\\S-+\\)[ \t]*$" + nil t) + (setq id (match-string-no-properties 1)) + (if (member id found) + (progn + (message "Duplicate ID \"%s\", also in file %s" + id (or (car (delq + nil + (mapcar + (lambda (x) + (if (member id (cdr x)) + (car x))) + reg))) + (buffer-file-name))) + (when (= ndup 0) + (ding) + (sit-for 2)) + (setq ndup (1+ ndup))) + (push id found) + (push id ids))) + (push (cons (abbreviate-file-name file) ids) reg)))))) + (org-release-buffers org-agenda-new-buffers) + (setq org-agenda-new-buffers nil) + (setq org-id-locations reg) + (setq org-id-files (mapcar 'car org-id-locations)) + (org-id-locations-save) ;; this function can also handle the alist form + ;; now convert to a hash + (setq org-id-locations (org-id-alist-to-hash org-id-locations)) + (if (> ndup 0) + (message "WARNING: %d duplicate IDs found, check *Messages* buffer" ndup) + (message "%d unique files scanned for IDs" (length org-id-files))) + org-id-locations))) + +(defun org-id-locations-save () + "Save `org-id-locations' in `org-id-locations-file'." + (when (and org-id-track-globally org-id-locations) + (let ((out (if (hash-table-p org-id-locations) + (org-id-hash-to-alist org-id-locations) + org-id-locations))) + (with-temp-file org-id-locations-file + (let ((print-level nil) + (print-length nil)) + (print out (current-buffer))))))) + +(defun org-id-locations-load () + "Read the data from `org-id-locations-file'." + (setq org-id-locations nil) + (when org-id-track-globally + (with-temp-buffer + (condition-case nil + (progn + (insert-file-contents org-id-locations-file) + (setq org-id-locations (read (current-buffer)))) + (error + (message "Could not read org-id-values from %s. Setting it to nil." + org-id-locations-file)))) + (setq org-id-files (mapcar 'car org-id-locations)) + (setq org-id-locations (org-id-alist-to-hash org-id-locations)))) + +(defun org-id-add-location (id file) + "Add the ID with location FILE to the database of ID locations." + ;; Only if global tracking is on, and when the buffer has a file + (when (and org-id-track-globally id file) + (unless org-id-locations (org-id-locations-load)) + (puthash id (abbreviate-file-name file) org-id-locations) + (add-to-list 'org-id-files (abbreviate-file-name file)))) + +(unless noninteractive + (add-hook 'kill-emacs-hook 'org-id-locations-save)) + +(defun org-id-hash-to-alist (hash) + "Turn an org-id hash into an alist, so that it can be written to a file." + (let (res x) + (maphash + (lambda (k v) + (if (setq x (member v res)) + (setcdr x (cons k (cdr x))) + (push (list v k) res))) + hash) + res)) + +(defun org-id-alist-to-hash (list) + "Turn an org-id location list into a hash table." + (let ((res (make-hash-table + :test 'equal + :size (apply '+ (mapcar 'length list)))) + f) + (mapc + (lambda (x) + (setq f (car x)) + (mapc (lambda (i) (puthash i f res)) (cdr x))) + list) + res)) + +(defun org-id-paste-tracker (txt &optional buffer-or-file) + "Update any IDs in TXT and assign BUFFER-OR-FILE to them." + (when org-id-track-globally + (save-match-data + (setq buffer-or-file (or buffer-or-file (current-buffer))) + (when (bufferp buffer-or-file) + (setq buffer-or-file (or (buffer-base-buffer buffer-or-file) + buffer-or-file)) + (setq buffer-or-file (buffer-file-name buffer-or-file))) + (when buffer-or-file + (let ((fname (abbreviate-file-name buffer-or-file)) + (s 0)) + (while (string-match "^[ \t]*:ID:[ \t]+\\([^ \t\n\r]+\\)" txt s) + (setq s (match-end 0)) + (org-id-add-location (match-string 1 txt) fname))))))) + +;; Finding entries with specified id + +;;;###autoload +(defun org-id-find-id-file (id) + "Query the id database for the file in which this ID is located." + (unless org-id-locations (org-id-locations-load)) + (or (and org-id-locations + (hash-table-p org-id-locations) + (gethash id org-id-locations)) + ;; ball back on current buffer + (buffer-file-name (or (buffer-base-buffer (current-buffer)) + (current-buffer))))) + +(defun org-id-find-id-in-file (id file &optional markerp) + "Return the position of the entry ID in FILE. +If that files does not exist, or if it does not contain this ID, +return nil. +The position is returned as a cons cell (file-name . position). With +optional argument MARKERP, return the position as a new marker." + (let (org-agenda-new-buffers buf pos) + (cond + ((not file) nil) + ((not (file-exists-p file)) nil) + (t (with-current-buffer (setq buf (org-get-agenda-file-buffer file)) + (setq pos (org-find-entry-with-id id)) + (when pos + (if markerp + (move-marker (make-marker) pos buf) + (cons file pos)))))))) + +;; id link type + +;; Calling the following function is hard-coded into `org-store-link', +;; so we do have to add it to `org-store-link-functions'. + +;;;###autoload +(defun org-id-store-link () + "Store a link to the current entry, using its ID." + (interactive) + (when (and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode)) + (let* ((link (concat "id:" (org-id-get-create))) + (case-fold-search nil) + (desc (save-excursion + (org-back-to-heading t) + (or (and (looking-at org-complex-heading-regexp) + (if (match-end 4) + (match-string 4) + (match-string 0))) + link)))) + (org-store-link-props :link link :description desc :type "id") + link))) + +(defun org-id-open (id) + "Go to the entry with id ID." + (org-mark-ring-push) + (let ((m (org-id-find id 'marker)) + cmd) + (unless m + (error "Cannot find entry with ID \"%s\"" id)) + ;; Use a buffer-switching command in analogy to finding files + (setq cmd + (or + (cdr + (assq + (cdr (assq 'file org-link-frame-setup)) + '((find-file . switch-to-buffer) + (find-file-other-window . switch-to-buffer-other-window) + (find-file-other-frame . switch-to-buffer-other-frame)))) + 'switch-to-buffer-other-window)) + (if (not (equal (current-buffer) (marker-buffer m))) + (funcall cmd (marker-buffer m))) + (goto-char m) + (move-marker m nil) + (org-show-context))) + +(org-link-set-parameters "id" :follow #'org-id-open) + +(provide 'org-id) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-id.el ends here diff --git a/elpa/org-9.1.14/org-indent.el b/elpa/org-9.1.14/org-indent.el new file mode 100644 index 00000000..84bac2aa --- /dev/null +++ b/elpa/org-9.1.14/org-indent.el @@ -0,0 +1,412 @@ +;;; org-indent.el --- Dynamic indentation for Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. +;; +;; GNU Emacs 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: + +;; This is an implementation of dynamic virtual indentation. It works +;; by adding text properties to a buffer to make sure lines are +;; indented according to outline structure. +;; +;; The process is synchronous, toggled at every buffer modification. +;; Though, the initialization (indentation of text already in the +;; buffer), which can take a few seconds in large buffers, happens on +;; idle time. +;; +;;; Code: + +(require 'org-macs) +(require 'org-compat) +(require 'org) + +(require 'cl-lib) + +(declare-function org-inlinetask-get-task-level "org-inlinetask" ()) +(declare-function org-inlinetask-in-task-p "org-inlinetask" ()) +(declare-function org-list-item-body-column "org-list" (item)) +(defvar org-inlinetask-show-first-star) + +(defgroup org-indent nil + "Options concerning dynamic virtual outline indentation." + :tag "Org Indent" + :group 'org) + +(defvar org-indent-inlinetask-first-star (org-add-props "*" '(face org-warning)) + "First star of inline tasks, with correct face.") +(defvar org-indent-agent-timer nil + "Timer running the initialize agent.") +(defvar org-indent-agentized-buffers nil + "List of buffers watched by the initialize agent.") +(defvar org-indent-agent-resume-timer nil + "Timer to reschedule agent after switching to other idle processes.") +(defvar org-indent-agent-active-delay '(0 2 0) + "Time to run agent before switching to other idle processes. +Delay used when the buffer to initialize is current.") +(defvar org-indent-agent-passive-delay '(0 0 400000) + "Time to run agent before switching to other idle processes. +Delay used when the buffer to initialize isn't current.") +(defvar org-indent-agent-resume-delay '(0 0 100000) + "Minimal time for other idle processes before switching back to agent.") +(defvar org-indent--initial-marker nil + "Position of initialization before interrupt. +This is used locally in each buffer being initialized.") +(defvar org-hide-leading-stars-before-indent-mode nil + "Used locally.") +(defvar org-indent-modified-headline-flag nil + "Non-nil means the last deletion operated on a headline. +It is modified by `org-indent-notify-modified-headline'.") + + +(defcustom org-indent-boundary-char ?\s + "The end of the virtual indentation strings, a single-character string. +The default is just a space, but if you wish, you can use \"|\" or so. +This can be useful on a terminal window - under a windowing system, +it may be prettier to customize the `org-indent' face." + :group 'org-indent + :type 'character) + +(defcustom org-indent-mode-turns-off-org-adapt-indentation t + "Non-nil means setting the variable `org-indent-mode' will \ +turn off indentation adaptation. +For details see the variable `org-adapt-indentation'." + :group 'org-indent + :type 'boolean) + +(defcustom org-indent-mode-turns-on-hiding-stars t + "Non-nil means setting the variable `org-indent-mode' will \ +turn on `org-hide-leading-stars'." + :group 'org-indent + :type 'boolean) + +(defcustom org-indent-indentation-per-level 2 + "Indentation per level in number of characters." + :group 'org-indent + :type 'integer) + +(defface org-indent '((t (:inherit org-hide))) + "Face for outline indentation. +The default is to make it look like whitespace. But you may find it +useful to make it ever so slightly different." + :group 'org-faces) + +(defvar org-indent--text-line-prefixes nil + "Vector containing line prefixes strings for regular text.") + +(defvar org-indent--heading-line-prefixes nil + "Vector containing line prefix strings for headlines.") + +(defvar org-indent--inlinetask-line-prefixes nil + "Vector containing line prefix strings for inline tasks.") + +(defconst org-indent--deepest-level 50 + "Maximum theoretical headline depth.") + +(defun org-indent--compute-prefixes () + "Compute prefix strings for regular text and headlines." + (setq org-indent--heading-line-prefixes + (make-vector org-indent--deepest-level nil)) + (setq org-indent--inlinetask-line-prefixes + (make-vector org-indent--deepest-level nil)) + (setq org-indent--text-line-prefixes + (make-vector org-indent--deepest-level nil)) + (dotimes (n org-indent--deepest-level) + (let ((indentation (if (<= n 1) 0 + (* (1- org-indent-indentation-per-level) + (1- n))))) + ;; Headlines line prefixes. + (let ((heading-prefix (make-string indentation ?*))) + (aset org-indent--heading-line-prefixes + n + (org-add-props heading-prefix nil 'face 'org-indent)) + ;; Inline tasks line prefixes + (aset org-indent--inlinetask-line-prefixes + n + (cond ((<= n 1) "") + ((bound-and-true-p org-inlinetask-show-first-star) + (concat org-indent-inlinetask-first-star + (substring heading-prefix 1))) + (t (org-add-props heading-prefix nil 'face 'org-indent))))) + ;; Text line prefixes. + (aset org-indent--text-line-prefixes + n + (concat (org-add-props (make-string (+ n indentation) ?\s) + nil 'face 'org-indent) + (and (> n 0) + (char-to-string org-indent-boundary-char))))))) + +(defsubst org-indent-remove-properties (beg end) + "Remove indentations between BEG and END." + (org-with-silent-modifications + (remove-text-properties beg end '(line-prefix nil wrap-prefix nil)))) + +;;;###autoload +(define-minor-mode org-indent-mode + "When active, indent text according to outline structure. + +Internally this works by adding `line-prefix' and `wrap-prefix' +properties, after each buffer modification, on the modified zone. + +The process is synchronous. Though, initial indentation of +buffer, which can take a few seconds on large buffers, is done +during idle time." + nil " Ind" nil + (cond + (org-indent-mode + ;; mode was turned on. + (setq-local indent-tabs-mode nil) + (setq-local org-indent--initial-marker (copy-marker 1)) + (when org-indent-mode-turns-off-org-adapt-indentation + (setq-local org-adapt-indentation nil)) + (when org-indent-mode-turns-on-hiding-stars + (setq-local org-hide-leading-stars-before-indent-mode + org-hide-leading-stars) + (setq-local org-hide-leading-stars t)) + (org-indent--compute-prefixes) + (add-hook 'filter-buffer-substring-functions + (lambda (fun start end delete) + (org-indent-remove-properties-from-string + (funcall fun start end delete))) + nil t) + (add-hook 'after-change-functions 'org-indent-refresh-maybe nil 'local) + (add-hook 'before-change-functions + 'org-indent-notify-modified-headline nil 'local) + (and font-lock-mode (org-restart-font-lock)) + (org-indent-remove-properties (point-min) (point-max)) + ;; Submit current buffer to initialize agent. If it's the first + ;; buffer submitted, also start the agent. Current buffer is + ;; pushed in both cases to avoid a race condition. + (if org-indent-agentized-buffers + (push (current-buffer) org-indent-agentized-buffers) + (push (current-buffer) org-indent-agentized-buffers) + (setq org-indent-agent-timer + (run-with-idle-timer 0.2 t #'org-indent-initialize-agent)))) + (t + ;; mode was turned off (or we refused to turn it on) + (kill-local-variable 'org-adapt-indentation) + (setq org-indent-agentized-buffers + (delq (current-buffer) org-indent-agentized-buffers)) + (when (markerp org-indent--initial-marker) + (set-marker org-indent--initial-marker nil)) + (when (boundp 'org-hide-leading-stars-before-indent-mode) + (setq-local org-hide-leading-stars + org-hide-leading-stars-before-indent-mode)) + (remove-hook 'filter-buffer-substring-functions + (lambda (fun start end delete) + (org-indent-remove-properties-from-string + (funcall fun start end delete)))) + (remove-hook 'after-change-functions 'org-indent-refresh-maybe 'local) + (remove-hook 'before-change-functions + 'org-indent-notify-modified-headline 'local) + (org-with-wide-buffer + (org-indent-remove-properties (point-min) (point-max))) + (and font-lock-mode (org-restart-font-lock)) + (redraw-display)))) + +(defun org-indent-indent-buffer () + "Add indentation properties to the accessible part of the buffer." + (interactive) + (if (not (derived-mode-p 'org-mode)) + (error "Not in Org mode") + (message "Setting buffer indentation. It may take a few seconds...") + (org-indent-remove-properties (point-min) (point-max)) + (org-indent-add-properties (point-min) (point-max)) + (message "Indentation of buffer set."))) + +(defun org-indent-remove-properties-from-string (string) + "Remove indentation properties from STRING." + (remove-text-properties 0 (length string) + '(line-prefix nil wrap-prefix nil) string) + string) + +(defun org-indent-initialize-agent () + "Start or resume current buffer initialization. +Only buffers in `org-indent-agentized-buffers' trigger an action. +When no more buffer is being watched, the agent suppress itself." + (when org-indent-agent-resume-timer + (cancel-timer org-indent-agent-resume-timer)) + (setq org-indent-agentized-buffers + (cl-remove-if-not #'buffer-live-p org-indent-agentized-buffers)) + (cond + ;; Job done: kill agent. + ((not org-indent-agentized-buffers) (cancel-timer org-indent-agent-timer)) + ;; Current buffer is agentized: start/resume initialization + ;; somewhat aggressively. + ((memq (current-buffer) org-indent-agentized-buffers) + (org-indent-initialize-buffer (current-buffer) + org-indent-agent-active-delay)) + ;; Else, start/resume initialization of the last agentized buffer, + ;; softly. + (t (org-indent-initialize-buffer (car org-indent-agentized-buffers) + org-indent-agent-passive-delay)))) + +(defun org-indent-initialize-buffer (buffer delay) + "Set virtual indentation for the buffer BUFFER, asynchronously. +Give hand to other idle processes if it takes longer than DELAY, +a time value." + (with-current-buffer buffer + (when org-indent-mode + (org-with-wide-buffer + (let ((interruptp + ;; Always nil unless interrupted. + (catch 'interrupt + (and org-indent--initial-marker + (marker-position org-indent--initial-marker) + (equal (marker-buffer org-indent--initial-marker) + buffer) + (org-indent-add-properties org-indent--initial-marker + (point-max) + delay) + nil)))) + (move-marker org-indent--initial-marker interruptp) + ;; Job is complete: un-agentize buffer. + (unless interruptp + (setq org-indent-agentized-buffers + (delq buffer org-indent-agentized-buffers)))))))) + +(defun org-indent-set-line-properties (level indentation &optional heading) + "Set prefix properties on current line an move to next one. + +LEVEL is the current level of heading. INDENTATION is the +expected indentation when wrapping line. + +When optional argument HEADING is non-nil, assume line is at +a heading. Moreover, if is is `inlinetask', the first star will +have `org-warning' face." + (let* ((line (aref (pcase heading + (`nil org-indent--text-line-prefixes) + (`inlinetask org-indent--inlinetask-line-prefixes) + (_ org-indent--heading-line-prefixes)) + level)) + (wrap + (org-add-props + (concat line + (if heading (concat (make-string level ?*) " ") + (make-string indentation ?\s))) + nil 'face 'org-indent))) + ;; Add properties down to the next line to indent empty lines. + (add-text-properties (line-beginning-position) (line-beginning-position 2) + `(line-prefix ,line wrap-prefix ,wrap))) + (forward-line)) + +(defun org-indent-add-properties (beg end &optional delay) + "Add indentation properties between BEG and END. + +When DELAY is non-nil, it must be a time value. In that case, +the process is asynchronous and can be interrupted, either by +user request, or after DELAY. This is done by throwing the +`interrupt' tag along with the buffer position where the process +stopped." + (save-match-data + (org-with-wide-buffer + (goto-char beg) + (beginning-of-line) + ;; Initialize prefix at BEG, according to current entry's level. + (let* ((case-fold-search t) + (limited-re (org-get-limited-outline-regexp)) + (level (or (org-current-level) 0)) + (time-limit (and delay (time-add (current-time) delay)))) + ;; For each line, set `line-prefix' and `wrap-prefix' + ;; properties depending on the type of line (headline, inline + ;; task, item or other). + (org-with-silent-modifications + (while (and (<= (point) end) (not (eobp))) + (cond + ;; When in asynchronous mode, check if interrupt is + ;; required. + ((and delay (input-pending-p)) (throw 'interrupt (point))) + ;; In asynchronous mode, take a break of + ;; `org-indent-agent-resume-delay' every DELAY to avoid + ;; blocking any other idle timer or process output. + ((and delay (time-less-p time-limit (current-time))) + (setq org-indent-agent-resume-timer + (run-with-idle-timer + (time-add (current-idle-time) org-indent-agent-resume-delay) + nil #'org-indent-initialize-agent)) + (throw 'interrupt (point))) + ;; Headline or inline task. + ((looking-at org-outline-regexp) + (let* ((nstars (- (match-end 0) (match-beginning 0) 1)) + (type (or (looking-at-p limited-re) 'inlinetask))) + (org-indent-set-line-properties nstars 0 type) + ;; At an headline, define new value for LEVEL. + (unless (eq type 'inlinetask) (setq level nstars)))) + ;; List item: `wrap-prefix' is set where body starts. + ((org-at-item-p) + (org-indent-set-line-properties + level (org-list-item-body-column (point)))) + ;; Regular line. + (t + (org-indent-set-line-properties level (org-get-indentation)))))))))) + +(defun org-indent-notify-modified-headline (beg end) + "Set `org-indent-modified-headline-flag' depending on context. + +BEG and END are the positions of the beginning and end of the +range of deleted text. + +This function is meant to be called by `before-change-functions'. +Flag will be non-nil if command is going to modify or delete an +headline." + (when org-indent-mode + (setq org-indent-modified-headline-flag + (org-with-wide-buffer + (goto-char beg) + (save-match-data + (or (and (org-at-heading-p) (< beg (match-end 0))) + (re-search-forward + (org-with-limited-levels org-outline-regexp-bol) end t))))))) + +(defun org-indent-refresh-maybe (beg end _) + "Refresh indentation properties in an adequate portion of buffer. +BEG and END are the positions of the beginning and end of the +range of inserted text. DUMMY is an unused argument. + +This function is meant to be called by `after-change-functions'." + (when org-indent-mode + (save-match-data + ;; If a headline was modified or inserted, set properties until + ;; next headline. + (org-with-wide-buffer + (if (or org-indent-modified-headline-flag + (save-excursion + (goto-char beg) + (beginning-of-line) + (re-search-forward + (org-with-limited-levels org-outline-regexp-bol) end t))) + (let ((end (save-excursion + (goto-char end) + (org-with-limited-levels (outline-next-heading)) + (point)))) + (setq org-indent-modified-headline-flag nil) + (org-indent-add-properties beg end)) + ;; Otherwise, only set properties on modified area. + (org-indent-add-properties beg end)))))) + +(provide 'org-indent) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-indent.el ends here diff --git a/elpa/org-9.1.14/org-info.el b/elpa/org-9.1.14/org-info.el new file mode 100644 index 00000000..6dde36ce --- /dev/null +++ b/elpa/org-9.1.14/org-info.el @@ -0,0 +1,148 @@ +;;; org-info.el --- Support for Links to Info Nodes -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file implements links to Info nodes from within Org mode. +;; Org mode loads this module by default - if this is not what you want, +;; configure the variable `org-modules'. + +;;; Code: + +(require 'org) + +;; Declare external functions and variables + +(declare-function Info-find-node "info" + (filename nodename &optional no-going-back strict-case)) +(defvar Info-current-file) +(defvar Info-current-node) + +;; Install the link type +(org-link-set-parameters "info" + :follow #'org-info-open + :export #'org-info-export + :store #'org-info-store-link) + +;; Implementation +(defun org-info-store-link () + "Store a link to an Info file and node." + (when (eq major-mode 'Info-mode) + (let ((link (concat "info:" + (file-name-nondirectory Info-current-file) + "#" Info-current-node)) + (desc (concat (file-name-nondirectory Info-current-file) + "#" Info-current-node))) + (org-store-link-props :type "info" :file Info-current-file + :node Info-current-node + :link link :desc desc) + link))) + +(defun org-info-open (path) + "Follow an Info file and node link specified by PATH." + (org-info-follow-link path)) + + +(defun org-info-follow-link (name) + "Follow an Info file and node link specified by NAME." + (if (or (string-match "\\(.*\\)[#:]:?\\(.*\\)" name) + (string-match "\\(.*\\)" name)) + (let ((filename (match-string 1 name)) + (nodename-or-index (or (match-string 2 name) "Top"))) + (require 'info) + ;; If nodename-or-index is invalid node name, then look it up + ;; in the index. + (condition-case nil + (Info-find-node filename nodename-or-index) + (user-error (Info-find-node filename "Top") + (condition-case nil + (Info-index nodename-or-index) + (user-error "Could not find '%s' node or index entry" + nodename-or-index))))) + (user-error "Could not open: %s" name))) + +(defconst org-info-emacs-documents + '("ada-mode" "auth" "autotype" "bovine" "calc" "ccmode" "cl" "dbus" "dired-x" + "ebrowse" "ede" "ediff" "edt" "efaq-w32" "efaq" "eieio" "eintr" "elisp" + "emacs-gnutls" "emacs-mime" "emacs" "epa" "erc" "ert" "eshell" "eudc" "eww" + "flymake" "forms" "gnus" "htmlfontify" "idlwave" "ido" "info" "mairix-el" + "message" "mh-e" "newsticker" "nxml-mode" "octave-mode" "org" "pcl-cvs" + "pgg" "rcirc" "reftex" "remember" "sasl" "sc" "semantic" "ses" "sieve" + "smtpmail" "speedbar" "srecode" "todo-mode" "tramp" "url" "vip" "viper" + "widget" "wisent" "woman") + "List of emacs documents available. +Taken from <https://www.gnu.org/software/emacs/manual/html_mono/.>") + +(defconst org-info-other-documents + '(("libc" . "https://www.gnu.org/software/libc/manual/html_mono/libc.html") + ("make" . "https://www.gnu.org/software/make/manual/make.html")) + "Alist of documents generated from Texinfo source. +When converting info links to HTML, links to any one of these manuals are +converted to use these URL.") + +(defun org-info-map-html-url (filename) + "Return URL or HTML file associated to Info FILENAME. +If FILENAME refers to an official GNU document, return a URL pointing to +the official page for that document, e.g., use \"gnu.org\" for all Emacs +related documents. Otherwise, append \".html\" extension to FILENAME. +See `org-info-emacs-documents' and `org-info-other-documents' for details." + (cond ((member filename org-info-emacs-documents) + (format "https://www.gnu.org/software/emacs/manual/html_mono/%s.html" + filename)) + ((cdr (assoc filename org-info-other-documents))) + (t (concat filename ".html")))) + +(defun org-info--expand-node-name (node) + "Expand Info NODE to HTML cross reference." + ;; See (info "(texinfo) HTML Xref Node Name Expansion") for the + ;; expansion rule. + (let ((node (replace-regexp-in-string + "\\([ \t\n\r]+\\)\\|\\([^a-zA-Z0-9]\\)" + (lambda (m) + (if (match-end 1) "-" (format "_%04x" (string-to-char m)))) + (org-trim node)))) + (cond ((string= node "") "") + ((string-match-p "\\`[0-9]" node) (concat "g_t" node)) + (t node)))) + +(defun org-info-export (path desc format) + "Export an info link. +See `org-link-parameters' for details about PATH, DESC and FORMAT." + (let* ((parts (split-string path "[#:]:?")) + (manual (car parts)) + (node (or (nth 1 parts) "Top"))) + (pcase format + (`html + (format "<a href=\"%s#%s\">%s</a>" + (org-info-map-html-url manual) + (org-info--expand-node-name node) + (or desc path))) + (`texinfo + (let ((title (or desc ""))) + (format "@ref{%s,%s,,%s,}" node title manual))) + (_ nil)))) + +(provide 'org-info) + +;;; org-info.el ends here diff --git a/elpa/org-9.1.14/org-inlinetask.el b/elpa/org-9.1.14/org-inlinetask.el new file mode 100644 index 00000000..d95db321 --- /dev/null +++ b/elpa/org-9.1.14/org-inlinetask.el @@ -0,0 +1,353 @@ +;;; org-inlinetask.el --- Tasks Independent of Outline Hierarchy -*- lexical-binding: t; -*- + +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: +;; +;; This module implements inline tasks in Org mode. Inline tasks are +;; tasks that have all the properties of normal outline nodes, +;; including the ability to store meta data like scheduling dates, +;; TODO state, tags and properties. However, these nodes are treated +;; specially by the visibility cycling. +;; +;; Visibility cycling exempts these nodes from cycling. So whenever +;; their parent is opened, so are these tasks. This will only work +;; with `org-cycle', so if you are also using other commands to +;; show/hide entries, you will occasionally find these tasks to behave +;; like all other outline nodes, seemingly splitting the text of the +;; parent into children. +;; +;; Special fontification of inline tasks, so that they can be +;; immediately recognized. From the stars of the headline, only the +;; first and the last two will be visible, the others will be hidden +;; using the `org-hide' face. +;; +;; An inline task is identified solely by a minimum outline level, +;; given by the variable `org-inlinetask-min-level', default 15. +;; +;; If you need to have a time planning line (DEADLINE etc), drawers, +;; for example LOGBOOK of PROPERTIES, or even normal text as part of +;; the inline task, you must add an "END" headline with the same +;; number of stars. +;; +;; As an example, here are two valid inline tasks: +;; +;; **************** TODO a small task +;; +;; and +;; +;; **************** TODO another small task +;; DEADLINE: <2009-03-30 Mon> +;; :PROPERTIES: +;; :SOMETHING: or other +;; :END: +;; And here is some extra text +;; **************** END +;; +;; Also, if you want to use refiling and archiving for inline tasks, +;; The END line must be present to make things work properly. +;; +;; Note that you should not try to use inline tasks within plain list, +;; visibility cycling is known to be problematic when doing so. +;; +;; This package installs one new command: +;; +;; C-c C-x t Insert a new inline task with END line + +;;; Code: + +(require 'org) + +(defgroup org-inlinetask nil + "Options concerning inline tasks in Org mode." + :tag "Org Inline Tasks" + :group 'org-structure) + +(defcustom org-inlinetask-min-level 15 + "Minimum level a headline must have before it is treated as an inline task. +Don't set it to something higher than `29' or clocking will break since this +is the hardcoded maximum number of stars `org-clock-sum' will work with. + +It is strongly recommended that you set `org-cycle-max-level' not at all, +or to a number smaller than this one. In fact, when `org-cycle-max-level' is +not set, it will be assumed to be one less than the value of smaller than +the value of this variable." + :group 'org-inlinetask + :type '(choice + (const :tag "Off" nil) + (integer))) + +(defcustom org-inlinetask-show-first-star nil + "Non-nil means display the first star of an inline task as additional marker. +When nil, the first star is not shown." + :tag "Org Inline Tasks" + :group 'org-structure + :type 'boolean) + +(defvar org-odd-levels-only) +(defvar org-keyword-time-regexp) +(defvar org-complex-heading-regexp) +(defvar org-property-end-re) + +(defcustom org-inlinetask-default-state nil + "Non-nil means make inline tasks have a TODO keyword initially. +This should be the state `org-inlinetask-insert-task' should use by +default, or nil if no state should be assigned." + :group 'org-inlinetask + :version "24.1" + :type '(choice + (const :tag "No state" nil) + (string :tag "Specific state"))) + +(defun org-inlinetask-insert-task (&optional no-state) + "Insert an inline task. +If prefix arg NO-STATE is set, ignore `org-inlinetask-default-state'." + (interactive "P") + ;; Error when inside an inline task, except if point was at its very + ;; beginning, in which case the new inline task will be inserted + ;; before this one. + (when (and (org-inlinetask-in-task-p) + (not (and (org-inlinetask-at-task-p) (bolp)))) + (error "Cannot nest inline tasks")) + (or (bolp) (newline)) + (let* ((indent (if org-odd-levels-only + (1- (* 2 org-inlinetask-min-level)) + org-inlinetask-min-level)) + (indent-string (concat (make-string indent ?*) " "))) + (insert indent-string + (if (or no-state (not org-inlinetask-default-state)) + "\n" + (concat org-inlinetask-default-state " \n")) + indent-string "END\n")) + (end-of-line -1)) +(define-key org-mode-map "\C-c\C-xt" 'org-inlinetask-insert-task) + +(defun org-inlinetask-outline-regexp () + "Return string matching an inline task heading. +The number of levels is controlled by `org-inlinetask-min-level'." + (let ((nstars (if org-odd-levels-only + (1- (* org-inlinetask-min-level 2)) + org-inlinetask-min-level))) + (format "^\\(\\*\\{%d,\\}\\)[ \t]+" nstars))) + +(defun org-inlinetask-end-p () + "Return a non-nil value if point is on inline task's END part." + (let ((case-fold-search t)) + (org-match-line (concat (org-inlinetask-outline-regexp) "END[ \t]*$")))) + +(defun org-inlinetask-at-task-p () + "Return non-nil if point is at beginning of an inline task." + (and (org-match-line (concat (org-inlinetask-outline-regexp) "\\(.*\\)")) + (not (org-inlinetask-end-p)))) + +(defun org-inlinetask-in-task-p () + "Return true if point is inside an inline task." + (save-excursion + (beginning-of-line) + (let ((case-fold-search t)) + (or (looking-at-p (concat (org-inlinetask-outline-regexp) "\\(?:.*\\)")) + (and (re-search-forward "^\\*+[ \t]+" nil t) + (org-inlinetask-end-p)))))) + +(defun org-inlinetask-goto-beginning () + "Go to the beginning of the inline task at point." + (end-of-line) + (let ((case-fold-search t) + (inlinetask-re (org-inlinetask-outline-regexp))) + (re-search-backward inlinetask-re nil t) + (when (org-inlinetask-end-p) + (re-search-backward inlinetask-re nil t)))) + +(defun org-inlinetask-goto-end () + "Go to the end of the inline task at point. + Return point." + (save-match-data + (beginning-of-line) + (let ((case-fold-search t) + (inlinetask-re (org-inlinetask-outline-regexp))) + (cond + ((org-inlinetask-end-p) + (forward-line)) + ((looking-at-p inlinetask-re) + (forward-line) + (cond + ((org-inlinetask-end-p) (forward-line)) + ((looking-at-p inlinetask-re)) + ((org-inlinetask-in-task-p) + (re-search-forward inlinetask-re nil t) + (forward-line)) + (t nil))) + (t + (re-search-forward inlinetask-re nil t) + (forward-line))))) + (point)) + +(defun org-inlinetask-get-task-level () + "Get the level of the inline task around. +This assumes the point is inside an inline task." + (save-excursion + (end-of-line) + (re-search-backward (org-inlinetask-outline-regexp) nil t) + (- (match-end 1) (match-beginning 1)))) + +(defun org-inlinetask-promote () + "Promote the inline task at point. +If the task has an end part, promote it. Also, prevents level from +going below `org-inlinetask-min-level'." + (interactive) + (if (not (org-inlinetask-in-task-p)) + (error "Not in an inline task") + (save-excursion + (let* ((lvl (org-inlinetask-get-task-level)) + (next-lvl (org-get-valid-level lvl -1)) + (diff (- next-lvl lvl)) + (down-task (concat (make-string next-lvl ?*))) + beg) + (if (< next-lvl org-inlinetask-min-level) + (error "Cannot promote an inline task at minimum level") + (org-inlinetask-goto-beginning) + (setq beg (point)) + (replace-match down-task nil t nil 1) + (org-inlinetask-goto-end) + (if (eobp) (beginning-of-line) (forward-line -1)) + (unless (= (point) beg) + (replace-match down-task nil t nil 1) + (when org-adapt-indentation + (goto-char beg) + (org-fixup-indentation diff)))))))) + +(defun org-inlinetask-demote () + "Demote the inline task at point. +If the task has an end part, also demote it." + (interactive) + (if (not (org-inlinetask-in-task-p)) + (error "Not in an inline task") + (save-excursion + (let* ((lvl (org-inlinetask-get-task-level)) + (next-lvl (org-get-valid-level lvl 1)) + (diff (- next-lvl lvl)) + (down-task (concat (make-string next-lvl ?*))) + beg) + (org-inlinetask-goto-beginning) + (setq beg (point)) + (replace-match down-task nil t nil 1) + (org-inlinetask-goto-end) + (if (eobp) (beginning-of-line) (forward-line -1)) + (unless (= (point) beg) + (replace-match down-task nil t nil 1) + (when org-adapt-indentation + (goto-char beg) + (org-fixup-indentation diff))))))) + +(defun org-inlinetask-get-current-indentation () + "Get the indentation of the last non-while line above this one." + (save-excursion + (beginning-of-line 1) + (skip-chars-backward " \t\n") + (beginning-of-line 1) + (or (org-at-item-p) + (looking-at "[ \t]*")) + (goto-char (match-end 0)) + (current-column))) + +(defvar org-indent-indentation-per-level) ; defined in org-indent.el + +(defface org-inlinetask '((t :inherit shadow)) + "Face for inlinetask headlines." + :group 'org-faces) + +(defun org-inlinetask-fontify (limit) + "Fontify the inline tasks down to LIMIT." + (let* ((nstars (if org-odd-levels-only + (1- (* 2 (or org-inlinetask-min-level 200))) + (or org-inlinetask-min-level 200))) + (re (concat "^\\(\\*\\)\\(\\*\\{" + (format "%d" (- nstars 3)) + ",\\}\\)\\(\\*\\* .*\\)")) + ;; Virtual indentation will add the warning face on the first + ;; star. Thus, in that case, only hide it. + (start-face (if (and (bound-and-true-p org-indent-mode) + (> org-indent-indentation-per-level 1)) + 'org-hide + 'org-warning))) + (while (re-search-forward re limit t) + (if org-inlinetask-show-first-star + (add-text-properties (match-beginning 1) (match-end 1) + `(face ,start-face font-lock-fontified t))) + (add-text-properties (match-beginning + (if org-inlinetask-show-first-star 2 1)) + (match-end 2) + '(face org-hide font-lock-fontified t)) + (add-text-properties (match-beginning 3) (match-end 3) + '(face org-inlinetask font-lock-fontified t))))) + +(defun org-inlinetask-toggle-visibility () + "Toggle visibility of inline task at point." + (let ((end (save-excursion + (org-inlinetask-goto-end) + (if (bolp) (1- (point)) (point)))) + (start (save-excursion + (org-inlinetask-goto-beginning) + (point-at-eol)))) + (cond + ;; Nothing to show/hide. + ((= end start)) + ;; Inlinetask was folded: expand it. + ((eq (get-char-property (1+ start) 'invisible) 'outline) + (outline-flag-region start end nil) + (org-cycle-hide-drawers 'children)) + (t (outline-flag-region start end t))))) + +(defun org-inlinetask-hide-tasks (state) + "Hide inline tasks in buffer when STATE is `contents' or `children'. +This function is meant to be used in `org-cycle-hook'." + (pcase state + (`contents + (let ((regexp (org-inlinetask-outline-regexp))) + (save-excursion + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (org-inlinetask-toggle-visibility) + (org-inlinetask-goto-end))))) + (`children + (save-excursion + (while + (or (org-inlinetask-at-task-p) + (and (outline-next-heading) (org-inlinetask-at-task-p))) + (org-inlinetask-toggle-visibility) + (org-inlinetask-goto-end)))))) + +(defun org-inlinetask-remove-END-maybe () + "Remove an END line when present." + (when (looking-at (format "\\([ \t]*\n\\)*\\*\\{%d,\\}[ \t]+END[ \t]*$" + org-inlinetask-min-level)) + (replace-match ""))) + +(add-hook 'org-font-lock-hook 'org-inlinetask-fontify) +(add-hook 'org-cycle-hook 'org-inlinetask-hide-tasks) + +(provide 'org-inlinetask) + +;;; org-inlinetask.el ends here diff --git a/elpa/org-9.1.14/org-install.el b/elpa/org-9.1.14/org-install.el new file mode 100644 index 00000000..58359597 --- /dev/null +++ b/elpa/org-9.1.14/org-install.el @@ -0,0 +1,17 @@ +;;; org-install.el --- backward compatibility file for obsolete configuration +;; +;;; Code: +;; +;; The file org-install is obsolete. +;; +;; It is provided here so that (require 'org-install) does not +;; trigger an error for users with obsolete Emacs configuration. +;; You can safely remove (require 'org-install) from your config." + +(provide 'org-install) + +;; Local Variables: +;; no-byte-compile: t +;; coding: utf-8 +;; End: +;;; org-install.el ends here diff --git a/elpa/org-9.1.14/org-irc.el b/elpa/org-9.1.14/org-irc.el new file mode 100644 index 00000000..8901956f --- /dev/null +++ b/elpa/org-9.1.14/org-irc.el @@ -0,0 +1,256 @@ +;;; org-irc.el --- Store Links to IRC Sessions -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2008-2018 Free Software Foundation, Inc. +;; +;; Author: Philip Jackson <emacs@shellarchive.co.uk> +;; Keywords: erc, irc, link, org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file implements links to an IRC session from within Org mode. +;; Org mode loads this module by default - if this is not what you want, +;; configure the variable `org-modules'. +;; +;; Please customize the variable `org-modules' to select +;; extensions you would like to use, and to deselect those which you don't +;; want. +;; +;; Please note that at the moment only ERC is supported. Other clients +;; shouldn't be difficult to add though. +;; +;; Then set `org-irc-link-to-logs' to non-nil if you would like a +;; file:/ type link to be created to the current line in the logs or +;; to t if you would like to create an irc:/ style link. +;; +;; Links within an org buffer might look like this: +;; +;; [[irc:/irc.freenode.net/#emacs/bob][chat with bob in #emacs on freenode]] +;; [[irc:/irc.freenode.net/#emacs][#emacs on freenode]] +;; [[irc:/irc.freenode.net/]] +;; +;; If, when the resulting link is visited, there is no connection to a +;; requested server then one will be created. + +;;; Code: + +(require 'org) + +(declare-function erc-buffer-filter "erc" (predicate &optional proc)) +(declare-function erc-channel-p "erc" (channel)) +(declare-function erc-cmd-JOIN "erc" (channel &optional key)) +(declare-function erc-current-logfile "erc-log" (&optional buffer)) +(declare-function erc-default-target "erc" ()) +(declare-function erc-get-server-nickname-list "erc" ()) +(declare-function erc-logging-enabled "erc-log" (&optional buffer)) +(declare-function erc-prompt "erc" ()) +(declare-function erc-save-buffer-in-logs "erc-log" (&optional buffer)) +(declare-function erc-server-buffer "erc" ()) + +(defvar org-irc-client 'erc + "The IRC client to act on.") + +(defvar org-irc-link-to-logs nil + "Non-nil will store a link to the logs, nil will store an irc: style link.") + +(defvar erc-default-port) ; dynamically scoped from erc.el +(defvar erc-session-port) ; dynamically scoped form erc-backend.el +(defvar erc-session-server) ; dynamically scoped form erc-backend.el + +;; Generic functions/config (extend these for other clients) + +(org-link-set-parameters "irc" :follow #'org-irc-visit :store #'org-irc-store-link) + +(defun org-irc-visit (link) + "Parse LINK and dispatch to the correct function based on the client found." + (let ((link (org-irc-parse-link link))) + (cond + ((eq org-irc-client 'erc) + (org-irc-visit-erc link)) + (t + (error "ERC only known client"))))) + +(defun org-irc-parse-link (link) + "Parse an IRC LINK and return the attributes found. +Parse a LINK that looks like server:port/chan/user (port, chan +and user being optional) and return any of the port, channel or user +attributes that are found." + (let* ((parts (split-string link "/" t)) + (len (length parts))) + (when (or (< len 1) (> len 3)) + (error "Failed to parse link needed 1-3 parts, got %d" len)) + (setcar parts (split-string (car parts) ":" t)) + parts)) + +;;;###autoload +(defun org-irc-store-link () + "Dispatch to the appropriate function to store a link to an IRC session." + (cond + ((eq major-mode 'erc-mode) + (org-irc-erc-store-link)))) + +(defun org-irc-ellipsify-description (string &optional after) + "Remove unnecessary white space from STRING and add ellipses if necessary. +Strip starting and ending white space from STRING and replace any +chars that the value AFTER with `...'" + (let* ((after (number-to-string (or after 30))) + (replace-map (list (cons "^[ \t]*" "") + (cons "[ \t]*$" "") + (cons (concat "^\\(.\\{" after + "\\}\\).*") "\\1...")))) + (dolist (x replace-map string) + (when (string-match (car x) string) + (setq string (replace-match (cdr x) nil nil string)))))) + +;; ERC specific functions + +(defun org-irc-erc-get-line-from-log (erc-line) + "Find the best line to link to from the ERC logs given ERC-LINE as a start. +If the user is on the ERC-prompt then search backward for the +first non-blank line, otherwise return the current line. The +result is a cons of the filename and search string." + (erc-save-buffer-in-logs) + (require 'erc-log) + (with-current-buffer (find-file-noselect (erc-current-logfile)) + (goto-char (point-max)) + (list + (abbreviate-file-name buffer-file-name) + ;; can we get a '::' part? + (if (string= erc-line (erc-prompt)) + (progn + (goto-char (point-at-bol)) + (when (search-backward-regexp "^[^ ]" nil t) + (buffer-substring-no-properties (point-at-bol) + (point-at-eol)))) + (when (search-backward erc-line nil t) + (buffer-substring-no-properties (point-at-bol) + (point-at-eol))))))) + +(defun org-irc-erc-store-link () + "Store a link to the IRC log file or the session itself. +Depending on the variable `org-irc-link-to-logs' store either a +link to the log file for the current session or an irc: link to +the session itself." + (require 'erc-log) + (if org-irc-link-to-logs + (let* ((erc-line (buffer-substring-no-properties + (point-at-bol) (point-at-eol))) + (parsed-line (org-irc-erc-get-line-from-log erc-line))) + (if (erc-logging-enabled nil) + (progn + (org-store-link-props + :type "file" + :description (concat "'" (org-irc-ellipsify-description + (cadr parsed-line) 20) + "' from an IRC conversation") + :link (concat "file:" (car parsed-line) "::" + (cadr parsed-line))) + t) + (error "This ERC session is not being logged"))) + (let* ((link-text (org-irc-get-erc-link)) + (link (org-irc-parse-link link-text))) + (if link-text + (progn + (org-store-link-props + :type "irc" + :link (concat "irc:/" link-text) + :description (concat "irc session `" link-text "'") + :server (car (car link)) + :port (or (string-to-number (cadr (pop link))) erc-default-port) + :nick (pop link)) + t) + (error "Failed to create ('irc:/' style) ERC link"))))) + +(defun org-irc-get-erc-link () + "Return an org compatible irc:/ link from an ERC buffer." + (let* ((session-port (if (numberp erc-session-port) + (number-to-string erc-session-port) + erc-session-port)) + (link (concat erc-session-server ":" session-port))) + (concat link "/" + (if (and (erc-default-target) + (erc-channel-p (erc-default-target)) + (car (get-text-property (point) 'erc-data))) + ;; we can get a nick + (let ((nick (car (get-text-property (point) 'erc-data)))) + (concat (erc-default-target) "/" nick)) + (erc-default-target))))) + +(defun org-irc-get-current-erc-port () + "Return the current port as a number. +Return the current port number or, if none is set, return the ERC +default." + (cond + ((stringp erc-session-port) + (string-to-number erc-session-port)) + ((numberp erc-session-port) + erc-session-port) + (t + erc-default-port))) + +(defun org-irc-visit-erc (link) + "Visit an ERC buffer based on criteria found in LINK." + (require 'erc) + (require 'erc-log) + (let* ((server (car (car link))) + (port (let ((p (cadr (pop link)))) + (if p (string-to-number p) erc-default-port))) + (server-buffer) + (buffer-list + (erc-buffer-filter + (lambda nil + (let ((tmp-server-buf (erc-server-buffer))) + (and tmp-server-buf + (with-current-buffer tmp-server-buf + (and + (eq (org-irc-get-current-erc-port) port) + (string= erc-session-server server) + (setq server-buffer tmp-server-buf))))))))) + (if buffer-list + (let ((chan-name (pop link))) + ;; if we got a channel name then switch to it or join it + (if chan-name + (let ((chan-buf (catch 'found + (dolist (x buffer-list) + (if (string= (buffer-name x) chan-name) + (throw 'found x)))))) + (if chan-buf + (progn + (pop-to-buffer-same-window chan-buf) + ;; if we got a nick, and they're in the chan, + ;; then start a chat with them + (let ((nick (pop link))) + (when nick + (if (member nick (erc-get-server-nickname-list)) + (progn + (goto-char (point-max)) + (insert (concat nick ": "))) + (error "%s not found in %s" nick chan-name))))) + (progn + (pop-to-buffer-same-window server-buffer) + (erc-cmd-JOIN chan-name)))) + (pop-to-buffer-same-window server-buffer))) + ;; no server match, make new connection + (erc-select :server server :port port)))) + +(provide 'org-irc) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-irc.el ends here diff --git a/elpa/org-9.1.14/org-lint.el b/elpa/org-9.1.14/org-lint.el new file mode 100644 index 00000000..9fcb17a2 --- /dev/null +++ b/elpa/org-9.1.14/org-lint.el @@ -0,0 +1,1242 @@ +;;; org-lint.el --- Linting for Org documents -*- lexical-binding: t; -*- + +;; Copyright (C) 2015-2018 Free Software Foundation, Inc. + +;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr> +;; Keywords: outlines, hypermedia, calendar, wp + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This library implements linting for Org syntax. The sole public +;; function is `org-lint', which see. + +;; Internally, the library defines a new structure: +;; `org-lint-checker', with the following slots: + +;; - NAME: Unique check identifier, as a non-nil symbol that doesn't +;; start with an hyphen. +;; +;; The check is done calling the function `org-lint-NAME' with one +;; mandatory argument, the parse tree describing the current Org +;; buffer. Such function calls are wrapped within +;; a `save-excursion' and point is always at `point-min'. Its +;; return value has to be an alist (POSITION MESSAGE) when +;; POSITION refer to the buffer position of the error, as an +;; integer, and MESSAGE is a string describing the error. + +;; - DESCRIPTION: Summary about the check, as a string. + +;; - CATEGORIES: Categories relative to the check, as a list of +;; symbol. They are used for filtering when calling `org-lint'. +;; Checkers not explicitly associated to a category are collected +;; in the `default' one. + +;; - TRUST: The trust level one can have in the check. It is either +;; `low' or `high', depending on the heuristics implemented and +;; the nature of the check. This has an indicative value only and +;; is displayed along reports. + +;; All checks have to be listed in `org-lint--checkers'. + +;; Results are displayed in a special "*Org Lint*" buffer with +;; a dedicated major mode, derived from `tabulated-list-mode'. +;; +;; In addition to the usual key-bindings inherited from it, "C-j" and +;; "TAB" display problematic line reported under point whereas "RET" +;; jumps to it. Also, "h" hides all reports similar to the current +;; one. Additionally, "i" removes them from subsequent reports. + +;; Checks currently implemented are: + +;; - duplicate CUSTOM_ID properties +;; - duplicate NAME values +;; - duplicate targets +;; - duplicate footnote definitions +;; - orphaned affiliated keywords +;; - obsolete affiliated keywords +;; - missing language in src blocks +;; - missing back-end in export blocks +;; - invalid Babel call blocks +;; - NAME values with a colon +;; - deprecated export block syntax +;; - deprecated Babel header properties +;; - wrong header arguments in src blocks +;; - misuse of CATEGORY keyword +;; - "coderef" links with unknown destination +;; - "custom-id" links with unknown destination +;; - "fuzzy" links with unknown destination +;; - "id" links with unknown destination +;; - links to non-existent local files +;; - SETUPFILE keywords with non-existent file parameter +;; - INCLUDE keywords with wrong link parameter +;; - obsolete markup in INCLUDE keyword +;; - unknown items in OPTIONS keyword +;; - spurious macro arguments or invalid macro templates +;; - special properties in properties drawer +;; - obsolete syntax for PROPERTIES drawers +;; - Invalid EFFORT property value +;; - missing definition for footnote references +;; - missing reference for footnote definitions +;; - non-footnote definitions in footnote section +;; - probable invalid keywords +;; - invalid blocks +;; - misplaced planning info line +;; - incomplete drawers +;; - indented diary-sexps +;; - obsolete QUOTE section +;; - obsolete "file+application" link +;; - blank headlines with tags + + +;;; Code: + +(require 'cl-lib) +(require 'org-element) +(require 'org-macro) +(require 'ox) +(require 'ob) + + +;;; Checkers + +(cl-defstruct (org-lint-checker (:copier nil)) + (name 'missing-checker-name) + (description "") + (categories '(default)) + (trust 'high)) ; `low' or `high' + +(defun org-lint-missing-checker-name (_) + (error + "`A checker has no `:name' property. Please verify `org-lint--checkers'")) + +(defconst org-lint--checkers + (list + (make-org-lint-checker + :name 'duplicate-custom-id + :description "Report duplicates CUSTOM_ID properties" + :categories '(link)) + (make-org-lint-checker + :name 'duplicate-name + :description "Report duplicate NAME values" + :categories '(babel link)) + (make-org-lint-checker + :name 'duplicate-target + :description "Report duplicate targets" + :categories '(link)) + (make-org-lint-checker + :name 'duplicate-footnote-definition + :description "Report duplicate footnote definitions" + :categories '(footnote)) + (make-org-lint-checker + :name 'orphaned-affiliated-keywords + :description "Report orphaned affiliated keywords" + :trust 'low) + (make-org-lint-checker + :name 'obsolete-affiliated-keywords + :description "Report obsolete affiliated keywords" + :categories '(obsolete)) + (make-org-lint-checker + :name 'deprecated-export-blocks + :description "Report deprecated export block syntax" + :categories '(obsolete export) + :trust 'low) + (make-org-lint-checker + :name 'deprecated-header-syntax + :description "Report deprecated Babel header syntax" + :categories '(obsolete babel) + :trust 'low) + (make-org-lint-checker + :name 'missing-language-in-src-block + :description "Report missing language in src blocks" + :categories '(babel)) + (make-org-lint-checker + :name 'missing-backend-in-export-block + :description "Report missing back-end in export blocks" + :categories '(export)) + (make-org-lint-checker + :name 'invalid-babel-call-block + :description "Report invalid Babel call blocks" + :categories '(babel)) + (make-org-lint-checker + :name 'colon-in-name + :description "Report NAME values with a colon" + :categories '(babel)) + (make-org-lint-checker + :name 'wrong-header-argument + :description "Report wrong babel headers" + :categories '(babel)) + (make-org-lint-checker + :name 'wrong-header-value + :description "Report invalid value in babel headers" + :categories '(babel) + :trust 'low) + (make-org-lint-checker + :name 'deprecated-category-setup + :description "Report misuse of CATEGORY keyword" + :categories '(obsolete)) + (make-org-lint-checker + :name 'invalid-coderef-link + :description "Report \"coderef\" links with unknown destination" + :categories '(link)) + (make-org-lint-checker + :name 'invalid-custom-id-link + :description "Report \"custom-id\" links with unknown destination" + :categories '(link)) + (make-org-lint-checker + :name 'invalid-fuzzy-link + :description "Report \"fuzzy\" links with unknown destination" + :categories '(link)) + (make-org-lint-checker + :name 'invalid-id-link + :description "Report \"id\" links with unknown destination" + :categories '(link)) + (make-org-lint-checker + :name 'link-to-local-file + :description "Report links to non-existent local files" + :categories '(link) + :trust 'low) + (make-org-lint-checker + :name 'non-existent-setupfile-parameter + :description "Report SETUPFILE keywords with non-existent file parameter" + :trust 'low) + (make-org-lint-checker + :name 'wrong-include-link-parameter + :description "Report INCLUDE keywords with misleading link parameter" + :categories '(export) + :trust 'low) + (make-org-lint-checker + :name 'obsolete-include-markup + :description "Report obsolete markup in INCLUDE keyword" + :categories '(obsolete export) + :trust 'low) + (make-org-lint-checker + :name 'unknown-options-item + :description "Report unknown items in OPTIONS keyword" + :categories '(export) + :trust 'low) + (make-org-lint-checker + :name 'invalid-macro-argument-and-template + :description "Report spurious macro arguments or invalid macro templates" + :categories '(export) + :trust 'low) + (make-org-lint-checker + :name 'special-property-in-properties-drawer + :description "Report special properties in properties drawers" + :categories '(properties)) + (make-org-lint-checker + :name 'obsolete-properties-drawer + :description "Report obsolete syntax for properties drawers" + :categories '(obsolete properties)) + (make-org-lint-checker + :name 'invalid-effort-property + :description "Report invalid duration in EFFORT property" + :categories '(properties)) + (make-org-lint-checker + :name 'undefined-footnote-reference + :description "Report missing definition for footnote references" + :categories '(footnote)) + (make-org-lint-checker + :name 'unreferenced-footnote-definition + :description "Report missing reference for footnote definitions" + :categories '(footnote)) + (make-org-lint-checker + :name 'extraneous-element-in-footnote-section + :description "Report non-footnote definitions in footnote section" + :categories '(footnote)) + (make-org-lint-checker + :name 'invalid-keyword-syntax + :description "Report probable invalid keywords" + :trust 'low) + (make-org-lint-checker + :name 'invalid-block + :description "Report invalid blocks" + :trust 'low) + (make-org-lint-checker + :name 'misplaced-planning-info + :description "Report misplaced planning info line" + :trust 'low) + (make-org-lint-checker + :name 'incomplete-drawer + :description "Report probable incomplete drawers" + :trust 'low) + (make-org-lint-checker + :name 'indented-diary-sexp + :description "Report probable indented diary-sexps" + :trust 'low) + (make-org-lint-checker + :name 'quote-section + :description "Report obsolete QUOTE section" + :categories '(obsolete) + :trust 'low) + (make-org-lint-checker + :name 'file-application + :description "Report obsolete \"file+application\" link" + :categories '(link obsolete)) + (make-org-lint-checker + :name 'empty-headline-with-tags + :description "Report ambiguous empty headlines with tags" + :categories '(headline) + :trust 'low)) + "List of all available checkers.") + +(defun org-lint--collect-duplicates + (ast type extract-key extract-position build-message) + "Helper function to collect duplicates in parse tree AST. + +EXTRACT-KEY is a function extracting key. It is called with +a single argument: the element or object. Comparison is done +with `equal'. + +EXTRACT-POSITION is a function returning position for the report. +It is called with two arguments, the object or element, and the +key. + +BUILD-MESSAGE is a function creating the report message. It is +called with one argument, the key used for comparison." + (let* (keys + originals + reports + (make-report + (lambda (position value) + (push (list position (funcall build-message value)) reports)))) + (org-element-map ast type + (lambda (datum) + (let ((key (funcall extract-key datum))) + (cond + ((not key)) + ((assoc key keys) (cl-pushnew (assoc key keys) originals) + (funcall make-report (funcall extract-position datum key) key)) + (t (push (cons key (funcall extract-position datum key)) keys)))))) + (dolist (e originals reports) (funcall make-report (cdr e) (car e))))) + +(defun org-lint-duplicate-custom-id (ast) + (org-lint--collect-duplicates + ast + 'node-property + (lambda (property) + (and (eq (compare-strings "CUSTOM_ID" nil nil + (org-element-property :key property) nil nil + t) + t) + (org-element-property :value property))) + (lambda (property _) (org-element-property :begin property)) + (lambda (key) (format "Duplicate CUSTOM_ID property \"%s\"" key)))) + +(defun org-lint-duplicate-name (ast) + (org-lint--collect-duplicates + ast + org-element-all-elements + (lambda (datum) (org-element-property :name datum)) + (lambda (datum name) + (goto-char (org-element-property :begin datum)) + (re-search-forward + (format "^[ \t]*#\\+[A-Za-z]+: +%s *$" (regexp-quote name))) + (match-beginning 0)) + (lambda (key) (format "Duplicate NAME \"%s\"" key)))) + +(defun org-lint-duplicate-target (ast) + (org-lint--collect-duplicates + ast + 'target + (lambda (target) (split-string (org-element-property :value target))) + (lambda (target _) (org-element-property :begin target)) + (lambda (key) + (format "Duplicate target <<%s>>" (mapconcat #'identity key " "))))) + +(defun org-lint-duplicate-footnote-definition (ast) + (org-lint--collect-duplicates + ast + 'footnote-definition + (lambda (definition) (org-element-property :label definition)) + (lambda (definition _) (org-element-property :post-affiliated definition)) + (lambda (key) (format "Duplicate footnote definition \"%s\"" key)))) + +(defun org-lint-orphaned-affiliated-keywords (ast) + ;; Ignore orphan RESULTS keywords, which could be generated from + ;; a source block returning no value. + (let ((keywords (cl-set-difference org-element-affiliated-keywords + '("RESULT" "RESULTS") + :test #'equal))) + (org-element-map ast 'keyword + (lambda (k) + (let ((key (org-element-property :key k))) + (and (or (let ((case-fold-search t)) + (string-match-p "\\`ATTR_[-_A-Za-z0-9]+\\'" key)) + (member key keywords)) + (list (org-element-property :post-affiliated k) + (format "Orphaned affiliated keyword: \"%s\"" key)))))))) + +(defun org-lint-obsolete-affiliated-keywords (_) + (let ((regexp (format "^[ \t]*#\\+%s:" + (regexp-opt '("DATA" "LABEL" "RESNAME" "SOURCE" + "SRCNAME" "TBLNAME" "RESULT" "HEADERS") + t))) + reports) + (while (re-search-forward regexp nil t) + (let ((key (upcase (match-string-no-properties 1)))) + (when (< (point) + (org-element-property :post-affiliated (org-element-at-point))) + (push + (list (line-beginning-position) + (format + "Obsolete affiliated keyword: \"%s\". Use \"%s\" instead" + key + (pcase key + ("HEADERS" "HEADER") + ("RESULT" "RESULTS") + (_ "NAME")))) + reports)))) + reports)) + +(defun org-lint-deprecated-export-blocks (ast) + (let ((deprecated '("ASCII" "BEAMER" "HTML" "LATEX" "MAN" "MARKDOWN" "MD" + "ODT" "ORG" "TEXINFO"))) + (org-element-map ast 'special-block + (lambda (b) + (let ((type (org-element-property :type b))) + (when (member-ignore-case type deprecated) + (list + (org-element-property :post-affiliated b) + (format + "Deprecated syntax for export block. Use \"BEGIN_EXPORT %s\" \ +instead" + type)))))))) + +(defun org-lint-deprecated-header-syntax (ast) + (let* ((deprecated-babel-properties + (mapcar (lambda (arg) (symbol-name (car arg))) + org-babel-common-header-args-w-values)) + (deprecated-re + (format "\\`%s[ \t]" (regexp-opt deprecated-babel-properties t)))) + (org-element-map ast '(keyword node-property) + (lambda (datum) + (let ((key (org-element-property :key datum))) + (pcase (org-element-type datum) + (`keyword + (let ((value (org-element-property :value datum))) + (and (string= key "PROPERTY") + (string-match deprecated-re value) + (list (org-element-property :begin datum) + (format "Deprecated syntax for \"%s\". \ +Use header-args instead" + (match-string-no-properties 1 value)))))) + (`node-property + (and (member-ignore-case key deprecated-babel-properties) + (list + (org-element-property :begin datum) + (format "Deprecated syntax for \"%s\". \ +Use :header-args: instead" + key)))))))))) + +(defun org-lint-missing-language-in-src-block (ast) + (org-element-map ast 'src-block + (lambda (b) + (unless (org-element-property :language b) + (list (org-element-property :post-affiliated b) + "Missing language in source block"))))) + +(defun org-lint-missing-backend-in-export-block (ast) + (org-element-map ast 'export-block + (lambda (b) + (unless (org-element-property :type b) + (list (org-element-property :post-affiliated b) + "Missing back-end in export block"))))) + +(defun org-lint-invalid-babel-call-block (ast) + (org-element-map ast 'babel-call + (lambda (b) + (cond + ((not (org-element-property :call b)) + (list (org-element-property :post-affiliated b) + "Invalid syntax in babel call block")) + ((let ((h (org-element-property :end-header b))) + (and h (string-match-p "\\`\\[.*\\]\\'" h))) + (list + (org-element-property :post-affiliated b) + "Babel call's end header must not be wrapped within brackets")))))) + +(defun org-lint-deprecated-category-setup (ast) + (org-element-map ast 'keyword + (let (category-flag) + (lambda (k) + (cond + ((not (string= (org-element-property :key k) "CATEGORY")) nil) + (category-flag + (list (org-element-property :post-affiliated k) + "Spurious CATEGORY keyword. Set :CATEGORY: property instead")) + (t (setf category-flag t) nil)))))) + +(defun org-lint-invalid-coderef-link (ast) + (let ((info (list :parse-tree ast))) + (org-element-map ast 'link + (lambda (link) + (let ((ref (org-element-property :path link))) + (and (equal (org-element-property :type link) "coderef") + (not (ignore-errors (org-export-resolve-coderef ref info))) + (list (org-element-property :begin link) + (format "Unknown coderef \"%s\"" ref)))))))) + +(defun org-lint-invalid-custom-id-link (ast) + (let ((info (list :parse-tree ast))) + (org-element-map ast 'link + (lambda (link) + (and (equal (org-element-property :type link) "custom-id") + (not (ignore-errors (org-export-resolve-id-link link info))) + (list (org-element-property :begin link) + (format "Unknown custom ID \"%s\"" + (org-element-property :path link)))))))) + +(defun org-lint-invalid-fuzzy-link (ast) + (let ((info (list :parse-tree ast))) + (org-element-map ast 'link + (lambda (link) + (and (equal (org-element-property :type link) "fuzzy") + (not (ignore-errors (org-export-resolve-fuzzy-link link info))) + (list (org-element-property :begin link) + (format "Unknown fuzzy location \"%s\"" + (let ((path (org-element-property :path link))) + (if (string-prefix-p "*" path) + (substring path 1) + path))))))))) + +(defun org-lint-invalid-id-link (ast) + (org-element-map ast 'link + (lambda (link) + (let ((id (org-element-property :path link))) + (and (equal (org-element-property :type link) "id") + (not (org-id-find id)) + (list (org-element-property :begin link) + (format "Unknown ID \"%s\"" id))))))) + +(defun org-lint-special-property-in-properties-drawer (ast) + (org-element-map ast 'node-property + (lambda (p) + (let ((key (org-element-property :key p))) + (and (member-ignore-case key org-special-properties) + (list (org-element-property :begin p) + (format + "Special property \"%s\" found in a properties drawer" + key))))))) + +(defun org-lint-obsolete-properties-drawer (ast) + (org-element-map ast 'drawer + (lambda (d) + (when (equal (org-element-property :drawer-name d) "PROPERTIES") + (let ((section (org-element-lineage d '(section)))) + (unless (org-element-map section 'property-drawer #'identity nil t) + (list (org-element-property :post-affiliated d) + (if (save-excursion + (goto-char (org-element-property :post-affiliated d)) + (forward-line -1) + (or (org-at-heading-p) (org-at-planning-p))) + "Incorrect contents for PROPERTIES drawer" + "Incorrect location for PROPERTIES drawer")))))))) + +(defun org-lint-invalid-effort-property (ast) + (org-element-map ast 'node-property + (lambda (p) + (when (equal "EFFORT" (org-element-property :key p)) + (let ((value (org-element-property :value p))) + (and (org-string-nw-p value) + (not (org-duration-p value)) + (list (org-element-property :begin p) + (format "Invalid effort duration format: %S" value)))))))) + +(defun org-lint-link-to-local-file (ast) + (org-element-map ast 'link + (lambda (l) + (when (equal (org-element-property :type l) "file") + (let ((file (org-link-unescape (org-element-property :path l)))) + (and (not (file-remote-p file)) + (not (file-exists-p file)) + (list (org-element-property :begin l) + (format (if (org-element-lineage l '(link)) + "Link to non-existent image file \"%s\"\ + in link description" + "Link to non-existent local file \"%s\"") + file)))))))) + +(defun org-lint-non-existent-setupfile-parameter (ast) + (org-element-map ast 'keyword + (lambda (k) + (when (equal (org-element-property :key k) "SETUPFILE") + (let ((file (org-unbracket-string + "\"" "\"" + (org-element-property :value k)))) + (and (not (file-remote-p file)) + (not (file-exists-p file)) + (list (org-element-property :begin k) + (format "Non-existent setup file \"%s\"" file)))))))) + +(defun org-lint-wrong-include-link-parameter (ast) + (org-element-map ast 'keyword + (lambda (k) + (when (equal (org-element-property :key k) "INCLUDE") + (let* ((value (org-element-property :value k)) + (path + (and (string-match "^\\(\".+\"\\|\\S-+\\)[ \t]*" value) + (save-match-data + (org-unbracket-string "\"" "\"" (match-string 1 value)))))) + (if (not path) + (list (org-element-property :post-affiliated k) + "Missing location argument in INCLUDE keyword") + (let* ((file (org-string-nw-p + (if (string-match "::\\(.*\\)\\'" path) + (substring path 0 (match-beginning 0)) + path))) + (search (and (not (equal file path)) + (org-string-nw-p (match-string 1 path))))) + (if (and file + (not (file-remote-p file)) + (not (file-exists-p file))) + (list (org-element-property :post-affiliated k) + "Non-existent file argument in INCLUDE keyword") + (let* ((visiting (if file (find-buffer-visiting file) + (current-buffer))) + (buffer (or visiting (find-file-noselect file)))) + (unwind-protect + (with-current-buffer buffer + (when (and search + (not + (ignore-errors + (let ((org-link-search-inhibit-query t)) + (org-link-search search nil t))))) + (list (org-element-property :post-affiliated k) + (format + "Invalid search part \"%s\" in INCLUDE keyword" + search)))) + (unless visiting (kill-buffer buffer)))))))))))) + +(defun org-lint-obsolete-include-markup (ast) + (let ((regexp (format "\\`\\(?:\".+\"\\|\\S-+\\)[ \t]+%s" + (regexp-opt + '("ASCII" "BEAMER" "HTML" "LATEX" "MAN" "MARKDOWN" "MD" + "ODT" "ORG" "TEXINFO") + t)))) + (org-element-map ast 'keyword + (lambda (k) + (when (equal (org-element-property :key k) "INCLUDE") + (let ((case-fold-search t) + (value (org-element-property :value k))) + (when (string-match regexp value) + (let ((markup (match-string-no-properties 1 value))) + (list (org-element-property :post-affiliated k) + (format "Obsolete markup \"%s\" in INCLUDE keyword. \ +Use \"export %s\" instead" + markup + markup)))))))))) + +(defun org-lint-unknown-options-item (ast) + (let ((allowed (delq nil + (append + (mapcar (lambda (o) (nth 2 o)) org-export-options-alist) + (cl-mapcan + (lambda (b) + (mapcar (lambda (o) (nth 2 o)) + (org-export-backend-options b))) + org-export-registered-backends)))) + reports) + (org-element-map ast 'keyword + (lambda (k) + (when (string= (org-element-property :key k) "OPTIONS") + (let ((value (org-element-property :value k)) + (start 0)) + (while (string-match "\\(.+?\\):\\((.*?)\\|\\S-*\\)[ \t]*" + value + start) + (setf start (match-end 0)) + (let ((item (match-string 1 value))) + (unless (member item allowed) + (push (list (org-element-property :post-affiliated k) + (format "Unknown OPTIONS item \"%s\"" item)) + reports)))))))) + reports)) + +(defun org-lint-invalid-macro-argument-and-template (ast) + (let ((extract-placeholders + (lambda (template) + (let ((start 0) + args) + (while (string-match "\\$\\([1-9][0-9]*\\)" template start) + (setf start (match-end 0)) + (push (string-to-number (match-string 1 template)) args)) + (sort (org-uniquify args) #'<)))) + reports) + ;; Check arguments for macro templates. + (org-element-map ast 'keyword + (lambda (k) + (when (string= (org-element-property :key k) "MACRO") + (let* ((value (org-element-property :value k)) + (name (and (string-match "^\\S-+" value) + (match-string 0 value))) + (template (and name + (org-trim (substring value (match-end 0)))))) + (cond + ((not name) + (push (list (org-element-property :post-affiliated k) + "Missing name in MACRO keyword") + reports)) + ((not (org-string-nw-p template)) + (push (list (org-element-property :post-affiliated k) + "Missing template in macro \"%s\"" name) + reports)) + (t + (unless (let ((args (funcall extract-placeholders template))) + (equal (number-sequence 1 (or (org-last args) 0)) args)) + (push (list (org-element-property :post-affiliated k) + (format "Unused placeholders in macro \"%s\"" + name)) + reports)))))))) + ;; Check arguments for macros. + (org-macro-initialize-templates) + (let ((templates (append + (mapcar (lambda (m) (cons m "$1")) + '("author" "date" "email" "title" "results")) + org-macro-templates))) + (org-element-map ast 'macro + (lambda (macro) + (let* ((name (org-element-property :key macro)) + (template (cdr (assoc-string name templates t)))) + (if (not template) + (push (list (org-element-property :begin macro) + (format "Undefined macro \"%s\"" name)) + reports) + (let ((arg-numbers (funcall extract-placeholders template))) + (when arg-numbers + (let ((spurious-args + (nthcdr (apply #'max arg-numbers) + (org-element-property :args macro)))) + (when spurious-args + (push + (list (org-element-property :begin macro) + (format "Unused argument%s in macro \"%s\": %s" + (if (> (length spurious-args) 1) "s" "") + name + (mapconcat (lambda (a) (format "\"%s\"" a)) + spurious-args + ", "))) + reports)))))))))) + reports)) + +(defun org-lint-undefined-footnote-reference (ast) + (let ((definitions (org-element-map ast 'footnote-definition + (lambda (f) (org-element-property :label f))))) + (org-element-map ast 'footnote-reference + (lambda (f) + (let ((label (org-element-property :label f))) + (and (eq 'standard (org-element-property :type f)) + (not (member label definitions)) + (list (org-element-property :begin f) + (format "Missing definition for footnote [%s]" + label)))))))) + +(defun org-lint-unreferenced-footnote-definition (ast) + (let ((references (org-element-map ast 'footnote-reference + (lambda (f) (org-element-property :label f))))) + (org-element-map ast 'footnote-definition + (lambda (f) + (let ((label (org-element-property :label f))) + (and label + (not (member label references)) + (list (org-element-property :post-affiliated f) + (format "No reference for footnote definition [%s]" + label)))))))) + +(defun org-lint-colon-in-name (ast) + (org-element-map ast org-element-all-elements + (lambda (e) + (let ((name (org-element-property :name e))) + (and name + (string-match-p ":" name) + (list (progn + (goto-char (org-element-property :begin e)) + (re-search-forward + (format "^[ \t]*#\\+\\w+: +%s *$" (regexp-quote name))) + (match-beginning 0)) + (format + "Name \"%s\" contains a colon; Babel cannot use it as input" + name))))))) + +(defun org-lint-misplaced-planning-info (_) + (let ((case-fold-search t) + reports) + (while (re-search-forward org-planning-line-re nil t) + (unless (memq (org-element-type (org-element-at-point)) + '(comment-block example-block export-block planning + src-block verse-block)) + (push (list (line-beginning-position) "Misplaced planning info line") + reports))) + reports)) + +(defun org-lint-incomplete-drawer (_) + (let (reports) + (while (re-search-forward org-drawer-regexp nil t) + (let ((name (org-trim (match-string-no-properties 0))) + (element (org-element-at-point))) + (pcase (org-element-type element) + ((or `drawer `property-drawer) + (goto-char (org-element-property :end element)) + nil) + ((or `comment-block `example-block `export-block `src-block + `verse-block) + nil) + (_ + (push (list (line-beginning-position) + (format "Possible incomplete drawer \"%s\"" name)) + reports))))) + reports)) + +(defun org-lint-indented-diary-sexp (_) + (let (reports) + (while (re-search-forward "^[ \t]+%%(" nil t) + (unless (memq (org-element-type (org-element-at-point)) + '(comment-block diary-sexp example-block export-block + src-block verse-block)) + (push (list (line-beginning-position) "Possible indented diary-sexp") + reports))) + reports)) + +(defun org-lint-invalid-block (_) + (let ((case-fold-search t) + (regexp "^[ \t]*#\\+\\(BEGIN\\|END\\)\\(?::\\|_[^[:space:]]*\\)?[ \t]*") + reports) + (while (re-search-forward regexp nil t) + (let ((name (org-trim (buffer-substring-no-properties + (line-beginning-position) (line-end-position))))) + (cond + ((and (string-prefix-p "END" (match-string 1) t) + (not (eolp))) + (push (list (line-beginning-position) + (format "Invalid block closing line \"%s\"" name)) + reports)) + ((not (memq (org-element-type (org-element-at-point)) + '(center-block comment-block dynamic-block example-block + export-block quote-block special-block + src-block verse-block))) + (push (list (line-beginning-position) + (format "Possible incomplete block \"%s\"" + name)) + reports))))) + reports)) + +(defun org-lint-invalid-keyword-syntax (_) + (let ((regexp "^[ \t]*#\\+\\([^[:space:]:]*\\)\\(?: \\|$\\)") + (exception-re + (format "[ \t]*#\\+%s\\(\\[.*\\]\\)?:\\(?: \\|$\\)" + (regexp-opt org-element-dual-keywords))) + reports) + (while (re-search-forward regexp nil t) + (let ((name (match-string-no-properties 1))) + (unless (or (string-prefix-p "BEGIN" name t) + (string-prefix-p "END" name t) + (save-excursion + (beginning-of-line) + (let ((case-fold-search t)) (looking-at exception-re)))) + (push (list (match-beginning 0) + (format "Possible missing colon in keyword \"%s\"" name)) + reports)))) + reports)) + +(defun org-lint-extraneous-element-in-footnote-section (ast) + (org-element-map ast 'headline + (lambda (h) + (and (org-element-property :footnote-section-p h) + (org-element-map (org-element-contents h) + (cl-remove-if + (lambda (e) + (memq e '(comment comment-block footnote-definition + property-drawer section))) + org-element-all-elements) + (lambda (e) + (not (and (eq (org-element-type e) 'headline) + (org-element-property :commentedp e)))) + nil t '(footnote-definition property-drawer)) + (list (org-element-property :begin h) + "Extraneous elements in footnote section are not exported"))))) + +(defun org-lint-quote-section (ast) + (org-element-map ast '(headline inlinetask) + (lambda (h) + (let ((title (org-element-property :raw-value h))) + (and (or (string-prefix-p "QUOTE " title) + (string-prefix-p (concat org-comment-string " QUOTE ") title)) + (list (org-element-property :begin h) + "Deprecated QUOTE section")))))) + +(defun org-lint-file-application (ast) + (org-element-map ast 'link + (lambda (l) + (let ((app (org-element-property :application l))) + (and app + (list (org-element-property :begin l) + (format "Deprecated \"file+%s\" link type" app))))))) + +(defun org-lint-wrong-header-argument (ast) + (let* ((reports) + (verify + (lambda (datum language headers) + (let ((allowed + ;; If LANGUAGE is specified, restrict allowed + ;; headers to both LANGUAGE-specific and default + ;; ones. Otherwise, accept headers from any loaded + ;; language. + (append + org-babel-header-arg-names + (cl-mapcan + (lambda (l) + (let ((v (intern (format "org-babel-header-args:%s" l)))) + (and (boundp v) (mapcar #'car (symbol-value v))))) + (if language (list language) + (mapcar #'car org-babel-load-languages)))))) + (dolist (header headers) + (let ((h (symbol-name (car header))) + (p (or (org-element-property :post-affiliated datum) + (org-element-property :begin datum)))) + (cond + ((not (string-prefix-p ":" h)) + (push + (list p + (format "Missing colon in header argument \"%s\"" h)) + reports)) + ((assoc-string (substring h 1) allowed)) + (t (push (list p (format "Unknown header argument \"%s\"" h)) + reports))))))))) + (org-element-map ast '(babel-call inline-babel-call inline-src-block keyword + node-property src-block) + (lambda (datum) + (pcase (org-element-type datum) + ((or `babel-call `inline-babel-call) + (funcall verify + datum + nil + (cl-mapcan #'org-babel-parse-header-arguments + (list + (org-element-property :inside-header datum) + (org-element-property :end-header datum))))) + (`inline-src-block + (funcall verify + datum + (org-element-property :language datum) + (org-babel-parse-header-arguments + (org-element-property :parameters datum)))) + (`keyword + (when (string= (org-element-property :key datum) "PROPERTY") + (let ((value (org-element-property :value datum))) + (when (string-match "\\`header-args\\(?::\\(\\S-+\\)\\)?\\+? *" + value) + (funcall verify + datum + (match-string 1 value) + (org-babel-parse-header-arguments + (substring value (match-end 0)))))))) + (`node-property + (let ((key (org-element-property :key datum))) + (when (let ((case-fold-search t)) + (string-match "\\`HEADER-ARGS\\(?::\\(\\S-+\\)\\)?\\+?" + key)) + (funcall verify + datum + (match-string 1 key) + (org-babel-parse-header-arguments + (org-element-property :value datum)))))) + (`src-block + (funcall verify + datum + (org-element-property :language datum) + (cl-mapcan #'org-babel-parse-header-arguments + (cons (org-element-property :parameters datum) + (org-element-property :header datum)))))))) + reports)) + +(defun org-lint-wrong-header-value (ast) + (let (reports) + (org-element-map ast + '(babel-call inline-babel-call inline-src-block src-block) + (lambda (datum) + (let* ((type (org-element-type datum)) + (language (org-element-property :language datum)) + (allowed-header-values + (append (and language + (let ((v (intern (concat "org-babel-header-args:" + language)))) + (and (boundp v) (symbol-value v)))) + org-babel-common-header-args-w-values)) + (datum-header-values + (org-babel-parse-header-arguments + (org-trim + (pcase type + (`src-block + (mapconcat + #'identity + (cons (org-element-property :parameters datum) + (org-element-property :header datum)) + " ")) + (`inline-src-block + (or (org-element-property :parameters datum) "")) + (_ + (concat + (org-element-property :inside-header datum) + " " + (org-element-property :end-header datum)))))))) + (dolist (header datum-header-values) + (let ((allowed-values + (cdr (assoc-string (substring (symbol-name (car header)) 1) + allowed-header-values)))) + (unless (memq allowed-values '(:any nil)) + (let ((values (cdr header)) + groups-alist) + (dolist (v (if (stringp values) (split-string values) + (list values))) + (let ((valid-value nil)) + (catch 'exit + (dolist (group allowed-values) + (cond + ((not (funcall + (if (stringp v) #'assoc-string #'assoc) + v group)) + (when (memq :any group) + (setf valid-value t) + (push (cons group v) groups-alist))) + ((assq group groups-alist) + (push + (list + (or (org-element-property :post-affiliated datum) + (org-element-property :begin datum)) + (format + "Forbidden combination in header \"%s\": %s, %s" + (car header) + (cdr (assq group groups-alist)) + v)) + reports) + (throw 'exit nil)) + (t (push (cons group v) groups-alist) + (setf valid-value t)))) + (unless valid-value + (push + (list + (or (org-element-property :post-affiliated datum) + (org-element-property :begin datum)) + (format "Unknown value \"%s\" for header \"%s\"" + v + (car header))) + reports)))))))))))) + reports)) + +(defun org-lint-empty-headline-with-tags (ast) + (org-element-map ast '(headline inlinetask) + (lambda (h) + (let ((title (org-element-property :raw-value h))) + (and (string-match-p "\\`:[[:alnum:]_@#%:]+:\\'" title) + (list (org-element-property :begin h) + (format "Headline containing only tags is ambiguous: %S" + title))))))) + + +;;; Reports UI + +(defvar org-lint--report-mode-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map tabulated-list-mode-map) + (define-key map (kbd "RET") 'org-lint--jump-to-source) + (define-key map (kbd "TAB") 'org-lint--show-source) + (define-key map (kbd "C-j") 'org-lint--show-source) + (define-key map (kbd "h") 'org-lint--hide-checker) + (define-key map (kbd "i") 'org-lint--ignore-checker) + map) + "Local keymap for `org-lint--report-mode' buffers.") + +(define-derived-mode org-lint--report-mode tabulated-list-mode "OrgLint" + "Major mode used to display reports emitted during linting. +\\{org-lint--report-mode-map}" + (setf tabulated-list-format + `[("Line" 6 + (lambda (a b) + (< (string-to-number (aref (cadr a) 0)) + (string-to-number (aref (cadr b) 0)))) + :right-align t) + ("Trust" 5 t) + ("Warning" 0 t)]) + (tabulated-list-init-header)) + +(defun org-lint--generate-reports (buffer checkers) + "Generate linting report for BUFFER. + +CHECKERS is the list of checkers used. + +Return an alist (ID [LINE TRUST DESCRIPTION CHECKER]), suitable +for `tabulated-list-printer'." + (with-current-buffer buffer + (save-excursion + (goto-char (point-min)) + (let ((ast (org-element-parse-buffer)) + (id 0) + (last-line 1) + (last-pos 1)) + ;; Insert unique ID for each report. Replace buffer positions + ;; with line numbers. + (mapcar + (lambda (report) + (list + (cl-incf id) + (apply #'vector + (cons + (progn + (goto-char (car report)) + (beginning-of-line) + (prog1 (number-to-string + (cl-incf last-line + (count-lines last-pos (point)))) + (setf last-pos (point)))) + (cdr report))))) + ;; Insert trust level in generated reports. Also sort them + ;; by buffer position in order to optimize lines computation. + (sort (cl-mapcan + (lambda (c) + (let ((trust (symbol-name (org-lint-checker-trust c)))) + (mapcar + (lambda (report) + (list (car report) trust (nth 1 report) c)) + (save-excursion + (funcall + (intern (format "org-lint-%s" + (org-lint-checker-name c))) + ast))))) + checkers) + #'car-less-than-car)))))) + +(defvar-local org-lint--source-buffer nil + "Source buffer associated to current report buffer.") + +(defvar-local org-lint--local-checkers nil + "List of checkers used to build current report.") + +(defun org-lint--refresh-reports () + (setq tabulated-list-entries + (org-lint--generate-reports org-lint--source-buffer + org-lint--local-checkers)) + (tabulated-list-print)) + +(defun org-lint--current-line () + "Return current report line, as a number." + (string-to-number (aref (tabulated-list-get-entry) 0))) + +(defun org-lint--current-checker (&optional entry) + "Return current report checker. +When optional argument ENTRY is non-nil, use this entry instead +of current one." + (aref (if entry (nth 1 entry) (tabulated-list-get-entry)) 3)) + +(defun org-lint--display-reports (source checkers) + "Display linting reports for buffer SOURCE. +CHECKERS is the list of checkers used." + (let ((buffer (get-buffer-create "*Org Lint*"))) + (with-current-buffer buffer + (org-lint--report-mode) + (setf org-lint--source-buffer source) + (setf org-lint--local-checkers checkers) + (org-lint--refresh-reports) + (tabulated-list-print) + (add-hook 'tabulated-list-revert-hook #'org-lint--refresh-reports nil t)) + (pop-to-buffer buffer))) + +(defun org-lint--jump-to-source () + "Move to source line that generated the report at point." + (interactive) + (let ((l (org-lint--current-line))) + (switch-to-buffer-other-window org-lint--source-buffer) + (org-goto-line l) + (org-show-set-visibility 'local) + (recenter))) + +(defun org-lint--show-source () + "Show source line that generated the report at point." + (interactive) + (let ((buffer (current-buffer))) + (org-lint--jump-to-source) + (switch-to-buffer-other-window buffer))) + +(defun org-lint--hide-checker () + "Hide all reports from checker that generated the report at point." + (interactive) + (let ((c (org-lint--current-checker))) + (setf tabulated-list-entries + (cl-remove-if (lambda (e) (equal c (org-lint--current-checker e))) + tabulated-list-entries)) + (tabulated-list-print))) + +(defun org-lint--ignore-checker () + "Ignore all reports from checker that generated the report at point. +Checker will also be ignored in all subsequent reports." + (interactive) + (setf org-lint--local-checkers + (remove (org-lint--current-checker) org-lint--local-checkers)) + (org-lint--hide-checker)) + + +;;; Public function + +;;;###autoload +(defun org-lint (&optional arg) + "Check current Org buffer for syntax mistakes. + +By default, run all checkers. With a `\\[universal-argument]' prefix ARG, \ +select one +category of checkers only. With a `\\[universal-argument] \ +\\[universal-argument]' prefix, run one precise +checker by its name. + +ARG can also be a list of checker names, as symbols, to run." + (interactive "P") + (unless (derived-mode-p 'org-mode) (user-error "Not in an Org buffer")) + (when (called-interactively-p 'any) + (message "Org linting process starting...")) + (let ((checkers + (pcase arg + (`nil org-lint--checkers) + (`(4) + (let ((category + (completing-read + "Checker category: " + (mapcar #'org-lint-checker-categories org-lint--checkers) + nil t))) + (cl-remove-if-not + (lambda (c) + (assoc-string (org-lint-checker-categories c) category)) + org-lint--checkers))) + (`(16) + (list + (let ((name (completing-read + "Checker name: " + (mapcar #'org-lint-checker-name org-lint--checkers) + nil t))) + (catch 'exit + (dolist (c org-lint--checkers) + (when (string= (org-lint-checker-name c) name) + (throw 'exit c))))))) + ((pred consp) + (cl-remove-if-not (lambda (c) (memq (org-lint-checker-name c) arg)) + org-lint--checkers)) + (_ (user-error "Invalid argument `%S' for `org-lint'" arg))))) + (if (not (called-interactively-p 'any)) + (org-lint--generate-reports (current-buffer) checkers) + (org-lint--display-reports (current-buffer) checkers) + (message "Org linting process completed")))) + + +(provide 'org-lint) +;;; org-lint.el ends here diff --git a/elpa/org-9.1.14/org-list.el b/elpa/org-9.1.14/org-list.el new file mode 100644 index 00000000..5e5e7c4b --- /dev/null +++ b/elpa/org-9.1.14/org-list.el @@ -0,0 +1,3613 @@ +;;; org-list.el --- Plain lists for Org -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Bastien Guerry <bzg@gnu.org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file contains the code dealing with plain lists in Org mode. + +;; The core concept behind lists is their structure. A structure is +;; a snapshot of the list, in the shape of a data tree (see +;; `org-list-struct'). + +;; Once the list structure is stored, it is possible to make changes +;; on it that will be mirrored to the real list or to get information +;; about the list, using accessors and methods provided in the +;; library. Most of them require the use of one or two helper +;; functions, namely `org-list-parents-alist' and +;; `org-list-prevs-alist'. + +;; Structure is eventually applied to the buffer with +;; `org-list-write-struct'. This function repairs (bullets, +;; indentation, checkboxes) the list in the process. It should be +;; called near the end of any function working on structures. + +;; Thus, a function applying to lists should usually follow this +;; template: + +;; 1. Verify point is in a list and grab item beginning (with the same +;; function `org-in-item-p'). If the function requires the cursor +;; to be at item's bullet, `org-at-item-p' is more selective. It +;; is also possible to move point to the closest item with +;; `org-list-search-backward', or `org-list-search-forward', +;; applied to the function `org-item-beginning-re'. + +;; 2. Get list structure with `org-list-struct'. + +;; 3. Compute one, or both, helper functions, +;; (`org-list-parents-alist', `org-list-prevs-alist') depending on +;; needed accessors. + +;; 4. Proceed with the modifications, using methods and accessors. + +;; 5. Verify and apply structure to buffer, using +;; `org-list-write-struct'. + +;; 6. If changes made to the list might have modified check-boxes, +;; call `org-update-checkbox-count-maybe'. + +;; Computing a structure can be a costly operation on huge lists (a +;; few thousand lines long). Thus, code should follow the rule: +;; "collect once, use many". As a corollary, it is usually a bad idea +;; to use directly an interactive function inside the code, as those, +;; being independent entities, read the whole list structure another +;; time. + +;;; Code: + +(require 'cl-lib) +(require 'org-macs) +(require 'org-compat) + +(defvar org-M-RET-may-split-line) +(defvar org-auto-align-tags) +(defvar org-blank-before-new-entry) +(defvar org-clock-string) +(defvar org-closed-string) +(defvar org-deadline-string) +(defvar org-description-max-indent) +(defvar org-done-keywords) +(defvar org-drawer-regexp) +(defvar org-element-all-objects) +(defvar org-inhibit-startup) +(defvar org-odd-levels-only) +(defvar org-outline-regexp-bol) +(defvar org-scheduled-string) +(defvar org-todo-line-regexp) +(defvar org-ts-regexp) +(defvar org-ts-regexp-both) + +(declare-function org-at-heading-p "org" (&optional invisible-ok)) +(declare-function org-back-to-heading "org" (&optional invisible-ok)) +(declare-function org-before-first-heading-p "org" ()) +(declare-function org-combine-plists "org" (&rest plists)) +(declare-function org-current-level "org" ()) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-context "org-element" (&optional element)) +(declare-function org-element-interpret-data "org-element" (data)) +(declare-function + org-element-lineage "org-element" (blob &optional types with-self)) +(declare-function org-element-macro-interpreter "org-element" (macro ##)) +(declare-function + org-element-map "org-element" + (data types fun &optional info first-match no-recursion with-affiliated)) +(declare-function org-element-normalize-string "org-element" (s)) +(declare-function org-element-parse-buffer "org-element" + (&optional granularity visible-only)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-put-property "org-element" + (element property value)) +(declare-function org-element-set-element "org-element" (old new)) +(declare-function org-element-type "org-element" (element)) +(declare-function org-element-update-syntax "org-element" ()) +(declare-function org-end-of-meta-data "org" (&optional full)) +(declare-function org-entry-get "org" + (pom property &optional inherit literal-nil)) +(declare-function org-export-create-backend "ox" (&rest rest) t) +(declare-function org-export-data-with-backend "ox" (data backend info)) +(declare-function org-export-get-backend "ox" (name)) +(declare-function org-export-get-environment "ox" + (&optional backend subtreep ext-plist)) +(declare-function org-export-get-next-element "ox" + (blob info &optional n)) +(declare-function org-export-with-backend "ox" + (backend data &optional contents info)) +(declare-function org-fix-tags-on-the-fly "org" ()) +(declare-function org-get-indentation "org" (&optional line)) +(declare-function org-get-todo-state "org" ()) +(declare-function org-in-block-p "org" (names)) +(declare-function org-in-regexp "org" (re &optional nlines visually)) +(declare-function org-inlinetask-goto-beginning "org-inlinetask" ()) +(declare-function org-inlinetask-goto-end "org-inlinetask" ()) +(declare-function org-inlinetask-in-task-p "org-inlinetask" ()) +(declare-function org-inlinetask-outline-regexp "org-inlinetask" ()) +(declare-function org-level-increment "org" ()) +(declare-function org-narrow-to-subtree "org" ()) +(declare-function org-outline-level "org" ()) +(declare-function org-previous-line-empty-p "org" ()) +(declare-function org-reduced-level "org" (L)) +(declare-function org-remove-indentation "org" (code &optional n)) +(declare-function org-show-subtree "org" ()) +(declare-function org-sort-remove-invisible "org" (S)) +(declare-function org-time-string-to-seconds "org" (s)) +(declare-function org-timer-hms-to-secs "org-timer" (hms)) +(declare-function org-timer-item "org-timer" (&optional arg)) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function org-uniquify "org" (list)) +(declare-function org-invisible-p "org" (&optional pos)) +(declare-function outline-flag-region "outline" (from to flag)) +(declare-function outline-next-heading "outline" ()) +(declare-function outline-previous-heading "outline" ()) + + + +;;; Configuration variables + +(defgroup org-plain-lists nil + "Options concerning plain lists in Org mode." + :tag "Org Plain lists" + :group 'org-structure) + +(defcustom org-cycle-include-plain-lists t + "When t, make TAB cycle visibility on plain list items. +Cycling plain lists works only when the cursor is on a plain list +item. When the cursor is on an outline heading, plain lists are +treated as text. This is the most stable way of handling this, +which is why it is the default. + +When this is the symbol `integrate', then integrate plain list +items when cycling, as if they were children of outline headings. + +This setting can lead to strange effects when switching visibility +to `children', because the first \"child\" in a subtree decides +what children should be listed. If that first \"child\" is a +plain list item with an implied large level number, all true +children and grand children of the outline heading will be +exposed in a children' view." + :group 'org-plain-lists + :group 'org-cycle + :type '(choice + (const :tag "Never" nil) + (const :tag "With cursor in plain list (recommended)" t) + (const :tag "As children of outline headings" integrate))) + +(defcustom org-list-demote-modify-bullet nil + "Default bullet type installed when demoting an item. +This is an association list, for each bullet type, this alist will point +to the bullet that should be used when this item is demoted. +For example, + + (setq org-list-demote-modify-bullet + \\='((\"+\" . \"-\") (\"-\" . \"+\") (\"*\" . \"+\"))) + +will make + + + Movies + + Silence of the Lambs + + My Cousin Vinny + + Books + + The Hunt for Red October + + The Road to Omaha + +into + + + Movies + - Silence of the Lambs + - My Cousin Vinny + + Books + - The Hunt for Red October + - The Road to Omaha" + :group 'org-plain-lists + :type '(repeat + (cons + (choice :tag "If the current bullet is " + (const "-") + (const "+") + (const "*") + (const "1.") + (const "1)")) + (choice :tag "demotion will change it to" + (const "-") + (const "+") + (const "*") + (const "1.") + (const "1)"))))) + +(defcustom org-plain-list-ordered-item-terminator t + "The character that makes a line with leading number an ordered list item. +Valid values are ?. and ?\). To get both terminators, use t. + +This variable needs to be set before org.el is loaded. If you +need to make a change while Emacs is running, use the customize +interface or run the following code after updating it: + + `\\[org-element-update-syntax]'" + :group 'org-plain-lists + :type '(choice (const :tag "dot like in \"2.\"" ?.) + (const :tag "paren like in \"2)\"" ?\)) + (const :tag "both" t)) + :set (lambda (var val) (set var val) + (when (featurep 'org-element) (org-element-update-syntax)))) + +(defcustom org-list-allow-alphabetical nil + "Non-nil means single character alphabetical bullets are allowed. + +Both uppercase and lowercase are handled. Lists with more than +26 items will fallback to standard numbering. Alphabetical +counters like \"[@c]\" will be recognized. + +This variable needs to be set before org.el is loaded. If you +need to make a change while Emacs is running, use the customize +interface or run the following code after updating it: + + `\\[org-element-update-syntax]'" + :group 'org-plain-lists + :version "24.1" + :type 'boolean + :set (lambda (var val) (set var val) + (when (featurep 'org-element) (org-element-update-syntax)))) + +(defcustom org-list-two-spaces-after-bullet-regexp nil + "A regular expression matching bullets that should have 2 spaces after them. +When nil, no bullet will have two spaces after them. When +a string, it will be used as a regular expression. When the +bullet type of a list is changed, the new bullet type will be +matched against this regexp. If it matches, there will be two +spaces instead of one after the bullet in each item of the list." + :group 'org-plain-lists + :type '(choice + (const :tag "never" nil) + (regexp))) + +(defcustom org-list-automatic-rules '((checkbox . t) + (indent . t)) + "Non-nil means apply set of rules when acting on lists. +\\<org-mode-map> +By default, automatic actions are taken when using + `\\[org-meta-return]', + `\\[org-metaright]', + `\\[org-metaleft]', + `\\[org-shiftmetaright]', + `\\[org-shiftmetaleft]', + `\\[org-ctrl-c-minus]', + `\\[org-toggle-checkbox]', + `\\[org-insert-todo-heading]'. + +You can disable individually these rules by setting them to nil. +Valid rules are: + +checkbox when non-nil, checkbox statistics is updated each time + you either insert a new checkbox or toggle a checkbox. +indent when non-nil, indenting or outdenting list top-item + with its subtree will move the whole list and + outdenting a list whose bullet is * to column 0 will + change that bullet to \"-\"." + :group 'org-plain-lists + :version "24.1" + :type '(alist :tag "Sets of rules" + :key-type + (choice + (const :tag "Checkbox" checkbox) + (const :tag "Indent" indent)) + :value-type + (boolean :tag "Activate" :value t))) + +(defcustom org-list-use-circular-motion nil + "Non-nil means commands implying motion in lists should be cyclic. +\\<org-mode-map> +In that case, the item following the last item is the first one, +and the item preceding the first item is the last one. + +This affects the behavior of + `\\[org-move-item-up]', + `\\[org-move-item-down]', + `\\[org-next-item]', + `\\[org-previous-item]'." + :group 'org-plain-lists + :version "24.1" + :type 'boolean) + +(defvar org-checkbox-statistics-hook nil + "Hook that is run whenever Org thinks checkbox statistics should be updated. +This hook runs even if checkbox rule in +`org-list-automatic-rules' does not apply, so it can be used to +implement alternative ways of collecting statistics +information.") + +(defcustom org-checkbox-hierarchical-statistics t + "Non-nil means checkbox statistics counts only the state of direct children. +When nil, all boxes below the cookie are counted. +This can be set to nil on a per-node basis using a COOKIE_DATA property +with the word \"recursive\" in the value." + :group 'org-plain-lists + :type 'boolean) + +(defcustom org-list-description-max-indent 20 + "Maximum indentation for the second line of a description list. +When the indentation would be larger than this, it will become +5 characters instead." + :group 'org-plain-lists + :type 'integer) + +(defcustom org-list-indent-offset 0 + "Additional indentation for sub-items in a list. +By setting this to a small number, usually 1 or 2, one can more +clearly distinguish sub-items in a list." + :group 'org-plain-lists + :version "24.1" + :type 'integer) + +(defcustom org-list-radio-list-templates + '((latex-mode "% BEGIN RECEIVE ORGLST %n +% END RECEIVE ORGLST %n +\\begin{comment} +#+ORGLST: SEND %n org-list-to-latex +- +\\end{comment}\n") + (texinfo-mode "@c BEGIN RECEIVE ORGLST %n +@c END RECEIVE ORGLST %n +@ignore +#+ORGLST: SEND %n org-list-to-texinfo +- +@end ignore\n") + (html-mode "<!-- BEGIN RECEIVE ORGLST %n --> +<!-- END RECEIVE ORGLST %n --> +<!-- +#+ORGLST: SEND %n org-list-to-html +- +-->\n")) + "Templates for radio lists in different major modes. +All occurrences of %n in a template will be replaced with the name of the +list, obtained by prompting the user." + :group 'org-plain-lists + :type '(repeat + (list (symbol :tag "Major mode") + (string :tag "Format")))) + +(defvar org-list-forbidden-blocks '("example" "verse" "src" "export") + "Names of blocks where lists are not allowed. +Names must be in lower case.") + +(defvar org-list-export-context '(block inlinetask) + "Context types where lists will be interpreted during export. + +Valid types are `drawer', `inlinetask' and `block'. More +specifically, type `block' is determined by the variable +`org-list-forbidden-blocks'.") + + + +;;; Predicates and regexps + +(defconst org-list-end-re "^[ \t]*\n[ \t]*\n" + "Regex matching the end of a plain list.") + +(defconst org-list-full-item-re + (concat "^[ \t]*\\(\\(?:[-+*]\\|\\(?:[0-9]+\\|[A-Za-z]\\)[.)]\\)\\(?:[ \t]+\\|$\\)\\)" + "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?" + "\\(?:\\(\\[[ X-]\\]\\)\\(?:[ \t]+\\|$\\)\\)?" + "\\(?:\\(.*\\)[ \t]+::\\(?:[ \t]+\\|$\\)\\)?") + "Matches a list item and puts everything into groups: +group 1: bullet +group 2: counter +group 3: checkbox +group 4: description tag") + +(defun org-item-re () + "Return the correct regular expression for plain lists." + (let ((term (cond + ((eq org-plain-list-ordered-item-terminator t) "[.)]") + ((= org-plain-list-ordered-item-terminator ?\)) ")") + ((= org-plain-list-ordered-item-terminator ?.) "\\.") + (t "[.)]"))) + (alpha (if org-list-allow-alphabetical "\\|[A-Za-z]" ""))) + (concat "\\([ \t]*\\([-+]\\|\\(\\([0-9]+" alpha "\\)" term + "\\)\\)\\|[ \t]+\\*\\)\\([ \t]+\\|$\\)"))) + +(defsubst org-item-beginning-re () + "Regexp matching the beginning of a plain list item." + (concat "^" (org-item-re))) + +(defun org-list-at-regexp-after-bullet-p (regexp) + "Is point at a list item with REGEXP after bullet?" + (and (org-at-item-p) + (save-excursion + (goto-char (match-end 0)) + (let ((counter-re (concat "\\(?:\\[@\\(?:start:\\)?" + (if org-list-allow-alphabetical + "\\([0-9]+\\|[A-Za-z]\\)" + "[0-9]+") + "\\][ \t]*\\)"))) + ;; Ignore counter if any + (when (looking-at counter-re) (goto-char (match-end 0)))) + (looking-at regexp)))) + +(defun org-list-in-valid-context-p () + "Is point in a context where lists are allowed?" + (not (org-in-block-p org-list-forbidden-blocks))) + +(defun org-in-item-p () + "Return item beginning position when in a plain list, nil otherwise." + (save-excursion + (beginning-of-line) + (let* ((case-fold-search t) + (context (org-list-context)) + (lim-up (car context)) + (inlinetask-re (and (featurep 'org-inlinetask) + (org-inlinetask-outline-regexp))) + (item-re (org-item-re)) + ;; Indentation isn't meaningful when point starts at an empty + ;; line or an inline task. + (ind-ref (if (or (looking-at "^[ \t]*$") + (and inlinetask-re (looking-at inlinetask-re))) + 10000 + (org-get-indentation)))) + (cond + ((eq (nth 2 context) 'invalid) nil) + ((looking-at item-re) (point)) + (t + ;; Detect if cursor in amidst `org-list-end-re'. First, count + ;; number HL of hard lines it takes, then call `org-in-regexp' + ;; to compute its boundaries END-BOUNDS. When point is + ;; in-between, move cursor before regexp beginning. + (let ((hl 0) (i -1) end-bounds) + (when (and (progn + (while (setq i (string-match + "[\r\n]" org-list-end-re (1+ i))) + (setq hl (1+ hl))) + (setq end-bounds (org-in-regexp org-list-end-re hl))) + (>= (point) (car end-bounds)) + (< (point) (cdr end-bounds))) + (goto-char (car end-bounds)) + (forward-line -1))) + ;; Look for an item, less indented that reference line. + (catch 'exit + (while t + (let ((ind (org-get-indentation))) + (cond + ;; This is exactly what we want. + ((and (looking-at item-re) (< ind ind-ref)) + (throw 'exit (point))) + ;; At upper bound of search or looking at the end of a + ;; previous list: search is over. + ((<= (point) lim-up) (throw 'exit nil)) + ((looking-at org-list-end-re) (throw 'exit nil)) + ;; Skip blocks, drawers, inline-tasks, blank lines + ((and (looking-at "^[ \t]*#\\+end_") + (re-search-backward "^[ \t]*#\\+begin_" lim-up t))) + ((and (looking-at "^[ \t]*:END:") + (re-search-backward org-drawer-regexp lim-up t)) + (beginning-of-line)) + ((and inlinetask-re (looking-at inlinetask-re)) + (org-inlinetask-goto-beginning) + (forward-line -1)) + ((looking-at "^[ \t]*$") (forward-line -1)) + ;; Text at column 0 cannot belong to a list: stop. + ((zerop ind) (throw 'exit nil)) + ;; Normal text less indented than reference line, take + ;; it as new reference. + ((< ind ind-ref) + (setq ind-ref ind) + (forward-line -1)) + (t (forward-line -1))))))))))) + +(defun org-at-item-p () + "Is point in a line starting a hand-formatted item?" + (save-excursion + (beginning-of-line) + (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))) + +(defun org-at-item-bullet-p () + "Is point at the bullet of a plain list item?" + (and (org-at-item-p) + (not (member (char-after) '(?\ ?\t))) + (< (point) (match-end 0)))) + +(defun org-at-item-timer-p () + "Is point at a line starting a plain list item with a timer?" + (org-list-at-regexp-after-bullet-p + "\\([0-9]+:[0-9]+:[0-9]+\\)[ \t]+::[ \t]+")) + +(defun org-at-item-description-p () + "Is point at a description list item?" + (org-list-at-regexp-after-bullet-p "\\(\\S-.+\\)[ \t]+::\\([ \t]+\\|$\\)")) + +(defun org-at-item-checkbox-p () + "Is point at a line starting a plain-list item with a checklet?" + (org-list-at-regexp-after-bullet-p "\\(\\[[- X]\\]\\)[ \t]+")) + +(defun org-at-item-counter-p () + "Is point at a line starting a plain-list item with a counter?" + (and (org-at-item-p) + (looking-at org-list-full-item-re) + (match-string 2))) + + + +;;; Structures and helper functions + +(defun org-list-context () + "Determine context, and its boundaries, around point. + +Context will be a cell like (MIN MAX CONTEXT) where MIN and MAX +are boundaries and CONTEXT is a symbol among `drawer', `block', +`invalid', `inlinetask' and nil. + +Contexts `block' and `invalid' refer to `org-list-forbidden-blocks'." + (save-match-data + (save-excursion + (org-with-limited-levels + (beginning-of-line) + (let ((case-fold-search t) (pos (point)) beg end context-type + ;; Get positions of surrounding headings. This is the + ;; default context. + (lim-up (or (save-excursion (and (ignore-errors (org-back-to-heading t)) + (point))) + (point-min))) + (lim-down (or (save-excursion (outline-next-heading)) (point-max)))) + ;; Is point inside a drawer? + (let ((end-re "^[ \t]*:END:") + (beg-re org-drawer-regexp)) + (when (save-excursion + (and (not (looking-at beg-re)) + (not (looking-at end-re)) + (setq beg (and (re-search-backward beg-re lim-up t) + (1+ (point-at-eol)))) + (setq end (or (and (re-search-forward end-re lim-down t) + (1- (match-beginning 0))) + lim-down)) + (>= end pos))) + (setq lim-up beg lim-down end context-type 'drawer))) + ;; Is point strictly in a block, and of which type? + (let ((block-re "^[ \t]*#\\+\\(begin\\|end\\)_") type) + (when (save-excursion + (and (not (looking-at block-re)) + (setq beg (and (re-search-backward block-re lim-up t) + (1+ (point-at-eol)))) + (looking-at "^[ \t]*#\\+begin_\\(\\S-+\\)") + (setq type (downcase (match-string 1))) + (goto-char beg) + (setq end (or (and (re-search-forward block-re lim-down t) + (1- (point-at-bol))) + lim-down)) + (>= end pos) + (equal (downcase (match-string 1)) "end"))) + (setq lim-up beg lim-down end + context-type (if (member type org-list-forbidden-blocks) + 'invalid 'block)))) + ;; Is point in an inlinetask? + (when (and (featurep 'org-inlinetask) + (save-excursion + (let* ((beg-re (org-inlinetask-outline-regexp)) + (end-re (concat beg-re "END[ \t]*$"))) + (and (not (looking-at "^\\*+")) + (setq beg (and (re-search-backward beg-re lim-up t) + (1+ (point-at-eol)))) + (not (looking-at end-re)) + (setq end (and (re-search-forward end-re lim-down t) + (1- (match-beginning 0)))) + (> (point) pos))))) + (setq lim-up beg lim-down end context-type 'inlinetask)) + ;; Return context boundaries and type. + (list lim-up lim-down context-type)))))) + +(defun org-list-struct () + "Return structure of list at point. + +A list structure is an alist where key is point at item, and +values are: +1. indentation, +2. bullet with trailing whitespace, +3. bullet counter, if any, +4. checkbox, if any, +5. description tag, if any, +6. position at item end. + +Thus the following list, where numbers in parens are +point-at-bol: + +- [X] first item (1) + 1. sub-item 1 (18) + 5. [@5] sub-item 2 (34) + some other text belonging to first item (55) +- last item (97) + + tag :: description (109) + (131) + +will get the following structure: + + ((1 0 \"- \" nil \"[X]\" nil 97) + (18 2 \"1. \" nil nil nil 34) + (34 2 \"5. \" \"5\" nil nil 55) + (97 0 \"- \" nil nil nil 131) + (109 2 \"+ \" nil nil \"tag\" 131)) + +Assume point is at an item." + (save-excursion + (beginning-of-line) + (let* ((case-fold-search t) + (context (org-list-context)) + (lim-up (car context)) + (lim-down (nth 1 context)) + (text-min-ind 10000) + (item-re (org-item-re)) + (inlinetask-re (and (featurep 'org-inlinetask) + (org-inlinetask-outline-regexp))) + (beg-cell (cons (point) (org-get-indentation))) + itm-lst itm-lst-2 end-lst end-lst-2 struct + (assoc-at-point + (function + ;; Return association at point. + (lambda (ind) + (looking-at org-list-full-item-re) + (let ((bullet (match-string-no-properties 1))) + (list (point) + ind + bullet + (match-string-no-properties 2) ; counter + (match-string-no-properties 3) ; checkbox + ;; Description tag. + (and (string-match-p "[-+*]" bullet) + (match-string-no-properties 4))))))) + (end-before-blank + (function + ;; Ensure list ends at the first blank line. + (lambda () + (skip-chars-backward " \r\t\n") + (min (1+ (point-at-eol)) lim-down))))) + ;; 1. Read list from starting item to its beginning, and save + ;; top item position and indentation in BEG-CELL. Also store + ;; ending position of items in END-LST. + (save-excursion + (catch 'exit + (while t + (let ((ind (org-get-indentation))) + (cond + ((<= (point) lim-up) + ;; At upward limit: if we ended at an item, store it, + ;; else dismiss useless data recorded above BEG-CELL. + ;; Jump to part 2. + (throw 'exit + (setq itm-lst + (if (not (looking-at item-re)) + (memq (assq (car beg-cell) itm-lst) itm-lst) + (setq beg-cell (cons (point) ind)) + (cons (funcall assoc-at-point ind) itm-lst))))) + ;; Looking at a list ending regexp. Dismiss useless + ;; data recorded above BEG-CELL. Jump to part 2. + ((looking-at org-list-end-re) + (throw 'exit + (setq itm-lst + (memq (assq (car beg-cell) itm-lst) itm-lst)))) + ;; Point is at an item. Add data to ITM-LST. It may + ;; also end a previous item: save it in END-LST. If + ;; ind is less or equal than BEG-CELL and there is no + ;; end at this ind or lesser, this item becomes the new + ;; BEG-CELL. + ((looking-at item-re) + (push (funcall assoc-at-point ind) itm-lst) + (push (cons ind (point)) end-lst) + (when (< ind text-min-ind) (setq beg-cell (cons (point) ind))) + (forward-line -1)) + ;; Skip blocks, drawers, inline tasks, blank lines. + ((and (looking-at "^[ \t]*#\\+end_") + (re-search-backward "^[ \t]*#\\+begin_" lim-up t))) + ((and (looking-at "^[ \t]*:END:") + (re-search-backward org-drawer-regexp lim-up t)) + (beginning-of-line)) + ((and inlinetask-re (looking-at inlinetask-re)) + (org-inlinetask-goto-beginning) + (forward-line -1)) + ((looking-at "^[ \t]*$") + (forward-line -1)) + ;; From there, point is not at an item. Interpret + ;; line's indentation: + ;; - text at column 0 is necessarily out of any list. + ;; Dismiss data recorded above BEG-CELL. Jump to + ;; part 2. + ;; - any other case may be an ending position for an + ;; hypothetical item above. Store it and proceed. + ((zerop ind) + (throw 'exit + (setq itm-lst + (memq (assq (car beg-cell) itm-lst) itm-lst)))) + (t + (when (< ind text-min-ind) (setq text-min-ind ind)) + (push (cons ind (point)) end-lst) + (forward-line -1))))))) + ;; 2. Read list from starting point to its end, that is until we + ;; get out of context, or that a non-item line is less or + ;; equally indented than BEG-CELL's cdr. Also, store ending + ;; position of items in END-LST-2. + (catch 'exit + (while t + (let ((ind (org-get-indentation))) + (cond + ((>= (point) lim-down) + ;; At downward limit: this is de facto the end of the + ;; list. Save point as an ending position, and jump to + ;; part 3. + (throw 'exit + (push (cons 0 (funcall end-before-blank)) end-lst-2))) + ;; Looking at a list ending regexp. Save point as an + ;; ending position and jump to part 3. + ((looking-at org-list-end-re) + (throw 'exit (push (cons 0 (point)) end-lst-2))) + ((looking-at item-re) + ;; Point is at an item. Add data to ITM-LST-2. It may + ;; also end a previous item, so save it in END-LST-2. + (push (funcall assoc-at-point ind) itm-lst-2) + (push (cons ind (point)) end-lst-2) + (forward-line 1)) + ;; Skip inline tasks and blank lines along the way + ((and inlinetask-re (looking-at inlinetask-re)) + (org-inlinetask-goto-end)) + ((looking-at "^[ \t]*$") + (forward-line 1)) + ;; Ind is lesser or equal than BEG-CELL's. The list is + ;; over: store point as an ending position and jump to + ;; part 3. + ((<= ind (cdr beg-cell)) + (throw 'exit + (push (cons 0 (funcall end-before-blank)) end-lst-2))) + ;; Else, if ind is lesser or equal than previous item's, + ;; this is an ending position: store it. In any case, + ;; skip block or drawer at point, and move to next line. + (t + (when (<= ind (nth 1 (car itm-lst-2))) + (push (cons ind (point)) end-lst-2)) + (cond + ((and (looking-at "^[ \t]*#\\+begin_") + (re-search-forward "^[ \t]*#\\+end_" lim-down t))) + ((and (looking-at org-drawer-regexp) + (re-search-forward "^[ \t]*:END:" lim-down t)))) + (forward-line 1)))))) + (setq struct (append itm-lst (cdr (nreverse itm-lst-2))) + end-lst (append end-lst (cdr (nreverse end-lst-2)))) + ;; 3. Associate each item to its end position. + (org-list-struct-assoc-end struct end-lst) + ;; 4. Return STRUCT + struct))) + +(defun org-list-struct-assoc-end (struct end-list) + "Associate proper ending point to items in STRUCT. + +END-LIST is a pseudo-alist where car is indentation and cdr is +ending position. + +This function modifies STRUCT." + (let ((endings end-list)) + (mapc + (lambda (elt) + (let ((pos (car elt)) + (ind (nth 1 elt))) + ;; Remove end candidates behind current item. + (while (or (<= (cdar endings) pos)) + (pop endings)) + ;; Add end position to item assoc. + (let ((old-end (nthcdr 6 elt)) + (new-end (assoc-default ind endings '<=))) + (if old-end + (setcar old-end new-end) + (setcdr elt (append (cdr elt) (list new-end))))))) + struct))) + +(defun org-list-prevs-alist (struct) + "Return alist between item and previous item in STRUCT." + (let ((item-end-alist (mapcar (lambda (e) (cons (car e) (nth 6 e))) + struct))) + (mapcar (lambda (e) + (let ((prev (car (rassq (car e) item-end-alist)))) + (cons (car e) prev))) + struct))) + +(defun org-list-parents-alist (struct) + "Return alist between item and parent in STRUCT." + (let* ((ind-to-ori (list (list (nth 1 (car struct))))) + (top-item (org-list-get-top-point struct)) + (prev-pos (list top-item))) + (cons prev-pos + (mapcar (lambda (item) + (let ((pos (car item)) + (ind (nth 1 item)) + (prev-ind (caar ind-to-ori))) + (push pos prev-pos) + (cond + ((> prev-ind ind) + ;; A sub-list is over. Find the associated + ;; origin in IND-TO-ORI. If it cannot be + ;; found (ill-formed list), set its parent as + ;; the first item less indented. If there is + ;; none, make it a top-level item. + (setq ind-to-ori + (or (member (assq ind ind-to-ori) ind-to-ori) + (catch 'exit + (mapc + (lambda (e) + (when (< (car e) ind) + (throw 'exit (member e ind-to-ori)))) + ind-to-ori) + (list (list ind))))) + (cons pos (cdar ind-to-ori))) + ;; A sub-list starts. Every item at IND will + ;; have previous item as its parent. + ((< prev-ind ind) + (let ((origin (nth 1 prev-pos))) + (push (cons ind origin) ind-to-ori) + (cons pos origin))) + ;; Another item in the same sub-list: it shares + ;; the same parent as the previous item. + (t (cons pos (cdar ind-to-ori)))))) + (cdr struct))))) + + + +;;; Accessors + +(defsubst org-list-get-nth (n key struct) + "Return the Nth value of KEY in STRUCT." + (nth n (assq key struct))) + +(defun org-list-set-nth (n key struct new) + "Set the Nth value of KEY in STRUCT to NEW. +\nThis function modifies STRUCT." + (setcar (nthcdr n (assq key struct)) new)) + +(defsubst org-list-get-ind (item struct) + "Return indentation of ITEM in STRUCT." + (org-list-get-nth 1 item struct)) + +(defun org-list-set-ind (item struct ind) + "Set indentation of ITEM in STRUCT to IND. +\nThis function modifies STRUCT." + (org-list-set-nth 1 item struct ind)) + +(defsubst org-list-get-bullet (item struct) + "Return bullet of ITEM in STRUCT." + (org-list-get-nth 2 item struct)) + +(defun org-list-set-bullet (item struct bullet) + "Set bullet of ITEM in STRUCT to BULLET. +\nThis function modifies STRUCT." + (org-list-set-nth 2 item struct bullet)) + +(defsubst org-list-get-counter (item struct) + "Return counter of ITEM in STRUCT." + (org-list-get-nth 3 item struct)) + +(defsubst org-list-get-checkbox (item struct) + "Return checkbox of ITEM in STRUCT or nil." + (org-list-get-nth 4 item struct)) + +(defun org-list-set-checkbox (item struct checkbox) + "Set checkbox of ITEM in STRUCT to CHECKBOX. +\nThis function modifies STRUCT." + (org-list-set-nth 4 item struct checkbox)) + +(defsubst org-list-get-tag (item struct) + "Return end position of ITEM in STRUCT." + (org-list-get-nth 5 item struct)) + +(defun org-list-get-item-end (item struct) + "Return end position of ITEM in STRUCT." + (org-list-get-nth 6 item struct)) + +(defun org-list-get-item-end-before-blank (item struct) + "Return point at end of ITEM in STRUCT, before any blank line. +Point returned is at end of line." + (save-excursion + (goto-char (org-list-get-item-end item struct)) + (skip-chars-backward " \r\t\n") + (point-at-eol))) + +(defun org-list-get-parent (item struct parents) + "Return parent of ITEM or nil. +STRUCT is the list structure. PARENTS is the alist of parents, +as returned by `org-list-parents-alist'." + (let ((parents (or parents (org-list-parents-alist struct)))) + (cdr (assq item parents)))) + +(defun org-list-has-child-p (item struct) + "Non-nil if ITEM has a child. + +STRUCT is the list structure. + +Value returned is the position of the first child of ITEM." + (let ((ind (org-list-get-ind item struct)) + (child-maybe (car (nth 1 (member (assq item struct) struct))))) + (when (and child-maybe + (< ind (org-list-get-ind child-maybe struct))) + child-maybe))) + +(defun org-list-get-next-item (item _struct prevs) + "Return next item in same sub-list as ITEM, or nil. +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'." + (car (rassq item prevs))) + +(defun org-list-get-prev-item (item _struct prevs) + "Return previous item in same sub-list as ITEM, or nil. +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'." + (cdr (assq item prevs))) + +(defun org-list-get-subtree (item struct) + "List all items having ITEM as a common ancestor, or nil. +STRUCT is the list structure." + (let* ((item-end (org-list-get-item-end item struct)) + (sub-struct (cdr (member (assq item struct) struct))) + subtree) + (catch 'exit + (mapc (lambda (e) + (let ((pos (car e))) + (if (< pos item-end) (push pos subtree) (throw 'exit nil)))) + sub-struct)) + (nreverse subtree))) + +(defun org-list-get-all-items (item struct prevs) + "List all items in the same sub-list as ITEM. +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'." + (let ((prev-item item) + (next-item item) + before-item after-item) + (while (setq prev-item (org-list-get-prev-item prev-item struct prevs)) + (push prev-item before-item)) + (while (setq next-item (org-list-get-next-item next-item struct prevs)) + (push next-item after-item)) + (append before-item (list item) (nreverse after-item)))) + +(defun org-list-get-children (item _struct parents) + "List all children of ITEM, or nil. +STRUCT is the list structure. PARENTS is the alist of parents, +as returned by `org-list-parents-alist'." + (let (all child) + (while (setq child (car (rassq item parents))) + (setq parents (cdr (member (assq child parents) parents))) + (push child all)) + (nreverse all))) + +(defun org-list-get-top-point (struct) + "Return point at beginning of list. +STRUCT is the list structure." + (caar struct)) + +(defun org-list-get-bottom-point (struct) + "Return point at bottom of list. +STRUCT is the list structure." + (apply #'max + (mapcar (lambda (e) (org-list-get-item-end (car e) struct)) struct))) + +(defun org-list-get-list-begin (item struct prevs) + "Return point at beginning of sub-list ITEM belongs. +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'." + (let ((first-item item) prev-item) + (while (setq prev-item (org-list-get-prev-item first-item struct prevs)) + (setq first-item prev-item)) + first-item)) + +(defalias 'org-list-get-first-item 'org-list-get-list-begin) + +(defun org-list-get-last-item (item struct prevs) + "Return point at last item of sub-list ITEM belongs. +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'." + (let ((last-item item) next-item) + (while (setq next-item (org-list-get-next-item last-item struct prevs)) + (setq last-item next-item)) + last-item)) + +(defun org-list-get-list-end (item struct prevs) + "Return point at end of sub-list ITEM belongs. +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'." + (org-list-get-item-end (org-list-get-last-item item struct prevs) struct)) + +(defun org-list-get-list-type (item struct prevs) + "Return the type of the list containing ITEM, as a symbol. + +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'. + +Possible types are `descriptive', `ordered' and `unordered'. The +type is determined by the first item of the list." + (let ((first (org-list-get-list-begin item struct prevs))) + (cond + ((string-match-p "[[:alnum:]]" (org-list-get-bullet first struct)) 'ordered) + ((org-list-get-tag first struct) 'descriptive) + (t 'unordered)))) + +(defun org-list-get-item-number (item struct prevs parents) + "Return ITEM's sequence number. + +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'. PARENTS is the +alist of ancestors, as returned by `org-list-parents-alist'. + +Return value is a list of integers. Counters have an impact on +that value." + (let ((get-relative-number + (function + (lambda (item struct prevs) + ;; Return relative sequence number of ITEM in the sub-list + ;; it belongs. STRUCT is the list structure. PREVS is + ;; the alist of previous items. + (let ((seq 0) (pos item) counter) + (while (and (not (setq counter (org-list-get-counter pos struct))) + (setq pos (org-list-get-prev-item pos struct prevs))) + (cl-incf seq)) + (if (not counter) (1+ seq) + (cond + ((string-match "[A-Za-z]" counter) + (+ (- (string-to-char (upcase (match-string 0 counter))) 64) + seq)) + ((string-match "[0-9]+" counter) + (+ (string-to-number (match-string 0 counter)) seq)) + (t (1+ seq))))))))) + ;; Cons each parent relative number into return value (OUT). + (let ((out (list (funcall get-relative-number item struct prevs))) + (parent item)) + (while (setq parent (org-list-get-parent parent struct parents)) + (push (funcall get-relative-number parent struct prevs) out)) + ;; Return value. + out))) + + + +;;; Searching + +(defun org-list-search-generic (search re bound noerr) + "Search a string in valid contexts for lists. +Arguments SEARCH, RE, BOUND and NOERR are similar to those used +in `re-search-forward'." + (catch 'exit + (let ((origin (point))) + (while t + ;; 1. No match: return to origin or bound, depending on NOERR. + (unless (funcall search re bound noerr) + (throw 'exit (and (goto-char (if (memq noerr '(t nil)) origin bound)) + nil))) + ;; 2. Match in valid context: return point. Else, continue + ;; searching. + (when (org-list-in-valid-context-p) (throw 'exit (point))))))) + +(defun org-list-search-backward (regexp &optional bound noerror) + "Like `re-search-backward' but stop only where lists are recognized. +Arguments REGEXP, BOUND and NOERROR are similar to those used in +`re-search-backward'." + (org-list-search-generic #'re-search-backward + regexp (or bound (point-min)) noerror)) + +(defun org-list-search-forward (regexp &optional bound noerror) + "Like `re-search-forward' but stop only where lists are recognized. +Arguments REGEXP, BOUND and NOERROR are similar to those used in +`re-search-forward'." + (org-list-search-generic #'re-search-forward + regexp (or bound (point-max)) noerror)) + + + +;;; Methods on structures + +(defsubst org-list-bullet-string (bullet) + "Return BULLET with the correct number of whitespaces. +It determines the number of whitespaces to append by looking at +`org-list-two-spaces-after-bullet-regexp'." + (save-match-data + (let ((spaces (if (and org-list-two-spaces-after-bullet-regexp + (string-match + org-list-two-spaces-after-bullet-regexp bullet)) + " " + " "))) + (if (string-match "\\S-+\\([ \t]*\\)" bullet) + (replace-match spaces nil nil bullet 1) + bullet)))) + +(defun org-list-swap-items (beg-A beg-B struct) + "Swap item starting at BEG-A with item starting at BEG-B in STRUCT. + +Blank lines at the end of items are left in place. Item +visibility is preserved. Return the new structure after the +changes. + +Assume BEG-A is lesser than BEG-B and that BEG-A and BEG-B belong +to the same sub-list. + +This function modifies STRUCT." + (save-excursion + (let* ((end-A-no-blank (org-list-get-item-end-before-blank beg-A struct)) + (end-B-no-blank (org-list-get-item-end-before-blank beg-B struct)) + (end-A (org-list-get-item-end beg-A struct)) + (end-B (org-list-get-item-end beg-B struct)) + (size-A (- end-A-no-blank beg-A)) + (size-B (- end-B-no-blank beg-B)) + (body-A (buffer-substring beg-A end-A-no-blank)) + (body-B (buffer-substring beg-B end-B-no-blank)) + (between-A-no-blank-and-B (buffer-substring end-A-no-blank beg-B)) + (sub-A (cons beg-A (org-list-get-subtree beg-A struct))) + (sub-B (cons beg-B (org-list-get-subtree beg-B struct))) + ;; Store overlays responsible for visibility status. We + ;; also need to store their boundaries as they will be + ;; removed from buffer. + (overlays + (cons + (delq nil + (mapcar (lambda (o) + (and (>= (overlay-start o) beg-A) + (<= (overlay-end o) end-A) + (list o (overlay-start o) (overlay-end o)))) + (overlays-in beg-A end-A))) + (delq nil + (mapcar (lambda (o) + (and (>= (overlay-start o) beg-B) + (<= (overlay-end o) end-B) + (list o (overlay-start o) (overlay-end o)))) + (overlays-in beg-B end-B)))))) + ;; 1. Move effectively items in buffer. + (goto-char beg-A) + (delete-region beg-A end-B-no-blank) + (insert (concat body-B between-A-no-blank-and-B body-A)) + ;; 2. Now modify struct. No need to re-read the list, the + ;; transformation is just a shift of positions. Some special + ;; attention is required for items ending at END-A and END-B + ;; as empty spaces are not moved there. In others words, + ;; item BEG-A will end with whitespaces that were at the end + ;; of BEG-B and the same applies to BEG-B. + (dolist (e struct) + (let ((pos (car e))) + (cond + ((< pos beg-A)) + ((memq pos sub-A) + (let ((end-e (nth 6 e))) + (setcar e (+ pos (- end-B-no-blank end-A-no-blank))) + (setcar (nthcdr 6 e) + (+ end-e (- end-B-no-blank end-A-no-blank))) + (when (= end-e end-A) (setcar (nthcdr 6 e) end-B)))) + ((memq pos sub-B) + (let ((end-e (nth 6 e))) + (setcar e (- (+ pos beg-A) beg-B)) + (setcar (nthcdr 6 e) (+ end-e (- beg-A beg-B))) + (when (= end-e end-B) + (setcar (nthcdr 6 e) + (+ beg-A size-B (- end-A end-A-no-blank)))))) + ((< pos beg-B) + (let ((end-e (nth 6 e))) + (setcar e (+ pos (- size-B size-A))) + (setcar (nthcdr 6 e) (+ end-e (- size-B size-A)))))))) + (setq struct (sort struct #'car-less-than-car)) + ;; Restore visibility status, by moving overlays to their new + ;; position. + (dolist (ov (car overlays)) + (move-overlay + (car ov) + (+ (nth 1 ov) (- (+ beg-B (- size-B size-A)) beg-A)) + (+ (nth 2 ov) (- (+ beg-B (- size-B size-A)) beg-A)))) + (dolist (ov (cdr overlays)) + (move-overlay (car ov) + (+ (nth 1 ov) (- beg-A beg-B)) + (+ (nth 2 ov) (- beg-A beg-B)))) + ;; Return structure. + struct))) + +(defun org-list-separating-blank-lines-number (pos struct prevs) + "Return number of blank lines that should separate items in list. + +POS is the position of point where `org-list-insert-item' was called. + +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'. + +Assume point is at item's beginning. If the item is alone, apply +some heuristics to guess the result." + (save-excursion + (let ((item (point)) + (insert-blank-p + (cdr (assq 'plain-list-item org-blank-before-new-entry))) + usr-blank + (count-blanks + (function + (lambda () + ;; Count blank lines above beginning of line. + (save-excursion + (count-lines (goto-char (point-at-bol)) + (progn (skip-chars-backward " \r\t\n") + (forward-line) + (point)))))))) + (cond + ;; Trivial cases where there should be none. + ((not insert-blank-p) 0) + ;; When `org-blank-before-new-entry' says so, it is 1. + ((eq insert-blank-p t) 1) + ;; `plain-list-item' is 'auto. Count blank lines separating + ;; neighbors' items in list. + (t (let ((next-p (org-list-get-next-item item struct prevs))) + (cond + ;; Is there a next item? + (next-p (goto-char next-p) + (funcall count-blanks)) + ;; Is there a previous item? + ((org-list-get-prev-item item struct prevs) + (funcall count-blanks)) + ;; User inserted blank lines, trust him. + ((and (> pos (org-list-get-item-end-before-blank item struct)) + (> (save-excursion (goto-char pos) + (setq usr-blank (funcall count-blanks))) + 0)) + usr-blank) + ;; Are there blank lines inside the list so far? + ((save-excursion + (goto-char (org-list-get-top-point struct)) + ;; Do not use `org-list-search-forward' so blank lines + ;; in blocks can be counted in. + (re-search-forward + "^[ \t]*$" (org-list-get-item-end-before-blank item struct) t)) + 1) + ;; Default choice: no blank line. + (t 0)))))))) + +(defun org-list-insert-item (pos struct prevs &optional checkbox after-bullet) + "Insert a new list item at POS and return the new structure. +If POS is before first character after bullet of the item, the +new item will be created before the current one. + +STRUCT is the list structure. PREVS is the alist of previous +items, as returned by `org-list-prevs-alist'. + +Insert a checkbox if CHECKBOX is non-nil, and string AFTER-BULLET +after the bullet. Cursor will be after this text once the +function ends. + +This function modifies STRUCT." + (let ((case-fold-search t)) + ;; 1. Get information about list: position of point with regards + ;; to item start (BEFOREP), blank lines number separating items + ;; (BLANK-NB), if we're allowed to (SPLIT-LINE-P). + (let* ((item (progn (goto-char pos) (goto-char (org-list-get-item-begin)))) + (item-end (org-list-get-item-end item struct)) + (item-end-no-blank (org-list-get-item-end-before-blank item struct)) + (beforep + (progn + (looking-at org-list-full-item-re) + (<= pos + (cond + ((not (match-beginning 4)) (match-end 0)) + ;; Ignore tag in a non-descriptive list. + ((save-match-data (string-match "[.)]" (match-string 1))) + (match-beginning 4)) + (t (save-excursion + (goto-char (match-end 4)) + (skip-chars-forward " \t") + (point))))))) + (split-line-p (org-get-alist-option org-M-RET-may-split-line 'item)) + (blank-nb (org-list-separating-blank-lines-number + pos struct prevs)) + ;; 2. Build the new item to be created. Concatenate same + ;; bullet as item, checkbox, text AFTER-BULLET if + ;; provided, and text cut from point to end of item + ;; (TEXT-CUT) to form item's BODY. TEXT-CUT depends on + ;; BEFOREP and SPLIT-LINE-P. The difference of size + ;; between what was cut and what was inserted in buffer + ;; is stored in SIZE-OFFSET. + (ind (org-list-get-ind item struct)) + (ind-size (if indent-tabs-mode + (+ (/ ind tab-width) (mod ind tab-width)) + ind)) + (bullet (org-list-bullet-string (org-list-get-bullet item struct))) + (box (when checkbox "[ ]")) + (text-cut + (and (not beforep) split-line-p + (progn + (goto-char pos) + ;; If POS is greater than ITEM-END, then point is + ;; in some white lines after the end of the list. + ;; Those must be removed, or they will be left, + ;; stacking up after the list. + (when (< item-end pos) + (delete-region (1- item-end) (point-at-eol))) + (skip-chars-backward " \r\t\n") + (setq pos (point)) + (delete-and-extract-region pos item-end-no-blank)))) + (body (concat bullet (when box (concat box " ")) after-bullet + (and text-cut + (if (string-match "\\`[ \t]+" text-cut) + (replace-match "" t t text-cut) + text-cut)))) + (item-sep (make-string (1+ blank-nb) ?\n)) + (item-size (+ ind-size (length body) (length item-sep))) + (size-offset (- item-size (length text-cut)))) + ;; 4. Insert effectively item into buffer. + (goto-char item) + (indent-to-column ind) + (insert body item-sep) + ;; 5. Add new item to STRUCT. + (mapc (lambda (e) + (let ((p (car e)) (end (nth 6 e))) + (cond + ;; Before inserted item, positions don't change but + ;; an item ending after insertion has its end shifted + ;; by SIZE-OFFSET. + ((< p item) + (when (> end item) (setcar (nthcdr 6 e) (+ end size-offset)))) + ;; Trivial cases where current item isn't split in + ;; two. Just shift every item after new one by + ;; ITEM-SIZE. + ((or beforep (not split-line-p)) + (setcar e (+ p item-size)) + (setcar (nthcdr 6 e) (+ end item-size))) + ;; Item is split in two: elements before POS are just + ;; shifted by ITEM-SIZE. In the case item would end + ;; after split POS, ending is only shifted by + ;; SIZE-OFFSET. + ((< p pos) + (setcar e (+ p item-size)) + (if (< end pos) + (setcar (nthcdr 6 e) (+ end item-size)) + (setcar (nthcdr 6 e) (+ end size-offset)))) + ;; Elements after POS are moved into new item. + ;; Length of ITEM-SEP has to be removed as ITEM-SEP + ;; doesn't appear in buffer yet. + ((< p item-end) + (setcar e (+ p size-offset (- item pos (length item-sep)))) + (if (= end item-end) + (setcar (nthcdr 6 e) (+ item item-size)) + (setcar (nthcdr 6 e) + (+ end size-offset + (- item pos (length item-sep)))))) + ;; Elements at ITEM-END or after are only shifted by + ;; SIZE-OFFSET. + (t (setcar e (+ p size-offset)) + (setcar (nthcdr 6 e) (+ end size-offset)))))) + struct) + (push (list item ind bullet nil box nil (+ item item-size)) struct) + (setq struct (sort struct (lambda (e1 e2) (< (car e1) (car e2))))) + ;; 6. If not BEFOREP, new item must appear after ITEM, so + ;; exchange ITEM with the next item in list. Position cursor + ;; after bullet, counter, checkbox, and label. + (if beforep + (goto-char item) + (setq struct (org-list-swap-items item (+ item item-size) struct)) + (goto-char (org-list-get-next-item + item struct (org-list-prevs-alist struct)))) + struct))) + +(defun org-list-delete-item (item struct) + "Remove ITEM from the list and return the new structure. + +STRUCT is the list structure." + (let* ((end (org-list-get-item-end item struct)) + (beg (if (= (org-list-get-bottom-point struct) end) + ;; If ITEM ends with the list, delete blank lines + ;; before it. + (save-excursion + (goto-char item) + (skip-chars-backward " \r\t\n") + (min (1+ (point-at-eol)) (point-max))) + item))) + ;; Remove item from buffer. + (delete-region beg end) + ;; Remove item from structure and shift others items accordingly. + ;; Don't forget to shift also ending position when appropriate. + (let ((size (- end beg))) + (delq nil (mapcar (lambda (e) + (let ((pos (car e))) + (cond + ((< pos item) + (let ((end-e (nth 6 e))) + (cond + ((< end-e item) e) + ((= end-e item) + (append (butlast e) (list beg))) + (t + (append (butlast e) (list (- end-e size))))))) + ((< pos end) nil) + (t + (cons (- pos size) + (append (butlast (cdr e)) + (list (- (nth 6 e) size)))))))) + struct))))) + +(defun org-list-send-item (item dest struct) + "Send ITEM to destination DEST. + +STRUCT is the list structure. + +DEST can have various values. + +If DEST is a buffer position, the function will assume it points +to another item in the same list as ITEM, and will move the +latter just before the former. + +If DEST is `begin' (respectively `end'), ITEM will be moved at +the beginning (respectively end) of the list it belongs to. + +If DEST is a string like \"N\", where N is an integer, ITEM will +be moved at the Nth position in the list. + +If DEST is `kill', ITEM will be deleted and its body will be +added to the kill-ring. + +If DEST is `delete', ITEM will be deleted. + +Visibility of item is preserved. + +This function returns, destructively, the new list structure." + (let* ((prevs (org-list-prevs-alist struct)) + (item-end (org-list-get-item-end item struct)) + ;; Grab full item body minus its bullet. + (body (org-trim + (buffer-substring + (save-excursion + (goto-char item) + (looking-at + (concat "[ \t]*" + (regexp-quote (org-list-get-bullet item struct)))) + (match-end 0)) + item-end))) + ;; Change DEST into a buffer position. A trick is needed + ;; when ITEM is meant to be sent at the end of the list. + ;; Indeed, by setting locally `org-M-RET-may-split-line' to + ;; nil and insertion point (INS-POINT) to the first line's + ;; end of the last item, we ensure the new item will be + ;; inserted after the last item, and not after any of its + ;; hypothetical sub-items. + (ins-point (cond + ((or (eq dest 'kill) (eq dest 'delete))) + ((eq dest 'begin) + (setq dest (org-list-get-list-begin item struct prevs))) + ((eq dest 'end) + (setq dest (org-list-get-list-end item struct prevs)) + (save-excursion + (goto-char (org-list-get-last-item item struct prevs)) + (point-at-eol))) + ((string-match-p "\\`[0-9]+\\'" dest) + (let* ((all (org-list-get-all-items item struct prevs)) + (len (length all)) + (index (mod (string-to-number dest) len))) + (if (not (zerop index)) + (setq dest (nth (1- index) all)) + ;; Send ITEM at the end of the list. + (setq dest (org-list-get-list-end item struct prevs)) + (save-excursion + (goto-char + (org-list-get-last-item item struct prevs)) + (point-at-eol))))) + (t dest))) + (org-M-RET-may-split-line nil) + ;; Store inner overlays (to preserve visibility). + (overlays (cl-remove-if (lambda (o) (or (< (overlay-start o) item) + (> (overlay-end o) item))) + (overlays-in item item-end)))) + (cond + ((eq dest 'delete) (org-list-delete-item item struct)) + ((eq dest 'kill) + (kill-new body) + (org-list-delete-item item struct)) + ((and (integerp dest) (/= item ins-point)) + (setq item (copy-marker item)) + (setq struct (org-list-insert-item ins-point struct prevs nil body)) + ;; 1. Structure returned by `org-list-insert-item' may not be + ;; accurate, as it cannot see sub-items included in BODY. + ;; Thus, first compute the real structure so far. + (let ((moved-items + (cons (marker-position item) + (org-list-get-subtree (marker-position item) struct))) + (new-end (org-list-get-item-end (point) struct)) + (old-end (org-list-get-item-end (marker-position item) struct)) + (new-item (point)) + (shift (- (point) item))) + ;; 1.1. Remove the item just created in structure. + (setq struct (delete (assq new-item struct) struct)) + ;; 1.2. Copy ITEM and any of its sub-items at NEW-ITEM. + (setq struct (sort + (append + struct + (mapcar (lambda (e) + (let* ((cell (assq e struct)) + (pos (car cell)) + (end (nth 6 cell))) + (cons (+ pos shift) + (append (butlast (cdr cell)) + (list (if (= end old-end) + new-end + (+ end shift))))))) + moved-items)) + #'car-less-than-car))) + ;; 2. Restore inner overlays. + (dolist (o overlays) + (move-overlay o + (+ (overlay-start o) (- (point) item)) + (+ (overlay-end o) (- (point) item)))) + ;; 3. Eventually delete extra copy of the item and clean marker. + (prog1 (org-list-delete-item (marker-position item) struct) + (move-marker item nil))) + (t struct)))) + +(defun org-list-struct-outdent (start end struct parents) + "Outdent items between positions START and END. + +STRUCT is the list structure. PARENTS is the alist of items' +parents, as returned by `org-list-parents-alist'. + +START is included, END excluded." + (let* (acc + (out (lambda (cell) + (let* ((item (car cell)) + (parent (cdr cell))) + (cond + ;; Item not yet in zone: keep association. + ((< item start) cell) + ;; Item out of zone: follow associations in ACC. + ((>= item end) + (let ((convert (and parent (assq parent acc)))) + (if convert (cons item (cdr convert)) cell))) + ;; Item has no parent: error + ((not parent) + (error "Cannot outdent top-level items")) + ;; Parent is outdented: keep association. + ((>= parent start) + (push (cons parent item) acc) cell) + (t + ;; Parent isn't outdented: reparent to grand-parent. + (let ((grand-parent (org-list-get-parent + parent struct parents))) + (push (cons parent item) acc) + (cons item grand-parent)))))))) + (mapcar out parents))) + +(defun org-list-struct-indent (start end struct parents prevs) + "Indent items between positions START and END. + +STRUCT is the list structure. PARENTS is the alist of parents +and PREVS is the alist of previous items, returned by, +respectively, `org-list-parents-alist' and +`org-list-prevs-alist'. + +START is included and END excluded. + +STRUCT may be modified if `org-list-demote-modify-bullet' matches +bullets between START and END." + (let* (acc + (set-assoc (lambda (cell) (push cell acc) cell)) + (change-bullet-maybe + (function + (lambda (item) + (let ((new-bul-p + (cdr (assoc + ;; Normalize ordered bullets. + (let ((bul (org-trim + (org-list-get-bullet item struct)))) + (cond ((string-match "[A-Z]\\." bul) "A.") + ((string-match "[A-Z])" bul) "A)") + ((string-match "[a-z]\\." bul) "a.") + ((string-match "[a-z])" bul) "a)") + ((string-match "[0-9]\\." bul) "1.") + ((string-match "[0-9])" bul) "1)") + (t bul))) + org-list-demote-modify-bullet)))) + (when new-bul-p (org-list-set-bullet item struct new-bul-p)))))) + (ind + (lambda (cell) + (let* ((item (car cell)) + (parent (cdr cell))) + (cond + ;; Item not yet in zone: keep association. + ((< item start) cell) + ((>= item end) + ;; Item out of zone: follow associations in ACC. + (let ((convert (assq parent acc))) + (if convert (cons item (cdr convert)) cell))) + (t + ;; Item is in zone... + (let ((prev (org-list-get-prev-item item struct prevs))) + ;; Check if bullet needs to be changed. + (funcall change-bullet-maybe item) + (cond + ;; First item indented but not parent: error + ((and (not prev) (or (not parent) (< parent start))) + (user-error "Cannot indent the first item of a list")) + ;; First item and parent indented: keep same + ;; parent. + ((not prev) (funcall set-assoc cell)) + ;; Previous item not indented: reparent to it. + ((< prev start) (funcall set-assoc (cons item prev))) + ;; Previous item indented: reparent like it. + (t + (funcall set-assoc + (cons item (cdr (assq prev acc))))))))))))) + (mapcar ind parents))) + + + +;;; Repairing structures + +(defun org-list-use-alpha-bul-p (first struct prevs) + "Non-nil if list starting at FIRST can have alphabetical bullets. + +STRUCT is list structure. PREVS is the alist of previous items, +as returned by `org-list-prevs-alist'." + (and org-list-allow-alphabetical + (catch 'exit + (let ((item first) (ascii 64) (case-fold-search nil)) + ;; Pretend that bullets are uppercase and check if alphabet + ;; is sufficient, taking counters into account. + (while item + (let ((count (org-list-get-counter item struct))) + ;; Virtually determine current bullet + (if (and count (string-match-p "[a-zA-Z]" count)) + ;; Counters are not case-sensitive. + (setq ascii (string-to-char (upcase count))) + (setq ascii (1+ ascii))) + ;; Test if bullet would be over z or Z. + (if (> ascii 90) + (throw 'exit nil) + (setq item (org-list-get-next-item item struct prevs))))) + ;; All items checked. All good. + t)))) + +(defun org-list-inc-bullet-maybe (bullet) + "Increment BULLET if applicable." + (let ((case-fold-search nil)) + (cond + ;; Num bullet: increment it. + ((string-match "[0-9]+" bullet) + (replace-match + (number-to-string (1+ (string-to-number (match-string 0 bullet)))) + nil nil bullet)) + ;; Alpha bullet: increment it. + ((string-match "[A-Za-z]" bullet) + (replace-match + (char-to-string (1+ (string-to-char (match-string 0 bullet)))) + nil nil bullet)) + ;; Unordered bullet: leave it. + (t bullet)))) + +(defun org-list-struct-fix-bul (struct prevs) + "Verify and correct bullets in STRUCT. +PREVS is the alist of previous items, as returned by +`org-list-prevs-alist'. + +This function modifies STRUCT." + (let ((case-fold-search nil) + (fix-bul + (function + ;; Set bullet of ITEM in STRUCT, depending on the type of + ;; first item of the list, the previous bullet and counter + ;; if any. + (lambda (item) + (let* ((prev (org-list-get-prev-item item struct prevs)) + (prev-bul (and prev (org-list-get-bullet prev struct))) + (counter (org-list-get-counter item struct)) + (bullet (org-list-get-bullet item struct)) + (alphap (and (not prev) + (org-list-use-alpha-bul-p item struct prevs)))) + (org-list-set-bullet + item struct + (org-list-bullet-string + (cond + ;; Alpha counter in alpha list: use counter. + ((and prev counter + (string-match "[a-zA-Z]" counter) + (string-match "[a-zA-Z]" prev-bul)) + ;; Use cond to be sure `string-match' is used in + ;; both cases. + (let ((real-count + (cond + ((string-match "[a-z]" prev-bul) (downcase counter)) + ((string-match "[A-Z]" prev-bul) (upcase counter))))) + (replace-match real-count nil nil prev-bul))) + ;; Num counter in a num list: use counter. + ((and prev counter + (string-match "[0-9]+" counter) + (string-match "[0-9]+" prev-bul)) + (replace-match counter nil nil prev-bul)) + ;; No counter: increase, if needed, previous bullet. + (prev + (org-list-inc-bullet-maybe (org-list-get-bullet prev struct))) + ;; Alpha counter at first item: use counter. + ((and counter (org-list-use-alpha-bul-p item struct prevs) + (string-match "[A-Za-z]" counter) + (string-match "[A-Za-z]" bullet)) + (let ((real-count + (cond + ((string-match "[a-z]" bullet) (downcase counter)) + ((string-match "[A-Z]" bullet) (upcase counter))))) + (replace-match real-count nil nil bullet))) + ;; Num counter at first item: use counter. + ((and counter + (string-match "[0-9]+" counter) + (string-match "[0-9]+" bullet)) + (replace-match counter nil nil bullet)) + ;; First bullet is alpha uppercase: use "A". + ((and alphap (string-match "[A-Z]" bullet)) + (replace-match "A" nil nil bullet)) + ;; First bullet is alpha lowercase: use "a". + ((and alphap (string-match "[a-z]" bullet)) + (replace-match "a" nil nil bullet)) + ;; First bullet is num: use "1". + ((string-match "\\([0-9]+\\|[A-Za-z]\\)" bullet) + (replace-match "1" nil nil bullet)) + ;; Not an ordered list: keep bullet. + (t bullet))))))))) + (mapc fix-bul (mapcar #'car struct)))) + +(defun org-list-struct-fix-ind (struct parents &optional bullet-size) + "Verify and correct indentation in STRUCT. + +PARENTS is the alist of parents, as returned by +`org-list-parents-alist'. + +If numeric optional argument BULLET-SIZE is set, assume all +bullets in list have this length to determine new indentation. + +This function modifies STRUCT." + (let* ((ancestor (org-list-get-top-point struct)) + (top-ind (org-list-get-ind ancestor struct)) + (new-ind + (lambda (item) + (let ((parent (org-list-get-parent item struct parents))) + (if parent + ;; Indent like parent + length of parent's bullet + + ;; sub-list offset. + (org-list-set-ind + item struct (+ (or bullet-size + (length + (org-list-get-bullet parent struct))) + (org-list-get-ind parent struct) + org-list-indent-offset)) + ;; If no parent, indent like top-point. + (org-list-set-ind item struct top-ind)))))) + (mapc new-ind (mapcar #'car (cdr struct))))) + +(defun org-list-struct-fix-box (struct parents prevs &optional ordered) + "Verify and correct checkboxes in STRUCT. + +PARENTS is the alist of parents and PREVS is the alist of +previous items, as returned by, respectively, +`org-list-parents-alist' and `org-list-prevs-alist'. + +If ORDERED is non-nil, a checkbox can only be checked when every +checkbox before it is checked too. If there was an attempt to +break this rule, the function will return the blocking item. In +all others cases, the return value will be nil. + +This function modifies STRUCT." + (let ((all-items (mapcar #'car struct)) + (set-parent-box + (function + (lambda (item) + (let* ((box-list + (mapcar (lambda (child) + (org-list-get-checkbox child struct)) + (org-list-get-children item struct parents)))) + (org-list-set-checkbox + item struct + (cond + ((and (member "[ ]" box-list) (member "[X]" box-list)) "[-]") + ((member "[-]" box-list) "[-]") + ((member "[X]" box-list) "[X]") + ((member "[ ]" box-list) "[ ]") + ;; Parent has no boxed child: leave box as-is. + (t (org-list-get-checkbox item struct)))))))) + parent-list) + ;; 1. List all parents with a checkbox. + (mapc + (lambda (e) + (let* ((parent (org-list-get-parent e struct parents)) + (parent-box-p (org-list-get-checkbox parent struct))) + (when (and parent-box-p (not (memq parent parent-list))) + (push parent parent-list)))) + all-items) + ;; 2. Sort those parents by decreasing indentation. + (setq parent-list (sort parent-list + (lambda (e1 e2) + (> (org-list-get-ind e1 struct) + (org-list-get-ind e2 struct))))) + ;; 3. For each parent, get all children's checkboxes to determine + ;; and set its checkbox accordingly. + (mapc set-parent-box parent-list) + ;; 4. If ORDERED is set, see if we need to uncheck some boxes. + (when ordered + (let* ((box-list + (mapcar (lambda (e) (org-list-get-checkbox e struct)) all-items)) + (after-unchecked (member "[ ]" box-list))) + ;; There are boxes checked after an unchecked one: fix that. + (when (member "[X]" after-unchecked) + (let ((index (- (length struct) (length after-unchecked)))) + (mapc (lambda (e) + (when (org-list-get-checkbox e struct) + (org-list-set-checkbox e struct "[ ]"))) + (nthcdr index all-items)) + ;; Verify once again the structure, without ORDERED. + (org-list-struct-fix-box struct parents prevs nil) + ;; Return blocking item. + (nth index all-items))))))) + +(defun org-list-struct-fix-item-end (struct) + "Verify and correct each item end position in STRUCT. + +This function modifies STRUCT." + (let (end-list acc-end) + (mapc (lambda (e) + (let* ((pos (car e)) + (ind-pos (org-list-get-ind pos struct)) + (end-pos (org-list-get-item-end pos struct))) + (unless (assq end-pos struct) + ;; To determine real ind of an ending position that is + ;; not at an item, we have to find the item it belongs + ;; to: it is the last item (ITEM-UP), whose ending is + ;; further than the position we're interested in. + (let ((item-up (assoc-default end-pos acc-end '>))) + (push (cons + ;; Else part is for the bottom point. + (if item-up (+ (org-list-get-ind item-up struct) 2) 0) + end-pos) + end-list))) + (push (cons ind-pos pos) end-list) + (push (cons end-pos pos) acc-end))) + struct) + (setq end-list (sort end-list (lambda (e1 e2) (< (cdr e1) (cdr e2))))) + (org-list-struct-assoc-end struct end-list))) + +(defun org-list-struct-apply-struct (struct old-struct) + "Apply set difference between STRUCT and OLD-STRUCT to the buffer. + +OLD-STRUCT is the structure before any modifications, and STRUCT +the structure to be applied. The function will only modify parts +of the list which have changed. + +Initial position of cursor is restored after the changes." + (let* ((origin (point-marker)) + (inlinetask-re (and (featurep 'org-inlinetask) + (org-inlinetask-outline-regexp))) + (item-re (org-item-re)) + (shift-body-ind + (function + ;; Shift the indentation between END and BEG by DELTA. + ;; Start from the line before END. + (lambda (end beg delta) + (goto-char end) + (skip-chars-backward " \r\t\n") + (beginning-of-line) + (while (or (> (point) beg) + (and (= (point) beg) + (not (looking-at item-re)))) + (cond + ;; Skip inline tasks. + ((and inlinetask-re (looking-at inlinetask-re)) + (org-inlinetask-goto-beginning)) + ;; Shift only non-empty lines. + ((looking-at-p "^[ \t]*\\S-") + (indent-line-to (+ (org-get-indentation) delta)))) + (forward-line -1))))) + (modify-item + (function + ;; Replace ITEM first line elements with new elements from + ;; STRUCT, if appropriate. + (lambda (item) + (goto-char item) + (let* ((new-ind (org-list-get-ind item struct)) + (old-ind (org-get-indentation)) + (new-bul (org-list-bullet-string + (org-list-get-bullet item struct))) + (old-bul (org-list-get-bullet item old-struct)) + (new-box (org-list-get-checkbox item struct))) + (looking-at org-list-full-item-re) + ;; a. Replace bullet + (unless (equal old-bul new-bul) + (replace-match new-bul nil nil nil 1)) + ;; b. Replace checkbox. + (cond + ((equal (match-string 3) new-box)) + ((and (match-string 3) new-box) + (replace-match new-box nil nil nil 3)) + ((match-string 3) + (looking-at ".*?\\([ \t]*\\[[ X-]\\]\\)") + (replace-match "" nil nil nil 1)) + (t (let ((counterp (match-end 2))) + (goto-char (if counterp (1+ counterp) (match-end 1))) + (insert (concat new-box (unless counterp " ")))))) + ;; c. Indent item to appropriate column. + (unless (= new-ind old-ind) + (delete-region (goto-char (point-at-bol)) + (progn (skip-chars-forward " \t") (point))) + (indent-to new-ind))))))) + ;; 1. First get list of items and position endings. We maintain + ;; two alists: ITM-SHIFT, determining indentation shift needed + ;; at item, and END-LIST, a pseudo-alist where key is ending + ;; position and value point. + (let (end-list acc-end itm-shift all-ends sliced-struct) + (dolist (e old-struct) + (let* ((pos (car e)) + (ind-pos (org-list-get-ind pos struct)) + (ind-old (org-list-get-ind pos old-struct)) + (bul-pos (org-list-get-bullet pos struct)) + (bul-old (org-list-get-bullet pos old-struct)) + (ind-shift (- (+ ind-pos (length bul-pos)) + (+ ind-old (length bul-old)))) + (end-pos (org-list-get-item-end pos old-struct))) + (push (cons pos ind-shift) itm-shift) + (unless (assq end-pos old-struct) + ;; To determine real ind of an ending position that + ;; is not at an item, we have to find the item it + ;; belongs to: it is the last item (ITEM-UP), whose + ;; ending is further than the position we're + ;; interested in. + (let ((item-up (assoc-default end-pos acc-end #'>))) + (push (cons end-pos item-up) end-list))) + (push (cons end-pos pos) acc-end))) + ;; 2. Slice the items into parts that should be shifted by the + ;; same amount of indentation. Each slice follow the pattern + ;; (END BEG DELTA). Slices are returned in reverse order. + (setq all-ends (sort (append (mapcar #'car itm-shift) + (org-uniquify (mapcar #'car end-list))) + #'<) + acc-end (nreverse acc-end)) + (while (cdr all-ends) + (let* ((up (pop all-ends)) + (down (car all-ends)) + (itemp (assq up struct)) + (delta + (if itemp (cdr (assq up itm-shift)) + ;; If we're not at an item, there's a child of the + ;; item point belongs to above. Make sure the less + ;; indented line in this slice has the same column + ;; as that child. + (let* ((child (cdr (assq up acc-end))) + (ind (org-list-get-ind child struct)) + (min-ind most-positive-fixnum)) + (save-excursion + (goto-char up) + (while (< (point) down) + ;; Ignore empty lines. Also ignore blocks and + ;; drawers contents. + (unless (looking-at-p "[ \t]*$") + (setq min-ind (min (org-get-indentation) min-ind)) + (cond + ((and (looking-at "#\\+BEGIN\\(:\\|_\\S-+\\)") + (re-search-forward + (format "^[ \t]*#\\+END%s[ \t]*$" + (match-string 1)) + down t))) + ((and (looking-at org-drawer-regexp) + (re-search-forward "^[ \t]*:END:[ \t]*$" + down t))))) + (forward-line))) + (- ind min-ind))))) + (push (list down up delta) sliced-struct))) + ;; 3. Shift each slice in buffer, provided delta isn't 0, from + ;; end to beginning. Take a special action when beginning is + ;; at item bullet. + (dolist (e sliced-struct) + (unless (zerop (nth 2 e)) (apply shift-body-ind e)) + (let* ((beg (nth 1 e)) + (cell (assq beg struct))) + (unless (or (not cell) (equal cell (assq beg old-struct))) + (funcall modify-item beg))))) + ;; 4. Go back to initial position and clean marker. + (goto-char origin) + (move-marker origin nil))) + +(defun org-list-write-struct (struct parents &optional old-struct) + "Correct bullets, checkboxes and indentation in list at point. + +STRUCT is the list structure. PARENTS is the alist of parents, +as returned by `org-list-parents-alist'. + +When non-nil, optional argument OLD-STRUCT is the reference +structure of the list. It should be provided whenever STRUCT +doesn't correspond anymore to the real list in buffer." + ;; Order of functions matters here: checkboxes and endings need + ;; correct indentation to be set, and indentation needs correct + ;; bullets. + ;; + ;; 0. Save a copy of structure before modifications + (let ((old-struct (or old-struct (copy-tree struct)))) + ;; 1. Set a temporary, but coherent with PARENTS, indentation in + ;; order to get items endings and bullets properly + (org-list-struct-fix-ind struct parents 2) + ;; 2. Fix each item end to get correct prevs alist. + (org-list-struct-fix-item-end struct) + ;; 3. Get bullets right. + (let ((prevs (org-list-prevs-alist struct))) + (org-list-struct-fix-bul struct prevs) + ;; 4. Now get real indentation. + (org-list-struct-fix-ind struct parents) + ;; 5. Eventually fix checkboxes. + (org-list-struct-fix-box struct parents prevs)) + ;; 6. Apply structure modifications to buffer. + (org-list-struct-apply-struct struct old-struct))) + + + +;;; Misc Tools + +(defun org-apply-on-list (function init-value &rest args) + "Call FUNCTION on each item of the list at point. +FUNCTION must be called with at least one argument: INIT-VALUE, +that will contain the value returned by the function at the +previous item, plus ARGS extra arguments. + +FUNCTION is applied on items in reverse order. + +As an example, \(org-apply-on-list \(lambda \(result) \(1+ result)) 0) +will return the number of items in the current list. + +Sublists of the list are skipped. Cursor is always at the +beginning of the item." + (let* ((struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (item (copy-marker (point-at-bol))) + (all (org-list-get-all-items (marker-position item) struct prevs)) + (value init-value)) + (mapc (lambda (e) + (goto-char e) + (setq value (apply function value args))) + (nreverse all)) + (goto-char item) + (move-marker item nil) + value)) + +(defun org-list-set-item-visibility (item struct view) + "Set visibility of ITEM in STRUCT to VIEW. + +Possible values are: `folded', `children' or `subtree'. See +`org-cycle' for more information." + (cond + ((eq view 'folded) + (let ((item-end (org-list-get-item-end-before-blank item struct))) + ;; Hide from eol + (outline-flag-region (save-excursion (goto-char item) (point-at-eol)) + item-end t))) + ((eq view 'children) + ;; First show everything. + (org-list-set-item-visibility item struct 'subtree) + ;; Then fold every child. + (let* ((parents (org-list-parents-alist struct)) + (children (org-list-get-children item struct parents))) + (mapc (lambda (e) + (org-list-set-item-visibility e struct 'folded)) + children))) + ((eq view 'subtree) + ;; Show everything + (let ((item-end (org-list-get-item-end item struct))) + (outline-flag-region item item-end nil))))) + +(defun org-list-item-body-column (item) + "Return column at which body of ITEM should start." + (save-excursion + (goto-char item) + (if (save-excursion + (end-of-line) + (re-search-backward + "[ \t]::\\([ \t]\\|$\\)" (line-beginning-position) t)) + ;; Descriptive list item. Body starts after item's tag, if + ;; possible. + (let ((start (1+ (- (match-beginning 1) (line-beginning-position)))) + (ind (org-get-indentation))) + (if (> start (+ ind org-list-description-max-indent)) + (+ ind 5) + start)) + ;; Regular item. Body starts after bullet. + (looking-at "[ \t]*\\(\\S-+\\)") + (+ (progn (goto-char (match-end 1)) (current-column)) + (if (and org-list-two-spaces-after-bullet-regexp + (string-match-p org-list-two-spaces-after-bullet-regexp + (match-string 1))) + 2 + 1))))) + + + +;;; Interactive functions + +(defalias 'org-list-get-item-begin 'org-in-item-p) + +(defun org-beginning-of-item () + "Go to the beginning of the current item. +Throw an error when not in a list." + (interactive) + (let ((begin (org-in-item-p))) + (if begin (goto-char begin) (error "Not in an item")))) + +(defun org-beginning-of-item-list () + "Go to the beginning item of the current list or sublist. +Throw an error when not in a list." + (interactive) + (let ((begin (org-in-item-p))) + (if (not begin) + (error "Not in an item") + (goto-char begin) + (let* ((struct (org-list-struct)) + (prevs (org-list-prevs-alist struct))) + (goto-char (org-list-get-list-begin begin struct prevs)))))) + +(defun org-end-of-item-list () + "Go to the end of the current list or sublist. +Throw an error when not in a list." + (interactive) + (let ((begin (org-in-item-p))) + (if (not begin) + (error "Not in an item") + (goto-char begin) + (let* ((struct (org-list-struct)) + (prevs (org-list-prevs-alist struct))) + (goto-char (org-list-get-list-end begin struct prevs)))))) + +(defun org-end-of-item () + "Go to the end of the current item. +Throw an error when not in a list." + (interactive) + (let ((begin (org-in-item-p))) + (if (not begin) + (error "Not in an item") + (goto-char begin) + (let ((struct (org-list-struct))) + (goto-char (org-list-get-item-end begin struct)))))) + +(defun org-previous-item () + "Move to the beginning of the previous item. +Throw an error when not in a list. Also throw an error when at +first item, unless `org-list-use-circular-motion' is non-nil." + (interactive) + (let ((item (org-in-item-p))) + (if (not item) + (error "Not in an item") + (goto-char item) + (let* ((struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (prevp (org-list-get-prev-item item struct prevs))) + (cond + (prevp (goto-char prevp)) + (org-list-use-circular-motion + (goto-char (org-list-get-last-item item struct prevs))) + (t (error "On first item"))))))) + +(defun org-next-item () + "Move to the beginning of the next item. +Throw an error when not in a list. Also throw an error when at +last item, unless `org-list-use-circular-motion' is non-nil." + (interactive) + (let ((item (org-in-item-p))) + (if (not item) + (error "Not in an item") + (goto-char item) + (let* ((struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (prevp (org-list-get-next-item item struct prevs))) + (cond + (prevp (goto-char prevp)) + (org-list-use-circular-motion + (goto-char (org-list-get-first-item item struct prevs))) + (t (error "On last item"))))))) + +(defun org-move-item-down () + "Move the item at point down, i.e. swap with following item. +Sub-items (items with larger indentation) are considered part of +the item, so this really moves item trees." + (interactive) + (unless (org-at-item-p) (error "Not at an item")) + (let* ((col (current-column)) + (item (point-at-bol)) + (struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (next-item (org-list-get-next-item (point-at-bol) struct prevs))) + (unless (or next-item org-list-use-circular-motion) + (user-error "Cannot move this item further down")) + (if (not next-item) + (setq struct (org-list-send-item item 'begin struct)) + (setq struct (org-list-swap-items item next-item struct)) + (goto-char + (org-list-get-next-item item struct (org-list-prevs-alist struct)))) + (org-list-write-struct struct (org-list-parents-alist struct)) + (org-move-to-column col))) + +(defun org-move-item-up () + "Move the item at point up, i.e. swap with previous item. +Sub-items (items with larger indentation) are considered part of +the item, so this really moves item trees." + (interactive) + (unless (org-at-item-p) (error "Not at an item")) + (let* ((col (current-column)) + (item (point-at-bol)) + (struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (prev-item (org-list-get-prev-item (point-at-bol) struct prevs))) + (unless (or prev-item org-list-use-circular-motion) + (user-error "Cannot move this item further up")) + (if (not prev-item) + (setq struct (org-list-send-item item 'end struct)) + (setq struct (org-list-swap-items prev-item item struct))) + (org-list-write-struct struct (org-list-parents-alist struct)) + (org-move-to-column col))) + +(defun org-insert-item (&optional checkbox) + "Insert a new item at the current level. +If cursor is before first character after bullet of the item, the +new item will be created before the current one. + +If CHECKBOX is non-nil, add a checkbox next to the bullet. + +Return t when things worked, nil when we are not in an item, or +item is invisible." + (interactive "P") + (let ((itemp (org-in-item-p)) + (pos (point))) + ;; If cursor isn't is a list or if list is invisible, return nil. + (unless (or (not itemp) + (save-excursion + (goto-char itemp) + (org-invisible-p))) + (if (save-excursion + (goto-char itemp) + (org-at-item-timer-p)) + ;; Timer list: delegate to `org-timer-item'. + (progn (org-timer-item) t) + (let* ((struct (save-excursion (goto-char itemp) + (org-list-struct))) + (prevs (org-list-prevs-alist struct)) + ;; If we're in a description list, ask for the new term. + (desc (when (eq (org-list-get-list-type itemp struct prevs) + 'descriptive) + " :: "))) + (setq struct (org-list-insert-item pos struct prevs checkbox desc)) + (org-list-write-struct struct (org-list-parents-alist struct)) + (when checkbox (org-update-checkbox-count-maybe)) + (looking-at org-list-full-item-re) + (goto-char (if (and (match-beginning 4) + (save-match-data + (string-match "[.)]" (match-string 1)))) + (match-beginning 4) + (match-end 0))) + (if desc (backward-char 1)) + t))))) + +(defun org-list-repair () + "Fix indentation, bullets and checkboxes in the list at point." + (interactive) + (unless (org-at-item-p) (error "This is not a list")) + (let* ((struct (org-list-struct)) + (parents (org-list-parents-alist struct))) + (org-list-write-struct struct parents))) + +(defun org-cycle-list-bullet (&optional which) + "Cycle through the different itemize/enumerate bullets. +This cycle the entire list level through the sequence: + + `-' -> `+' -> `*' -> `1.' -> `1)' + +If WHICH is a valid string, use that as the new bullet. If WHICH +is an integer, 0 means `-', 1 means `+' etc. If WHICH is +`previous', cycle backwards." + (interactive "P") + (unless (org-at-item-p) (error "Not at an item")) + (save-excursion + (beginning-of-line) + (let* ((struct (org-list-struct)) + (parents (org-list-parents-alist struct)) + (prevs (org-list-prevs-alist struct)) + (list-beg (org-list-get-first-item (point) struct prevs)) + (bullet (org-list-get-bullet list-beg struct)) + (alpha-p (org-list-use-alpha-bul-p list-beg struct prevs)) + (case-fold-search nil) + (current (cond + ((string-match "[a-z]\\." bullet) "a.") + ((string-match "[a-z])" bullet) "a)") + ((string-match "[A-Z]\\." bullet) "A.") + ((string-match "[A-Z])" bullet) "A)") + ((string-match "\\." bullet) "1.") + ((string-match ")" bullet) "1)") + (t (org-trim bullet)))) + ;; Compute list of possible bullets, depending on context. + (bullet-list + (append '("-" "+" ) + ;; *-bullets are not allowed at column 0. + (unless (looking-at "\\S-") '("*")) + ;; Description items cannot be numbered. + (unless (or (eq org-plain-list-ordered-item-terminator ?\)) + (org-at-item-description-p)) + '("1.")) + (unless (or (eq org-plain-list-ordered-item-terminator ?.) + (org-at-item-description-p)) + '("1)")) + (unless (or (not alpha-p) + (eq org-plain-list-ordered-item-terminator ?\)) + (org-at-item-description-p)) + '("a." "A.")) + (unless (or (not alpha-p) + (eq org-plain-list-ordered-item-terminator ?.) + (org-at-item-description-p)) + '("a)" "A)")))) + (len (length bullet-list)) + (item-index (- len (length (member current bullet-list)))) + (get-value (lambda (index) (nth (mod index len) bullet-list))) + (new (cond + ((member which bullet-list) which) + ((numberp which) (funcall get-value which)) + ((eq 'previous which) (funcall get-value (1- item-index))) + (t (funcall get-value (1+ item-index)))))) + ;; Use a short variation of `org-list-write-struct' as there's + ;; no need to go through all the steps. + (let ((old-struct (copy-tree struct))) + (org-list-set-bullet list-beg struct (org-list-bullet-string new)) + (org-list-struct-fix-bul struct prevs) + (org-list-struct-fix-ind struct parents) + (org-list-struct-apply-struct struct old-struct))))) + +(defun org-toggle-checkbox (&optional toggle-presence) + "Toggle the checkbox in the current line. + +With prefix argument TOGGLE-PRESENCE, add or remove checkboxes. +With a double prefix argument, set the checkbox to \"[-]\". + +When there is an active region, toggle status or presence of the +first checkbox there, and make every item inside have the same +status or presence, respectively. + +If point is on a headline, apply this to all checkbox items in +the text below the heading, taking as reference the first item in +subtree, ignoring planning line and any drawer following it." + (interactive "P") + (save-excursion + (let* (singlep + block-item + lim-up + lim-down + (orderedp (org-entry-get nil "ORDERED")) + (_bounds + ;; In a region, start at first item in region. + (cond + ((org-region-active-p) + (let ((limit (region-end))) + (goto-char (region-beginning)) + (if (org-list-search-forward (org-item-beginning-re) limit t) + (setq lim-up (point-at-bol)) + (error "No item in region")) + (setq lim-down (copy-marker limit)))) + ((org-at-heading-p) + ;; On a heading, start at first item after drawers and + ;; time-stamps (scheduled, etc.). + (let ((limit (save-excursion (outline-next-heading) (point)))) + (org-end-of-meta-data t) + (if (org-list-search-forward (org-item-beginning-re) limit t) + (setq lim-up (point-at-bol)) + (error "No item in subtree")) + (setq lim-down (copy-marker limit)))) + ;; Just one item: set SINGLEP flag. + ((org-at-item-p) + (setq singlep t) + (setq lim-up (point-at-bol) + lim-down (copy-marker (point-at-eol)))) + (t (error "Not at an item or heading, and no active region")))) + ;; Determine the checkbox going to be applied to all items + ;; within bounds. + (ref-checkbox + (progn + (goto-char lim-up) + (let ((cbox (and (org-at-item-checkbox-p) (match-string 1)))) + (cond + ((equal toggle-presence '(16)) "[-]") + ((equal toggle-presence '(4)) + (unless cbox "[ ]")) + ((equal "[X]" cbox) "[ ]") + (t "[X]")))))) + ;; When an item is found within bounds, grab the full list at + ;; point structure, then: (1) set check-box of all its items + ;; within bounds to REF-CHECKBOX, (2) fix check-boxes of the + ;; whole list, (3) move point after the list. + (goto-char lim-up) + (while (and (< (point) lim-down) + (org-list-search-forward (org-item-beginning-re) + lim-down 'move)) + (let* ((struct (org-list-struct)) + (struct-copy (copy-tree struct)) + (parents (org-list-parents-alist struct)) + (prevs (org-list-prevs-alist struct)) + (bottom (copy-marker (org-list-get-bottom-point struct))) + (items-to-toggle (cl-remove-if + (lambda (e) (or (< e lim-up) (> e lim-down))) + (mapcar #'car struct)))) + (mapc (lambda (e) (org-list-set-checkbox + e struct + ;; If there is no box at item, leave as-is + ;; unless function was called with C-u prefix. + (let ((cur-box (org-list-get-checkbox e struct))) + (if (or cur-box (equal toggle-presence '(4))) + ref-checkbox + cur-box)))) + items-to-toggle) + (setq block-item (org-list-struct-fix-box + struct parents prevs orderedp)) + ;; Report some problems due to ORDERED status of subtree. + ;; If only one box was being checked, throw an error, else, + ;; only signal problems. + (cond + ((and singlep block-item (> lim-up block-item)) + (error + "Checkbox blocked because of unchecked box at line %d" + (org-current-line block-item))) + (block-item + (message + "Checkboxes were removed due to unchecked box at line %d" + (org-current-line block-item)))) + (goto-char bottom) + (move-marker bottom nil) + (org-list-struct-apply-struct struct struct-copy))) + (move-marker lim-down nil))) + (org-update-checkbox-count-maybe)) + +(defun org-reset-checkbox-state-subtree () + "Reset all checkboxes in an entry subtree." + (interactive "*") + (if (org-before-first-heading-p) + (error "Not inside a tree") + (save-restriction + (save-excursion + (org-narrow-to-subtree) + (org-show-subtree) + (goto-char (point-min)) + (let ((end (point-max))) + (while (< (point) end) + (when (org-at-item-checkbox-p) + (replace-match "[ ]" t t nil 1)) + (beginning-of-line 2))) + (org-update-checkbox-count-maybe 'all))))) + +(defun org-update-checkbox-count (&optional all) + "Update the checkbox statistics in the current section. + +This will find all statistic cookies like [57%] and [6/12] and +update them with the current numbers. + +With optional prefix argument ALL, do this for the whole buffer." + (interactive "P") + (org-with-wide-buffer + (let* ((cookie-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)") + (box-re "^[ \t]*\\([-+*]\\|\\([0-9]+\\|[A-Za-z]\\)[.)]\\)[ \t]+\ +\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?\\(\\[[- X]\\]\\)") + (recursivep + (or (not org-checkbox-hierarchical-statistics) + (string-match "\\<recursive\\>" + (or (org-entry-get nil "COOKIE_DATA") "")))) + (within-inlinetask (and (not all) + (featurep 'org-inlinetask) + (org-inlinetask-in-task-p))) + (end (cond (all (point-max)) + (within-inlinetask + (save-excursion (outline-next-heading) (point))) + (t (save-excursion + (org-with-limited-levels (outline-next-heading)) + (point))))) + (count-boxes + (lambda (item structs recursivep) + ;; Return number of checked boxes and boxes of all types + ;; in all structures in STRUCTS. If RECURSIVEP is + ;; non-nil, also count boxes in sub-lists. If ITEM is + ;; nil, count across the whole structure, else count only + ;; across subtree whose ancestor is ITEM. + (let ((c-on 0) (c-all 0)) + (dolist (s structs (list c-on c-all)) + (let* ((pre (org-list-prevs-alist s)) + (par (org-list-parents-alist s)) + (items + (cond + ((and recursivep item) (org-list-get-subtree item s)) + (recursivep (mapcar #'car s)) + (item (org-list-get-children item s par)) + (t (org-list-get-all-items + (org-list-get-top-point s) s pre)))) + (cookies (delq nil (mapcar + (lambda (e) + (org-list-get-checkbox e s)) + items)))) + (cl-incf c-all (length cookies)) + (cl-incf c-on (cl-count "[X]" cookies :test #'equal))))))) + cookies-list cache) + ;; Move to start. + (cond (all (goto-char (point-min))) + (within-inlinetask (org-back-to-heading t)) + (t (org-with-limited-levels (outline-previous-heading)))) + ;; Build an alist for each cookie found. The key is the position + ;; at beginning of cookie and values ending position, format of + ;; cookie, number of checked boxes to report and total number of + ;; boxes. + (while (re-search-forward cookie-re end t) + (let ((context (save-excursion (backward-char) + (save-match-data (org-element-context))))) + (when (eq (org-element-type context) 'statistics-cookie) + (push + (append + (list (match-beginning 1) (match-end 1) (match-end 2)) + (let* ((container + (org-element-lineage + context + '(drawer center-block dynamic-block inlinetask item + quote-block special-block verse-block))) + (beg (if container + (org-element-property :contents-begin container) + (save-excursion + (org-with-limited-levels + (outline-previous-heading)) + (point))))) + (or (cdr (assq beg cache)) + (save-excursion + (goto-char beg) + (let ((end + (if container + (org-element-property :contents-end container) + (save-excursion + (org-with-limited-levels (outline-next-heading)) + (point)))) + structs) + (while (re-search-forward box-re end t) + (let ((element (org-element-at-point))) + (when (eq (org-element-type element) 'item) + (push (org-element-property :structure element) + structs) + ;; Skip whole list since we have its + ;; structure anyway. + (while (setq element (org-element-lineage + element '(plain-list))) + (goto-char + (min (org-element-property :end element) + end)))))) + ;; Cache count for cookies applying to the same + ;; area. Then return it. + (let ((count + (funcall count-boxes + (and (eq (org-element-type container) + 'item) + (org-element-property + :begin container)) + structs + recursivep))) + (push (cons beg count) cache) + count)))))) + cookies-list)))) + ;; Apply alist to buffer. + (dolist (cookie cookies-list) + (let* ((beg (car cookie)) + (end (nth 1 cookie)) + (percent (nth 2 cookie)) + (checked (nth 3 cookie)) + (total (nth 4 cookie))) + (goto-char beg) + (insert + (if percent (format "[%d%%]" (floor (* 100.0 checked) + (max 1 total))) + (format "[%d/%d]" checked total))) + (delete-region (point) (+ (point) (- end beg))) + (when org-auto-align-tags (org-fix-tags-on-the-fly))))))) + +(defun org-get-checkbox-statistics-face () + "Select the face for checkbox statistics. +The face will be `org-done' when all relevant boxes are checked. +Otherwise it will be `org-todo'." + (if (match-end 1) + (if (equal (match-string 1) "100%") + 'org-checkbox-statistics-done + 'org-checkbox-statistics-todo) + (if (and (> (match-end 2) (match-beginning 2)) + (equal (match-string 2) (match-string 3))) + 'org-checkbox-statistics-done + 'org-checkbox-statistics-todo))) + +(defun org-update-checkbox-count-maybe (&optional all) + "Update checkbox statistics unless turned off by user. +With an optional argument ALL, update them in the whole buffer." + (when (cdr (assq 'checkbox org-list-automatic-rules)) + (org-update-checkbox-count all)) + (run-hooks 'org-checkbox-statistics-hook)) + +(defvar org-last-indent-begin-marker (make-marker)) +(defvar org-last-indent-end-marker (make-marker)) +(defun org-list-indent-item-generic (arg no-subtree struct) + "Indent a local list item including its children. +When number ARG is a negative, item will be outdented, otherwise +it will be indented. + +If a region is active, all items inside will be moved. + +If NO-SUBTREE is non-nil, only indent the item itself, not its +children. + +STRUCT is the list structure. + +Return t if successful." + (save-excursion + (let* ((regionp (org-region-active-p)) + (rbeg (and regionp (region-beginning))) + (rend (and regionp (region-end))) + (top (org-list-get-top-point struct)) + (parents (org-list-parents-alist struct)) + (prevs (org-list-prevs-alist struct)) + ;; Are we going to move the whole list? + (specialp + (and (not regionp) + (= top (point-at-bol)) + (cdr (assq 'indent org-list-automatic-rules)) + (if no-subtree + (user-error + "At first item: use S-M-<left/right> to move the whole list") + t)))) + ;; Determine begin and end points of zone to indent. If moving + ;; more than one item, save them for subsequent moves. + (unless (and (memq last-command '(org-shiftmetaright org-shiftmetaleft)) + (memq this-command '(org-shiftmetaright org-shiftmetaleft))) + (if regionp + (progn + (set-marker org-last-indent-begin-marker rbeg) + (set-marker org-last-indent-end-marker rend)) + (set-marker org-last-indent-begin-marker (point-at-bol)) + (set-marker org-last-indent-end-marker + (cond + (specialp (org-list-get-bottom-point struct)) + (no-subtree (1+ (point-at-bol))) + (t (org-list-get-item-end (point-at-bol) struct)))))) + (let* ((beg (marker-position org-last-indent-begin-marker)) + (end (marker-position org-last-indent-end-marker))) + (cond + ;; Special case: moving top-item with indent rule. + (specialp + (let* ((level-skip (org-level-increment)) + (offset (if (< arg 0) (- level-skip) level-skip)) + (top-ind (org-list-get-ind beg struct)) + (old-struct (copy-tree struct))) + (if (< (+ top-ind offset) 0) + (error "Cannot outdent beyond margin") + ;; Change bullet if necessary. + (when (and (= (+ top-ind offset) 0) + (string-match "*" + (org-list-get-bullet beg struct))) + (org-list-set-bullet beg struct + (org-list-bullet-string "-"))) + ;; Shift every item by OFFSET and fix bullets. Then + ;; apply changes to buffer. + (mapc (lambda (e) + (let ((ind (org-list-get-ind (car e) struct))) + (org-list-set-ind (car e) struct (+ ind offset)))) + struct) + (org-list-struct-fix-bul struct prevs) + (org-list-struct-apply-struct struct old-struct)))) + ;; Forbidden move: + ((and (< arg 0) + ;; If only one item is moved, it mustn't have a child. + (or (and no-subtree + (not regionp) + (org-list-has-child-p beg struct)) + ;; If a subtree or region is moved, the last item + ;; of the subtree mustn't have a child. + (let ((last-item (caar + (reverse + (cl-remove-if + (lambda (e) (>= (car e) end)) + struct))))) + (org-list-has-child-p last-item struct)))) + (error "Cannot outdent an item without its children")) + ;; Normal shifting + (t + (let* ((new-parents + (if (< arg 0) + (org-list-struct-outdent beg end struct parents) + (org-list-struct-indent beg end struct parents prevs)))) + (org-list-write-struct struct new-parents)) + (org-update-checkbox-count-maybe)))))) + t) + +(defun org-outdent-item () + "Outdent a local list item, but not its children. +If a region is active, all items inside will be moved." + (interactive) + (let ((regionp (org-region-active-p))) + (cond + ((or (org-at-item-p) + (and regionp + (save-excursion (goto-char (region-beginning)) + (org-at-item-p)))) + (let ((struct (if (not regionp) (org-list-struct) + (save-excursion (goto-char (region-beginning)) + (org-list-struct))))) + (org-list-indent-item-generic -1 t struct))) + (regionp (error "Region not starting at an item")) + (t (error "Not at an item"))))) + +(defun org-indent-item () + "Indent a local list item, but not its children. +If a region is active, all items inside will be moved." + (interactive) + (let ((regionp (org-region-active-p))) + (cond + ((or (org-at-item-p) + (and regionp + (save-excursion (goto-char (region-beginning)) + (org-at-item-p)))) + (let ((struct (if (not regionp) (org-list-struct) + (save-excursion (goto-char (region-beginning)) + (org-list-struct))))) + (org-list-indent-item-generic 1 t struct))) + (regionp (error "Region not starting at an item")) + (t (error "Not at an item"))))) + +(defun org-outdent-item-tree () + "Outdent a local list item including its children. +If a region is active, all items inside will be moved." + (interactive) + (let ((regionp (org-region-active-p))) + (cond + ((or (org-at-item-p) + (and regionp + (save-excursion (goto-char (region-beginning)) + (org-at-item-p)))) + (let ((struct (if (not regionp) (org-list-struct) + (save-excursion (goto-char (region-beginning)) + (org-list-struct))))) + (org-list-indent-item-generic -1 nil struct))) + (regionp (error "Region not starting at an item")) + (t (error "Not at an item"))))) + +(defun org-indent-item-tree () + "Indent a local list item including its children. +If a region is active, all items inside will be moved." + (interactive) + (let ((regionp (org-region-active-p))) + (cond + ((or (org-at-item-p) + (and regionp + (save-excursion (goto-char (region-beginning)) + (org-at-item-p)))) + (let ((struct (if (not regionp) (org-list-struct) + (save-excursion (goto-char (region-beginning)) + (org-list-struct))))) + (org-list-indent-item-generic 1 nil struct))) + (regionp (error "Region not starting at an item")) + (t (error "Not at an item"))))) + +(defvar org-tab-ind-state) +(defvar org-adapt-indentation) +(defun org-cycle-item-indentation () + "Cycle levels of indentation of an empty item. +The first run indents the item, if applicable. Subsequent runs +outdent it at meaningful levels in the list. When done, item is +put back at its original position with its original bullet. + +Return t at each successful move." + (when (org-at-item-p) + (let* ((org-adapt-indentation nil) + (struct (org-list-struct)) + (ind (org-list-get-ind (point-at-bol) struct)) + (bullet (org-trim (buffer-substring (point-at-bol) (point-at-eol))))) + ;; Accept empty items or if cycle has already started. + (when (or (eq last-command 'org-cycle-item-indentation) + (and (save-excursion + (beginning-of-line) + (looking-at org-list-full-item-re)) + (>= (match-end 0) (save-excursion + (goto-char (org-list-get-item-end + (point-at-bol) struct)) + (skip-chars-backward " \r\t\n") + (point))))) + (setq this-command 'org-cycle-item-indentation) + ;; When in the middle of the cycle, try to outdent first. If + ;; it fails, and point is still at initial position, indent. + ;; Else, re-create it at its original position. + (if (eq last-command 'org-cycle-item-indentation) + (cond + ((ignore-errors (org-list-indent-item-generic -1 t struct))) + ((and (= ind (car org-tab-ind-state)) + (ignore-errors (org-list-indent-item-generic 1 t struct)))) + (t (delete-region (point-at-bol) (point-at-eol)) + (indent-to-column (car org-tab-ind-state)) + (insert (cdr org-tab-ind-state) " ") + ;; Break cycle + (setq this-command 'identity))) + ;; If a cycle is starting, remember indentation and bullet, + ;; then try to indent. If it fails, try to outdent. + (setq org-tab-ind-state (cons ind bullet)) + (cond + ((ignore-errors (org-list-indent-item-generic 1 t struct))) + ((ignore-errors (org-list-indent-item-generic -1 t struct))) + (t (user-error "Cannot move item")))) + t)))) + +(defun org-sort-list + (&optional with-case sorting-type getkey-func compare-func interactive?) + "Sort list items. +The cursor may be at any item of the list that should be sorted. +Sublists are not sorted. Checkboxes, if any, are ignored. + +Sorting can be alphabetically, numerically, by date/time as given +by a time stamp, by a property or by priority. + +Comparing entries ignores case by default. However, with an +optional argument WITH-CASE, the sorting considers case as well. + +The command prompts for the sorting type unless it has been given +to the function through the SORTING-TYPE argument, which needs to +be a character, \(?n ?N ?a ?A ?t ?T ?f ?F ?x ?X). Here is the +detailed meaning of each character: + +n Numerically, by converting the beginning of the item to a number. +a Alphabetically. Only the first line of item is checked. +t By date/time, either the first active time stamp in the entry, if + any, or by the first inactive one. In a timer list, sort the timers. +x By \"checked\" status of a check list. + +Capital letters will reverse the sort order. + +If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies +a function to be called with point at the beginning of the +record. It must return a value that is compatible with COMPARE-FUNC, +the function used to compare entries. + +Sorting is done against the visible part of the headlines, it +ignores hidden links. + +A non-nil value for INTERACTIVE? is used to signal that this +function is being called interactively." + (interactive (list current-prefix-arg nil nil nil t)) + (let* ((case-func (if with-case 'identity 'downcase)) + (struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (start (org-list-get-list-begin (point-at-bol) struct prevs)) + (end (org-list-get-list-end (point-at-bol) struct prevs)) + (sorting-type + (or sorting-type + (progn + (message + "Sort plain list: [a]lpha [n]umeric [t]ime [f]unc [x]checked A/N/T/F/X means reversed:") + (read-char-exclusive)))) + (dcst (downcase sorting-type)) + (getkey-func + (and (= dcst ?f) + (or getkey-func + (and interactive? + (org-read-function "Function for extracting keys: ")) + (error "Missing key extractor")))) + (sort-func + (cond + ((= dcst ?a) #'string<) + ((= dcst ?f) + (or compare-func + (and interactive? + (org-read-function + (concat "Function for comparing keys " + "(empty for default `sort-subr' predicate): ") + 'allow-empty)))) + ((= dcst ?t) #'<) + ((= dcst ?x) #'string<)))) + (message "Sorting items...") + (save-restriction + (narrow-to-region start end) + (goto-char (point-min)) + (let* ((case-fold-search nil) + (now (current-time)) + (next-record (lambda () + (skip-chars-forward " \r\t\n") + (or (eobp) (beginning-of-line)))) + (end-record (lambda () + (goto-char (org-list-get-item-end-before-blank + (point) struct)))) + (value-to-sort + (lambda () + (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+") + (cond + ((= dcst ?n) + (string-to-number + (org-sort-remove-invisible + (buffer-substring (match-end 0) (point-at-eol))))) + ((= dcst ?a) + (funcall case-func + (org-sort-remove-invisible + (buffer-substring + (match-end 0) (point-at-eol))))) + ((= dcst ?t) + (cond + ;; If it is a timer list, convert timer to seconds + ((org-at-item-timer-p) + (org-timer-hms-to-secs (match-string 1))) + ((or (save-excursion + (re-search-forward org-ts-regexp (point-at-eol) t)) + (save-excursion (re-search-forward org-ts-regexp-both + (point-at-eol) t))) + (org-time-string-to-seconds (match-string 0))) + (t (float-time now)))) + ((= dcst ?x) (or (and (stringp (match-string 1)) + (match-string 1)) + "")) + ((= dcst ?f) + (if getkey-func + (let ((value (funcall getkey-func))) + (if (stringp value) + (funcall case-func value) + value)) + (error "Invalid key function `%s'" getkey-func))) + (t (error "Invalid sorting type `%c'" sorting-type))))))) + (sort-subr (/= dcst sorting-type) + next-record + end-record + value-to-sort + nil + sort-func) + ;; Read and fix list again, as `sort-subr' probably destroyed + ;; its structure. + (org-list-repair) + (run-hooks 'org-after-sorting-entries-or-items-hook) + (message "Sorting items...done"))))) + +(defun org-toggle-item (arg) + "Convert headings or normal lines to items, items to normal lines. +If there is no active region, only the current line is considered. + +If the first non blank line in the region is a headline, convert +all headlines to items, shifting text accordingly. + +If it is an item, convert all items to normal lines. + +If it is normal text, change region into a list of items. +With a prefix argument ARG, change the region in a single item." + (interactive "P") + (let ((shift-text + (lambda (ind end) + ;; Shift text in current section to IND, from point to END. + ;; The function leaves point to END line. + (let ((min-i 1000) (end (copy-marker end))) + ;; First determine the minimum indentation (MIN-I) of + ;; the text. + (save-excursion + (catch 'exit + (while (< (point) end) + (let ((i (org-get-indentation))) + (cond + ;; Skip blank lines and inline tasks. + ((looking-at "^[ \t]*$")) + ((looking-at org-outline-regexp-bol)) + ;; We can't find less than 0 indentation. + ((zerop i) (throw 'exit (setq min-i 0))) + ((< i min-i) (setq min-i i)))) + (forward-line)))) + ;; Then indent each line so that a line indented to + ;; MIN-I becomes indented to IND. Ignore blank lines + ;; and inline tasks in the process. + (let ((delta (- ind min-i))) + (while (< (point) end) + (unless (or (looking-at "^[ \t]*$") + (looking-at org-outline-regexp-bol)) + (indent-line-to (+ (org-get-indentation) delta))) + (forward-line)))))) + (skip-blanks + (lambda (pos) + ;; Return beginning of first non-blank line, starting from + ;; line at POS. + (save-excursion + (goto-char pos) + (skip-chars-forward " \r\t\n") + (point-at-bol)))) + beg end) + ;; Determine boundaries of changes. + (if (org-region-active-p) + (setq beg (funcall skip-blanks (region-beginning)) + end (copy-marker (region-end))) + (setq beg (funcall skip-blanks (point-at-bol)) + end (copy-marker (point-at-eol)))) + ;; Depending on the starting line, choose an action on the text + ;; between BEG and END. + (org-with-limited-levels + (save-excursion + (goto-char beg) + (cond + ;; Case 1. Start at an item: de-itemize. Note that it only + ;; happens when a region is active: `org-ctrl-c-minus' + ;; would call `org-cycle-list-bullet' otherwise. + ((org-at-item-p) + (while (< (point) end) + (when (org-at-item-p) + (skip-chars-forward " \t") + (delete-region (point) (match-end 0))) + (forward-line))) + ;; Case 2. Start at an heading: convert to items. + ((org-at-heading-p) + (let* ((bul (org-list-bullet-string "-")) + (bul-len (length bul)) + ;; Indentation of the first heading. It should be + ;; relative to the indentation of its parent, if any. + (start-ind (save-excursion + (cond + ((not org-adapt-indentation) 0) + ((not (outline-previous-heading)) 0) + (t (length (match-string 0)))))) + ;; Level of first heading. Further headings will be + ;; compared to it to determine hierarchy in the list. + (ref-level (org-reduced-level (org-outline-level)))) + (while (< (point) end) + (let* ((level (org-reduced-level (org-outline-level))) + (delta (max 0 (- level ref-level))) + (todo-state (org-get-todo-state))) + ;; If current headline is less indented than the first + ;; one, set it as reference, in order to preserve + ;; subtrees. + (when (< level ref-level) (setq ref-level level)) + ;; Remove stars and TODO keyword. + (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)) + (delete-region (point) (or (match-beginning 3) + (line-end-position))) + (insert bul) + (indent-line-to (+ start-ind (* delta bul-len))) + ;; Turn TODO keyword into a check box. + (when todo-state + (let* ((struct (org-list-struct)) + (old (copy-tree struct))) + (org-list-set-checkbox + (line-beginning-position) + struct + (if (member todo-state org-done-keywords) + "[X]" + "[ ]")) + (org-list-write-struct struct + (org-list-parents-alist struct) + old))) + ;; Ensure all text down to END (or SECTION-END) belongs + ;; to the newly created item. + (let ((section-end (save-excursion + (or (outline-next-heading) (point))))) + (forward-line) + (funcall shift-text + (+ start-ind (* (1+ delta) bul-len)) + (min end section-end))))))) + ;; Case 3. Normal line with ARG: make the first line of region + ;; an item, and shift indentation of others lines to + ;; set them as item's body. + (arg (let* ((bul (org-list-bullet-string "-")) + (bul-len (length bul)) + (ref-ind (org-get-indentation))) + (skip-chars-forward " \t") + (insert bul) + (forward-line) + (while (< (point) end) + ;; Ensure that lines less indented than first one + ;; still get included in item body. + (funcall shift-text + (+ ref-ind bul-len) + (min end (save-excursion (or (outline-next-heading) + (point))))) + (forward-line)))) + ;; Case 4. Normal line without ARG: turn each non-item line + ;; into an item. + (t + (while (< (point) end) + (unless (or (org-at-heading-p) (org-at-item-p)) + (when (looking-at "\\([ \t]*\\)\\(\\S-\\)") + (replace-match + (concat "\\1" (org-list-bullet-string "-") "\\2")))) + (forward-line)))))))) + + +;;; Send and receive lists + +(defun org-list-to-lisp (&optional delete) + "Parse the list at point and maybe DELETE it. + +Return a list whose car is a symbol of list type, among +`ordered', `unordered' and `descriptive'. Then, each item is +a list of strings and other sub-lists. + +For example, the following list: + + 1. first item + + sub-item one + + [X] sub-item two + more text in first item + 2. [@3] last item + +is parsed as + + (ordered + (\"first item\" + (unordered + (\"sub-item one\") + (\"[X] sub-item two\")) + \"more text in first item\") + (\"[@3] last item\")) + +Point is left at list's end." + (letrec ((struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (parents (org-list-parents-alist struct)) + (top (org-list-get-top-point struct)) + (bottom (org-list-get-bottom-point struct)) + (trim + (lambda (text) + ;; Remove indentation and final newline from TEXT. + (org-remove-indentation + (if (string-match-p "\n\\'" text) + (substring text 0 -1) + text)))) + (parse-sublist + (lambda (e) + ;; Return a list whose car is list type and cdr a list + ;; of items' body. + (cons (org-list-get-list-type (car e) struct prevs) + (mapcar parse-item e)))) + (parse-item + (lambda (e) + ;; Return a list containing counter of item, if any, + ;; text and any sublist inside it. + (let* ((end (org-list-get-item-end e struct)) + (children (org-list-get-children e struct parents)) + (body + (save-excursion + (goto-char e) + (looking-at "[ \t]*\\S-+[ \t]*") + (list + (funcall + trim + (concat + (make-string (string-width (match-string 0)) ?\s) + (buffer-substring-no-properties + (match-end 0) (or (car children) end)))))))) + (while children + (let* ((child (car children)) + (sub (org-list-get-all-items child struct prevs)) + (last-in-sub (car (last sub)))) + (push (funcall parse-sublist sub) body) + ;; Remove whole sub-list from children. + (setq children (cdr (memq last-in-sub children))) + ;; There is a chunk of text belonging to the item + ;; if last child doesn't end where next child + ;; starts or where item ends. + (let ((sub-end (org-list-get-item-end last-in-sub struct)) + (next (or (car children) end))) + (when (/= sub-end next) + (push (funcall + trim + (buffer-substring-no-properties sub-end next)) + body))))) + (nreverse body))))) + ;; Store output, take care of cursor position and deletion of + ;; list, then return output. + (prog1 (funcall parse-sublist (org-list-get-all-items top struct prevs)) + (goto-char top) + (when delete + (delete-region top bottom) + (when (and (not (looking-at "[ \t]*$")) (looking-at org-list-end-re)) + (replace-match "")))))) + +(defun org-list-make-subtree () + "Convert the plain list at point into a subtree." + (interactive) + (if (not (ignore-errors (goto-char (org-in-item-p)))) + (error "Not in a list") + (let ((list (save-excursion (org-list-to-lisp t)))) + (insert (org-list-to-subtree list))))) + +(defun org-list-insert-radio-list () + "Insert a radio list template appropriate for this major mode." + (interactive) + (let* ((e (cl-assoc-if #'derived-mode-p org-list-radio-list-templates)) + (txt (nth 1 e)) + name pos) + (unless e (error "No radio list setup defined for %s" major-mode)) + (setq name (read-string "List name: ")) + (while (string-match "%n" txt) + (setq txt (replace-match name t t txt))) + (or (bolp) (insert "\n")) + (setq pos (point)) + (insert txt) + (goto-char pos))) + +(defun org-list-send-list (&optional maybe) + "Send a transformed version of this list to the receiver position. +With argument MAYBE, fail quietly if no transformation is defined +for this list." + (interactive) + (catch 'exit + (unless (org-at-item-p) (error "Not at a list item")) + (save-excursion + (let ((case-fold-search t)) + (re-search-backward "^[ \t]*#\\+ORGLST:" nil t) + (unless (looking-at + "[ \t]*#\\+ORGLST:[ \t]+SEND[ \t]+\\(\\S-+\\)[ \t]+\\([^ \t\n]+\\)") + (if maybe (throw 'exit nil) + (error "Don't know how to transform this list"))))) + (let* ((name (regexp-quote (match-string 1))) + (transform (intern (match-string 2))) + (bottom-point + (save-excursion + (re-search-forward + "\\(\\\\end{comment}\\|@end ignore\\|-->\\)" nil t) + (match-beginning 0))) + (top-point + (progn + (re-search-backward "#\\+ORGLST" nil t) + (re-search-forward (org-item-beginning-re) bottom-point t) + (match-beginning 0))) + (plain-list (save-excursion + (goto-char top-point) + (org-list-to-lisp)))) + (unless (fboundp transform) + (error "No such transformation function %s" transform)) + (let ((txt (funcall transform plain-list))) + ;; Find the insertion(s) place(s). + (save-excursion + (goto-char (point-min)) + (let ((receiver-count 0) + (begin-re (format "BEGIN +RECEIVE +ORGLST +%s\\([ \t]\\|$\\)" + name)) + (end-re (format "END +RECEIVE +ORGLST +%s\\([ \t]\\|$\\)" + name))) + (while (re-search-forward begin-re nil t) + (cl-incf receiver-count) + (let ((beg (line-beginning-position 2))) + (unless (re-search-forward end-re nil t) + (user-error "Cannot find end of receiver location at %d" beg)) + (beginning-of-line) + (delete-region beg (point)) + (insert txt "\n"))) + (cond + ((> receiver-count 1) + (message "List converted and installed at receiver locations")) + ((= receiver-count 1) + (message "List converted and installed at receiver location")) + (t (user-error "No valid receiver location found"))))))))) + +(defun org-list-to-generic (list params) + "Convert a LIST parsed through `org-list-to-lisp' to a custom format. + +LIST is a list as returned by `org-list-to-lisp', which see. +PARAMS is a property list of parameters used to tweak the output +format. + +Valid parameters are: + +:backend, :raw + + Export back-end used as a basis to transcode elements of the + list, when no specific parameter applies to it. It is also + used to translate its contents. You can prevent this by + setting :raw property to a non-nil value. + +:splice + + When non-nil, only export the contents of the top most plain + list, effectively ignoring its opening and closing lines. + +:ustart, :uend + + Strings to start and end an unordered list. They can also be + set to a function returning a string or nil, which will be + called with the depth of the list, counting from 1. + +:ostart, :oend + + Strings to start and end an ordered list. They can also be set + to a function returning a string or nil, which will be called + with the depth of the list, counting from 1. + +:dstart, :dend + + Strings to start and end a descriptive list. They can also be + set to a function returning a string or nil, which will be + called with the depth of the list, counting from 1. + +:dtstart, :dtend, :ddstart, :ddend + + Strings to start and end a descriptive term. + +:istart, :iend + + Strings to start or end a list item, and to start a list item + with a counter. They can also be set to a function returning + a string or nil, which will be called with two arguments: the + type of list and the depth of the item, counting from 1. + +:icount + + Strings to start a list item with a counter. It can also be + set to a function returning a string or nil, which will be + called with three arguments: the type of list, the depth of the + item, counting from 1, and the counter. Its value, when + non-nil, has precedence over `:istart'. + +:isep + + String used to separate items. It can also be set to + a function returning a string or nil, which will be called with + two arguments: the type of list and the depth of the item, + counting from 1. It always start on a new line. + +:ifmt + + Function to be applied to the contents of every item. It is + called with two arguments: the type of list and the contents. + +:cbon, :cboff, :cbtrans + + String to insert, respectively, an un-checked check-box, + a checked check-box and a check-box in transitional state." + (require 'ox) + (let* ((backend (plist-get params :backend)) + (custom-backend + (org-export-create-backend + :parent (or backend 'org) + :transcoders + `((plain-list . ,(org-list--to-generic-plain-list params)) + (item . ,(org-list--to-generic-item params)) + (macro . (lambda (m c i) (org-element-macro-interpreter m nil)))))) + data info) + ;; Write LIST back into Org syntax and parse it. + (with-temp-buffer + (let ((org-inhibit-startup t)) (org-mode)) + (letrec ((insert-list + (lambda (l) + (dolist (i (cdr l)) + (funcall insert-item i (car l))))) + (insert-item + (lambda (i type) + (let ((start (point))) + (insert (if (eq type 'ordered) "1. " "- ")) + (dolist (e i) + (if (consp e) (funcall insert-list e) + (insert e) + (insert "\n"))) + (beginning-of-line) + (save-excursion + (let ((ind (if (eq type 'ordered) 3 2))) + (while (> (point) start) + (unless (looking-at-p "[ \t]*$") + (indent-to ind)) + (forward-line -1)))))))) + (funcall insert-list list)) + (setf data + (org-element-map (org-element-parse-buffer) 'plain-list + #'identity nil t)) + (setf info (org-export-get-environment backend nil params))) + (when (and backend (symbolp backend) (not (org-export-get-backend backend))) + (user-error "Unknown :backend value")) + (unless backend (require 'ox-org)) + ;; When`:raw' property has a non-nil value, turn all objects back + ;; into Org syntax. + (when (and backend (plist-get params :raw)) + (org-element-map data org-element-all-objects + (lambda (object) + (org-element-set-element + object (org-element-interpret-data object))))) + ;; We use a low-level mechanism to export DATA so as to skip all + ;; usual pre-processing and post-processing, i.e., hooks, filters, + ;; Babel code evaluation, include keywords and macro expansion, + ;; and filters. + (let ((output (org-export-data-with-backend data custom-backend info))) + ;; Remove final newline. + (if (org-string-nw-p output) (substring-no-properties output 0 -1) "")))) + +(defun org-list--depth (element) + "Return the level of ELEMENT within current plain list. +ELEMENT is either an item or a plain list." + (cl-count-if (lambda (ancestor) (eq (org-element-type ancestor) 'plain-list)) + (org-element-lineage element nil t))) + +(defun org-list--trailing-newlines (string) + "Return the number of trailing newlines in STRING." + (with-temp-buffer + (insert string) + (skip-chars-backward " \t\n") + (count-lines (line-beginning-position 2) (point-max)))) + +(defun org-list--generic-eval (value &rest args) + "Evaluate VALUE according to its type. +VALUE is either nil, a string or a function. In the latter case, +it is called with arguments ARGS." + (cond ((null value) nil) + ((stringp value) value) + ((functionp value) (apply value args)) + (t (error "Wrong value: %s" value)))) + +(defun org-list--to-generic-plain-list (params) + "Return a transcoder for `plain-list' elements. +PARAMS is a plist used to tweak the behavior of the transcoder." + (let ((ustart (plist-get params :ustart)) + (uend (plist-get params :uend)) + (ostart (plist-get params :ostart)) + (oend (plist-get params :oend)) + (dstart (plist-get params :dstart)) + (dend (plist-get params :dend)) + (splice (plist-get params :splice)) + (backend (plist-get params :backend))) + (lambda (plain-list contents info) + (let* ((type (org-element-property :type plain-list)) + (depth (org-list--depth plain-list)) + (start (and (not splice) + (org-list--generic-eval + (pcase type + (`ordered ostart) + (`unordered ustart) + (_ dstart)) + depth))) + (end (and (not splice) + (org-list--generic-eval + (pcase type + (`ordered oend) + (`unordered uend) + (_ dend)) + depth)))) + ;; Make sure trailing newlines in END appear in the output by + ;; setting `:post-blank' property to their number. + (when end + (org-element-put-property + plain-list :post-blank (org-list--trailing-newlines end))) + ;; Build output. + (concat (and start (concat start "\n")) + (if (or start end splice (not backend)) + contents + (org-export-with-backend backend plain-list contents info)) + end))))) + +(defun org-list--to-generic-item (params) + "Return a transcoder for `item' elements. +PARAMS is a plist used to tweak the behavior of the transcoder." + (let ((backend (plist-get params :backend)) + (istart (plist-get params :istart)) + (iend (plist-get params :iend)) + (isep (plist-get params :isep)) + (icount (plist-get params :icount)) + (ifmt (plist-get params :ifmt)) + (cboff (plist-get params :cboff)) + (cbon (plist-get params :cbon)) + (cbtrans (plist-get params :cbtrans)) + (dtstart (plist-get params :dtstart)) + (dtend (plist-get params :dtend)) + (ddstart (plist-get params :ddstart)) + (ddend (plist-get params :ddend))) + (lambda (item contents info) + (let* ((type + (org-element-property :type (org-element-property :parent item))) + (tag (org-element-property :tag item)) + (depth (org-list--depth item)) + (separator (and (org-export-get-next-element item info) + (org-list--generic-eval isep type depth))) + (closing (pcase (org-list--generic-eval iend type depth) + ((or `nil "") "\n") + ((and (guard separator) s) + (if (equal (substring s -1) "\n") s (concat s "\n"))) + (s s)))) + ;; When a closing line or a separator is provided, make sure + ;; its trailing newlines are taken into account when building + ;; output. This is done by setting `:post-blank' property to + ;; the number of such lines in the last line to be added. + (let ((last-string (or separator closing))) + (when last-string + (org-element-put-property + item + :post-blank + (max (1- (org-list--trailing-newlines last-string)) 0)))) + ;; Build output. + (concat + (let ((c (org-element-property :counter item))) + (if (and c icount) (org-list--generic-eval icount type depth c) + (org-list--generic-eval istart type depth))) + (let ((body + (if (or istart iend icount ifmt cbon cboff cbtrans (not backend) + (and (eq type 'descriptive) + (or dtstart dtend ddstart ddend))) + (concat + (pcase (org-element-property :checkbox item) + (`on cbon) + (`off cboff) + (`trans cbtrans)) + (and tag + (concat dtstart + (if backend + (org-export-data-with-backend + tag backend info) + (org-element-interpret-data tag)) + dtend)) + (and tag ddstart) + (let ((contents + (if (= (length contents) 0) "" + (substring contents 0 -1)))) + (if ifmt (org-list--generic-eval ifmt type contents) + contents)) + (and tag ddend)) + (org-export-with-backend backend item contents info)))) + ;; Remove final newline. + (if (equal body "") "" + (substring (org-element-normalize-string body) 0 -1))) + closing + separator))))) + +(defun org-list-to-latex (list &optional params) + "Convert LIST into a LaTeX list. +LIST is a parsed plain list, as returned by `org-list-to-lisp'. +PARAMS is a property list with overruling parameters for +`org-list-to-generic'. Return converted list as a string." + (require 'ox-latex) + (org-list-to-generic list (org-combine-plists '(:backend latex) params))) + +(defun org-list-to-html (list &optional params) + "Convert LIST into a HTML list. +LIST is a parsed plain list, as returned by `org-list-to-lisp'. +PARAMS is a property list with overruling parameters for +`org-list-to-generic'. Return converted list as a string." + (require 'ox-html) + (org-list-to-generic list (org-combine-plists '(:backend html) params))) + +(defun org-list-to-texinfo (list &optional params) + "Convert LIST into a Texinfo list. +LIST is a parsed plain list, as returned by `org-list-to-lisp'. +PARAMS is a property list with overruling parameters for +`org-list-to-generic'. Return converted list as a string." + (require 'ox-texinfo) + (org-list-to-generic list (org-combine-plists '(:backend texinfo) params))) + +(defun org-list-to-org (list &optional params) + "Convert LIST into an Org plain list. +LIST is as returned by `org-list-parse-list'. PARAMS is a property list +with overruling parameters for `org-list-to-generic'." + (let* ((make-item + (lambda (type _depth &optional c) + (concat (if (eq type 'ordered) "1. " "- ") + (and c (format "[@%d] " c))))) + (defaults + (list :istart make-item + :icount make-item + :ifmt (lambda (_type contents) + (replace-regexp-in-string "\n" "\n " contents)) + :dtend " :: " + :cbon "[X] " + :cboff "[ ] " + :cbtrans "[-] "))) + (org-list-to-generic list (org-combine-plists defaults params)))) + +(defun org-list-to-subtree (list &optional params) + "Convert LIST into an Org subtree. +LIST is as returned by `org-list-to-lisp'. PARAMS is a property +list with overruling parameters for `org-list-to-generic'." + (let* ((blank (pcase (cdr (assq 'heading org-blank-before-new-entry)) + (`t t) + (`auto (save-excursion + (org-with-limited-levels (outline-previous-heading)) + (org-previous-line-empty-p))))) + (level (org-reduced-level (or (org-current-level) 0))) + (make-stars + (lambda (_type depth &optional _count) + ;; Return the string for the heading, depending on DEPTH + ;; of current sub-list. + (let ((oddeven-level (+ level depth))) + (concat (make-string (if org-odd-levels-only + (1- (* 2 oddeven-level)) + oddeven-level) + ?*) + " "))))) + (org-list-to-generic + list + (org-combine-plists + (list :splice t + :istart make-stars + :icount make-stars + :dtstart " " :dtend " " + :isep (if blank "\n\n" "\n") + :cbon "DONE " :cboff "TODO " :cbtrans "TODO ") + params)))) + +(provide 'org-list) + +;;; org-list.el ends here diff --git a/elpa/org-9.1.14/org-loaddefs.el b/elpa/org-9.1.14/org-loaddefs.el new file mode 100644 index 00000000..ec6e5de9 --- /dev/null +++ b/elpa/org-9.1.14/org-loaddefs.el @@ -0,0 +1,3565 @@ +;;; org-loaddefs.el --- autogenerated file, do not edit +;; +;;; Code: + +;;;### (autoloads nil "ob-core" "ob-core.el" "2360a439d4b3b494bbdc436ee6d6976d") +;;; Generated autoloads from ob-core.el + +(autoload 'org-babel-execute-safely-maybe "ob-core" "\ + + +\(fn)" nil nil) + +(autoload 'org-babel-execute-maybe "ob-core" "\ + + +\(fn)" t nil) + +(autoload 'org-babel-view-src-block-info "ob-core" "\ +Display information on the current source block. +This includes header arguments, language and name, and is largely +a window into the `org-babel-get-src-block-info' function. + +\(fn)" t nil) + +(autoload 'org-babel-expand-src-block-maybe "ob-core" "\ +Conditionally expand a source block. +Detect if this is context for an org-babel src-block and if so +then run `org-babel-expand-src-block'. + +\(fn)" t nil) + +(autoload 'org-babel-load-in-session-maybe "ob-core" "\ +Conditionally load a source block in a session. +Detect if this is context for an org-babel src-block and if so +then run `org-babel-load-in-session'. + +\(fn)" t nil) + +(autoload 'org-babel-pop-to-session-maybe "ob-core" "\ +Conditionally pop to a session. +Detect if this is context for an org-babel src-block and if so +then run `org-babel-switch-to-session'. + +\(fn)" t nil) + +(autoload 'org-babel-execute-src-block "ob-core" "\ +Execute the current source code block. +Insert the results of execution into the buffer. Source code +execution and the collection and formatting of results can be +controlled through a variety of header arguments. + +With prefix argument ARG, force re-execution even if an existing +result cached in the buffer would otherwise have been returned. + +Optionally supply a value for INFO in the form returned by +`org-babel-get-src-block-info'. + +Optionally supply a value for PARAMS which will be merged with +the header arguments specified at the front of the source code +block. + +\(fn &optional ARG INFO PARAMS)" t nil) + +(autoload 'org-babel-expand-src-block "ob-core" "\ +Expand the current source code block. +Expand according to the source code block's header +arguments and pop open the results in a preview buffer. + +\(fn &optional ARG INFO PARAMS)" t nil) + +(autoload 'org-babel-check-src-block "ob-core" "\ +Check for misspelled header arguments in the current code block. + +\(fn)" t nil) + +(autoload 'org-babel-insert-header-arg "ob-core" "\ +Insert a header argument selecting from lists of common args and values. + +\(fn &optional HEADER-ARG VALUE)" t nil) + +(autoload 'org-babel-load-in-session "ob-core" "\ +Load the body of the current source-code block. +Evaluate the header arguments for the source block before +entering the session. After loading the body this pops open the +session. + +\(fn &optional ARG INFO)" t nil) + +(autoload 'org-babel-initiate-session "ob-core" "\ +Initiate session for current code block. +If called with a prefix argument then resolve any variable +references in the header arguments and assign these variables in +the session. Copy the body of the code block to the kill ring. + +\(fn &optional ARG INFO)" t nil) + +(autoload 'org-babel-switch-to-session "ob-core" "\ +Switch to the session of the current code block. +Uses `org-babel-initiate-session' to start the session. If called +with a prefix argument then this is passed on to +`org-babel-initiate-session'. + +\(fn &optional ARG INFO)" t nil) + +(autoload 'org-babel-switch-to-session-with-code "ob-core" "\ +Switch to code buffer and display session. + +\(fn &optional ARG INFO)" t nil) + +(autoload 'org-babel-do-in-edit-buffer "ob-core" "\ +Evaluate BODY in edit buffer if there is a code block at point. +Return t if a code block was found at point, nil otherwise. + +\(fn &rest BODY)" nil t) + +(autoload 'org-babel-open-src-block-result "ob-core" "\ +If `point' is on a src block then open the results of the +source code block, otherwise return nil. With optional prefix +argument RE-RUN the source-code block is evaluated even if +results already exist. + +\(fn &optional RE-RUN)" t nil) + +(autoload 'org-babel-map-src-blocks "ob-core" "\ +Evaluate BODY forms on each source-block in FILE. +If FILE is nil evaluate BODY forms on source blocks in current +buffer. During evaluation of BODY the following local variables +are set relative to the currently matched code block. + +full-block ------- string holding the entirety of the code block +beg-block -------- point at the beginning of the code block +end-block -------- point at the end of the matched code block +lang ------------- string holding the language of the code block +beg-lang --------- point at the beginning of the lang +end-lang --------- point at the end of the lang +switches --------- string holding the switches +beg-switches ----- point at the beginning of the switches +end-switches ----- point at the end of the switches +header-args ------ string holding the header-args +beg-header-args -- point at the beginning of the header-args +end-header-args -- point at the end of the header-args +body ------------- string holding the body of the code block +beg-body --------- point at the beginning of the body +end-body --------- point at the end of the body + +\(fn FILE &rest BODY)" nil t) + +(function-put 'org-babel-map-src-blocks 'lisp-indent-function '1) + +(autoload 'org-babel-map-inline-src-blocks "ob-core" "\ +Evaluate BODY forms on each inline source block in FILE. +If FILE is nil evaluate BODY forms on source blocks in current +buffer. + +\(fn FILE &rest BODY)" nil t) + +(function-put 'org-babel-map-inline-src-blocks 'lisp-indent-function '1) + +(autoload 'org-babel-map-call-lines "ob-core" "\ +Evaluate BODY forms on each call line in FILE. +If FILE is nil evaluate BODY forms on source blocks in current +buffer. + +\(fn FILE &rest BODY)" nil t) + +(function-put 'org-babel-map-call-lines 'lisp-indent-function '1) + +(autoload 'org-babel-map-executables "ob-core" "\ +Evaluate BODY forms on each active Babel code in FILE. +If FILE is nil evaluate BODY forms on source blocks in current +buffer. + +\(fn FILE &rest BODY)" nil t) + +(function-put 'org-babel-map-executables 'lisp-indent-function '1) + +(autoload 'org-babel-execute-buffer "ob-core" "\ +Execute source code blocks in a buffer. +Call `org-babel-execute-src-block' on every source block in +the current buffer. + +\(fn &optional ARG)" t nil) + +(autoload 'org-babel-execute-subtree "ob-core" "\ +Execute source code blocks in a subtree. +Call `org-babel-execute-src-block' on every source block in +the current subtree. + +\(fn &optional ARG)" t nil) + +(autoload 'org-babel-sha1-hash "ob-core" "\ +Generate an sha1 hash based on the value of info. + +\(fn &optional INFO)" t nil) + +(autoload 'org-babel-hide-result-toggle-maybe "ob-core" "\ +Toggle visibility of result at point. + +\(fn)" t nil) + +(autoload 'org-babel-goto-src-block-head "ob-core" "\ +Go to the beginning of the current code block. + +\(fn)" t nil) + +(autoload 'org-babel-goto-named-src-block "ob-core" "\ +Go to a named source-code block. + +\(fn NAME)" t nil) + +(autoload 'org-babel-goto-named-result "ob-core" "\ +Go to a named result. + +\(fn NAME)" t nil) + +(autoload 'org-babel-next-src-block "ob-core" "\ +Jump to the next source block. +With optional prefix argument ARG, jump forward ARG many source blocks. + +\(fn &optional ARG)" t nil) + +(autoload 'org-babel-previous-src-block "ob-core" "\ +Jump to the previous source block. +With optional prefix argument ARG, jump backward ARG many source blocks. + +\(fn &optional ARG)" t nil) + +(autoload 'org-babel-mark-block "ob-core" "\ +Mark current src block. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "ob-keys" "ob-keys.el" "22ff8882b2f215251464dafb29893479") +;;; Generated autoloads from ob-keys.el + +(autoload 'org-babel-describe-bindings "ob-keys" "\ +Describe all keybindings behind `org-babel-key-prefix'. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "ob-lob" "ob-lob.el" "c7b7a7fd9c121e0d73709dd5a4821194") +;;; Generated autoloads from ob-lob.el + +(autoload 'org-babel-lob-execute-maybe "ob-lob" "\ +Execute a Library of Babel source block, if appropriate. +Detect if this is context for a Library Of Babel source block and +if so then run the appropriate source block from the Library. + +\(fn)" t nil) + +(autoload 'org-babel-lob-get-info "ob-lob" "\ +Return internal representation for Library of Babel function call. + +Consider DATUM, when provided, or element at point otherwise. + +Return nil when not on an appropriate location. Otherwise return +a list compatible with `org-babel-get-src-block-info', which +see. + +\(fn &optional DATUM)" nil nil) + +;;;*** + +;;;### (autoloads nil "ob-tangle" "ob-tangle.el" "6f42a8d7a0ef762480d9e747e6ab033a") +;;; Generated autoloads from ob-tangle.el + +(autoload 'org-babel-tangle-file "ob-tangle" "\ +Extract the bodies of source code blocks in FILE. +Source code blocks are extracted with `org-babel-tangle'. +Optional argument TARGET-FILE can be used to specify a default +export file for all source blocks. Optional argument LANG can be +used to limit the exported source code blocks by language. +Return a list whose CAR is the tangled file name. + +\(fn FILE &optional TARGET-FILE LANG)" t nil) + +(autoload 'org-babel-tangle "ob-tangle" "\ +Write code blocks to source-specific files. +Extract the bodies of all source code blocks from the current +file into their own source-specific files. +With one universal prefix argument, only tangle the block at point. +When two universal prefix arguments, only tangle blocks for the +tangle file of the block at point. +Optional argument TARGET-FILE can be used to specify a default +export file for all source blocks. Optional argument LANG can be +used to limit the exported source code blocks by language. + +\(fn &optional ARG TARGET-FILE LANG)" t nil) + +;;;*** + +;;;### (autoloads nil "org-agenda" "org-agenda.el" (23266 31379 196273 +;;;;;; 327000)) +;;; Generated autoloads from org-agenda.el + +(autoload 'org-toggle-sticky-agenda "org-agenda" "\ +Toggle `org-agenda-sticky'. + +\(fn &optional ARG)" t nil) + +(autoload 'org-agenda "org-agenda" "\ +Dispatch agenda commands to collect entries to the agenda buffer. +Prompts for a command to execute. Any prefix arg will be passed +on to the selected command. The default selections are: + +a Call `org-agenda-list' to display the agenda for current day or week. +t Call `org-todo-list' to display the global todo list. +T Call `org-todo-list' to display the global todo list, select only + entries with a specific TODO keyword (the user gets a prompt). +m Call `org-tags-view' to display headlines with tags matching + a condition (the user is prompted for the condition). +M Like `m', but select only TODO entries, no ordinary headlines. +e Export views to associated files. +s Search entries for keywords. +S Search entries for keywords, only with TODO keywords. +/ Multi occur across all agenda files and also files listed + in `org-agenda-text-search-extra-files'. +< Restrict agenda commands to buffer, subtree, or region. + Press several times to get the desired effect. +> Remove a previous restriction. +# List \"stuck\" projects. +! Configure what \"stuck\" means. +C Configure custom agenda commands. + +More commands can be added by configuring the variable +`org-agenda-custom-commands'. In particular, specific tags and TODO keyword +searches can be pre-defined in this way. + +If the current buffer is in Org mode and visiting a file, you can also +first press `<' once to indicate that the agenda should be temporarily +\(until the next use of `\\[org-agenda]') restricted to the current file. +Pressing `<' twice means to restrict to the current subtree or region +\(if active). + +\(fn &optional ARG ORG-KEYS RESTRICTION)" t nil) + +(autoload 'org-batch-agenda "org-agenda" "\ +Run an agenda command in batch mode and send the result to STDOUT. +If CMD-KEY is a string of length 1, it is used as a key in +`org-agenda-custom-commands' and triggers this command. If it is a +longer string it is used as a tags/todo match string. +Parameters are alternating variable names and values that will be bound +before running the agenda command. + +\(fn CMD-KEY &rest PARAMETERS)" nil t) + +(autoload 'org-batch-agenda-csv "org-agenda" "\ +Run an agenda command in batch mode and send the result to STDOUT. +If CMD-KEY is a string of length 1, it is used as a key in +`org-agenda-custom-commands' and triggers this command. If it is a +longer string it is used as a tags/todo match string. +Parameters are alternating variable names and values that will be bound +before running the agenda command. + +The output gives a line for each selected agenda item. Each +item is a list of comma-separated values, like this: + +category,head,type,todo,tags,date,time,extra,priority-l,priority-n + +category The category of the item +head The headline, without TODO kwd, TAGS and PRIORITY +type The type of the agenda entry, can be + todo selected in TODO match + tagsmatch selected in tags match + diary imported from diary + deadline a deadline on given date + scheduled scheduled on given date + timestamp entry has timestamp on given date + closed entry was closed on given date + upcoming-deadline warning about deadline + past-scheduled forwarded scheduled item + block entry has date block including g. date +todo The todo keyword, if any +tags All tags including inherited ones, separated by colons +date The relevant date, like 2007-2-14 +time The time, like 15:00-16:50 +extra Sting with extra planning info +priority-l The priority letter if any was given +priority-n The computed numerical priority +agenda-day The day in the agenda where this is listed + +\(fn CMD-KEY &rest PARAMETERS)" nil t) + +(autoload 'org-store-agenda-views "org-agenda" "\ +Store agenda views. + +\(fn &rest PARAMETERS)" t nil) + +(autoload 'org-batch-store-agenda-views "org-agenda" "\ +Run all custom agenda commands that have a file argument. + +\(fn &rest PARAMETERS)" nil t) + +(autoload 'org-agenda-list "org-agenda" "\ +Produce a daily/weekly view from all files in variable `org-agenda-files'. +The view will be for the current day or week, but from the overview buffer +you will be able to go to other days/weeks. + +With a numeric prefix argument in an interactive call, the agenda will +span ARG days. Lisp programs should instead specify SPAN to change +the number of days. SPAN defaults to `org-agenda-span'. + +START-DAY defaults to TODAY, or to the most recent match for the weekday +given in `org-agenda-start-on-weekday'. + +When WITH-HOUR is non-nil, only include scheduled and deadline +items if they have an hour specification like [h]h:mm. + +\(fn &optional ARG START-DAY SPAN WITH-HOUR)" t nil) + +(autoload 'org-search-view "org-agenda" "\ +Show all entries that contain a phrase or words or regular expressions. + +With optional prefix argument TODO-ONLY, only consider entries that are +TODO entries. The argument STRING can be used to pass a default search +string into this function. If EDIT-AT is non-nil, it means that the +user should get a chance to edit this string, with cursor at position +EDIT-AT. + +The search string can be viewed either as a phrase that should be found as +is, or it can be broken into a number of snippets, each of which must match +in a Boolean way to select an entry. The default depends on the variable +`org-agenda-search-view-always-boolean'. +Even if this is turned off (the default) you can always switch to +Boolean search dynamically by preceding the first word with \"+\" or \"-\". + +The default is a direct search of the whole phrase, where each space in +the search string can expand to an arbitrary amount of whitespace, +including newlines. + +If using a Boolean search, the search string is split on whitespace and +each snippet is searched separately, with logical AND to select an entry. +Words prefixed with a minus must *not* occur in the entry. Words without +a prefix or prefixed with a plus must occur in the entry. Matching is +case-insensitive. Words are enclosed by word delimiters (i.e. they must +match whole words, not parts of a word) if +`org-agenda-search-view-force-full-words' is set (default is nil). + +Boolean search snippets enclosed by curly braces are interpreted as +regular expressions that must or (when preceded with \"-\") must not +match in the entry. Snippets enclosed into double quotes will be taken +as a whole, to include whitespace. + +- If the search string starts with an asterisk, search only in headlines. +- If (possibly after the leading star) the search string starts with an + exclamation mark, this also means to look at TODO entries only, an effect + that can also be achieved with a prefix argument. +- If (possibly after star and exclamation mark) the search string starts + with a colon, this will mean that the (non-regexp) snippets of the + Boolean search must match as full words. + +This command searches the agenda files, and in addition the files +listed in `org-agenda-text-search-extra-files' unless a restriction lock +is active. + +\(fn &optional TODO-ONLY STRING EDIT-AT)" t nil) + +(autoload 'org-todo-list "org-agenda" "\ +Show all (not done) TODO entries from all agenda file in a single list. +The prefix arg can be used to select a specific TODO keyword and limit +the list to these. When using `\\[universal-argument]', you will be prompted +for a keyword. A numeric prefix directly selects the Nth keyword in +`org-todo-keywords-1'. + +\(fn &optional ARG)" t nil) + +(autoload 'org-tags-view "org-agenda" "\ +Show all headlines for all `org-agenda-files' matching a TAGS criterion. +The prefix arg TODO-ONLY limits the search to TODO entries. + +\(fn &optional TODO-ONLY MATCH)" t nil) + +(autoload 'org-agenda-list-stuck-projects "org-agenda" "\ +Create agenda view for projects that are stuck. +Stuck projects are project that have no next actions. For the definitions +of what a project is and how to check if it stuck, customize the variable +`org-stuck-projects'. + +\(fn &rest IGNORE)" t nil) + +(autoload 'org-diary "org-agenda" "\ +Return diary information from org files. +This function can be used in a \"sexp\" diary entry in the Emacs calendar. +It accesses org files and extracts information from those files to be +listed in the diary. The function accepts arguments specifying what +items should be listed. For a list of arguments allowed here, see the +variable `org-agenda-entry-types'. + +The call in the diary file should look like this: + + &%%(org-diary) ~/path/to/some/orgfile.org + +Use a separate line for each org file to check. Or, if you omit the file name, +all files listed in `org-agenda-files' will be checked automatically: + + &%%(org-diary) + +If you don't give any arguments (as in the example above), the default value +of `org-agenda-entry-types' is used: (:deadline :scheduled :timestamp :sexp). +So the example above may also be written as + + &%%(org-diary :deadline :timestamp :sexp :scheduled) + +The function expects the lisp variables `entry' and `date' to be provided +by the caller, because this is how the calendar works. Don't use this +function from a program - use `org-agenda-get-day-entries' instead. + +\(fn &rest ARGS)" nil nil) + +(autoload 'org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item "org-agenda" "\ +Do we have a reason to ignore this TODO entry because it has a time stamp? + +\(fn &optional END)" nil nil) + +(autoload 'org-agenda-set-restriction-lock "org-agenda" "\ +Set restriction lock for agenda, to current subtree or file. +Restriction will be the file if TYPE is `file', or if type is the +universal prefix \\='(4), or if the cursor is before the first headline +in the file. Otherwise, restriction will be to the current subtree. + +\(fn &optional TYPE)" t nil) + +(autoload 'org-calendar-goto-agenda "org-agenda" "\ +Compute the Org agenda for the calendar date displayed at the cursor. +This is a command that has to be installed in `calendar-mode-map'. + +\(fn)" t nil) + +(autoload 'org-agenda-to-appt "org-agenda" "\ +Activate appointments found in `org-agenda-files'. + +With a `\\[universal-argument]' prefix, refresh the list of appointments. + +If FILTER is t, interactively prompt the user for a regular +expression, and filter out entries that don't match it. + +If FILTER is a string, use this string as a regular expression +for filtering entries out. + +If FILTER is a function, filter out entries against which +calling the function returns nil. This function takes one +argument: an entry from `org-agenda-get-day-entries'. + +FILTER can also be an alist with the car of each cell being +either `headline' or `category'. For example: + + \\='((headline \"IMPORTANT\") + (category \"Work\")) + +will only add headlines containing IMPORTANT or headlines +belonging to the \"Work\" category. + +ARGS are symbols indicating what kind of entries to consider. +By default `org-agenda-to-appt' will use :deadline*, :scheduled* +\(i.e., deadlines and scheduled items with a hh:mm specification) +and :timestamp entries. See the docstring of `org-diary' for +details and examples. + +If an entry has a APPT_WARNTIME property, its value will be used +to override `appt-message-warning-time'. + +\(fn &optional REFRESH FILTER &rest ARGS)" t nil) + +;;;*** + +;;;### (autoloads nil "org-archive" "org-archive.el" "b46ec348f237e44615caaa99e48ff324") +;;; Generated autoloads from org-archive.el + +(autoload 'org-add-archive-files "org-archive" "\ +Splice the archive files into the list of files. +This implies visiting all these files and finding out what the +archive file is. + +\(fn FILES)" nil nil) + +(autoload 'org-archive-subtree "org-archive" "\ +Move the current subtree to the archive. +The archive can be a certain top-level heading in the current +file, or in a different file. The tree will be moved to that +location, the subtree heading be marked DONE, and the current +time will be added. + +When called with a single prefix argument FIND-DONE, find whole +trees without any open TODO items and archive them (after getting +confirmation from the user). When called with a double prefix +argument, find whole trees with timestamps before today and +archive them (after getting confirmation from the user). If the +cursor is not at a headline when these commands are called, try +all level 1 trees. If the cursor is on a headline, only try the +direct children of this heading. + +\(fn &optional FIND-DONE)" t nil) + +(autoload 'org-archive-to-archive-sibling "org-archive" "\ +Archive the current heading by moving it under the archive sibling. + +The archive sibling is a sibling of the heading with the heading name +`org-archive-sibling-heading' and an `org-archive-tag' tag. If this +sibling does not exist, it will be created at the end of the subtree. + +Archiving time is retained in the ARCHIVE_TIME node property. + +\(fn)" t nil) + +(autoload 'org-toggle-archive-tag "org-archive" "\ +Toggle the archive tag for the current headline. +With prefix ARG, check all children of current headline and offer tagging +the children that do not contain any open TODO items. + +\(fn &optional FIND-DONE)" t nil) + +(autoload 'org-archive-subtree-default "org-archive" "\ +Archive the current subtree with the default command. +This command is set with the variable `org-archive-default-command'. + +\(fn)" t nil) + +(autoload 'org-archive-subtree-default-with-confirmation "org-archive" "\ +Archive the current subtree with the default command. +This command is set with the variable `org-archive-default-command'. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "org-attach" "org-attach.el" "649a2308d04a53d6af3d987342905a97") +;;; Generated autoloads from org-attach.el + +(autoload 'org-attach "org-attach" "\ +The dispatcher for attachment commands. +Shows a list of commands and prompts for another key to execute a command. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "org-bbdb" "org-bbdb.el" "fa404717dfcbde54e13812132d9d4850") +;;; Generated autoloads from org-bbdb.el + +(autoload 'org-bbdb-anniversaries "org-bbdb" "\ +Extract anniversaries from BBDB for display in the agenda. + +\(fn)" nil nil) + +;;;*** + +;;;### (autoloads nil "org-capture" "org-capture.el" (23260 10064 +;;;;;; 718296 919000)) +;;; Generated autoloads from org-capture.el + +(autoload 'org-capture-string "org-capture" "\ +Capture STRING with the template selected by KEYS. + +\(fn STRING &optional KEYS)" t nil) + +(autoload 'org-capture "org-capture" "\ +Capture something. +\\<org-capture-mode-map> +This will let you select a template from `org-capture-templates', and +then file the newly captured information. The text is immediately +inserted at the target location, and an indirect buffer is shown where +you can edit it. Pressing `\\[org-capture-finalize]' brings you back to the previous +state of Emacs, so that you can continue your work. + +When called interactively with a `\\[universal-argument]' prefix argument GOTO, don't +capture anything, just go to the file/headline where the selected +template stores its notes. + +With a `\\[universal-argument] \\[universal-argument]' prefix argument, go to the last note stored. + +When called with a `C-0' (zero) prefix, insert a template at point. + +When called with a `C-1' (one) prefix, force prompting for a date when +a datetree entry is made. + +ELisp programs can set KEYS to a string associated with a template +in `org-capture-templates'. In this case, interactive selection +will be bypassed. + +If `org-capture-use-agenda-date' is non-nil, capturing from the +agenda will use the date at point as the default date. Then, a +`C-1' prefix will tell the capture process to use the HH:MM time +of the day at point (if any) or the current HH:MM time. + +\(fn &optional GOTO KEYS)" t nil) + +(autoload 'org-capture-import-remember-templates "org-capture" "\ +Set `org-capture-templates' to be similar to `org-remember-templates'. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "org-clock" "org-clock.el" "731d09f8ca5acf7266b16282a1e05671") +;;; Generated autoloads from org-clock.el + +(autoload 'org-resolve-clocks "org-clock" "\ +Resolve all currently open Org clocks. +If `only-dangling-p' is non-nil, only ask to resolve dangling +\(i.e., not currently open and valid) clocks. + +\(fn &optional ONLY-DANGLING-P PROMPT-FN LAST-VALID)" t nil) + +(autoload 'org-clock-in "org-clock" "\ +Start the clock on the current item. + +If necessary, clock-out of the currently active clock. + +With a `\\[universal-argument]' prefix argument SELECT, offer a list of recently clocked +tasks to clock into. + +When SELECT is `\\[universal-argument] \\[universal-argument]', clock into the current task and mark it as +the default task, a special task that will always be offered in the +clocking selection, associated with the letter `d'. + +When SELECT is `\\[universal-argument] \\[universal-argument] \\[universal-argument]', clock in by using the last clock-out +time as the start time. See `org-clock-continuously' to make this +the default behavior. + +\(fn &optional SELECT START-TIME)" t nil) + +(autoload 'org-clock-in-last "org-clock" "\ +Clock in the last closed clocked item. +When already clocking in, send a warning. +With a universal prefix argument, select the task you want to +clock in from the last clocked in tasks. +With two universal prefix arguments, start clocking using the +last clock-out time, if any. +With three universal prefix arguments, interactively prompt +for a todo state to switch to, overriding the existing value +`org-clock-in-switch-to-state'. + +\(fn &optional ARG)" t nil) + +(autoload 'org-clock-out "org-clock" "\ +Stop the currently running clock. +Throw an error if there is no running clock and FAIL-QUIETLY is nil. +With a universal prefix, prompt for a state to switch the clocked out task +to, overriding the existing value of `org-clock-out-switch-to-state'. + +\(fn &optional SWITCH-TO-STATE FAIL-QUIETLY AT-TIME)" t nil) + +(autoload 'org-clock-cancel "org-clock" "\ +Cancel the running clock by removing the start timestamp. + +\(fn)" t nil) + +(autoload 'org-clock-goto "org-clock" "\ +Go to the currently clocked-in entry, or to the most recently clocked one. +With prefix arg SELECT, offer recently clocked tasks for selection. + +\(fn &optional SELECT)" t nil) + +(autoload 'org-clock-sum-today "org-clock" "\ +Sum the times for each subtree for today. + +\(fn &optional HEADLINE-FILTER)" nil nil) + +(autoload 'org-clock-sum "org-clock" "\ +Sum the times for each subtree. +Puts the resulting times in minutes as a text property on each headline. +TSTART and TEND can mark a time range to be considered. +HEADLINE-FILTER is a zero-arg function that, if specified, is called for +each headline in the time range with point at the headline. Headlines for +which HEADLINE-FILTER returns nil are excluded from the clock summation. +PROPNAME lets you set a custom text property instead of :org-clock-minutes. + +\(fn &optional TSTART TEND HEADLINE-FILTER PROPNAME)" nil nil) + +(autoload 'org-clock-display "org-clock" "\ +Show subtree times in the entire buffer. + +By default, show the total time for the range defined in +`org-clock-display-default-range'. With `\\[universal-argument]' prefix, show +the total time for today instead. + +With `\\[universal-argument] \\[universal-argument]' prefix, use a custom range, entered at prompt. + +With `\\[universal-argument] \\[universal-argument] \\[universal-argument]' prefix, display the total time in the +echo area. + +Use `\\[org-clock-remove-overlays]' to remove the subtree times. + +\(fn &optional ARG)" t nil) + +(autoload 'org-clock-remove-overlays "org-clock" "\ +Remove the occur highlights from the buffer. +If NOREMOVE is nil, remove this function from the +`before-change-functions' in the current buffer. + +\(fn &optional BEG END NOREMOVE)" t nil) + +(autoload 'org-clock-get-clocktable "org-clock" "\ +Get a formatted clocktable with parameters according to PROPS. +The table is created in a temporary buffer, fully formatted and +fontified, and then returned. + +\(fn &rest PROPS)" nil nil) + +(autoload 'org-clock-report "org-clock" "\ +Update or create a table containing a report about clocked time. + +If point is inside an existing clocktable block, update it. +Otherwise, insert a new one. + +The new table inherits its properties from the variable +`org-clock-clocktable-default-properties'. The scope of the +clocktable, when not specified in the previous variable, is +`subtree' when the function is called from within a subtree, and +`file' elsewhere. + +When called with a prefix argument, move to the first clock table +in the buffer and update it. + +\(fn &optional ARG)" t nil) + +(autoload 'org-clocktable-shift "org-clock" "\ +Try to shift the :block date of the clocktable at point. +Point must be in the #+BEGIN: line of a clocktable, or this function +will throw an error. +DIR is a direction, a symbol `left', `right', `up', or `down'. +Both `left' and `down' shift the block toward the past, `up' and `right' +push it toward the future. +N is the number of shift steps to take. The size of the step depends on +the currently selected interval size. + +\(fn DIR N)" nil nil) + +(autoload 'org-dblock-write:clocktable "org-clock" "\ +Write the standard clocktable. + +\(fn PARAMS)" nil nil) + +(autoload 'org-clock-update-time-maybe "org-clock" "\ +If this is a CLOCK line, update it and return t. +Otherwise, return nil. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "org-colview" "org-colview.el" (23195 45027 +;;;;;; 389190 102000)) +;;; Generated autoloads from org-colview.el + +(autoload 'org-columns-remove-overlays "org-colview" "\ +Remove all currently active column overlays. + +\(fn)" t nil) + +(autoload 'org-columns-get-format-and-top-level "org-colview" "\ + + +\(fn)" nil nil) + +(autoload 'org-columns "org-colview" "\ +Turn on column view on an Org mode file. + +Column view applies to the whole buffer if point is before the +first headline. Otherwise, it applies to the first ancestor +setting \"COLUMNS\" property. If there is none, it defaults to +the current headline. With a `\\[universal-argument]' prefix argument, turn on column +view for the whole buffer unconditionally. + +When COLUMNS-FMT-STRING is non-nil, use it as the column format. + +\(fn &optional GLOBAL COLUMNS-FMT-STRING)" t nil) + +(autoload 'org-columns-compute "org-colview" "\ +Summarize the values of PROPERTY hierarchically. +Also update existing values for PROPERTY according to the first +column specification. + +\(fn PROPERTY)" t nil) + +(autoload 'org-dblock-write:columnview "org-colview" "\ +Write the column view table. +PARAMS is a property list of parameters: + +:id the :ID: property of the entry where the columns view + should be built. When the symbol `local', call locally. + When `global' call column view with the cursor at the beginning + of the buffer (usually this means that the whole buffer switches + to column view). When \"file:path/to/file.org\", invoke column + view at the start of that file. Otherwise, the ID is located + using `org-id-find'. +:hlines When t, insert a hline before each item. When a number, insert + a hline before each level <= that number. +:indent When non-nil, indent each ITEM field according to its level. +:vlines When t, make each column a colgroup to enforce vertical lines. +:maxlevel When set to a number, don't capture headlines below this level. +:skip-empty-rows + When t, skip rows where all specifiers other than ITEM are empty. +:width apply widths specified in columns format using <N> specifiers. +:format When non-nil, specify the column view format to use. + +\(fn PARAMS)" nil nil) + +(autoload 'org-columns-insert-dblock "org-colview" "\ +Create a dynamic block capturing a column view table. + +\(fn)" t nil) + +(autoload 'org-agenda-columns "org-colview" "\ +Turn on or update column view in the agenda. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "org-compat" "org-compat.el" (23195 45027 389190 +;;;;;; 102000)) +;;; Generated autoloads from org-compat.el + +(autoload 'org-check-version "org-compat" "\ +Try very hard to provide sensible version strings. + +\(fn)" nil t) + +;;;*** + +;;;### (autoloads nil "org-datetree" "org-datetree.el" "ba966f278edd387a7bef6fe54c90b123") +;;; Generated autoloads from org-datetree.el + +(autoload 'org-datetree-find-date-create "org-datetree" "\ +Find or create an entry for date D. +If KEEP-RESTRICTION is non-nil, do not widen the buffer. +When it is nil, the buffer will be widened to make sure an existing date +tree can be found. If it is the symbol `subtree-at-point', then the tree +will be built under the headline at point. + +\(fn D &optional KEEP-RESTRICTION)" nil nil) + +(autoload 'org-datetree-find-iso-week-create "org-datetree" "\ +Find or create an ISO week entry for date D. +Compared to `org-datetree-find-date-create' this function creates +entries ordered by week instead of months. +When it is nil, the buffer will be widened to make sure an existing date +tree can be found. If it is the symbol `subtree-at-point', then the tree +will be built under the headline at point. + +\(fn D &optional KEEP-RESTRICTION)" nil nil) + +;;;*** + +;;;### (autoloads nil "org-duration" "org-duration.el" (23122 46211 +;;;;;; 557086 433000)) +;;; Generated autoloads from org-duration.el + +(autoload 'org-duration-set-regexps "org-duration" "\ +Set duration related regexps. + +\(fn)" t nil) + +(autoload 'org-duration-p "org-duration" "\ +Non-nil when string S is a time duration. + +\(fn S)" nil nil) + +(autoload 'org-duration-to-minutes "org-duration" "\ +Return number of minutes of DURATION string. + +When optional argument CANONICAL is non-nil, ignore +`org-duration-units' and use standard time units value. + +A bare number is translated into minutes. The empty string is +translated into 0.0. + +Return value as a float. Raise an error if duration format is +not recognized. + +\(fn DURATION &optional CANONICAL)" nil nil) + +(autoload 'org-duration-from-minutes "org-duration" "\ +Return duration string for a given number of MINUTES. + +Format duration according to `org-duration-format' or FMT, when +non-nil. + +When optional argument CANONICAL is non-nil, ignore +`org-duration-units' and use standard time units value. + +Raise an error if expected format is unknown. + +\(fn MINUTES &optional FMT CANONICAL)" nil nil) + +(autoload 'org-duration-h:mm-only-p "org-duration" "\ +Non-nil when every duration in TIMES has \"H:MM\" or \"H:MM:SS\" format. + +TIMES is a list of duration strings. + +Return nil if any duration is expressed with units, as defined in +`org-duration-units'. Otherwise, if any duration is expressed +with \"H:MM:SS\" format, return `h:mm:ss'. Otherwise, return +`h:mm'. + +\(fn TIMES)" nil nil) + +;;;*** + +;;;### (autoloads nil "org-element" "org-element.el" "9884bb79ba81b08be137ab07c79303a1") +;;; Generated autoloads from org-element.el + +(autoload 'org-element-update-syntax "org-element" "\ +Update parser internals. + +\(fn)" t nil) + +(autoload 'org-element-interpret-data "org-element" "\ +Interpret DATA as Org syntax. +DATA is a parse tree, an element, an object or a secondary string +to interpret. Return Org syntax as a string. + +\(fn DATA)" nil nil) + +(autoload 'org-element-cache-reset "org-element" "\ +Reset cache in current buffer. +When optional argument ALL is non-nil, reset cache in all Org +buffers. + +\(fn &optional ALL)" t nil) + +(autoload 'org-element-cache-refresh "org-element" "\ +Refresh cache at position POS. + +\(fn POS)" nil nil) + +(autoload 'org-element-at-point "org-element" "\ +Determine closest element around point. + +Return value is a list like (TYPE PROPS) where TYPE is the type +of the element and PROPS a plist of properties associated to the +element. + +Possible types are defined in `org-element-all-elements'. +Properties depend on element or object type, but always include +`:begin', `:end', `:parent' and `:post-blank' properties. + +As a special case, if point is at the very beginning of the first +item in a list or sub-list, returned element will be that list +instead of the item. Likewise, if point is at the beginning of +the first row of a table, returned element will be the table +instead of the first row. + +When point is at the end of the buffer, return the innermost +element ending there. + +\(fn)" nil nil) + +(autoload 'org-element-context "org-element" "\ +Return smallest element or object around point. + +Return value is a list like (TYPE PROPS) where TYPE is the type +of the element or object and PROPS a plist of properties +associated to it. + +Possible types are defined in `org-element-all-elements' and +`org-element-all-objects'. Properties depend on element or +object type, but always include `:begin', `:end', `:parent' and +`:post-blank'. + +As a special case, if point is right after an object and not at +the beginning of any other object, return that object. + +Optional argument ELEMENT, when non-nil, is the closest element +containing point, as returned by `org-element-at-point'. +Providing it allows for quicker computation. + +\(fn &optional ELEMENT)" nil nil) + +;;;*** + +;;;### (autoloads nil "org-feed" "org-feed.el" "cc9d7655449e79a01a0a7b58bd1d9ca1") +;;; Generated autoloads from org-feed.el + +(autoload 'org-feed-update-all "org-feed" "\ +Get inbox items from all feeds in `org-feed-alist'. + +\(fn)" t nil) + +(autoload 'org-feed-update "org-feed" "\ +Get inbox items from FEED. +FEED can be a string with an association in `org-feed-alist', or +it can be a list structured like an entry in `org-feed-alist'. + +\(fn FEED &optional RETRIEVE-ONLY)" t nil) + +(autoload 'org-feed-goto-inbox "org-feed" "\ +Go to the inbox that captures the feed named FEED. + +\(fn FEED)" t nil) + +(autoload 'org-feed-show-raw-feed "org-feed" "\ +Show the raw feed buffer of a feed. + +\(fn FEED)" t nil) + +;;;*** + +;;;### (autoloads nil "org-footnote" "org-footnote.el" "e9ce16dcb970cce6c642f3b7f07bbbc8") +;;; Generated autoloads from org-footnote.el + +(autoload 'org-footnote-action "org-footnote" "\ +Do the right thing for footnotes. + +When at a footnote reference, jump to the definition. + +When at a definition, jump to the references if they exist, offer +to create them otherwise. + +When neither at definition or reference, create a new footnote, +interactively if possible. + +With prefix arg SPECIAL, or when no footnote can be created, +offer additional commands in a menu. + +\(fn &optional SPECIAL)" t nil) + +;;;*** + +;;;### (autoloads nil "org-id" "org-id.el" "3a6cfd2d05c88ba07781cd0a2d1078f3") +;;; Generated autoloads from org-id.el + +(autoload 'org-id-get-create "org-id" "\ +Create an ID for the current entry and return it. +If the entry already has an ID, just return it. +With optional argument FORCE, force the creation of a new ID. + +\(fn &optional FORCE)" t nil) + +(autoload 'org-id-copy "org-id" "\ +Copy the ID of the entry at point to the kill ring. +Create an ID if necessary. + +\(fn)" t nil) + +(autoload 'org-id-get "org-id" "\ +Get the ID property of the entry at point-or-marker POM. +If POM is nil, refer to the entry at point. +If the entry does not have an ID, the function returns nil. +However, when CREATE is non nil, create an ID if none is present already. +PREFIX will be passed through to `org-id-new'. +In any case, the ID of the entry is returned. + +\(fn &optional POM CREATE PREFIX)" nil nil) + +(autoload 'org-id-get-with-outline-path-completion "org-id" "\ +Use `outline-path-completion' to retrieve the ID of an entry. +TARGETS may be a setting for `org-refile-targets' to define +eligible headlines. When omitted, all headlines in the current +file are eligible. This function returns the ID of the entry. +If necessary, the ID is created. + +\(fn &optional TARGETS)" nil nil) + +(autoload 'org-id-get-with-outline-drilling "org-id" "\ +Use an outline-cycling interface to retrieve the ID of an entry. +This only finds entries in the current buffer, using `org-get-location'. +It returns the ID of the entry. If necessary, the ID is created. + +\(fn)" nil nil) + +(autoload 'org-id-goto "org-id" "\ +Switch to the buffer containing the entry with id ID. +Move the cursor to that entry in that buffer. + +\(fn ID)" t nil) + +(autoload 'org-id-find "org-id" "\ +Return the location of the entry with the id ID. +The return value is a cons cell (file-name . position), or nil +if there is no entry with that ID. +With optional argument MARKERP, return the position as a new marker. + +\(fn ID &optional MARKERP)" nil nil) + +(autoload 'org-id-new "org-id" "\ +Create a new globally unique ID. + +An ID consists of two parts separated by a colon: +- a prefix +- a unique part that will be created according to `org-id-method'. + +PREFIX can specify the prefix, the default is given by the variable +`org-id-prefix'. However, if PREFIX is the symbol `none', don't use any +prefix even if `org-id-prefix' specifies one. + +So a typical ID could look like \"Org:4nd91V40HI\". + +\(fn &optional PREFIX)" nil nil) + +(autoload 'org-id-update-id-locations "org-id" "\ +Scan relevant files for IDs. +Store the relation between files and corresponding IDs. +This will scan all agenda files, all associated archives, and all +files currently mentioned in `org-id-locations'. +When FILES is given, scan these files instead. + +\(fn &optional FILES SILENT)" t nil) + +(autoload 'org-id-find-id-file "org-id" "\ +Query the id database for the file in which this ID is located. + +\(fn ID)" nil nil) + +(autoload 'org-id-store-link "org-id" "\ +Store a link to the current entry, using its ID. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "org-indent" "org-indent.el" "a1b3a5cb538d830f8686ef38fac39a3f") +;;; Generated autoloads from org-indent.el + +(autoload 'org-indent-mode "org-indent" "\ +When active, indent text according to outline structure. + +Internally this works by adding `line-prefix' and `wrap-prefix' +properties, after each buffer modification, on the modified zone. + +The process is synchronous. Though, initial indentation of +buffer, which can take a few seconds on large buffers, is done +during idle time. + +\(fn &optional ARG)" t nil) + +;;;*** + +;;;### (autoloads nil "org-irc" "org-irc.el" "4c557982f1eec29419c881a776b4c7bf") +;;; Generated autoloads from org-irc.el + +(autoload 'org-irc-store-link "org-irc" "\ +Dispatch to the appropriate function to store a link to an IRC session. + +\(fn)" nil nil) + +;;;*** + +;;;### (autoloads nil "org-lint" "org-lint.el" (23122 46211 569086 +;;;;;; 279000)) +;;; Generated autoloads from org-lint.el + +(autoload 'org-lint "org-lint" "\ +Check current Org buffer for syntax mistakes. + +By default, run all checkers. With a `\\[universal-argument]' prefix ARG, select one +category of checkers only. With a `\\[universal-argument] \\[universal-argument]' prefix, run one precise +checker by its name. + +ARG can also be a list of checker names, as symbols, to run. + +\(fn &optional ARG)" t nil) + +;;;*** + +;;;### (autoloads nil "org-macs" "org-macs.el" (23195 45027 401189 +;;;;;; 958000)) +;;; Generated autoloads from org-macs.el + +(autoload 'org-load-noerror-mustsuffix "org-macs" "\ +Load FILE with optional arguments NOERROR and MUSTSUFFIX. + +\(fn FILE)" nil t) + +;;;*** + +;;;### (autoloads nil "org-mobile" "org-mobile.el" "e005b7accde48f9f5da5855f7bb547ec") +;;; Generated autoloads from org-mobile.el + +(autoload 'org-mobile-push "org-mobile" "\ +Push the current state of Org affairs to the target directory. +This will create the index file, copy all agenda files there, and also +create all custom agenda views, for upload to the mobile phone. + +\(fn)" t nil) + +(autoload 'org-mobile-pull "org-mobile" "\ +Pull the contents of `org-mobile-capture-file' and integrate them. +Apply all flagged actions, flag entries to be flagged and then call an +agenda view showing the flagged items. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "org-plot" "org-plot.el" "85b14ab93a67abe34c254eb6c55bd79c") +;;; Generated autoloads from org-plot.el + +(autoload 'org-plot/gnuplot "org-plot" "\ +Plot table using gnuplot. Gnuplot options can be specified with PARAMS. +If not given options will be taken from the +PLOT +line directly before or after the table. + +\(fn &optional PARAMS)" t nil) + +;;;*** + +;;;### (autoloads nil "org-table" "org-table.el" "655b68fb9b54da75d23bcfc26f39e1d3") +;;; Generated autoloads from org-table.el + +(autoload 'org-table-create-with-table\.el "org-table" "\ +Use the table.el package to insert a new table. +If there is already a table at point, convert between Org tables +and table.el tables. + +\(fn)" t nil) + +(autoload 'org-table-create-or-convert-from-region "org-table" "\ +Convert region to table, or create an empty table. +If there is an active region, convert it to a table, using the function +`org-table-convert-region'. See the documentation of that function +to learn how the prefix argument is interpreted to determine the field +separator. +If there is no such region, create an empty table with `org-table-create'. + +\(fn ARG)" t nil) + +(autoload 'org-table-create "org-table" "\ +Query for a size and insert a table skeleton. +SIZE is a string Columns x Rows like for example \"3x2\". + +\(fn &optional SIZE)" t nil) + +(autoload 'org-table-convert-region "org-table" "\ +Convert region to a table. + +The region goes from BEG0 to END0, but these borders will be moved +slightly, to make sure a beginning of line in the first line is included. + +SEPARATOR specifies the field separator in the lines. It can have the +following values: + +\(4) Use the comma as a field separator +\(16) Use a TAB as field separator +\(64) Prompt for a regular expression as field separator +integer When a number, use that many spaces, or a TAB, as field separator +regexp When a regular expression, use it to match the separator +nil When nil, the command tries to be smart and figure out the + separator in the following way: + - when each line contains a TAB, assume TAB-separated material + - when each line contains a comma, assume CSV material + - else, assume one or more SPACE characters as separator. + +\(fn BEG0 END0 &optional SEPARATOR)" t nil) + +(autoload 'org-table-import "org-table" "\ +Import FILE as a table. + +The command tries to be smart and figure out the separator in the +following way: + + - when each line contains a TAB, assume TAB-separated material + - when each line contains a comma, assume CSV material + - else, assume one or more SPACE characters as separator. + +When non-nil, SEPARATOR specifies the field separator in the +lines. It can have the following values: + +\(4) Use the comma as a field separator +\(16) Use a TAB as field separator +\(64) Prompt for a regular expression as field separator +integer When a number, use that many spaces, or a TAB, as field separator +regexp When a regular expression, use it to match the separator. + +\(fn FILE SEPARATOR)" t nil) + +(autoload 'org-table-export "org-table" "\ +Export table to a file, with configurable format. +Such a file can be imported into usual spreadsheet programs. + +FILE can be the output file name. If not given, it will be taken +from a TABLE_EXPORT_FILE property in the current entry or higher +up in the hierarchy, or the user will be prompted for a file +name. FORMAT can be an export format, of the same kind as it +used when `orgtbl-mode' sends a table in a different format. + +The command suggests a format depending on TABLE_EXPORT_FORMAT, +whether it is set locally or up in the hierarchy, then on the +extension of the given file name, and finally on the variable +`org-table-export-default-format'. + +\(fn &optional FILE FORMAT)" t nil) + +(autoload 'org-table-align "org-table" "\ +Align the table at point by aligning all vertical bars. + +\(fn)" t nil) + +(autoload 'org-table-begin "org-table" "\ +Find the beginning of the table and return its position. +With a non-nil optional argument TABLE-TYPE, return the beginning +of a table.el-type table. This function assumes point is on +a table. + +\(fn &optional TABLE-TYPE)" nil nil) + +(autoload 'org-table-end "org-table" "\ +Find the end of the table and return its position. +With a non-nil optional argument TABLE-TYPE, return the end of +a table.el-type table. This function assumes point is on +a table. + +\(fn &optional TABLE-TYPE)" nil nil) + +(autoload 'org-table-justify-field-maybe "org-table" "\ +Justify the current field, text to left, number to right. +Optional argument NEW may specify text to replace the current field content. + +\(fn &optional NEW)" nil nil) + +(autoload 'org-table-next-field "org-table" "\ +Go to the next field in the current table, creating new lines as needed. +Before doing so, re-align the table if necessary. + +\(fn)" t nil) + +(autoload 'org-table-previous-field "org-table" "\ +Go to the previous field in the table. +Before doing so, re-align the table if necessary. + +\(fn)" t nil) + +(autoload 'org-table-next-row "org-table" "\ +Go to the next row (same column) in the current table. +Before doing so, re-align the table if necessary. + +\(fn)" t nil) + +(autoload 'org-table-copy-down "org-table" "\ +Copy the value of the current field one row below. + +If the field at the cursor is empty, copy the content of the +nearest non-empty field above. With argument N, use the Nth +non-empty field. + +If the current field is not empty, it is copied down to the next +row, and the cursor is moved with it. Therefore, repeating this +command causes the column to be filled row-by-row. + +If the variable `org-table-copy-increment' is non-nil and the +field is an integer or a timestamp, it will be incremented while +copying. By default, increment by the difference between the +value in the current field and the one in the field above. To +increment using a fixed integer, set `org-table-copy-increment' +to a number. In the case of a timestamp, increment by days. + +\(fn N)" t nil) + +(autoload 'org-table-blank-field "org-table" "\ +Blank the current table field or active region. + +\(fn)" t nil) + +(autoload 'org-table-field-info "org-table" "\ +Show info about the current field, and highlight any reference at point. + +\(fn ARG)" t nil) + +(autoload 'org-table-goto-column "org-table" "\ +Move the cursor to the Nth column in the current table line. +With optional argument ON-DELIM, stop with point before the left delimiter +of the field. +If there are less than N fields, just go to after the last delimiter. +However, when FORCE is non-nil, create new columns if necessary. + +\(fn N &optional ON-DELIM FORCE)" t nil) + +(autoload 'org-table-insert-column "org-table" "\ +Insert a new column into the table. + +\(fn)" t nil) + +(autoload 'org-table-delete-column "org-table" "\ +Delete a column from the table. + +\(fn)" t nil) + +(autoload 'org-table-move-column-right "org-table" "\ +Move column to the right. + +\(fn)" t nil) + +(autoload 'org-table-move-column-left "org-table" "\ +Move column to the left. + +\(fn)" t nil) + +(autoload 'org-table-move-column "org-table" "\ +Move the current column to the right. With arg LEFT, move to the left. + +\(fn &optional LEFT)" t nil) + +(autoload 'org-table-move-row-down "org-table" "\ +Move table row down. + +\(fn)" t nil) + +(autoload 'org-table-move-row-up "org-table" "\ +Move table row up. + +\(fn)" t nil) + +(autoload 'org-table-move-row "org-table" "\ +Move the current table line down. With arg UP, move it up. + +\(fn &optional UP)" t nil) + +(autoload 'org-table-insert-row "org-table" "\ +Insert a new row above the current line into the table. +With prefix ARG, insert below the current line. + +\(fn &optional ARG)" t nil) + +(autoload 'org-table-insert-hline "org-table" "\ +Insert a horizontal-line below the current line into the table. +With prefix ABOVE, insert above the current line. + +\(fn &optional ABOVE)" t nil) + +(autoload 'org-table-hline-and-move "org-table" "\ +Insert a hline and move to the row below that line. + +\(fn &optional SAME-COLUMN)" t nil) + +(autoload 'org-table-kill-row "org-table" "\ +Delete the current row or horizontal line from the table. + +\(fn)" t nil) + +(autoload 'org-table-sort-lines "org-table" "\ +Sort table lines according to the column at point. + +The position of point indicates the column to be used for +sorting, and the range of lines is the range between the nearest +horizontal separator lines, or the entire table of no such lines +exist. If point is before the first column, you will be prompted +for the sorting column. If there is an active region, the mark +specifies the first line and the sorting column, while point +should be in the last line to be included into the sorting. + +The command then prompts for the sorting type which can be +alphabetically, numerically, or by time (as given in a time stamp +in the field, or as a HH:MM value). Sorting in reverse order is +also possible. + +With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive. + +If SORTING-TYPE is specified when this function is called from a Lisp +program, no prompting will take place. SORTING-TYPE must be a character, +any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that +sorting should be done in reverse order. + +If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies +a function to be called to extract the key. It must return a value +that is compatible with COMPARE-FUNC, the function used to compare +entries. + +A non-nil value for INTERACTIVE? is used to signal that this +function is being called interactively. + +\(fn &optional WITH-CASE SORTING-TYPE GETKEY-FUNC COMPARE-FUNC INTERACTIVE\\=\\?)" t nil) + +(autoload 'org-table-cut-region "org-table" "\ +Copy region in table to the clipboard and blank all relevant fields. +If there is no active region, use just the field at point. + +\(fn BEG END)" t nil) + +(autoload 'org-table-copy-region "org-table" "\ +Copy rectangular region in table to clipboard. +A special clipboard is used which can only be accessed +with `org-table-paste-rectangle'. + +\(fn BEG END &optional CUT)" t nil) + +(autoload 'org-table-paste-rectangle "org-table" "\ +Paste a rectangular region into a table. +The upper right corner ends up in the current field. All involved fields +will be overwritten. If the rectangle does not fit into the present table, +the table is enlarged as needed. The process ignores horizontal separator +lines. + +\(fn)" t nil) + +(autoload 'org-table-convert "org-table" "\ +Convert from `org-mode' table to table.el and back. +Obviously, this only works within limits. When an Org table is converted +to table.el, all horizontal separator lines get lost, because table.el uses +these as cell boundaries and has no notion of horizontal lines. A table.el +table can be converted to an Org table only if it does not do row or column +spanning. Multiline cells will become multiple cells. Beware, Org mode +does not test if the table can be successfully converted - it blindly +applies a recipe that works for simple tables. + +\(fn)" t nil) + +(autoload 'org-table-wrap-region "org-table" "\ +Wrap several fields in a column like a paragraph. +This is useful if you'd like to spread the contents of a field over several +lines, in order to keep the table compact. + +If there is an active region, and both point and mark are in the same column, +the text in the column is wrapped to minimum width for the given number of +lines. Generally, this makes the table more compact. A prefix ARG may be +used to change the number of desired lines. For example, `C-2 \\[org-table-wrap-region]' +formats the selected text to two lines. If the region was longer than two +lines, the remaining lines remain empty. A negative prefix argument reduces +the current number of lines by that amount. The wrapped text is pasted back +into the table. If you formatted it to more lines than it was before, fields +further down in the table get overwritten - so you might need to make space in +the table first. + +If there is no region, the current field is split at the cursor position and +the text fragment to the right of the cursor is prepended to the field one +line down. + +If there is no region, but you specify a prefix ARG, the current field gets +blank, and the content is appended to the field above. + +\(fn ARG)" t nil) + +(autoload 'org-table-edit-field "org-table" "\ +Edit table field in a different window. +This is mainly useful for fields that contain hidden parts. + +When called with a `\\[universal-argument]' prefix, just make the full field +visible so that it can be edited in place. + +When called with a `\\[universal-argument] \\[universal-argument]' prefix, toggle `org-table-follow-field-mode'. + +\(fn ARG)" t nil) + +(autoload 'org-table-sum "org-table" "\ +Sum numbers in region of current table column. +The result will be displayed in the echo area, and will be available +as kill to be inserted with \\[yank]. + +If there is an active region, it is interpreted as a rectangle and all +numbers in that rectangle will be summed. If there is no active +region and point is located in a table column, sum all numbers in that +column. + +If at least one number looks like a time HH:MM or HH:MM:SS, all other +numbers are assumed to be times as well (in decimal hours) and the +numbers are added as such. + +If NLAST is a number, only the NLAST fields will actually be summed. + +\(fn &optional BEG END NLAST)" t nil) + +(autoload 'org-table-get-stored-formulas "org-table" "\ +Return an alist with the stored formulas directly after current table. +By default, only return active formulas, i.e., formulas located +on the first line after the table. However, if optional argument +LOCATION is a buffer position, consider the formulas there. + +\(fn &optional NOERROR LOCATION)" nil nil) + +(autoload 'org-table-maybe-eval-formula "org-table" "\ +Check if the current field starts with \"=\" or \":=\". +If yes, store the formula and apply it. + +\(fn)" nil nil) + +(autoload 'org-table-rotate-recalc-marks "org-table" "\ +Rotate the recalculation mark in the first column. +If in any row, the first field is not consistent with a mark, +insert a new column for the markers. +When there is an active region, change all the lines in the region, +after prompting for the marking character. +After each change, a message will be displayed indicating the meaning +of the new mark. + +\(fn &optional NEWCHAR)" t nil) + +(autoload 'org-table-analyze "org-table" "\ +Analyze table at point and store results. + +This function sets up the following dynamically scoped variables: + + `org-table-column-name-regexp', + `org-table-column-names', + `org-table-current-begin-pos', + `org-table-current-line-types', + `org-table-current-ncol', + `org-table-dlines', + `org-table-hlines', + `org-table-local-parameters', + `org-table-named-field-locations'. + +\(fn)" nil nil) + +(autoload 'org-table-maybe-recalculate-line "org-table" "\ +Recompute the current line if marked for it, and if we haven't just done it. + +\(fn)" t nil) + +(autoload 'org-table-eval-formula "org-table" "\ +Replace the table field value at the cursor by the result of a calculation. + +In a table, this command replaces the value in the current field with the +result of a formula. It also installs the formula as the \"current\" column +formula, by storing it in a special line below the table. When called +with a `\\[universal-argument]' prefix the formula is installed as a field formula. + +When called with a `\\[universal-argument] \\[universal-argument]' prefix, insert the active equation for the field +back into the current field, so that it can be edited there. This is useful +in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to check the referenced fields. + +When called, the command first prompts for a formula, which is read in +the minibuffer. Previously entered formulas are available through the +history list, and the last used formula is offered as a default. +These stored formulas are adapted correctly when moving, inserting, or +deleting columns with the corresponding commands. + +The formula can be any algebraic expression understood by the Calc package. +For details, see the Org mode manual. + +This function can also be called from Lisp programs and offers +additional arguments: EQUATION can be the formula to apply. If this +argument is given, the user will not be prompted. + +SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing +unnecessary aligns. + +SUPPRESS-CONST suppresses the interpretation of constants in the +formula, assuming that this has been done already outside the +function. + +SUPPRESS-STORE means the formula should not be stored, either +because it is already stored, or because it is a modified +equation that should not overwrite the stored one. + +SUPPRESS-ANALYSIS prevents analyzing the table and checking +location of point. + +\(fn &optional ARG EQUATION SUPPRESS-ALIGN SUPPRESS-CONST SUPPRESS-STORE SUPPRESS-ANALYSIS)" t nil) + +(autoload 'org-table-recalculate "org-table" "\ +Recalculate the current table line by applying all stored formulas. + +With prefix arg ALL, do this for all lines in the table. + +When called with a `\\[universal-argument] \\[universal-argument]' prefix, or if ALL is the symbol `iterate', +recompute the table until it no longer changes. + +If NOALIGN is not nil, do not re-align the table after the computations +are done. This is typically used internally to save time, if it is +known that the table will be realigned a little later anyway. + +\(fn &optional ALL NOALIGN)" t nil) + +(autoload 'org-table-iterate "org-table" "\ +Recalculate the table until it does not change anymore. +The maximum number of iterations is 10, but you can choose a different value +with the prefix ARG. + +\(fn &optional ARG)" t nil) + +(autoload 'org-table-recalculate-buffer-tables "org-table" "\ +Recalculate all tables in the current buffer. + +\(fn)" t nil) + +(autoload 'org-table-iterate-buffer-tables "org-table" "\ +Iterate all tables in the buffer, to converge inter-table dependencies. + +\(fn)" t nil) + +(autoload 'org-table-edit-formulas "org-table" "\ +Edit the formulas of the current table in a separate buffer. + +\(fn)" t nil) + +(autoload 'org-table-toggle-coordinate-overlays "org-table" "\ +Toggle the display of Row/Column numbers in tables. + +\(fn)" t nil) + +(autoload 'org-table-toggle-formula-debugger "org-table" "\ +Toggle the formula debugger in tables. + +\(fn)" t nil) + +(autoload 'orgtbl-mode "org-table" "\ +The Org mode table editor as a minor mode for use in other modes. + +\(fn &optional ARG)" t nil) + +(defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$" "\ +Regular expression matching exponentials as produced by calc.") + +(autoload 'org-table-to-lisp "org-table" "\ +Convert the table at point to a Lisp structure. +The structure will be a list. Each item is either the symbol `hline' +for a horizontal separator line, or a list of field values as strings. +The table is taken from the parameter TXT, or from the buffer at point. + +\(fn &optional TXT)" nil nil) + +(autoload 'orgtbl-to-generic "org-table" "\ +Convert the orgtbl-mode TABLE to some other format. + +This generic routine can be used for many standard cases. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that +line. PARAMS is a property list of parameters that can +influence the conversion. + +Valid parameters are: + +:backend, :raw + + Export back-end used as a basis to transcode elements of the + table, when no specific parameter applies to it. It is also + used to translate cells contents. You can prevent this by + setting :raw property to a non-nil value. + +:splice + + When non-nil, only convert rows, not the table itself. This is + equivalent to setting to the empty string both :tstart + and :tend, which see. + +:skip + + When set to an integer N, skip the first N lines of the table. + Horizontal separation lines do count for this parameter! + +:skipcols + + List of columns that should be skipped. If the table has + a column with calculation marks, that column is automatically + discarded beforehand. + +:hline + + String to be inserted on horizontal separation lines. May be + nil to ignore these lines altogether. + +:sep + + Separator between two fields, as a string. + +Each in the following group may be either a string or a function +of no arguments returning a string: + +:tstart, :tend + + Strings to start and end the table. Ignored when :splice is t. + +:lstart, :lend + + Strings to start and end a new table line. + +:llstart, :llend + + Strings to start and end the last table line. Default, + respectively, to :lstart and :lend. + +Each in the following group may be a string or a function of one +argument (either the cells in the current row, as a list of +strings, or the current cell) returning a string: + +:lfmt + + Format string for an entire row, with enough %s to capture all + fields. When non-nil, :lstart, :lend, and :sep are ignored. + +:llfmt + + Format for the entire last line, defaults to :lfmt. + +:fmt + + A format to be used to wrap the field, should contain %s for + the original field value. For example, to wrap everything in + dollars, you could use :fmt \"$%s$\". This may also be + a property list with column numbers and format strings, or + functions, e.g., + + (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c)))) + +:hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt + + Same as above, specific for the header lines in the table. + All lines before the first hline are treated as header. If + any of these is not present, the data line value is used. + +This may be either a string or a function of two arguments: + +:efmt + + Use this format to print numbers with exponential. The format + should have %s twice for inserting mantissa and exponent, for + example \"%s\\\\times10^{%s}\". This may also be a property + list with column numbers and format strings or functions. + :fmt will still be applied after :efmt. + +\(fn TABLE PARAMS)" nil nil) + +(autoload 'orgtbl-to-tsv "org-table" "\ +Convert the orgtbl-mode table to TAB separated material. + +\(fn TABLE PARAMS)" nil nil) + +(autoload 'orgtbl-to-csv "org-table" "\ +Convert the orgtbl-mode table to CSV material. +This does take care of the proper quoting of fields with comma or quotes. + +\(fn TABLE PARAMS)" nil nil) + +(autoload 'orgtbl-to-latex "org-table" "\ +Convert the orgtbl-mode TABLE to LaTeX. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported. It is also possible to use the following ones: + +:booktabs + + When non-nil, use formal \"booktabs\" style. + +:environment + + Specify environment to use, as a string. If you use + \"longtable\", you may also want to specify :language property, + as a string, to get proper continuation strings. + +\(fn TABLE PARAMS)" nil nil) + +(autoload 'orgtbl-to-html "org-table" "\ +Convert the orgtbl-mode TABLE to HTML. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported. It is also possible to use the following one: + +:attributes + + Attributes and values, as a plist, which will be used in + <table> tag. + +\(fn TABLE PARAMS)" nil nil) + +(autoload 'orgtbl-to-texinfo "org-table" "\ +Convert the orgtbl-mode TABLE to Texinfo. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported. It is also possible to use the following one: + +:columns + + Column widths, as a string. When providing column fractions, + \"@columnfractions\" command can be omitted. + +\(fn TABLE PARAMS)" nil nil) + +(autoload 'orgtbl-to-orgtbl "org-table" "\ +Convert the orgtbl-mode TABLE into another orgtbl-mode table. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported. + +Useful when slicing one table into many. The :hline, :sep, +:lstart, and :lend provide orgtbl framing. :tstart and :tend can +be set to provide ORGTBL directives for the generated table. + +\(fn TABLE PARAMS)" nil nil) + +(autoload 'orgtbl-ascii-plot "org-table" "\ +Draw an ASCII bar plot in a column. + +With cursor in a column containing numerical values, this function +will draw a plot in a new column. + +ASK, if given, is a numeric prefix to override the default 12 +characters width of the plot. ASK may also be the `\\[universal-argument]' prefix, +which will prompt for the width. + +\(fn &optional ASK)" t nil) + +;;;*** + +;;;### (autoloads nil "org-timer" "org-timer.el" "df503e638f325920ee58c88d4d825ad2") +;;; Generated autoloads from org-timer.el + +(autoload 'org-timer-start "org-timer" "\ +Set the starting time for the relative timer to now. +When called with prefix argument OFFSET, prompt the user for an offset time, +with the default taken from a timer stamp at point, if any. +If OFFSET is a string or an integer, it is directly taken to be the offset +without user interaction. +When called with a double prefix arg, all timer strings in the active +region will be shifted by a specific amount. You will be prompted for +the amount, with the default to make the first timer string in +the region 0:00:00. + +\(fn &optional OFFSET)" t nil) + +(autoload 'org-timer "org-timer" "\ +Insert a H:MM:SS string from the timer into the buffer. +The first time this command is used, the timer is started. + +When used with a `\\[universal-argument]' prefix, force restarting the timer. + +When used with a `\\[universal-argument] \\[universal-argument]' prefix, change all the timer strings +in the region by a fixed amount. This can be used to re-calibrate +a timer that was not started at the correct moment. + +If NO-INSERT is non-nil, return the string instead of inserting +it in the buffer. + +\(fn &optional RESTART NO-INSERT)" t nil) + +(autoload 'org-timer-change-times-in-region "org-timer" "\ +Change all h:mm:ss time in region by a DELTA. + +\(fn BEG END DELTA)" t nil) + +(autoload 'org-timer-item "org-timer" "\ +Insert a description-type item with the current timer value. + +\(fn &optional ARG)" t nil) + +(autoload 'org-timer-set-timer "org-timer" "\ +Prompt for a duration in minutes or hh:mm:ss and set a timer. + +If `org-timer-default-timer' is not \"0\", suggest this value as +the default duration for the timer. If a timer is already set, +prompt the user if she wants to replace it. + +Called with a numeric prefix argument, use this numeric value as +the duration of the timer in minutes. + +Called with a `C-u' prefix arguments, use `org-timer-default-timer' +without prompting the user for a duration. + +With two `C-u' prefix arguments, use `org-timer-default-timer' +without prompting the user for a duration and automatically +replace any running timer. + +By default, the timer duration will be set to the number of +minutes in the Effort property, if any. You can ignore this by +using three `C-u' prefix arguments. + +\(fn &optional OPT)" t nil) + +;;;*** + +;;;### (autoloads nil "org-version" "org-version.el" (23427 16140 +;;;;;; 563457 533000)) +;;; Generated autoloads from org-version.el + +(autoload 'org-release "org-version" "\ +The release version of Org. +Inserted by installing Org mode or when a release is made. + +\(fn)" nil nil) + +(autoload 'org-git-version "org-version" "\ +The Git version of Org mode. +Inserted by installing Org or when a release is made. + +\(fn)" nil nil) + +(defvar org-odt-data-dir "/usr/share/emacs/etc/org" "\ +The location of ODT styles.") + +;;;*** + +;;;### (autoloads nil "org" "org.el" (23427 16131 247531 494000)) +;;; Generated autoloads from org.el + +(autoload 'org-babel-do-load-languages "org" "\ +Load the languages defined in `org-babel-load-languages'. + +\(fn SYM VALUE)" nil nil) + +(autoload 'org-babel-load-file "org" "\ +Load Emacs Lisp source code blocks in the Org FILE. +This function exports the source code using `org-babel-tangle' +and then loads the resulting file using `load-file'. With prefix +arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp +file to byte-code before it is loaded. + +\(fn FILE &optional COMPILE)" t nil) + +(autoload 'org-version "org" "\ +Show the Org version. +Interactively, or when MESSAGE is non-nil, show it in echo area. +With prefix argument, or when HERE is non-nil, insert it at point. +In non-interactive uses, a reduced version string is output unless +FULL is given. + +\(fn &optional HERE FULL MESSAGE)" t nil) + +(autoload 'turn-on-orgtbl "org" "\ +Unconditionally turn on `orgtbl-mode'. + +\(fn)" nil nil) + +(autoload 'org-clock-persistence-insinuate "org" "\ +Set up hooks for clock persistence. + +\(fn)" nil nil) + +(autoload 'org-mode "org" "\ +Outline-based notes management and organizer, alias +\"Carsten's outline-mode for keeping track of everything.\" + +Org mode develops organizational tasks around a NOTES file which +contains information about projects as plain text. Org mode is +implemented on top of Outline mode, which is ideal to keep the content +of large files well structured. It supports ToDo items, deadlines and +time stamps, which magically appear in the diary listing of the Emacs +calendar. Tables are easily created with a built-in table editor. +Plain text URL-like links connect to websites, emails (VM), Usenet +messages (Gnus), BBDB entries, and any files related to the project. +For printing and sharing of notes, an Org file (or a part of it) +can be exported as a structured ASCII or HTML file. + +The following commands are available: + +\\{org-mode-map} + +\(fn)" t nil) + +(autoload 'org-cycle "org" "\ +TAB-action and visibility cycling for Org mode. + +This is the command invoked in Org mode by the `TAB' key. Its main +purpose is outline visibility cycling, but it also invokes other actions +in special contexts. + +When this function is called with a `\\[universal-argument]' prefix, rotate the entire +buffer through 3 states (global cycling) + 1. OVERVIEW: Show only top-level headlines. + 2. CONTENTS: Show all headlines of all levels, but no body text. + 3. SHOW ALL: Show everything. + +With a `\\[universal-argument] \\[universal-argument]' prefix argument, switch to the startup visibility, +determined by the variable `org-startup-folded', and by any VISIBILITY +properties in the buffer. + +With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' prefix argument, show the entire buffer, including +any drawers. + +When inside a table, re-align the table and move to the next field. + +When point is at the beginning of a headline, rotate the subtree started +by this line through 3 different states (local cycling) + 1. FOLDED: Only the main headline is shown. + 2. CHILDREN: The main headline and the direct children are shown. + From this state, you can move to one of the children + and zoom in further. + 3. SUBTREE: Show the entire subtree, including body text. +If there is no subtree, switch directly from CHILDREN to FOLDED. + +When point is at the beginning of an empty headline and the variable +`org-cycle-level-after-item/entry-creation' is set, cycle the level +of the headline by demoting and promoting it to likely levels. This +speeds up creation document structure by pressing `TAB' once or several +times right after creating a new headline. + +When there is a numeric prefix, go up to a heading with level ARG, do +a `show-subtree' and return to the previous cursor position. If ARG +is negative, go up that many levels. + +When point is not at the beginning of a headline, execute the global +binding for `TAB', which is re-indenting the line. See the option +`org-cycle-emulate-tab' for details. + +As a special case, if point is at the beginning of the buffer and there is +no headline in line 1, this function will act as if called with prefix arg +\(`\\[universal-argument] TAB', same as `S-TAB') also when called without prefix arg, but only +if the variable `org-cycle-global-at-bob' is t. + +\(fn &optional ARG)" t nil) + +(autoload 'org-global-cycle "org" "\ +Cycle the global visibility. For details see `org-cycle'. +With `\\[universal-argument]' prefix ARG, switch to startup visibility. +With a numeric prefix, show all headlines up to that level. + +\(fn &optional ARG)" t nil) +(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp) + +(autoload 'orgstruct-mode "org" "\ +Toggle the minor mode `orgstruct-mode'. +This mode is for using Org mode structure commands in other +modes. The following keys behave as if Org mode were active, if +the cursor is on a headline, or on a plain list item (both as +defined by Org mode). + +\(fn &optional ARG)" t nil) + +(autoload 'turn-on-orgstruct "org" "\ +Unconditionally turn on `orgstruct-mode'. + +\(fn)" nil nil) + +(autoload 'turn-on-orgstruct++ "org" "\ +Unconditionally turn on `orgstruct++-mode'. + +\(fn)" nil nil) + +(autoload 'org-run-like-in-org-mode "org" "\ +Run a command, pretending that the current buffer is in Org mode. +This will temporarily bind local variables that are typically bound in +Org mode to the values they have in Org mode, and then interactively +call CMD. + +\(fn CMD)" nil nil) + +(autoload 'org-store-link "org" "\ +Store an org-link to the current location. +\\<org-mode-map> +This link is added to `org-stored-links' and can later be inserted +into an Org buffer with `org-insert-link' (`\\[org-insert-link]'). + +For some link types, a `\\[universal-argument]' prefix ARG is interpreted. A single +`\\[universal-argument]' negates `org-context-in-file-links' for file links or +`org-gnus-prefer-web-links' for links to Usenet articles. + +A `\\[universal-argument] \\[universal-argument]' prefix ARG forces skipping storing functions that are not +part of Org core. + +A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' prefix ARG forces storing a link for each line in the +active region. + +\(fn ARG)" t nil) + +(autoload 'org-insert-link-global "org" "\ +Insert a link like Org mode does. +This command can be called in any mode to insert a link in Org syntax. + +\(fn)" t nil) + +(autoload 'org-open-at-point-global "org" "\ +Follow a link or time-stamp like Org mode does. +This command can be called in any mode to follow an external link +or a time-stamp that has Org mode syntax. Its behavior is +undefined when called on internal links (e.g., fuzzy links). +Raise an error when there is nothing to follow. + +\(fn)" t nil) + +(autoload 'org-open-link-from-string "org" "\ +Open a link in the string S, as if it was in Org mode. + +\(fn S &optional ARG REFERENCE-BUFFER)" t nil) + +(autoload 'org-switchb "org" "\ +Switch between Org buffers. + +With `\\[universal-argument]' prefix, restrict available buffers to files. + +With `\\[universal-argument] \\[universal-argument]' prefix, restrict available buffers to agenda files. + +\(fn &optional ARG)" t nil) + +(autoload 'org-cycle-agenda-files "org" "\ +Cycle through the files in `org-agenda-files'. +If the current buffer visits an agenda file, find the next one in the list. +If the current buffer does not, find the first agenda file. + +\(fn)" t nil) + +(autoload 'org-submit-bug-report "org" "\ +Submit a bug report on Org via mail. + +Don't hesitate to report any problems or inaccurate documentation. + +If you don't have setup sending mail from (X)Emacs, please copy the +output buffer into your mail program, as it gives us important +information about your Org version and configuration. + +\(fn)" t nil) + +(autoload 'org-reload "org" "\ +Reload all Org Lisp files. +With prefix arg UNCOMPILED, load the uncompiled versions. + +\(fn &optional UNCOMPILED)" t nil) + +(autoload 'org-customize "org" "\ +Call the customize function with org as argument. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "ox" "ox.el" "72daa607ccab31f421d02552b327a7c8") +;;; Generated autoloads from ox.el + +(autoload 'org-export-get-backend "ox" "\ +Return export back-end named after NAME. +NAME is a symbol. Return nil if no such back-end is found. + +\(fn NAME)" nil nil) + +(autoload 'org-export-get-environment "ox" "\ +Collect export options from the current buffer. + +Optional argument BACKEND is an export back-end, as returned by +`org-export-create-backend'. + +When optional argument SUBTREEP is non-nil, assume the export is +done against the current sub-tree. + +Third optional argument EXT-PLIST is a property list with +external parameters overriding Org default settings, but still +inferior to file-local settings. + +\(fn &optional BACKEND SUBTREEP EXT-PLIST)" nil nil) + +(autoload 'org-export-as "ox" "\ +Transcode current Org buffer into BACKEND code. + +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. + +If narrowing is active in the current buffer, only transcode its +narrowed part. + +If a region is active, transcode that region. + +When optional argument SUBTREEP is non-nil, transcode the +sub-tree at point, extracting information from the headline +properties first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only return body +code, without surrounding template. + +Optional argument EXT-PLIST, when provided, is a property list +with external parameters overriding Org default settings, but +still inferior to file-local settings. + +Return code as a string. + +\(fn BACKEND &optional SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" nil nil) + +(autoload 'org-export-string-as "ox" "\ +Transcode STRING into BACKEND code. + +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. + +When optional argument BODY-ONLY is non-nil, only return body +code, without preamble nor postamble. + +Optional argument EXT-PLIST, when provided, is a property list +with external parameters overriding Org default settings, but +still inferior to file-local settings. + +Return code as a string. + +\(fn STRING BACKEND &optional BODY-ONLY EXT-PLIST)" nil nil) + +(autoload 'org-export-replace-region-by "ox" "\ +Replace the active region by its export to BACKEND. +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. + +\(fn BACKEND)" nil nil) + +(autoload 'org-export-insert-default-template "ox" "\ +Insert all export keywords with default values at beginning of line. + +BACKEND is a symbol referring to the name of a registered export +back-end, for which specific export options should be added to +the template, or `default' for default template. When it is nil, +the user will be prompted for a category. + +If SUBTREEP is non-nil, export configuration will be set up +locally for the subtree through node properties. + +\(fn &optional BACKEND SUBTREEP)" t nil) + +(autoload 'org-export-to-buffer "ox" "\ +Call `org-export-as' with output to a specified buffer. + +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. + +BUFFER is the name of the output buffer. If it already exists, +it will be erased first, otherwise, it will be created. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should then be accessible +through the `org-export-stack' interface. When ASYNC is nil, the +buffer is displayed if `org-export-show-temporary-export-buffer' +is non-nil. + +Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and +EXT-PLIST are similar to those used in `org-export-as', which +see. + +Optional argument POST-PROCESS is a function which should accept +no argument. It is always called within the current process, +from BUFFER, with point at its beginning. Export back-ends can +use it to set a major mode there, e.g, + + (defun org-latex-export-as-latex + (&optional async subtreep visible-only body-only ext-plist) + (interactive) + (org-export-to-buffer \\='latex \"*Org LATEX Export*\" + async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode)))) + +This function returns BUFFER. + +\(fn BACKEND BUFFER &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST POST-PROCESS)" nil nil) + +(function-put 'org-export-to-buffer 'lisp-indent-function '2) + +(autoload 'org-export-to-file "ox" "\ +Call `org-export-as' with output to a specified file. + +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. FILE is the name of the output file, as +a string. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer will then be accessible +through the `org-export-stack' interface. + +Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and +EXT-PLIST are similar to those used in `org-export-as', which +see. + +Optional argument POST-PROCESS is called with FILE as its +argument and happens asynchronously when ASYNC is non-nil. It +has to return a file name, or nil. Export back-ends can use this +to send the output file through additional processing, e.g, + + (defun org-latex-export-to-latex + (&optional async subtreep visible-only body-only ext-plist) + (interactive) + (let ((outfile (org-export-output-file-name \".tex\" subtreep))) + (org-export-to-file \\='latex outfile + async subtreep visible-only body-only ext-plist + (lambda (file) (org-latex-compile file))) + +The function returns either a file name returned by POST-PROCESS, +or FILE. + +\(fn BACKEND FILE &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST POST-PROCESS)" nil nil) + +(function-put 'org-export-to-file 'lisp-indent-function '2) + +(autoload 'org-export-dispatch "ox" "\ +Export dispatcher for Org mode. + +It provides an access to common export related tasks in a buffer. +Its interface comes in two flavors: standard and expert. + +While both share the same set of bindings, only the former +displays the valid keys associations in a dedicated buffer. +Scrolling (resp. line-wise motion) in this buffer is done with +SPC and DEL (resp. C-n and C-p) keys. + +Set variable `org-export-dispatch-use-expert-ui' to switch to one +flavor or the other. + +When ARG is `\\[universal-argument]', repeat the last export action, with the same +set of options used back then, on the current buffer. + +When ARG is `\\[universal-argument] \\[universal-argument]', display the asynchronous export stack. + +\(fn &optional ARG)" t nil) + +;;;*** + +;;;### (autoloads nil "ox-ascii" "ox-ascii.el" "4a772695edb7dedf932be8995d9c407a") +;;; Generated autoloads from ox-ascii.el + +(autoload 'org-ascii-export-as-ascii "ox-ascii" "\ +Export current buffer to a text buffer. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should be accessible +through the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, strip title and +table of contents from output. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Export is done in a buffer named \"*Org ASCII Export*\", which +will be displayed when `org-export-show-temporary-export-buffer' +is non-nil. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-ascii-export-to-ascii "ox-ascii" "\ +Export current buffer to a text file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, strip title and +table of contents from output. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return output file's name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-ascii-publish-to-ascii "ox-ascii" "\ +Publish an Org file to ASCII. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +(autoload 'org-ascii-publish-to-latin1 "ox-ascii" "\ +Publish an Org file to Latin-1. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +(autoload 'org-ascii-publish-to-utf8 "ox-ascii" "\ +Publish an org file to UTF-8. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +;;;*** + +;;;### (autoloads nil "ox-beamer" "ox-beamer.el" "d99129f12ce947bce4b46176eeaf2a40") +;;; Generated autoloads from ox-beamer.el + +(autoload 'org-beamer-mode "ox-beamer" "\ +Support for editing Beamer oriented Org mode files. + +\(fn &optional ARG)" t nil) + +(autoload 'org-beamer-export-as-latex "ox-beamer" "\ +Export current buffer as a Beamer buffer. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should be accessible +through the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Export is done in a buffer named \"*Org BEAMER Export*\", which +will be displayed when `org-export-show-temporary-export-buffer' +is non-nil. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-beamer-export-to-latex "ox-beamer" "\ +Export current buffer as a Beamer presentation (tex). + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return output file's name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-beamer-export-to-pdf "ox-beamer" "\ +Export current buffer as a Beamer presentation (PDF). + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return PDF file's name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-beamer-select-environment "ox-beamer" "\ +Select the environment to be used by beamer for this entry. +While this uses (for convenience) a tag selection interface, the +result of this command will be that the BEAMER_env *property* of +the entry is set. + +In addition to this, the command will also set a tag as a visual +aid, but the tag does not have any semantic meaning. + +\(fn)" t nil) + +(autoload 'org-beamer-publish-to-latex "ox-beamer" "\ +Publish an Org file to a Beamer presentation (LaTeX). + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +(autoload 'org-beamer-publish-to-pdf "ox-beamer" "\ +Publish an Org file to a Beamer presentation (PDF, via LaTeX). + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +;;;*** + +;;;### (autoloads nil "ox-html" "ox-html.el" "b2b303489000b91b8507671209cc2924") +;;; Generated autoloads from ox-html.el + +(put 'org-html-head-include-default-style 'safe-local-variable 'booleanp) + +(put 'org-html-head 'safe-local-variable 'stringp) + +(put 'org-html-head-extra 'safe-local-variable 'stringp) + +(autoload 'org-html-htmlize-generate-css "ox-html" "\ +Create the CSS for all font definitions in the current Emacs session. +Use this to create face definitions in your CSS style file that can then +be used by code snippets transformed by htmlize. +This command just produces a buffer that contains class definitions for all +faces used in the current Emacs session. You can copy and paste the ones you +need into your CSS file. + +If you then set `org-html-htmlize-output-type' to `css', calls +to the function `org-html-htmlize-region-for-paste' will +produce code that uses these same face definitions. + +\(fn)" t nil) + +(autoload 'org-html-export-as-html "ox-html" "\ +Export current buffer to an HTML buffer. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should be accessible +through the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"<body>\" and \"</body>\" tags. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Export is done in a buffer named \"*Org HTML Export*\", which +will be displayed when `org-export-show-temporary-export-buffer' +is non-nil. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-html-convert-region-to-html "ox-html" "\ +Assume the current region has Org syntax, and convert it to HTML. +This can be used in any buffer. For example, you can write an +itemized list in Org syntax in an HTML buffer and use this command +to convert it. + +\(fn)" t nil) + +(autoload 'org-html-export-to-html "ox-html" "\ +Export current buffer to a HTML file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"<body>\" and \"</body>\" tags. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return output file's name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-html-publish-to-html "ox-html" "\ +Publish an org file to HTML. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +;;;*** + +;;;### (autoloads nil "ox-icalendar" "ox-icalendar.el" "9d179af5b2a082e77567ef226b3b132b") +;;; Generated autoloads from ox-icalendar.el + +(autoload 'org-icalendar-export-to-ics "ox-icalendar" "\ +Export current buffer to an iCalendar file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\". + +Return ICS file name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY)" t nil) + +(autoload 'org-icalendar-export-agenda-files "ox-icalendar" "\ +Export all agenda files to iCalendar files. +When optional argument ASYNC is non-nil, export happens in an +external process. + +\(fn &optional ASYNC)" t nil) + +(autoload 'org-icalendar-combine-agenda-files "ox-icalendar" "\ +Combine all agenda files into a single iCalendar file. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +The file is stored under the name chosen in +`org-icalendar-combined-agenda-file'. + +\(fn &optional ASYNC)" t nil) + +;;;*** + +;;;### (autoloads nil "ox-latex" "ox-latex.el" "62b465cef63a59a8fa6b5db9fc12558c") +;;; Generated autoloads from ox-latex.el + +(autoload 'org-latex-make-preamble "ox-latex" "\ +Return a formatted LaTeX preamble. +INFO is a plist used as a communication channel. Optional +argument TEMPLATE, when non-nil, is the header template string, +as expected by `org-splice-latex-header'. When SNIPPET? is +non-nil, only includes packages relevant to image generation, as +specified in `org-latex-default-packages-alist' or +`org-latex-packages-alist'. + +\(fn INFO &optional TEMPLATE SNIPPET\\=\\?)" nil nil) + +(autoload 'org-latex-export-as-latex "ox-latex" "\ +Export current buffer as a LaTeX buffer. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should be accessible +through the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Export is done in a buffer named \"*Org LATEX Export*\", which +will be displayed when `org-export-show-temporary-export-buffer' +is non-nil. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-latex-convert-region-to-latex "ox-latex" "\ +Assume the current region has Org syntax, and convert it to LaTeX. +This can be used in any buffer. For example, you can write an +itemized list in Org syntax in an LaTeX buffer and use this +command to convert it. + +\(fn)" t nil) + +(autoload 'org-latex-export-to-latex "ox-latex" "\ +Export current buffer to a LaTeX file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-latex-export-to-pdf "ox-latex" "\ +Export current buffer to LaTeX then process through to PDF. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return PDF file's name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-latex-publish-to-latex "ox-latex" "\ +Publish an Org file to LaTeX. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +(autoload 'org-latex-publish-to-pdf "ox-latex" "\ +Publish an Org file to PDF (via LaTeX). + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +;;;*** + +;;;### (autoloads nil "ox-md" "ox-md.el" "68551e4d17f879632900749c3d173d5d") +;;; Generated autoloads from ox-md.el + +(autoload 'org-md-export-as-markdown "ox-md" "\ +Export current buffer to a Markdown buffer. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should be accessible +through the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +Export is done in a buffer named \"*Org MD Export*\", which will +be displayed when `org-export-show-temporary-export-buffer' is +non-nil. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY)" t nil) + +(autoload 'org-md-convert-region-to-md "ox-md" "\ +Assume the current region has Org syntax, and convert it to Markdown. +This can be used in any buffer. For example, you can write an +itemized list in Org syntax in a Markdown buffer and use +this command to convert it. + +\(fn)" t nil) + +(autoload 'org-md-export-to-markdown "ox-md" "\ +Export current buffer to a Markdown file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +Return output file's name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY)" t nil) + +(autoload 'org-md-publish-to-md "ox-md" "\ +Publish an org file to Markdown. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +;;;*** + +;;;### (autoloads nil "ox-odt" "ox-odt.el" "07f96439ecf6e83d08d1acc3b3a85023") +;;; Generated autoloads from ox-odt.el + +(put 'org-odt-preferred-output-format 'safe-local-variable 'stringp) + +(autoload 'org-odt-export-as-odf "ox-odt" "\ +Export LATEX-FRAG as OpenDocument formula file ODF-FILE. +Use `org-create-math-formula' to convert LATEX-FRAG first to +MathML. When invoked as an interactive command, use +`org-latex-regexps' to infer LATEX-FRAG from currently active +region. If no LaTeX fragments are found, prompt for it. Push +MathML source to kill ring depending on the value of +`org-export-copy-to-kill-ring'. + +\(fn LATEX-FRAG &optional ODF-FILE)" t nil) + +(autoload 'org-odt-export-as-odf-and-open "ox-odt" "\ +Export LaTeX fragment as OpenDocument formula and immediately open it. +Use `org-odt-export-as-odf' to read LaTeX fragment and OpenDocument +formula file. + +\(fn)" t nil) + +(autoload 'org-odt-export-to-odt "ox-odt" "\ +Export current buffer to a ODT file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return output file's name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY EXT-PLIST)" t nil) + +(autoload 'org-odt-convert "ox-odt" "\ +Convert IN-FILE to format OUT-FMT using a command line converter. +IN-FILE is the file to be converted. If unspecified, it defaults +to variable `buffer-file-name'. OUT-FMT is the desired output +format. Use `org-odt-convert-process' as the converter. If OPEN +is non-nil then the newly converted file is opened using +`org-open-file'. + +\(fn &optional IN-FILE OUT-FMT OPEN)" t nil) + +;;;*** + +;;;### (autoloads nil "ox-org" "ox-org.el" "49bbdfb54542fbea3d9e2c956bb0d56b") +;;; Generated autoloads from ox-org.el + +(autoload 'org-org-export-as-org "ox-org" "\ +Export current buffer to an Org buffer. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should be accessible +through the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, strip document +keywords from output. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Export is done in a buffer named \"*Org ORG Export*\", which will +be displayed when `org-export-show-temporary-export-buffer' is +non-nil. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-org-export-to-org "ox-org" "\ +Export current buffer to an org file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, strip document +keywords from output. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return output file name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-org-publish-to-org "ox-org" "\ +Publish an org file to org. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +;;;*** + +;;;### (autoloads nil "ox-publish" "ox-publish.el" "5920e1273f48b9bead560af7f30c3537") +;;; Generated autoloads from ox-publish.el + +(defalias 'org-publish-project 'org-publish) + +(autoload 'org-publish "ox-publish" "\ +Publish PROJECT. + +PROJECT is either a project name, as a string, or a project +alist (see `org-publish-project-alist' variable). + +When optional argument FORCE is non-nil, force publishing all +files in PROJECT. With a non-nil optional argument ASYNC, +publishing will be done asynchronously, in another process. + +\(fn PROJECT &optional FORCE ASYNC)" t nil) + +(autoload 'org-publish-all "ox-publish" "\ +Publish all projects. +With prefix argument FORCE, remove all files in the timestamp +directory and force publishing all projects. With a non-nil +optional argument ASYNC, publishing will be done asynchronously, +in another process. + +\(fn &optional FORCE ASYNC)" t nil) + +(autoload 'org-publish-current-file "ox-publish" "\ +Publish the current file. +With prefix argument FORCE, force publish the file. When +optional argument ASYNC is non-nil, publishing will be done +asynchronously, in another process. + +\(fn &optional FORCE ASYNC)" t nil) + +(autoload 'org-publish-current-project "ox-publish" "\ +Publish the project associated with the current file. +With a prefix argument, force publishing of all files in +the project. + +\(fn &optional FORCE ASYNC)" t nil) + +;;;*** + +;;;### (autoloads nil "ox-texinfo" "ox-texinfo.el" "fa6ddaec0cc36a7edd90b629e42b6fdd") +;;; Generated autoloads from ox-texinfo.el + +(autoload 'org-texinfo-export-to-texinfo "ox-texinfo" "\ +Export current buffer to a Texinfo file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return output file's name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-texinfo-export-to-info "ox-texinfo" "\ +Export current buffer to Texinfo then process through to INFO. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +When optional argument PUB-DIR is set, use it as the publishing +directory. + +Return INFO file's name. + +\(fn &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" t nil) + +(autoload 'org-texinfo-publish-to-texinfo "ox-texinfo" "\ +Publish an org file to Texinfo. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name. + +\(fn PLIST FILENAME PUB-DIR)" nil nil) + +(autoload 'org-texinfo-convert-region-to-texinfo "ox-texinfo" "\ +Assume the current region has Org syntax, and convert it to Texinfo. +This can be used in any buffer. For example, you can write an +itemized list in Org syntax in an Texinfo buffer and use this +command to convert it. + +\(fn)" t nil) + +;;;*** + +;;;### (autoloads nil "ox" "ox.el" (23195 45027 425189 671000)) +;;; Generated autoloads from ox.el + +(autoload 'org-export-get-backend "ox" "\ +Return export back-end named after NAME. +NAME is a symbol. Return nil if no such back-end is found. + +\(fn NAME)" nil nil) + +(autoload 'org-export-get-environment "ox" "\ +Collect export options from the current buffer. + +Optional argument BACKEND is an export back-end, as returned by +`org-export-create-backend'. + +When optional argument SUBTREEP is non-nil, assume the export is +done against the current sub-tree. + +Third optional argument EXT-PLIST is a property list with +external parameters overriding Org default settings, but still +inferior to file-local settings. + +\(fn &optional BACKEND SUBTREEP EXT-PLIST)" nil nil) + +(autoload 'org-export-as "ox" "\ +Transcode current Org buffer into BACKEND code. + +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. + +If narrowing is active in the current buffer, only transcode its +narrowed part. + +If a region is active, transcode that region. + +When optional argument SUBTREEP is non-nil, transcode the +sub-tree at point, extracting information from the headline +properties first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only return body +code, without surrounding template. + +Optional argument EXT-PLIST, when provided, is a property list +with external parameters overriding Org default settings, but +still inferior to file-local settings. + +Return code as a string. + +\(fn BACKEND &optional SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST)" nil nil) + +(autoload 'org-export-string-as "ox" "\ +Transcode STRING into BACKEND code. + +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. + +When optional argument BODY-ONLY is non-nil, only return body +code, without preamble nor postamble. + +Optional argument EXT-PLIST, when provided, is a property list +with external parameters overriding Org default settings, but +still inferior to file-local settings. + +Return code as a string. + +\(fn STRING BACKEND &optional BODY-ONLY EXT-PLIST)" nil nil) + +(autoload 'org-export-replace-region-by "ox" "\ +Replace the active region by its export to BACKEND. +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. + +\(fn BACKEND)" nil nil) + +(autoload 'org-export-insert-default-template "ox" "\ +Insert all export keywords with default values at beginning of line. + +BACKEND is a symbol referring to the name of a registered export +back-end, for which specific export options should be added to +the template, or `default' for default template. When it is nil, +the user will be prompted for a category. + +If SUBTREEP is non-nil, export configuration will be set up +locally for the subtree through node properties. + +\(fn &optional BACKEND SUBTREEP)" t nil) + +(autoload 'org-export-to-buffer "ox" "\ +Call `org-export-as' with output to a specified buffer. + +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. + +BUFFER is the name of the output buffer. If it already exists, +it will be erased first, otherwise, it will be created. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should then be accessible +through the `org-export-stack' interface. When ASYNC is nil, the +buffer is displayed if `org-export-show-temporary-export-buffer' +is non-nil. + +Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and +EXT-PLIST are similar to those used in `org-export-as', which +see. + +Optional argument POST-PROCESS is a function which should accept +no argument. It is always called within the current process, +from BUFFER, with point at its beginning. Export back-ends can +use it to set a major mode there, e.g, + + (defun org-latex-export-as-latex + (&optional async subtreep visible-only body-only ext-plist) + (interactive) + (org-export-to-buffer \\='latex \"*Org LATEX Export*\" + async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode)))) + +This function returns BUFFER. + +\(fn BACKEND BUFFER &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST POST-PROCESS)" nil nil) + +(function-put 'org-export-to-buffer 'lisp-indent-function '2) + +(autoload 'org-export-to-file "ox" "\ +Call `org-export-as' with output to a specified file. + +BACKEND is either an export back-end, as returned by, e.g., +`org-export-create-backend', or a symbol referring to +a registered back-end. FILE is the name of the output file, as +a string. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer will then be accessible +through the `org-export-stack' interface. + +Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and +EXT-PLIST are similar to those used in `org-export-as', which +see. + +Optional argument POST-PROCESS is called with FILE as its +argument and happens asynchronously when ASYNC is non-nil. It +has to return a file name, or nil. Export back-ends can use this +to send the output file through additional processing, e.g, + + (defun org-latex-export-to-latex + (&optional async subtreep visible-only body-only ext-plist) + (interactive) + (let ((outfile (org-export-output-file-name \".tex\" subtreep))) + (org-export-to-file \\='latex outfile + async subtreep visible-only body-only ext-plist + (lambda (file) (org-latex-compile file))) + +The function returns either a file name returned by POST-PROCESS, +or FILE. + +\(fn BACKEND FILE &optional ASYNC SUBTREEP VISIBLE-ONLY BODY-ONLY EXT-PLIST POST-PROCESS)" nil nil) + +(function-put 'org-export-to-file 'lisp-indent-function '2) + +(autoload 'org-export-dispatch "ox" "\ +Export dispatcher for Org mode. + +It provides an access to common export related tasks in a buffer. +Its interface comes in two flavors: standard and expert. + +While both share the same set of bindings, only the former +displays the valid keys associations in a dedicated buffer. +Scrolling (resp. line-wise motion) in this buffer is done with +SPC and DEL (resp. C-n and C-p) keys. + +Set variable `org-export-dispatch-use-expert-ui' to switch to one +flavor or the other. + +When ARG is `\\[universal-argument]', repeat the last export action, with the same +set of options used back then, on the current buffer. + +When ARG is `\\[universal-argument] \\[universal-argument]', display the asynchronous export stack. + +\(fn &optional ARG)" t nil) + +;;;*** + +(provide 'org-loaddefs) + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; coding: utf-8 +;; End: +;;; org-loaddefs.el ends here diff --git a/elpa/org-9.1.14/org-macro.el b/elpa/org-9.1.14/org-macro.el new file mode 100644 index 00000000..1033db2a --- /dev/null +++ b/elpa/org-9.1.14/org-macro.el @@ -0,0 +1,355 @@ +;;; org-macro.el --- Macro Replacement Code for Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2013-2018 Free Software Foundation, Inc. + +;; Author: Nicolas Goaziou <n.goaziou@gmail.com> +;; Keywords: outlines, hypermedia, calendar, wp + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; Macros are expanded with `org-macro-replace-all', which relies +;; internally on `org-macro-expand'. + +;; Default templates for expansion are stored in the buffer-local +;; variable `org-macro-templates'. This variable is updated by +;; `org-macro-initialize-templates', which recursively calls +;; `org-macro--collect-macros' in order to read setup files. + +;; Argument in macros are separated with commas. Proper escaping rules +;; are implemented in `org-macro-escape-arguments' and arguments can +;; be extracted from a string with `org-macro-extract-arguments'. + +;; Along with macros defined through #+MACRO: keyword, default +;; templates include the following hard-coded macros: +;; {{{time(format-string)}}}, +;; {{{property(node-property)}}}, +;; {{{input-file}}}, +;; {{{modification-time(format-string)}}}, +;; {{{n(counter,action}}}. + +;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}}, +;; {{{email}}} and {{{title}}} macros. + +;;; Code: +(require 'cl-lib) +(require 'org-macs) +(require 'org-compat) + +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-context "org-element" (&optional element)) +(declare-function org-element-macro-parser "org-element" ()) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-type "org-element" (element)) +(declare-function org-file-contents "org" (file &optional noerror nocache)) +(declare-function org-file-url-p "org" (file)) +(declare-function org-in-commented-heading-p "org" (&optional no-inheritance)) +(declare-function org-mode "org" ()) +(declare-function org-trim "org" (s &optional keep-lead)) +(declare-function vc-backend "vc-hooks" (f)) +(declare-function vc-call "vc-hooks" (fun file &rest args) t) +(declare-function vc-exec-after "vc-dispatcher" (code)) + +;;; Variables + +(defvar-local org-macro-templates nil + "Alist containing all macro templates in current buffer. +Associations are in the shape of (NAME . TEMPLATE) where NAME +stands for macro's name and template for its replacement value, +both as strings. This is an internal variable. Do not set it +directly, use instead: + + #+MACRO: name template") + +;;; Functions + +(defun org-macro--collect-macros () + "Collect macro definitions in current buffer and setup files. +Return an alist containing all macro templates found." + (letrec ((collect-macros + (lambda (files templates) + ;; Return an alist of macro templates. FILES is a list + ;; of setup files names read so far, used to avoid + ;; circular dependencies. TEMPLATES is the alist + ;; collected so far. + (let ((case-fold-search t)) + (org-with-wide-buffer + (goto-char (point-min)) + (while (re-search-forward + "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t) + (let ((element (org-element-at-point))) + (when (eq (org-element-type element) 'keyword) + (let ((val (org-element-property :value element))) + (if (equal (org-element-property :key element) "MACRO") + ;; Install macro in TEMPLATES. + (when (string-match + "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val) + (let* ((name (match-string 1 val)) + (template (or (match-string 2 val) "")) + (old-cell (assoc name templates))) + (if old-cell (setcdr old-cell template) + (push (cons name template) templates)))) + ;; Enter setup file. + (let* ((uri (org-unbracket-string "\"" "\"" (org-trim val))) + (uri-is-url (org-file-url-p uri)) + (uri (if uri-is-url + uri + (expand-file-name uri)))) + ;; Avoid circular dependencies. + (unless (member uri files) + (with-temp-buffer + (unless uri-is-url + (setq default-directory + (file-name-directory uri))) + (org-mode) + (insert (org-file-contents uri 'noerror)) + (setq templates + (funcall collect-macros (cons uri files) + templates))))))))))) + templates)))) + (funcall collect-macros nil nil))) + +(defun org-macro-initialize-templates () + "Collect macro templates defined in current buffer. +Templates are stored in buffer-local variable +`org-macro-templates'. In addition to buffer-defined macros, the +function installs the following ones: \"property\", +\"time\". and, if the buffer is associated to a file, +\"input-file\" and \"modification-time\"." + (let* ((templates nil) + (update-templates + (lambda (cell) + (let ((old-template (assoc (car cell) templates))) + (if old-template (setcdr old-template (cdr cell)) + (push cell templates)))))) + ;; Install "property", "time" macros. + (mapc update-templates + (list (cons "property" + "(eval (save-excursion + (let ((l \"$2\")) + (when (org-string-nw-p l) + (condition-case _ + (let ((org-link-search-must-match-exact-headline t)) + (org-link-search l nil t)) + (error + (error \"Macro property failed: cannot find location %s\" + l))))) + (org-entry-get nil \"$1\" 'selective)))") + (cons "time" "(eval (format-time-string \"$1\"))"))) + ;; Install "input-file", "modification-time" macros. + (let ((visited-file (buffer-file-name (buffer-base-buffer)))) + (when (and visited-file (file-exists-p visited-file)) + (mapc update-templates + (list (cons "input-file" (file-name-nondirectory visited-file)) + (cons "modification-time" + (format "(eval (format-time-string \"$1\" (or (and (org-string-nw-p \"$2\") (org-macro--vc-modified-time %s)) '%s)))" + (prin1-to-string visited-file) + (prin1-to-string + (nth 5 (file-attributes visited-file))))))))) + ;; Initialize and install "n" macro. + (org-macro--counter-initialize) + (funcall update-templates + (cons "n" "(eval (org-macro--counter-increment \"$1\" \"$2\"))")) + (setq org-macro-templates (nconc (org-macro--collect-macros) templates)))) + +(defun org-macro-expand (macro templates) + "Return expanded MACRO, as a string. +MACRO is an object, obtained, for example, with +`org-element-context'. TEMPLATES is an alist of templates used +for expansion. See `org-macro-templates' for a buffer-local +default value. Return nil if no template was found." + (let ((template + ;; Macro names are case-insensitive. + (cdr (assoc-string (org-element-property :key macro) templates t)))) + (when template + (let ((value (replace-regexp-in-string + "\\$[0-9]+" + (lambda (arg) + (or (nth (1- (string-to-number (substring arg 1))) + (org-element-property :args macro)) + ;; No argument: remove place-holder. + "")) + template nil 'literal))) + ;; VALUE starts with "(eval": it is a s-exp, `eval' it. + (when (string-match "\\`(eval\\>" value) + (setq value (eval (read value)))) + ;; Return string. + (format "%s" (or value "")))))) + +(defun org-macro-replace-all (templates &optional finalize keywords) + "Replace all macros in current buffer by their expansion. + +TEMPLATES is an alist of templates used for expansion. See +`org-macro-templates' for a buffer-local default value. + +If optional arg FINALIZE is non-nil, raise an error if a macro is +found in the buffer with no definition in TEMPLATES. + +Optional argument KEYWORDS, when non-nil is a list of keywords, +as strings, where macro expansion is allowed." + (org-with-wide-buffer + (goto-char (point-min)) + (let ((properties-regexp (format "\\`EXPORT_%s\\+?\\'" + (regexp-opt keywords))) + record) + (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t) + (unless (save-match-data (org-in-commented-heading-p)) + (let* ((datum (save-match-data (org-element-context))) + (type (org-element-type datum)) + (macro + (cond + ((eq type 'macro) datum) + ;; In parsed keywords and associated node + ;; properties, force macro recognition. + ((or (and (eq type 'keyword) + (member (org-element-property :key datum) keywords)) + (and (eq type 'node-property) + (string-match-p properties-regexp + (org-element-property :key datum)))) + (save-excursion + (goto-char (match-beginning 0)) + (org-element-macro-parser)))))) + (when macro + (let* ((value (org-macro-expand macro templates)) + (begin (org-element-property :begin macro)) + (signature (list begin + macro + (org-element-property :args macro)))) + ;; Avoid circular dependencies by checking if the same + ;; macro with the same arguments is expanded at the + ;; same position twice. + (cond ((member signature record) + (error "Circular macro expansion: %s" + (org-element-property :key macro))) + (value + (push signature record) + (delete-region + begin + ;; Preserve white spaces after the macro. + (progn (goto-char (org-element-property :end macro)) + (skip-chars-backward " \t") + (point))) + ;; Leave point before replacement in case of + ;; recursive expansions. + (save-excursion (insert value))) + (finalize + (error "Undefined Org macro: %s; aborting" + (org-element-property :key macro)))))))))))) + +(defun org-macro-escape-arguments (&rest args) + "Build macro's arguments string from ARGS. +ARGS are strings. Return value is a string with arguments +properly escaped and separated with commas. This is the opposite +of `org-macro-extract-arguments'." + (let ((s "")) + (dolist (arg (reverse args) (substring s 1)) + (setq s + (concat + "," + (replace-regexp-in-string + "\\(\\\\*\\)," + (lambda (m) + (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\) + ",")) + ;; If a non-terminal argument ends on backslashes, make + ;; sure to also escape them as they will be followed by + ;; a comma. + (concat arg (and (not (equal s "")) + (string-match "\\\\+\\'" arg) + (match-string 0 arg))) + nil t) + s))))) + +(defun org-macro-extract-arguments (s) + "Extract macro arguments from string S. +S is a string containing comma separated values properly escaped. +Return a list of arguments, as strings. This is the opposite of +`org-macro-escape-arguments'." + ;; Do not use `org-split-string' since empty strings are + ;; meaningful here. + (split-string + (replace-regexp-in-string + "\\(\\\\*\\)," + (lambda (str) + (let ((len (length (match-string 1 str)))) + (concat (make-string (/ len 2) ?\\) + (if (zerop (mod len 2)) "\000" ",")))) + s nil t) + "\000")) + + +;;; Helper functions and variables for internal macros + +(defun org-macro--vc-modified-time (file) + (save-window-excursion + (when (vc-backend file) + (let ((buf (get-buffer-create " *org-vc*")) + (case-fold-search t) + date) + (unwind-protect + (progn + (vc-call print-log file buf nil nil 1) + (with-current-buffer buf + (vc-exec-after + (lambda () + (goto-char (point-min)) + (when (re-search-forward "Date:?[ \t]*" nil t) + (let ((time (parse-time-string + (buffer-substring + (point) (line-end-position))))) + (when (cl-some #'identity time) + (setq date (apply #'encode-time time)))))))) + (let ((proc (get-buffer-process buf))) + (while (and proc (accept-process-output proc .5 nil t))))) + (kill-buffer buf)) + date)))) + +(defvar org-macro--counter-table nil + "Hash table containing counter value per name.") + +(defun org-macro--counter-initialize () + "Initialize `org-macro--counter-table'." + (setq org-macro--counter-table (make-hash-table :test #'equal))) + +(defun org-macro--counter-increment (name &optional action) + "Increment counter NAME. +NAME is a string identifying the counter. + +When non-nil, optional argument ACTION is a string. + +If the string is \"-\", keep the NAME counter at its current +value, i.e. do not increment. + +If the string represents an integer, set the counter to this number. + +Any other non-empty string resets the counter to 1." + (let ((name-trimmed (org-trim name)) + (action-trimmed (when (org-string-nw-p action) + (org-trim action)))) + (puthash name-trimmed + (cond ((not (org-string-nw-p action-trimmed)) + (1+ (gethash name-trimmed org-macro--counter-table 0))) + ((string= "-" action-trimmed) + (gethash name-trimmed org-macro--counter-table 1)) + ((string-match-p "\\`[0-9]+\\'" action-trimmed) + (string-to-number action-trimmed)) + (t 1)) + org-macro--counter-table))) + + +(provide 'org-macro) +;;; org-macro.el ends here diff --git a/elpa/org-9.1.14/org-macs.el b/elpa/org-9.1.14/org-macs.el new file mode 100644 index 00000000..510ece1c --- /dev/null +++ b/elpa/org-9.1.14/org-macs.el @@ -0,0 +1,429 @@ +;;; org-macs.el --- Top-level Definitions for Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file contains macro definitions, defsubst definitions, other +;; stuff needed for compilation and top-level forms in Org mode, as +;; well lots of small functions that are not Org mode specific but +;; simply generally useful stuff. + +;;; Code: + +(defmacro org-with-gensyms (symbols &rest body) + (declare (debug (sexp body)) (indent 1)) + `(let ,(mapcar (lambda (s) + `(,s (make-symbol (concat "--" (symbol-name ',s))))) + symbols) + ,@body)) + +(defun org-string-nw-p (s) + "Return S if S is a string containing a non-blank character. +Otherwise, return nil." + (and (stringp s) + (string-match-p "[^ \r\t\n]" s) + s)) + +(defun org-split-string (string &optional separators) + "Splits STRING into substrings at SEPARATORS. + +SEPARATORS is a regular expression. When nil, it defaults to +\"[ \f\t\n\r\v]+\". + +Unlike `split-string', matching SEPARATORS at the beginning and +end of string are ignored." + (let ((separators (or separators "[ \f\t\n\r\v]+"))) + (when (string-match (concat "\\`" separators) string) + (setq string (replace-match "" nil nil string))) + (when (string-match (concat separators "\\'") string) + (setq string (replace-match "" nil nil string))) + (split-string string separators))) + +(defun org-string-display (string) + "Return STRING as it is displayed in the current buffer. +This function takes into consideration `invisible' and `display' +text properties." + (let* ((build-from-parts + (lambda (s property filter) + ;; Build a new string out of string S. On every group of + ;; contiguous characters with the same PROPERTY value, + ;; call FILTER on the properties list at the beginning of + ;; the group. If it returns a string, replace the + ;; characters in the group with it. Otherwise, preserve + ;; those characters. + (let ((len (length s)) + (new "") + (i 0) + (cursor 0)) + (while (setq i (text-property-not-all i len property nil s)) + (let ((end (next-single-property-change i property s len)) + (value (funcall filter (text-properties-at i s)))) + (when value + (setq new (concat new (substring s cursor i) value)) + (setq cursor end)) + (setq i end))) + (concat new (substring s cursor))))) + (prune-invisible + (lambda (s) + (funcall build-from-parts s 'invisible + (lambda (props) + ;; If `invisible' property in PROPS means text + ;; is to be invisible, return the empty string. + ;; Otherwise return nil so that the part is + ;; skipped. + (and (or (eq t buffer-invisibility-spec) + (assoc-string (plist-get props 'invisible) + buffer-invisibility-spec)) + ""))))) + (replace-display + (lambda (s) + (funcall build-from-parts s 'display + (lambda (props) + ;; If there is any string specification in + ;; `display' property return it. Also attach + ;; other text properties on the part to that + ;; string (face...). + (let* ((display (plist-get props 'display)) + (value (if (stringp display) display + (cl-some #'stringp display)))) + (when value + (apply #'propertize + ;; Displayed string could contain + ;; invisible parts, but no nested + ;; display. + (funcall prune-invisible value) + 'display + (and (not (stringp display)) + (cl-remove-if #'stringp display)) + props)))))))) + ;; `display' property overrides `invisible' one. So we first + ;; replace characters with `display' property. Then we remove + ;; invisible characters. + (funcall prune-invisible (funcall replace-display string)))) + +(defun org-string-width (string) + "Return width of STRING when displayed in the current buffer. +Unlike `string-width', this function takes into consideration +`invisible' and `display' text properties." + (string-width (org-string-display string))) + +(defun org-not-nil (v) + "If V not nil, and also not the string \"nil\", then return V. +Otherwise return nil." + (and v (not (equal v "nil")) v)) + +(defmacro org-preserve-lc (&rest body) + (declare (debug (body))) + (org-with-gensyms (line col) + `(let ((,line (org-current-line)) + (,col (current-column))) + (unwind-protect + (progn ,@body) + (org-goto-line ,line) + (org-move-to-column ,col))))) + +;; Use `org-with-silent-modifications' to ignore cosmetic changes and +;; `org-unmodified' to ignore real text modifications +(defmacro org-unmodified (&rest body) + "Run BODY while preserving the buffer's `buffer-modified-p' state." + (declare (debug (body))) + (org-with-gensyms (was-modified) + `(let ((,was-modified (buffer-modified-p))) + (unwind-protect + (let ((buffer-undo-list t) + (inhibit-modification-hooks t)) + ,@body) + (set-buffer-modified-p ,was-modified))))) + +(defmacro org-without-partial-completion (&rest body) + (declare (debug (body))) + `(if (and (boundp 'partial-completion-mode) + partial-completion-mode + (fboundp 'partial-completion-mode)) + (unwind-protect + (progn + (partial-completion-mode -1) + ,@body) + (partial-completion-mode 1)) + ,@body)) + +(defmacro org-with-point-at (pom &rest body) + "Move to buffer and point of point-or-marker POM for the duration of BODY." + (declare (debug (form body)) (indent 1)) + (org-with-gensyms (mpom) + `(let ((,mpom ,pom)) + (save-excursion + (if (markerp ,mpom) (set-buffer (marker-buffer ,mpom))) + (org-with-wide-buffer + (goto-char (or ,mpom (point))) + ,@body))))) + +(defmacro org-with-remote-undo (buffer &rest body) + "Execute BODY while recording undo information in two buffers." + (declare (debug (form body)) (indent 1)) + (org-with-gensyms (cline cmd buf1 buf2 undo1 undo2 c1 c2) + `(let ((,cline (org-current-line)) + (,cmd this-command) + (,buf1 (current-buffer)) + (,buf2 ,buffer) + (,undo1 buffer-undo-list) + (,undo2 (with-current-buffer ,buffer buffer-undo-list)) + ,c1 ,c2) + ,@body + (when org-agenda-allow-remote-undo + (setq ,c1 (org-verify-change-for-undo + ,undo1 (with-current-buffer ,buf1 buffer-undo-list)) + ,c2 (org-verify-change-for-undo + ,undo2 (with-current-buffer ,buf2 buffer-undo-list))) + (when (or ,c1 ,c2) + ;; make sure there are undo boundaries + (and ,c1 (with-current-buffer ,buf1 (undo-boundary))) + (and ,c2 (with-current-buffer ,buf2 (undo-boundary))) + ;; remember which buffer to undo + (push (list ,cmd ,cline ,buf1 ,c1 ,buf2 ,c2) + org-agenda-undo-list)))))) + +(defmacro org-no-read-only (&rest body) + "Inhibit read-only for BODY." + (declare (debug (body))) + `(let ((inhibit-read-only t)) ,@body)) + +(defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t + rear-nonsticky t mouse-map t fontified t + org-emphasis t) + "Properties to remove when a string without properties is wanted.") + +(defsubst org-no-properties (s &optional restricted) + "Remove all text properties from string S. +When RESTRICTED is non-nil, only remove the properties listed +in `org-rm-props'." + (if restricted (remove-text-properties 0 (length s) org-rm-props s) + (set-text-properties 0 (length s) nil s)) + s) + +(defsubst org-get-alist-option (option key) + (cond ((eq key t) t) + ((eq option t) t) + ((assoc key option) (cdr (assoc key option))) + (t (let ((r (cdr (assq 'default option)))) + (if (listp r) (delq nil r) r))))) + +(defsubst org-check-external-command (cmd &optional use no-error) + "Check if external program CMD for USE exists, error if not. +When the program does exist, return its path. +When it does not exist and NO-ERROR is set, return nil. +Otherwise, throw an error. The optional argument USE can describe what this +program is needed for, so that the error message can be more informative." + (or (executable-find cmd) + (if no-error + nil + (error "Can't find `%s'%s" cmd + (if use (format " (%s)" use) ""))))) + +(defsubst org-last (list) + "Return the last element of LIST." + (car (last list))) + +(defun org-let (list &rest body) + (eval (cons 'let (cons list body)))) +(put 'org-let 'lisp-indent-function 1) + +(defun org-let2 (list1 list2 &rest body) + (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body))))))) +(put 'org-let2 'lisp-indent-function 2) + +(defsubst org-call-with-arg (command arg) + "Call COMMAND interactively, but pretend prefix arg was ARG." + (let ((current-prefix-arg arg)) (call-interactively command))) + +(defsubst org-current-line (&optional pos) + (save-excursion + (and pos (goto-char pos)) + ;; works also in narrowed buffer, because we start at 1, not point-min + (+ (if (bolp) 1 0) (count-lines 1 (point))))) + +(defsubst org-goto-line (N) + (save-restriction + (widen) + (goto-char (point-min)) + (forward-line (1- N)))) + +(defsubst org-current-line-string (&optional to-here) + (buffer-substring (point-at-bol) (if to-here (point) (point-at-eol)))) + +(defsubst org-pos-in-match-range (pos n) + (and (match-beginning n) + (<= (match-beginning n) pos) + (>= (match-end n) pos))) + +(defun org-match-line (regexp) + "Match REGEXP at the beginning of the current line." + (save-excursion + (beginning-of-line) + (looking-at regexp))) + +(defun org-plist-delete (plist property) + "Delete PROPERTY from PLIST. +This is in contrast to merely setting it to 0." + (let (p) + (while plist + (if (not (eq property (car plist))) + (setq p (plist-put p (car plist) (nth 1 plist)))) + (setq plist (cddr plist))) + p)) + +(defmacro org-save-outline-visibility (use-markers &rest body) + "Save and restore outline visibility around BODY. +If USE-MARKERS is non-nil, use markers for the positions. +This means that the buffer may change while running BODY, +but it also means that the buffer should stay alive +during the operation, because otherwise all these markers will +point nowhere." + (declare (debug (form body)) (indent 1)) + (org-with-gensyms (data) + `(let ((,data (org-outline-overlay-data ,use-markers))) + (unwind-protect + (prog1 (progn ,@body) + (org-set-outline-overlay-data ,data)) + (when ,use-markers + (dolist (c ,data) + (when (markerp (car c)) (move-marker (car c) nil)) + (when (markerp (cdr c)) (move-marker (cdr c) nil)))))))) + +(defmacro org-with-wide-buffer (&rest body) + "Execute body while temporarily widening the buffer." + (declare (debug (body))) + `(save-excursion + (save-restriction + (widen) + ,@body))) + +(defmacro org-with-limited-levels (&rest body) + "Execute BODY with limited number of outline levels." + (declare (debug (body))) + `(progn + (defvar org-called-with-limited-levels) + (defvar org-outline-regexp) + (defvar outline-regexp) + (defvar org-outline-regexp-bol) + (let* ((org-called-with-limited-levels t) + (org-outline-regexp (org-get-limited-outline-regexp)) + (outline-regexp org-outline-regexp) + (org-outline-regexp-bol (concat "^" org-outline-regexp))) + ,@body))) + +(defvar org-outline-regexp) ; defined in org.el +(defvar org-odd-levels-only) ; defined in org.el +(defvar org-inlinetask-min-level) ; defined in org-inlinetask.el +(defun org-get-limited-outline-regexp () + "Return outline-regexp with limited number of levels. +The number of levels is controlled by `org-inlinetask-min-level'" + (cond ((not (derived-mode-p 'org-mode)) + outline-regexp) + ((not (featurep 'org-inlinetask)) + org-outline-regexp) + (t + (let* ((limit-level (1- org-inlinetask-min-level)) + (nstars (if org-odd-levels-only + (1- (* limit-level 2)) + limit-level))) + (format "\\*\\{1,%d\\} " nstars))))) + +(defmacro org-eval-in-environment (environment form) + (declare (debug (form form)) (indent 1)) + `(eval (list 'let ,environment ',form))) + +(defun org-make-parameter-alist (flat) + "Return alist based on FLAT. +FLAT is a list with alternating symbol names and values. The +returned alist is a list of lists with the symbol name in car and +the value in cdr." + (when flat + (cons (list (car flat) (cadr flat)) + (org-make-parameter-alist (cddr flat))))) + +;;;###autoload +(defmacro org-load-noerror-mustsuffix (file) + "Load FILE with optional arguments NOERROR and MUSTSUFFIX." + `(load ,file 'noerror nil nil 'mustsuffix)) + +(defun org-unbracket-string (pre post string) + "Remove PRE/POST from the beginning/end of STRING. +Both PRE and POST must be pre-/suffixes of STRING, or neither is +removed." + (if (and (string-prefix-p pre string) + (string-suffix-p post string)) + (substring string (length pre) (- (length post))) + string)) + +(defun org-read-function (prompt &optional allow-empty?) + "Prompt for a function. +If ALLOW-EMPTY? is non-nil, return nil rather than raising an +error when the user input is empty." + (let ((func (completing-read prompt obarray #'fboundp t))) + (cond ((not (string= func "")) + (intern func)) + (allow-empty? nil) + (t (user-error "Empty input is not valid"))))) + +(defconst org-unique-local-variables + '(org-element--cache + org-element--cache-objects + org-element--cache-sync-keys + org-element--cache-sync-requests + org-element--cache-sync-timer) + "List of local variables that cannot be transferred to another buffer.") + +(defun org-get-local-variables () + "Return a list of all local variables in an Org mode buffer." + (delq nil + (mapcar + (lambda (x) + (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x)))) + (name (car binding))) + (and (not (get name 'org-state)) + (not (memq name org-unique-local-variables)) + (string-match-p + "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\ +auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)" + (symbol-name name)) + binding))) + (with-temp-buffer + (org-mode) + (buffer-local-variables))))) + +(defun org-clone-local-variables (from-buffer &optional regexp) + "Clone local variables from FROM-BUFFER. +Optional argument REGEXP selects variables to clone." + (dolist (pair (buffer-local-variables from-buffer)) + (pcase pair + (`(,name . ,value) ;ignore unbound variables + (when (and (not (memq name org-unique-local-variables)) + (or (null regexp) (string-match-p regexp (symbol-name name)))) + (ignore-errors (set (make-local-variable name) value))))))) + + +(provide 'org-macs) + +;;; org-macs.el ends here diff --git a/elpa/org-9.1.14/org-mhe.el b/elpa/org-9.1.14/org-mhe.el new file mode 100644 index 00000000..e74a9ee5 --- /dev/null +++ b/elpa/org-9.1.14/org-mhe.el @@ -0,0 +1,219 @@ +;;; org-mhe.el --- Support for Links to MH-E Messages -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Thomas Baumann <thomas dot baumann at ch dot tum dot de> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file implements links to MH-E messages from within Org. +;; Org mode loads this module by default - if this is not what you want, +;; configure the variable `org-modules'. + +;;; Code: + +(require 'org-macs) +(require 'org) + +;; Customization variables + +(defcustom org-mhe-search-all-folders nil + "Non-nil means the search for the mh-message may extend to all folders. +When non-nil, the search for a message will extend to all other +folders if it cannot be found in the folder given in the link. +Searching all folders may be slow with the default pick based +search but is very efficient with one of the other search engines +supported by MH-E." + :group 'org-link-follow + :type 'boolean) + +;; Declare external functions and variables +(declare-function mh-display-msg "mh-show" (msg-num folder-name)) +(declare-function mh-find-path "mh-utils" ()) +(declare-function mh-get-header-field "mh-utils" (field)) +(declare-function mh-get-msg-num "mh-utils" (error-if-no-message)) +(declare-function mh-header-display "mh-show" ()) +(declare-function mh-index-previous-folder "mh-search" ()) +(declare-function mh-normalize-folder-name "mh-utils" + (folder &optional empty-string-okay dont-remove-trailing-slash + return-nil-if-folder-empty)) +(declare-function mh-search "mh-search" + (folder search-regexp &optional redo-search-flag + window-config)) +(declare-function mh-search-choose "mh-search" (&optional searcher)) +(declare-function mh-show "mh-show" (&optional message redisplay-flag)) +(declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer)) +(declare-function mh-show-header-display "mh-show" t t) +(declare-function mh-show-msg "mh-show" (msg)) +(declare-function mh-show-show "mh-show" t t) +(declare-function mh-visit-folder "mh-folder" (folder &optional + range index-data)) +(defvar mh-progs) +(defvar mh-current-folder) +(defvar mh-show-folder-buffer) +(defvar mh-index-folder) +(defvar mh-searcher) +(defvar mh-search-regexp-builder) + +;; Install the link type +(org-link-set-parameters "mhe" :follow #'org-mhe-open :store #'org-mhe-store-link) + +;; Implementation +(defun org-mhe-store-link () + "Store a link to an MH-E folder or message." + (when (or (eq major-mode 'mh-folder-mode) + (eq major-mode 'mh-show-mode)) + (save-window-excursion + (let* ((from (org-mhe-get-header "From:")) + (to (org-mhe-get-header "To:")) + (message-id (org-mhe-get-header "Message-Id:")) + (subject (org-mhe-get-header "Subject:")) + (date (org-mhe-get-header "Date:")) + link desc) + (org-store-link-props :type "mh" :from from :to to :date date + :subject subject :message-id message-id) + (setq desc (org-email-link-description)) + (setq link (concat "mhe:" (org-mhe-get-message-real-folder) "#" + (org-unbracket-string "<" ">" message-id))) + (org-add-link-props :link link :description desc) + link)))) + +(defun org-mhe-open (path) + "Follow an MH-E message link specified by PATH." + (let (folder article) + (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path)) + (error "Error in MH-E link")) + (setq folder (match-string 1 path) + article (match-string 3 path)) + (org-mhe-follow-link folder article))) + +;;; mh-e integration based on planner-mode +(defun org-mhe-get-message-real-folder () + "Return the name of the real folder for the current message. +So if you use sequences, it will now work." + (save-excursion + (let* ((folder + (if (eq major-mode 'mh-folder-mode) + mh-current-folder + ;; Refer to the show buffer + mh-show-folder-buffer)) + (end-index + (if (boundp 'mh-index-folder) + (min (length mh-index-folder) (length folder)))) + ) + ;; a simple test on mh-index-data does not work, because + ;; mh-index-data is always nil in a show buffer. + (if (and (boundp 'mh-index-folder) + (string= mh-index-folder (substring folder 0 end-index))) + (if (eq major-mode 'mh-show-mode) + (save-window-excursion + (let (pop-up-frames) + (when (buffer-live-p (get-buffer folder)) + (progn + (pop-to-buffer folder) + (org-mhe-get-message-folder-from-index) + ) + ))) + (org-mhe-get-message-folder-from-index) + ) + folder + ) + ))) + +(defun org-mhe-get-message-folder-from-index () + "Return the name of the message folder in an index folder buffer." + (save-excursion + (mh-index-previous-folder) + (if (re-search-forward "^\\(+.*\\)$" nil t) + (message "%s" (match-string 1))))) + +(defun org-mhe-get-message-folder () + "Return the name of the current message folder. +Be careful if you use sequences." + (save-excursion + (if (eq major-mode 'mh-folder-mode) + mh-current-folder + ;; Refer to the show buffer + mh-show-folder-buffer))) + +(defun org-mhe-get-message-num () + "Return the number of the current message. +Be careful if you use sequences." + (save-excursion + (if (eq major-mode 'mh-folder-mode) + (mh-get-msg-num nil) + ;; Refer to the show buffer + (mh-show-buffer-message-number)))) + +(defun org-mhe-get-header (header) + "Return the field for HEADER of the message in folder mode. +This will create a show buffer for the corresponding message. If +you have a better idea of how to do this then please let us know." + (let* ((folder (org-mhe-get-message-folder)) + (num (org-mhe-get-message-num)) + (buffer (get-buffer-create (concat "show-" folder))) + (header-field)) + (with-current-buffer buffer + (mh-display-msg num folder) + (if (eq major-mode 'mh-folder-mode) + (mh-header-display) + (mh-show-header-display)) + (set-buffer buffer) + (setq header-field (mh-get-header-field header)) + (if (eq major-mode 'mh-folder-mode) + (mh-show) + (mh-show-show)) + (org-trim header-field)))) + +(defun org-mhe-follow-link (folder article) + "Follow an MH-E link to FOLDER and ARTICLE. +If ARTICLE is nil FOLDER is shown. If the configuration variable +`org-mhe-search-all-folders' is t and `mh-searcher' is pick, +ARTICLE is searched in all folders. Indexed searches (swish++, +namazu, and others supported by MH-E) will always search in all +folders." + (require 'mh-e) + (require 'mh-search) + (require 'mh-utils) + (mh-find-path) + (if (not article) + (mh-visit-folder (mh-normalize-folder-name folder)) + (mh-search-choose) + (if (eq mh-searcher 'pick) + (progn + (setq article (org-add-angle-brackets article)) + (mh-search folder (list "--message-id" article)) + (when (and org-mhe-search-all-folders + (not (org-mhe-get-message-real-folder))) + (kill-buffer) + (mh-search "+" (list "--message-id" article)))) + (if mh-search-regexp-builder + (mh-search "+" (funcall mh-search-regexp-builder + (list (cons 'message-id article)))) + (mh-search "+" article))) + (if (org-mhe-get-message-real-folder) + (mh-show-msg 1) + (kill-buffer) + (error "Message not found")))) + +(provide 'org-mhe) + +;;; org-mhe.el ends here diff --git a/elpa/org-9.1.14/org-mobile.el b/elpa/org-9.1.14/org-mobile.el new file mode 100644 index 00000000..cbf169f4 --- /dev/null +++ b/elpa/org-9.1.14/org-mobile.el @@ -0,0 +1,1115 @@ +;;; org-mobile.el --- Code for Asymmetric Sync With a Mobile Device -*- lexical-binding: t; -*- +;; Copyright (C) 2009-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. +;; +;; GNU Emacs 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: +;; +;; This file contains the code to interact with Richard Moreland's +;; iPhone application MobileOrg, as well as with the Android version +;; by Matthew Jones. This code is documented in Appendix B of the Org +;; manual. The code is not specific for the iPhone and Android - any +;; external viewer/flagging/editing application that uses the same +;; conventions could be used. + +(require 'org) +(require 'org-agenda) +(require 'cl-lib) + +(defvar org-agenda-keep-restricted-file-list) + +;;; Code: + +(defgroup org-mobile nil + "Options concerning support for a viewer/editor on a mobile device." + :tag "Org Mobile" + :group 'org) + +(defcustom org-mobile-files '(org-agenda-files) + "Files to be staged for MobileOrg. +This is basically a list of files and directories. Files will be staged +directly. Directories will be search for files with the extension `.org'. +In addition to this, the list may also contain the following symbols: + +org-agenda-files + This means include the complete, unrestricted list of files given in + the variable `org-agenda-files'. +org-agenda-text-search-extra-files + Include the files given in the variable + `org-agenda-text-search-extra-files'" + :group 'org-mobile + :type '(list :greedy t + (option (const :tag "org-agenda-files" org-agenda-files)) + (option (const :tag "org-agenda-text-search-extra-files" + org-agenda-text-search-extra-files)) + (repeat :inline t :tag "Additional files" + (file)))) + +(defcustom org-mobile-files-exclude-regexp "" + "A regexp to exclude files from `org-mobile-files'." + :group 'org-mobile + :version "24.1" + :type 'regexp) + +(defcustom org-mobile-directory "" + "The WebDAV directory where the interaction with the mobile takes place." + :group 'org-mobile + :type 'directory) + +(defcustom org-mobile-allpriorities "A B C" + "Default set of priority cookies for the index file." + :version "24.4" + :package-version '(Org . "8.0") + :type 'string + :group 'org-mobile) + +(defcustom org-mobile-use-encryption nil + "Non-nil means keep only encrypted files on the WebDAV server. +Encryption uses AES-256, with a password given in +`org-mobile-encryption-password'. +When nil, plain files are kept on the server. +Turning on encryption requires setting the same password in the MobileOrg +application. Before turning this on, check of MobileOrg does already +support it - at the time of this writing it did not yet." + :group 'org-mobile + :version "24.1" + :type 'boolean) + +(defcustom org-mobile-encryption-tempfile "~/orgtmpcrypt" + "File that is being used as a temporary file for encryption. +This must be local file on your local machine (not on the WebDAV server). +You might want to put this file into a directory where only you have access." + :group 'org-mobile + :version "24.1" + :type 'directory) + +(defcustom org-mobile-encryption-password "" + "Password for encrypting files uploaded to the server. +This is a single password which is used for AES-256 encryption. The same +password must also be set in the MobileOrg application. All Org files, +including mobileorg.org will be encrypted using this password. + +SECURITY CONSIDERATIONS: + +Note that, when Org runs the encryption commands, the password could +be visible briefly on your system with the `ps' command. So this method is +only intended to keep the files secure on the server, not on your own machine. + +Also, if you set this variable in an init file (.emacs or .emacs.d/init.el +or custom.el...) and if that file is stored in a way so that other can read +it, this also limits the security of this approach. You can also leave +this variable empty - Org will then ask for the password once per Emacs +session." + :group 'org-mobile + :version "24.1" + :type '(string :tag "Password")) + +(defvar org-mobile-encryption-password-session nil) + +(defun org-mobile-encryption-password () + (or (org-string-nw-p org-mobile-encryption-password) + (org-string-nw-p org-mobile-encryption-password-session) + (setq org-mobile-encryption-password-session + (read-passwd "Password for MobileOrg: " t)))) + +(defcustom org-mobile-inbox-for-pull "~/org/from-mobile.org" + "The file where captured notes and flags will be appended to. +During the execution of `org-mobile-pull', the file +`org-mobile-capture-file' will be emptied it's contents have +been appended to the file given here. This file should be in +`org-directory', and not in the staging area or on the web server." + :group 'org-mobile + :type 'file) + +(defconst org-mobile-capture-file "mobileorg.org" + "The capture file where the mobile stores captured notes and flags. +This should not be changed, because MobileOrg assumes this name.") + +(defcustom org-mobile-index-file "index.org" + "The index file with links to all Org files that should be loaded by MobileOrg. +Relative to `org-mobile-directory'. The Address field in the MobileOrg setup +should point to this file." + :group 'org-mobile + :type 'file) + +(defcustom org-mobile-agendas 'all + "The agendas that should be pushed to MobileOrg. +Allowed values: + +default the weekly agenda and the global TODO list +custom all custom agendas defined by the user +all the custom agendas and the default ones +list a list of selection key(s) as string." + :group 'org-mobile + :version "24.1" + :type '(choice + (const :tag "Default Agendas" default) + (const :tag "Custom Agendas" custom) + (const :tag "Default and Custom Agendas" all) + (repeat :tag "Selected" + (string :tag "Selection Keys")))) + +(defcustom org-mobile-force-id-on-agenda-items t + "Non-nil means make all agenda items carry an ID." + :group 'org-mobile + :type 'boolean) + +(defcustom org-mobile-force-mobile-change nil + "Non-nil means force the change made on the mobile device. +So even if there have been changes to the computer version of the entry, +force the new value set on the mobile. +When nil, mark the entry from the mobile with an error message. +Instead of nil or t, this variable can also be a list of symbols, indicating +the editing types for which the mobile version should always dominate." + :group 'org-mobile + :type '(choice + (const :tag "Always" t) + (const :tag "Never" nil) + (set :greedy t :tag "Specify" + (const todo) + (const tags) + (const priority) + (const heading) + (const body)))) + +(defcustom org-mobile-checksum-binary (or (executable-find "shasum") + (executable-find "sha1sum") + (executable-find "md5sum") + (executable-find "md5")) + "Executable used for computing checksums of agenda files." + :group 'org-mobile + :type 'string) + +(defvar org-mobile-pre-push-hook nil + "Hook run before running `org-mobile-push'. +This could be used to clean up `org-mobile-directory', for example to +remove files that used to be included in the agenda but no longer are. +The presence of such files would not really be a problem, but after time +they may accumulate.") + +(defvar org-mobile-post-push-hook nil + "Hook run after running `org-mobile-push'. +If Emacs does not have direct write access to the WebDAV directory used +by the mobile device, this hook should be used to copy all files from the +local staging directory `org-mobile-directory' to the WebDAV directory, +for example using `rsync' or `scp'.") + +(defvar org-mobile-pre-pull-hook nil + "Hook run before executing `org-mobile-pull'. +If Emacs does not have direct write access to the WebDAV directory used +by the mobile device, this hook should be used to copy the capture file +`mobileorg.org' from the WebDAV location to the local staging +directory `org-mobile-directory'.") + +(defvar org-mobile-post-pull-hook nil + "Hook run after running `org-mobile-pull', only if new items were found. +If Emacs does not have direct write access to the WebDAV directory used +by the mobile device, this hook should be used to copy the emptied +capture file `mobileorg.org' back to the WebDAV directory, for example +using `rsync' or `scp'.") + +(defconst org-mobile-action-alist '(("edit" . org-mobile-edit)) + "Alist with flags and actions for mobile sync. +When flagging an entry, MobileOrg will create entries that look like + + * F(action:data) [[id:entry-id][entry title]] + +This alist defines that the ACTION in the parentheses of F() +should mean, i.e. what action should be taken. The :data part in +the parenthesis is optional. If present, the string after the +colon will be passed to the action function as the first argument +variable. + +The car of each elements of the alist is an actions string. The +cdr is a function that is called with the cursor on the headline +of that entry. It should accept three arguments, the :data part, +the old and new values for the entry.") + +(defvar org-mobile-last-flagged-files nil + "List of files containing entries flagged in the latest pull.") + +(defvar org-mobile-files-alist nil) +(defvar org-mobile-checksum-files nil) + +(defun org-mobile-prepare-file-lists () + (setq org-mobile-files-alist (org-mobile-files-alist)) + (setq org-mobile-checksum-files nil)) + +(defun org-mobile-files-alist () + "Expand the list in `org-mobile-files' to a list of existing files. +Also exclude files matching `org-mobile-files-exclude-regexp'." + (let* ((include-archives + (and (member 'org-agenda-text-search-extra-files org-mobile-files) + (member 'agenda-archives org-agenda-text-search-extra-files) + t)) + (files + (apply 'append + (mapcar + (lambda (f) + (cond + ((eq f 'org-agenda-files) + (org-agenda-files t include-archives)) + ((eq f 'org-agenda-text-search-extra-files) + (delq 'agenda-archives + (copy-sequence + org-agenda-text-search-extra-files))) + ((and (stringp f) (file-directory-p f)) + (directory-files f 'full "\\.org\\'")) + ((and (stringp f) (file-exists-p f)) + (list f)) + (t nil))) + org-mobile-files))) + (files (delq + nil + (mapcar (lambda (f) + (unless (and (not (string= org-mobile-files-exclude-regexp "")) + (string-match org-mobile-files-exclude-regexp f)) + (identity f))) + files))) + (orgdir-uname (file-name-as-directory (file-truename org-directory))) + (orgdir-re (concat "\\`" (regexp-quote orgdir-uname))) + uname seen rtn file link-name) + ;; Make the files unique, and determine the name under which they will + ;; be listed. + (while (setq file (pop files)) + (if (not (file-name-absolute-p file)) + (setq file (expand-file-name file org-directory))) + (setq uname (file-truename file)) + (unless (member uname seen) + (push uname seen) + (if (string-match orgdir-re uname) + (setq link-name (substring uname (match-end 0))) + (setq link-name (file-name-nondirectory uname))) + (push (cons file link-name) rtn))) + (nreverse rtn))) + +;;;###autoload +(defun org-mobile-push () + "Push the current state of Org affairs to the target directory. +This will create the index file, copy all agenda files there, and also +create all custom agenda views, for upload to the mobile phone." + (interactive) + (let ((org-agenda-buffer-name "*SUMO*") + (org-agenda-tag-filter org-agenda-tag-filter) + (org-agenda-redo-command org-agenda-redo-command)) + (save-excursion + (save-restriction + (save-window-excursion + (run-hooks 'org-mobile-pre-push-hook) + (org-mobile-check-setup) + (org-mobile-prepare-file-lists) + (message "Creating agendas...") + (let ((inhibit-redisplay t) + (org-agenda-files (mapcar 'car org-mobile-files-alist))) + (org-mobile-create-sumo-agenda)) + (message "Creating agendas...done") + (org-save-all-org-buffers) ; to save any IDs created by this process + (message "Copying files...") + (org-mobile-copy-agenda-files) + (message "Writing index file...") + (org-mobile-create-index-file) + (message "Writing checksums...") + (org-mobile-write-checksums) + (run-hooks 'org-mobile-post-push-hook))))) + (org-agenda-maybe-redo) + (message "Files for mobile viewer staged")) + +(defvar org-mobile-before-process-capture-hook nil + "Hook that is run after content was moved to `org-mobile-inbox-for-pull'. +The inbox file is visited by the current buffer, and the buffer is +narrowed to the newly captured data.") + +;;;###autoload +(defun org-mobile-pull () + "Pull the contents of `org-mobile-capture-file' and integrate them. +Apply all flagged actions, flag entries to be flagged and then call an +agenda view showing the flagged items." + (interactive) + (org-mobile-check-setup) + (run-hooks 'org-mobile-pre-pull-hook) + (let ((insertion-marker (org-mobile-move-capture))) + (if (not (markerp insertion-marker)) + (message "No new items") + (org-with-point-at insertion-marker + (save-restriction + (narrow-to-region (point) (point-max)) + (run-hooks 'org-mobile-before-process-capture-hook))) + (org-with-point-at insertion-marker + (org-mobile-apply (point) (point-max))) + (move-marker insertion-marker nil) + (run-hooks 'org-mobile-post-pull-hook) + (when org-mobile-last-flagged-files + ;; Make an agenda view of flagged entries, but only in the files + ;; where stuff has been added. + (put 'org-agenda-files 'org-restrict org-mobile-last-flagged-files) + (let ((org-agenda-keep-restricted-file-list t)) + (org-agenda nil "?")))))) + +(defun org-mobile-check-setup () + "Check if org-mobile-directory has been set up." + (org-mobile-cleanup-encryption-tempfile) + (unless (and org-directory + (stringp org-directory) + (string-match "\\S-" org-directory) + (file-exists-p org-directory) + (file-directory-p org-directory)) + (error + "Please set `org-directory' to the directory where your org files live")) + (unless (and org-mobile-directory + (stringp org-mobile-directory) + (string-match "\\S-" org-mobile-directory) + (file-exists-p org-mobile-directory) + (file-directory-p org-mobile-directory)) + (error + "Variable `org-mobile-directory' must point to an existing directory")) + (unless (and org-mobile-inbox-for-pull + (stringp org-mobile-inbox-for-pull) + (string-match "\\S-" org-mobile-inbox-for-pull) + (file-exists-p + (file-name-directory org-mobile-inbox-for-pull))) + (error + "Variable `org-mobile-inbox-for-pull' must point to a file in an existing directory")) + (unless (and org-mobile-checksum-binary + (string-match "\\S-" org-mobile-checksum-binary)) + (error "No executable found to compute checksums")) + (when org-mobile-use-encryption + (unless (string-match "\\S-" (org-mobile-encryption-password)) + (error + "To use encryption, you must set `org-mobile-encryption-password'")) + (unless (file-writable-p org-mobile-encryption-tempfile) + (error "Cannot write to encryption tempfile %s" + org-mobile-encryption-tempfile)) + (unless (executable-find "openssl") + (error "OpenSSL is needed to encrypt files")))) + +(defun org-mobile-create-index-file () + "Write the index file in the WebDAV directory." + (let ((files-alist (sort (copy-sequence org-mobile-files-alist) + (lambda (a b) (string< (cdr a) (cdr b))))) + (def-todo (default-value 'org-todo-keywords)) + (def-tags org-tag-alist) + (target-file (expand-file-name org-mobile-index-file + org-mobile-directory)) + todo-kwds done-kwds tags) + (when (stringp (car def-todo)) + (setq def-todo (list (cons 'sequence def-todo)))) + (org-agenda-prepare-buffers (mapcar 'car files-alist)) + (setq done-kwds (org-uniquify org-done-keywords-for-agenda)) + (setq todo-kwds (org-delete-all + done-kwds + (org-uniquify org-todo-keywords-for-agenda))) + (setq tags (mapcar 'car (org-global-tags-completion-table + (mapcar 'car files-alist)))) + (with-temp-file (if org-mobile-use-encryption org-mobile-encryption-tempfile + target-file) + (insert "#+READONLY\n") + (dolist (entry def-todo) + (let ((kwds (mapcar (lambda (x) + (if (string-match "(" x) + (substring x 0 (match-beginning 0)) + x)) + (cdr entry)))) + (insert "#+TODO: " (mapconcat #'identity kwds " ") "\n") + (let* ((dwds (or (member "|" kwds) (last kwds))) + (twds (org-delete-all dwds kwds))) + (setq todo-kwds (org-delete-all twds todo-kwds)) + (setq done-kwds (org-delete-all dwds done-kwds))))) + (when (or todo-kwds done-kwds) + (insert "#+TODO: " (mapconcat 'identity todo-kwds " ") " | " + (mapconcat 'identity done-kwds " ") "\n")) + (setq def-tags (split-string (org-tag-alist-to-string def-tags t))) + (setq tags (org-delete-all def-tags tags)) + (setq tags (sort tags (lambda (a b) (string< (downcase a) (downcase b))))) + (setq tags (append def-tags tags nil)) + (insert "#+TAGS: " (mapconcat 'identity tags " ") "\n") + (insert "#+ALLPRIORITIES: " org-mobile-allpriorities "\n") + (when (file-exists-p (expand-file-name + org-mobile-directory "agendas.org")) + (insert "* [[file:agendas.org][Agenda Views]]\n")) + (pcase-dolist (`(,_ . ,link-name) files-alist) + (insert (format "* [[file:%s][%s]]\n" link-name link-name))) + (push (cons org-mobile-index-file (md5 (buffer-string))) + org-mobile-checksum-files)) + (when org-mobile-use-encryption + (org-mobile-encrypt-and-move org-mobile-encryption-tempfile + target-file) + (org-mobile-cleanup-encryption-tempfile)))) + +(defun org-mobile-copy-agenda-files () + "Copy all agenda files to the stage or WebDAV directory." + (let ((files-alist org-mobile-files-alist) + file buf entry link-name target-path target-dir check) + (while (setq entry (pop files-alist)) + (setq file (car entry) link-name (cdr entry)) + (when (file-exists-p file) + (setq target-path (expand-file-name link-name org-mobile-directory) + target-dir (file-name-directory target-path)) + (unless (file-directory-p target-dir) + (make-directory target-dir 'parents)) + (if org-mobile-use-encryption + (org-mobile-encrypt-and-move file target-path) + (copy-file file target-path 'ok-if-already-exists)) + (setq check (shell-command-to-string + (concat (shell-quote-argument org-mobile-checksum-binary) + " " + (shell-quote-argument (expand-file-name file))))) + (when (string-match "[a-fA-F0-9]\\{30,40\\}" check) + (push (cons link-name (match-string 0 check)) + org-mobile-checksum-files)))) + + (setq file (expand-file-name org-mobile-capture-file + org-mobile-directory)) + (save-excursion + (setq buf (find-file file)) + (when (and (= (point-min) (point-max))) + (insert "\n") + (save-buffer) + (when org-mobile-use-encryption + (write-file org-mobile-encryption-tempfile) + (org-mobile-encrypt-and-move org-mobile-encryption-tempfile file))) + (push (cons org-mobile-capture-file (md5 (buffer-string))) + org-mobile-checksum-files)) + (org-mobile-cleanup-encryption-tempfile) + (kill-buffer buf))) + +(defun org-mobile-write-checksums () + "Create checksums for all files in `org-mobile-directory'. +The table of checksums is written to the file mobile-checksums." + (let ((sumfile (expand-file-name "checksums.dat" org-mobile-directory)) + (files org-mobile-checksum-files) + entry file sum) + (with-temp-file sumfile + (set-buffer-file-coding-system 'undecided-unix nil) + (while (setq entry (pop files)) + (setq file (car entry) sum (cdr entry)) + (insert (format "%s %s\n" sum file)))))) + +(defun org-mobile-sumo-agenda-command () + "Return an agenda custom command that comprises all custom commands." + (let ((custom-list + ;; normalize different versions + (delq nil + (mapcar + (lambda (x) + (cond ((stringp (cdr x)) nil) + ((stringp (nth 1 x)) x) + ((not (nth 1 x)) (cons (car x) (cons "" (cddr x)))) + (t (cons (car x) (cons "" (cdr x)))))) + org-agenda-custom-commands))) + (default-list '(("a" "Agenda" agenda) ("t" "All TODO" alltodo))) + thelist atitle new e key desc type match settings cmds gkey gdesc gsettings cnt) + (cond + ((eq org-mobile-agendas 'custom) + (setq thelist custom-list)) + ((eq org-mobile-agendas 'default) + (setq thelist default-list)) + ((eq org-mobile-agendas 'all) + (setq thelist custom-list) + (unless (assoc "t" thelist) (push '("t" "ALL TODO" alltodo) thelist)) + (unless (assoc "a" thelist) (push '("a" "Agenda" agenda) thelist))) + ((listp org-mobile-agendas) + (setq thelist (append custom-list default-list)) + (setq thelist (delq nil (mapcar (lambda (k) (assoc k thelist)) + org-mobile-agendas))))) + (while (setq e (pop thelist)) + (cond + ((stringp (cdr e)) + ;; this is a description entry - skip it + ) + ((eq (nth 2 e) 'search) + ;; Search view is interactive, skip + ) + ((memq (nth 2 e) '(todo-tree tags-tree occur-tree)) + ;; These are trees, not really agenda commands + ) + ((and (memq (nth 2 e) '(todo tags tags-todo)) + (or (null (nth 3 e)) + (not (string-match "\\S-" (nth 3 e))))) + ;; These would be interactive because the match string is empty + ) + ((memq (nth 2 e) '(agenda alltodo todo tags tags-todo)) + ;; a normal command + (setq key (car e) desc (nth 1 e) type (nth 2 e) match (nth 3 e) + settings (nth 4 e)) + (setq settings + (cons (list 'org-agenda-title-append + (concat "<after>KEYS=" key " TITLE: " + (if (and (stringp desc) (> (length desc) 0)) + desc (symbol-name type)) + "</after>")) + settings)) + (push (list type match settings) new)) + ((or (functionp (nth 2 e)) (symbolp (nth 2 e))) + ;; A user-defined function, which can do anything, so simply + ;; ignore it. + ) + (t + ;; a block agenda + (setq gkey (car e) gdesc (nth 1 e) gsettings (nth 3 e) cmds (nth 2 e)) + (setq cnt 0) + (while (setq e (pop cmds)) + (setq type (car e) match (nth 1 e) settings (nth 2 e)) + (setq atitle (if (string= "" gdesc) match gdesc)) + (setq settings (append gsettings settings)) + (setq settings + (cons (list 'org-agenda-title-append + (concat "<after>KEYS=" gkey "#" (number-to-string + (setq cnt (1+ cnt))) + " TITLE: " atitle "</after>")) + settings)) + (push (list type match settings) new))))) + (and new (list "X" "SUMO" (reverse new) + '((org-agenda-compact-blocks nil)))))) + +(defvar org-mobile-creating-agendas nil) +(defun org-mobile-write-agenda-for-mobile (file) + (let ((all (buffer-string)) in-date id pl prefix line app short m sexp) + (with-temp-file file + (org-mode) + (insert "#+READONLY\n") + (insert all) + (goto-char (point-min)) + (while (not (eobp)) + (cond + ((looking-at "[ \t]*$")) ; keep empty lines + ((looking-at "=+$") + ;; remove underlining + (delete-region (point) (point-at-eol))) + ((get-text-property (point) 'org-agenda-structural-header) + (setq in-date nil) + (setq app (get-text-property (point) 'org-agenda-title-append)) + (setq short (get-text-property (point) 'short-heading)) + (when (and short (looking-at ".+")) + (replace-match short nil t) + (beginning-of-line 1)) + (when app + (end-of-line 1) + (insert app) + (beginning-of-line 1)) + (insert "* ")) + ((get-text-property (point) 'org-agenda-date-header) + (setq in-date t) + (insert "** ")) + ((setq m (or (get-text-property (point) 'org-hd-marker) + (get-text-property (point) 'org-marker))) + (setq sexp (member (get-text-property (point) 'type) + '("diary" "sexp"))) + (if (setq pl (text-property-any (point) (point-at-eol) 'org-heading t)) + (progn + (setq prefix (org-trim (buffer-substring + (point) pl)) + line (org-trim (buffer-substring + pl + (point-at-eol)))) + (delete-region (point-at-bol) (point-at-eol)) + (insert line "<before>" prefix "</before>") + (beginning-of-line 1)) + (and (looking-at "[ \t]+") (replace-match ""))) + (insert (if in-date "*** " "** ")) + (end-of-line 1) + (insert "\n") + (unless sexp + (insert (org-agenda-get-some-entry-text + m 10 " " 'planning) + "\n") + (when (setq id + (if (bound-and-true-p + org-mobile-force-id-on-agenda-items) + (org-id-get m 'create) + (or (org-entry-get m "ID") + (org-mobile-get-outline-path-link m)))) + (insert " :PROPERTIES:\n :ORIGINAL_ID: " id + "\n :END:\n"))))) + (beginning-of-line 2)) + (push (cons "agendas.org" (md5 (buffer-string))) + org-mobile-checksum-files)) + (message "Agenda written to Org file %s" file))) + +(defun org-mobile-get-outline-path-link (pom) + (org-with-point-at pom + (concat "olp:" + (org-mobile-escape-olp (file-name-nondirectory buffer-file-name)) + ":" + (mapconcat 'org-mobile-escape-olp + (org-get-outline-path) + "/") + "/" + (org-mobile-escape-olp (nth 4 (org-heading-components)))))) + +(defun org-mobile-escape-olp (s) + (let ((table '(?: ?/))) + (org-link-escape s table))) + +(defun org-mobile-create-sumo-agenda () + "Create a file that contains all custom agenda views." + (interactive) + (let* ((file (expand-file-name "agendas.org" + org-mobile-directory)) + (file1 (if org-mobile-use-encryption + org-mobile-encryption-tempfile + file)) + (sumo (org-mobile-sumo-agenda-command)) + (org-agenda-custom-commands + (list (append sumo (list (list file1))))) + (org-mobile-creating-agendas t)) + (unless (file-writable-p file1) + (error "Cannot write to file %s" file1)) + (when sumo + (org-store-agenda-views)) + (when org-mobile-use-encryption + (org-mobile-encrypt-and-move file1 file) + (delete-file file1) + (org-mobile-cleanup-encryption-tempfile)))) + +(defun org-mobile-encrypt-and-move (infile outfile) + "Encrypt INFILE locally to INFILE_enc, then move it to OUTFILE. +We do this in two steps so that remote paths will work, even if the +encryption program does not understand them." + (let ((encfile (concat infile "_enc"))) + (org-mobile-encrypt-file infile encfile) + (when outfile + (copy-file encfile outfile 'ok-if-already-exists) + (delete-file encfile)))) + +(defun org-mobile-encrypt-file (infile outfile) + "Encrypt INFILE to OUTFILE, using `org-mobile-encryption-password'." + (shell-command + (format "openssl enc -md md5 -aes-256-cbc -salt -pass %s -in %s -out %s" + (shell-quote-argument (concat "pass:" + (org-mobile-encryption-password))) + (shell-quote-argument (expand-file-name infile)) + (shell-quote-argument (expand-file-name outfile))))) + +(defun org-mobile-decrypt-file (infile outfile) + "Decrypt INFILE to OUTFILE, using `org-mobile-encryption-password'." + (shell-command + (format "openssl enc -md md5 -d -aes-256-cbc -salt -pass %s -in %s -out %s" + (shell-quote-argument (concat "pass:" + (org-mobile-encryption-password))) + (shell-quote-argument (expand-file-name infile)) + (shell-quote-argument (expand-file-name outfile))))) + +(defun org-mobile-cleanup-encryption-tempfile () + "Remove the encryption tempfile if it exists." + (and (stringp org-mobile-encryption-tempfile) + (file-exists-p org-mobile-encryption-tempfile) + (delete-file org-mobile-encryption-tempfile))) + +(defun org-mobile-move-capture () + "Move the contents of the capture file to the inbox file. +Return a marker to the location where the new content has been added. +If nothing new has been added, return nil." + (interactive) + (let* ((encfile nil) + (capture-file (expand-file-name org-mobile-capture-file + org-mobile-directory)) + (inbox-buffer (find-file-noselect org-mobile-inbox-for-pull)) + (capture-buffer + (if (not org-mobile-use-encryption) + (find-file-noselect capture-file) + (org-mobile-cleanup-encryption-tempfile) + (setq encfile (concat org-mobile-encryption-tempfile "_enc")) + (copy-file capture-file encfile) + (org-mobile-decrypt-file encfile org-mobile-encryption-tempfile) + (find-file-noselect org-mobile-encryption-tempfile))) + (insertion-point (make-marker)) + not-empty content) + (with-current-buffer capture-buffer + (setq content (buffer-string)) + (setq not-empty (string-match "\\S-" content)) + (when not-empty + (set-buffer inbox-buffer) + (widen) + (goto-char (point-max)) + (or (bolp) (newline)) + (move-marker insertion-point + (prog1 (point) (insert content))) + (save-buffer) + (set-buffer capture-buffer) + (erase-buffer) + (save-buffer) + (org-mobile-update-checksum-for-capture-file (buffer-string)))) + (kill-buffer capture-buffer) + (when org-mobile-use-encryption + (org-mobile-encrypt-and-move org-mobile-encryption-tempfile + capture-file) + (org-mobile-cleanup-encryption-tempfile)) + (if not-empty insertion-point))) + +(defun org-mobile-update-checksum-for-capture-file (buffer-string) + "Find the checksum line and modify it to match BUFFER-STRING." + (let* ((file (expand-file-name "checksums.dat" org-mobile-directory)) + (buffer (find-file-noselect file))) + (when buffer + (with-current-buffer buffer + (when (re-search-forward (concat "\\([0-9a-fA-F]\\{30,\\}\\).*?" + (regexp-quote org-mobile-capture-file) + "[ \t]*$") nil t) + (goto-char (match-beginning 1)) + (delete-region (match-beginning 1) (match-end 1)) + (insert (md5 buffer-string)) + (save-buffer))) + (kill-buffer buffer)))) + +(defun org-mobile-apply (&optional beg end) + "Apply all change requests in the current buffer. +If BEG and END are given, only do this in that region." + (interactive) + (require 'org-archive) + (setq org-mobile-last-flagged-files nil) + (setq beg (or beg (point-min)) end (or end (point-max))) + + ;; Remove all Note IDs + (goto-char beg) + (while (re-search-forward "^\\*\\* Note ID: [-0-9A-F]+[ \t]*\n" end t) + (replace-match "")) + + ;; Find all the referenced entries, without making any changes yet + (let ((marker (make-marker)) + (bos-marker (make-marker)) + (end (move-marker (make-marker) end)) + (cnt-new 0) + (cnt-edit 0) + (cnt-flag 0) + (cnt-error 0) + buf-list + org-mobile-error) + + ;; Count the new captures + (goto-char beg) + (while (re-search-forward "^\\* \\(.*\\)" end t) + (and (>= (- (match-end 1) (match-beginning 1)) 2) + (not (equal (downcase (substring (match-string 1) 0 2)) "f(")) + (cl-incf cnt-new))) + + ;; Find and apply the edits + (goto-char beg) + (while (re-search-forward + "^\\*+[ \t]+F(\\([^():\n]*\\)\\(:\\([^()\n]*\\)\\)?)[ \t]+\\[\\[\\(\\(id\\|olp\\):\\([^]\n]+\\)\\)" end t) + (catch 'next + (let* ((action (match-string 1)) + (data (and (match-end 3) (match-string 3))) + (id-pos (condition-case msg + (org-mobile-locate-entry (match-string 4)) + (error (nth 1 msg)))) + (bos (line-beginning-position)) + (eos (save-excursion (org-end-of-subtree t t))) + (cmd (if (equal action "") + (let ((note (buffer-substring-no-properties + (line-beginning-position 2) eos))) + (lambda (_data _old _new) + (cl-incf cnt-flag) + (org-toggle-tag "FLAGGED" 'on) + (org-entry-put + nil "THEFLAGGINGNOTE" + (replace-regexp-in-string "\n" "\\\\n" note)))) + (cl-incf cnt-edit) + (cdr (assoc action org-mobile-action-alist)))) + ;; Do not take notes interactively. + (org-inhibit-logging 'note) + old new) + + (goto-char bos) + (when (and (markerp id-pos) + (not (member (marker-buffer id-pos) buf-list))) + (org-mobile-timestamp-buffer (marker-buffer id-pos)) + (push (marker-buffer id-pos) buf-list)) + (unless (markerp id-pos) + (goto-char (+ 2 (point-at-bol))) + (if (stringp id-pos) + (insert id-pos " ") + (insert "BAD REFERENCE ")) + (cl-incf cnt-error) + (throw 'next t)) + (unless cmd + (insert "BAD FLAG ") + (cl-incf cnt-error) + (throw 'next t)) + (move-marker bos-marker (point)) + (if (re-search-forward "^** Old value[ \t]*$" eos t) + (setq old (buffer-substring + (1+ (match-end 0)) + (progn (outline-next-heading) (point))))) + (if (re-search-forward "^** New value[ \t]*$" eos t) + (setq new (buffer-substring + (1+ (match-end 0)) + (progn (outline-next-heading) + (if (eobp) (org-back-over-empty-lines)) + (point))))) + (setq old (org-string-nw-p old)) + (setq new (org-string-nw-p new)) + (unless (equal data "body") + (setq new (and new (org-trim new))) + (setq old (and old (org-trim old)))) + (goto-char (+ 2 bos-marker)) + ;; Remember this place so that we can return + (move-marker marker (point)) + (setq org-mobile-error nil) + (condition-case msg + (org-with-point-at id-pos + (funcall cmd data old new) + (unless (member data '("delete" "archive" "archive-sibling" + "addheading")) + (when (member "FLAGGED" (org-get-tags)) + (add-to-list 'org-mobile-last-flagged-files + (buffer-file-name))))) + (error (setq org-mobile-error msg))) + (when org-mobile-error + (pop-to-buffer-same-window (marker-buffer marker)) + (goto-char marker) + (cl-incf cnt-error) + (insert (if (stringp (nth 1 org-mobile-error)) + (nth 1 org-mobile-error) + "EXECUTION FAILED") + " ") + (throw 'next t)) + ;; If we get here, the action has been applied successfully + ;; So remove the entry + (goto-char bos-marker) + (delete-region (point) (org-end-of-subtree t t))))) + (save-buffer) + (move-marker marker nil) + (move-marker end nil) + (message "%d new, %d edits, %d flags, %d errors" + cnt-new cnt-edit cnt-flag cnt-error) + (sit-for 1))) + +(defun org-mobile-timestamp-buffer (buf) + "Time stamp buffer BUF, just to make sure its checksum will change." + (with-current-buffer buf + (save-excursion + (save-restriction + (widen) + (goto-char (point-min)) + (if (re-search-forward + "^\\([ \t]*\\)#\\+LAST_MOBILE_CHANGE:.*\n?" nil t) + (progn + (goto-char (match-end 1)) + (delete-region (point) (match-end 0))) + (if (looking-at ".*?-\\*-.*-\\*-") + (forward-line 1))) + (insert "#+LAST_MOBILE_CHANGE: " + (format-time-string "%Y-%m-%d %T") "\n"))))) + +(defun org-mobile-smart-read () + "Parse the entry at point for shortcuts and expand them. +These shortcuts are meant for fast and easy typing on the limited +keyboards of a mobile device. Below we show a list of the shortcuts +currently implemented. + +The entry is expected to contain an inactive time stamp indicating when +the entry was created. When setting dates and +times (for example for deadlines), the time strings are interpreted +relative to that creation date. +Abbreviations are expected to take up entire lines, just because it is so +easy to type RET on a mobile device. Abbreviations start with one or two +letters, followed immediately by a dot and then additional information. +Generally the entire shortcut line is removed after action have been taken. +Time stamps will be constructed using `org-read-date'. So for example a +line \"dd. 2tue\" will set a deadline on the second Tuesday after the +creation date. + +Here are the shortcuts currently implemented: + +dd. string set deadline +ss. string set scheduling +tt. string set time tamp, here. +ti. string set inactive time + +tg. tag1 tag2 tag3 set all these tags, change case where necessary +td. kwd set this todo keyword, change case where necessary + +FIXME: Hmmm, not sure if we can make his work against the +auto-correction feature. Needs a bit more thinking. So this function +is currently a noop.") + +(defun org-mobile-locate-entry (link) + (if (string-match "\\`id:\\(.*\\)$" link) + (org-id-find (match-string 1 link) 'marker) + (if (not (string-match "\\`olp:\\(.*?\\):\\(.*\\)$" link)) + ; not found with path, but maybe it is to be inserted + ; in top level of the file? + (if (not (string-match "\\`olp:\\(.*?\\)$" link)) + nil + (let ((file (match-string 1 link))) + (setq file (org-link-unescape file)) + (setq file (expand-file-name file org-directory)) + (save-excursion + (find-file file) + (goto-char (point-max)) + (newline) + (goto-char (point-max)) + (point-marker)))) + (let ((file (match-string 1 link)) + (path (match-string 2 link))) + (setq file (org-link-unescape file)) + (setq file (expand-file-name file org-directory)) + (setq path (mapcar 'org-link-unescape + (org-split-string path "/"))) + (org-find-olp (cons file path)))))) + +(defun org-mobile-edit (what old new) + "Edit item WHAT in the current entry by replacing OLD with NEW. +WHAT can be \"heading\", \"todo\", \"tags\", \"priority\", or \"body\". +The edit only takes place if the current value is equal (except for +white space) the OLD. If this is so, OLD will be replace by NEW +and the command will return t. If something goes wrong, a string will +be returned that indicates what went wrong." + (let (current old1 new1 level) + (if (stringp what) (setq what (intern what))) + + (cond + + ((memq what '(todo todostate)) + (setq current (org-get-todo-state)) + (cond + ((equal new "DONEARCHIVE") + (org-todo 'done) + (org-archive-subtree-default)) + ((equal new current) t) ; nothing needs to be done + ((or (equal current old) + (eq org-mobile-force-mobile-change t) + (memq 'todo org-mobile-force-mobile-change)) + (org-todo (or new 'none)) t) + (t (error "State before change was expected as \"%s\", but is \"%s\"" + old current)))) + + ((eq what 'tags) + (setq current (org-get-tags) + new1 (and new (org-split-string new ":+")) + old1 (and old (org-split-string old ":+"))) + (cond + ((org-mobile-tags-same-p current new1) t) ; no change needed + ((or (org-mobile-tags-same-p current old1) + (eq org-mobile-force-mobile-change t) + (memq 'tags org-mobile-force-mobile-change)) + (org-set-tags-to new1) t) + (t (error "Tags before change were expected as \"%s\", but are \"%s\"" + (or old "") (or current ""))))) + + ((eq what 'priority) + (let ((case-fold-search nil)) + (when (looking-at org-complex-heading-regexp) + (let ((current (and (match-end 3) (substring (match-string 3) 2 3)))) + (cond + ((equal current new) t) ;no action required + ((or (equal current old) + (eq org-mobile-force-mobile-change t) + (memq 'tags org-mobile-force-mobile-change)) + (org-priority (and new (string-to-char new)))) + (t (error "Priority was expected to be %s, but is %s" + old current))))))) + + ((eq what 'heading) + (let ((case-fold-search nil)) + (when (looking-at org-complex-heading-regexp) + (let ((current (match-string 4))) + (cond + ((equal current new) t) ;no action required + ((or (equal current old) + (eq org-mobile-force-mobile-change t) + (memq 'heading org-mobile-force-mobile-change)) + (goto-char (match-beginning 4)) + (insert new) + (delete-region (point) (+ (point) (length current))) + (org-set-tags nil 'align)) + (t (error "Heading changed in MobileOrg and on the computer"))))))) + + ((eq what 'addheading) + (if (org-at-heading-p) ; if false we are in top-level of file + (progn + ;; Workaround a `org-insert-heading-respect-content' bug + ;; which prevents correct insertion when point is invisible + (org-show-subtree) + (end-of-line 1) + (org-insert-heading-respect-content t) + (org-demote)) + (beginning-of-line) + (insert "* ")) + (insert new)) + + ((eq what 'refile) + (org-copy-subtree) + (org-with-point-at (org-mobile-locate-entry new) + (if (org-at-heading-p) ; if false we are in top-level of file + (progn + (setq level (org-get-valid-level (funcall outline-level) 1)) + (org-end-of-subtree t t) + (org-paste-subtree level)) + (org-paste-subtree 1))) + (org-cut-subtree)) + + ((eq what 'delete) + (org-cut-subtree)) + + ((eq what 'archive) + (org-archive-subtree)) + + ((eq what 'archive-sibling) + (org-archive-to-archive-sibling)) + + ((eq what 'body) + (setq current (buffer-substring (min (1+ (point-at-eol)) (point-max)) + (save-excursion (outline-next-heading) + (point)))) + (if (not (string-match "\\S-" current)) (setq current nil)) + (cond + ((org-mobile-bodies-same-p current new) t) ; no action necessary + ((or (org-mobile-bodies-same-p current old) + (eq org-mobile-force-mobile-change t) + (memq 'body org-mobile-force-mobile-change)) + (save-excursion + (end-of-line 1) + (insert "\n" new) + (or (bolp) (insert "\n")) + (delete-region (point) (progn (org-back-to-heading t) + (outline-next-heading) + (point)))) + t) + (t (error "Body was changed in MobileOrg and on the computer"))))))) + +(defun org-mobile-tags-same-p (list1 list2) + "Are the two tag lists the same?" + (not (or (org-delete-all list1 list2) + (org-delete-all list2 list1)))) + +(defun org-mobile-bodies-same-p (a b) + "Compare if A and B are visually equal strings. +We first remove leading and trailing white space from the entire strings. +Then we split the strings into lines and remove leading/trailing whitespace +from each line. Then we compare. +A and B must be strings or nil." + (cond + ((and (not a) (not b)) t) + ((or (not a) (not b)) nil) + (t (setq a (org-trim a) b (org-trim b)) + (setq a (mapconcat 'identity (org-split-string a "[ \t]*\n[ \t]*") "\n")) + (setq b (mapconcat 'identity (org-split-string b "[ \t]*\n[ \t]*") "\n")) + (equal a b)))) + +(provide 'org-mobile) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-mobile.el ends here diff --git a/elpa/org-9.1.14/org-mouse.el b/elpa/org-9.1.14/org-mouse.el new file mode 100644 index 00000000..5a10b59b --- /dev/null +++ b/elpa/org-9.1.14/org-mouse.el @@ -0,0 +1,1110 @@ +;;; org-mouse.el --- Better mouse support for Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2006-2018 Free Software Foundation, Inc. + +;; Author: Piotr Zielinski <piotr dot zielinski at gmail dot com> +;; Maintainer: Carsten Dominik <carsten at orgmode dot org> + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: +;; +;; Org-mouse provides mouse support for org-mode. +;; +;; https://orgmode.org +;; +;; Org mouse implements the following features: +;; * following links with the left mouse button +;; * subtree expansion/collapse (org-cycle) with the left mouse button +;; * several context menus on the right mouse button: +;; + general text +;; + headlines +;; + timestamps +;; + priorities +;; + links +;; + tags +;; * promoting/demoting/moving subtrees with mouse-3 +;; + if the drag starts and ends in the same line then promote/demote +;; + otherwise move the subtree +;; +;; Use +;; --- +;; +;; To use this package, put the following line in your .emacs: +;; +;; (require 'org-mouse) +;; + +;; FIXME: +;; + deal with folding / unfolding issues + +;; TODO (This list is only theoretical, if you'd like to have some +;; feature implemented or a bug fix please send me an email, even if +;; something similar appears in the list below. This will help me get +;; the priorities right.): +;; +;; + org-store-link, insert link +;; + org tables +;; + occur with the current word/tag (same menu item) +;; + ctrl-c ctrl-c, for example, renumber the current list +;; + internal links + +;; Please email the maintainer with new feature suggestions / bugs + +;; History: +;; +;; Since version 5.10: Changes are listed in the general Org docs. +;; +;; Version 5.09;; + Version number synchronization with Org mode. +;; +;; Version 0.25 +;; + made compatible with Org 4.70 (thanks to Carsten for the patch) +;; +;; Version 0.24 +;; + minor changes to the table menu +;; +;; Version 0.23 +;; + preliminary support for tables and calculation marks +;; + context menu support for org-agenda-undo & org-sort-entries +;; +;; Version 0.22 +;; + handles undo support for the agenda buffer (requires Org >=4.58) +;; +;; Version 0.21 +;; + selected text activates its context menu +;; + shift-middleclick or right-drag inserts the text from the clipboard in the form of a link +;; +;; Version 0.20 +;; + the new "TODO Status" submenu replaces the "Cycle TODO" menu item +;; + the TODO menu can now list occurrences of a specific TODO keyword +;; + #+STARTUP line is now recognized +;; +;; Version 0.19 +;; + added support for dragging URLs to the org-buffer +;; +;; Version 0.18 +;; + added support for agenda blocks +;; +;; Version 0.17 +;; + toggle checkboxes with a single click +;; +;; Version 0.16 +;; + added support for checkboxes +;; +;; Version 0.15 +;; + Org now works with the Agenda buffer as well +;; +;; Version 0.14 +;; + added a menu option that converts plain list items to outline items +;; +;; Version 0.13 +;; + "Insert Heading" now inserts a sibling heading if the point is +;; on "***" and a child heading otherwise +;; +;; Version 0.12 +;; + compatible with Emacs 21 +;; + custom agenda commands added to the main menu +;; + moving trees should now work between windows in the same frame +;; +;; Version 0.11 +;; + fixed org-mouse-at-link (thanks to Carsten) +;; + removed [follow-link] bindings +;; +;; Version 0.10 +;; + added a menu option to remove highlights +;; + compatible with Org 4.21 now +;; +;; Version 0.08: +;; + trees can be moved/promoted/demoted by dragging with the right +;; mouse button (mouse-3) +;; + small changes in the above function +;; +;; Versions 0.01 -- 0.07: (I don't remember) + +;;; Code: + +(require 'org) +(require 'cl-lib) + +(defvar org-agenda-allow-remote-undo) +(defvar org-agenda-undo-list) +(defvar org-agenda-custom-commands) +(declare-function org-agenda-change-all-lines "org-agenda" + (newhead hdmarker &optional fixface just-this)) +(declare-function org-verify-change-for-undo "org-agenda" (l1 l2)) +(declare-function org-apply-on-list "org-list" (function init-value &rest args)) +(declare-function org-agenda-earlier "org-agenda" (arg)) +(declare-function org-agenda-later "org-agenda" (arg)) + +(defvar org-mouse-main-buffer nil + "Active buffer for mouse operations.") +(defvar org-mouse-plain-list-regexp "\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) " + "Regular expression that matches a plain list.") +(defvar org-mouse-direct t + "Internal variable indicating whether the current action is direct. + +If t, then the current action has been invoked directly through the buffer +it is intended to operate on. If nil, then the action has been invoked +indirectly, for example, through the agenda buffer.") + +(defgroup org-mouse nil + "Mouse support for org-mode." + :tag "Org Mouse" + :group 'org) + +(defcustom org-mouse-punctuation ":" + "Punctuation used when inserting text by drag and drop." + :group 'org-mouse + :type 'string) + +(defcustom org-mouse-features + '(context-menu yank-link activate-stars activate-bullets activate-checkboxes) + "The features of org-mouse that should be activated. +Changing this variable requires a restart of Emacs to get activated." + :group 'org-mouse + :type '(set :greedy t + (const :tag "Mouse-3 shows context menu" context-menu) + (const :tag "C-mouse-1 and mouse-3 move trees" move-tree) + (const :tag "S-mouse-2 and drag-mouse-3 yank link" yank-link) + (const :tag "Activate headline stars" activate-stars) + (const :tag "Activate item bullets" activate-bullets) + (const :tag "Activate checkboxes" activate-checkboxes))) + +(defun org-mouse-re-search-line (regexp) + "Search the current line for a given regular expression." + (beginning-of-line) + (re-search-forward regexp (point-at-eol) t)) + +(defun org-mouse-end-headline () + "Go to the end of current headline (ignoring tags)." + (interactive) + (end-of-line) + (skip-chars-backward "\t ") + (when (looking-back ":[A-Za-z]+:" (line-beginning-position)) + (skip-chars-backward ":A-Za-z") + (skip-chars-backward "\t "))) + +(defvar-local org-mouse-context-menu-function nil + "Function to create the context menu. +The value of this variable is the function invoked by +`org-mouse-context-menu' as the context menu.") + +(defun org-mouse-show-context-menu (event prefix) + "Invoke the context menu. + +If the value of `org-mouse-context-menu-function' is a function, then +this function is called. Otherwise, the current major mode menu is used." + (interactive "@e \nP") + (if (and (= (event-click-count event) 1) + (or (not mark-active) + (sit-for (/ double-click-time 1000.0)))) + (progn + (select-window (posn-window (event-start event))) + (when (not (org-mouse-mark-active)) + (goto-char (posn-point (event-start event))) + (when (not (eolp)) (save-excursion (run-hooks 'post-command-hook))) + (sit-for 0)) + (if (functionp org-mouse-context-menu-function) + (funcall org-mouse-context-menu-function event) + (if (fboundp 'mouse-menu-major-mode-map) + (popup-menu (mouse-menu-major-mode-map) event prefix) + (with-no-warnings ; don't warn about fallback, obsolete since 23.1 + (mouse-major-mode-menu event prefix))))) + (setq this-command 'mouse-save-then-kill) + (mouse-save-then-kill event))) + +(defun org-mouse-line-position () + "Return `:beginning' or `:middle' or `:end', depending on the point position. + +If the point is at the end of the line, return `:end'. +If the point is separated from the beginning of the line only by white +space and *'s (`org-mouse-bolp'), return `:beginning'. Otherwise, +return `:middle'." + (cond + ((eolp) :end) + ((org-mouse-bolp) :beginning) + (t :middle))) + +(defun org-mouse-empty-line () + "Return non-nil iff the line contains only white space." + (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))) + +(defun org-mouse-next-heading () + "Go to the next heading. +If there is none, ensure that the point is at the beginning of an empty line." + (unless (outline-next-heading) + (beginning-of-line) + (unless (org-mouse-empty-line) + (end-of-line) + (newline)))) + +(defun org-mouse-insert-heading () + "Insert a new heading, as `org-insert-heading'. + +If the point is at the :beginning (`org-mouse-line-position') of the line, +insert the new heading before the current line. Otherwise, insert it +after the current heading." + (interactive) + (cl-case (org-mouse-line-position) + (:beginning (beginning-of-line) + (org-insert-heading)) + (t (org-mouse-next-heading) + (org-insert-heading)))) + +(defun org-mouse-timestamp-today (&optional shift units) + "Change the timestamp into SHIFT UNITS in the future. + +For the acceptable UNITS, see `org-timestamp-change'." + (interactive) + (org-time-stamp nil) + (when shift (org-timestamp-change shift units))) + +(defun org-mouse-keyword-menu (keywords function &optional selected itemformat) + "A helper function. + +Returns a menu fragment consisting of KEYWORDS. When a keyword +is selected by the user, FUNCTION is called with the selected +keyword as the only argument. + +If SELECTED is nil, then all items are normal menu items. If +SELECTED is a function, then each item is a checkbox, which is +enabled for a given keyword iff (funcall SELECTED keyword) return +non-nil. If SELECTED is neither nil nor a function, then the +items are radio buttons. A radio button is enabled for the +keyword `equal' to SELECTED. + +ITEMFORMAT governs formatting of the elements of KEYWORDS. If it +is a function, it is invoked with the keyword as the only +argument. If it is a string, it is interpreted as the format +string to (format ITEMFORMAT keyword). If it is neither a string +nor a function, elements of KEYWORDS are used directly." + (mapcar + `(lambda (keyword) + (vector (cond + ((functionp ,itemformat) (funcall ,itemformat keyword)) + ((stringp ,itemformat) (format ,itemformat keyword)) + (t keyword)) + (list 'funcall ,function keyword) + :style (cond + ((null ,selected) t) + ((functionp ,selected) 'toggle) + (t 'radio)) + :selected (if (functionp ,selected) + (and (funcall ,selected keyword) t) + (equal ,selected keyword)))) + keywords)) + +(defun org-mouse-remove-match-and-spaces () + "Remove the match, make just one space around the point." + (interactive) + (replace-match "") + (just-one-space)) + +(defvar org-mouse-rest) +(defun org-mouse-replace-match-and-surround + (_newtext &optional _fixedcase _literal _string subexp) + "The same as `replace-match', but surrounds the replacement with spaces." + (apply #'replace-match org-mouse-rest) + (save-excursion + (goto-char (match-beginning (or subexp 0))) + (just-one-space) + (goto-char (match-end (or subexp 0))) + (just-one-space))) + +(defun org-mouse-keyword-replace-menu (keywords &optional group itemformat + nosurround) + "A helper function. + +Returns a menu fragment consisting of KEYWORDS. When a keyword +is selected, group GROUP of the current match is replaced by the +keyword. The method ensures that both ends of the replacement +are separated from the rest of the text in the buffer by +individual spaces (unless NOSURROUND is non-nil). + +The final entry of the menu is always \"None\", which removes the +match. + +ITEMFORMAT governs formatting of the elements of KEYWORDS. If it +is a function, it is invoked with the keyword as the only +argument. If it is a string, it is interpreted as the format +string to (format ITEMFORMAT keyword). If it is neither a string +nor a function, elements of KEYWORDS are used directly." + (setq group (or group 0)) + (let ((replace (org-mouse-match-closure + (if nosurround 'replace-match + 'org-mouse-replace-match-and-surround)))) + (append + (org-mouse-keyword-menu + keywords + `(lambda (keyword) (funcall ,replace keyword t t nil ,group)) + (match-string group) + itemformat) + `(["None" org-mouse-remove-match-and-spaces + :style radio + :selected ,(not (member (match-string group) keywords))])))) + +(defun org-mouse-show-headlines () + "Change the visibility of the current org buffer to only show headlines." + (interactive) + (let ((this-command 'org-cycle) + (last-command 'org-cycle) + (org-cycle-global-status nil)) + (org-cycle '(4)) + (org-cycle '(4)))) + +(defun org-mouse-show-overview () + "Change visibility of current org buffer to first-level headlines only." + (interactive) + (let ((org-cycle-global-status nil)) + (org-cycle '(4)))) + +(defun org-mouse-set-priority (priority) + "Set the priority of the current headline to PRIORITY." + (org-priority priority)) + +(defvar org-mouse-priority-regexp "\\[#\\([A-Z]\\)\\]" + "Regular expression matching the priority indicator. +Differs from `org-priority-regexp' in that it doesn't contain the +leading `.*?'.") + +(defun org-mouse-get-priority (&optional default) + "Return the priority of the current headline. +DEFAULT is returned if no priority is given in the headline." + (save-excursion + (if (org-mouse-re-search-line org-mouse-priority-regexp) + (match-string 1) + (when default (char-to-string org-default-priority))))) + +(defun org-mouse-delete-timestamp () + "Deletes the current timestamp as well as the preceding keyword. +SCHEDULED: or DEADLINE: or ANYTHINGLIKETHIS:" + (when (or (org-at-date-range-p) (org-at-timestamp-p 'lax)) + (replace-match "") ;delete the timestamp + (skip-chars-backward " :A-Z") + (when (looking-at " *[A-Z][A-Z]+:") + (replace-match "")))) + +(defun org-mouse-looking-at (regexp skipchars &optional movechars) + (save-excursion + (let ((point (point))) + (if (looking-at regexp) t + (skip-chars-backward skipchars) + (forward-char (or movechars 0)) + (when (looking-at regexp) + (> (match-end 0) point)))))) + +(defun org-mouse-priority-list () + (cl-loop for priority from ?A to org-lowest-priority + collect (char-to-string priority))) + +(defun org-mouse-todo-menu (state) + "Create the menu with TODO keywords." + (append + (let ((kwds org-todo-keywords-1)) + (org-mouse-keyword-menu + kwds + `(lambda (kwd) (org-todo kwd)) + (lambda (kwd) (equal state kwd)))))) + +(defun org-mouse-tag-menu () ;todo + "Create the tags menu." + (append + (let ((tags (org-get-tags))) + (org-mouse-keyword-menu + (sort (mapcar 'car (org-get-buffer-tags)) 'string-lessp) + `(lambda (tag) + (org-mouse-set-tags + (sort (if (member tag (quote ,tags)) + (delete tag (quote ,tags)) + (cons tag (quote ,tags))) + 'string-lessp))) + `(lambda (tag) (member tag (quote ,tags))) + )) + '("--" + ["Align Tags Here" (org-set-tags nil t) t] + ["Align Tags in Buffer" (org-set-tags t t) t] + ["Set Tags ..." (org-set-tags) t]))) + +(defun org-mouse-set-tags (tags) + (save-excursion + ;; remove existing tags first + (beginning-of-line) + (when (org-mouse-re-search-line ":\\(\\([A-Za-z_]+:\\)+\\)") + (replace-match "")) + + ;; set new tags if any + (when tags + (end-of-line) + (insert " :" (mapconcat 'identity tags ":") ":") + (org-set-tags nil t)))) + +(defun org-mouse-insert-checkbox () + (interactive) + (and (org-at-item-p) + (goto-char (match-end 0)) + (unless (org-at-item-checkbox-p) + (delete-horizontal-space) + (insert " [ ] ")))) + +(defun org-mouse-agenda-type (type) + (pcase type + (`tags "Tags: ") + (`todo "TODO: ") + (`tags-tree "Tags tree: ") + (`todo-tree "TODO tree: ") + (`occur-tree "Occur tree: ") + (_ "Agenda command ???"))) + +(defun org-mouse-list-options-menu (alloptions &optional function) + (let ((options (save-match-data + (split-string (match-string-no-properties 1))))) + (print options) + (cl-loop for name in alloptions + collect + (vector name + `(progn + (replace-match + (mapconcat 'identity + (sort (if (member ',name ',options) + (delete ',name ',options) + (cons ',name ',options)) + 'string-lessp) + " ") + nil nil nil 1) + (when (functionp ',function) (funcall ',function))) + :style 'toggle + :selected (and (member name options) t))))) + +(defun org-mouse-clip-text (text maxlength) + (if (> (length text) maxlength) + (concat (substring text 0 (- maxlength 3)) "...") + text)) + +(defun org-mouse-popup-global-menu () + (popup-menu + `("Main Menu" + ["Show Overview" org-mouse-show-overview t] + ["Show Headlines" org-mouse-show-headlines t] + ["Show All" outline-show-all t] + ["Remove Highlights" org-remove-occur-highlights + :visible org-occur-highlights] + "--" + ["Check Deadlines" + (if (functionp 'org-check-deadlines-and-todos) + (org-check-deadlines-and-todos org-deadline-warning-days) + (org-check-deadlines org-deadline-warning-days)) t] + ["Check TODOs" org-show-todo-tree t] + ("Check Tags" + ,@(org-mouse-keyword-menu + (sort (mapcar 'car (org-get-buffer-tags)) 'string-lessp) + #'(lambda (tag) (org-tags-sparse-tree nil tag))) + "--" + ["Custom Tag ..." org-tags-sparse-tree t]) + ["Check Phrase ..." org-occur] + "--" + ["Display Agenda" org-agenda-list t] + ["Display TODO List" org-todo-list t] + ("Display Tags" + ,@(org-mouse-keyword-menu + (sort (mapcar 'car (org-get-buffer-tags)) 'string-lessp) + #'(lambda (tag) (org-tags-view nil tag))) + "--" + ["Custom Tag ..." org-tags-view t]) + ["Display Calendar" org-goto-calendar t] + "--" + ,@(org-mouse-keyword-menu + (mapcar 'car org-agenda-custom-commands) + #'(lambda (key) + (eval `(org-agenda nil (string-to-char ,key)))) + nil + #'(lambda (key) + (let ((entry (assoc key org-agenda-custom-commands))) + (org-mouse-clip-text + (cond + ((stringp (nth 1 entry)) (nth 1 entry)) + ((stringp (nth 2 entry)) + (concat (org-mouse-agenda-type (nth 1 entry)) + (nth 2 entry))) + (t "Agenda Command `%s'")) + 30)))) + "--" + ["Delete Blank Lines" delete-blank-lines + :visible (org-mouse-empty-line)] + ["Insert Checkbox" org-mouse-insert-checkbox + :visible (and (org-at-item-p) (not (org-at-item-checkbox-p)))] + ["Insert Checkboxes" + (org-mouse-for-each-item 'org-mouse-insert-checkbox) + :visible (and (org-at-item-p) (not (org-at-item-checkbox-p)))] + ["Plain List to Outline" org-mouse-transform-to-outline + :visible (org-at-item-p)]))) + +(defun org-mouse-get-context (contextlist context) + (let ((contextdata (assq context contextlist))) + (when contextdata + (save-excursion + (goto-char (nth 1 contextdata)) + (re-search-forward ".*" (nth 2 contextdata)))))) + +(defun org-mouse-for-each-item (funct) + ;; Functions called by `org-apply-on-list' need an argument. + (let ((wrap-fun (lambda (_) (funcall funct)))) + (when (ignore-errors (goto-char (org-in-item-p))) + (save-excursion (org-apply-on-list wrap-fun nil))))) + +(defun org-mouse-bolp () + "Return true if there only spaces, tabs, and `*' before point. +This means, between the beginning of line and the point." + (save-excursion + (skip-chars-backward " \t*") (bolp))) + +(defun org-mouse-insert-item (text) + (cl-case (org-mouse-line-position) + (:beginning ; insert before + (beginning-of-line) + (looking-at "[ \t]*") + (open-line 1) + (indent-to-column (- (match-end 0) (match-beginning 0))) + (insert "+ ")) + (:middle ; insert after + (end-of-line) + (newline t) + (indent-relative) + (insert "+ ")) + (:end ; insert text here + (skip-chars-backward " \t") + (kill-region (point) (point-at-eol)) + (unless (looking-back org-mouse-punctuation (line-beginning-position)) + (insert (concat org-mouse-punctuation " "))))) + (insert text) + (beginning-of-line)) + +(defadvice dnd-insert-text (around org-mouse-dnd-insert-text activate) + (if (derived-mode-p 'org-mode) + (org-mouse-insert-item text) + ad-do-it)) + +(defadvice dnd-open-file (around org-mouse-dnd-open-file activate) + (if (derived-mode-p 'org-mode) + (org-mouse-insert-item uri) + ad-do-it)) + +(defun org-mouse-match-closure (function) + (let ((match (match-data t))) + `(lambda (&rest rest) + (save-match-data + (set-match-data ',match) + (apply ',function rest))))) + +(defun org-mouse-yank-link (click) + (interactive "e") + ;; Give temporary modes such as isearch a chance to turn off. + (run-hooks 'mouse-leave-buffer-hook) + (mouse-set-point click) + (setq mouse-selection-click-count 0) + (delete-horizontal-space) + (insert-for-yank (concat " [[" (current-kill 0) "]] "))) + +(defun org-mouse-context-menu (&optional event) + (let* ((stamp-prefixes (list org-deadline-string org-scheduled-string)) + (contextlist (org-context)) + (get-context (lambda (context) (org-mouse-get-context contextlist context)))) + (cond + ((org-mouse-mark-active) + (let ((region-string (buffer-substring (region-beginning) (region-end)))) + (popup-menu + `(nil + ["Sparse Tree" (org-occur ',region-string)] + ["Find in Buffer" (occur ',region-string)] + ["Grep in Current Dir" + (grep (format "grep -rnH -e '%s' *" ',region-string))] + ["Grep in Parent Dir" + (grep (format "grep -rnH -e '%s' ../*" ',region-string))] + "--" + ["Convert to Link" + (progn (save-excursion (goto-char (region-beginning)) (insert "[[")) + (save-excursion (goto-char (region-end)) (insert "]]")))] + ["Insert Link Here" (org-mouse-yank-link ',event)])))) + ((save-excursion (beginning-of-line) (looking-at "[ \t]*#\\+STARTUP: \\(.*\\)")) + (popup-menu + `(nil + ,@(org-mouse-list-options-menu (mapcar 'car org-startup-options) + 'org-mode-restart)))) + ((or (eolp) + (and (looking-at "\\( \\|\t\\)\\(+:[0-9a-zA-Z_:]+\\)?\\( \\|\t\\)+$") + (looking-back " \\|\t" (- (point) 2) + (line-beginning-position)))) + (org-mouse-popup-global-menu)) + ((funcall get-context :checkbox) + (popup-menu + '(nil + ["Toggle" org-toggle-checkbox t] + ["Remove" org-mouse-remove-match-and-spaces t] + "" + ["All Clear" (org-mouse-for-each-item + (lambda () + (when (save-excursion (org-at-item-checkbox-p)) + (replace-match "[ ] "))))] + ["All Set" (org-mouse-for-each-item + (lambda () + (when (save-excursion (org-at-item-checkbox-p)) + (replace-match "[X] "))))] + ["All Toggle" (org-mouse-for-each-item 'org-toggle-checkbox) t] + ["All Remove" (org-mouse-for-each-item + (lambda () + (when (save-excursion (org-at-item-checkbox-p)) + (org-mouse-remove-match-and-spaces))))] + ))) + ((and (org-mouse-looking-at "\\b\\w+" "a-zA-Z0-9_") + (member (match-string 0) org-todo-keywords-1)) + (popup-menu + `(nil + ,@(org-mouse-todo-menu (match-string 0)) + "--" + ["Check TODOs" org-show-todo-tree t] + ["List all TODO keywords" org-todo-list t] + [,(format "List only %s" (match-string 0)) + (org-todo-list (match-string 0)) t] + ))) + ((and (org-mouse-looking-at "\\b[A-Z]+:" "A-Z") + (member (match-string 0) stamp-prefixes)) + (popup-menu + `(nil + ,@(org-mouse-keyword-replace-menu stamp-prefixes) + "--" + ["Check Deadlines" org-check-deadlines t] + ))) + ((org-mouse-looking-at org-mouse-priority-regexp "[]A-Z#") ; priority + (popup-menu `(nil ,@(org-mouse-keyword-replace-menu + (org-mouse-priority-list) 1 "Priority %s" t)))) + ((funcall get-context :link) + (popup-menu + '(nil + ["Open" org-open-at-point t] + ["Open in Emacs" (org-open-at-point t) t] + "--" + ["Copy link" (org-kill-new (match-string 0))] + ["Cut link" + (progn + (kill-region (match-beginning 0) (match-end 0)) + (just-one-space))] + "--" + ["Grep for TODOs" + (grep (format "grep -nH -i 'todo\\|fixme' %s*" (match-string 2)))] + ; ["Paste file link" ((insert "file:") (yank))] + ))) + ((org-mouse-looking-at ":\\([A-Za-z0-9_]+\\):" "A-Za-z0-9_" -1) ;tags + (popup-menu + `(nil + [,(format-message "Display `%s'" (match-string 1)) + (org-tags-view nil ,(match-string 1))] + [,(format-message "Sparse Tree `%s'" (match-string 1)) + (org-tags-sparse-tree nil ,(match-string 1))] + "--" + ,@(org-mouse-tag-menu)))) + ((org-at-timestamp-p 'lax) + (popup-menu + '(nil + ["Show Day" org-open-at-point t] + ["Change Timestamp" org-time-stamp t] + ["Delete Timestamp" (org-mouse-delete-timestamp) t] + ["Compute Time Range" org-evaluate-time-range (org-at-date-range-p)] + "--" + ["Set for Today" org-mouse-timestamp-today] + ["Set for Tomorrow" (org-mouse-timestamp-today 1 'day)] + ["Set in 1 Week" (org-mouse-timestamp-today 7 'day)] + ["Set in 2 Weeks" (org-mouse-timestamp-today 14 'day)] + ["Set in a Month" (org-mouse-timestamp-today 1 'month)] + "--" + ["+ 1 Day" (org-timestamp-change 1 'day)] + ["+ 1 Week" (org-timestamp-change 7 'day)] + ["+ 1 Month" (org-timestamp-change 1 'month)] + "--" + ["- 1 Day" (org-timestamp-change -1 'day)] + ["- 1 Week" (org-timestamp-change -7 'day)] + ["- 1 Month" (org-timestamp-change -1 'month)]))) + ((funcall get-context :table-special) + (let ((mdata (match-data))) + (cl-incf (car mdata) 2) + (store-match-data mdata)) + (message "match: %S" (match-string 0)) + (popup-menu `(nil ,@(org-mouse-keyword-replace-menu + '(" " "!" "^" "_" "$" "#" "*" "'") 0 + (lambda (mark) + (cl-case (string-to-char mark) + (? "( ) Nothing Special") + (?! "(!) Column Names") + (?^ "(^) Field Names Above") + (?_ "(^) Field Names Below") + (?$ "($) Formula Parameters") + (?# "(#) Recalculation: Auto") + (?* "(*) Recalculation: Manual") + (?' "(') Recalculation: None"))) t)))) + ((assq :table contextlist) + (popup-menu + '(nil + ["Align Table" org-ctrl-c-ctrl-c] + ["Blank Field" org-table-blank-field] + ["Edit Field" org-table-edit-field] + "--" + ("Column" + ["Move Column Left" org-metaleft] + ["Move Column Right" org-metaright] + ["Delete Column" org-shiftmetaleft] + ["Insert Column" org-shiftmetaright] + "--" + ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :selected org-table-limit-column-width :style toggle]) + ("Row" + ["Move Row Up" org-metaup] + ["Move Row Down" org-metadown] + ["Delete Row" org-shiftmetaup] + ["Insert Row" org-shiftmetadown] + ["Sort lines in region" org-table-sort-lines (org-at-table-p)] + "--" + ["Insert Hline" org-table-insert-hline]) + ("Rectangle" + ["Copy Rectangle" org-copy-special] + ["Cut Rectangle" org-cut-special] + ["Paste Rectangle" org-paste-special] + ["Fill Rectangle" org-table-wrap-region]) + "--" + ["Set Column Formula" org-table-eval-formula] + ["Set Field Formula" (org-table-eval-formula '(4))] + ["Edit Formulas" org-table-edit-formulas] + "--" + ["Recalculate Line" org-table-recalculate] + ["Recalculate All" (org-table-recalculate '(4))] + ["Iterate All" (org-table-recalculate '(16))] + "--" + ["Toggle Recalculate Mark" org-table-rotate-recalc-marks] + ["Sum Column/Rectangle" org-table-sum + :active (or (org-at-table-p) (org-region-active-p))] + ["Field Info" org-table-field-info] + ["Debug Formulas" + (setq org-table-formula-debug (not org-table-formula-debug)) + :style toggle :selected org-table-formula-debug] + ))) + ((and (assq :headline contextlist) (not (eolp))) + (let ((priority (org-mouse-get-priority t))) + (popup-menu + `("Headline Menu" + ("Tags and Priorities" + ,@(org-mouse-keyword-menu + (org-mouse-priority-list) + #'(lambda (keyword) + (org-mouse-set-priority (string-to-char keyword))) + priority "Priority %s") + "--" + ,@(org-mouse-tag-menu)) + ("TODO Status" + ,@(org-mouse-todo-menu (org-get-todo-state))) + ["Show Tags" + (with-current-buffer org-mouse-main-buffer (org-agenda-show-tags)) + :visible (not org-mouse-direct)] + ["Show Priority" + (with-current-buffer org-mouse-main-buffer (org-agenda-show-priority)) + :visible (not org-mouse-direct)] + ,@(if org-mouse-direct '("--") nil) + ["New Heading" org-mouse-insert-heading :visible org-mouse-direct] + ["Set Deadline" + (progn (org-mouse-end-headline) (insert " ") (org-deadline)) + :active (not (save-excursion + (org-mouse-re-search-line org-deadline-regexp)))] + ["Schedule Task" + (progn (org-mouse-end-headline) (insert " ") (org-schedule)) + :active (not (save-excursion + (org-mouse-re-search-line org-scheduled-regexp)))] + ["Insert Timestamp" + (progn (org-mouse-end-headline) (insert " ") (org-time-stamp nil)) t] + ; ["Timestamp (inactive)" org-time-stamp-inactive t] + "--" + ["Archive Subtree" org-archive-subtree] + ["Cut Subtree" org-cut-special] + ["Copy Subtree" org-copy-special] + ["Paste Subtree" org-paste-special :visible org-mouse-direct] + ("Sort Children" + ["Alphabetically" (org-sort-entries nil ?a)] + ["Numerically" (org-sort-entries nil ?n)] + ["By Time/Date" (org-sort-entries nil ?t)] + "--" + ["Reverse Alphabetically" (org-sort-entries nil ?A)] + ["Reverse Numerically" (org-sort-entries nil ?N)] + ["Reverse By Time/Date" (org-sort-entries nil ?T)]) + "--" + ["Move Trees" org-mouse-move-tree :active nil] + )))) + (t + (org-mouse-popup-global-menu))))) + +(defun org-mouse-mark-active () + (and mark-active transient-mark-mode)) + +(defun org-mouse-in-region-p (pos) + (and (org-mouse-mark-active) + (>= pos (region-beginning)) + (< pos (region-end)))) + +(defun org-mouse-down-mouse (event) + (interactive "e") + (setq this-command last-command) + (unless (and (= 1 (event-click-count event)) + (org-mouse-in-region-p (posn-point (event-start event)))) + (mouse-drag-region event))) + +(add-hook 'org-mode-hook + #'(lambda () + (setq org-mouse-context-menu-function 'org-mouse-context-menu) + + (when (memq 'context-menu org-mouse-features) + (org-defkey org-mouse-map [mouse-3] nil) + (org-defkey org-mode-map [mouse-3] 'org-mouse-show-context-menu)) + (org-defkey org-mode-map [down-mouse-1] 'org-mouse-down-mouse) + (when (memq 'context-menu org-mouse-features) + (org-defkey org-mouse-map [C-drag-mouse-1] 'org-mouse-move-tree) + (org-defkey org-mouse-map [C-down-mouse-1] 'org-mouse-move-tree-start)) + (when (memq 'yank-link org-mouse-features) + (org-defkey org-mode-map [S-mouse-2] 'org-mouse-yank-link) + (org-defkey org-mode-map [drag-mouse-3] 'org-mouse-yank-link)) + (when (memq 'move-tree org-mouse-features) + (org-defkey org-mouse-map [drag-mouse-3] 'org-mouse-move-tree) + (org-defkey org-mouse-map [down-mouse-3] 'org-mouse-move-tree-start)) + + (when (memq 'activate-stars org-mouse-features) + (font-lock-add-keywords + nil + `((,org-outline-regexp + 0 `(face org-link mouse-face highlight keymap ,org-mouse-map) + 'prepend)) + t)) + + (when (memq 'activate-bullets org-mouse-features) + (font-lock-add-keywords + nil + `(("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +" + (1 `(face org-link keymap ,org-mouse-map mouse-face highlight) + 'prepend))) + t)) + + (when (memq 'activate-checkboxes org-mouse-features) + (font-lock-add-keywords + nil + `(("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)" + (2 `(face bold keymap ,org-mouse-map mouse-face highlight) t))) + t)) + + (defadvice org-open-at-point (around org-mouse-open-at-point activate) + (let ((context (org-context))) + (cond + ((assq :headline-stars context) (org-cycle)) + ((assq :checkbox context) (org-toggle-checkbox)) + ((assq :item-bullet context) + (let ((org-cycle-include-plain-lists t)) (org-cycle))) + ((org-footnote-at-reference-p) nil) + (t ad-do-it)))))) + +(defun org-mouse-move-tree-start (_event) + (interactive "e") + (message "Same line: promote/demote, (***):move before, (text): make a child")) + + +(defun org-mouse-make-marker (position) + (with-current-buffer (window-buffer (posn-window position)) + (copy-marker (posn-point position)))) + +(defun org-mouse-move-tree (event) + ;; todo: handle movements between different buffers + (interactive "e") + (save-excursion + (let* ((start (org-mouse-make-marker (event-start event))) + (end (org-mouse-make-marker (event-end event))) + (sbuf (marker-buffer start)) + (ebuf (marker-buffer end))) + + (when (and sbuf ebuf) + (set-buffer sbuf) + (goto-char start) + (org-back-to-heading) + (if (and (eq sbuf ebuf) + (equal + (point) + (save-excursion (goto-char end) (org-back-to-heading) (point)))) + ;; if the same line then promote/demote + (if (>= end start) (org-demote-subtree) (org-promote-subtree)) + ;; if different lines then move + (org-cut-subtree) + + (set-buffer ebuf) + (goto-char end) + (org-back-to-heading) + (when (and (eq sbuf ebuf) + (equal + (point) + (save-excursion (goto-char start) + (org-back-to-heading) (point)))) + (progn (org-end-of-subtree nil t) + (unless (eobp) (backward-char))) + (end-of-line) + (if (eobp) (newline) (forward-char))) + + (when (looking-at org-outline-regexp) + (let ((level (- (match-end 0) (match-beginning 0)))) + (when (> end (match-end 0)) + (progn (org-end-of-subtree nil t) + (unless (eobp) (backward-char))) + (end-of-line) + (if (eobp) (newline) (forward-char)) + (setq level (1+ level))) + (org-paste-subtree level) + (save-excursion + (progn (org-end-of-subtree nil t) + (unless (eobp) (backward-char))) + (when (bolp) (delete-char -1)))))))))) + + +(defun org-mouse-transform-to-outline () + (interactive) + (org-back-to-heading) + (let ((minlevel 1000) + (replace-text (concat (match-string 0) "* "))) + (beginning-of-line 2) + (save-excursion + (while (not (or (eobp) (looking-at org-outline-regexp))) + (when (looking-at org-mouse-plain-list-regexp) + (setq minlevel (min minlevel (- (match-end 1) (match-beginning 1))))) + (forward-line))) + (while (not (or (eobp) (looking-at org-outline-regexp))) + (when (and (looking-at org-mouse-plain-list-regexp) + (eq minlevel (- (match-end 1) (match-beginning 1)))) + (replace-match replace-text)) + (forward-line)))) + +(defvar org-mouse-cmd) ;dynamically scoped from `org-with-remote-undo'. + +(defun org-mouse-do-remotely (command) + ;; (org-agenda-check-no-diary) + (when (get-text-property (point) 'org-marker) + (let* ((anticol (- (point-at-eol) (point))) + (marker (get-text-property (point) 'org-marker)) + (buffer (marker-buffer marker)) + (pos (marker-position marker)) + (hdmarker (get-text-property (point) 'org-hd-marker)) + (buffer-read-only nil) + (newhead "--- removed ---") + (org-mouse-direct nil) + (org-mouse-main-buffer (current-buffer))) + (when (eq (with-current-buffer buffer major-mode) 'org-mode) + (let ((endmarker (with-current-buffer buffer + (org-end-of-subtree nil t) + (unless (eobp) (forward-char 1)) + (point-marker)))) + (org-with-remote-undo buffer + (with-current-buffer buffer + (widen) + (goto-char pos) + (org-show-hidden-entry) + (save-excursion + (and (outline-next-heading) + (org-flag-heading nil))) ; show the next heading + (org-back-to-heading) + (setq marker (point-marker)) + (goto-char (max (point-at-bol) (- (point-at-eol) anticol))) + (funcall command) + (message "_cmd: %S" org-mouse-cmd) + (message "this-command: %S" this-command) + (unless (eq (marker-position marker) (marker-position endmarker)) + (setq newhead (org-get-heading)))) + + (beginning-of-line 1) + (save-excursion + (org-agenda-change-all-lines newhead hdmarker 'fixface)))) + t)))) + +(defun org-mouse-agenda-context-menu (&optional _event) + (or (org-mouse-do-remotely 'org-mouse-context-menu) + (popup-menu + '("Agenda" + ("Agenda Files") + "--" + ["Undo" (progn (message "last command: %S" last-command) (setq this-command 'org-agenda-undo) (org-agenda-undo)) + :visible (if (eq last-command 'org-agenda-undo) + org-agenda-pending-undo-list + org-agenda-undo-list)] + ["Rebuild Buffer" org-agenda-redo t] + ["New Diary Entry" + org-agenda-diary-entry (org-agenda-check-type nil 'agenda) t] + "--" + ["Goto Today" org-agenda-goto-today + (org-agenda-check-type nil 'agenda) t] + ["Display Calendar" org-agenda-goto-calendar + (org-agenda-check-type nil 'agenda) t] + ("Calendar Commands" + ["Phases of the Moon" org-agenda-phases-of-moon + (org-agenda-check-type nil 'agenda)] + ["Sunrise/Sunset" org-agenda-sunrise-sunset + (org-agenda-check-type nil 'agenda)] + ["Holidays" org-agenda-holidays + (org-agenda-check-type nil 'agenda)] + ["Convert" org-agenda-convert-date + (org-agenda-check-type nil 'agenda)] + "--" + ["Create iCalendar file" org-icalendar-combine-agenda-files t]) + "--" + ["Day View" org-agenda-day-view + :active (org-agenda-check-type nil 'agenda) + :style radio :selected (eq org-agenda-current-span 'day)] + ["Week View" org-agenda-week-view + :active (org-agenda-check-type nil 'agenda) + :style radio :selected (eq org-agenda-current-span 'week)] + "--" + ["Show Logbook entries" org-agenda-log-mode + :style toggle :selected org-agenda-show-log + :active (org-agenda-check-type nil 'agenda)] + ["Include Diary" org-agenda-toggle-diary + :style toggle :selected org-agenda-include-diary + :active (org-agenda-check-type nil 'agenda)] + ["Use Time Grid" org-agenda-toggle-time-grid + :style toggle :selected org-agenda-use-time-grid + :active (org-agenda-check-type nil 'agenda)] + ["Follow Mode" org-agenda-follow-mode + :style toggle :selected org-agenda-follow-mode] + "--" + ["Quit" org-agenda-quit t] + ["Exit and Release Buffers" org-agenda-exit t] + )))) + +(defun org-mouse-get-gesture (event) + (let ((startxy (posn-x-y (event-start event))) + (endxy (posn-x-y (event-end event)))) + (if (< (car startxy) (car endxy)) :right :left))) + + + ; (setq org-agenda-mode-hook nil) +(defvar org-agenda-mode-map) +(add-hook 'org-agenda-mode-hook + (lambda () + (setq org-mouse-context-menu-function 'org-mouse-agenda-context-menu) + (org-defkey org-agenda-mode-map [mouse-3] 'org-mouse-show-context-menu) + (org-defkey org-agenda-mode-map [down-mouse-3] 'org-mouse-move-tree-start) + (org-defkey org-agenda-mode-map [C-mouse-4] 'org-agenda-earlier) + (org-defkey org-agenda-mode-map [C-mouse-5] 'org-agenda-later) + (org-defkey org-agenda-mode-map [drag-mouse-3] + (lambda (event) (interactive "e") + (cl-case (org-mouse-get-gesture event) + (:left (org-agenda-earlier 1)) + (:right (org-agenda-later 1))))))) + +(provide 'org-mouse) + +;;; org-mouse.el ends here diff --git a/elpa/org-9.1.14/org-pcomplete.el b/elpa/org-9.1.14/org-pcomplete.el new file mode 100644 index 00000000..88a2e10d --- /dev/null +++ b/elpa/org-9.1.14/org-pcomplete.el @@ -0,0 +1,386 @@ +;;; org-pcomplete.el --- In-buffer Completion Code -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; John Wiegley <johnw at gnu dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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/>. +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Code: + +;;;; Require other packages + +(require 'org-macs) +(require 'org-compat) +(require 'pcomplete) + +(declare-function org-make-org-heading-search-string "org" (&optional string)) +(declare-function org-get-buffer-tags "org" ()) +(declare-function org-get-tags "org" ()) +(declare-function org-buffer-property-keys "org" + (&optional specials defaults columns ignore-malformed)) +(declare-function org-entry-properties "org" (&optional pom which)) +(declare-function org-tag-alist-to-string "org" (alist &optional skip-key)) + +;;;; Customization variables + +(defvar org-drawer-regexp) +(defvar org-property-re) +(defvar org-current-tag-alist) + +(defun org-thing-at-point () + "Examine the thing at point and let the caller know what it is. +The return value is a string naming the thing at point." + (let ((beg1 (save-excursion + (skip-chars-backward "[:alnum:]-_@") + (point))) + (beg (save-excursion + (skip-chars-backward "a-zA-Z0-9-_:$") + (point))) + (line-to-here (buffer-substring (point-at-bol) (point)))) + (cond + ((string-match "\\`[ \t]*#\\+begin: clocktable[ \t]+" line-to-here) + (cons "block-option" "clocktable")) + ((string-match "\\`[ \t]*#\\+begin_src[ \t]+" line-to-here) + (cons "block-option" "src")) + ((save-excursion + (re-search-backward "^[ \t]*#\\+\\([A-Z_]+\\):.*" + (line-beginning-position) t)) + (cons "file-option" (match-string-no-properties 1))) + ((string-match "\\`[ \t]*#\\+[a-zA-Z_]*\\'" line-to-here) + (cons "file-option" nil)) + ((equal (char-before beg) ?\[) + (cons "link" nil)) + ((equal (char-before beg) ?\\) + (cons "tex" nil)) + ((string-match "\\`\\*+[ \t]+\\'" + (buffer-substring (point-at-bol) beg)) + (cons "todo" nil)) + ((equal (char-before beg) ?*) + (cons "searchhead" nil)) + ((and (equal (char-before beg1) ?:) + (equal (char-after (point-at-bol)) ?*)) + (cons "tag" nil)) + ((and (equal (char-before beg1) ?:) + (not (equal (char-after (point-at-bol)) ?*)) + (save-excursion + (move-beginning-of-line 1) + (skip-chars-backward "[ \t\n]") + ;; org-drawer-regexp matches a whole line but while + ;; looking-back, we just ignore trailing whitespaces + (or (looking-back (substring org-drawer-regexp 0 -1) + (line-beginning-position)) + (looking-back org-property-re + (line-beginning-position))))) + (cons "prop" nil)) + ((and (equal (char-before beg1) ?:) + (not (equal (char-after (point-at-bol)) ?*))) + (cons "drawer" nil)) + (t nil)))) + +(defun org-command-at-point () + "Return the qualified name of the Org completion entity at point. +When completing for #+STARTUP, for example, this function returns +\"file-option/startup\"." + (let ((thing (org-thing-at-point))) + (cond + ((string= "file-option" (car thing)) + (concat (car thing) + (and (cdr thing) (concat "/" (downcase (cdr thing)))))) + ((string= "block-option" (car thing)) + (concat (car thing) "/" (downcase (cdr thing)))) + (t (car thing))))) + +(defun org-parse-arguments () + "Parse whitespace separated arguments in the current region." + (let ((begin (line-beginning-position)) + (end (line-end-position)) + begins args) + (save-restriction + (narrow-to-region begin end) + (save-excursion + (goto-char (point-min)) + (while (not (eobp)) + (skip-chars-forward " \t\n[") + (setq begins (cons (point) begins)) + (skip-chars-forward "^ \t\n[") + (setq args (cons (buffer-substring-no-properties + (car begins) (point)) + args))) + (cons (reverse args) (reverse begins)))))) + +(defun org-pcomplete-initial () + "Calls the right completion function for first argument completions." + (ignore + (funcall (or (pcomplete-find-completion-function + (car (org-thing-at-point))) + pcomplete-default-completion-function)))) + +(defvar org-options-keywords) ; From org.el +(defvar org-element-affiliated-keywords) ; From org-element.el +(declare-function org-get-export-keywords "org" ()) +(defun pcomplete/org-mode/file-option () + "Complete against all valid file options." + (require 'org-element) + (pcomplete-here + (org-pcomplete-case-double + (append (mapcar (lambda (keyword) (concat keyword " ")) + org-options-keywords) + (mapcar (lambda (keyword) (concat keyword ": ")) + org-element-affiliated-keywords) + (let (block-names) + (dolist (name + '("CENTER" "COMMENT" "EXAMPLE" "EXPORT" "QUOTE" "SRC" + "VERSE") + block-names) + (push (format "END_%s" name) block-names) + (push (concat "BEGIN_" + name + ;; Since language is compulsory in + ;; export blocks source blocks, add + ;; a space. + (and (member name '("EXPORT" "SRC")) " ")) + block-names) + (push (format "ATTR_%s: " name) block-names))) + (mapcar (lambda (keyword) (concat keyword ": ")) + (org-get-export-keywords)))) + (substring pcomplete-stub 2))) + +(defun pcomplete/org-mode/file-option/author () + "Complete arguments for the #+AUTHOR file option." + (pcomplete-here (list user-full-name))) + +(defvar org-time-stamp-formats) +(defun pcomplete/org-mode/file-option/date () + "Complete arguments for the #+DATE file option." + (pcomplete-here (list (format-time-string (car org-time-stamp-formats))))) + +(defun pcomplete/org-mode/file-option/email () + "Complete arguments for the #+EMAIL file option." + (pcomplete-here (list user-mail-address))) + +(defvar org-export-exclude-tags) +(defun pcomplete/org-mode/file-option/exclude_tags () + "Complete arguments for the #+EXCLUDE_TAGS file option." + (require 'ox) + (pcomplete-here + (and org-export-exclude-tags + (list (mapconcat 'identity org-export-exclude-tags " "))))) + +(defvar org-file-tags) +(defun pcomplete/org-mode/file-option/filetags () + "Complete arguments for the #+FILETAGS file option." + (pcomplete-here (and org-file-tags (mapconcat 'identity org-file-tags " ")))) + +(defvar org-export-default-language) +(defun pcomplete/org-mode/file-option/language () + "Complete arguments for the #+LANGUAGE file option." + (require 'ox) + (pcomplete-here + (pcomplete-uniqify-list + (list org-export-default-language "en")))) + +(defvar org-default-priority) +(defvar org-highest-priority) +(defvar org-lowest-priority) +(defun pcomplete/org-mode/file-option/priorities () + "Complete arguments for the #+PRIORITIES file option." + (pcomplete-here (list (format "%c %c %c" + org-highest-priority + org-lowest-priority + org-default-priority)))) + +(defvar org-export-select-tags) +(defun pcomplete/org-mode/file-option/select_tags () + "Complete arguments for the #+SELECT_TAGS file option." + (require 'ox) + (pcomplete-here + (and org-export-select-tags + (list (mapconcat 'identity org-export-select-tags " "))))) + +(defvar org-startup-options) +(defun pcomplete/org-mode/file-option/startup () + "Complete arguments for the #+STARTUP file option." + (while (pcomplete-here + (let ((opts (pcomplete-uniqify-list + (mapcar 'car org-startup-options)))) + ;; Some options are mutually exclusive, and shouldn't be completed + ;; against if certain other options have already been seen. + (dolist (arg pcomplete-args) + (cond + ((string= arg "hidestars") + (setq opts (delete "showstars" opts))))) + opts)))) + +(defun pcomplete/org-mode/file-option/tags () + "Complete arguments for the #+TAGS file option." + (pcomplete-here + (list (org-tag-alist-to-string org-current-tag-alist)))) + +(defun pcomplete/org-mode/file-option/title () + "Complete arguments for the #+TITLE file option." + (pcomplete-here + (let ((visited-file (buffer-file-name (buffer-base-buffer)))) + (list (or (and visited-file + (file-name-sans-extension + (file-name-nondirectory visited-file))) + (buffer-name (buffer-base-buffer))))))) + + +(declare-function org-export-backend-options "ox" (cl-x) t) +(defun pcomplete/org-mode/file-option/options () + "Complete arguments for the #+OPTIONS file option." + (while (pcomplete-here + (pcomplete-uniqify-list + (append + ;; Hard-coded OPTION items always available. + '("H:" "\\n:" "num:" "timestamp:" "arch:" "author:" "c:" + "creator:" "date:" "d:" "email:" "*:" "e:" "::" "f:" + "inline:" "tex:" "p:" "pri:" "':" "-:" "stat:" "^:" "toc:" + "|:" "tags:" "tasks:" "<:" "todo:") + ;; OPTION items from registered back-ends. + (let (items) + (dolist (backend (bound-and-true-p + org-export-registered-backends)) + (dolist (option (org-export-backend-options backend)) + (let ((item (nth 2 option))) + (when item (push (concat item ":") items))))) + items)))))) + +(defun pcomplete/org-mode/file-option/infojs_opt () + "Complete arguments for the #+INFOJS_OPT file option." + (while (pcomplete-here + (pcomplete-uniqify-list + (mapcar (lambda (item) (format "%s:" (car item))) + (bound-and-true-p org-html-infojs-opts-table)))))) + +(defun pcomplete/org-mode/file-option/bind () + "Complete arguments for the #+BIND file option, which are variable names." + (let (vars) + (mapatoms + (lambda (a) (if (boundp a) (setq vars (cons (symbol-name a) vars))))) + (pcomplete-here vars))) + +(defvar org-link-abbrev-alist-local) +(defvar org-link-abbrev-alist) +(defun pcomplete/org-mode/link () + "Complete against defined #+LINK patterns." + (pcomplete-here + (pcomplete-uniqify-list + (copy-sequence + (append (mapcar 'car org-link-abbrev-alist-local) + (mapcar 'car org-link-abbrev-alist)))))) + +(defvar org-entities) +(defun pcomplete/org-mode/tex () + "Complete against TeX-style HTML entity names." + (require 'org-entities) + (while (pcomplete-here + (pcomplete-uniqify-list (remove nil (mapcar 'car-safe org-entities))) + (substring pcomplete-stub 1)))) + +(defvar org-todo-keywords-1) +(defun pcomplete/org-mode/todo () + "Complete against known TODO keywords." + (pcomplete-here (pcomplete-uniqify-list (copy-sequence org-todo-keywords-1)))) + +(defvar org-todo-line-regexp) +(defun pcomplete/org-mode/searchhead () + "Complete against all headings. +This needs more work, to handle headings with lots of spaces in them." + (while + (pcomplete-here + (save-excursion + (goto-char (point-min)) + (let (tbl) + (let ((case-fold-search nil)) + (while (re-search-forward org-todo-line-regexp nil t) + (push (org-make-org-heading-search-string + (match-string-no-properties 3)) + tbl))) + (pcomplete-uniqify-list tbl))) + (substring pcomplete-stub 1)))) + +(defun pcomplete/org-mode/tag () + "Complete a tag name. Omit tags already set." + (while (pcomplete-here + (mapcar (lambda (x) (concat x ":")) + (let ((lst (pcomplete-uniqify-list + (or (remq + nil + (mapcar (lambda (x) (org-string-nw-p (car x))) + org-current-tag-alist)) + (mapcar #'car (org-get-buffer-tags)))))) + (dolist (tag (org-get-tags)) + (setq lst (delete tag lst))) + lst)) + (and (string-match ".*:" pcomplete-stub) + (substring pcomplete-stub (match-end 0)))))) + +(defun pcomplete/org-mode/prop () + "Complete a property name. Omit properties already set." + (pcomplete-here + (mapcar (lambda (x) + (concat x ": ")) + (let ((lst (pcomplete-uniqify-list + (copy-sequence + (org-buffer-property-keys nil t t t))))) + (dolist (prop (org-entry-properties)) + (setq lst (delete (car prop) lst))) + lst)) + (substring pcomplete-stub 1))) + +(defun pcomplete/org-mode/block-option/src () + "Complete the arguments of a begin_src block. +Complete a language in the first field, the header arguments and switches." + (pcomplete-here + (mapcar + (lambda(x) (symbol-name (nth 3 x))) + (cdr (car (cdr (memq :key-type (plist-get + (symbol-plist + 'org-babel-load-languages) + 'custom-type))))))) + (while (pcomplete-here + '("-n" "-r" "-l" + ":cache" ":colnames" ":comments" ":dir" ":eval" ":exports" + ":file" ":hlines" ":no-expand" ":noweb" ":results" ":rownames" + ":session" ":shebang" ":tangle" ":tangle-mode" ":var")))) + +(defun pcomplete/org-mode/block-option/clocktable () + "Complete keywords in a clocktable line." + (while (pcomplete-here '(":maxlevel" ":scope" ":lang" + ":tstart" ":tend" ":block" ":step" + ":stepskip0" ":fileskip0" + ":emphasize" ":link" ":narrow" ":indent" + ":tcolumns" ":level" ":compact" ":timestamp" + ":formula" ":formatter" ":wstart" ":mstart")))) + +(defun org-pcomplete-case-double (list) + "Return list with both upcase and downcase version of all strings in LIST." + (let (e res) + (while (setq e (pop list)) + (setq res (cons (downcase e) (cons (upcase e) res)))) + (nreverse res))) + +;;;; Finish up + +(provide 'org-pcomplete) + +;;; org-pcomplete.el ends here diff --git a/elpa/org-9.1.14/org-pkg.el b/elpa/org-9.1.14/org-pkg.el new file mode 100644 index 00000000..dc481746 --- /dev/null +++ b/elpa/org-9.1.14/org-pkg.el @@ -0,0 +1,2 @@ +;; Generated package description from org.el +(define-package "org" "9.1.14" "Outline-based notes management and organizer" 'nil :url "http://elpa.gnu.org/packages/org.html" :keywords '("outlines" "hypermedia" "calendar" "wp")) diff --git a/elpa/org-9.1.14/org-plot.el b/elpa/org-9.1.14/org-plot.el new file mode 100644 index 00000000..ebd7af42 --- /dev/null +++ b/elpa/org-9.1.14/org-plot.el @@ -0,0 +1,354 @@ +;;; org-plot.el --- Support for Plotting from Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2008-2018 Free Software Foundation, Inc. +;; +;; Author: Eric Schulte <schulte dot eric at gmail dot com> +;; Keywords: tables, plotting +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; Borrows ideas and a couple of lines of code from org-exp.el. + +;; Thanks to the Org mailing list for testing and implementation and +;; feature suggestions + +;;; Code: + +(require 'cl-lib) +(require 'org) +(require 'org-table) + +(declare-function gnuplot-delchar-or-maybe-eof "ext:gnuplot" (arg)) +(declare-function gnuplot-mode "ext:gnuplot" ()) +(declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot" ()) + +(defvar org-plot/gnuplot-default-options + '((:plot-type . 2d) + (:with . lines) + (:ind . 0)) + "Default options to gnuplot used by `org-plot/gnuplot'.") + +(defvar org-plot-timestamp-fmt nil) + +(defun org-plot/add-options-to-plist (p options) + "Parse an OPTIONS line and set values in the property list P. +Returns the resulting property list." + (when options + (let ((op '(("type" . :plot-type) + ("script" . :script) + ("line" . :line) + ("set" . :set) + ("title" . :title) + ("ind" . :ind) + ("deps" . :deps) + ("with" . :with) + ("file" . :file) + ("labels" . :labels) + ("map" . :map) + ("timeind" . :timeind) + ("timefmt" . :timefmt))) + (multiples '("set" "line")) + (regexp ":\\([\"][^\"]+?[\"]\\|[(][^)]+?[)]\\|[^ \t\n\r;,.]*\\)") + (start 0)) + (dolist (o op) + (if (member (car o) multiples) ;; keys with multiple values + (while (string-match + (concat (regexp-quote (car o)) regexp) + options start) + (setq start (match-end 0)) + (setq p (plist-put p (cdr o) + (cons (car (read-from-string + (match-string 1 options))) + (plist-get p (cdr o))))) + p) + (if (string-match (concat (regexp-quote (car o)) regexp) + options) + (setq p (plist-put p (cdr o) + (car (read-from-string + (match-string 1 options)))))))))) + p) + +(defun org-plot/goto-nearest-table () + "Move the point forward to the beginning of nearest table. +Return value is the point at the beginning of the table." + (interactive) (move-beginning-of-line 1) + (while (not (or (org-at-table-p) (< 0 (forward-line 1))))) + (goto-char (org-table-begin))) + +(defun org-plot/collect-options (&optional params) + "Collect options from an org-plot `#+Plot:' line. +Accepts an optional property list PARAMS, to which the options +will be added. Returns the resulting property list." + (interactive) + (let ((line (thing-at-point 'line))) + (if (string-match "#\\+PLOT: +\\(.*\\)$" line) + (org-plot/add-options-to-plist params (match-string 1 line)) + params))) + +(defun org-plot-quote-timestamp-field (s) + "Convert field S from timestamp to Unix time and export to gnuplot." + (format-time-string org-plot-timestamp-fmt (org-time-string-to-time s))) + +(defun org-plot-quote-tsv-field (s) + "Quote field S for export to gnuplot." + (if (string-match org-table-number-regexp s) s + (if (string-match org-ts-regexp3 s) + (org-plot-quote-timestamp-field s) + (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")))) + +(defun org-plot/gnuplot-to-data (table data-file params) + "Export TABLE to DATA-FILE in a format readable by gnuplot. +Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE." + (with-temp-file + data-file + (setq-local org-plot-timestamp-fmt (or + (plist-get params :timefmt) + "%Y-%m-%d-%H:%M:%S")) + (insert (orgtbl-to-generic + table + (org-combine-plists + '(:sep "\t" :fmt org-plot-quote-tsv-field) + params)))) + nil) + +(defun org-plot/gnuplot-to-grid-data (table data-file params) + "Export the data in TABLE to DATA-FILE for gnuplot. +This means in a format appropriate for grid plotting by gnuplot. +PARAMS specifies which columns of TABLE should be plotted as independent +and dependant variables." + (interactive) + (let* ((ind (- (plist-get params :ind) 1)) + (deps (if (plist-member params :deps) + (mapcar (lambda (val) (- val 1)) (plist-get params :deps)) + (let (collector) + (dotimes (col (length (nth 0 table))) + (setf collector (cons col collector))) + collector))) + (counter 0) + row-vals) + (when (>= ind 0) ;; collect values of ind col + (setf row-vals (mapcar (lambda (row) (setf counter (+ 1 counter)) + (cons counter (nth ind row))) table))) + (when (or deps (>= ind 0)) ;; remove non-plotting columns + (setf deps (delq ind deps)) + (setf table (mapcar (lambda (row) + (dotimes (col (length row)) + (unless (memq col deps) + (setf (nth col row) nil))) + (delq nil row)) + table))) + ;; write table to gnuplot grid datafile format + (with-temp-file data-file + (let ((num-rows (length table)) (num-cols (length (nth 0 table))) + (gnuplot-row (lambda (col row value) + (setf col (+ 1 col)) (setf row (+ 1 row)) + (format "%f %f %f\n%f %f %f\n" + col (- row 0.5) value ;; lower edge + col (+ row 0.5) value))) ;; upper edge + front-edge back-edge) + (dotimes (col num-cols) + (dotimes (row num-rows) + (setf back-edge + (concat back-edge + (funcall gnuplot-row (- col 1) row + (string-to-number (nth col (nth row table)))))) + (setf front-edge + (concat front-edge + (funcall gnuplot-row col row + (string-to-number (nth col (nth row table))))))) + ;; only insert once per row + (insert back-edge) (insert "\n") ;; back edge + (insert front-edge) (insert "\n") ;; front edge + (setf back-edge "") (setf front-edge "")))) + row-vals)) + +(defun org-plot/gnuplot-script (data-file num-cols params &optional preface) + "Write a gnuplot script to DATA-FILE respecting the options set in PARAMS. +NUM-COLS controls the number of columns plotted in a 2-d plot. +Optional argument PREFACE returns only option parameters in a +manner suitable for prepending to a user-specified script." + (let* ((type (plist-get params :plot-type)) + (with (if (eq type 'grid) 'pm3d (plist-get params :with))) + (sets (plist-get params :set)) + (lines (plist-get params :line)) + (map (plist-get params :map)) + (title (plist-get params :title)) + (file (plist-get params :file)) + (ind (plist-get params :ind)) + (time-ind (plist-get params :timeind)) + (timefmt (plist-get params :timefmt)) + (text-ind (plist-get params :textind)) + (deps (if (plist-member params :deps) (plist-get params :deps))) + (col-labels (plist-get params :labels)) + (x-labels (plist-get params :xlabels)) + (y-labels (plist-get params :ylabels)) + (plot-str "'%s' using %s%d%s with %s title '%s'") + (plot-cmd (pcase type + (`2d "plot") + (`3d "splot") + (`grid "splot"))) + (script "reset") + ;; ats = add-to-script + (ats (lambda (line) (setf script (concat script "\n" line)))) + plot-lines) + (when file ; output file + (funcall ats (format "set term %s" (file-name-extension file))) + (funcall ats (format "set output '%s'" file))) + (pcase type ; type + (`2d ()) + (`3d (when map (funcall ats "set map"))) + (`grid (funcall ats (if map "set pm3d map" "set pm3d")))) + (when title (funcall ats (format "set title '%s'" title))) ; title + (mapc ats lines) ; line + (dolist (el sets) (funcall ats (format "set %s" el))) ; set + ;; Unless specified otherwise, values are TAB separated. + (unless (string-match-p "^set datafile separator" script) + (funcall ats "set datafile separator \"\\t\"")) + (when x-labels ; x labels (xtics) + (funcall ats + (format "set xtics (%s)" + (mapconcat (lambda (pair) + (format "\"%s\" %d" (cdr pair) (car pair))) + x-labels ", ")))) + (when y-labels ; y labels (ytics) + (funcall ats + (format "set ytics (%s)" + (mapconcat (lambda (pair) + (format "\"%s\" %d" (cdr pair) (car pair))) + y-labels ", ")))) + (when time-ind ; timestamp index + (funcall ats "set xdata time") + (funcall ats (concat "set timefmt \"" + (or timefmt ; timefmt passed to gnuplot + "%Y-%m-%d-%H:%M:%S") "\""))) + (unless preface + (pcase type ; plot command + (`2d (dotimes (col num-cols) + (unless (and (eq type '2d) + (or (and ind (equal (1+ col) ind)) + (and deps (not (member (1+ col) deps))))) + (setf plot-lines + (cons + (format plot-str data-file + (or (and ind (> ind 0) + (not text-ind) + (format "%d:" ind)) "") + (1+ col) + (if text-ind (format ":xticlabel(%d)" ind) "") + with + (or (nth col col-labels) + (format "%d" (1+ col)))) + plot-lines))))) + (`3d + (setq plot-lines (list (format "'%s' matrix with %s title ''" + data-file with)))) + (`grid + (setq plot-lines (list (format "'%s' with %s title ''" + data-file with))))) + (funcall ats + (concat plot-cmd " " (mapconcat #'identity + (reverse plot-lines) + ",\\\n ")))) + script)) + +;;----------------------------------------------------------------------------- +;; facade functions +;;;###autoload +(defun org-plot/gnuplot (&optional params) + "Plot table using gnuplot. Gnuplot options can be specified with PARAMS. +If not given options will be taken from the +PLOT +line directly before or after the table." + (interactive) + (require 'gnuplot) + (save-window-excursion + (delete-other-windows) + (when (get-buffer "*gnuplot*") ; reset *gnuplot* if it already running + (with-current-buffer "*gnuplot*" + (goto-char (point-max)))) + (org-plot/goto-nearest-table) + ;; Set default options. + (dolist (pair org-plot/gnuplot-default-options) + (unless (plist-member params (car pair)) + (setf params (plist-put params (car pair) (cdr pair))))) + ;; collect table and table information + (let* ((data-file (make-temp-file "org-plot")) + (table (org-table-to-lisp)) + (num-cols (length (if (eq (nth 0 table) 'hline) (nth 1 table) + (nth 0 table))))) + (run-with-idle-timer 0.1 nil #'delete-file data-file) + (while (eq 'hline (car table)) (setf table (cdr table))) + (when (eq (cadr table) 'hline) + (setf params + (plist-put params :labels (nth 0 table))) ; headers to labels + (setf table (delq 'hline (cdr table)))) ; clean non-data from table + ;; Collect options. + (save-excursion (while (and (equal 0 (forward-line -1)) + (looking-at "[[:space:]]*#\\+")) + (setf params (org-plot/collect-options params)))) + ;; Dump table to datafile (very different for grid). + (pcase (plist-get params :plot-type) + (`2d (org-plot/gnuplot-to-data table data-file params)) + (`3d (org-plot/gnuplot-to-data table data-file params)) + (`grid (let ((y-labels (org-plot/gnuplot-to-grid-data + table data-file params))) + (when y-labels (plist-put params :ylabels y-labels))))) + ;; Check for timestamp ind column. + (let ((ind (1- (plist-get params :ind)))) + (when (and (>= ind 0) (eq '2d (plist-get params :plot-type))) + (if (= (length + (delq 0 (mapcar + (lambda (el) + (if (string-match org-ts-regexp3 el) 0 1)) + (mapcar (lambda (row) (nth ind row)) table)))) + 0) + (plist-put params :timeind t) + ;; Check for text ind column. + (if (or (string= (plist-get params :with) "hist") + (> (length + (delq 0 (mapcar + (lambda (el) + (if (string-match org-table-number-regexp el) + 0 1)) + (mapcar (lambda (row) (nth ind row)) table)))) + 0)) + (plist-put params :textind t))))) + ;; Write script. + (with-temp-buffer + (if (plist-get params :script) ; user script + (progn (insert + (org-plot/gnuplot-script data-file num-cols params t)) + (insert "\n") + (insert-file-contents (plist-get params :script)) + (goto-char (point-min)) + (while (re-search-forward "$datafile" nil t) + (replace-match data-file nil nil))) + (insert (org-plot/gnuplot-script data-file num-cols params))) + ;; Graph table. + (gnuplot-mode) + (gnuplot-send-buffer-to-gnuplot)) + ;; Cleanup. + (bury-buffer (get-buffer "*gnuplot*"))))) + +(provide 'org-plot) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-plot.el ends here diff --git a/elpa/org-9.1.14/org-protocol.el b/elpa/org-9.1.14/org-protocol.el new file mode 100644 index 00000000..33957ee3 --- /dev/null +++ b/elpa/org-9.1.14/org-protocol.el @@ -0,0 +1,730 @@ +;;; org-protocol.el --- Intercept Calls from Emacsclient to Trigger Custom Actions -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2008-2018 Free Software Foundation, Inc. +;; +;; Authors: Bastien Guerry <bzg@gnu.org> +;; Daniel M German <dmg AT uvic DOT org> +;; Sebastian Rose <sebastian_rose AT gmx DOT de> +;; Ross Patterson <me AT rpatterson DOT net> +;; Maintainer: Sebastian Rose <sebastian_rose AT gmx DOT de> +;; Keywords: org, emacsclient, wp + +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: +;; +;; Intercept calls from emacsclient to trigger custom actions. +;; +;; This is done by advising `server-visit-files' to scan the list of filenames +;; for `org-protocol-the-protocol' and sub-protocols defined in +;; `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'. +;; +;; Any application that supports calling external programs with an URL +;; as argument may be used with this functionality. +;; +;; +;; Usage: +;; ------ +;; +;; 1.) Add this to your init file (.emacs probably): +;; +;; (add-to-list 'load-path "/path/to/org-protocol/") +;; (require 'org-protocol) +;; +;; 3.) Ensure emacs-server is up and running. +;; 4.) Try this from the command line (adjust the URL as needed): +;; +;; $ emacsclient \ +;; org-protocol://store-link?url=http:%2F%2Flocalhost%2Findex.html&title=The%20title +;; +;; 5.) Optionally add custom sub-protocols and handlers: +;; +;; (setq org-protocol-protocol-alist +;; '(("my-protocol" +;; :protocol "my-protocol" +;; :function my-protocol-handler-function))) +;; +;; A "sub-protocol" will be found in URLs like this: +;; +;; org-protocol://sub-protocol?key=val&key2=val2 +;; +;; If it works, you can now setup other applications for using this feature. +;; +;; +;; As of March 2009 Firefox users follow the steps documented on +;; http://kb.mozillazine.org/Register_protocol, Opera setup is described here: +;; http://www.opera.com/support/kb/view/535/ +;; +;; +;; Documentation +;; ------------- +;; +;; org-protocol.el comes with and installs handlers to open sources of published +;; online content, store and insert the browser's URLs and cite online content +;; by clicking on a bookmark in Firefox, Opera and probably other browsers and +;; applications: +;; +;; * `org-protocol-open-source' uses the sub-protocol \"open-source\" and maps +;; URLs to local filenames defined in `org-protocol-project-alist'. +;; +;; * `org-protocol-store-link' stores an Org link (if Org is present) and +;; pushes the browsers URL to the `kill-ring' for yanking. This handler is +;; triggered through the sub-protocol \"store-link\". +;; +;; * Call `org-protocol-capture' by using the sub-protocol \"capture\". If +;; Org is loaded, Emacs will pop-up a capture buffer and fill the +;; template with the data provided. I.e. the browser's URL is inserted as an +;; Org-link of which the page title will be the description part. If text +;; was select in the browser, that text will be the body of the entry. +;; +;; You may use the same bookmark URL for all those standard handlers and just +;; adjust the sub-protocol used: +;; +;; location.href='org-protocol://sub-protocol?url='+ +;; encodeURIComponent(location.href)+'&title='+ +;; encodeURIComponent(document.title)+'&body='+ +;; encodeURIComponent(window.getSelection()) +;; +;; The handler for the sub-protocol \"capture\" detects an optional template +;; char that, if present, triggers the use of a special template. +;; Example: +;; +;; location.href='org-protocol://capture?template=x'+ ... +;; +;; uses template ?x. +;; +;; Note that using double slashes is optional from org-protocol.el's point of +;; view because emacsclient squashes the slashes to one. +;; +;; +;; provides: 'org-protocol +;; +;;; Code: + +(require 'org) + +(declare-function org-publish-get-project-from-filename "ox-publish" + (filename &optional up)) +(declare-function server-edit "server" (&optional arg)) + +(defvar org-capture-link-is-already-stored) + +(defgroup org-protocol nil + "Intercept calls from emacsclient to trigger custom actions. + +This is done by advising `server-visit-files' to scan the list of filenames +for `org-protocol-the-protocol' and sub-protocols defined in +`org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'." + :version "22.1" + :group 'convenience + :group 'org) + + +;;; Variables: + +(defconst org-protocol-protocol-alist-default + '(("org-capture" :protocol "capture" :function org-protocol-capture :kill-client t) + ("org-store-link" :protocol "store-link" :function org-protocol-store-link) + ("org-open-source" :protocol "open-source" :function org-protocol-open-source)) + "Default protocols to use. +See `org-protocol-protocol-alist' for a description of this variable.") + +(defconst org-protocol-the-protocol "org-protocol" + "This is the protocol to detect if org-protocol.el is loaded. +`org-protocol-protocol-alist-default' and `org-protocol-protocol-alist' hold +the sub-protocols that trigger the required action. You will have to define +just one protocol handler OS-wide (MS-Windows) or per application (Linux). +That protocol handler should call emacsclient.") + +;;; User variables: + +(defcustom org-protocol-reverse-list-of-files t + "Non-nil means re-reverse the list of filenames passed on the command line. +The filenames passed on the command line are passed to the emacs-server in +reverse order. Set to t (default) to re-reverse the list, i.e. use the +sequence on the command line. If nil, the sequence of the filenames is +unchanged." + :group 'org-protocol + :type 'boolean) + +(defcustom org-protocol-project-alist nil + "Map URLs to local filenames for `org-protocol-open-source' (open-source). + +Each element of this list must be of the form: + + (module-name :property value property: value ...) + +where module-name is an arbitrary name. All the values are strings. + +Possible properties are: + + :online-suffix - the suffix to strip from the published URLs + :working-suffix - the replacement for online-suffix + :base-url - the base URL, e.g. http://www.example.com/project/ + Last slash required. + :working-directory - the local working directory. This is, what base-url will + be replaced with. + :redirects - A list of cons cells, each of which maps a regular + expression to match to a path relative to :working-directory. + +Example: + + (setq org-protocol-project-alist + \\='((\"https://orgmode.org/worg/\" + :online-suffix \".php\" + :working-suffix \".org\" + :base-url \"https://orgmode.org/worg/\" + :working-directory \"/home/user/org/Worg/\") + (\"http://localhost/org-notes/\" + :online-suffix \".html\" + :working-suffix \".org\" + :base-url \"http://localhost/org/\" + :working-directory \"/home/user/org/\" + :rewrites ((\"org/?$\" . \"index.php\"))) + (\"Hugo based blog\" + :base-url \"https://www.site.com/\" + :working-directory \"~/site/content/post/\" + :online-suffix \".html\" + :working-suffix \".md\" + :rewrites ((\"\\(https://site.com/[0-9]+/[0-9]+/[0-9]+/\\)\" . \".md\"))))) + + + The last line tells `org-protocol-open-source' to open + /home/user/org/index.php, if the URL cannot be mapped to an existing + file, and ends with either \"org\" or \"org/\". + +Consider using the interactive functions `org-protocol-create' and +`org-protocol-create-for-org' to help you filling this variable with valid contents." + :group 'org-protocol + :type 'alist) + +(defcustom org-protocol-protocol-alist nil + "Register custom handlers for org-protocol. + +Each element of this list must be of the form: + + (module-name :protocol protocol :function func :kill-client nil) + +protocol - protocol to detect in a filename without trailing + colon and slashes. See rfc1738 section 2.1 for more + on this. If you define a protocol \"my-protocol\", + `org-protocol-check-filename-for-protocol' will search + filenames for \"org-protocol:/my-protocol\" and + trigger your action for every match. `org-protocol' + is defined in `org-protocol-the-protocol'. Double and + triple slashes are compressed to one by emacsclient. + +function - function that handles requests with protocol and takes + one argument. If a new-style link (key=val&key2=val2) + is given, the argument will be a property list with + the values from the link. If an old-style link is + given (val1/val2), the argument will be the filename + with all protocols stripped. + + If the function returns nil, emacsclient and -server + do nothing. Any non-nil return value is considered a + valid filename and thus passed to the server. + + `org-protocol.el' provides some support for handling + old-style filenames, if you follow the conventions + used for the standard handlers in + `org-protocol-protocol-alist-default'. See + `org-protocol-parse-parameters'. + +kill-client - If t, kill the client immediately, once the sub-protocol is + detected. This is necessary for actions that can be interrupted by + `C-g' to avoid dangling emacsclients. Note that all other command + line arguments but the this one will be discarded. Greedy handlers + still receive the whole list of arguments though. + +Here is an example: + + (setq org-protocol-protocol-alist + \\='((\"my-protocol\" + :protocol \"my-protocol\" + :function my-protocol-handler-function) + (\"your-protocol\" + :protocol \"your-protocol\" + :function your-protocol-handler-function)))" + :group 'org-protocol + :type '(alist)) + +(defcustom org-protocol-default-template-key nil + "The default template key to use. +This is usually a single character string but can also be a +string with two characters." + :group 'org-protocol + :type '(choice (const nil) (string))) + +(defcustom org-protocol-data-separator "/+\\|\\?" + "The default data separator to use. +This should be a single regexp string." + :group 'org-protocol + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +;;; Helper functions: + +(defun org-protocol-sanitize-uri (uri) + "Sanitize slashes to double-slashes in URI. +Emacsclient compresses double and triple slashes." + (when (string-match "^\\([a-z]+\\):/" uri) + (let* ((splitparts (split-string uri "/+"))) + (setq uri (concat (car splitparts) "//" (mapconcat 'identity (cdr splitparts) "/"))))) + uri) + +(defun org-protocol-split-data (data &optional unhexify separator) + "Split the DATA argument for an org-protocol handler function. +If UNHEXIFY is non-nil, hex-decode each split part. If UNHEXIFY +is a function, use that function to decode each split part. The +string is split at each occurrence of SEPARATOR (regexp). If no +SEPARATOR is specified or SEPARATOR is nil, assume \"/+\". The +results of that splitting are returned as a list." + (let* ((sep (or separator "/+\\|\\?")) + (split-parts (split-string data sep))) + (if unhexify + (if (fboundp unhexify) + (mapcar unhexify split-parts) + (mapcar 'org-link-unescape split-parts)) + split-parts))) + +(defun org-protocol-flatten-greedy (param-list &optional strip-path replacement) + "Transform PARAM-LIST into a flat list for greedy handlers. + +Greedy handlers might receive a list like this from emacsclient: +\((\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\")) +where \"/dir/\" is the absolute path to emacsclient's working directory. This +function transforms it into a flat list using `org-protocol-flatten' and +transforms the elements of that list as follows: + +If STRIP-PATH is non-nil, remove the \"/dir/\" prefix from all members of +param-list. + +If REPLACEMENT is string, replace the \"/dir/\" prefix with it. + +The first parameter, the one that contains the protocols, is always changed. +Everything up to the end of the protocols is stripped. + +Note, that this function will always behave as if +`org-protocol-reverse-list-of-files' was set to t and the returned list will +reflect that. emacsclient's first parameter will be the first one in the +returned list." + (let* ((l (org-protocol-flatten (if org-protocol-reverse-list-of-files + param-list + (reverse param-list)))) + (trigger (car l)) + (len 0) + dir + ret) + (when (string-match "^\\(.*\\)\\(org-protocol:/+[a-zA-z0-9][-_a-zA-z0-9]*:/+\\)\\(.*\\)" trigger) + (setq dir (match-string 1 trigger)) + (setq len (length dir)) + (setcar l (concat dir (match-string 3 trigger)))) + (if strip-path + (progn + (dolist (e l ret) + (setq ret + (append ret + (list + (if (stringp e) + (if (stringp replacement) + (setq e (concat replacement (substring e len))) + (setq e (substring e len))) + e))))) + ret) + l))) + +(defun org-protocol-flatten (list) + "Transform LIST into a flat list. + +Greedy handlers might receive a list like this from emacsclient: +\((\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\")) +where \"/dir/\" is the absolute path to emacsclients working directory. +This function transforms it into a flat list." + (if (null list) () + (if (listp list) + (append (org-protocol-flatten (car list)) (org-protocol-flatten (cdr list))) + (list list)))) + +(defun org-protocol-parse-parameters (info &optional new-style default-order) + "Return a property list of parameters from INFO. +If NEW-STYLE is non-nil, treat INFO as a query string (ex: +url=URL&title=TITLE). If old-style links are used (ex: +org-protocol://store-link/url/title), assign them to attributes +following DEFAULT-ORDER. + +If no DEFAULT-ORDER is specified, return the list of values. + +If INFO is already a property list, return it unchanged." + (if (listp info) + info + (if new-style + (let ((data (org-protocol-convert-query-to-plist info)) + result) + (while data + (setq result + (append + result + (list + (pop data) + (org-link-unescape (pop data)))))) + result) + (let ((data (org-protocol-split-data info t org-protocol-data-separator))) + (if default-order + (org-protocol-assign-parameters data default-order) + data))))) + +(defun org-protocol-assign-parameters (data default-order) + "Return a property list of parameters from DATA. +Key names are taken from DEFAULT-ORDER, which should be a list of +symbols. If DEFAULT-ORDER is shorter than the number of values +specified, the rest of the values are treated as :key value pairs." + (let (result) + (while default-order + (setq result + (append result + (list (pop default-order) + (pop data))))) + (while data + (setq result + (append result + (list (intern (concat ":" (pop data))) + (pop data))))) + result)) + +;;; Standard protocol handlers: + +(defun org-protocol-store-link (fname) + "Process an org-protocol://store-link style url. +Additionally store a browser URL as an org link. Also pushes the +link's URL to the `kill-ring'. + +Parameters: url, title (optional), body (optional) + +Old-style links such as org-protocol://store-link://URL/TITLE are +also recognized. + +The location for a browser's bookmark has to look like this: + + javascript:location.href = \\ + \\='org-protocol://store-link?url=\\=' + \\ + encodeURIComponent(location.href) + \\='&title=\\=' + \\ + encodeURIComponent(document.title); + +Don't use `escape()'! Use `encodeURIComponent()' instead. The +title of the page could contain slashes and the location +definitely will. + +The sub-protocol used to reach this function is set in +`org-protocol-protocol-alist'. + +FNAME should be a property list. If not, an old-style link of the +form URL/TITLE can also be used." + (let* ((splitparts (org-protocol-parse-parameters fname nil '(:url :title))) + (uri (org-protocol-sanitize-uri (plist-get splitparts :url))) + (title (plist-get splitparts :title))) + (when (boundp 'org-stored-links) + (push (list uri title) org-stored-links)) + (kill-new uri) + (message "`%s' to insert new org-link, `%s' to insert `%s'" + (substitute-command-keys "`\\[org-insert-link]'") + (substitute-command-keys "`\\[yank]'") + uri)) + nil) + +(defun org-protocol-capture (info) + "Process an org-protocol://capture style url with INFO. + +The sub-protocol used to reach this function is set in +`org-protocol-protocol-alist'. + +This function detects an URL, title and optional text, separated +by `/'. The location for a browser's bookmark looks like this: + + javascript:location.href = \\='org-protocol://capture?url=\\='+ \\ + encodeURIComponent(location.href) + \\='&title=\\=' \\ + encodeURIComponent(document.title) + \\='&body=\\=' + \\ + encodeURIComponent(window.getSelection()) + +By default, it uses the character `org-protocol-default-template-key', +which should be associated with a template in `org-capture-templates'. +You may specify the template with a template= query parameter, like this: + + javascript:location.href = \\='org-protocol://capture?template=b\\='+ ... + +Now template ?b will be used." + (if (and (boundp 'org-stored-links) + (org-protocol-do-capture info)) + (message "Item captured.")) + nil) + +(defun org-protocol-convert-query-to-plist (query) + "Convert QUERY key=value pairs in the URL to a property list." + (if query + (apply 'append (mapcar (lambda (x) + (let ((c (split-string x "="))) + (list (intern (concat ":" (car c))) (cadr c)))) + (split-string query "&"))))) + +(defun org-protocol-do-capture (info) + "Perform the actual capture based on INFO." + (let* ((temp-parts (org-protocol-parse-parameters info)) + (parts + (cond + ((and (listp info) (symbolp (car info))) info) + ((= (length (car temp-parts)) 1) ;; First parameter is exactly one character long + (org-protocol-assign-parameters temp-parts '(:template :url :title :body))) + (t + (org-protocol-assign-parameters temp-parts '(:url :title :body))))) + (template (or (plist-get parts :template) + org-protocol-default-template-key)) + (url (and (plist-get parts :url) (org-protocol-sanitize-uri (plist-get parts :url)))) + (type (and url (if (string-match "^\\([a-z]+\\):" url) + (match-string 1 url)))) + (title (or (plist-get parts :title) "")) + (region (or (plist-get parts :body) "")) + (orglink (if url + (org-make-link-string + url (if (string-match "[^[:space:]]" title) title url)) + title)) + (org-capture-link-is-already-stored t)) ;; avoid call to org-store-link + (setq org-stored-links + (cons (list url title) org-stored-links)) + (org-store-link-props :type type + :link url + :description title + :annotation orglink + :initial region + :query parts) + (raise-frame) + (funcall 'org-capture nil template))) + +(defun org-protocol-open-source (fname) + "Process an org-protocol://open-source?url= style URL with FNAME. + +Change a filename by mapping URLs to local filenames as set +in `org-protocol-project-alist'. + +The location for a browser's bookmark should look like this: + + javascript:location.href = \\='org-protocol://open-source?url=\\=' + \\ + encodeURIComponent(location.href)" + ;; As we enter this function for a match on our protocol, the return value + ;; defaults to nil. + (let ((result nil) + (f (org-protocol-sanitize-uri + (plist-get (org-protocol-parse-parameters fname nil '(:url)) + :url)))) + (catch 'result + (dolist (prolist org-protocol-project-alist) + (let* ((base-url (plist-get (cdr prolist) :base-url)) + (wsearch (regexp-quote base-url))) + + (when (string-match wsearch f) + (let* ((wdir (plist-get (cdr prolist) :working-directory)) + (strip-suffix (plist-get (cdr prolist) :online-suffix)) + (add-suffix (plist-get (cdr prolist) :working-suffix)) + ;; Strip "[?#].*$" if `f' is a redirect with another + ;; ending than strip-suffix here: + (f1 (substring f 0 (string-match "\\([\\?#].*\\)?$" f))) + (start-pos (+ (string-match wsearch f1) (length base-url))) + (end-pos (string-match + (regexp-quote strip-suffix) f1)) + ;; We have to compare redirects without suffix below: + (f2 (concat wdir (substring f1 start-pos end-pos))) + (the-file (concat f2 add-suffix))) + + ;; Note: the-file may still contain `%C3' et al here because browsers + ;; tend to encode `ä' in URLs to `%25C3' - `%25' being `%'. + ;; So the results may vary. + + ;; -- start redirects -- + (unless (file-exists-p the-file) + (message "File %s does not exist.\nTesting for rewritten URLs." the-file) + (let ((rewrites (plist-get (cdr prolist) :rewrites))) + (when rewrites + (message "Rewrites found: %S" rewrites) + (dolist (rewrite rewrites) + ;; Try to match a rewritten URL and map it to + ;; a real file. Compare redirects without + ;; suffix. + (when (string-match (car rewrite) f1) + (let ((replacement + (concat (directory-file-name + (replace-match "" nil nil f1 1)) + (cdr rewrite)))) + (throw 'result (concat wdir replacement)))))))) + ;; -- end of redirects -- + + (if (file-readable-p the-file) + (throw 'result the-file)) + (if (file-exists-p the-file) + (message "%s: permission denied!" the-file) + (message "%s: no such file or directory." the-file)))))) + result))) + + +;;; Core functions: + +(defun org-protocol-check-filename-for-protocol (fname restoffiles _client) + "Check if `org-protocol-the-protocol' and a valid protocol are used in FNAME. +Sub-protocols are registered in `org-protocol-protocol-alist' and +`org-protocol-protocol-alist-default'. This is how the matching is done: + + (string-match \"protocol:/+sub-protocol\\\\(://\\\\|\\\\?\\\\)\" ...) + +protocol and sub-protocol are regexp-quoted. + +Old-style links such as \"protocol://sub-protocol://param1/param2\" are +also recognized. + +If a matching protocol is found, the protocol is stripped from +fname and the result is passed to the protocol function as the +first parameter. The second parameter will be non-nil if FNAME +uses key=val&key2=val2-type arguments, or nil if FNAME uses +val/val2-type arguments. If the function returns nil, the +filename is removed from the list of filenames passed from +emacsclient to the server. If the function returns a non-nil +value, that value is passed to the server as filename. + +If the handler function is greedy, RESTOFFILES will also be passed to it. + +CLIENT is ignored." + (let ((sub-protocols (append org-protocol-protocol-alist + org-protocol-protocol-alist-default))) + (catch 'fname + (let ((the-protocol (concat (regexp-quote org-protocol-the-protocol) + ":/+"))) + (when (string-match the-protocol fname) + (dolist (prolist sub-protocols) + (let ((proto + (concat the-protocol + (regexp-quote (plist-get (cdr prolist) :protocol)) + "\\(:/+\\|\\?\\)"))) + (when (string-match proto fname) + (let* ((func (plist-get (cdr prolist) :function)) + (greedy (plist-get (cdr prolist) :greedy)) + (split (split-string fname proto)) + (result (if greedy restoffiles (cadr split))) + (new-style (string= (match-string 1 fname) "?"))) + (when (plist-get (cdr prolist) :kill-client) + (message "Greedy org-protocol handler. Killing client.") + (server-edit)) + (when (fboundp func) + (unless greedy + (throw 'fname + (if new-style + (funcall func (org-protocol-parse-parameters + result new-style)) + (warn "Please update your Org Protocol handler \ +to deal with new-style links.") + (funcall func result)))) + ;; Greedy protocol handlers are responsible for + ;; parsing their own filenames. + (funcall func result) + (throw 'fname t)))))))) + fname))) + +(defadvice server-visit-files (before org-protocol-detect-protocol-server activate) + "Advice server-visit-flist to call `org-protocol-modify-filename-for-protocol'." + (let ((flist (if org-protocol-reverse-list-of-files + (reverse (ad-get-arg 0)) + (ad-get-arg 0))) + (client (ad-get-arg 1))) + (catch 'greedy + (dolist (var flist) + ;; `\' to `/' on windows. FIXME: could this be done any better? + (let ((fname (expand-file-name (car var)))) + (setq fname (org-protocol-check-filename-for-protocol + fname (member var flist) client)) + (if (eq fname t) ;; greedy? We need the t return value. + (progn + (ad-set-arg 0 nil) + (throw 'greedy t)) + (if (stringp fname) ;; probably filename + (setcar var fname) + (ad-set-arg 0 (delq var (ad-get-arg 0)))))))))) + +;;; Org specific functions: + +(defun org-protocol-create-for-org () + "Create an Org protocol project for the current file's project. +The visited file needs to be part of a publishing project in +`org-publish-project-alist' for this to work. The function +delegates most of the work to `org-protocol-create'." + (interactive) + (require 'ox-publish) + (let ((all (or (org-publish-get-project-from-filename buffer-file-name)))) + (if all (org-protocol-create (cdr all)) + (message "%s" + (substitute-command-keys + "Not in an Org project. \ +Did you mean `\\[org-protocol-create]'?"))))) + +(defun org-protocol-create (&optional project-plist) + "Create a new org-protocol project interactively. +An org-protocol project is an entry in +`org-protocol-project-alist' which is used by +`org-protocol-open-source'. Optionally use PROJECT-PLIST to +initialize the defaults for this project. If PROJECT-PLIST is +the cdr of an element in `org-publish-project-alist', reuse +:base-directory, :html-extension and :base-extension." + (interactive) + (let ((working-dir (expand-file-name + (or (plist-get project-plist :base-directory) + default-directory))) + (base-url "https://orgmode.org/worg/") + (strip-suffix (or (plist-get project-plist :html-extension) ".html")) + (working-suffix (if (plist-get project-plist :base-extension) + (concat "." (plist-get project-plist :base-extension)) + ".org")) + (insert-default-directory t) + (minibuffer-allow-text-properties nil)) + + (setq base-url (read-string "Base URL of published content: " base-url nil base-url t)) + (or (string-suffix-p "/" base-url) + (setq base-url (concat base-url "/"))) + + (setq working-dir + (expand-file-name + (read-directory-name "Local working directory: " working-dir working-dir t))) + (or (string-suffix-p "/" working-dir) + (setq working-dir (concat working-dir "/"))) + + (setq strip-suffix + (read-string + (concat "Extension to strip from published URLs (" strip-suffix "): ") + strip-suffix nil strip-suffix t)) + + (setq working-suffix + (read-string + (concat "Extension of editable files (" working-suffix "): ") + working-suffix nil working-suffix t)) + + (when (yes-or-no-p "Save the new org-protocol-project to your init file? ") + (setq org-protocol-project-alist + (cons `(,base-url . (:base-url ,base-url + :working-directory ,working-dir + :online-suffix ,strip-suffix + :working-suffix ,working-suffix)) + org-protocol-project-alist)) + (customize-save-variable 'org-protocol-project-alist org-protocol-project-alist)))) + +(provide 'org-protocol) + +;;; org-protocol.el ends here diff --git a/elpa/org-9.1.14/org-rmail.el b/elpa/org-9.1.14/org-rmail.el new file mode 100644 index 00000000..d50fd648 --- /dev/null +++ b/elpa/org-9.1.14/org-rmail.el @@ -0,0 +1,115 @@ +;;; org-rmail.el --- Support for Links to Rmail Messages -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file implements links to Rmail messages from within Org mode. +;; Org mode loads this module by default - if this is not what you +;; want, configure the variable `org-modules'. + +;;; Code: + +(require 'org) + +;; Declare external functions and variables +(declare-function rmail-show-message "rmail" (&optional n no-summary)) +(declare-function rmail-what-message "rmail" (&optional pos)) +(declare-function rmail-toggle-header "rmail" (&optional arg)) +(declare-function rmail "rmail" (&optional file-name-arg)) +(declare-function rmail-widen "rmail" ()) +(defvar rmail-current-message) ; From rmail.el +(defvar rmail-header-style) ; From rmail.el +(defvar rmail-file-name) ; From rmail.el + +;; Install the link type +(org-link-set-parameters "rmail" :follow #'org-rmail-open :store #'org-rmail-store-link) + +;; Implementation +(defun org-rmail-store-link () + "Store a link to an Rmail folder or message." + (when (or (eq major-mode 'rmail-mode) + (eq major-mode 'rmail-summary-mode)) + (save-window-excursion + (save-restriction + (when (eq major-mode 'rmail-summary-mode) + (rmail-show-message rmail-current-message)) + (when (fboundp 'rmail-narrow-to-non-pruned-header) + (rmail-narrow-to-non-pruned-header)) + (when (eq rmail-header-style 'normal) + (rmail-toggle-header -1)) + (let* ((folder buffer-file-name) + (message-id (mail-fetch-field "message-id")) + (from (mail-fetch-field "from")) + (to (mail-fetch-field "to")) + (subject (mail-fetch-field "subject")) + (date (mail-fetch-field "date")) + desc link) + (org-store-link-props + :type "rmail" :from from :to to :date date + :subject subject :message-id message-id) + (setq message-id (org-unbracket-string "<" ">" message-id)) + (setq desc (org-email-link-description)) + (setq link (concat "rmail:" folder "#" message-id)) + (org-add-link-props :link link :description desc) + (rmail-show-message rmail-current-message) + link))))) + +(defun org-rmail-open (path) + "Follow an Rmail message link to the specified PATH." + (let (folder article) + (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path)) + (error "Error in Rmail link")) + (setq folder (match-string 1 path) + article (match-string 3 path)) + (org-rmail-follow-link folder article))) + +(defun org-rmail-follow-link (folder article) + "Follow an Rmail link to FOLDER and ARTICLE." + (require 'rmail) + (cond ((null article) (setq article "")) + ((stringp article) + (setq article (org-add-angle-brackets article))) + (t (user-error "Wrong RMAIL link format"))) + (let (message-number) + (save-excursion + (save-window-excursion + (rmail (if (string= folder "RMAIL") rmail-file-name folder)) + (setq message-number + (save-restriction + (rmail-widen) + (goto-char (point-max)) + (if (re-search-backward + (concat "^Message-ID:\\s-+" (regexp-quote article)) + nil t) + (rmail-what-message)))))) + (if message-number + (progn + (rmail (if (string= folder "RMAIL") rmail-file-name folder)) + (rmail-show-message message-number) + message-number) + (error "Message not found")))) + +(provide 'org-rmail) + +;;; org-rmail.el ends here diff --git a/elpa/org-9.1.14/org-src.el b/elpa/org-9.1.14/org-src.el new file mode 100644 index 00000000..4d65a71d --- /dev/null +++ b/elpa/org-9.1.14/org-src.el @@ -0,0 +1,1158 @@ +;;; org-src.el --- Source code examples in Org -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Bastien Guerry <bzg@gnu.org> +;; Dan Davison <davison at stats dot ox dot ac dot uk> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file contains the code dealing with source code examples in +;; Org mode. + +;;; Code: + +(require 'cl-lib) +(require 'org-macs) +(require 'org-compat) +(require 'ob-keys) +(require 'ob-comint) + +(declare-function org-base-buffer "org" (buffer)) +(declare-function org-do-remove-indentation "org" (&optional n)) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-class "org-element" (datum &optional parent)) +(declare-function org-element-context "org-element" (&optional element)) +(declare-function org-element-lineage "org-element" + (blob &optional types with-self)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-type "org-element" (element)) +(declare-function org-footnote-goto-definition "org-footnote" + (label &optional location)) +(declare-function org-get-indentation "org" (&optional line)) +(declare-function org-switch-to-buffer-other-window "org" (&rest args)) +(declare-function org-trim "org" (s &optional keep-lead)) + +(defvar org-inhibit-startup) + +(defcustom org-edit-src-turn-on-auto-save nil + "Non-nil means turn `auto-save-mode' on when editing a source block. +This will save the content of the source code editing buffer into +a newly created file, not the base buffer for this source block. + +If you want to regularly save the base buffer instead of the source +code editing buffer, see `org-edit-src-auto-save-idle-delay' instead." + :group 'org-edit-structure + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-edit-src-auto-save-idle-delay 0 + "Delay before saving a source code buffer back into its base buffer. +When a positive integer N, save after N seconds of idle time. +When 0 (the default), don't auto-save. + +If you want to save the source code buffer itself, don't use this. +Check `org-edit-src-turn-on-auto-save' instead." + :group 'org-edit-structure + :version "24.4" + :package-version '(Org . "8.0") + :type 'integer) + +(defcustom org-coderef-label-format "(ref:%s)" + "The default coderef format. +This format string will be used to search for coderef labels in literal +examples (EXAMPLE and SRC blocks). The format can be overwritten in +an individual literal example with the -l option, like + +#+BEGIN_SRC pascal +n -r -l \"((%s))\" +... +#+END_SRC + +If you want to use this for HTML export, make sure that the format does +not introduce special font-locking, and avoid the HTML special +characters `<', `>', and `&'. The reason for this restriction is that +the labels are searched for only after htmlize has done its job." + :group 'org-edit-structure ; FIXME this is not in the right group + :type 'string) + +(defcustom org-edit-fixed-width-region-mode 'artist-mode + "The mode that should be used to edit fixed-width regions. +These are the regions where each line starts with a colon." + :group 'org-edit-structure + :type '(choice + (const artist-mode) + (const picture-mode) + (const fundamental-mode) + (function :tag "Other (specify)"))) + +(defcustom org-src-preserve-indentation nil + "If non-nil preserve leading whitespace characters on export. +\\<org-mode-map> +If non-nil leading whitespace characters in source code blocks +are preserved on export, and when switching between the org +buffer and the language mode edit buffer. + +When this variable is nil, after editing with `\\[org-edit-src-code]', +the minimum (across-lines) number of leading whitespace characters +are removed from all lines, and the code block is uniformly indented +according to the value of `org-edit-src-content-indentation'." + :group 'org-edit-structure + :type 'boolean) + +(defcustom org-edit-src-content-indentation 2 + "Indentation for the content of a source code block. + +This should be the number of spaces added to the indentation of the #+begin +line in order to compute the indentation of the block content after +editing it with `\\[org-edit-src-code]'. + +It has no effect if `org-src-preserve-indentation' is non-nil." + :group 'org-edit-structure + :type 'integer) + +(defcustom org-edit-src-persistent-message t + "Non-nil means show persistent exit help message while editing src examples. +The message is shown in the header-line, which will be created in the +first line of the window showing the editing buffer." + :group 'org-edit-structure + :type 'boolean) + +(defcustom org-src-ask-before-returning-to-edit-buffer t + "Non-nil means ask before switching to an existing edit buffer. +If nil, when `org-edit-src-code' is used on a block that already +has an active edit buffer, it will switch to that edit buffer +immediately; otherwise it will ask whether you want to return to +the existing edit buffer." + :group 'org-edit-structure + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-src-window-setup 'reorganize-frame + "How the source code edit buffer should be displayed. +Possible values for this option are: + +current-window Show edit buffer in the current window, keeping all other + windows. +other-window Use `switch-to-buffer-other-window' to display edit buffer. +reorganize-frame Show only two windows on the current frame, the current + window and the edit buffer. When exiting the edit buffer, + return to one window. +other-frame Use `switch-to-buffer-other-frame' to display edit buffer. + Also, when exiting the edit buffer, kill that frame." + :group 'org-edit-structure + :type '(choice + (const current-window) + (const other-frame) + (const other-window) + (const reorganize-frame))) + +(defvar org-src-mode-hook nil + "Hook run after Org switched a source code snippet to its Emacs mode. +\\<org-mode-map> +This hook will run: +- when editing a source code snippet with `\\[org-edit-special]' +- when formatting a source code snippet for export with htmlize. + +You may want to use this hook for example to turn off `outline-minor-mode' +or similar things which you want to have when editing a source code file, +but which mess up the display of a snippet in Org exported files.") + +(defcustom org-src-lang-modes + '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist) + ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql) + ("calc" . fundamental) ("C" . c) ("cpp" . c++) ("C++" . c++) + ("screen" . shell-script) ("shell" . sh) ("bash" . sh)) + "Alist mapping languages to their major mode. +The key is the language name, the value is the string that should +be inserted as the name of the major mode. For many languages this is +simple, but for language where this is not the case, this variable +provides a way to simplify things on the user side. +For example, there is no ocaml-mode in Emacs, but the mode to use is +`tuareg-mode'." + :group 'org-edit-structure + :type '(repeat + (cons + (string "Language name") + (symbol "Major mode")))) + +(defcustom org-src-block-faces nil + "Alist of faces to be used for source-block. +Each element is a cell of the format + + (\"language\" FACE) + +Where FACE is either a defined face or an anonymous face. + +For instance, the following value would color the background of +emacs-lisp source blocks and python source blocks in purple and +green, respectability. + + \\='((\"emacs-lisp\" (:background \"#EEE2FF\")) + (\"python\" (:background \"#e5ffb8\")))" + :group 'org-edit-structure + :type '(repeat (list (string :tag "language") + (choice + (face :tag "Face") + (sexp :tag "Anonymous face")))) + :version "26.1" + :package-version '(Org . "9.0")) + +(defcustom org-src-tab-acts-natively nil + "If non-nil, the effect of TAB in a code block is as if it were +issued in the language major mode buffer." + :type 'boolean + :version "24.1" + :group 'org-babel) + + + +;;; Internal functions and variables + +(defvar-local org-src--allow-write-back t) +(put 'org-src--allow-write-back 'permanent-local t) + +(defvar-local org-src--auto-save-timer nil) +(put 'org-src--auto-save-timer 'permanent-local t) + +(defvar-local org-src--babel-info nil) +(put 'org-src--babel-info 'permanent-local t) + +(defvar-local org-src--beg-marker nil) +(put 'org-src--beg-marker 'permanent-local t) + +(defvar-local org-src--block-indentation nil) +(put 'org-src--block-indentation 'permanent-local t) + +(defvar-local org-src--end-marker nil) +(put 'org-src--end-marker 'permanent-local t) + +(defvar-local org-src--from-org-mode nil) +(put 'org-src--from-org-mode 'permanent-local t) + +(defvar-local org-src--overlay nil) +(put 'org-src--overlay 'permanent-local t) + +(defvar-local org-src--preserve-indentation nil) +(put 'org-src--preserve-indentation 'permanent-local t) + +(defvar-local org-src--remote nil) +(put 'org-src--remote 'permanent-local t) + +(defvar-local org-src--saved-temp-window-config nil) +(put 'org-src--saved-temp-window-config 'permanent-local t) + +(defvar-local org-src--source-type nil + "Type of element being edited, as a symbol.") +(put 'org-src--source-type 'permanent-local t) + +(defvar-local org-src--tab-width nil + "Contains `tab-width' value from Org source buffer. +However, if `indent-tabs-mode' is nil in that buffer, its value +is 0.") +(put 'org-src--tab-width 'permanent-local t) + +(defun org-src--construct-edit-buffer-name (org-buffer-name lang) + "Construct the buffer name for a source editing buffer." + (concat "*Org Src " org-buffer-name "[ " lang " ]*")) + +(defun org-src--edit-buffer (beg end) + "Return buffer editing area between BEG and END. +Return nil if there is no such buffer." + (catch 'exit + (dolist (b (buffer-list)) + (with-current-buffer b + (and (org-src-edit-buffer-p) + (= beg org-src--beg-marker) + (eq (marker-buffer beg) (marker-buffer org-src--beg-marker)) + (= end org-src--end-marker) + (eq (marker-buffer end) (marker-buffer org-src--end-marker)) + (throw 'exit b)))))) + +(defun org-src--source-buffer () + "Return source buffer edited by current buffer." + (unless (org-src-edit-buffer-p) (error "Not in a source buffer")) + (or (marker-buffer org-src--beg-marker) + (error "No source buffer available for current editing session"))) + +(defun org-src--get-lang-mode (lang) + "Return major mode that should be used for LANG. +LANG is a string, and the returned major mode is a symbol." + (intern + (concat + (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang))) + (if (symbolp l) (symbol-name l) l)) + "-mode"))) + +(defun org-src--coordinates (pos beg end) + "Return coordinates of POS relatively to BEG and END. +POS, BEG and END are buffer positions. Return value is either +a cons cell (LINE . COLUMN) or symbol `end'. See also +`org-src--goto-coordinates'." + (if (>= pos end) 'end + (org-with-wide-buffer + (goto-char (max beg pos)) + (cons (count-lines beg (line-beginning-position)) + ;; Column is relative to the end of line to avoid problems of + ;; comma escaping or colons appended in front of the line. + (- (current-column) + (progn (end-of-line) (current-column))))))) + +(defun org-src--goto-coordinates (coord beg end) + "Move to coordinates COORD relatively to BEG and END. +COORD are coordinates, as returned by `org-src--coordinates', +which see. BEG and END are buffer positions." + (goto-char + (if (eq coord 'end) (max (1- end) beg) + ;; If BEG happens to be located outside of the narrowed part of + ;; the buffer, widen it first. + (org-with-wide-buffer + (goto-char beg) + (forward-line (car coord)) + (end-of-line) + (org-move-to-column (max (+ (current-column) (cdr coord)) 0)) + (point))))) + +(defun org-src--contents-area (datum) + "Return contents boundaries of DATUM. +DATUM is an element or object. Return a list (BEG END CONTENTS) +where BEG and END are buffer positions and CONTENTS is a string." + (let ((type (org-element-type datum))) + (org-with-wide-buffer + (cond + ((eq type 'footnote-definition) + (let* ((beg (progn + (goto-char (org-element-property :post-affiliated datum)) + (search-forward "]"))) + (end (or (org-element-property :contents-end datum) beg))) + (list beg end (buffer-substring-no-properties beg end)))) + ((eq type 'inline-src-block) + (let ((beg (progn (goto-char (org-element-property :begin datum)) + (search-forward "{" (line-end-position) t))) + (end (progn (goto-char (org-element-property :end datum)) + (search-backward "}" (line-beginning-position) t)))) + (list beg end (buffer-substring-no-properties beg end)))) + ((org-element-property :contents-begin datum) + (let ((beg (org-element-property :contents-begin datum)) + (end (org-element-property :contents-end datum))) + (list beg end (buffer-substring-no-properties beg end)))) + ((memq type '(example-block export-block src-block)) + (list (progn (goto-char (org-element-property :post-affiliated datum)) + (line-beginning-position 2)) + (progn (goto-char (org-element-property :end datum)) + (skip-chars-backward " \r\t\n") + (line-beginning-position 1)) + (org-element-property :value datum))) + ((memq type '(fixed-width latex-environment table)) + (let ((beg (org-element-property :post-affiliated datum)) + (end (progn (goto-char (org-element-property :end datum)) + (skip-chars-backward " \r\t\n") + (line-beginning-position 2)))) + (list beg + end + (if (eq type 'fixed-width) (org-element-property :value datum) + (buffer-substring-no-properties beg end))))) + (t (error "Unsupported element or object: %s" type)))))) + +(defun org-src--make-source-overlay (beg end edit-buffer) + "Create overlay between BEG and END positions and return it. +EDIT-BUFFER is the buffer currently editing area between BEG and +END." + (let ((overlay (make-overlay beg end))) + (overlay-put overlay 'face 'secondary-selection) + (overlay-put overlay 'edit-buffer edit-buffer) + (overlay-put overlay 'help-echo + "Click with mouse-1 to switch to buffer editing this segment") + (overlay-put overlay 'face 'secondary-selection) + (overlay-put overlay 'keymap + (let ((map (make-sparse-keymap))) + (define-key map [mouse-1] 'org-edit-src-continue) + map)) + (let ((read-only + (list + (lambda (&rest _) + (user-error + "Cannot modify an area being edited in a dedicated buffer"))))) + (overlay-put overlay 'modification-hooks read-only) + (overlay-put overlay 'insert-in-front-hooks read-only) + (overlay-put overlay 'insert-behind-hooks read-only)) + overlay)) + +(defun org-src--remove-overlay () + "Remove overlay from current source buffer." + (when (overlayp org-src--overlay) (delete-overlay org-src--overlay))) + +(defun org-src--on-datum-p (datum) + "Non-nil when point is on DATUM. +DATUM is an element or an object. Consider blank lines or white +spaces after it as being outside." + (and (>= (point) (org-element-property :begin datum)) + (<= (point) + (org-with-wide-buffer + (goto-char (org-element-property :end datum)) + (skip-chars-backward " \r\t\n") + (if (eq (org-element-class datum) 'element) + (line-end-position) + (point)))))) + +(defun org-src--contents-for-write-back () + "Return buffer contents in a format appropriate for write back. +Assume point is in the corresponding edit buffer." + (let ((indentation-offset + (if org-src--preserve-indentation 0 + (+ (or org-src--block-indentation 0) + (if (memq org-src--source-type '(example-block src-block)) + org-edit-src-content-indentation + 0)))) + (use-tabs? (and (> org-src--tab-width 0) t)) + (source-tab-width org-src--tab-width) + (contents (org-with-wide-buffer (buffer-string))) + (write-back org-src--allow-write-back)) + (with-temp-buffer + ;; Reproduce indentation parameters from source buffer. + (setq-local indent-tabs-mode use-tabs?) + (when (> source-tab-width 0) (setq-local tab-width source-tab-width)) + ;; Apply WRITE-BACK function on edit buffer contents. + (insert (org-no-properties contents)) + (goto-char (point-min)) + (when (functionp write-back) (save-excursion (funcall write-back))) + ;; Add INDENTATION-OFFSET to every non-empty line in buffer, + ;; unless indentation is meant to be preserved. + (when (> indentation-offset 0) + (while (not (eobp)) + (skip-chars-forward " \t") + (unless (eolp) ;ignore blank lines + (let ((i (current-column))) + (delete-region (line-beginning-position) (point)) + (indent-to (+ i indentation-offset)))) + (forward-line))) + (buffer-string)))) + +(defun org-src--edit-element + (datum name &optional initialize write-back contents remote) + "Edit DATUM contents in a dedicated buffer NAME. + +INITIALIZE is a function to call upon creating the buffer. + +When WRITE-BACK is non-nil, assume contents will replace original +region. Moreover, if it is a function, apply it in the edit +buffer, from point min, before returning the contents. + +When CONTENTS is non-nil, display them in the edit buffer. +Otherwise, show DATUM contents as specified by +`org-src--contents-area'. + +When REMOTE is non-nil, do not try to preserve point or mark when +moving from the edit area to the source. + +Leave point in edit buffer." + (setq org-src--saved-temp-window-config (current-window-configuration)) + (let* ((area (org-src--contents-area datum)) + (beg (copy-marker (nth 0 area))) + (end (copy-marker (nth 1 area) t)) + (old-edit-buffer (org-src--edit-buffer beg end)) + (contents (or contents (nth 2 area)))) + (if (and old-edit-buffer + (or (not org-src-ask-before-returning-to-edit-buffer) + (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? "))) + ;; Move to existing buffer. + (org-src-switch-to-buffer old-edit-buffer 'return) + ;; Discard old edit buffer. + (when old-edit-buffer + (with-current-buffer old-edit-buffer (org-src--remove-overlay)) + (kill-buffer old-edit-buffer)) + (let* ((org-mode-p (derived-mode-p 'org-mode)) + (source-tab-width (if indent-tabs-mode tab-width 0)) + (type (org-element-type datum)) + (ind (org-with-wide-buffer + (goto-char (org-element-property :begin datum)) + (org-get-indentation))) + (preserve-ind + (and (memq type '(example-block src-block)) + (or (org-element-property :preserve-indent datum) + org-src-preserve-indentation))) + ;; Store relative positions of mark (if any) and point + ;; within the edited area. + (point-coordinates (and (not remote) + (org-src--coordinates (point) beg end))) + (mark-coordinates (and (not remote) + (org-region-active-p) + (let ((m (mark))) + (and (>= m beg) (>= end m) + (org-src--coordinates m beg end))))) + ;; Generate a new edit buffer. + (buffer (generate-new-buffer name)) + ;; Add an overlay on top of source. + (overlay (org-src--make-source-overlay beg end buffer))) + ;; Switch to edit buffer. + (org-src-switch-to-buffer buffer 'edit) + ;; Insert contents. + (insert contents) + (remove-text-properties (point-min) (point-max) + '(display nil invisible nil intangible nil)) + (unless preserve-ind (org-do-remove-indentation)) + (set-buffer-modified-p nil) + (setq buffer-file-name nil) + ;; Initialize buffer. + (when (functionp initialize) + (let ((org-inhibit-startup t)) + (condition-case e + (funcall initialize) + (error (message "Initialization fails with: %S" + (error-message-string e)))))) + ;; Transmit buffer-local variables for exit function. It must + ;; be done after initializing major mode, as this operation + ;; may reset them otherwise. + (setq org-src--tab-width source-tab-width) + (setq org-src--from-org-mode org-mode-p) + (setq org-src--beg-marker beg) + (setq org-src--end-marker end) + (setq org-src--remote remote) + (setq org-src--source-type type) + (setq org-src--block-indentation ind) + (setq org-src--preserve-indentation preserve-ind) + (setq org-src--overlay overlay) + (setq org-src--allow-write-back write-back) + ;; Start minor mode. + (org-src-mode) + ;; Move mark and point in edit buffer to the corresponding + ;; location. + (if remote + (progn + ;; Put point at first non read-only character after + ;; leading blank. + (goto-char + (or (text-property-any (point-min) (point-max) 'read-only nil) + (point-max))) + (skip-chars-forward " \r\t\n")) + ;; Set mark and point. + (when mark-coordinates + (org-src--goto-coordinates mark-coordinates (point-min) (point-max)) + (push-mark (point) 'no-message t) + (setq deactivate-mark nil)) + (org-src--goto-coordinates + point-coordinates (point-min) (point-max))))))) + + + +;;; Fontification of source blocks + +(defun org-src-font-lock-fontify-block (lang start end) + "Fontify code block. +This function is called by emacs automatic fontification, as long +as `org-src-fontify-natively' is non-nil." + (let ((lang-mode (org-src--get-lang-mode lang))) + (when (fboundp lang-mode) + (let ((string (buffer-substring-no-properties start end)) + (modified (buffer-modified-p)) + (org-buffer (current-buffer))) + (remove-text-properties start end '(face nil)) + (with-current-buffer + (get-buffer-create + (format " *org-src-fontification:%s*" lang-mode)) + (let ((inhibit-modification-hooks nil)) + (erase-buffer) + ;; Add string and a final space to ensure property change. + (insert string " ")) + (unless (eq major-mode lang-mode) (funcall lang-mode)) + (org-font-lock-ensure) + (let ((pos (point-min)) next) + (while (setq next (next-property-change pos)) + ;; Handle additional properties from font-lock, so as to + ;; preserve, e.g., composition. + (dolist (prop (cons 'face font-lock-extra-managed-props)) + (let ((new-prop (get-text-property pos prop))) + (put-text-property + (+ start (1- pos)) (1- (+ start next)) prop new-prop + org-buffer))) + (setq pos next)))) + ;; Add Org faces. + (let ((src-face (nth 1 (assoc-string lang org-src-block-faces t)))) + (when (or (facep src-face) (listp src-face)) + (font-lock-append-text-property start end 'face src-face)) + (font-lock-append-text-property start end 'face 'org-block)) + (add-text-properties + start end + '(font-lock-fontified t fontified t font-lock-multiline t)) + (set-buffer-modified-p modified))))) + + +;;; Escape contents + +(defun org-escape-code-in-region (beg end) + "Escape lines between BEG and END. +Escaping happens when a line starts with \"*\", \"#+\", \",*\" or +\",#+\" by appending a comma to it." + (interactive "r") + (save-excursion + (goto-char end) + (while (re-search-backward "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" beg t) + (save-excursion (replace-match ",\\1" nil nil nil 1))))) + +(defun org-escape-code-in-string (s) + "Escape lines in string S. +Escaping happens when a line starts with \"*\", \"#+\", \",*\" or +\",#+\" by appending a comma to it." + (replace-regexp-in-string "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" ",\\1" + s nil nil 1)) + +(defun org-unescape-code-in-region (beg end) + "Un-escape lines between BEG and END. +Un-escaping happens by removing the first comma on lines starting +with \",*\", \",#+\", \",,*\" and \",,#+\"." + (interactive "r") + (save-excursion + (goto-char end) + (while (re-search-backward "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" beg t) + (save-excursion (replace-match "" nil nil nil 1))))) + +(defun org-unescape-code-in-string (s) + "Un-escape lines in string S. +Un-escaping happens by removing the first comma on lines starting +with \",*\", \",#+\", \",,*\" and \",,#+\"." + (replace-regexp-in-string + "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1)) + + + +;;; Org src minor mode + +(defvar org-src-mode-map + (let ((map (make-sparse-keymap))) + (define-key map "\C-c'" 'org-edit-src-exit) + (define-key map "\C-c\C-k" 'org-edit-src-abort) + (define-key map "\C-x\C-s" 'org-edit-src-save) + map)) + +(define-minor-mode org-src-mode + "Minor mode for language major mode buffers generated by Org. +\\<org-mode-map> +This minor mode is turned on in two situations: + - when editing a source code snippet with `\\[org-edit-special]' + - when formatting a source code snippet for export with htmlize. + +\\{org-src-mode-map} + +See also `org-src-mode-hook'." + nil " OrgSrc" nil + (when org-edit-src-persistent-message + (setq-local + header-line-format + (substitute-command-keys + (if org-src--allow-write-back + "Edit, then exit with `\\[org-edit-src-exit]' or abort with \ +`\\[org-edit-src-abort]'" + "Exit with `\\[org-edit-src-exit]' or abort with \ +`\\[org-edit-src-abort]'")))) + ;; Possibly activate various auto-save features (for the edit buffer + ;; or the source buffer). + (when org-edit-src-turn-on-auto-save + (setq buffer-auto-save-file-name + (concat (make-temp-name "org-src-") + (format-time-string "-%Y-%d-%m") + ".txt"))) + (unless (or org-src--auto-save-timer (zerop org-edit-src-auto-save-idle-delay)) + (setq org-src--auto-save-timer + (run-with-idle-timer + org-edit-src-auto-save-idle-delay t + (lambda () + (save-excursion + (let (edit-flag) + (dolist (b (buffer-list)) + (with-current-buffer b + (when (org-src-edit-buffer-p) + (unless edit-flag (setq edit-flag t)) + (when (buffer-modified-p) (org-edit-src-save))))) + (unless edit-flag + (cancel-timer org-src--auto-save-timer) + (setq org-src--auto-save-timer nil))))))))) + +(defun org-src-mode-configure-edit-buffer () + (when (bound-and-true-p org-src--from-org-mode) + (add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local) + (if (bound-and-true-p org-src--allow-write-back) + (progn + (setq buffer-offer-save t) + (setq buffer-file-name + (concat (buffer-file-name (marker-buffer org-src--beg-marker)) + "[" (buffer-name) "]")) + (setq-local write-contents-functions '(org-edit-src-save))) + (setq buffer-read-only t)))) + +(add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer) + + + +;;; Babel related functions + +(defun org-src-associate-babel-session (info) + "Associate edit buffer with comint session." + (interactive) + (let ((session (cdr (assq :session (nth 2 info))))) + (and session (not (string= session "none")) + (org-babel-comint-buffer-livep session) + (let ((f (intern (format "org-babel-%s-associate-session" + (nth 0 info))))) + (and (fboundp f) (funcall f session)))))) + +(defun org-src-babel-configure-edit-buffer () + (when org-src--babel-info + (org-src-associate-babel-session org-src--babel-info))) + +(add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer) + + +;;; Public API + +(defmacro org-src-do-at-code-block (&rest body) + "Execute BODY from an edit buffer in the Org mode buffer." + (declare (debug (body))) + `(let ((beg-marker org-src--beg-marker)) + (when beg-marker + (with-current-buffer (marker-buffer beg-marker) + (goto-char beg-marker) + ,@body)))) + +(defun org-src-do-key-sequence-at-code-block (&optional key) + "Execute key sequence at code block in the source Org buffer. +The command bound to KEY in the Org-babel key map is executed +remotely with point temporarily at the start of the code block in +the Org buffer. + +This command is not bound to a key by default, to avoid conflicts +with language major mode bindings. To bind it to C-c @ in all +language major modes, you could use + + (add-hook \\='org-src-mode-hook + (lambda () (define-key org-src-mode-map \"\\C-c@\" + \\='org-src-do-key-sequence-at-code-block))) + +In that case, for example, C-c @ t issued in code edit buffers +would tangle the current Org code block, C-c @ e would execute +the block and C-c @ h would display the other available +Org-babel commands." + (interactive "kOrg-babel key: ") + (if (equal key (kbd "C-g")) (keyboard-quit) + (org-edit-src-save) + (org-src-do-at-code-block + (call-interactively (lookup-key org-babel-map key))))) + +(defun org-src-edit-buffer-p (&optional buffer) + "Non-nil when current buffer is a source editing buffer. +If BUFFER is non-nil, test it instead." + (let ((buffer (org-base-buffer (or buffer (current-buffer))))) + (and (buffer-live-p buffer) + (local-variable-p 'org-src--beg-marker buffer) + (local-variable-p 'org-src--end-marker buffer)))) + +(defun org-src-switch-to-buffer (buffer context) + (pcase org-src-window-setup + (`current-window (pop-to-buffer-same-window buffer)) + (`other-window + (switch-to-buffer-other-window buffer)) + (`other-frame + (pcase context + (`exit + (let ((frame (selected-frame))) + (switch-to-buffer-other-frame buffer) + (delete-frame frame))) + (`save + (kill-buffer (current-buffer)) + (pop-to-buffer-same-window buffer)) + (_ (switch-to-buffer-other-frame buffer)))) + (`reorganize-frame + (when (eq context 'edit) (delete-other-windows)) + (org-switch-to-buffer-other-window buffer) + (when (eq context 'exit) (delete-other-windows))) + (`switch-invisibly (set-buffer buffer)) + (_ + (message "Invalid value %s for `org-src-window-setup'" + org-src-window-setup) + (pop-to-buffer-same-window buffer)))) + +(defun org-src-coderef-format (&optional element) + "Return format string for block at point. + +When optional argument ELEMENT is provided, use that block. +Otherwise, assume point is either at a source block, at an +example block. + +If point is in an edit buffer, retrieve format string associated +to the remote source block." + (cond + ((and element (org-element-property :label-fmt element))) + ((org-src-edit-buffer-p) (org-src-do-at-code-block (org-src-coderef-format))) + ((org-element-property :label-fmt (org-element-at-point))) + (t org-coderef-label-format))) + +(defun org-src-coderef-regexp (fmt &optional label) + "Return regexp matching a coderef format string FMT. + +When optional argument LABEL is non-nil, match coderef for that +label only. + +Match group 1 contains the full coderef string with surrounding +white spaces. Match group 2 contains the same string without any +surrounding space. Match group 3 contains the label. + +A coderef format regexp can only match at the end of a line." + (format "\\([ \t]*\\(%s\\)[ \t]*\\)$" + (replace-regexp-in-string + "%s" + (if label (regexp-quote label) "\\([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)") + (regexp-quote fmt) + nil t))) + +(defun org-edit-footnote-reference () + "Edit definition of footnote reference at point." + (interactive) + (let* ((context (org-element-context)) + (label (org-element-property :label context))) + (unless (and (eq (org-element-type context) 'footnote-reference) + (org-src--on-datum-p context)) + (user-error "Not on a footnote reference")) + (unless label (user-error "Cannot edit remotely anonymous footnotes")) + (let* ((definition (org-with-wide-buffer + (org-footnote-goto-definition label) + (backward-char) + (org-element-context))) + (inline? (eq 'footnote-reference (org-element-type definition))) + (contents + (org-with-wide-buffer + (buffer-substring-no-properties + (or (org-element-property :post-affiliated definition) + (org-element-property :begin definition)) + (cond + (inline? (1+ (org-element-property :contents-end definition))) + ((org-element-property :contents-end definition)) + (t (goto-char (org-element-property :post-affiliated definition)) + (line-end-position))))))) + (add-text-properties + 0 + (progn (string-match (if inline? "\\`\\[fn:.*?:" "\\`.*?\\]") contents) + (match-end 0)) + '(read-only "Cannot edit footnote label" front-sticky t rear-nonsticky t) + contents) + (when inline? + (let ((l (length contents))) + (add-text-properties + (1- l) l + '(read-only "Cannot edit past footnote reference" + front-sticky nil rear-nonsticky nil) + contents))) + (org-src--edit-element + definition + (format "*Edit footnote [%s]*" label) + (let ((source (current-buffer))) + (lambda () + (org-mode) + (org-clone-local-variables source))) + (lambda () + (if (not inline?) (delete-region (point) (search-forward "]")) + (delete-region (point) (search-forward ":" nil t 2)) + (delete-region (1- (point-max)) (point-max)) + (when (re-search-forward "\n[ \t]*\n" nil t) + (user-error "Inline definitions cannot contain blank lines")) + ;; If footnote reference belongs to a table, make sure to + ;; remove any newline characters in order to preserve + ;; table's structure. + (when (org-element-lineage definition '(table-cell)) + (while (search-forward "\n" nil t) (replace-match ""))))) + contents + 'remote)) + ;; Report success. + t)) + +(defun org-edit-table.el () + "Edit \"table.el\" table at point. +\\<org-src-mode-map> +A new buffer is created and the table is copied into it. Then +the table is recognized with `table-recognize'. When done +editing, exit with `\\[org-edit-src-exit]'. The edited text will \ +then replace +the area in the Org mode buffer. + +Throw an error when not at such a table." + (interactive) + (let ((element (org-element-at-point))) + (unless (and (eq (org-element-type element) 'table) + (eq (org-element-property :type element) 'table.el) + (org-src--on-datum-p element)) + (user-error "Not in a table.el table")) + (org-src--edit-element + element + (org-src--construct-edit-buffer-name (buffer-name) "Table") + #'text-mode t) + (when (bound-and-true-p flyspell-mode) (flyspell-mode -1)) + (table-recognize) + t)) + +(defun org-edit-latex-environment () + "Edit LaTeX environment at point. +\\<org-src-mode-map> +The LaTeX environment is copied into a new buffer. Major mode is +set to the one associated to \"latex\" in `org-src-lang-modes', +or to `latex-mode' if there is none. + +When done, exit with `\\[org-edit-src-exit]'. The edited text \ +will then replace +the LaTeX environment in the Org mode buffer." + (interactive) + (let ((element (org-element-at-point))) + (unless (and (eq (org-element-type element) 'latex-environment) + (org-src--on-datum-p element)) + (user-error "Not in a LaTeX environment")) + (org-src--edit-element + element + (org-src--construct-edit-buffer-name (buffer-name) "LaTeX environment") + (org-src--get-lang-mode "latex") + t) + t)) + +(defun org-edit-export-block () + "Edit export block at point. +\\<org-src-mode-map> +A new buffer is created and the block is copied into it, and the +buffer is switched into an appropriate major mode. See also +`org-src-lang-modes'. + +When done, exit with `\\[org-edit-src-exit]'. The edited text \ +will then replace +the area in the Org mode buffer. + +Throw an error when not at an export block." + (interactive) + (let ((element (org-element-at-point))) + (unless (and (eq (org-element-type element) 'export-block) + (org-src--on-datum-p element)) + (user-error "Not in an export block")) + (let* ((type (downcase (or (org-element-property :type element) + ;; Missing export-block type. Fallback + ;; to default mode. + "fundamental"))) + (mode (org-src--get-lang-mode type))) + (unless (functionp mode) (error "No such language mode: %s" mode)) + (org-src--edit-element + element + (org-src--construct-edit-buffer-name (buffer-name) type) + mode + (lambda () (org-escape-code-in-region (point-min) (point-max))))) + t)) + +(defun org-edit-src-code (&optional code edit-buffer-name) + "Edit the source or example block at point. +\\<org-src-mode-map> +The code is copied to a separate buffer and the appropriate mode +is turned on. When done, exit with `\\[org-edit-src-exit]'. This \ +will remove the +original code in the Org buffer, and replace it with the edited +version. See `org-src-window-setup' to configure the display of +windows containing the Org buffer and the code buffer. + +When optional argument CODE is a string, edit it in a dedicated +buffer instead. + +When optional argument EDIT-BUFFER-NAME is non-nil, use it as the +name of the sub-editing buffer." + (interactive) + (let* ((element (org-element-at-point)) + (type (org-element-type element))) + (unless (and (memq type '(example-block src-block)) + (org-src--on-datum-p element)) + (user-error "Not in a source or example block")) + (let* ((lang + (if (eq type 'src-block) (org-element-property :language element) + "example")) + (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang))) + (babel-info (and (eq type 'src-block) + (org-babel-get-src-block-info 'light))) + deactivate-mark) + (when (and (eq type 'src-block) (not (functionp lang-f))) + (error "No such language mode: %s" lang-f)) + (org-src--edit-element + element + (or edit-buffer-name + (org-src--construct-edit-buffer-name (buffer-name) lang)) + lang-f + (and (null code) + (lambda () (org-escape-code-in-region (point-min) (point-max)))) + (and code (org-unescape-code-in-string code))) + ;; Finalize buffer. + (setq-local org-coderef-label-format + (or (org-element-property :label-fmt element) + org-coderef-label-format)) + (when (eq type 'src-block) + (setq org-src--babel-info babel-info) + (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang)))) + (when (fboundp edit-prep-func) + (funcall edit-prep-func babel-info)))) + t))) + +(defun org-edit-inline-src-code () + "Edit inline source code at point." + (interactive) + (let ((context (org-element-context))) + (unless (and (eq (org-element-type context) 'inline-src-block) + (org-src--on-datum-p context)) + (user-error "Not on inline source code")) + (let* ((lang (org-element-property :language context)) + (lang-f (org-src--get-lang-mode lang)) + (babel-info (org-babel-get-src-block-info 'light)) + deactivate-mark) + (unless (functionp lang-f) (error "No such language mode: %s" lang-f)) + (org-src--edit-element + context + (org-src--construct-edit-buffer-name (buffer-name) lang) + lang-f + (lambda () + ;; Inline src blocks are limited to one line. + (while (re-search-forward "\n[ \t]*" nil t) (replace-match " ")) + ;; Trim contents. + (goto-char (point-min)) + (skip-chars-forward " \t") + (delete-region (point-min) (point)) + (goto-char (point-max)) + (skip-chars-backward " \t") + (delete-region (point) (point-max)))) + ;; Finalize buffer. + (setq org-src--babel-info babel-info) + (setq org-src--preserve-indentation t) + (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang)))) + (when (fboundp edit-prep-func) (funcall edit-prep-func babel-info))) + ;; Return success. + t))) + +(defun org-edit-fixed-width-region () + "Edit the fixed-width ASCII drawing at point. +\\<org-src-mode-map> +This must be a region where each line starts with a colon +followed by a space or a newline character. + +A new buffer is created and the fixed-width region is copied into +it, and the buffer is switched into the major mode defined in +`org-edit-fixed-width-region-mode', which see. + +When done, exit with `\\[org-edit-src-exit]'. The edited text \ +will then replace +the area in the Org mode buffer." + (interactive) + (let ((element (org-element-at-point))) + (unless (and (eq (org-element-type element) 'fixed-width) + (org-src--on-datum-p element)) + (user-error "Not in a fixed-width area")) + (org-src--edit-element + element + (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width") + org-edit-fixed-width-region-mode + (lambda () (while (not (eobp)) (insert ": ") (forward-line)))) + ;; Return success. + t)) + +(defun org-edit-src-abort () + "Abort editing of the src code and return to the Org buffer." + (interactive) + (let (org-src--allow-write-back) (org-edit-src-exit))) + +(defun org-edit-src-continue (e) + "Unconditionally return to buffer editing area under point. +Throw an error if there is no such buffer." + (interactive "e") + (mouse-set-point e) + (let ((buf (get-char-property (point) 'edit-buffer))) + (if buf (org-src-switch-to-buffer buf 'continue) + (user-error "No sub-editing buffer for area at point")))) + +(defun org-edit-src-save () + "Save parent buffer with current state source-code buffer." + (interactive) + (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer")) + (set-buffer-modified-p nil) + (let ((edited-code (org-src--contents-for-write-back)) + (beg org-src--beg-marker) + (end org-src--end-marker) + (overlay org-src--overlay)) + (with-current-buffer (org-src--source-buffer) + (undo-boundary) + (goto-char beg) + ;; Temporarily disable read-only features of OVERLAY in order to + ;; insert new contents. + (delete-overlay overlay) + (delete-region beg end) + (let ((expecting-bol (bolp))) + (insert edited-code) + (when (and expecting-bol (not (bolp))) (insert "\n"))) + (save-buffer) + (move-overlay overlay beg (point)))) + ;; `write-contents-functions' requires the function to return + ;; a non-nil value so that other functions are not called. + t) + +(defun org-edit-src-exit () + "Kill current sub-editing buffer and return to source buffer." + (interactive) + (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer")) + (let* ((beg org-src--beg-marker) + (end org-src--end-marker) + (write-back org-src--allow-write-back) + (remote org-src--remote) + (coordinates (and (not remote) + (org-src--coordinates (point) 1 (point-max)))) + (code (and write-back (org-src--contents-for-write-back)))) + (set-buffer-modified-p nil) + ;; Switch to source buffer. Kill sub-editing buffer. + (let ((edit-buffer (current-buffer)) + (source-buffer (marker-buffer beg))) + (unless source-buffer (error "Source buffer disappeared. Aborting")) + (org-src-switch-to-buffer source-buffer 'exit) + (kill-buffer edit-buffer)) + ;; Insert modified code. Ensure it ends with a newline character. + (org-with-wide-buffer + (when (and write-back (not (equal (buffer-substring beg end) code))) + (undo-boundary) + (goto-char beg) + (delete-region beg end) + (let ((expecting-bol (bolp))) + (insert code) + (when (and expecting-bol (not (bolp))) (insert "\n"))))) + ;; If we are to return to source buffer, put point at an + ;; appropriate location. In particular, if block is hidden, move + ;; to the beginning of the block opening line. + (unless remote + (goto-char beg) + (cond + ;; Block is hidden; move at start of block. + ((cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block)) + (overlays-at (point))) + (beginning-of-line 0)) + (write-back (org-src--goto-coordinates coordinates beg end)))) + ;; Clean up left-over markers and restore window configuration. + (set-marker beg nil) + (set-marker end nil) + (when org-src--saved-temp-window-config + (set-window-configuration org-src--saved-temp-window-config) + (setq org-src--saved-temp-window-config nil)))) + + +(provide 'org-src) + +;;; org-src.el ends here diff --git a/elpa/org-9.1.14/org-table.el b/elpa/org-9.1.14/org-table.el new file mode 100644 index 00000000..e4513502 --- /dev/null +++ b/elpa/org-9.1.14/org-table.el @@ -0,0 +1,5570 @@ +;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file contains the table editor and spreadsheet for Org mode. + +;; Watch out: Here we are talking about two different kind of tables. +;; Most of the code is for the tables created with the Org mode table editor. +;; Sometimes, we talk about tables created and edited with the table.el +;; Emacs package. We call the former org-type tables, and the latter +;; table.el-type tables. + +;;; Code: + +(require 'cl-lib) +(require 'org) + +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-contents "org-element" (element)) +(declare-function org-element-extract-element "org-element" (element)) +(declare-function org-element-interpret-data "org-element" (data)) +(declare-function org-element-lineage "org-element" + (blob &optional types with-self)) +(declare-function org-element-map "org-element" + (data types fun + &optional info first-match no-recursion with-affiliated)) +(declare-function org-element-parse-buffer "org-element" + (&optional granularity visible-only)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-type "org-element" (element)) + +(declare-function org-export-create-backend "ox" (&rest rest) t) +(declare-function org-export-data-with-backend "ox" (data backend info)) +(declare-function org-export-filter-apply-functions "ox" + (filters value info)) +(declare-function org-export-first-sibling-p "ox" (blob info)) +(declare-function org-export-get-backend "ox" (name)) +(declare-function org-export-get-environment "ox" + (&optional backend subtreep ext-plist)) +(declare-function org-export-install-filters "ox" (info)) +(declare-function org-export-table-has-special-column-p "ox" (table)) +(declare-function org-export-table-row-is-special-p "ox" (table-row info)) + +(declare-function calc-eval "calc" (str &optional separator &rest args)) + +(defvar constants-unit-system) +(defvar org-element-use-cache) +(defvar org-export-filters-alist) +(defvar org-table-follow-field-mode) +(defvar orgtbl-mode) ; defined below +(defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized +(defvar sort-fold-case) + +(defvar orgtbl-after-send-table-hook nil + "Hook for functions attaching to `C-c C-c', if the table is sent. +This can be used to add additional functionality after the table is sent +to the receiver position, otherwise, if table is not sent, the functions +are not run.") + +(defvar org-table-TBLFM-begin-regexp "^[ \t]*|.*\n[ \t]*#\\+TBLFM: ") + +(defcustom orgtbl-optimized t + "Non-nil means use the optimized table editor version for `orgtbl-mode'. + +In the optimized version, the table editor takes over all simple keys that +normally just insert a character. In tables, the characters are inserted +in a way to minimize disturbing the table structure (i.e. in overwrite mode +for empty fields). Outside tables, the correct binding of the keys is +restored. + +Changing this variable requires a restart of Emacs to become +effective." + :group 'org-table + :type 'boolean) + +(defcustom orgtbl-radio-table-templates + '((latex-mode "% BEGIN RECEIVE ORGTBL %n +% END RECEIVE ORGTBL %n +\\begin{comment} +#+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0 +| | | +\\end{comment}\n") + (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n +@c END RECEIVE ORGTBL %n +@ignore +#+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0 +| | | +@end ignore\n") + (html-mode "<!-- BEGIN RECEIVE ORGTBL %n --> +<!-- END RECEIVE ORGTBL %n --> +<!-- +#+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0 +| | | +-->\n") + (org-mode "#+ BEGIN RECEIVE ORGTBL %n +#+ END RECEIVE ORGTBL %n + +#+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0 +| | | +")) + "Templates for radio tables in different major modes. +Each template must define lines that will be treated as a comment and that +must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\" +lines where \"%n\" will be replaced with the name of the table during +insertion of the template. The transformed table will later be inserted +between these lines. + +The template should also contain a minimal table in a multiline comment. +If multiline comments are not possible in the buffer language, +you can pack it into a string that will not be used when the code +is compiled or executed. Above the table will you need a line with +the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to +convert the table into a data structure useful in the +language of the buffer. Check the manual for the section on +\"Translator functions\", and more generally check out +the Info node `(org)Tables in arbitrary syntax'. + +All occurrences of %n in a template will be replaced with the name of the +table, obtained by prompting the user." + :group 'org-table + :type '(repeat + (list (symbol :tag "Major mode") + (string :tag "Format")))) + +(defgroup org-table-settings nil + "Settings for tables in Org mode." + :tag "Org Table Settings" + :group 'org-table) + +(defcustom org-table-default-size "5x2" + "The default size for newly created tables, Columns x Rows." + :group 'org-table-settings + :type 'string) + +(defcustom org-table-number-regexp + "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$" + "Regular expression for recognizing numbers in table columns. +If a table column contains mostly numbers, it will be aligned to the +right. If not, it will be aligned to the left. + +The default value of this option is a regular expression which allows +anything which looks remotely like a number as used in scientific +context. For example, all of the following will be considered a +number: + 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5 + +Other options offered by the customize interface are more restrictive." + :group 'org-table-settings + :type '(choice + (const :tag "Positive Integers" + "^[0-9]+$") + (const :tag "Integers" + "^[-+]?[0-9]+$") + (const :tag "Floating Point Numbers" + "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$") + (const :tag "Floating Point Number or Integer" + "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$") + (const :tag "Exponential, Floating point, Integer" + "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$") + (const :tag "Very General Number-Like, including hex and Calc radix" + "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$") + (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark" + "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$") + (string :tag "Regexp:"))) + +(defcustom org-table-number-fraction 0.5 + "Fraction of numbers in a column required to make the column align right. +In a column all non-white fields are considered. If at least +this fraction of fields is matched by `org-table-number-regexp', +alignment to the right border applies." + :group 'org-table-settings + :type 'number) + +(defgroup org-table-editing nil + "Behavior of tables during editing in Org mode." + :tag "Org Table Editing" + :group 'org-table) + +(defcustom org-table-automatic-realign t + "Non-nil means automatically re-align table when pressing TAB or RETURN. +When nil, aligning is only done with `\\[org-table-align]', or after column +removal/insertion." + :group 'org-table-editing + :type 'boolean) + +(defcustom org-table-auto-blank-field t + "Non-nil means automatically blank table field when starting to type into it. +This only happens when typing immediately after a field motion +command (TAB, S-TAB or RET)." + :group 'org-table-editing + :type 'boolean) + +(defcustom org-table-exit-follow-field-mode-when-leaving-table t + "Non-nil means automatically exit the follow mode. +When nil, the follow mode will stay on and be active in any table +the cursor enters. Since the table follow filed mode messes with the +window configuration, it is not recommended to set this variable to nil, +except maybe locally in a special file that has mostly tables with long +fields." + :group 'org-table + :version "24.1" + :type 'boolean) + +(defcustom org-table-fix-formulas-confirm nil + "Whether the user should confirm when Org fixes formulas." + :group 'org-table-editing + :version "24.1" + :type '(choice + (const :tag "with yes-or-no" yes-or-no-p) + (const :tag "with y-or-n" y-or-n-p) + (const :tag "no confirmation" nil))) +(put 'org-table-fix-formulas-confirm + 'safe-local-variable + #'(lambda (x) (member x '(yes-or-no-p y-or-n-p)))) + +(defcustom org-table-tab-jumps-over-hlines t + "Non-nil means tab in the last column of a table with jump over a hline. +If a horizontal separator line is following the current line, +`org-table-next-field' can either create a new row before that line, or jump +over the line. When this option is nil, a new line will be created before +this line." + :group 'org-table-editing + :type 'boolean) + +(defgroup org-table-calculation nil + "Options concerning tables in Org mode." + :tag "Org Table Calculation" + :group 'org-table) + +(defcustom org-table-use-standard-references 'from + "Non-nil means using table references like B3 instead of @3$2. +Possible values are: +nil never use them +from accept as input, do not present for editing +t accept as input and present for editing" + :group 'org-table-calculation + :type '(choice + (const :tag "Never, don't even check user input for them" nil) + (const :tag "Always, both as user input, and when editing" t) + (const :tag "Convert user input, don't offer during editing" from))) + +(defcustom org-table-copy-increment t + "Non-nil means increment when copying current field with \ +`\\[org-table-copy-down]'." + :group 'org-table-calculation + :version "26.1" + :package-version '(Org . "8.3") + :type '(choice + (const :tag "Use the difference between the current and the above fields" t) + (integer :tag "Use a number" 1) + (const :tag "Don't increment the value when copying a field" nil))) + +(defcustom org-calc-default-modes + '(calc-internal-prec 12 + calc-float-format (float 8) + calc-angle-mode deg + calc-prefer-frac nil + calc-symbolic-mode nil + calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm)) + calc-display-working-message t + ) + "List with Calc mode settings for use in `calc-eval' for table formulas. +The list must contain alternating symbols (Calc modes variables and values). +Don't remove any of the default settings, just change the values. Org mode +relies on the variables to be present in the list." + :group 'org-table-calculation + :type 'plist) + +(defcustom org-table-duration-custom-format 'hours + "Format for the output of calc computations like $1+$2;t. +The default value is `hours', and will output the results as a +number of hours. Other allowed values are `seconds', `minutes' and +`days', and the output will be a fraction of seconds, minutes or +days. `hh:mm' selects to use hours and minutes, ignoring seconds. +The `U' flag in a table formula will select this specific format for +a single formula." + :group 'org-table-calculation + :version "24.1" + :type '(choice (symbol :tag "Seconds" 'seconds) + (symbol :tag "Minutes" 'minutes) + (symbol :tag "Hours " 'hours) + (symbol :tag "Days " 'days) + (symbol :tag "HH:MM " 'hh:mm))) + +(defcustom org-table-duration-hour-zero-padding t + "Non-nil means hours in table duration computations should be zero-padded. +So this is about 08:32:34 versus 8:33:34." + :group 'org-table-calculation + :version "26.1" + :package-version '(Org . "9.1") + :type 'boolean + :safe #'booleanp) + +(defcustom org-table-formula-field-format "%s" + "Format for fields which contain the result of a formula. +For example, using \"~%s~\" will display the result within tilde +characters. Beware that modifying the display can prevent the +field from being used in another formula." + :group 'org-table-settings + :version "24.1" + :type 'string) + +(defcustom org-table-formula-evaluate-inline t + "Non-nil means TAB and RET evaluate a formula in current table field. +If the current field starts with an equal sign, it is assumed to be a formula +which should be evaluated as described in the manual and in the documentation +string of the command `org-table-eval-formula'. This feature requires the +Emacs calc package. +When this variable is nil, formula calculation is only available through +the command `\\[org-table-eval-formula]'." + :group 'org-table-calculation + :type 'boolean) + +(defcustom org-table-formula-use-constants t + "Non-nil means interpret constants in formulas in tables. +A constant looks like `$c' or `$Grav' and will be replaced before evaluation +by the value given in `org-table-formula-constants', or by a value obtained +from the `constants.el' package." + :group 'org-table-calculation + :type 'boolean) + +(defcustom org-table-formula-constants nil + "Alist with constant names and values, for use in table formulas. +The car of each element is a name of a constant, without the `$' before it. +The cdr is the value as a string. For example, if you'd like to use the +speed of light in a formula, you would configure + + (setq org-table-formula-constants \\='((\"c\" . \"299792458.\"))) + +and then use it in an equation like `$1*$c'. + +Constants can also be defined on a per-file basis using a line like + +#+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6" + :group 'org-table-calculation + :type '(repeat + (cons (string :tag "name") + (string :tag "value")))) + +(defcustom org-table-allow-automatic-line-recalculation t + "Non-nil means lines marked with |#| or |*| will be recomputed automatically. +\\<org-mode-map>\ +Automatically means when `TAB' or `RET' or `\\[org-ctrl-c-ctrl-c]' \ +are pressed in the line." + :group 'org-table-calculation + :type 'boolean) + +(defcustom org-table-relative-ref-may-cross-hline t + "Non-nil means relative formula references may cross hlines. +Here are the allowed values: + +nil Relative references may not cross hlines. They will reference the + field next to the hline instead. Coming from below, the reference + will be to the field below the hline. Coming from above, it will be + to the field above. +t Relative references may cross hlines. +error An attempt to cross a hline will throw an error. + +It is probably good to never set this variable to nil, for the sake of +portability of tables." + :group 'org-table-calculation + :type '(choice + (const :tag "Allow to cross" t) + (const :tag "Stick to hline" nil) + (const :tag "Error on attempt to cross" error))) + +(defcustom org-table-formula-create-columns nil + "Non-nil means evaluation of formula can add new columns. +When non-nil, evaluating an out-of-bounds field can insert as +many columns as needed. When set to `warn', issue a warning when +doing so. When set to `prompt', ask user before creating a new +column. Otherwise, throw an error." + :group 'org-table-calculation + :version "26.1" + :package-version '(Org . "8.3") + :type '(choice + (const :tag "Out-of-bounds field generates an error (default)" nil) + (const :tag "Out-of-bounds field silently adds columns as needed" t) + (const :tag "Out-of-bounds field adds columns, but issues a warning" warn) + (const :tag "Prompt user when setting an out-of-bounds field" prompt))) + +(defgroup org-table-import-export nil + "Options concerning table import and export in Org mode." + :tag "Org Table Import Export" + :group 'org-table) + +(defcustom org-table-export-default-format "orgtbl-to-tsv" + "Default export parameters for `org-table-export'. +These can be overridden for a specific table by setting the +TABLE_EXPORT_FORMAT property. See the manual section on orgtbl +radio tables for the different export transformations and +available parameters." + :group 'org-table-import-export + :type 'string) + +(defcustom org-table-convert-region-max-lines 999 + "Max lines that `org-table-convert-region' will attempt to process. + +The function can be slow on larger regions; this safety feature +prevents it from hanging emacs." + :group 'org-table-import-export + :type 'integer + :version "26.1" + :package-version '(Org . "8.3")) + +(defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)" + "Regexp matching a line marked for automatic recalculation.") + +(defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)" + "Regexp matching a line marked for recalculation.") + +(defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)" + "Regexp matching a line marked for calculation.") + +(defconst org-table-border-regexp "^[ \t]*[^| \t]" + "Regexp matching any line outside an Org table.") + +(defvar org-table-last-highlighted-reference nil) + +(defvar org-table-formula-history nil) + +(defvar org-table-column-names nil + "Alist with column names, derived from the `!' line. +This variable is initialized with `org-table-analyze'.") + +(defvar org-table-column-name-regexp nil + "Regular expression matching the current column names. +This variable is initialized with `org-table-analyze'.") + +(defvar org-table-local-parameters nil + "Alist with parameter names, derived from the `$' line. +This variable is initialized with `org-table-analyze'.") + +(defvar org-table-named-field-locations nil + "Alist with locations of named fields. +Associations follow the pattern (NAME LINE COLUMN) where + NAME is the name of the field as a string, + LINE is the number of lines from the beginning of the table, + COLUMN is the column of the field, as an integer. +This variable is initialized with `org-table-analyze'.") + +(defvar org-table-current-line-types nil + "Table row types in current table. +This variable is initialized with `org-table-analyze'.") + +(defvar org-table-current-begin-pos nil + "Current table begin position, as a marker. +This variable is initialized with `org-table-analyze'.") + +(defvar org-table-current-ncol nil + "Number of columns in current table. +This variable is initialized with `org-table-analyze'.") + +(defvar org-table-dlines nil + "Vector of data line line numbers in the current table. +Line numbers are counted from the beginning of the table. This +variable is initialized with `org-table-analyze'.") + +(defvar org-table-hlines nil + "Vector of hline line numbers in the current table. +Line numbers are counted from the beginning of the table. This +variable is initialized with `org-table-analyze'.") + +(defconst org-table-range-regexp + "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?" + ;; 1 2 3 4 5 + "Regular expression for matching ranges in formulas.") + +(defconst org-table-range-regexp2 + (concat + "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)" + "\\.\\." + "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)") + "Match a range for reference display.") + +(defconst org-table-translate-regexp + (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)") + "Match a reference that needs translation, for reference display.") + +(defmacro org-table-save-field (&rest body) + "Save current field; execute BODY; restore field. +Field is restored even in case of abnormal exit." + (declare (debug (body))) + (org-with-gensyms (line column) + `(let ((,line (copy-marker (line-beginning-position))) + (,column (org-table-current-column))) + (unwind-protect + (progn ,@body) + (goto-char ,line) + (org-table-goto-column ,column) + (set-marker ,line nil))))) + +;;;###autoload +(defun org-table-create-with-table.el () + "Use the table.el package to insert a new table. +If there is already a table at point, convert between Org tables +and table.el tables." + (interactive) + (require 'table) + (cond + ((org-at-table.el-p) + (if (y-or-n-p "Convert table to Org table? ") + (org-table-convert))) + ((org-at-table-p) + (when (y-or-n-p "Convert table to table.el table? ") + (org-table-align) + (org-table-convert))) + (t (call-interactively 'table-insert)))) + +;;;###autoload +(defun org-table-create-or-convert-from-region (arg) + "Convert region to table, or create an empty table. +If there is an active region, convert it to a table, using the function +`org-table-convert-region'. See the documentation of that function +to learn how the prefix argument is interpreted to determine the field +separator. +If there is no such region, create an empty table with `org-table-create'." + (interactive "P") + (if (org-region-active-p) + (org-table-convert-region (region-beginning) (region-end) arg) + (org-table-create arg))) + +;;;###autoload +(defun org-table-create (&optional size) + "Query for a size and insert a table skeleton. +SIZE is a string Columns x Rows like for example \"3x2\"." + (interactive "P") + (unless size + (setq size (read-string + (concat "Table size Columns x Rows [e.g. " + org-table-default-size "]: ") + "" nil org-table-default-size))) + + (let* ((pos (point)) + (indent (make-string (current-column) ?\ )) + (split (org-split-string size " *x *")) + (rows (string-to-number (nth 1 split))) + (columns (string-to-number (car split))) + (line (concat (apply 'concat indent "|" (make-list columns " |")) + "\n"))) + (if (string-match "^[ \t]*$" (buffer-substring-no-properties + (point-at-bol) (point))) + (beginning-of-line 1) + (newline)) + ;; (mapcar (lambda (x) (insert line)) (make-list rows t)) + (dotimes (_ rows) (insert line)) + (goto-char pos) + (if (> rows 1) + ;; Insert a hline after the first row. + (progn + (end-of-line 1) + (insert "\n|-") + (goto-char pos))) + (org-table-align))) + +;;;###autoload +(defun org-table-convert-region (beg0 end0 &optional separator) + "Convert region to a table. + +The region goes from BEG0 to END0, but these borders will be moved +slightly, to make sure a beginning of line in the first line is included. + +SEPARATOR specifies the field separator in the lines. It can have the +following values: + +(4) Use the comma as a field separator +(16) Use a TAB as field separator +(64) Prompt for a regular expression as field separator +integer When a number, use that many spaces, or a TAB, as field separator +regexp When a regular expression, use it to match the separator +nil When nil, the command tries to be smart and figure out the + separator in the following way: + - when each line contains a TAB, assume TAB-separated material + - when each line contains a comma, assume CSV material + - else, assume one or more SPACE characters as separator." + (interactive "r\nP") + (let* ((beg (min beg0 end0)) + (end (max beg0 end0)) + re) + (if (> (count-lines beg end) org-table-convert-region-max-lines) + (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting" + org-table-convert-region-max-lines) + (if (equal separator '(64)) + (setq separator (read-regexp "Regexp for field separator"))) + (goto-char beg) + (beginning-of-line 1) + (setq beg (point-marker)) + (goto-char end) + (if (bolp) (backward-char 1) (end-of-line 1)) + (setq end (point-marker)) + ;; Get the right field separator + (unless separator + (goto-char beg) + (setq separator + (cond + ((not (re-search-forward "^[^\n\t]+$" end t)) '(16)) + ((not (re-search-forward "^[^\n,]+$" end t)) '(4)) + (t 1)))) + (goto-char beg) + (if (equal separator '(4)) + (while (< (point) end) + ;; parse the csv stuff + (cond + ((looking-at "^") (insert "| ")) + ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2)) + ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"") + (replace-match "\\1") + (if (looking-at "\"") (insert "\""))) + ((looking-at "[^,\n]+") (goto-char (match-end 0))) + ((looking-at "[ \t]*,") (replace-match " | ")) + (t (beginning-of-line 2)))) + (setq re (cond + ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?") + ((equal separator '(16)) "^\\|\t") + ((integerp separator) + (if (< separator 1) + (user-error "Number of spaces in separator must be >= 1") + (format "^ *\\| *\t *\\| \\{%d,\\}" separator))) + ((stringp separator) + (format "^ *\\|%s" separator)) + (t (error "This should not happen")))) + (while (re-search-forward re end t) + (replace-match "| " t t))) + (goto-char beg) + (org-table-align)))) + +;;;###autoload +(defun org-table-import (file separator) + "Import FILE as a table. + +The command tries to be smart and figure out the separator in the +following way: + + - when each line contains a TAB, assume TAB-separated material + - when each line contains a comma, assume CSV material + - else, assume one or more SPACE characters as separator. + +When non-nil, SEPARATOR specifies the field separator in the +lines. It can have the following values: + +(4) Use the comma as a field separator +(16) Use a TAB as field separator +(64) Prompt for a regular expression as field separator +integer When a number, use that many spaces, or a TAB, as field separator +regexp When a regular expression, use it to match the separator." + (interactive "f\nP") + (unless (bolp) (insert "\n")) + (let ((beg (point)) + (pm (point-max))) + (insert-file-contents file) + (org-table-convert-region beg (+ (point) (- (point-max) pm)) separator))) + + +;;;###autoload +(defun org-table-export (&optional file format) + "Export table to a file, with configurable format. +Such a file can be imported into usual spreadsheet programs. + +FILE can be the output file name. If not given, it will be taken +from a TABLE_EXPORT_FILE property in the current entry or higher +up in the hierarchy, or the user will be prompted for a file +name. FORMAT can be an export format, of the same kind as it +used when `orgtbl-mode' sends a table in a different format. + +The command suggests a format depending on TABLE_EXPORT_FORMAT, +whether it is set locally or up in the hierarchy, then on the +extension of the given file name, and finally on the variable +`org-table-export-default-format'." + (interactive) + (unless (org-at-table-p) (user-error "No table at point")) + (org-table-align) ; Make sure we have everything we need. + (let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t)))) + (unless file + (setq file (read-file-name "Export table to: ")) + (unless (or (not (file-exists-p file)) + (y-or-n-p (format "Overwrite file %s? " file))) + (user-error "File not written"))) + (when (file-directory-p file) + (user-error "This is a directory path, not a file")) + (when (and (buffer-file-name (buffer-base-buffer)) + (file-equal-p + (file-truename file) + (file-truename (buffer-file-name (buffer-base-buffer))))) + (user-error "Please specify a file name that is different from current")) + (let ((fileext (concat (file-name-extension file) "$")) + (format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t)))) + (unless format + (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex" + "orgtbl-to-html" "orgtbl-to-generic" + "orgtbl-to-texinfo" "orgtbl-to-orgtbl" + "orgtbl-to-unicode")) + (deffmt-readable + (replace-regexp-in-string + "\t" "\\t" + (replace-regexp-in-string + "\n" "\\n" + (or (car (delq nil + (mapcar + (lambda (f) + (and (string-match-p fileext f) f)) + formats))) + org-table-export-default-format) + t t) t t))) + (setq format + (org-completing-read + "Format: " formats nil nil deffmt-readable)))) + (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format) + (let ((transform (intern (match-string 1 format))) + (params (and (match-end 2) + (read (concat "(" (match-string 2 format) ")")))) + (table (org-table-to-lisp + (buffer-substring-no-properties + (org-table-begin) (org-table-end))))) + (unless (fboundp transform) + (user-error "No such transformation function %s" transform)) + (let (buf) + (with-current-buffer (find-file-noselect file) + (setq buf (current-buffer)) + (erase-buffer) + (fundamental-mode) + (insert (funcall transform table params) "\n") + (save-buffer)) + (kill-buffer buf)) + (message "Export done.")) + (user-error "TABLE_EXPORT_FORMAT invalid"))))) + +(defvar org-table-aligned-begin-marker (make-marker) + "Marker at the beginning of the table last aligned. +Used to check if cursor still is in that table, to minimize realignment.") +(defvar org-table-aligned-end-marker (make-marker) + "Marker at the end of the table last aligned. +Used to check if cursor still is in that table, to minimize realignment.") +(defvar org-table-last-alignment nil + "List of flags for flushright alignment, from the last re-alignment. +This is being used to correctly align a single field after TAB or RET.") +(defvar org-table-last-column-widths nil + "List of max width of fields in each column. +This is being used to correctly align a single field after TAB or RET.") +(defvar-local org-table-formula-debug nil + "Non-nil means debug table formulas. +When nil, simply write \"#ERROR\" in corrupted fields.") +(defvar-local org-table-overlay-coordinates nil + "Overlay coordinates after each align of a table.") + +(defvar org-last-recalc-line nil) +(defvar org-table-do-narrow t) ; for dynamic scoping +(defconst org-narrow-column-arrow "=>" + "Used as display property in narrowed table columns.") + +;;;###autoload +(defun org-table-align () + "Align the table at point by aligning all vertical bars." + (interactive) + (let* ((beg (org-table-begin)) + (end (copy-marker (org-table-end)))) + (org-table-save-field + ;; Make sure invisible characters in the table are at the right + ;; place since column widths take them into account. + (font-lock-fontify-region beg end) + (move-marker org-table-aligned-begin-marker beg) + (move-marker org-table-aligned-end-marker end) + (goto-char beg) + (let* ((indent (progn (looking-at "[ \t]*") (match-string 0))) + ;; Table's rows. Separators are replaced by nil. Trailing + ;; spaces are also removed. + (lines (mapcar (lambda (l) + (and (not (string-match-p "\\`[ \t]*|-" l)) + (let ((l (org-trim l))) + (remove-text-properties + 0 (length l) '(display t org-cwidth t) l) + l))) + (org-split-string (buffer-substring beg end) "\n"))) + ;; Get the data fields by splitting the lines. + (fields (mapcar (lambda (l) (org-split-string l " *| *")) + (remq nil lines))) + ;; Compute number of fields in the longest line. If the + ;; table contains no field, create a default table. + (maxfields (if fields (apply #'max (mapcar #'length fields)) + (kill-region beg end) + (org-table-create org-table-default-size) + (user-error "Empty table - created default table"))) + ;; A list of empty strings to fill any short rows on output. + (emptycells (make-list maxfields "")) + lengths typenums) + ;; Check for special formatting. + (dotimes (i maxfields) + (let ((column (mapcar (lambda (x) (or (nth i x) "")) fields)) + fmax falign) + ;; Look for an explicit width or alignment. + (when (save-excursion + (or (re-search-forward "| *<[lrc][0-9]*> *\\(|\\|$\\)" end t) + (and org-table-do-narrow + (re-search-forward + "| *<[lrc]?[0-9]+> *\\(|\\|$\\)" end t)))) + (catch :exit + (dolist (cell column) + (when (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'" cell) + (when (match-end 1) (setq falign (match-string 1 cell))) + (when (and org-table-do-narrow (match-end 2)) + (setq fmax (string-to-number (match-string 2 cell)))) + (when (or falign fmax) (throw :exit nil))))) + ;; Find fields that are wider than FMAX, and shorten them. + (when fmax + (dolist (x column) + (when (> (org-string-width x) fmax) + (org-add-props x nil + 'help-echo + (concat + "Clipped table field, use `\\[org-table-edit-field]' to \ +edit. Full value is:\n" + (substring-no-properties x))) + (let ((l (length x)) + (f1 (min fmax + (or (string-match org-bracket-link-regexp x) + fmax))) + (f2 1)) + (unless (> f1 1) + (user-error + "Cannot narrow field starting with wide link \"%s\"" + (match-string 0 x))) + (if (= (org-string-width x) l) (setq f2 f1) + (setq f2 1) + (while (< (org-string-width (substring x 0 f2)) f1) + (cl-incf f2))) + (add-text-properties f2 l (list 'org-cwidth t) x) + (add-text-properties + (if (>= (string-width (substring x (1- f2) f2)) 2) (1- f2) + (- f2 2)) + f2 + (list 'display org-narrow-column-arrow) + x)))))) + ;; Get the maximum width for each column + (push (or fmax (apply #'max 1 (mapcar #'org-string-width column))) + lengths) + ;; Get the fraction of numbers among non-empty cells to + ;; decide about alignment of the column. + (if falign (push (equal (downcase falign) "r") typenums) + (let ((cnt 0) + (frac 0.0)) + (dolist (x column) + (unless (equal x "") + (setq frac + (/ (+ (* frac cnt) + (if (string-match-p org-table-number-regexp x) + 1 + 0)) + (cl-incf cnt))))) + (push (>= frac org-table-number-fraction) typenums))))) + (setq lengths (nreverse lengths)) + (setq typenums (nreverse typenums)) + ;; Store alignment of this table, for later editing of single + ;; fields. + (setq org-table-last-alignment typenums) + (setq org-table-last-column-widths lengths) + ;; With invisible characters, `format' does not get the field + ;; width right So we need to make these fields wide by hand. + ;; Invisible characters may be introduced by fontified links, + ;; emphasis, macros or sub/superscripts. + (when (or (text-property-any beg end 'invisible 'org-link) + (text-property-any beg end 'invisible t)) + (dotimes (i maxfields) + (let ((len (nth i lengths))) + (dotimes (j (length fields)) + (let* ((c (nthcdr i (nth j fields))) + (cell (car c))) + (when (and + (stringp cell) + (let ((l (length cell))) + (or (text-property-any 0 l 'invisible 'org-link cell) + (text-property-any beg end 'invisible t))) + (< (org-string-width cell) len)) + (let ((s (make-string (- len (org-string-width cell)) ?\s))) + (setcar c (if (nth i typenums) (concat s cell) + (concat cell s)))))))))) + + ;; Compute the formats needed for output of the table. + (let ((hfmt (concat indent "|")) + (rfmt (concat indent "|")) + (rfmt1 " %%%s%ds |") + (hfmt1 "-%s-+")) + (dolist (l lengths (setq hfmt (concat (substring hfmt 0 -1) "|"))) + (let ((ty (if (pop typenums) "" "-"))) ; Flush numbers right. + (setq rfmt (concat rfmt (format rfmt1 ty l))) + (setq hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))) + ;; Replace modified lines only. Check not only contents, but + ;; also columns' width. + (dolist (l lines) + (let ((line + (if l (apply #'format rfmt (append (pop fields) emptycells)) + hfmt)) + (previous (buffer-substring (point) (line-end-position)))) + (if (and (equal previous line) + (let ((a 0) + (b 0)) + (while (and (progn + (setq a (next-single-property-change + a 'org-cwidth previous)) + (setq b (next-single-property-change + b 'org-cwidth line))) + (eq a b))) + (eq a b))) + (forward-line) + (insert line "\n") + (delete-region (point) (line-beginning-position 2)))))) + (when (and orgtbl-mode (not (derived-mode-p 'org-mode))) + (goto-char org-table-aligned-begin-marker) + (while (org-hide-wide-columns org-table-aligned-end-marker))) + (set-marker end nil) + (when org-table-overlay-coordinates (org-table-overlay-coordinates)) + (setq org-table-may-need-update nil))))) + +;;;###autoload +(defun org-table-begin (&optional table-type) + "Find the beginning of the table and return its position. +With a non-nil optional argument TABLE-TYPE, return the beginning +of a table.el-type table. This function assumes point is on +a table." + (cond (table-type + (org-element-property :post-affiliated (org-element-at-point))) + ((save-excursion + (and (re-search-backward org-table-border-regexp nil t) + (line-beginning-position 2)))) + (t (point-min)))) + +;;;###autoload +(defun org-table-end (&optional table-type) + "Find the end of the table and return its position. +With a non-nil optional argument TABLE-TYPE, return the end of +a table.el-type table. This function assumes point is on +a table." + (save-excursion + (cond (table-type + (goto-char (org-element-property :end (org-element-at-point))) + (skip-chars-backward " \t\n") + (line-beginning-position 2)) + ((re-search-forward org-table-border-regexp nil t) + (match-beginning 0)) + ;; When the line right after the table is the last line in + ;; the buffer with trailing spaces but no final newline + ;; character, be sure to catch the correct ending at its + ;; beginning. In any other case, ending is expected to be + ;; at point max. + (t (goto-char (point-max)) + (skip-chars-backward " \t") + (if (bolp) (point) (line-end-position)))))) + +;;;###autoload +(defun org-table-justify-field-maybe (&optional new) + "Justify the current field, text to left, number to right. +Optional argument NEW may specify text to replace the current field content." + (cond + ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway + ((org-at-table-hline-p)) + ((and (not new) + (or (not (eq (marker-buffer org-table-aligned-begin-marker) + (current-buffer))) + (< (point) org-table-aligned-begin-marker) + (>= (point) org-table-aligned-end-marker))) + ;; This is not the same table, force a full re-align. + (setq org-table-may-need-update t)) + (t + ;; Realign the current field, based on previous full realign. + (let ((pos (point)) + (col (org-table-current-column))) + (when (> col 0) + (skip-chars-backward "^|") + (if (not (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")) + (setq org-table-may-need-update t) + (let* ((numbers? (nth (1- col) org-table-last-alignment)) + (cell (match-string 0)) + (field (match-string 1)) + (len (max 1 (- (org-string-width cell) 3))) + (properly-closed? (/= (match-beginning 2) (match-end 2))) + (fmt (format (if numbers? " %%%ds %s" " %%-%ds %s") + len + (if properly-closed? "|" + (setq org-table-may-need-update t) + ""))) + (new-cell + (cond ((not new) (format fmt field)) + ((<= (org-string-width new) len) (format fmt new)) + (t + (setq org-table-may-need-update t) + (format " %s |" new))))) + (unless (equal new-cell cell) + (let (org-table-may-need-update) + (replace-match new-cell t t))) + (goto-char pos)))))))) + +;;;###autoload +(defun org-table-next-field () + "Go to the next field in the current table, creating new lines as needed. +Before doing so, re-align the table if necessary." + (interactive) + (org-table-maybe-eval-formula) + (org-table-maybe-recalculate-line) + (if (and org-table-automatic-realign + org-table-may-need-update) + (org-table-align)) + (let ((end (org-table-end))) + (if (org-at-table-hline-p) + (end-of-line 1)) + (condition-case nil + (progn + (re-search-forward "|" end) + (if (looking-at "[ \t]*$") + (re-search-forward "|" end)) + (if (and (looking-at "-") + org-table-tab-jumps-over-hlines + (re-search-forward "^[ \t]*|\\([^-]\\)" end t)) + (goto-char (match-beginning 1))) + (if (looking-at "-") + (progn + (beginning-of-line 0) + (org-table-insert-row 'below)) + (if (looking-at " ") (forward-char 1)))) + (error + (org-table-insert-row 'below))))) + +;;;###autoload +(defun org-table-previous-field () + "Go to the previous field in the table. +Before doing so, re-align the table if necessary." + (interactive) + (org-table-justify-field-maybe) + (org-table-maybe-recalculate-line) + (when (and org-table-automatic-realign + org-table-may-need-update) + (org-table-align)) + (when (org-at-table-hline-p) + (end-of-line)) + (let ((start (org-table-begin)) + (origin (point))) + (condition-case nil + (progn + (search-backward "|" start nil 2) + (while (looking-at-p "|\\(?:-\\|[ \t]*$\\)") + (search-backward "|" start))) + (error + (goto-char origin) + (user-error "Cannot move to previous table field")))) + (when (looking-at "| ?") + (goto-char (match-end 0)))) + +(defun org-table-beginning-of-field (&optional n) + "Move to the beginning of the current table field. +If already at or before the beginning, move to the beginning of the +previous field. +With numeric argument N, move N-1 fields backward first." + (interactive "p") + (let ((pos (point))) + (while (> n 1) + (setq n (1- n)) + (org-table-previous-field)) + (if (not (re-search-backward "|" (point-at-bol 0) t)) + (user-error "No more table fields before the current") + (goto-char (match-end 0)) + (and (looking-at " ") (forward-char 1))) + (if (>= (point) pos) (org-table-beginning-of-field 2)))) + +(defun org-table-end-of-field (&optional n) + "Move to the end of the current table field. +If already at or after the end, move to the end of the next table field. +With numeric argument N, move N-1 fields forward first." + (interactive "p") + (let ((pos (point))) + (while (> n 1) + (setq n (1- n)) + (org-table-next-field)) + (when (re-search-forward "|" (point-at-eol 1) t) + (backward-char 1) + (skip-chars-backward " ") + (if (and (equal (char-before (point)) ?|) (looking-at " ")) + (forward-char 1))) + (if (<= (point) pos) (org-table-end-of-field 2)))) + +;;;###autoload +(defun org-table-next-row () + "Go to the next row (same column) in the current table. +Before doing so, re-align the table if necessary." + (interactive) + (org-table-maybe-eval-formula) + (org-table-maybe-recalculate-line) + (if (and org-table-automatic-realign + org-table-may-need-update) + (org-table-align)) + (let ((col (org-table-current-column))) + (beginning-of-line 2) + (when (or (not (org-at-table-p)) + (org-at-table-hline-p)) + (beginning-of-line 0) + (org-table-insert-row 'below)) + (org-table-goto-column col) + (skip-chars-backward "^|\n\r") + (when (looking-at " ") (forward-char)))) + +;;;###autoload +(defun org-table-copy-down (n) + "Copy the value of the current field one row below. + +If the field at the cursor is empty, copy the content of the +nearest non-empty field above. With argument N, use the Nth +non-empty field. + +If the current field is not empty, it is copied down to the next +row, and the cursor is moved with it. Therefore, repeating this +command causes the column to be filled row-by-row. + +If the variable `org-table-copy-increment' is non-nil and the +field is an integer or a timestamp, it will be incremented while +copying. By default, increment by the difference between the +value in the current field and the one in the field above. To +increment using a fixed integer, set `org-table-copy-increment' +to a number. In the case of a timestamp, increment by days." + (interactive "p") + (let* ((colpos (org-table-current-column)) + (col (current-column)) + (field (save-excursion (org-table-get-field))) + (field-up (or (save-excursion + (org-table-get (1- (org-table-current-line)) + (org-table-current-column))) "")) + (non-empty (string-match "[^ \t]" field)) + (non-empty-up (string-match "[^ \t]" field-up)) + (beg (org-table-begin)) + (orig-n n) + txt txt-up inc) + (org-table-check-inside-data-field) + (if (not non-empty) + (save-excursion + (setq txt + (catch 'exit + (while (progn (beginning-of-line 1) + (re-search-backward org-table-dataline-regexp + beg t)) + (org-table-goto-column colpos t) + (if (and (looking-at + "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|") + (<= (setq n (1- n)) 0)) + (throw 'exit (match-string 1)))))) + (setq field-up + (catch 'exit + (while (progn (beginning-of-line 1) + (re-search-backward org-table-dataline-regexp + beg t)) + (org-table-goto-column colpos t) + (if (and (looking-at + "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|") + (<= (setq n (1- n)) 0)) + (throw 'exit (match-string 1)))))) + (setq non-empty-up (and field-up (string-match "[^ \t]" field-up)))) + ;; Above field was not empty, go down to the next row + (setq txt (org-trim field)) + (org-table-next-row) + (org-table-blank-field)) + (if non-empty-up (setq txt-up (org-trim field-up))) + (setq inc (cond + ((numberp org-table-copy-increment) org-table-copy-increment) + (txt-up (cond ((and (string-match org-ts-regexp3 txt-up) + (string-match org-ts-regexp3 txt)) + (- (org-time-string-to-absolute txt) + (org-time-string-to-absolute txt-up))) + ((string-match org-ts-regexp3 txt) 1) + ((string-match "\\([-+]\\)?\\(?:[0-9]+\\)?\\(?:\.[0-9]+\\)?" txt-up) + (- (string-to-number txt) + (string-to-number (match-string 0 txt-up)))) + (t 1))) + (t 1))) + (if (not txt) + (user-error "No non-empty field found") + (if (and org-table-copy-increment + (not (equal orig-n 0)) + (string-match-p "^[-+^/*0-9eE.]+$" txt) + (< (string-to-number txt) 100000000)) + (setq txt (calc-eval (concat txt "+" (number-to-string inc))))) + (insert txt) + (org-move-to-column col) + (if (and org-table-copy-increment (org-at-timestamp-p 'lax)) + (org-timestamp-up-day inc) + (org-table-maybe-recalculate-line)) + (org-table-align) + (org-move-to-column col)))) + +(defun org-table-check-inside-data-field (&optional noerror) + "Is point inside a table data field? +I.e. not on a hline or before the first or after the last column? +This actually throws an error, so it aborts the current command." + (cond ((and (org-at-table-p) + (not (save-excursion (skip-chars-backward " \t") (bolp))) + (not (org-at-table-hline-p)) + (not (looking-at "[ \t]*$")))) + (noerror nil) + (t (user-error "Not in table data field")))) + +(defvar org-table-clip nil + "Clipboard for table regions.") + +(defun org-table-get (line column) + "Get the field in table line LINE, column COLUMN. +If LINE is larger than the number of data lines in the table, the function +returns nil. However, if COLUMN is too large, we will simply return an +empty string. +If LINE is nil, use the current line. +If COLUMN is nil, use the current column." + (setq column (or column (org-table-current-column))) + (save-excursion + (and (or (not line) (org-table-goto-line line)) + (org-trim (org-table-get-field column))))) + +(defun org-table-put (line column value &optional align) + "Put VALUE into line LINE, column COLUMN. +When ALIGN is set, also realign the table." + (setq column (or column (org-table-current-column))) + (prog1 (save-excursion + (and (or (not line) (org-table-goto-line line)) + (progn (org-table-goto-column column nil 'force) t) + (org-table-get-field column value))) + (and align (org-table-align)))) + +(defun org-table-current-line () + "Return the index of the current data line." + (let ((pos (point)) (end (org-table-end)) (cnt 0)) + (save-excursion + (goto-char (org-table-begin)) + (while (and (re-search-forward org-table-dataline-regexp end t) + (setq cnt (1+ cnt)) + (< (point-at-eol) pos)))) + cnt)) + +(defun org-table-goto-line (N) + "Go to the Nth data line in the current table. +Return t when the line exists, nil if it does not exist." + (goto-char (org-table-begin)) + (let ((end (org-table-end)) (cnt 0)) + (while (and (re-search-forward org-table-dataline-regexp end t) + (< (setq cnt (1+ cnt)) N))) + (= cnt N))) + +;;;###autoload +(defun org-table-blank-field () + "Blank the current table field or active region." + (interactive) + (org-table-check-inside-data-field) + (if (and (called-interactively-p 'any) (org-region-active-p)) + (let (org-table-clip) + (org-table-cut-region (region-beginning) (region-end))) + (skip-chars-backward "^|") + (backward-char 1) + (if (looking-at "|[^|\n]+") + (let* ((pos (match-beginning 0)) + (match (match-string 0)) + (len (org-string-width match))) + (replace-match (concat "|" (make-string (1- len) ?\ ))) + (goto-char (+ 2 pos)) + (substring match 1))))) + +(defun org-table-get-field (&optional n replace) + "Return the value of the field in column N of current row. +N defaults to current column. If REPLACE is a string, replace +field with this value. The return value is always the old +value." + (when n (org-table-goto-column n)) + (skip-chars-backward "^|\n") + (if (or (bolp) (looking-at-p "[ \t]*$")) + ;; Before first column or after last one. + "" + (looking-at "[^|\r\n]*") + (let* ((pos (match-beginning 0)) + (val (buffer-substring pos (match-end 0)))) + (when replace + (replace-match (if (equal replace "") " " replace) t t)) + (goto-char (min (line-end-position) (1+ pos))) + val))) + +;;;###autoload +(defun org-table-field-info (_arg) + "Show info about the current field, and highlight any reference at point." + (interactive "P") + (unless (org-at-table-p) (user-error "Not at a table")) + (org-table-analyze) + (save-excursion + (let* ((pos (point)) + (col (org-table-current-column)) + (cname (car (rassoc (int-to-string col) org-table-column-names))) + (name (car (rassoc (list (count-lines org-table-current-begin-pos + (line-beginning-position)) + col) + org-table-named-field-locations))) + (eql (org-table-expand-lhs-ranges + (mapcar + (lambda (e) + (cons (org-table-formula-handle-first/last-rc (car e)) + (cdr e))) + (org-table-get-stored-formulas)))) + (dline (org-table-current-dline)) + (ref (format "@%d$%d" dline col)) + (ref1 (org-table-convert-refs-to-an ref)) + ;; Prioritize field formulas over column formulas. + (fequation (or (assoc name eql) (assoc ref eql))) + (cequation (assoc (format "$%d" col) eql)) + (eqn (or fequation cequation))) + (let ((p (and eqn (get-text-property 0 :orig-eqn (car eqn))))) + (when p (setq eqn p))) + (goto-char pos) + (ignore-errors (org-table-show-reference 'local)) + (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s" + dline col + (if cname (concat " or $" cname) "") + dline col ref1 + (if name (concat " or $" name) "") + ;; FIXME: formula info not correct if special table line + (if eqn + (concat ", formula: " + (org-table-formula-to-user + (concat + (if (or (string-prefix-p "$" (car eqn)) + (string-prefix-p "@" (car eqn))) + "" + "$") + (car eqn) "=" (cdr eqn)))) + ""))))) + +(defun org-table-current-column () + "Find out which column we are in." + (interactive) + (save-excursion + (let ((column 0) (pos (point))) + (beginning-of-line) + (while (search-forward "|" pos t) (cl-incf column)) + column))) + +(defun org-table-current-dline () + "Find out what table data line we are in. +Only data lines count for this." + (save-excursion + (let ((c 0) + (pos (line-beginning-position))) + (goto-char (org-table-begin)) + (while (<= (point) pos) + (when (looking-at org-table-dataline-regexp) (cl-incf c)) + (forward-line)) + c))) + +;;;###autoload +(defun org-table-goto-column (n &optional on-delim force) + "Move the cursor to the Nth column in the current table line. +With optional argument ON-DELIM, stop with point before the left delimiter +of the field. +If there are less than N fields, just go to after the last delimiter. +However, when FORCE is non-nil, create new columns if necessary." + (interactive "p") + (beginning-of-line 1) + (when (> n 0) + (while (and (> (setq n (1- n)) -1) + (or (search-forward "|" (point-at-eol) t) + (and force + (progn (end-of-line 1) + (skip-chars-backward "^|") + (insert " | ") + t))))) + (when (and force (not (looking-at ".*|"))) + (save-excursion (end-of-line 1) (insert " | "))) + (if on-delim + (backward-char 1) + (if (looking-at " ") (forward-char 1))))) + +;;;###autoload +(defun org-table-insert-column () + "Insert a new column into the table." + (interactive) + (unless (org-at-table-p) (user-error "Not at a table")) + (org-table-find-dataline) + (let* ((col (max 1 (org-table-current-column))) + (beg (org-table-begin)) + (end (copy-marker (org-table-end)))) + (org-table-save-field + (goto-char beg) + (while (< (point) end) + (unless (org-at-table-hline-p) + (org-table-goto-column col t) + (insert "| ")) + (forward-line))) + (set-marker end nil) + (org-table-align) + (when (or (not org-table-fix-formulas-confirm) + (funcall org-table-fix-formulas-confirm "Fix formulas? ")) + (org-table-fix-formulas "$" nil (1- col) 1) + (org-table-fix-formulas "$LR" nil (1- col) 1)))) + +(defun org-table-find-dataline () + "Find a data line in the current table, which is needed for column commands." + (if (and (org-at-table-p) + (not (org-at-table-hline-p))) + t + (let ((col (current-column)) + (end (org-table-end))) + (org-move-to-column col) + (while (and (< (point) end) + (or (not (= (current-column) col)) + (org-at-table-hline-p))) + (beginning-of-line 2) + (org-move-to-column col)) + (if (and (org-at-table-p) + (not (org-at-table-hline-p))) + t + (user-error + "Please position cursor in a data line for column operations"))))) + +(defun org-table-line-to-dline (line &optional above) + "Turn a buffer line number into a data line number. + +If there is no data line in this line, return nil. + +If there is no matching dline (most likely the reference was +a hline), the first dline below it is used. When ABOVE is +non-nil, the one above is used." + (let ((min 1) + (max (1- (length org-table-dlines)))) + (cond ((or (> (aref org-table-dlines min) line) + (< (aref org-table-dlines max) line)) + nil) + ((= (aref org-table-dlines max) line) max) + (t (catch 'exit + (while (> (- max min) 1) + (let* ((mean (/ (+ max min) 2)) + (v (aref org-table-dlines mean))) + (cond ((= v line) (throw 'exit mean)) + ((> v line) (setq max mean)) + (t (setq min mean))))) + (if above min max)))))) + +;;;###autoload +(defun org-table-delete-column () + "Delete a column from the table." + (interactive) + (unless (org-at-table-p) (user-error "Not at a table")) + (org-table-find-dataline) + (org-table-check-inside-data-field) + (let ((col (org-table-current-column)) + (beg (org-table-begin)) + (end (copy-marker (org-table-end)))) + (org-table-save-field + (goto-char beg) + (while (< (point) end) + (if (org-at-table-hline-p) + nil + (org-table-goto-column col t) + (and (looking-at "|[^|\n]+|") + (replace-match "|"))) + (forward-line))) + (set-marker end nil) + (org-table-goto-column (max 1 (1- col))) + (org-table-align) + (when (or (not org-table-fix-formulas-confirm) + (funcall org-table-fix-formulas-confirm "Fix formulas? ")) + (org-table-fix-formulas + "$" (list (cons (number-to-string col) "INVALID")) col -1 col) + (org-table-fix-formulas + "$LR" (list (cons (number-to-string col) "INVALID")) col -1 col)))) + +;;;###autoload +(defun org-table-move-column-right () + "Move column to the right." + (interactive) + (org-table-move-column nil)) +;;;###autoload +(defun org-table-move-column-left () + "Move column to the left." + (interactive) + (org-table-move-column 'left)) + +;;;###autoload +(defun org-table-move-column (&optional left) + "Move the current column to the right. With arg LEFT, move to the left." + (interactive "P") + (unless (org-at-table-p) (user-error "Not at a table")) + (org-table-find-dataline) + (org-table-check-inside-data-field) + (let* ((col (org-table-current-column)) + (col1 (if left (1- col) col)) + (colpos (if left (1- col) (1+ col))) + (beg (org-table-begin)) + (end (copy-marker (org-table-end)))) + (when (and left (= col 1)) + (user-error "Cannot move column further left")) + (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$")) + (user-error "Cannot move column further right")) + (org-table-save-field + (goto-char beg) + (while (< (point) end) + (unless (org-at-table-hline-p) + (org-table-goto-column col1 t) + (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|") + (transpose-regions + (match-beginning 1) (match-end 1) + (match-beginning 2) (match-end 2)))) + (forward-line))) + (set-marker end nil) + (org-table-goto-column colpos) + (org-table-align) + (when (or (not org-table-fix-formulas-confirm) + (funcall org-table-fix-formulas-confirm "Fix formulas? ")) + (org-table-fix-formulas + "$" (list (cons (number-to-string col) (number-to-string colpos)) + (cons (number-to-string colpos) (number-to-string col)))) + (org-table-fix-formulas + "$LR" (list (cons (number-to-string col) (number-to-string colpos)) + (cons (number-to-string colpos) (number-to-string col))))))) + +;;;###autoload +(defun org-table-move-row-down () + "Move table row down." + (interactive) + (org-table-move-row nil)) +;;;###autoload +(defun org-table-move-row-up () + "Move table row up." + (interactive) + (org-table-move-row 'up)) + +;;;###autoload +(defun org-table-move-row (&optional up) + "Move the current table line down. With arg UP, move it up." + (interactive "P") + (let* ((col (current-column)) + (pos (point)) + (hline1p (save-excursion (beginning-of-line 1) + (looking-at org-table-hline-regexp))) + (dline1 (org-table-current-dline)) + (dline2 (+ dline1 (if up -1 1))) + (tonew (if up 0 2)) + hline2p) + (when (and up (= (point-min) (line-beginning-position))) + (user-error "Cannot move row further")) + (beginning-of-line tonew) + (when (or (and (not up) (eobp)) (not (org-at-table-p))) + (goto-char pos) + (user-error "Cannot move row further")) + (setq hline2p (looking-at org-table-hline-regexp)) + (goto-char pos) + (let ((row (delete-and-extract-region (line-beginning-position) + (line-beginning-position 2)))) + (beginning-of-line tonew) + (unless (bolp) (insert "\n")) ;at eob without a newline + (insert row) + (unless (bolp) (insert "\n")) ;missing final newline in ROW + (beginning-of-line 0) + (org-move-to-column col) + (unless (or hline1p hline2p + (not (or (not org-table-fix-formulas-confirm) + (funcall org-table-fix-formulas-confirm + "Fix formulas? ")))) + (org-table-fix-formulas + "@" (list + (cons (number-to-string dline1) (number-to-string dline2)) + (cons (number-to-string dline2) (number-to-string dline1)))))))) + +;;;###autoload +(defun org-table-insert-row (&optional arg) + "Insert a new row above the current line into the table. +With prefix ARG, insert below the current line." + (interactive "P") + (unless (org-at-table-p) (user-error "Not at a table")) + (let* ((line (buffer-substring (line-beginning-position) (line-end-position))) + (new (org-table-clean-line line))) + ;; Fix the first field if necessary + (if (string-match "^[ \t]*| *[#$] *|" line) + (setq new (replace-match (match-string 0 line) t t new))) + (beginning-of-line (if arg 2 1)) + ;; Buffer may not end of a newline character, so ensure + ;; (beginning-of-line 2) moves point to a new line. + (unless (bolp) (insert "\n")) + (let (org-table-may-need-update) (insert-before-markers new "\n")) + (beginning-of-line 0) + (re-search-forward "| ?" (line-end-position) t) + (when (or org-table-may-need-update org-table-overlay-coordinates) + (org-table-align)) + (when (or (not org-table-fix-formulas-confirm) + (funcall org-table-fix-formulas-confirm "Fix formulas? ")) + (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))) + +;;;###autoload +(defun org-table-insert-hline (&optional above) + "Insert a horizontal-line below the current line into the table. +With prefix ABOVE, insert above the current line." + (interactive "P") + (if (not (org-at-table-p)) + (user-error "Not at a table")) + (when (eobp) (insert "\n") (backward-char 1)) + (if (not (string-match-p "|[ \t]*$" (org-current-line-string))) + (org-table-align)) + (let ((line (org-table-clean-line + (buffer-substring (point-at-bol) (point-at-eol)))) + (col (current-column))) + (while (string-match "|\\( +\\)|" line) + (setq line (replace-match + (concat "+" (make-string (- (match-end 1) (match-beginning 1)) + ?-) "|") t t line))) + (and (string-match "\\+" line) (setq line (replace-match "|" t t line))) + (beginning-of-line (if above 1 2)) + (insert line "\n") + (beginning-of-line (if above 1 -1)) + (org-move-to-column col) + (and org-table-overlay-coordinates (org-table-align)))) + +;;;###autoload +(defun org-table-hline-and-move (&optional same-column) + "Insert a hline and move to the row below that line." + (interactive "P") + (let ((col (org-table-current-column))) + (org-table-maybe-eval-formula) + (org-table-maybe-recalculate-line) + (org-table-insert-hline) + (end-of-line 2) + (if (looking-at "\n[ \t]*|-") + (progn (insert "\n|") (org-table-align)) + (org-table-next-field)) + (if same-column (org-table-goto-column col)))) + +(defun org-table-clean-line (s) + "Convert a table line S into a string with only \"|\" and space. +In particular, this does handle wide and invisible characters." + (if (string-match "^[ \t]*|-" s) + ;; It's a hline, just map the characters + (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s "")) + (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s) + (setq s (replace-match + (concat "|" (make-string (org-string-width (match-string 1 s)) + ?\ ) "|") + t t s))) + s)) + +;;;###autoload +(defun org-table-kill-row () + "Delete the current row or horizontal line from the table." + (interactive) + (if (not (org-at-table-p)) + (user-error "Not at a table")) + (let ((col (current-column)) + (dline (and (not (org-match-line org-table-hline-regexp)) + (org-table-current-dline)))) + (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max))) + (if (not (org-at-table-p)) (beginning-of-line 0)) + (org-move-to-column col) + (when (and dline + (or (not org-table-fix-formulas-confirm) + (funcall org-table-fix-formulas-confirm "Fix formulas? "))) + (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID")) + dline -1 dline)))) + +;;;###autoload +(defun org-table-sort-lines + (&optional with-case sorting-type getkey-func compare-func interactive?) + "Sort table lines according to the column at point. + +The position of point indicates the column to be used for +sorting, and the range of lines is the range between the nearest +horizontal separator lines, or the entire table of no such lines +exist. If point is before the first column, you will be prompted +for the sorting column. If there is an active region, the mark +specifies the first line and the sorting column, while point +should be in the last line to be included into the sorting. + +The command then prompts for the sorting type which can be +alphabetically, numerically, or by time (as given in a time stamp +in the field, or as a HH:MM value). Sorting in reverse order is +also possible. + +With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive. + +If SORTING-TYPE is specified when this function is called from a Lisp +program, no prompting will take place. SORTING-TYPE must be a character, +any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that +sorting should be done in reverse order. + +If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies +a function to be called to extract the key. It must return a value +that is compatible with COMPARE-FUNC, the function used to compare +entries. + +A non-nil value for INTERACTIVE? is used to signal that this +function is being called interactively." + (interactive (list current-prefix-arg nil nil nil t)) + (when (org-region-active-p) (goto-char (region-beginning))) + ;; Point must be either within a field or before a data line. + (save-excursion + (skip-chars-backward " \t") + (when (bolp) (search-forward "|" (line-end-position) t)) + (org-table-check-inside-data-field)) + ;; Set appropriate case sensitivity and column used for sorting. + (let ((column (let ((c (org-table-current-column))) + (cond ((> c 0) c) + (interactive? + (read-number "Use column N for sorting: ")) + (t 1)))) + (sorting-type + (or sorting-type + (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \ +\[t]ime, [f]unc. A/N/T/F means reversed: ")))) + (save-restriction + ;; Narrow buffer to appropriate sorting area. + (if (org-region-active-p) + (progn (goto-char (region-beginning)) + (narrow-to-region + (point) + (save-excursion (goto-char (region-end)) + (line-beginning-position 2)))) + (let ((start (org-table-begin)) + (end (org-table-end))) + (narrow-to-region + (save-excursion + (if (re-search-backward org-table-hline-regexp start t) + (line-beginning-position 2) + start)) + (if (save-excursion (re-search-forward org-table-hline-regexp end t)) + (match-beginning 0) + end)))) + ;; Determine arguments for `sort-subr'. Also record original + ;; position. `org-table-save-field' cannot help here since + ;; sorting is too much destructive. + (let* ((sort-fold-case (not with-case)) + (coordinates + (cons (count-lines (point-min) (line-beginning-position)) + (current-column))) + (extract-key-from-field + ;; Function to be called on the contents of the field + ;; used for sorting in the current row. + (cl-case sorting-type + ((?n ?N) #'string-to-number) + ((?a ?A) #'org-sort-remove-invisible) + ((?t ?T) + (lambda (f) + (cond ((string-match org-ts-regexp-both f) + (float-time + (org-time-string-to-time (match-string 0 f)))) + ((org-duration-p f) (org-duration-to-minutes f)) + ((string-match "\\<[0-9]+:[0-9]\\{2\\}\\>" f) + (org-duration-to-minutes (match-string 0 f))) + (t 0)))) + ((?f ?F) + (or getkey-func + (and interactive? + (org-read-function "Function for extracting keys: ")) + (error "Missing key extractor to sort rows"))) + (t (user-error "Invalid sorting type `%c'" sorting-type)))) + (predicate + (cl-case sorting-type + ((?n ?N ?t ?T) #'<) + ((?a ?A) #'string<) + ((?f ?F) + (or compare-func + (and interactive? + (org-read-function + (concat "Function for comparing keys " + "(empty for default `sort-subr' predicate): ") + 'allow-empty))))))) + (goto-char (point-min)) + (sort-subr (memq sorting-type '(?A ?N ?T ?F)) + (lambda () + (forward-line) + (while (and (not (eobp)) + (not (looking-at org-table-dataline-regexp))) + (forward-line))) + #'end-of-line + (lambda () + (funcall extract-key-from-field + (org-trim (org-table-get-field column)))) + nil + predicate) + ;; Move back to initial field. + (forward-line (car coordinates)) + (move-to-column (cdr coordinates)))))) + +;;;###autoload +(defun org-table-cut-region (beg end) + "Copy region in table to the clipboard and blank all relevant fields. +If there is no active region, use just the field at point." + (interactive (list + (if (org-region-active-p) (region-beginning) (point)) + (if (org-region-active-p) (region-end) (point)))) + (org-table-copy-region beg end 'cut)) + +;;;###autoload +(defun org-table-copy-region (beg end &optional cut) + "Copy rectangular region in table to clipboard. +A special clipboard is used which can only be accessed +with `org-table-paste-rectangle'." + (interactive (list + (if (org-region-active-p) (region-beginning) (point)) + (if (org-region-active-p) (region-end) (point)) + current-prefix-arg)) + (goto-char (min beg end)) + (org-table-check-inside-data-field) + (let ((beg (line-beginning-position)) + (c01 (org-table-current-column)) + region) + (goto-char (max beg end)) + (org-table-check-inside-data-field) + (let* ((end (copy-marker (line-end-position))) + (c02 (org-table-current-column)) + (column-start (min c01 c02)) + (column-end (max c01 c02)) + (column-number (1+ (- column-end column-start))) + (rpl (and cut " "))) + (goto-char beg) + (while (< (point) end) + (unless (org-at-table-hline-p) + ;; Collect every cell between COLUMN-START and COLUMN-END. + (let (cols) + (dotimes (c column-number) + (push (org-table-get-field (+ c column-start) rpl) cols)) + (push (nreverse cols) region))) + (forward-line)) + (set-marker end nil)) + (when cut (org-table-align)) + (setq org-table-clip (nreverse region)))) + +;;;###autoload +(defun org-table-paste-rectangle () + "Paste a rectangular region into a table. +The upper right corner ends up in the current field. All involved fields +will be overwritten. If the rectangle does not fit into the present table, +the table is enlarged as needed. The process ignores horizontal separator +lines." + (interactive) + (unless (consp org-table-clip) + (user-error "First cut/copy a region to paste!")) + (org-table-check-inside-data-field) + (let* ((column (org-table-current-column)) + (org-table-automatic-realign nil)) + (org-table-save-field + (dolist (row org-table-clip) + (while (org-at-table-hline-p) (forward-line)) + ;; If we left the table, create a new row. + (when (and (bolp) (not (looking-at "[ \t]*|"))) + (end-of-line 0) + (org-table-next-field)) + (let ((c column)) + (dolist (field row) + (org-table-goto-column c nil 'force) + (org-table-get-field nil field) + (cl-incf c))) + (forward-line))) + (org-table-align))) + +;;;###autoload +(defun org-table-convert () + "Convert from `org-mode' table to table.el and back. +Obviously, this only works within limits. When an Org table is converted +to table.el, all horizontal separator lines get lost, because table.el uses +these as cell boundaries and has no notion of horizontal lines. A table.el +table can be converted to an Org table only if it does not do row or column +spanning. Multiline cells will become multiple cells. Beware, Org mode +does not test if the table can be successfully converted - it blindly +applies a recipe that works for simple tables." + (interactive) + (require 'table) + (if (org-at-table.el-p) + ;; convert to Org table + (let ((beg (copy-marker (org-table-begin t))) + (end (copy-marker (org-table-end t)))) + (table-unrecognize-region beg end) + (goto-char beg) + (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t) + (replace-match "")) + (goto-char beg)) + (if (org-at-table-p) + ;; convert to table.el table + (let ((beg (copy-marker (org-table-begin))) + (end (copy-marker (org-table-end)))) + ;; first, get rid of all horizontal lines + (goto-char beg) + (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t) + (replace-match "")) + ;; insert a hline before first + (goto-char beg) + (org-table-insert-hline 'above) + (beginning-of-line -1) + ;; insert a hline after each line + (while (progn (beginning-of-line 3) (< (point) end)) + (org-table-insert-hline)) + (goto-char beg) + (setq end (move-marker end (org-table-end))) + ;; replace "+" at beginning and ending of hlines + (while (re-search-forward "^\\([ \t]*\\)|-" end t) + (replace-match "\\1+-")) + (goto-char beg) + (while (re-search-forward "-|[ \t]*$" end t) + (replace-match "-+")) + (goto-char beg))))) + +(defun org-table-transpose-table-at-point () + "Transpose Org table at point and eliminate hlines. +So a table like + +| 1 | 2 | 4 | 5 | +|---+---+---+---| +| a | b | c | d | +| e | f | g | h | + +will be transposed as + +| 1 | a | e | +| 2 | b | f | +| 4 | c | g | +| 5 | d | h | + +Note that horizontal lines disappear." + (interactive) + (let* ((table (delete 'hline (org-table-to-lisp))) + (dline_old (org-table-current-line)) + (col_old (org-table-current-column)) + (contents (mapcar (lambda (_) + (let ((tp table)) + (mapcar + (lambda (_) + (prog1 + (pop (car tp)) + (setq tp (cdr tp)))) + table))) + (car table)))) + (goto-char (org-table-begin)) + (re-search-forward "|") + (backward-char) + (delete-region (point) (org-table-end)) + (insert (mapconcat + (lambda(x) + (concat "| " (mapconcat 'identity x " | " ) " |\n" )) + contents "")) + (org-table-goto-line col_old) + (org-table-goto-column dline_old)) + (org-table-align)) + +;;;###autoload +(defun org-table-wrap-region (arg) + "Wrap several fields in a column like a paragraph. +This is useful if you'd like to spread the contents of a field over several +lines, in order to keep the table compact. + +If there is an active region, and both point and mark are in the same column, +the text in the column is wrapped to minimum width for the given number of +lines. Generally, this makes the table more compact. A prefix ARG may be +used to change the number of desired lines. For example, \ +`C-2 \\[org-table-wrap-region]' +formats the selected text to two lines. If the region was longer than two +lines, the remaining lines remain empty. A negative prefix argument reduces +the current number of lines by that amount. The wrapped text is pasted back +into the table. If you formatted it to more lines than it was before, fields +further down in the table get overwritten - so you might need to make space in +the table first. + +If there is no region, the current field is split at the cursor position and +the text fragment to the right of the cursor is prepended to the field one +line down. + +If there is no region, but you specify a prefix ARG, the current field gets +blank, and the content is appended to the field above." + (interactive "P") + (org-table-check-inside-data-field) + (if (org-region-active-p) + ;; There is a region: fill as a paragraph. + (let ((start (region-beginning))) + (org-table-cut-region (region-beginning) (region-end)) + (when (> (length (car org-table-clip)) 1) + (user-error "Region must be limited to single column")) + (let ((nlines (cond ((not arg) (length org-table-clip)) + ((< arg 1) (+ (length org-table-clip) arg)) + (t arg)))) + (setq org-table-clip + (mapcar #'list + (org-wrap (mapconcat #'car org-table-clip " ") + nil + nlines)))) + (goto-char start) + (org-table-paste-rectangle)) + ;; No region, split the current field at point. + (unless (org-get-alist-option org-M-RET-may-split-line 'table) + (skip-chars-forward "^\r\n|")) + (cond + (arg ; Combine with field above. + (let ((s (org-table-blank-field)) + (col (org-table-current-column))) + (forward-line -1) + (while (org-at-table-hline-p) (forward-line -1)) + (org-table-goto-column col) + (skip-chars-forward "^|") + (skip-chars-backward " ") + (insert " " (org-trim s)) + (org-table-align))) + ((looking-at "\\([^|]+\\)+|") ; Split field. + (let ((s (match-string 1))) + (replace-match " |") + (goto-char (match-beginning 0)) + (org-table-next-row) + (insert (org-trim s) " ") + (org-table-align))) + (t (org-table-next-row))))) + +(defvar org-field-marker nil) + +;;;###autoload +(defun org-table-edit-field (arg) + "Edit table field in a different window. +This is mainly useful for fields that contain hidden parts. + +When called with a `\\[universal-argument]' prefix, just make the full field +visible so that it can be edited in place. + +When called with a `\\[universal-argument] \\[universal-argument]' prefix, \ +toggle `org-table-follow-field-mode'." + (interactive "P") + (unless (org-at-table-p) (user-error "Not at a table")) + (cond + ((equal arg '(16)) + (org-table-follow-field-mode (if org-table-follow-field-mode -1 1))) + (arg + (let ((b (save-excursion (skip-chars-backward "^|") (point))) + (e (save-excursion (skip-chars-forward "^|\r\n") (point)))) + (remove-text-properties b e '(org-cwidth t invisible t + display t intangible t)) + (if (and (boundp 'font-lock-mode) font-lock-mode) + (font-lock-fontify-block)))) + (t + (let ((pos (point-marker)) + (coord + (if (eq org-table-use-standard-references t) + (concat (org-number-to-letters (org-table-current-column)) + (int-to-string (org-table-current-dline))) + (concat "@" (int-to-string (org-table-current-dline)) + "$" (int-to-string (org-table-current-column))))) + (field (org-table-get-field)) + (cw (current-window-configuration)) + p) + (goto-char pos) + (org-switch-to-buffer-other-window "*Org Table Edit Field*") + (when (and (local-variable-p 'org-field-marker) + (markerp org-field-marker)) + (move-marker org-field-marker nil)) + (erase-buffer) + (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n") + (let ((org-inhibit-startup t)) (org-mode)) + (auto-fill-mode -1) + (setq truncate-lines nil) + (setq word-wrap t) + (goto-char (setq p (point-max))) + (insert (org-trim field)) + (remove-text-properties p (point-max) + '(invisible t org-cwidth t display t + intangible t)) + (goto-char p) + (setq-local org-finish-function 'org-table-finish-edit-field) + (setq-local org-window-configuration cw) + (setq-local org-field-marker pos) + (message "Edit and finish with C-c C-c"))))) + +(defun org-table-finish-edit-field () + "Finish editing a table data field. +Remove all newline characters, insert the result into the table, realign +the table and kill the editing buffer." + (let ((pos org-field-marker) + (cw org-window-configuration) + (cb (current-buffer)) + text) + (goto-char (point-min)) + (while (re-search-forward "^#.*\n?" nil t) (replace-match "")) + (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t) + (replace-match " ")) + (setq text (org-trim (buffer-string))) + (set-window-configuration cw) + (kill-buffer cb) + (select-window (get-buffer-window (marker-buffer pos))) + (goto-char pos) + (move-marker pos nil) + (org-table-check-inside-data-field) + (org-table-get-field nil text) + (org-table-align) + (message "New field value inserted"))) + +(define-minor-mode org-table-follow-field-mode + "Minor mode to make the table field editor window follow the cursor. +When this mode is active, the field editor window will always show the +current field. The mode exits automatically when the cursor leaves the +table (but see `org-table-exit-follow-field-mode-when-leaving-table')." + nil " TblFollow" nil + (if org-table-follow-field-mode + (add-hook 'post-command-hook 'org-table-follow-fields-with-editor + 'append 'local) + (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local) + (let* ((buf (get-buffer "*Org Table Edit Field*")) + (win (and buf (get-buffer-window buf)))) + (when win (delete-window win)) + (when buf + (with-current-buffer buf + (move-marker org-field-marker nil)) + (kill-buffer buf))))) + +(defun org-table-follow-fields-with-editor () + (if (and org-table-exit-follow-field-mode-when-leaving-table + (not (org-at-table-p))) + ;; We have left the table, exit the follow mode + (org-table-follow-field-mode -1) + (when (org-table-check-inside-data-field 'noerror) + (let ((win (selected-window))) + (org-table-edit-field nil) + (org-fit-window-to-buffer) + (select-window win))))) + +(defvar org-timecnt) ; dynamically scoped parameter + +;;;###autoload +(defun org-table-sum (&optional beg end nlast) + "Sum numbers in region of current table column. +The result will be displayed in the echo area, and will be available +as kill to be inserted with \\[yank]. + +If there is an active region, it is interpreted as a rectangle and all +numbers in that rectangle will be summed. If there is no active +region and point is located in a table column, sum all numbers in that +column. + +If at least one number looks like a time HH:MM or HH:MM:SS, all other +numbers are assumed to be times as well (in decimal hours) and the +numbers are added as such. + +If NLAST is a number, only the NLAST fields will actually be summed." + (interactive) + (save-excursion + (let (col (org-timecnt 0) diff h m s org-table-clip) + (cond + ((and beg end)) ; beg and end given explicitly + ((org-region-active-p) + (setq beg (region-beginning) end (region-end))) + (t + (setq col (org-table-current-column)) + (goto-char (org-table-begin)) + (unless (re-search-forward "^[ \t]*|[^-]" nil t) + (user-error "No table data")) + (org-table-goto-column col) + (setq beg (point)) + (goto-char (org-table-end)) + (unless (re-search-backward "^[ \t]*|[^-]" nil t) + (user-error "No table data")) + (org-table-goto-column col) + (setq end (point)))) + (let* ((items (apply 'append (org-table-copy-region beg end))) + (items1 (cond ((not nlast) items) + ((>= nlast (length items)) items) + (t (setq items (reverse items)) + (setcdr (nthcdr (1- nlast) items) nil) + (nreverse items)))) + (numbers (delq nil (mapcar 'org-table-get-number-for-summing + items1))) + (res (apply '+ numbers)) + (sres (if (= org-timecnt 0) + (number-to-string res) + (setq diff (* 3600 res) + h (floor (/ diff 3600)) diff (mod diff 3600) + m (floor (/ diff 60)) diff (mod diff 60) + s diff) + (format "%.0f:%02.0f:%02.0f" h m s)))) + (kill-new sres) + (when (called-interactively-p 'interactive) + (message "%s" (substitute-command-keys + (format "Sum of %d items: %-20s \ +\(\\[yank] will insert result into buffer)" (length numbers) sres)))) + sres)))) + +(defun org-table-get-number-for-summing (s) + (let (n) + (if (string-match "^ *|? *" s) + (setq s (replace-match "" nil nil s))) + (if (string-match " *|? *$" s) + (setq s (replace-match "" nil nil s))) + (setq n (string-to-number s)) + (cond + ((and (string-match "0" s) + (string-match "\\`[-+ \t0.edED]+\\'" s)) 0) + ((string-match "\\`[ \t]+\\'" s) nil) + ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s) + (let ((h (string-to-number (or (match-string 1 s) "0"))) + (m (string-to-number (or (match-string 2 s) "0"))) + (s (string-to-number (or (match-string 4 s) "0")))) + (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt))) + (* 1.0 (+ h (/ m 60.0) (/ s 3600.0))))) + ((equal n 0) nil) + (t n)))) + +(defun org-table-current-field-formula (&optional key noerror) + "Return the formula active for the current field. + +Assumes that table is already analyzed. If KEY is given, return +the key to this formula. Otherwise return the formula preceded +with \"=\" or \":=\"." + (let* ((line (count-lines org-table-current-begin-pos + (line-beginning-position))) + (row (org-table-line-to-dline line))) + (cond + (row + (let* ((col (org-table-current-column)) + (name (car (rassoc (list line col) + org-table-named-field-locations))) + (scol (format "$%d" col)) + (ref (format "@%d$%d" (org-table-current-dline) col)) + (stored-list (org-table-get-stored-formulas noerror)) + (ass (or (assoc name stored-list) + (assoc ref stored-list) + (assoc scol stored-list)))) + (cond (key (car ass)) + (ass (concat (if (string-match-p "^[0-9]+$" (car ass)) "=" ":=") + (cdr ass)))))) + (noerror nil) + (t (error "No formula active for the current field"))))) + +(defun org-table-get-formula (&optional equation named) + "Read a formula from the minibuffer, offer stored formula as default. +When NAMED is non-nil, look for a named equation." + (let* ((stored-list (org-table-get-stored-formulas)) + (name (car (rassoc (list (count-lines org-table-current-begin-pos + (line-beginning-position)) + (org-table-current-column)) + org-table-named-field-locations))) + (ref (format "@%d$%d" + (org-table-current-dline) + (org-table-current-column))) + (scol (cond + ((not named) (format "$%d" (org-table-current-column))) + ((and name (not (string-match "\\`LR[0-9]+\\'" name))) name) + (t ref))) + (name (or name ref)) + (org-table-may-need-update nil) + (stored (cdr (assoc scol stored-list))) + (eq (cond + ((and stored equation (string-match-p "^ *=? *$" equation)) + stored) + ((stringp equation) + equation) + (t (org-table-formula-from-user + (read-string + (org-table-formula-to-user + (format "%s formula %s=" + (if named "Field" "Column") + scol)) + (if stored (org-table-formula-to-user stored) "") + 'org-table-formula-history + ))))) + mustsave) + (when (not (string-match "\\S-" eq)) + ;; remove formula + (setq stored-list (delq (assoc scol stored-list) stored-list)) + (org-table-store-formulas stored-list) + (user-error "Formula removed")) + (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq))) + (if (string-match " *$" eq) (setq eq (replace-match "" t t eq))) + (if (and name (not named)) + ;; We set the column equation, delete the named one. + (setq stored-list (delq (assoc name stored-list) stored-list) + mustsave t)) + (if stored + (setcdr (assoc scol stored-list) eq) + (setq stored-list (cons (cons scol eq) stored-list))) + (if (or mustsave (not (equal stored eq))) + (org-table-store-formulas stored-list)) + eq)) + +(defun org-table-store-formulas (alist &optional location) + "Store the list of formulas below the current table. +If optional argument LOCATION is a buffer position, insert it at +LOCATION instead." + (save-excursion + (if location + (progn (goto-char location) (beginning-of-line)) + (goto-char (org-table-end))) + (let ((case-fold-search t)) + (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)") + (progn + ;; Don't overwrite TBLFM, we might use text properties to + ;; store stuff. + (goto-char (match-beginning 3)) + (delete-region (match-beginning 3) (match-end 0))) + (org-indent-line) + (insert (or (match-string 2) "#+TBLFM:"))) + (insert " " + (mapconcat (lambda (x) (concat (car x) "=" (cdr x))) + (sort alist #'org-table-formula-less-p) + "::") + "\n")))) + +(defsubst org-table-formula-make-cmp-string (a) + (when (string-match "\\`$[<>]" a) + (let ((arrow (string-to-char (substring a 1)))) + ;; Fake a high number to make sure this is sorted at the end. + (setq a (org-table-formula-handle-first/last-rc a)) + (setq a (format "$%d" (+ 10000 + (if (= arrow ?<) -1000 0) + (string-to-number (substring a 1))))))) + (when (string-match + "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" + a) + (concat + (if (match-end 2) + (format "@%05d" (string-to-number (match-string 2 a))) "") + (if (match-end 4) + (format "$%05d" (string-to-number (match-string 4 a))) "") + (if (match-end 5) + (concat "@@" (match-string 5 a)))))) + +(defun org-table-formula-less-p (a b) + "Compare two formulas for sorting." + (let ((as (org-table-formula-make-cmp-string (car a))) + (bs (org-table-formula-make-cmp-string (car b)))) + (and as bs (string< as bs)))) + +;;;###autoload +(defun org-table-get-stored-formulas (&optional noerror location) + "Return an alist with the stored formulas directly after current table. +By default, only return active formulas, i.e., formulas located +on the first line after the table. However, if optional argument +LOCATION is a buffer position, consider the formulas there." + (save-excursion + (if location + (progn (goto-char location) (beginning-of-line)) + (goto-char (org-table-end))) + (let ((case-fold-search t)) + (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)") + (let ((strings (org-split-string (match-string-no-properties 2) + " *:: *")) + eq-alist seen) + (dolist (string strings (nreverse eq-alist)) + (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\ +[<>]+\\)\\) *= *\\(.*[^ \t]\\)" + string) + (let ((lhs + (let ((m (match-string 1 string))) + (cond + ((not (match-end 2)) m) + ;; Is it a column reference? + ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m) m) + ;; Since named columns are not possible in + ;; LHS, assume this is a named field. + (t (match-string 2 string))))) + (rhs (match-string 3 string))) + (push (cons lhs rhs) eq-alist) + (cond + ((not (member lhs seen)) (push lhs seen)) + (noerror + (message + "Double definition `%s=' in TBLFM line, please fix by hand" + lhs) + (ding) + (sit-for 2)) + (t + (user-error + "Double definition `%s=' in TBLFM line, please fix by hand" + lhs))))))))))) + +(defun org-table-fix-formulas (key replace &optional limit delta remove) + "Modify the equations after the table structure has been edited. +KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace. +For all numbers larger than LIMIT, shift them by DELTA." + (save-excursion + (goto-char (org-table-end)) + (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:")) + (let ((msg "The formulas in #+TBLFM have been updated") + (re (concat key "\\([0-9]+\\)")) + (re2 + (when remove + (if (or (equal key "$") (equal key "$LR")) + (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)" + (regexp-quote key) remove) + (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove)))) + s n a) + (when remove + (while (re-search-forward re2 (point-at-eol) t) + (unless (save-match-data (org-in-regexp "remote([^)]+?)")) + (if (equal (char-before (match-beginning 0)) ?.) + (user-error + "Change makes TBLFM term %s invalid, use undo to recover" + (match-string 0)) + (replace-match ""))))) + (while (re-search-forward re (point-at-eol) t) + (unless (save-match-data (org-in-regexp "remote([^)]+?)")) + (setq s (match-string 1) n (string-to-number s)) + (cond + ((setq a (assoc s replace)) + (replace-match (concat key (cdr a)) t t) + (message msg)) + ((and limit (> n limit)) + (replace-match (concat key (int-to-string (+ n delta))) t t) + (message msg)))))) + (forward-line)))) + +;;;###autoload +(defun org-table-maybe-eval-formula () + "Check if the current field starts with \"=\" or \":=\". +If yes, store the formula and apply it." + ;; We already know we are in a table. Get field will only return a formula + ;; when appropriate. It might return a separator line, but no problem. + (when org-table-formula-evaluate-inline + (let* ((field (org-trim (or (org-table-get-field) ""))) + named eq) + (when (string-match "^:?=\\(.*[^=]\\)$" field) + (setq named (equal (string-to-char field) ?:) + eq (match-string 1 field)) + (org-table-eval-formula (and named '(4)) + (org-table-formula-from-user eq)))))) + +(defvar org-recalc-commands nil + "List of commands triggering the recalculation of a line. +Will be filled automatically during use.") + +(defvar org-recalc-marks + '((" " . "Unmarked: no special line, no automatic recalculation") + ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line") + ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'") + ("!" . "Column name definition line. Reference in formula as $name.") + ("$" . "Parameter definition line name=value. Reference in formula as $name.") + ("_" . "Names for values in row below this one.") + ("^" . "Names for values in row above this one."))) + +;;;###autoload +(defun org-table-rotate-recalc-marks (&optional newchar) + "Rotate the recalculation mark in the first column. +If in any row, the first field is not consistent with a mark, +insert a new column for the markers. +When there is an active region, change all the lines in the region, +after prompting for the marking character. +After each change, a message will be displayed indicating the meaning +of the new mark." + (interactive) + (unless (org-at-table-p) (user-error "Not at a table")) + (let* ((region (org-region-active-p)) + (l1 (and region + (save-excursion (goto-char (region-beginning)) + (copy-marker (line-beginning-position))))) + (l2 (and region + (save-excursion (goto-char (region-end)) + (copy-marker (line-beginning-position))))) + (l (copy-marker (line-beginning-position))) + (col (org-table-current-column)) + (newchar (if region + (char-to-string + (read-char-exclusive + "Change region to what mark? Type # * ! $ or SPC: ")) + newchar)) + (no-special-column + (save-excursion + (goto-char (org-table-begin)) + (re-search-forward + "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t)))) + (when (and newchar (not (assoc newchar org-recalc-marks))) + (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'" + newchar)) + (when l1 (goto-char l1)) + (save-excursion + (beginning-of-line) + (unless (looking-at org-table-dataline-regexp) + (user-error "Not at a table data line"))) + (when no-special-column + (org-table-goto-column 1) + (org-table-insert-column)) + (let ((previous-line-end (line-end-position)) + (newchar + (save-excursion + (beginning-of-line) + (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#") + (newchar) + (t (cadr (member (match-string 1) + (append (mapcar #'car org-recalc-marks) + '(" "))))))))) + ;; Rotate mark in first row. + (org-table-get-field 1 (format " %s " newchar)) + ;; Rotate marks in additional rows if a region is active. + (when region + (save-excursion + (forward-line) + (while (<= (point) l2) + (when (looking-at org-table-dataline-regexp) + (org-table-get-field 1 (format " %s " newchar))) + (forward-line)))) + ;; Only align if rotation actually changed lines' length. + (when (/= previous-line-end (line-end-position)) (org-table-align))) + (goto-char l) + (org-table-goto-column (if no-special-column (1+ col) col)) + (when l1 (set-marker l1 nil)) + (when l2 (set-marker l2 nil)) + (set-marker l nil) + (when (called-interactively-p 'interactive) + (message "%s" (cdr (assoc newchar org-recalc-marks)))))) + +;;;###autoload +(defun org-table-analyze () + "Analyze table at point and store results. + +This function sets up the following dynamically scoped variables: + + `org-table-column-name-regexp', + `org-table-column-names', + `org-table-current-begin-pos', + `org-table-current-line-types', + `org-table-current-ncol', + `org-table-dlines', + `org-table-hlines', + `org-table-local-parameters', + `org-table-named-field-locations'." + (let ((beg (org-table-begin)) + (end (org-table-end))) + (save-excursion + (goto-char beg) + ;; Extract column names. + (setq org-table-column-names nil) + (when (save-excursion + (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)) + (let ((c 1)) + (dolist (name (org-split-string (match-string 1) " *| *")) + (cl-incf c) + (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name) + (push (cons name (int-to-string c)) org-table-column-names))))) + (setq org-table-column-names (nreverse org-table-column-names)) + (setq org-table-column-name-regexp + (format "\\$\\(%s\\)\\>" + (regexp-opt (mapcar #'car org-table-column-names) t))) + ;; Extract local parameters. + (setq org-table-local-parameters nil) + (save-excursion + (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t) + (dolist (field (org-split-string (match-string 1) " *| *")) + (when (string-match + "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field) + (push (cons (match-string 1 field) (match-string 2 field)) + org-table-local-parameters))))) + ;; Update named fields locations. We minimize `count-lines' + ;; processing by storing last known number of lines in LAST. + (setq org-table-named-field-locations nil) + (save-excursion + (let ((last (cons (point) 0))) + (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t) + (let ((c (match-string 1)) + (fields (org-split-string (match-string 2) " *| *"))) + (save-excursion + (forward-line (if (equal c "_") 1 -1)) + (let ((fields1 + (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)") + (org-split-string (match-string 1) " *| *"))) + (line (cl-incf (cdr last) (count-lines (car last) (point)))) + (col 1)) + (setcar last (point)) ; Update last known position. + (while (and fields fields1) + (let ((field (pop fields)) + (v (pop fields1))) + (cl-incf col) + (when (and (stringp field) + (stringp v) + (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" + field)) + (push (cons field v) org-table-local-parameters) + (push (list field line col) + org-table-named-field-locations)))))))))) + ;; Re-use existing markers when possible. + (if (markerp org-table-current-begin-pos) + (move-marker org-table-current-begin-pos (point)) + (setq org-table-current-begin-pos (point-marker))) + ;; Analyze the line types. + (let ((l 0) hlines dlines types) + (while (looking-at "[ \t]*|\\(-\\)?") + (push (if (match-end 1) 'hline 'dline) types) + (if (match-end 1) (push l hlines) (push l dlines)) + (forward-line) + (cl-incf l)) + (push 'hline types) ; Add an imaginary extra hline to the end. + (setq org-table-current-line-types (apply #'vector (nreverse types))) + (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines)))) + (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines))))) + ;; Get the number of columns from the first data line in table. + (goto-char beg) + (forward-line (aref org-table-dlines 1)) + (let* ((fields + (org-split-string + (buffer-substring (line-beginning-position) (line-end-position)) + "[ \t]*|[ \t]*")) + (nfields (length fields)) + al al2) + (setq org-table-current-ncol nfields) + (let ((last-dline + (aref org-table-dlines (1- (length org-table-dlines))))) + (dotimes (i nfields) + (let ((column (1+ i))) + (push (list (format "LR%d" column) last-dline column) al) + (push (cons (format "LR%d" column) (nth i fields)) al2)))) + (setq org-table-named-field-locations + (append org-table-named-field-locations al)) + (setq org-table-local-parameters + (append org-table-local-parameters al2)))))) + +(defun org-table-goto-field (ref &optional create-column-p) + "Move point to a specific field in the current table. + +REF is either the name of a field its absolute reference, as +a string. No column is created unless CREATE-COLUMN-P is +non-nil. If it is a function, it is called with the column +number as its argument as is used as a predicate to know if the +column can be created. + +This function assumes the table is already analyzed (i.e., using +`org-table-analyze')." + (let* ((coordinates + (cond + ((cdr (assoc ref org-table-named-field-locations))) + ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref) + (list (condition-case nil + (aref org-table-dlines + (string-to-number (match-string 1 ref))) + (error (user-error "Invalid row number in %s" ref))) + (string-to-number (match-string 2 ref)))) + (t (user-error "Unknown field: %s" ref)))) + (line (car coordinates)) + (column (nth 1 coordinates)) + (create-new-column (if (functionp create-column-p) + (funcall create-column-p column) + create-column-p))) + (when coordinates + (goto-char org-table-current-begin-pos) + (forward-line line) + (org-table-goto-column column nil create-new-column)))) + +;;;###autoload +(defun org-table-maybe-recalculate-line () + "Recompute the current line if marked for it, and if we haven't just done it." + (interactive) + (and org-table-allow-automatic-line-recalculation + (not (and (memq last-command org-recalc-commands) + (eq org-last-recalc-line (line-beginning-position)))) + (save-excursion (beginning-of-line 1) + (looking-at org-table-auto-recalculate-regexp)) + (org-table-recalculate) t)) + +(defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula' +(defsubst org-set-calc-mode (var &optional value) + (if (stringp var) + (setq var (assoc var '(("D" calc-angle-mode deg) + ("R" calc-angle-mode rad) + ("F" calc-prefer-frac t) + ("S" calc-symbolic-mode t))) + value (nth 2 var) var (nth 1 var))) + (if (memq var org-tbl-calc-modes) + (setcar (cdr (memq var org-tbl-calc-modes)) value) + (cons var (cons value org-tbl-calc-modes))) + org-tbl-calc-modes) + +;;;###autoload +(defun org-table-eval-formula (&optional arg equation + suppress-align suppress-const + suppress-store suppress-analysis) + "Replace the table field value at the cursor by the result of a calculation. + +In a table, this command replaces the value in the current field with the +result of a formula. It also installs the formula as the \"current\" column +formula, by storing it in a special line below the table. When called +with a `\\[universal-argument]' prefix the formula is installed as a \ +field formula. + +When called with a `\\[universal-argument] \\[universal-argument]' prefix, \ +insert the active equation for the field +back into the current field, so that it can be edited there. This is \ +useful +in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \ +check the referenced fields. + +When called, the command first prompts for a formula, which is read in +the minibuffer. Previously entered formulas are available through the +history list, and the last used formula is offered as a default. +These stored formulas are adapted correctly when moving, inserting, or +deleting columns with the corresponding commands. + +The formula can be any algebraic expression understood by the Calc package. +For details, see the Org mode manual. + +This function can also be called from Lisp programs and offers +additional arguments: EQUATION can be the formula to apply. If this +argument is given, the user will not be prompted. + +SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing +unnecessary aligns. + +SUPPRESS-CONST suppresses the interpretation of constants in the +formula, assuming that this has been done already outside the +function. + +SUPPRESS-STORE means the formula should not be stored, either +because it is already stored, or because it is a modified +equation that should not overwrite the stored one. + +SUPPRESS-ANALYSIS prevents analyzing the table and checking +location of point." + (interactive "P") + (unless suppress-analysis + (org-table-check-inside-data-field) + (org-table-analyze)) + (if (equal arg '(16)) + (let ((eq (org-table-current-field-formula))) + (org-table-get-field nil eq) + (org-table-align) + (setq org-table-may-need-update t)) + (let* (fields + (ndown (if (integerp arg) arg 1)) + (org-table-automatic-realign nil) + (case-fold-search nil) + (down (> ndown 1)) + (formula (if (and equation suppress-store) + equation + (org-table-get-formula equation (equal arg '(4))))) + (n0 (org-table-current-column)) + (org-tbl-calc-modes (copy-sequence org-calc-default-modes)) + (numbers nil) ; was a variable, now fixed default + (keep-empty nil) + n form form0 formrpl formrg bw fmt x ev orig c lispp literal + duration duration-output-format) + ;; Parse the format string. Since we have a lot of modes, this is + ;; a lot of work. However, I think calc still uses most of the time. + (if (string-match ";" formula) + (let ((tmp (org-split-string formula ";"))) + (setq formula (car tmp) + fmt (concat (cdr (assoc "%" org-table-local-parameters)) + (nth 1 tmp))) + (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt) + (setq c (string-to-char (match-string 1 fmt)) + n (string-to-number (match-string 2 fmt))) + (if (= c ?p) + (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n)) + (setq org-tbl-calc-modes + (org-set-calc-mode + 'calc-float-format + (list (cdr (assoc c '((?n . float) (?f . fix) + (?s . sci) (?e . eng)))) + n)))) + (setq fmt (replace-match "" t t fmt))) + (if (string-match "[tTU]" fmt) + (let ((ff (match-string 0 fmt))) + (setq duration t numbers t + duration-output-format + (cond ((equal ff "T") nil) + ((equal ff "t") org-table-duration-custom-format) + ((equal ff "U") 'hh:mm)) + fmt (replace-match "" t t fmt)))) + (if (string-match "N" fmt) + (setq numbers t + fmt (replace-match "" t t fmt))) + (if (string-match "L" fmt) + (setq literal t + fmt (replace-match "" t t fmt))) + (if (string-match "E" fmt) + (setq keep-empty t + fmt (replace-match "" t t fmt))) + (while (string-match "[DRFS]" fmt) + (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt))) + (setq fmt (replace-match "" t t fmt))) + (unless (string-match "\\S-" fmt) + (setq fmt nil)))) + (when (and (not suppress-const) org-table-formula-use-constants) + (setq formula (org-table-formula-substitute-names formula))) + (setq orig (or (get-text-property 1 :orig-formula formula) "?")) + (setq formula (org-table-formula-handle-first/last-rc formula)) + (while (> ndown 0) + (setq fields (org-split-string + (org-trim + (buffer-substring-no-properties + (line-beginning-position) (line-end-position))) + " *| *")) + ;; replace fields with duration values if relevant + (if duration + (setq fields + (mapcar (lambda (x) (org-table-time-string-to-seconds x)) + fields))) + (if (eq numbers t) + (setq fields (mapcar + (lambda (x) + (if (string-match "\\S-" x) + (number-to-string (string-to-number x)) + x)) + fields))) + (setq ndown (1- ndown)) + (setq form (copy-sequence formula) + lispp (and (> (length form) 2) (equal (substring form 0 2) "'("))) + (if (and lispp literal) (setq lispp 'literal)) + + ;; Insert row and column number of formula result field + (while (string-match "[@$]#" form) + (setq form + (replace-match + (format "%d" + (save-match-data + (if (equal (substring form (match-beginning 0) + (1+ (match-beginning 0))) + "@") + (org-table-current-dline) + (org-table-current-column)))) + t t form))) + + ;; Check for old vertical references + (org-table--error-on-old-row-references form) + ;; Insert remote references + (setq form (org-table-remote-reference-indirection form)) + (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form) + (setq form + (replace-match + (save-match-data + (org-table-make-reference + (let ((rmtrng (org-table-get-remote-range + (match-string 1 form) (match-string 2 form)))) + (if duration + (if (listp rmtrng) + (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng) + (org-table-time-string-to-seconds rmtrng)) + rmtrng)) + keep-empty numbers lispp)) + t t form))) + ;; Insert complex ranges + (while (and (string-match org-table-range-regexp form) + (> (length (match-string 0 form)) 1)) + (setq formrg + (save-match-data + (org-table-get-range + (match-string 0 form) org-table-current-begin-pos n0))) + (setq formrpl + (save-match-data + (org-table-make-reference + ;; possibly handle durations + (if duration + (if (listp formrg) + (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg) + (org-table-time-string-to-seconds formrg)) + formrg) + keep-empty numbers lispp))) + (if (not (save-match-data + (string-match (regexp-quote form) formrpl))) + (setq form (replace-match formrpl t t form)) + (user-error "Spreadsheet error: invalid reference \"%s\"" form))) + ;; Insert simple ranges, i.e. included in the current row. + (while (string-match + "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)" + form) + (setq form + (replace-match + (save-match-data + (org-table-make-reference + (cl-subseq fields + (+ (if (match-end 2) n0 0) + (string-to-number (match-string 1 form)) + -1) + (+ (if (match-end 4) n0 0) + (string-to-number (match-string 3 form)))) + keep-empty numbers lispp)) + t t form))) + (setq form0 form) + ;; Insert the references to fields in same row + (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form) + (setq n (+ (string-to-number (match-string 1 form)) + (if (match-end 2) n0 0)) + x (nth (1- (if (= n 0) n0 (max n 1))) fields) + formrpl (save-match-data + (org-table-make-reference + x keep-empty numbers lispp))) + (when (or (not x) + (save-match-data + (string-match (regexp-quote formula) formrpl))) + (user-error "Invalid field specifier \"%s\"" + (match-string 0 form))) + (setq form (replace-match formrpl t t form))) + + (if lispp + (setq ev (condition-case nil + (eval (eval (read form))) + (error "#ERROR")) + ev (if (numberp ev) (number-to-string ev) ev) + ev (if duration (org-table-time-seconds-to-string + (string-to-number ev) + duration-output-format) ev)) + + ;; Use <...> time-stamps so that Calc can handle them. + (setq form + (replace-regexp-in-string org-ts-regexp-inactive "<\\1>" form)) + ;; Internationalize local time-stamps by setting locale to + ;; "C". + (setq form + (replace-regexp-in-string + org-ts-regexp + (lambda (ts) + (let ((system-time-locale "C")) + (format-time-string + (org-time-stamp-format + (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)) + (apply #'encode-time + (save-match-data (org-parse-time-string ts)))))) + form t t)) + + (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form)) + form + (calc-eval (cons form org-tbl-calc-modes) + (when (and (not keep-empty) numbers) 'num))) + ev (if duration (org-table-time-seconds-to-string + (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev) + (string-to-number (org-table-time-string-to-seconds ev)) + (string-to-number ev)) + duration-output-format) + ev))) + + (when org-table-formula-debug + (with-output-to-temp-buffer "*Substitution History*" + (princ (format "Substitution history of formula +Orig: %s +$xyz-> %s +@r$c-> %s +$1-> %s\n" orig formula form0 form)) + (if (consp ev) + (princ (format " %s^\nError: %s" + (make-string (car ev) ?\-) (nth 1 ev))) + (princ (format "Result: %s\nFormat: %s\nFinal: %s" + ev (or fmt "NONE") + (if fmt (format fmt (string-to-number ev)) ev))))) + (setq bw (get-buffer-window "*Substitution History*")) + (org-fit-window-to-buffer bw) + (unless (and (called-interactively-p 'any) (not ndown)) + (unless (let (inhibit-redisplay) + (y-or-n-p "Debugging Formula. Continue to next? ")) + (org-table-align) + (user-error "Abort")) + (delete-window bw) + (message ""))) + (when (consp ev) (setq fmt nil ev "#ERROR")) + (org-table-justify-field-maybe + (format org-table-formula-field-format + (cond + ((not (stringp ev)) ev) + (fmt (format fmt (string-to-number ev))) + ;; Replace any active time stamp in the result with + ;; an inactive one. Dates in tables are likely + ;; piece of regular data, not meant to appear in the + ;; agenda. + (t (replace-regexp-in-string org-ts-regexp "[\\1]" ev))))) + (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]")) + (call-interactively 'org-return) + (setq ndown 0))) + (and down (org-table-maybe-recalculate-line)) + (or suppress-align (and org-table-may-need-update + (org-table-align)))))) + +(defun org-table-put-field-property (prop value) + (save-excursion + (put-text-property (progn (skip-chars-backward "^|") (point)) + (progn (skip-chars-forward "^|") (point)) + prop value))) + +(defun org-table-get-range (desc &optional tbeg col highlight corners-only) + "Get a calc vector from a column, according to descriptor DESC. + +Optional arguments TBEG and COL can give the beginning of the table and +the current column, to avoid unnecessary parsing. + +HIGHLIGHT means just highlight the range. + +When CORNERS-ONLY is set, only return the corners of the range as +a list (line1 column1 line2 column2) where line1 and line2 are +line numbers relative to beginning of table, or TBEG, and column1 +and column2 are table column numbers." + (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc) + (replace-regexp-in-string "\\$" "@0$" desc) + desc)) + (col (or col (org-table-current-column))) + (tbeg (or tbeg (org-table-begin))) + (thisline (count-lines tbeg (line-beginning-position)))) + (unless (string-match org-table-range-regexp desc) + (user-error "Invalid table range specifier `%s'" desc)) + (let ((rangep (match-end 3)) + (r1 (let ((r (and (match-end 1) (match-string 1 desc)))) + (or (save-match-data + (and (org-string-nw-p r) + (org-table--descriptor-line r thisline))) + thisline))) + (r2 (let ((r (and (match-end 4) (match-string 4 desc)))) + (or (save-match-data + (and (org-string-nw-p r) + (org-table--descriptor-line r thisline))) + thisline))) + (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1)))) + (if (or (not c) (= (string-to-number c) 0)) col + (+ (string-to-number c) + (if (memq (string-to-char c) '(?- ?+)) col 0))))) + (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1)))) + (if (or (not c) (= (string-to-number c) 0)) col + (+ (string-to-number c) + (if (memq (string-to-char c) '(?- ?+)) col 0)))))) + (save-excursion + (if (and (not corners-only) + (or (not rangep) (and (= r1 r2) (= c1 c2)))) + ;; Just one field. + (progn + (forward-line (- r1 thisline)) + (while (not (looking-at org-table-dataline-regexp)) + (forward-line)) + (prog1 (org-trim (org-table-get-field c1)) + (when highlight (org-table-highlight-rectangle)))) + ;; A range, return a vector. First sort the numbers to get + ;; a regular rectangle. + (let ((first-row (min r1 r2)) + (last-row (max r1 r2)) + (first-column (min c1 c2)) + (last-column (max c1 c2))) + (if corners-only (list first-row first-column last-row last-column) + ;; Copy the range values into a list. + (forward-line (- first-row thisline)) + (while (not (looking-at org-table-dataline-regexp)) + (forward-line) + (cl-incf first-row)) + (org-table-goto-column first-column) + (let ((beg (point))) + (forward-line (- last-row first-row)) + (while (not (looking-at org-table-dataline-regexp)) + (forward-line -1)) + (org-table-goto-column last-column) + (let ((end (point))) + (when highlight + (org-table-highlight-rectangle + beg (progn (skip-chars-forward "^|\n") (point)))) + ;; Return string representation of calc vector. + (mapcar #'org-trim + (apply #'append + (org-table-copy-region beg end)))))))))))) + +(defun org-table--descriptor-line (desc cline) + "Return relative line number corresponding to descriptor DESC. +The cursor is currently in relative line number CLINE." + (if (string-match "\\`[0-9]+\\'" desc) + (aref org-table-dlines (string-to-number desc)) + (when (or (not (string-match + "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" + ;; 1 2 3 4 5 6 + desc)) + (and (not (match-end 3)) (not (match-end 6))) + (and (match-end 3) (match-end 6) (not (match-end 5)))) + (user-error "Invalid row descriptor `%s'" desc)) + (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3)))) + (hdir (match-string 2 desc)) + (odir (match-string 5 desc)) + (on (and (match-end 6) (string-to-number (match-string 6 desc)))) + (rel (and (match-end 6) + (or (and (match-end 1) (not (match-end 3))) + (match-end 5))))) + (when (and hn (not hdir)) + (setq cline 0) + (setq hdir "+") + (when (eq (aref org-table-current-line-types 0) 'hline) (cl-decf hn))) + (when (and (not hn) on (not odir)) (user-error "Should never happen")) + (when hn + (setq cline + (org-table--row-type 'hline hn cline (equal hdir "-") nil desc))) + (when on + (setq cline + (org-table--row-type 'dline on cline (equal odir "-") rel desc))) + cline))) + +(defun org-table--row-type (type n i backwards relative desc) + "Return relative line of Nth row with type TYPE. +Search starts from relative line I. When BACKWARDS in non-nil, +look before I. When RELATIVE is non-nil, the reference is +relative. DESC is the original descriptor that started the +search, as a string." + (let ((l (length org-table-current-line-types))) + (catch :exit + (dotimes (_ n) + (while (and (cl-incf i (if backwards -1 1)) + (>= i 0) + (< i l) + (not (eq (aref org-table-current-line-types i) type)) + ;; We are going to cross a hline. Check if this is + ;; an authorized move. + (cond + ((not relative)) + ((not (eq (aref org-table-current-line-types i) 'hline))) + ((eq org-table-relative-ref-may-cross-hline t)) + ((eq org-table-relative-ref-may-cross-hline 'error) + (user-error "Row descriptor %s crosses hline" desc)) + (t (cl-decf i (if backwards -1 1)) ; Step back. + (throw :exit nil))))))) + (cond ((or (< i 0) (>= i l)) + (user-error "Row descriptor %s leads outside table" desc)) + ;; The last hline doesn't exist. Instead, point to last row + ;; in table. + ((= i (1- l)) (1- i)) + (t i)))) + +(defun org-table--error-on-old-row-references (s) + (when (string-match "&[-+0-9I]" s) + (user-error "Formula contains old &row reference, please rewrite using @-syntax"))) + +(defun org-table-make-reference (elements keep-empty numbers lispp) + "Convert list ELEMENTS to something appropriate to insert into formula. +KEEP-EMPTY indicated to keep empty fields, default is to skip them. +NUMBERS indicates that everything should be converted to numbers. +LISPP non-nil means to return something appropriate for a Lisp +list, `literal' is for the format specifier L." + ;; Calc nan (not a number) is used for the conversion of the empty + ;; field to a reference for several reasons: (i) It is accepted in a + ;; Calc formula (e. g. "" or "()" would result in a Calc error). + ;; (ii) In a single field (not in range) it can be distinguished + ;; from "(nan)" which is the reference made from a single field + ;; containing "nan". + (if (stringp elements) + ;; field reference + (if lispp + (if (eq lispp 'literal) + elements + (if (and (eq elements "") (not keep-empty)) + "" + (prin1-to-string + (if numbers (string-to-number elements) elements)))) + (if (string-match "\\S-" elements) + (progn + (when numbers (setq elements (number-to-string + (string-to-number elements)))) + (concat "(" elements ")")) + (if (or (not keep-empty) numbers) "(0)" "nan"))) + ;; range reference + (unless keep-empty + (setq elements + (delq nil + (mapcar (lambda (x) (if (string-match "\\S-" x) x nil)) + elements)))) + (setq elements (or elements '())) ; if delq returns nil then we need '() + (if lispp + (mapconcat + (lambda (x) + (if (eq lispp 'literal) + x + (prin1-to-string (if numbers (string-to-number x) x)))) + elements " ") + (concat "[" (mapconcat + (lambda (x) + (if (string-match "\\S-" x) + (if numbers + (number-to-string (string-to-number x)) + x) + (if (or (not keep-empty) numbers) "0" "nan"))) + elements + ",") "]")))) + +(defun org-table-message-once-per-second (t1 &rest args) + "If there has been more than one second since T1, display message. +ARGS are passed as arguments to the `message' function. Returns +current time if a message is printed, otherwise returns T1. If +T1 is nil, always messages." + (let ((curtime (current-time))) + (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1)))) + (progn (apply 'message args) + curtime) + t1))) + +;;;###autoload +(defun org-table-recalculate (&optional all noalign) + "Recalculate the current table line by applying all stored formulas. + +With prefix arg ALL, do this for all lines in the table. + +When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \ +if ALL is the symbol `iterate', +recompute the table until it no longer changes. + +If NOALIGN is not nil, do not re-align the table after the computations +are done. This is typically used internally to save time, if it is +known that the table will be realigned a little later anyway." + (interactive "P") + (unless (memq this-command org-recalc-commands) + (push this-command org-recalc-commands)) + (unless (org-at-table-p) (user-error "Not at a table")) + (if (or (eq all 'iterate) (equal all '(16))) + (org-table-iterate) + (org-table-analyze) + (let* ((eqlist (sort (org-table-get-stored-formulas) + (lambda (a b) (string< (car a) (car b))))) + (inhibit-redisplay (not debug-on-error)) + (line-re org-table-dataline-regexp) + (log-first-time (current-time)) + (log-last-time log-first-time) + (cnt 0) + beg end eqlcol eqlfield) + ;; Insert constants in all formulas. + (when eqlist + (org-table-save-field + ;; Expand equations, then split the equation list between + ;; column formulas and field formulas. + (dolist (eq eqlist) + (let* ((rhs (org-table-formula-substitute-names + (org-table-formula-handle-first/last-rc (cdr eq)))) + (old-lhs (car eq)) + (lhs + (org-table-formula-handle-first/last-rc + (cond + ((string-match "\\`@-?I+" old-lhs) + (user-error "Can't assign to hline relative reference")) + ((string-match "\\`$[<>]" old-lhs) + (let ((new (org-table-formula-handle-first/last-rc + old-lhs))) + (when (assoc new eqlist) + (user-error "\"%s=\" formula tries to overwrite \ +existing formula for column %s" + old-lhs + new)) + new)) + (t old-lhs))))) + (if (string-match-p "\\`\\$[0-9]+\\'" lhs) + (push (cons lhs rhs) eqlcol) + (push (cons lhs rhs) eqlfield)))) + (setq eqlcol (nreverse eqlcol)) + ;; Expand ranges in lhs of formulas + (setq eqlfield (org-table-expand-lhs-ranges (nreverse eqlfield))) + ;; Get the correct line range to process. + (if all + (progn + (setq end (copy-marker (org-table-end))) + (goto-char (setq beg org-table-current-begin-pos)) + (cond + ((re-search-forward org-table-calculate-mark-regexp end t) + ;; This is a table with marked lines, compute selected + ;; lines. + (setq line-re org-table-recalculate-regexp)) + ;; Move forward to the first non-header line. + ((and (re-search-forward org-table-dataline-regexp end t) + (re-search-forward org-table-hline-regexp end t) + (re-search-forward org-table-dataline-regexp end t)) + (setq beg (match-beginning 0))) + ;; Just leave BEG at the start of the table. + (t nil))) + (setq beg (line-beginning-position) + end (copy-marker (line-beginning-position 2)))) + (goto-char beg) + ;; Mark named fields untouchable. Also check if several + ;; field/range formulas try to set the same field. + (remove-text-properties beg end '(:org-untouchable t)) + (let ((current-line (count-lines org-table-current-begin-pos + (line-beginning-position))) + seen-fields) + (dolist (eq eqlfield) + (let* ((name (car eq)) + (location (assoc name org-table-named-field-locations)) + (eq-line (or (nth 1 location) + (and (string-match "\\`@\\([0-9]+\\)" name) + (aref org-table-dlines + (string-to-number + (match-string 1 name)))))) + (reference + (if location + ;; Turn field coordinates associated to NAME + ;; into an absolute reference. + (format "@%d$%d" + (org-table-line-to-dline eq-line) + (nth 2 location)) + name))) + (when (member reference seen-fields) + (user-error "Several field/range formulas try to set %s" + reference)) + (push reference seen-fields) + (when (or all (eq eq-line current-line)) + (org-table-goto-field name) + (org-table-put-field-property :org-untouchable t))))) + ;; Evaluate the column formulas, but skip fields covered by + ;; field formulas. + (goto-char beg) + (while (re-search-forward line-re end t) + (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1)) + ;; Unprotected line, recalculate. + (cl-incf cnt) + (when all + (setq log-last-time + (org-table-message-once-per-second + log-last-time + "Re-applying formulas to full table...(line %d)" cnt))) + (if (markerp org-last-recalc-line) + (move-marker org-last-recalc-line (line-beginning-position)) + (setq org-last-recalc-line + (copy-marker (line-beginning-position)))) + (dolist (entry eqlcol) + (goto-char org-last-recalc-line) + (org-table-goto-column + (string-to-number (substring (car entry) 1)) nil 'force) + (unless (get-text-property (point) :org-untouchable) + (org-table-eval-formula + nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis))))) + ;; Evaluate the field formulas. + (dolist (eq eqlfield) + (let ((reference (car eq)) + (formula (cdr eq))) + (setq log-last-time + (org-table-message-once-per-second + (and all log-last-time) + "Re-applying formula to field: %s" (car eq))) + (org-table-goto-field + reference + ;; Possibly create a new column, as long as + ;; `org-table-formula-create-columns' allows it. + (let ((column-count (progn (end-of-line) + (1- (org-table-current-column))))) + (lambda (column) + (when (> column 1000) + (user-error "Formula column target too large")) + (and (> column column-count) + (or (eq org-table-formula-create-columns t) + (and (eq org-table-formula-create-columns 'warn) + (progn + (org-display-warning + "Out-of-bounds formula added columns") + t)) + (and (eq org-table-formula-create-columns 'prompt) + (yes-or-no-p + "Out-of-bounds formula. Add columns? ")) + (user-error + "Missing columns in the table. Aborting")))))) + (org-table-eval-formula nil formula t t t t)))) + ;; Clean up markers and internal text property. + (remove-text-properties (point-min) (point-max) '(org-untouchable t)) + (set-marker end nil) + (unless noalign + (when org-table-may-need-update (org-table-align)) + (when all + (org-table-message-once-per-second + log-first-time "Re-applying formulas to %d lines... done" cnt))) + (org-table-message-once-per-second + (and all log-first-time) "Re-applying formulas... done"))))) + +;;;###autoload +(defun org-table-iterate (&optional arg) + "Recalculate the table until it does not change anymore. +The maximum number of iterations is 10, but you can choose a different value +with the prefix ARG." + (interactive "P") + (let ((imax (if arg (prefix-numeric-value arg) 10)) + (i 0) + (lasttbl (buffer-substring (org-table-begin) (org-table-end))) + thistbl) + (catch 'exit + (while (< i imax) + (setq i (1+ i)) + (org-table-recalculate 'all) + (setq thistbl (buffer-substring (org-table-begin) (org-table-end))) + (if (not (string= lasttbl thistbl)) + (setq lasttbl thistbl) + (if (> i 1) + (message "Convergence after %d iterations" i) + (message "Table was already stable")) + (throw 'exit t))) + (user-error "No convergence after %d iterations" i)))) + +;;;###autoload +(defun org-table-recalculate-buffer-tables () + "Recalculate all tables in the current buffer." + (interactive) + (org-with-wide-buffer + (org-table-map-tables + (lambda () + ;; Reason for separate `org-table-align': When repeating + ;; (org-table-recalculate t) `org-table-may-need-update' gets in + ;; the way. + (org-table-recalculate t t) + (org-table-align)) + t))) + +;;;###autoload +(defun org-table-iterate-buffer-tables () + "Iterate all tables in the buffer, to converge inter-table dependencies." + (interactive) + (let* ((imax 10) + (i imax) + (checksum (md5 (buffer-string))) + c1) + (org-with-wide-buffer + (catch 'exit + (while (> i 0) + (setq i (1- i)) + (org-table-map-tables (lambda () (org-table-recalculate t t)) t) + (if (equal checksum (setq c1 (md5 (buffer-string)))) + (progn + (org-table-map-tables #'org-table-align t) + (message "Convergence after %d iterations" (- imax i)) + (throw 'exit t)) + (setq checksum c1))) + (org-table-map-tables #'org-table-align t) + (user-error "No convergence after %d iterations" imax))))) + +(defun org-table-calc-current-TBLFM (&optional arg) + "Apply the #+TBLFM in the line at point to the table." + (interactive "P") + (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line")) + (let ((formula (buffer-substring + (line-beginning-position) + (line-end-position)))) + (save-excursion + ;; Insert a temporary formula at right after the table + (goto-char (org-table-TBLFM-begin)) + (let ((s (point-marker))) + (insert formula "\n") + (let ((e (point-marker))) + ;; Recalculate the table. + (beginning-of-line 0) ; move to the inserted line + (skip-chars-backward " \r\n\t") + (unwind-protect + (org-call-with-arg #'org-table-recalculate (or arg t)) + ;; Delete the formula inserted temporarily. + (delete-region s e) + (set-marker s nil) + (set-marker e nil))))))) + +(defun org-table-TBLFM-begin () + "Find the beginning of the TBLFM lines and return its position. +Return nil when the beginning of TBLFM line was not found." + (save-excursion + (when (progn (forward-line 1) + (re-search-backward org-table-TBLFM-begin-regexp nil t)) + (line-beginning-position 2)))) + +(defun org-table-expand-lhs-ranges (equations) + "Expand list of formulas. +If some of the RHS in the formulas are ranges or a row reference, +expand them to individual field equations for each field. This +function assumes the table is already analyzed (i.e., using +`org-table-analyze')." + (let (res) + (dolist (e equations (nreverse res)) + (let ((lhs (car e)) + (rhs (cdr e))) + (cond + ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs) + ;; This just refers to one fixed field. + (push e res)) + ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs) + ;; This just refers to one fixed named field. + (push e res)) + ((string-match-p "\\`\\$[0-9]+\\'" lhs) + ;; Column formulas are treated specially and are not + ;; expanded. + (push e res)) + ((string-match "\\`@[0-9]+\\'" lhs) + (dotimes (ic org-table-current-ncol) + (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e) + rhs) + res))) + (t + (let* ((range (org-table-get-range + lhs org-table-current-begin-pos 1 nil 'corners)) + (r1 (org-table-line-to-dline (nth 0 range))) + (c1 (nth 1 range)) + (r2 (org-table-line-to-dline (nth 2 range) 'above)) + (c2 (nth 3 range))) + (cl-loop for ir from r1 to r2 do + (cl-loop for ic from c1 to c2 do + (push (cons (propertize + (format "@%d$%d" ir ic) :orig-eqn e) + rhs) + res)))))))))) + +(defun org-table-formula-handle-first/last-rc (s) + "Replace @<, @>, $<, $> with first/last row/column of the table. +So @< and $< will always be replaced with @1 and $1, respectively. +The advantage of these special markers are that structure editing of +the table will not change them, while @1 and $1 will be modified +when a line/row is swapped out of that privileged position. So for +formulas that use a range of rows or columns, it may often be better +to anchor the formula with \"I\" row markers, or to offset from the +borders of the table using the @< @> $< $> makers." + (let (n nmax len char (start 0)) + (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)" + s start) + (if (match-end 3) + (setq start (match-end 3)) + (setq nmax (if (equal (match-string 1 s) "@") + (1- (length org-table-dlines)) + org-table-current-ncol) + len (- (match-end 2) (match-beginning 2)) + char (string-to-char (match-string 2 s)) + n (if (= char ?<) + len + (- nmax len -1))) + (if (or (< n 1) (> n nmax)) + (user-error "Reference \"%s\" in expression \"%s\" points outside table" + (match-string 0 s) s)) + (setq start (match-beginning 0)) + (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s))))) + s) + +(defun org-table-formula-substitute-names (f) + "Replace $const with values in string F." + (let ((start 0) + (pp (/= (string-to-char f) ?')) + (duration (string-match-p ";.*[Tt].*\\'" f)) + (new (replace-regexp-in-string ; Check for column names. + org-table-column-name-regexp + (lambda (m) + (concat "$" (cdr (assoc (match-string 1 m) + org-table-column-names)))) + f t t))) + ;; Parameters and constants. + (while (setq start + (string-match + "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" + new start)) + (if (match-end 2) (setq start (match-end 2)) + (cl-incf start) + ;; When a duration is expected, convert value on the fly. + (let ((value + (save-match-data + (let ((v (org-table-get-constant (match-string 1 new)))) + (if (and (org-string-nw-p v) duration) + (org-table-time-string-to-seconds v) + v))))) + (when value + (setq new (replace-match + (concat (and pp "(") value (and pp ")")) t t new)))))) + (if org-table-formula-debug (propertize new :orig-formula f) new))) + +(defun org-table-get-constant (const) + "Find the value for a parameter or constant in a formula. +Parameters get priority." + (or (cdr (assoc const org-table-local-parameters)) + (cdr (assoc const org-table-formula-constants-local)) + (cdr (assoc const org-table-formula-constants)) + (and (fboundp 'constants-get) (constants-get const)) + (and (string= (substring const 0 (min 5 (length const))) "PROP_") + (org-entry-get nil (substring const 5) 'inherit)) + "#UNDEFINED_NAME")) + +(defvar org-table-fedit-map + (let ((map (make-sparse-keymap))) + (org-defkey map "\C-x\C-s" 'org-table-fedit-finish) + (org-defkey map "\C-c\C-s" 'org-table-fedit-finish) + (org-defkey map "\C-c\C-c" 'org-table-fedit-finish) + (org-defkey map "\C-c'" 'org-table-fedit-finish) + (org-defkey map "\C-c\C-q" 'org-table-fedit-abort) + (org-defkey map "\C-c?" 'org-table-show-reference) + (org-defkey map [(meta shift up)] 'org-table-fedit-line-up) + (org-defkey map [(meta shift down)] 'org-table-fedit-line-down) + (org-defkey map [(shift up)] 'org-table-fedit-ref-up) + (org-defkey map [(shift down)] 'org-table-fedit-ref-down) + (org-defkey map [(shift left)] 'org-table-fedit-ref-left) + (org-defkey map [(shift right)] 'org-table-fedit-ref-right) + (org-defkey map [(meta up)] 'org-table-fedit-scroll-down) + (org-defkey map [(meta down)] 'org-table-fedit-scroll) + (org-defkey map [(meta tab)] 'lisp-complete-symbol) + (org-defkey map "\M-\C-i" 'lisp-complete-symbol) + (org-defkey map [(tab)] 'org-table-fedit-lisp-indent) + (org-defkey map "\C-i" 'org-table-fedit-lisp-indent) + (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type) + (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates) + map)) + +(easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu" + '("Edit-Formulas" + ["Finish and Install" org-table-fedit-finish t] + ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"] + ["Abort" org-table-fedit-abort t] + "--" + ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t] + ["Complete Lisp Symbol" lisp-complete-symbol t] + "--" + "Shift Reference at Point" + ["Up" org-table-fedit-ref-up t] + ["Down" org-table-fedit-ref-down t] + ["Left" org-table-fedit-ref-left t] + ["Right" org-table-fedit-ref-right t] + "-" + "Change Test Row for Column Formulas" + ["Up" org-table-fedit-line-up t] + ["Down" org-table-fedit-line-down t] + "--" + ["Scroll Table Window" org-table-fedit-scroll t] + ["Scroll Table Window down" org-table-fedit-scroll-down t] + ["Show Table Grid" org-table-fedit-toggle-coordinates + :style toggle :selected (with-current-buffer (marker-buffer org-pos) + org-table-overlay-coordinates)] + "--" + ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type + :style toggle :selected org-table-buffer-is-an])) + +(defvar org-pos) +(defvar org-table--fedit-source nil + "Position of the TBLFM line being edited.") + +;;;###autoload +(defun org-table-edit-formulas () + "Edit the formulas of the current table in a separate buffer." + (interactive) + (let ((at-tblfm (org-at-TBLFM-p))) + (unless (or at-tblfm (org-at-table-p)) + (user-error "Not at a table")) + (save-excursion + ;; Move point within the table before analyzing it. + (when at-tblfm (re-search-backward "^[ \t]*|")) + (org-table-analyze)) + (let ((key (org-table-current-field-formula 'key 'noerror)) + (eql (sort (org-table-get-stored-formulas t (and at-tblfm (point))) + #'org-table-formula-less-p)) + (pos (point-marker)) + (source (copy-marker (line-beginning-position))) + (startline 1) + (wc (current-window-configuration)) + (sel-win (selected-window)) + (titles '((column . "# Column Formulas\n") + (field . "# Field and Range Formulas\n") + (named . "# Named Field Formulas\n")))) + (org-switch-to-buffer-other-window "*Edit Formulas*") + (erase-buffer) + ;; Keep global-font-lock-mode from turning on font-lock-mode + (let ((font-lock-global-modes '(not fundamental-mode))) + (fundamental-mode)) + (setq-local font-lock-global-modes (list 'not major-mode)) + (setq-local org-pos pos) + (setq-local org-table--fedit-source source) + (setq-local org-window-configuration wc) + (setq-local org-selected-window sel-win) + (use-local-map org-table-fedit-map) + (add-hook 'post-command-hook #'org-table-fedit-post-command t t) + (easy-menu-add org-table-fedit-menu) + (setq startline (org-current-line)) + (dolist (entry eql) + (let* ((type (cond + ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry)) + 'column) + ((equal (string-to-char (car entry)) ?@) 'field) + (t 'named))) + (title (assq type titles))) + (when title + (unless (bobp) (insert "\n")) + (insert + (org-add-props (cdr title) nil 'face font-lock-comment-face)) + (setq titles (remove title titles))) + (when (equal key (car entry)) (setq startline (org-current-line))) + (let ((s (concat + (if (memq (string-to-char (car entry)) '(?@ ?$)) "" "$") + (car entry) " = " (cdr entry) "\n"))) + (remove-text-properties 0 (length s) '(face nil) s) + (insert s)))) + (when (eq org-table-use-standard-references t) + (org-table-fedit-toggle-ref-type)) + (org-goto-line startline) + (message "%s" (substitute-command-keys "\\<org-mode-map>\ +Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \ +See menu for more commands."))))) + +(defun org-table-fedit-post-command () + (when (not (memq this-command '(lisp-complete-symbol))) + (let ((win (selected-window))) + (save-excursion + (ignore-errors (org-table-show-reference)) + (select-window win))))) + +(defun org-table-formula-to-user (s) + "Convert a formula from internal to user representation." + (if (eq org-table-use-standard-references t) + (org-table-convert-refs-to-an s) + s)) + +(defun org-table-formula-from-user (s) + "Convert a formula from user to internal representation." + (if org-table-use-standard-references + (org-table-convert-refs-to-rc s) + s)) + +(defun org-table-convert-refs-to-rc (s) + "Convert spreadsheet references from A7 to @7$28. +Works for single references, but also for entire formulas and even the +full TBLFM line." + (let ((start 0)) + (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start) + (cond + ((match-end 3) + ;; format match, just advance + (setq start (match-end 0))) + ((and (> (match-beginning 0) 0) + (equal ?. (aref s (max (1- (match-beginning 0)) 0))) + (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0))))) + ;; 3.e5 or something like this. + (setq start (match-end 0))) + ((or (> (- (match-end 1) (match-beginning 1)) 2) + ;; (member (match-string 1 s) + ;; '("arctan" "exp" "expm" "lnp" "log" "stir")) + ) + ;; function name, just advance + (setq start (match-end 0))) + (t + (setq start (match-beginning 0) + s (replace-match + (if (equal (match-string 2 s) "&") + (format "$%d" (org-letters-to-number (match-string 1 s))) + (format "@%d$%d" + (string-to-number (match-string 2 s)) + (org-letters-to-number (match-string 1 s)))) + t t s))))) + s)) + +(defun org-table-convert-refs-to-an (s) + "Convert spreadsheet references from to @7$28 to AB7. +Works for single references, but also for entire formulas and even the +full TBLFM line." + (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s) + (setq s (replace-match + (format "%s%d" + (org-number-to-letters + (string-to-number (match-string 2 s))) + (string-to-number (match-string 1 s))) + t t s))) + (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s) + (setq s (replace-match (concat "\\1" + (org-number-to-letters + (string-to-number (match-string 2 s))) "&") + t nil s))) + s) + +(defun org-letters-to-number (s) + "Convert a base 26 number represented by letters into an integer. +For example: AB -> 28." + (let ((n 0)) + (setq s (upcase s)) + (while (> (length s) 0) + (setq n (+ (* n 26) (string-to-char s) (- ?A) 1) + s (substring s 1))) + n)) + +(defun org-number-to-letters (n) + "Convert an integer into a base 26 number represented by letters. +For example: 28 -> AB." + (let ((s "")) + (while (> n 0) + (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s) + n (/ (1- n) 26))) + s)) + +(defun org-table-time-string-to-seconds (s) + "Convert a time string into numerical duration in seconds. +S can be a string matching either -?HH:MM:SS or -?HH:MM. +If S is a string representing a number, keep this number." + (if (equal s "") + s + (let (hour minus min sec res) + (cond + ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s)) + (setq minus (< 0 (length (match-string 1 s))) + hour (string-to-number (match-string 2 s)) + min (string-to-number (match-string 3 s)) + sec (string-to-number (match-string 4 s))) + (if minus + (setq res (- (+ (* hour 3600) (* min 60) sec))) + (setq res (+ (* hour 3600) (* min 60) sec)))) + ((and (not (string-match org-ts-regexp-both s)) + (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s)) + (setq minus (< 0 (length (match-string 1 s))) + hour (string-to-number (match-string 2 s)) + min (string-to-number (match-string 3 s))) + (if minus + (setq res (- (+ (* hour 3600) (* min 60)))) + (setq res (+ (* hour 3600) (* min 60))))) + (t (setq res (string-to-number s)))) + (number-to-string res)))) + +(defun org-table-time-seconds-to-string (secs &optional output-format) + "Convert a number of seconds to a time string. +If OUTPUT-FORMAT is non-nil, return a number of days, hours, +minutes or seconds." + (let* ((secs0 (abs secs)) + (res + (cond ((eq output-format 'days) + (format "%.3f" (/ (float secs0) 86400))) + ((eq output-format 'hours) + (format "%.2f" (/ (float secs0) 3600))) + ((eq output-format 'minutes) + (format "%.1f" (/ (float secs0) 60))) + ((eq output-format 'seconds) + (format "%d" secs0)) + ((eq output-format 'hh:mm) + ;; Ignore seconds + (substring (format-seconds + (if org-table-duration-hour-zero-padding + "%.2h:%.2m:%.2s" "%h:%.2m:%.2s") + secs0) + 0 -3)) + (t (format-seconds + (if org-table-duration-hour-zero-padding + "%.2h:%.2m:%.2s" "%h:%.2m:%.2s") + secs0))))) + (if (< secs 0) (concat "-" res) res))) + +(defun org-table-fedit-convert-buffer (function) + "Convert all references in this buffer, using FUNCTION." + (let ((origin (copy-marker (line-beginning-position)))) + (goto-char (point-min)) + (while (not (eobp)) + (insert (funcall function (buffer-substring (point) (line-end-position)))) + (delete-region (point) (line-end-position)) + (forward-line)) + (goto-char origin) + (set-marker origin nil))) + +(defun org-table-fedit-toggle-ref-type () + "Convert all references in the buffer from B3 to @3$2 and back." + (interactive) + (setq-local org-table-buffer-is-an (not org-table-buffer-is-an)) + (org-table-fedit-convert-buffer + (if org-table-buffer-is-an + 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc)) + (message "Reference type switched to %s" + (if org-table-buffer-is-an "A1 etc" "@row$column"))) + +(defun org-table-fedit-ref-up () + "Shift the reference at point one row/hline up." + (interactive) + (org-table-fedit-shift-reference 'up)) +(defun org-table-fedit-ref-down () + "Shift the reference at point one row/hline down." + (interactive) + (org-table-fedit-shift-reference 'down)) +(defun org-table-fedit-ref-left () + "Shift the reference at point one field to the left." + (interactive) + (org-table-fedit-shift-reference 'left)) +(defun org-table-fedit-ref-right () + "Shift the reference at point one field to the right." + (interactive) + (org-table-fedit-shift-reference 'right)) + +(defun org-table-fedit-shift-reference (dir) + (cond + ((org-in-regexp "\\(\\<[a-zA-Z]\\)&") + (if (memq dir '(left right)) + (org-rematch-and-replace 1 (eq dir 'left)) + (user-error "Cannot shift reference in this direction"))) + ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)") + ;; A B3-like reference + (if (memq dir '(up down)) + (org-rematch-and-replace 2 (eq dir 'up)) + (org-rematch-and-replace 1 (eq dir 'left)))) + ((org-in-regexp + "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?") + ;; An internal reference + (if (memq dir '(up down)) + (org-rematch-and-replace 2 (eq dir 'up) (match-end 3)) + (org-rematch-and-replace 5 (eq dir 'left)))))) + +(defun org-rematch-and-replace (n &optional decr hline) + "Re-match the group N, and replace it with the shifted reference." + (or (match-end n) (user-error "Cannot shift reference in this direction")) + (goto-char (match-beginning n)) + (and (looking-at (regexp-quote (match-string n))) + (replace-match (org-table-shift-refpart (match-string 0) decr hline) + t t))) + +(defun org-table-shift-refpart (ref &optional decr hline) + "Shift a reference part REF. +If DECR is set, decrease the references row/column, else increase. +If HLINE is set, this may be a hline reference, it certainly is not +a translation reference." + (save-match-data + (let* ((sign (string-match "^[-+]" ref)) n) + + (if sign (setq sign (substring ref 0 1) ref (substring ref 1))) + (cond + ((and hline (string-match "^I+" ref)) + (setq n (string-to-number (concat sign (number-to-string (length ref))))) + (setq n (+ n (if decr -1 1))) + (if (= n 0) (setq n (+ n (if decr -1 1)))) + (if sign + (setq sign (if (< n 0) "-" "+") n (abs n)) + (setq n (max 1 n))) + (concat sign (make-string n ?I))) + + ((string-match "^[0-9]+" ref) + (setq n (string-to-number (concat sign ref))) + (setq n (+ n (if decr -1 1))) + (if sign + (concat (if (< n 0) "-" "+") (number-to-string (abs n))) + (number-to-string (max 1 n)))) + + ((string-match "^[a-zA-Z]+" ref) + (org-number-to-letters + (max 1 (+ (org-letters-to-number ref) (if decr -1 1))))) + + (t (user-error "Cannot shift reference")))))) + +(defun org-table-fedit-toggle-coordinates () + "Toggle the display of coordinates in the referenced table." + (interactive) + (let ((pos (marker-position org-pos))) + (with-current-buffer (marker-buffer org-pos) + (save-excursion + (goto-char pos) + (org-table-toggle-coordinate-overlays))))) + +(defun org-table-fedit-finish (&optional arg) + "Parse the buffer for formula definitions and install them. +With prefix ARG, apply the new formulas to the table." + (interactive "P") + (org-table-remove-rectangle-highlight) + (when org-table-use-standard-references + (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc) + (setq org-table-buffer-is-an nil)) + (let ((pos org-pos) + (sel-win org-selected-window) + (source org-table--fedit-source) + eql) + (goto-char (point-min)) + (while (re-search-forward + "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)" + nil t) + (let ((var (match-string 1)) + (form (org-trim (match-string 3)))) + (unless (equal form "") + (while (string-match "[ \t]*\n[ \t]*" form) + (setq form (replace-match " " t t form))) + (when (assoc var eql) + (user-error "Double formulas for %s" var)) + (push (cons var form) eql)))) + (set-window-configuration org-window-configuration) + (select-window sel-win) + (goto-char source) + (org-table-store-formulas eql) + (set-marker pos nil) + (set-marker source nil) + (kill-buffer "*Edit Formulas*") + (if arg + (org-table-recalculate 'all) + (message "New formulas installed - press C-u C-c C-c to apply.")))) + +(defun org-table-fedit-abort () + "Abort editing formulas, without installing the changes." + (interactive) + (org-table-remove-rectangle-highlight) + (let ((pos org-pos) (sel-win org-selected-window)) + (set-window-configuration org-window-configuration) + (select-window sel-win) + (goto-char pos) + (move-marker pos nil) + (message "Formula editing aborted without installing changes"))) + +(defun org-table-fedit-lisp-indent () + "Pretty-print and re-indent Lisp expressions in the Formula Editor." + (interactive) + (let ((pos (point)) beg end ind) + (beginning-of-line 1) + (cond + ((looking-at "[ \t]") + (goto-char pos) + (call-interactively 'lisp-indent-line)) + ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos)) + ((not (fboundp 'pp-buffer)) + (user-error "Cannot pretty-print. Command `pp-buffer' is not available")) + ((looking-at "[$&@0-9a-zA-Z]+ *= *'(") + (goto-char (- (match-end 0) 2)) + (setq beg (point)) + (setq ind (make-string (current-column) ?\ )) + (condition-case nil (forward-sexp 1) + (error + (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis"))) + (setq end (point)) + (save-restriction + (narrow-to-region beg end) + (if (eq last-command this-command) + (progn + (goto-char (point-min)) + (setq this-command nil) + (while (re-search-forward "[ \t]*\n[ \t]*" nil t) + (replace-match " "))) + (pp-buffer) + (untabify (point-min) (point-max)) + (goto-char (1+ (point-min))) + (while (re-search-forward "^." nil t) + (beginning-of-line 1) + (insert ind)) + (goto-char (point-max)) + (org-delete-backward-char 1))) + (goto-char beg)) + (t nil)))) + +(defvar org-show-positions nil) + +(defun org-table-show-reference (&optional local) + "Show the location/value of the $ expression at point. +When LOCAL is non-nil, show references for the table at point." + (interactive) + (org-table-remove-rectangle-highlight) + (when local (org-table-analyze)) + (catch 'exit + (let ((pos (if local (point) org-pos)) + (face2 'highlight) + (org-inhibit-highlight-removal t) + (win (selected-window)) + (org-show-positions nil) + var name e what match dest) + (setq what (cond + ((org-in-regexp "^@[0-9]+[ \t=]") + (setq match (concat (substring (match-string 0) 0 -1) + "$1.." + (substring (match-string 0) 0 -1) + "$100")) + 'range) + ((or (org-in-regexp org-table-range-regexp2) + (org-in-regexp org-table-translate-regexp) + (org-in-regexp org-table-range-regexp)) + (setq match + (save-match-data + (org-table-convert-refs-to-rc (match-string 0)))) + 'range) + ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name) + ((org-in-regexp "\\$[0-9]+") 'column) + ((not local) nil) + (t (user-error "No reference at point"))) + match (and what (or match (match-string 0)))) + (when (and match (not (equal (match-beginning 0) (point-at-bol)))) + (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0) + 'secondary-selection)) + (add-hook 'before-change-functions + #'org-table-remove-rectangle-highlight) + (when (eq what 'name) (setq var (substring match 1))) + (when (eq what 'range) + (unless (eq (string-to-char match) ?@) (setq match (concat "@" match))) + (setq match (org-table-formula-substitute-names match))) + (unless local + (save-excursion + (end-of-line) + (re-search-backward "^\\S-" nil t) + (beginning-of-line) + (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\ +\\([0-9]+\\|&\\)\\) *=") + (setq dest + (save-match-data + (org-table-convert-refs-to-rc (match-string 1)))) + (org-table-add-rectangle-overlay + (match-beginning 1) (match-end 1) face2)))) + (if (and (markerp pos) (marker-buffer pos)) + (if (get-buffer-window (marker-buffer pos)) + (select-window (get-buffer-window (marker-buffer pos))) + (org-switch-to-buffer-other-window (get-buffer-window + (marker-buffer pos))))) + (goto-char pos) + (org-table-force-dataline) + (let ((table-start + (if local org-table-current-begin-pos (org-table-begin)))) + (when dest + (setq name (substring dest 1)) + (cond + ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest) + (org-table-goto-field dest)) + ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" + dest) + (org-table-goto-field dest)) + (t (org-table-goto-column (string-to-number name)))) + (move-marker pos (point)) + (org-table-highlight-rectangle nil nil face2)) + (cond + ((equal dest match)) + ((not match)) + ((eq what 'range) + (ignore-errors (org-table-get-range match table-start nil 'highlight))) + ((setq e (assoc var org-table-named-field-locations)) + (org-table-goto-field var) + (org-table-highlight-rectangle) + (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e))) + ((setq e (assoc var org-table-column-names)) + (org-table-goto-column (string-to-number (cdr e))) + (org-table-highlight-rectangle) + (goto-char table-start) + (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|") + (org-table-end) t) + (progn + (goto-char (match-beginning 1)) + (org-table-highlight-rectangle) + (message "Named column (column %s)" (cdr e))) + (user-error "Column name not found"))) + ((eq what 'column) + ;; Column number. + (org-table-goto-column (string-to-number (substring match 1))) + (org-table-highlight-rectangle) + (message "Column %s" (substring match 1))) + ((setq e (assoc var org-table-local-parameters)) + (goto-char table-start) + (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t) + (progn + (goto-char (match-beginning 1)) + (org-table-highlight-rectangle) + (message "Local parameter.")) + (user-error "Parameter not found"))) + ((not var) (user-error "No reference at point")) + ((setq e (assoc var org-table-formula-constants-local)) + (message "Local Constant: $%s=%s in #+CONSTANTS line." + var (cdr e))) + ((setq e (assoc var org-table-formula-constants)) + (message "Constant: $%s=%s in `org-table-formula-constants'." + var (cdr e))) + ((setq e (and (fboundp 'constants-get) (constants-get var))) + (message "Constant: $%s=%s, from `constants.el'%s." + var e (format " (%s units)" constants-unit-system))) + (t (user-error "Undefined name $%s" var))) + (goto-char pos) + (when (and org-show-positions + (not (memq this-command '(org-table-fedit-scroll + org-table-fedit-scroll-down)))) + (push pos org-show-positions) + (push table-start org-show-positions) + (let ((min (apply 'min org-show-positions)) + (max (apply 'max org-show-positions))) + (set-window-start (selected-window) min) + (goto-char max) + (or (pos-visible-in-window-p max) + (set-window-start (selected-window) max))))) + (select-window win)))) + +(defun org-table-force-dataline () + "Make sure the cursor is in a dataline in a table." + (unless (save-excursion + (beginning-of-line 1) + (looking-at org-table-dataline-regexp)) + (let* ((re org-table-dataline-regexp) + (p1 (save-excursion (re-search-forward re nil 'move))) + (p2 (save-excursion (re-search-backward re nil 'move)))) + (cond ((and p1 p2) + (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point)))) + p1 p2))) + ((or p1 p2) (goto-char (or p1 p2))) + (t (user-error "No table dataline around here")))))) + +(defun org-table-fedit-line-up () + "Move cursor one line up in the window showing the table." + (interactive) + (org-table-fedit-move 'previous-line)) + +(defun org-table-fedit-line-down () + "Move cursor one line down in the window showing the table." + (interactive) + (org-table-fedit-move 'next-line)) + +(defun org-table-fedit-move (command) + "Move the cursor in the window showing the table. +Use COMMAND to do the motion, repeat if necessary to end up in a data line." + (let ((org-table-allow-automatic-line-recalculation nil) + (pos org-pos) (win (selected-window)) p) + (select-window (get-buffer-window (marker-buffer org-pos))) + (setq p (point)) + (call-interactively command) + (while (and (org-at-table-p) + (org-at-table-hline-p)) + (call-interactively command)) + (or (org-at-table-p) (goto-char p)) + (move-marker pos (point)) + (select-window win))) + +(defun org-table-fedit-scroll (N) + (interactive "p") + (let ((other-window-scroll-buffer (marker-buffer org-pos))) + (scroll-other-window N))) + +(defun org-table-fedit-scroll-down (N) + (interactive "p") + (org-table-fedit-scroll (- N))) + +(defvar org-table-rectangle-overlays nil) + +(defun org-table-add-rectangle-overlay (beg end &optional face) + "Add a new overlay." + (let ((ov (make-overlay beg end))) + (overlay-put ov 'face (or face 'secondary-selection)) + (push ov org-table-rectangle-overlays))) + +(defun org-table-highlight-rectangle (&optional beg end face) + "Highlight rectangular region in a table. +When buffer positions BEG and END are provided, use them to +delimit the region to highlight. Otherwise, refer to point. Use +FACE, when non-nil, for the highlight." + (let* ((beg (or beg (point))) + (end (or end (point))) + (b (min beg end)) + (e (max beg end)) + (start-coordinates + (save-excursion + (goto-char b) + (cons (line-beginning-position) (org-table-current-column)))) + (end-coordinates + (save-excursion + (goto-char e) + (cons (line-beginning-position) (org-table-current-column))))) + (when (boundp 'org-show-positions) + (setq org-show-positions (cons b (cons e org-show-positions)))) + (goto-char (car start-coordinates)) + (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates))) + (column-end (max (cdr start-coordinates) (cdr end-coordinates))) + (last-row (car end-coordinates))) + (while (<= (point) last-row) + (when (looking-at org-table-dataline-regexp) + (org-table-goto-column column-start) + (skip-chars-backward "^|\n") + (let ((p (point))) + (org-table-goto-column column-end) + (skip-chars-forward "^|\n") + (org-table-add-rectangle-overlay p (point) face))) + (forward-line))) + (goto-char (car start-coordinates))) + (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight)) + +(defun org-table-remove-rectangle-highlight (&rest _ignore) + "Remove the rectangle overlays." + (unless org-inhibit-highlight-removal + (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight) + (mapc 'delete-overlay org-table-rectangle-overlays) + (setq org-table-rectangle-overlays nil))) + +(defvar-local org-table-coordinate-overlays nil + "Collects the coordinate grid overlays, so that they can be removed.") + +(defun org-table-overlay-coordinates () + "Add overlays to the table at point, to show row/column coordinates." + (interactive) + (mapc 'delete-overlay org-table-coordinate-overlays) + (setq org-table-coordinate-overlays nil) + (save-excursion + (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg) + (goto-char (org-table-begin)) + (while (org-at-table-p) + (setq eol (point-at-eol)) + (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol)))) + (push ov org-table-coordinate-overlays) + (setq hline (looking-at org-table-hline-regexp)) + (setq str (if hline (format "I*%-2d" (setq ih (1+ ih))) + (format "%4d" (setq id (1+ id))))) + (org-overlay-before-string ov str 'org-special-keyword 'evaporate) + (when hline + (setq ic 0) + (while (re-search-forward "[+|]\\(-+\\)" eol t) + (setq beg (1+ (match-beginning 0)) + ic (1+ ic) + s1 (concat "$" (int-to-string ic)) + s2 (org-number-to-letters ic) + str (if (eq org-table-use-standard-references t) s2 s1)) + (setq ov (make-overlay beg (+ beg (length str)))) + (push ov org-table-coordinate-overlays) + (org-overlay-display ov str 'org-special-keyword 'evaporate))) + (beginning-of-line 2))))) + +;;;###autoload +(defun org-table-toggle-coordinate-overlays () + "Toggle the display of Row/Column numbers in tables." + (interactive) + (setq org-table-overlay-coordinates (not org-table-overlay-coordinates)) + (message "Tables Row/Column numbers display turned %s" + (if org-table-overlay-coordinates "on" "off")) + (if (and (org-at-table-p) org-table-overlay-coordinates) + (org-table-align)) + (unless org-table-overlay-coordinates + (mapc 'delete-overlay org-table-coordinate-overlays) + (setq org-table-coordinate-overlays nil))) + +;;;###autoload +(defun org-table-toggle-formula-debugger () + "Toggle the formula debugger in tables." + (interactive) + (setq org-table-formula-debug (not org-table-formula-debug)) + (message "Formula debugging has been turned %s" + (if org-table-formula-debug "on" "off"))) + +;;; The orgtbl minor mode + +;; Define a minor mode which can be used in other modes in order to +;; integrate the Org table editor. + +;; This is really a hack, because the Org table editor uses several +;; keys which normally belong to the major mode, for example the TAB +;; and RET keys. Here is how it works: The minor mode defines all the +;; keys necessary to operate the table editor, but wraps the commands +;; into a function which tests if the cursor is currently inside +;; a table. If that is the case, the table editor command is +;; executed. However, when any of those keys is used outside a table, +;; the function uses `key-binding' to look up if the key has an +;; associated command in another currently active keymap (minor modes, +;; major mode, global), and executes that command. There might be +;; problems if any of the keys used by the table editor is otherwise +;; used as a prefix key. + +;; Another challenge is that the key binding for TAB can be tab or \C-i, +;; likewise the binding for RET can be return or \C-m. Orgtbl-mode +;; addresses this by checking explicitly for both bindings. + +;; The optimized version (see variable `orgtbl-optimized') takes over +;; all keys which are bound to `self-insert-command' in the *global map*. +;; Some modes bind other commands to simple characters, for example +;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode +;; active, this binding is ignored inside tables and replaced with a +;; modified self-insert. + + +(defvar orgtbl-mode-map (make-keymap) + "Keymap for `orgtbl-mode'.") + +(defvar org-old-auto-fill-inhibit-regexp nil + "Local variable used by `orgtbl-mode'.") + +(defconst orgtbl-line-start-regexp + "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)" + "Matches a line belonging to an orgtbl.") + +(defconst orgtbl-extra-font-lock-keywords + (list (list (concat "^" orgtbl-line-start-regexp ".*") + 0 (quote 'org-table) 'prepend)) + "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.") + +;; Install it as a minor mode. +(put 'orgtbl-mode :included t) +(put 'orgtbl-mode :menu-tag "Org Table Mode") + +;;;###autoload +(define-minor-mode orgtbl-mode + "The Org mode table editor as a minor mode for use in other modes." + :lighter " OrgTbl" :keymap orgtbl-mode-map + (org-load-modules-maybe) + (cond + ((derived-mode-p 'org-mode) + ;; Exit without error, in case some hook functions calls this by + ;; accident in Org mode. + (message "Orgtbl mode is not useful in Org mode, command ignored")) + (orgtbl-mode + (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?! + ;; Make sure we are first in minor-mode-map-alist + (let ((c (assq 'orgtbl-mode minor-mode-map-alist))) + ;; FIXME: maybe it should use emulation-mode-map-alists? + (and c (setq minor-mode-map-alist + (cons c (delq c minor-mode-map-alist))))) + (setq-local org-table-may-need-update t) + (add-hook 'before-change-functions 'org-before-change-function + nil 'local) + (setq-local org-old-auto-fill-inhibit-regexp + auto-fill-inhibit-regexp) + (setq-local auto-fill-inhibit-regexp + (if auto-fill-inhibit-regexp + (concat orgtbl-line-start-regexp "\\|" + auto-fill-inhibit-regexp) + orgtbl-line-start-regexp)) + (add-to-invisibility-spec '(org-cwidth)) + (when (fboundp 'font-lock-add-keywords) + (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords) + (org-restart-font-lock)) + (easy-menu-add orgtbl-mode-menu)) + (t + (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp) + (org-table-cleanup-narrow-column-properties) + (org-remove-from-invisibility-spec '(org-cwidth)) + (remove-hook 'before-change-functions 'org-before-change-function t) + (when (fboundp 'font-lock-remove-keywords) + (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords) + (org-restart-font-lock)) + (easy-menu-remove orgtbl-mode-menu) + (force-mode-line-update 'all)))) + +(defun org-table-cleanup-narrow-column-properties () + "Remove all properties related to narrow-column invisibility." + (let ((s (point-min))) + (while (setq s (text-property-any s (point-max) + 'display org-narrow-column-arrow)) + (remove-text-properties s (1+ s) '(display t))) + (setq s (point-min)) + (while (setq s (text-property-any s (point-max) 'org-cwidth 1)) + (remove-text-properties s (1+ s) '(org-cwidth t))) + (setq s (point-min)) + (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth)) + (remove-text-properties s (1+ s) '(invisible t))))) + +(defun orgtbl-make-binding (fun n &rest keys) + "Create a function for binding in the table minor mode. +FUN is the command to call inside a table. N is used to create a unique +command name. KEYS are keys that should be checked in for a command +to execute outside of tables." + (eval + (list 'defun + (intern (concat "orgtbl-hijacker-command-" (int-to-string n))) + '(arg) + (concat "In tables, run `" (symbol-name fun) "'.\n" + "Outside of tables, run the binding of `" + (mapconcat #'key-description keys "' or `") + "'.") + '(interactive "p") + (list 'if + '(org-at-table-p) + (list 'call-interactively (list 'quote fun)) + (list 'let '(orgtbl-mode) + (list 'call-interactively + (append '(or) + (mapcar (lambda (k) + (list 'key-binding k)) + keys) + '('orgtbl-error)))))))) + +(defun orgtbl-error () + "Error when there is no default binding for a table key." + (interactive) + (user-error "This key has no function outside tables")) + +(defun orgtbl-setup () + "Setup orgtbl keymaps." + (let ((nfunc 0) + (bindings + '(([(meta shift left)] org-table-delete-column) + ([(meta left)] org-table-move-column-left) + ([(meta right)] org-table-move-column-right) + ([(meta shift right)] org-table-insert-column) + ([(meta shift up)] org-table-kill-row) + ([(meta shift down)] org-table-insert-row) + ([(meta up)] org-table-move-row-up) + ([(meta down)] org-table-move-row-down) + ("\C-c\C-w" org-table-cut-region) + ("\C-c\M-w" org-table-copy-region) + ("\C-c\C-y" org-table-paste-rectangle) + ("\C-c\C-w" org-table-wrap-region) + ("\C-c-" org-table-insert-hline) + ("\C-c}" org-table-toggle-coordinate-overlays) + ("\C-c{" org-table-toggle-formula-debugger) + ("\C-m" org-table-next-row) + ([(shift return)] org-table-copy-down) + ("\C-c?" org-table-field-info) + ("\C-c " org-table-blank-field) + ("\C-c+" org-table-sum) + ("\C-c=" org-table-eval-formula) + ("\C-c'" org-table-edit-formulas) + ("\C-c`" org-table-edit-field) + ("\C-c*" org-table-recalculate) + ("\C-c^" org-table-sort-lines) + ("\M-a" org-table-beginning-of-field) + ("\M-e" org-table-end-of-field) + ([(control ?#)] org-table-rotate-recalc-marks))) + elt key fun cmd) + (while (setq elt (pop bindings)) + (setq nfunc (1+ nfunc)) + (setq key (org-key (car elt)) + fun (nth 1 elt) + cmd (orgtbl-make-binding fun nfunc key)) + (org-defkey orgtbl-mode-map key cmd)) + + ;; Special treatment needed for TAB, RET and DEL + (org-defkey orgtbl-mode-map [(return)] + (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m")) + (org-defkey orgtbl-mode-map "\C-m" + (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)])) + (org-defkey orgtbl-mode-map [(tab)] + (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i")) + (org-defkey orgtbl-mode-map "\C-i" + (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])) + (org-defkey orgtbl-mode-map [(shift tab)] + (orgtbl-make-binding 'org-table-previous-field 104 + [(shift tab)] [(tab)] "\C-i")) + (org-defkey orgtbl-mode-map [backspace] + (orgtbl-make-binding 'org-delete-backward-char 109 + [backspace] (kbd "DEL"))) + + (org-defkey orgtbl-mode-map [S-iso-lefttab] + (orgtbl-make-binding 'org-table-previous-field 107 + [S-iso-lefttab] [backtab] [(shift tab)] + [(tab)] "\C-i")) + + (org-defkey orgtbl-mode-map [backtab] + (orgtbl-make-binding 'org-table-previous-field 108 + [backtab] [S-iso-lefttab] [(shift tab)] + [(tab)] "\C-i")) + + (org-defkey orgtbl-mode-map "\M-\C-m" + (orgtbl-make-binding 'org-table-wrap-region 105 + "\M-\C-m" [(meta return)])) + (org-defkey orgtbl-mode-map [(meta return)] + (orgtbl-make-binding 'org-table-wrap-region 106 + [(meta return)] "\M-\C-m")) + + (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c) + (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region) + + (when orgtbl-optimized + ;; If the user wants maximum table support, we need to hijack + ;; some standard editing functions + (org-remap orgtbl-mode-map + 'self-insert-command 'orgtbl-self-insert-command + 'delete-char 'org-delete-char + 'delete-backward-char 'org-delete-backward-char) + (org-defkey orgtbl-mode-map "|" 'org-force-self-insert)) + (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu" + '("OrgTbl" + ["Create or convert" org-table-create-or-convert-from-region + :active (not (org-at-table-p)) :keys "C-c |" ] + "--" + ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"] + ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"] + ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"] + ["Next Row" org-return :active (org-at-table-p) :keys "RET"] + "--" + ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"] + ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "] + ["Copy Field from Above" + org-table-copy-down :active (org-at-table-p) :keys "S-RET"] + "--" + ("Column" + ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"] + ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"] + ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"] + ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]) + ("Row" + ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"] + ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"] + ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"] + ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"] + ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"] + "--" + ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"]) + ("Rectangle" + ["Copy Rectangle" org-copy-special :active (org-at-table-p)] + ["Cut Rectangle" org-cut-special :active (org-at-table-p)] + ["Paste Rectangle" org-paste-special :active (org-at-table-p)] + ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)]) + "--" + ("Radio tables" + ["Insert table template" orgtbl-insert-radio-table + (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)] + ["Comment/uncomment table" orgtbl-toggle-comment t]) + "--" + ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="] + ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="] + ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"] + ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"] + ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"] + ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"] + ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"] + ["Sum Column/Rectangle" org-table-sum + :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"] + ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"] + ["Debug Formulas" + org-table-toggle-formula-debugger :active (org-at-table-p) + :keys "C-c {" + :style toggle :selected org-table-formula-debug] + ["Show Col/Row Numbers" + org-table-toggle-coordinate-overlays :active (org-at-table-p) + :keys "C-c }" + :style toggle :selected org-table-overlay-coordinates] + "--" + ("Plot" + ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"] + ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"]))) + t)) + +(defun orgtbl-ctrl-c-ctrl-c (arg) + "If the cursor is inside a table, realign the table. +If it is a table to be sent away to a receiver, do it. +With prefix arg, also recompute table." + (interactive "P") + (let ((case-fold-search t) (pos (point)) action) + (save-excursion + (beginning-of-line 1) + (setq action (cond + ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0)) + ((looking-at "[ \t]*|") pos) + ((looking-at "[ \t]*#\\+tblfm:") 'recalc)))) + (cond + ((integerp action) + (goto-char action) + (org-table-maybe-eval-formula) + (if arg + (call-interactively 'org-table-recalculate) + (org-table-maybe-recalculate-line)) + (call-interactively 'org-table-align) + (when (orgtbl-send-table 'maybe) + (run-hooks 'orgtbl-after-send-table-hook))) + ((eq action 'recalc) + (save-excursion + (beginning-of-line 1) + (skip-chars-backward " \r\n\t") + (if (org-at-table-p) + (org-call-with-arg 'org-table-recalculate t)))) + (t (let (orgtbl-mode) + (call-interactively (key-binding "\C-c\C-c"))))))) + +(defun orgtbl-create-or-convert-from-region (_arg) + "Create table or convert region to table, if no conflicting binding. +This installs the table binding `C-c |', but only if there is no +conflicting binding to this key outside orgtbl-mode." + (interactive "P") + (let* (orgtbl-mode (cmd (key-binding "\C-c|"))) + (if cmd + (call-interactively cmd) + (call-interactively 'org-table-create-or-convert-from-region)))) + +(defun orgtbl-tab (arg) + "Justification and field motion for `orgtbl-mode'." + (interactive "P") + (if arg (org-table-edit-field t) + (org-table-justify-field-maybe) + (org-table-next-field))) + +(defun orgtbl-ret () + "Justification and field motion for `orgtbl-mode'." + (interactive) + (if (bobp) + (newline) + (org-table-justify-field-maybe) + (org-table-next-row))) + +(defun orgtbl-self-insert-command (N) + "Like `self-insert-command', use overwrite-mode for whitespace in tables. +If the cursor is in a table looking at whitespace, the whitespace is +overwritten, and the table is not marked as requiring realignment." + (interactive "p") + (if (and (org-at-table-p) + (or + (and org-table-auto-blank-field + (member last-command + '(orgtbl-hijacker-command-100 + orgtbl-hijacker-command-101 + orgtbl-hijacker-command-102 + orgtbl-hijacker-command-103 + orgtbl-hijacker-command-104 + orgtbl-hijacker-command-105 + yas/expand)) + (org-table-blank-field)) + t) + (eq N 1) + (looking-at "[^|\n]* \\( \\)|")) + (let (org-table-may-need-update) + (delete-region (match-beginning 1) (match-end 1)) + (self-insert-command N)) + (setq org-table-may-need-update t) + (let* (orgtbl-mode + a + (cmd (or (key-binding + (or (and (listp function-key-map) + (setq a (assoc last-input-event function-key-map)) + (cdr a)) + (vector last-input-event))) + 'self-insert-command))) + (call-interactively cmd) + (if (and org-self-insert-cluster-for-undo + (eq cmd 'self-insert-command)) + (if (not (eq last-command 'orgtbl-self-insert-command)) + (setq org-self-insert-command-undo-counter 1) + (if (>= org-self-insert-command-undo-counter 20) + (setq org-self-insert-command-undo-counter 1) + (and (> org-self-insert-command-undo-counter 0) + buffer-undo-list + (not (cadr buffer-undo-list)) ; remove nil entry + (setcdr buffer-undo-list (cddr buffer-undo-list))) + (setq org-self-insert-command-undo-counter + (1+ org-self-insert-command-undo-counter)))))))) + +;;;###autoload +(defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$" + "Regular expression matching exponentials as produced by calc.") + +(defun orgtbl-gather-send-defs () + "Gather a plist of :name, :transform, :params for each destination before +a radio table." + (save-excursion + (goto-char (org-table-begin)) + (let (rtn) + (beginning-of-line 0) + (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?") + (let ((name (org-no-properties (match-string 1))) + (transform (intern (match-string 2))) + (params (if (match-end 3) + (read (concat "(" (match-string 3) ")"))))) + (push (list :name name :transform transform :params params) + rtn) + (beginning-of-line 0))) + rtn))) + +(defun orgtbl-send-replace-tbl (name text) + "Find and replace table NAME with TEXT." + (save-excursion + (goto-char (point-min)) + (let* ((location-flag nil) + (name (regexp-quote name)) + (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)) + (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))) + (while (re-search-forward begin-re nil t) + (unless location-flag (setq location-flag t)) + (let ((beg (line-beginning-position 2))) + (unless (re-search-forward end-re nil t) + (user-error "Cannot find end of receiver location at %d" beg)) + (beginning-of-line) + (delete-region beg (point)) + (insert text "\n"))) + (unless location-flag + (user-error "No valid receiver location found in the buffer"))))) + +;;;###autoload +(defun org-table-to-lisp (&optional txt) + "Convert the table at point to a Lisp structure. +The structure will be a list. Each item is either the symbol `hline' +for a horizontal separator line, or a list of field values as strings. +The table is taken from the parameter TXT, or from the buffer at point." + (unless (or txt (org-at-table-p)) (user-error "No table at point")) + (let ((txt (or txt + (buffer-substring-no-properties (org-table-begin) + (org-table-end))))) + (mapcar (lambda (x) + (if (string-match org-table-hline-regexp x) 'hline + (org-split-string (org-trim x) "\\s-*|\\s-*"))) + (org-split-string txt "[ \t]*\n[ \t]*")))) + +(defun orgtbl-send-table (&optional maybe) + "Send a transformed version of table at point to the receiver position. +With argument MAYBE, fail quietly if no transformation is defined +for this table." + (interactive) + (catch 'exit + (unless (org-at-table-p) (user-error "Not at a table")) + ;; when non-interactive, we assume align has just happened. + (when (called-interactively-p 'any) (org-table-align)) + (let ((dests (orgtbl-gather-send-defs)) + (table (org-table-to-lisp + (buffer-substring-no-properties (org-table-begin) + (org-table-end)))) + (ntbl 0)) + (unless dests + (if maybe (throw 'exit nil) + (user-error "Don't know how to transform this table"))) + (dolist (dest dests) + (let ((name (plist-get dest :name)) + (transform (plist-get dest :transform)) + (params (plist-get dest :params))) + (unless (fboundp transform) + (user-error "No such transformation function %s" transform)) + (orgtbl-send-replace-tbl name (funcall transform table params))) + (cl-incf ntbl)) + (message "Table converted and installed at %d receiver location%s" + ntbl (if (> ntbl 1) "s" "")) + (and (> ntbl 0) ntbl)))) + +(defun org-remove-by-index (list indices &optional i0) + "Remove the elements in LIST with indices in INDICES. +First element has index 0, or I0 if given." + (if (not indices) + list + (if (integerp indices) (setq indices (list indices))) + (setq i0 (1- (or i0 0))) + (delq :rm (mapcar (lambda (x) + (setq i0 (1+ i0)) + (if (memq i0 indices) :rm x)) + list)))) + +(defun orgtbl-toggle-comment () + "Comment or uncomment the orgtbl at point." + (interactive) + (let* ((case-fold-search t) + (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp)) + (re2 (concat "^" orgtbl-line-start-regexp)) + (commented (save-excursion (beginning-of-line 1) + (cond ((looking-at re1) t) + ((looking-at re2) nil) + (t (user-error "Not at an org table"))))) + (re (if commented re1 re2)) + beg end) + (save-excursion + (beginning-of-line 1) + (while (looking-at re) (beginning-of-line 0)) + (beginning-of-line 2) + (setq beg (point)) + (while (looking-at re) (beginning-of-line 2)) + (setq end (point))) + (comment-region beg end (if commented '(4) nil)))) + +(defun orgtbl-insert-radio-table () + "Insert a radio table template appropriate for this major mode." + (interactive) + (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)) + (txt (nth 1 e)) + name pos) + (unless e (user-error "No radio table setup defined for %s" major-mode)) + (setq name (read-string "Table name: ")) + (while (string-match "%n" txt) + (setq txt (replace-match name t t txt))) + (or (bolp) (insert "\n")) + (setq pos (point)) + (insert txt) + (goto-char pos))) + +;;;###autoload +(defun orgtbl-to-generic (table params) + "Convert the orgtbl-mode TABLE to some other format. + +This generic routine can be used for many standard cases. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that +line. PARAMS is a property list of parameters that can +influence the conversion. + +Valid parameters are: + +:backend, :raw + + Export back-end used as a basis to transcode elements of the + table, when no specific parameter applies to it. It is also + used to translate cells contents. You can prevent this by + setting :raw property to a non-nil value. + +:splice + + When non-nil, only convert rows, not the table itself. This is + equivalent to setting to the empty string both :tstart + and :tend, which see. + +:skip + + When set to an integer N, skip the first N lines of the table. + Horizontal separation lines do count for this parameter! + +:skipcols + + List of columns that should be skipped. If the table has + a column with calculation marks, that column is automatically + discarded beforehand. + +:hline + + String to be inserted on horizontal separation lines. May be + nil to ignore these lines altogether. + +:sep + + Separator between two fields, as a string. + +Each in the following group may be either a string or a function +of no arguments returning a string: + +:tstart, :tend + + Strings to start and end the table. Ignored when :splice is t. + +:lstart, :lend + + Strings to start and end a new table line. + +:llstart, :llend + + Strings to start and end the last table line. Default, + respectively, to :lstart and :lend. + +Each in the following group may be a string or a function of one +argument (either the cells in the current row, as a list of +strings, or the current cell) returning a string: + +:lfmt + + Format string for an entire row, with enough %s to capture all + fields. When non-nil, :lstart, :lend, and :sep are ignored. + +:llfmt + + Format for the entire last line, defaults to :lfmt. + +:fmt + + A format to be used to wrap the field, should contain %s for + the original field value. For example, to wrap everything in + dollars, you could use :fmt \"$%s$\". This may also be + a property list with column numbers and format strings, or + functions, e.g., + + (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c)))) + +:hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt + + Same as above, specific for the header lines in the table. + All lines before the first hline are treated as header. If + any of these is not present, the data line value is used. + +This may be either a string or a function of two arguments: + +:efmt + + Use this format to print numbers with exponential. The format + should have %s twice for inserting mantissa and exponent, for + example \"%s\\\\times10^{%s}\". This may also be a property + list with column numbers and format strings or functions. + :fmt will still be applied after :efmt." + ;; Make sure `org-export-create-backend' is available. + (require 'ox) + (let* ((backend (plist-get params :backend)) + (custom-backend + ;; Build a custom back-end according to PARAMS. Before + ;; defining a translator, check if there is anything to do. + ;; When there isn't, let BACKEND handle the element. + (org-export-create-backend + :parent (or backend 'org) + :transcoders + `((table . ,(org-table--to-generic-table params)) + (table-row . ,(org-table--to-generic-row params)) + (table-cell . ,(org-table--to-generic-cell params)) + ;; Macros are not going to be expanded. However, no + ;; regular back-end has a transcoder for them. We + ;; provide one so they are not ignored, but displayed + ;; as-is instead. + (macro . (lambda (m c i) (org-element-macro-interpreter m nil)))))) + data info) + ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells. + ;; Initialize communication channel in INFO. + (with-temp-buffer + (let ((org-inhibit-startup t)) (org-mode)) + (let ((standard-output (current-buffer)) + (org-element-use-cache nil)) + (dolist (e table) + (cond ((eq e 'hline) (princ "|--\n")) + ((consp e) + (princ "| ") (dolist (c e) (princ c) (princ " |")) + (princ "\n"))))) + ;; Add back-end specific filters, but not user-defined ones. In + ;; particular, make sure to call parse-tree filters on the + ;; table. + (setq info + (let ((org-export-filters-alist nil)) + (org-export-install-filters + (org-combine-plists + (org-export-get-environment backend nil params) + `(:back-end ,(org-export-get-backend backend)))))) + (setq data + (org-export-filter-apply-functions + (plist-get info :filter-parse-tree) + (org-element-map (org-element-parse-buffer) 'table + #'identity nil t) + info))) + (when (and backend (symbolp backend) (not (org-export-get-backend backend))) + (user-error "Unknown :backend value")) + (when (or (not backend) (plist-get info :raw)) (require 'ox-org)) + ;; Handle :skip parameter. + (let ((skip (plist-get info :skip))) + (when skip + (unless (wholenump skip) (user-error "Wrong :skip value")) + (let ((n 0)) + (org-element-map data 'table-row + (lambda (row) + (if (>= n skip) t + (org-element-extract-element row) + (cl-incf n) + nil)) + nil t)))) + ;; Handle :skipcols parameter. + (let ((skipcols (plist-get info :skipcols))) + (when skipcols + (unless (consp skipcols) (user-error "Wrong :skipcols value")) + (org-element-map data 'table + (lambda (table) + (let ((specialp (org-export-table-has-special-column-p table))) + (dolist (row (org-element-contents table)) + (when (eq (org-element-property :type row) 'standard) + (let ((c 1)) + (dolist (cell (nthcdr (if specialp 1 0) + (org-element-contents row))) + (when (memq c skipcols) + (org-element-extract-element cell)) + (cl-incf c)))))))))) + ;; Since we are going to export using a low-level mechanism, + ;; ignore special column and special rows manually. + (let ((special? (org-export-table-has-special-column-p data)) + ignore) + (org-element-map data (if special? '(table-cell table-row) 'table-row) + (lambda (datum) + (when (if (eq (org-element-type datum) 'table-row) + (org-export-table-row-is-special-p datum nil) + (org-export-first-sibling-p datum nil)) + (push datum ignore)))) + (setq info (plist-put info :ignore-list ignore))) + ;; We use a low-level mechanism to export DATA so as to skip all + ;; usual pre-processing and post-processing, i.e., hooks, Babel + ;; code evaluation, include keywords and macro expansion. Only + ;; back-end specific filters are retained. + (let ((output (org-export-data-with-backend data custom-backend info))) + ;; Remove final newline. + (if (org-string-nw-p output) (substring-no-properties output 0 -1) "")))) + +(defun org-table--generic-apply (value name &optional with-cons &rest args) + (cond ((null value) nil) + ((functionp value) `(funcall ',value ,@args)) + ((stringp value) + (cond ((consp (car args)) `(apply #'format ,value ,@args)) + (args `(format ,value ,@args)) + (t value))) + ((and with-cons (consp value)) + `(let ((val (cadr (memq column ',value)))) + (cond ((null val) contents) + ((stringp val) (format val ,@args)) + ((functionp val) (funcall val ,@args)) + (t (user-error "Wrong %s value" ,name))))) + (t (user-error "Wrong %s value" name)))) + +(defun org-table--to-generic-table (params) + "Return custom table transcoder according to PARAMS. +PARAMS is a plist. See `orgtbl-to-generic' for more +information." + (let ((backend (plist-get params :backend)) + (splice (plist-get params :splice)) + (tstart (plist-get params :tstart)) + (tend (plist-get params :tend))) + `(lambda (table contents info) + (concat + ,(and tstart (not splice) + `(concat ,(org-table--generic-apply tstart ":tstart") "\n")) + ,(if (or (not backend) tstart tend splice) 'contents + `(org-export-with-backend ',backend table contents info)) + ,(org-table--generic-apply (and (not splice) tend) ":tend"))))) + +(defun org-table--to-generic-row (params) + "Return custom table row transcoder according to PARAMS. +PARAMS is a plist. See `orgtbl-to-generic' for more +information." + (let* ((backend (plist-get params :backend)) + (lstart (plist-get params :lstart)) + (llstart (plist-get params :llstart)) + (hlstart (plist-get params :hlstart)) + (hllstart (plist-get params :hllstart)) + (lend (plist-get params :lend)) + (llend (plist-get params :llend)) + (hlend (plist-get params :hlend)) + (hllend (plist-get params :hllend)) + (lfmt (plist-get params :lfmt)) + (llfmt (plist-get params :llfmt)) + (hlfmt (plist-get params :hlfmt)) + (hllfmt (plist-get params :hllfmt))) + `(lambda (row contents info) + (if (eq (org-element-property :type row) 'rule) + ,(cond + ((plist-member params :hline) + (org-table--generic-apply (plist-get params :hline) ":hline")) + (backend `(org-export-with-backend ',backend row nil info))) + (let ((headerp ,(and (or hlfmt hlstart hlend) + '(org-export-table-row-in-header-p row info))) + (last-header-p + ,(and (or hllfmt hllstart hllend) + '(org-export-table-row-ends-header-p row info))) + (lastp (not (org-export-get-next-element row info)))) + (when contents + ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or + ;; `:hllfmt' to CONTENTS. Otherwise, fallback on + ;; `:lstart', `:lend' and their relatives. + ,(let ((cells + '(org-element-map row 'table-cell + (lambda (cell) + ;; Export all cells, without separators. + ;; + ;; Use `org-export-data-with-backend' + ;; instead of `org-export-data' to eschew + ;; cached values, which + ;; ignore :orgtbl-ignore-sep parameter. + (org-export-data-with-backend + cell + (plist-get info :back-end) + (org-combine-plists info '(:orgtbl-ignore-sep t)))) + info))) + `(cond + ,(and hllfmt + `(last-header-p ,(org-table--generic-apply + hllfmt ":hllfmt" nil cells))) + ,(and hlfmt + `(headerp ,(org-table--generic-apply + hlfmt ":hlfmt" nil cells))) + ,(and llfmt + `(lastp ,(org-table--generic-apply + llfmt ":llfmt" nil cells))) + (t + ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells) + `(concat + (cond + ,(and + (or hllstart hllend) + `(last-header-p + (concat + ,(org-table--generic-apply hllstart ":hllstart") + contents + ,(org-table--generic-apply hllend ":hllend")))) + ,(and + (or hlstart hlend) + `(headerp + (concat + ,(org-table--generic-apply hlstart ":hlstart") + contents + ,(org-table--generic-apply hlend ":hlend")))) + ,(and + (or llstart llend) + `(lastp + (concat + ,(org-table--generic-apply llstart ":llstart") + contents + ,(org-table--generic-apply llend ":llend")))) + (t + ,(cond + ((or lstart lend) + `(concat + ,(org-table--generic-apply lstart ":lstart") + contents + ,(org-table--generic-apply lend ":lend"))) + (backend + `(org-export-with-backend + ',backend row contents info)) + (t 'contents))))))))))))))) + +(defun org-table--to-generic-cell (params) + "Return custom table cell transcoder according to PARAMS. +PARAMS is a plist. See `orgtbl-to-generic' for more +information." + (let* ((backend (plist-get params :backend)) + (efmt (plist-get params :efmt)) + (fmt (plist-get params :fmt)) + (hfmt (plist-get params :hfmt)) + (sep (plist-get params :sep)) + (hsep (plist-get params :hsep))) + `(lambda (cell contents info) + ;; Make sure that contents are exported as Org data when :raw + ;; parameter is non-nil. + ,(when (and backend (plist-get params :raw)) + `(setq contents + ;; Since we don't know what are the pseudo object + ;; types defined in backend, we cannot pass them to + ;; `org-element-interpret-data'. As a consequence, + ;; they will be treated as pseudo elements, and will + ;; have newlines appended instead of spaces. + ;; Therefore, we must make sure :post-blank value is + ;; really turned into spaces. + (replace-regexp-in-string + "\n" " " + (org-trim + (org-element-interpret-data + (org-element-contents cell)))))) + + (let ((headerp ,(and (or hfmt hsep) + '(org-export-table-row-in-header-p + (org-export-get-parent-element cell) info))) + (column + ;; Call costly `org-export-table-cell-address' only if + ;; absolutely necessary, i.e., if one + ;; of :fmt :efmt :hfmt has a "plist type" value. + ,(and (cl-some (lambda (v) (integerp (car-safe v))) + (list efmt hfmt fmt)) + '(1+ (cdr (org-export-table-cell-address cell info)))))) + (when contents + ;; Check if we can apply `:efmt' on CONTENTS. + ,(when efmt + `(when (string-match orgtbl-exp-regexp contents) + (let ((mantissa (match-string 1 contents)) + (exponent (match-string 2 contents))) + (setq contents ,(org-table--generic-apply + efmt ":efmt" t 'mantissa 'exponent))))) + ;; Check if we can apply FMT (or HFMT) on CONTENTS. + (cond + ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply + hfmt ":hfmt" t 'contents)))) + ,(and fmt `(t (setq contents ,(org-table--generic-apply + fmt ":fmt" t 'contents)))))) + ;; If a separator is provided, use it instead of BACKEND's. + ;; Separators are ignored when LFMT (or equivalent) is + ;; provided. + ,(cond + ((or hsep sep) + `(if (or ,(and (not sep) '(not headerp)) + (plist-get info :orgtbl-ignore-sep) + (not (org-export-get-next-element cell info))) + ,(if (not backend) 'contents + `(org-export-with-backend ',backend cell contents info)) + (concat contents + ,(if (and sep hsep) `(if headerp ,hsep ,sep) + (or hsep sep))))) + (backend `(org-export-with-backend ',backend cell contents info)) + (t 'contents)))))) + +;;;###autoload +(defun orgtbl-to-tsv (table params) + "Convert the orgtbl-mode table to TAB separated material." + (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params))) + +;;;###autoload +(defun orgtbl-to-csv (table params) + "Convert the orgtbl-mode table to CSV material. +This does take care of the proper quoting of fields with comma or quotes." + (orgtbl-to-generic table + (org-combine-plists '(:sep "," :fmt org-quote-csv-field) + params))) + +;;;###autoload +(defun orgtbl-to-latex (table params) + "Convert the orgtbl-mode TABLE to LaTeX. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported. It is also possible to use the following ones: + +:booktabs + + When non-nil, use formal \"booktabs\" style. + +:environment + + Specify environment to use, as a string. If you use + \"longtable\", you may also want to specify :language property, + as a string, to get proper continuation strings." + (require 'ox-latex) + (orgtbl-to-generic + table + (org-combine-plists + ;; Provide sane default values. + (list :backend 'latex + :latex-default-table-mode 'table + :latex-tables-centered nil + :latex-tables-booktabs (plist-get params :booktabs) + :latex-table-scientific-notation nil + :latex-default-table-environment + (or (plist-get params :environment) "tabular")) + params))) + +;;;###autoload +(defun orgtbl-to-html (table params) + "Convert the orgtbl-mode TABLE to HTML. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported. It is also possible to use the following one: + +:attributes + + Attributes and values, as a plist, which will be used in + <table> tag." + (require 'ox-html) + (orgtbl-to-generic + table + (org-combine-plists + ;; Provide sane default values. + (list :backend 'html + :html-table-data-tags '("<td%s>" . "</td>") + :html-table-use-header-tags-for-first-column nil + :html-table-align-individual-fields t + :html-table-row-tags '("<tr>" . "</tr>") + :html-table-attributes + (if (plist-member params :attributes) + (plist-get params :attributes) + '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups" + :frame "hsides"))) + params))) + +;;;###autoload +(defun orgtbl-to-texinfo (table params) + "Convert the orgtbl-mode TABLE to Texinfo. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported. It is also possible to use the following one: + +:columns + + Column widths, as a string. When providing column fractions, + \"@columnfractions\" command can be omitted." + (require 'ox-texinfo) + (let ((output + (orgtbl-to-generic + table + (org-combine-plists + (list :backend 'texinfo + :texinfo-tables-verbatim nil + :texinfo-table-scientific-notation nil) + params))) + (columns (let ((w (plist-get params :columns))) + (cond ((not w) nil) + ((string-match-p "{\\|@columnfractions " w) w) + (t (concat "@columnfractions " w)))))) + (if (not columns) output + (replace-regexp-in-string + "@multitable \\(.*\\)" columns output t nil 1)))) + +;;;###autoload +(defun orgtbl-to-orgtbl (table params) + "Convert the orgtbl-mode TABLE into another orgtbl-mode table. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported. + +Useful when slicing one table into many. The :hline, :sep, +:lstart, and :lend provide orgtbl framing. :tstart and :tend can +be set to provide ORGTBL directives for the generated table." + (require 'ox-org) + (orgtbl-to-generic table (org-combine-plists params (list :backend 'org)))) + +(defun orgtbl-to-table.el (table params) + "Convert the orgtbl-mode TABLE into a table.el table. +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported." + (with-temp-buffer + (insert (orgtbl-to-orgtbl table params)) + (org-table-align) + (replace-regexp-in-string + "-|" "-+" + (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size)))))) + +(defun orgtbl-to-unicode (table params) + "Convert the orgtbl-mode TABLE into a table with unicode characters. + +TABLE is a list, each entry either the symbol `hline' for +a horizontal separator line, or a list of fields for that line. +PARAMS is a property list of parameters that can influence the +conversion. All parameters from `orgtbl-to-generic' are +supported. It is also possible to use the following ones: + +:ascii-art + + When non-nil, use \"ascii-art-to-unicode\" package to translate + the table. You can download it here: + http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el. + +:narrow + + When non-nil, narrow columns width than provided width cookie, + using \"=>\" as an ellipsis, just like in an Org mode buffer." + (require 'ox-ascii) + (orgtbl-to-generic + table + (org-combine-plists + (list :backend 'ascii + :ascii-charset 'utf-8 + :ascii-table-widen-columns (not (plist-get params :narrow)) + :ascii-table-use-ascii-art (plist-get params :ascii-art)) + params))) + +;; Put the cursor in a column containing numerical values +;; of an Org table, +;; type C-c " a +;; A new column is added with a bar plot. +;; When the table is refreshed (C-u C-c *), +;; the plot is updated to reflect the new values. + +(defun orgtbl-ascii-draw (value min max &optional width characters) + "Draw an ascii bar in a table. +VALUE is the value to plot, it determines the width of the bar to draw. +MIN is the value that will be displayed as empty (zero width bar). +MAX is the value that will draw a bar filling all the WIDTH. +WIDTH is the span in characters from MIN to MAX. +CHARACTERS is a string that will compose the bar, with shades of grey +from pure white to pure black. It defaults to a 10 characters string +of regular ascii characters." + (let* ((width (ceiling (or width 12))) + (characters (or characters " .:;c!lhVHW")) + (len (1- (length characters))) + (value (float (if (numberp value) + value (string-to-number value)))) + (relative (/ (- value min) (- max min))) + (steps (round (* relative width len)))) + (cond ((< steps 0) "too small") + ((> steps (* width len)) "too large") + (t (let* ((int-division (/ steps len)) + (remainder (- steps (* int-division len)))) + (concat (make-string int-division (elt characters len)) + (string (elt characters remainder)))))))) + +;;;###autoload +(defun orgtbl-ascii-plot (&optional ask) + "Draw an ASCII bar plot in a column. + +With cursor in a column containing numerical values, this function +will draw a plot in a new column. + +ASK, if given, is a numeric prefix to override the default 12 +characters width of the plot. ASK may also be the `\\[universal-argument]' \ +prefix, +which will prompt for the width." + (interactive "P") + (let ((col (org-table-current-column)) + (min 1e999) ; 1e999 will be converted to infinity + (max -1e999) ; which is the desired result + (table (org-table-to-lisp)) + (length + (cond ((consp ask) + (read-number "Length of column " 12)) + ((numberp ask) ask) + (t 12)))) + ;; Skip any hline a the top of table. + (while (eq (car table) 'hline) (setq table (cdr table))) + ;; Skip table header if any. + (dolist (x (or (cdr (memq 'hline table)) table)) + (when (consp x) + (setq x (nth (1- col) x)) + (when (string-match + "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$" + x) + (setq x (string-to-number x)) + (when (> min x) (setq min x)) + (when (< max x) (setq max x))))) + (org-table-insert-column) + (org-table-move-column-right) + (org-table-store-formulas + (cons + (cons + (concat "$" (number-to-string (1+ col))) + (format "'(%s $%s %s %s %s)" + "orgtbl-ascii-draw" col min max length)) + (org-table-get-stored-formulas))) + (org-table-recalculate t))) + +;; Example of extension: unicode characters +;; Here are two examples of different styles. + +;; Unicode block characters are used to give a smooth effect. +;; See http://en.wikipedia.org/wiki/Block_Elements +;; Use one of those drawing functions +;; - orgtbl-ascii-draw (the default ascii) +;; - orgtbl-uc-draw-grid (unicode with a grid effect) +;; - orgtbl-uc-draw-cont (smooth unicode) + +;; This is best viewed with the "DejaVu Sans Mono" font +;; (use M-x set-frame-font). + +(defun orgtbl-uc-draw-grid (value min max &optional width) + "Draw a bar in a table using block unicode characters. +It is a variant of orgtbl-ascii-draw with Unicode block +characters, for a smooth display. Bars appear as grids (to the +extent the font allows)." + ;; http://en.wikipedia.org/wiki/Block_Elements + ;; best viewed with the "DejaVu Sans Mono" font. + (orgtbl-ascii-draw value min max width + " \u258F\u258E\u258D\u258C\u258B\u258A\u2589")) + +(defun orgtbl-uc-draw-cont (value min max &optional width) + "Draw a bar in a table using block unicode characters. +It is a variant of orgtbl-ascii-draw with Unicode block +characters, for a smooth display. Bars are solid (to the extent +the font allows)." + (orgtbl-ascii-draw value min max width + " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588")) + +(defun org-table-get-remote-range (name-or-id form) + "Get a field value or a list of values in a range from table at ID. + +NAME-OR-ID may be the name of a table in the current file as set +by a \"#+NAME:\" directive. The first table following this line +will then be used. Alternatively, it may be an ID referring to +any entry, also in a different file. In this case, the first +table in that entry will be referenced. +FORM is a field or range descriptor like \"@2$3\" or \"B3\" or +\"@I$2..@II$2\". All the references must be absolute, not relative. + +The return value is either a single string for a single field, or a +list of the fields in the rectangle." + (save-match-data + (let ((case-fold-search t) (id-loc nil) + ;; Protect a bunch of variables from being overwritten by + ;; the context of the remote table. + org-table-column-names org-table-column-name-regexp + org-table-local-parameters org-table-named-field-locations + org-table-current-line-types + org-table-current-begin-pos org-table-dlines + org-table-current-ncol + org-table-hlines org-table-last-alignment + org-table-last-column-widths org-table-last-alignment + org-table-last-column-widths + buffer loc) + (setq form (org-table-convert-refs-to-rc form)) + (org-with-wide-buffer + (goto-char (point-min)) + (if (re-search-forward + (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*" + (regexp-quote name-or-id) "[ \t]*$") + nil t) + (setq buffer (current-buffer) loc (match-beginning 0)) + (setq id-loc (org-id-find name-or-id 'marker)) + (unless (and id-loc (markerp id-loc)) + (user-error "Can't find remote table \"%s\"" name-or-id)) + (setq buffer (marker-buffer id-loc) + loc (marker-position id-loc)) + (move-marker id-loc nil)) + (with-current-buffer buffer + (org-with-wide-buffer + (goto-char loc) + (forward-char 1) + (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t) + (not (match-beginning 1))) + (user-error "Cannot find a table at NAME or ID %s" name-or-id)) + (org-table-analyze) + (setq form (org-table-formula-substitute-names + (org-table-formula-handle-first/last-rc form))) + (if (and (string-match org-table-range-regexp form) + (> (length (match-string 0 form)) 1)) + (org-table-get-range + (match-string 0 form) org-table-current-begin-pos 1) + form))))))) + +(defun org-table-remote-reference-indirection (form) + "Return formula with table remote references substituted by indirection. +For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\". +This indirection works only with the format @ROW$COLUMN. The +format \"B3\" is not supported because it can not be +distinguished from a plain table name or ID." + (let ((regexp + ;; Same as in `org-table-eval-formula'. + (concat "\\<remote([ \t]*\\(" + ;; Allow "$1", "@<", "$-1", "@<<$1" etc. + "[@$][^ \t,]+" + "\\)[ \t]*,[ \t]*\\([^\n)]+\\))"))) + (replace-regexp-in-string + regexp + (lambda (m) + (save-match-data + (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m)))) + (org-table-get-range + (if (string-match-p "\\`\\$[0-9]+\\'" eq) + (concat "@0" eq) + eq))))) + form t t 1))) + +(defmacro org-define-lookup-function (mode) + (let ((mode-str (symbol-name mode)) + (first-p (eq mode 'first)) + (all-p (eq mode 'all))) + (let ((plural-str (if all-p "s" ""))) + `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate) + ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST. +If R-LIST is nil, return matching element%s of S-LIST. +If PREDICATE is not nil, use it instead of `equal' to match VAL. +Matching is done by (PREDICATE VAL S), where S is an element of S-LIST. +This function is generated by a call to the macro `org-define-lookup-function'." + mode-str plural-str plural-str plural-str) + (let ,(let ((lvars '((p (or predicate 'equal)) + (sl s-list) + (rl (or r-list s-list)) + (ret nil)))) + (if first-p (cons '(match-p nil) lvars) lvars)) + (while ,(if first-p '(and (not match-p) sl) 'sl) + (when (funcall p val (car sl)) + ,(when first-p '(setq match-p t)) + (let ((rval (car rl))) + (setq ret ,(if all-p '(append ret (list rval)) 'rval)))) + (setq sl (cdr sl) rl (cdr rl))) + ret))))) + +(org-define-lookup-function first) +(org-define-lookup-function last) +(org-define-lookup-function all) + +(provide 'org-table) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-table.el ends here diff --git a/elpa/org-9.1.14/org-timer.el b/elpa/org-9.1.14/org-timer.el new file mode 100644 index 00000000..d840944e --- /dev/null +++ b/elpa/org-9.1.14/org-timer.el @@ -0,0 +1,509 @@ +;;; org-timer.el --- Timer code for Org mode -*- lexical-binding: t; -*- + +;; Copyright (C) 2008-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This file implements two types of timers for Org buffers: +;; +;; - A relative timer that counts up (from 0 or a specified offset) +;; - A countdown timer that counts down from a specified time +;; +;; The relative and countdown timers differ in their entry points. +;; Use `org-timer' or `org-timer-start' to start the relative timer, +;; and `org-timer-set-timer' to start the countdown timer. + +;;; Code: + +(require 'cl-lib) +(require 'org-clock) + +(declare-function org-agenda-error "org-agenda" ()) + +(defvar org-timer-start-time nil + "t=0 for the running timer.") + +(defvar org-timer-pause-time nil + "Time when the timer was paused.") + +(defvar org-timer-countdown-timer nil + "Current countdown timer. +This is a timer object if there is an active countdown timer, +`paused' if there is a paused countdown timer, and nil +otherwise.") + +(defvar org-timer-countdown-timer-title nil + "Title for notification displayed when a countdown finishes.") + +(defconst org-timer-re "\\([-+]?[0-9]+\\):\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)" + "Regular expression used to match timer stamps.") + +(defcustom org-timer-format "%s " + "The format to insert the time of the timer. +This format must contain one instance of \"%s\" which will be replaced by +the value of the timer." + :group 'org-time + :type 'string) + +(defcustom org-timer-default-timer "0" + "The default timer when a timer is set, in minutes or hh:mm:ss format. +When 0, the user is prompted for a value." + :group 'org-time + :version "26.1" + :package-version '(Org . "8.3") + :type 'string) + +(defcustom org-timer-display 'mode-line + "Define where running timer is displayed, if at all. +When a timer is running, Org can display it in the mode line +and/or frame title. Allowed values are: + +both displays in both mode line and frame title +mode-line displays only in mode line (default) +frame-title displays only in frame title +nil current timer is not displayed" + :group 'org-time + :type '(choice + (const :tag "Mode line" mode-line) + (const :tag "Frame title" frame-title) + (const :tag "Both" both) + (const :tag "None" nil))) + +(defvar org-timer-start-hook nil + "Hook run after relative timer is started.") + +(defvar org-timer-stop-hook nil + "Hook run before relative or countdown timer is stopped.") + +(defvar org-timer-pause-hook nil + "Hook run before relative or countdown timer is paused.") + +(defvar org-timer-continue-hook nil + "Hook run after relative or countdown timer is continued.") + +(defvar org-timer-set-hook nil + "Hook run after countdown timer is set.") + +(defvar org-timer-done-hook nil + "Hook run after countdown timer reaches zero.") + +;;;###autoload +(defun org-timer-start (&optional offset) + "Set the starting time for the relative timer to now. +When called with prefix argument OFFSET, prompt the user for an offset time, +with the default taken from a timer stamp at point, if any. +If OFFSET is a string or an integer, it is directly taken to be the offset +without user interaction. +When called with a double prefix arg, all timer strings in the active +region will be shifted by a specific amount. You will be prompted for +the amount, with the default to make the first timer string in +the region 0:00:00." + (interactive "P") + (cond + ((equal offset '(16)) + (call-interactively 'org-timer-change-times-in-region)) + (org-timer-countdown-timer + (user-error "Countdown timer is running. Cancel first")) + (t + (let (delta def s) + (if (not offset) + (setq org-timer-start-time (current-time)) + (cond + ((integerp offset) (setq delta offset)) + ((stringp offset) (setq delta (org-timer-hms-to-secs offset))) + (t + (setq def (if (org-in-regexp org-timer-re) + (match-string 0) + "0:00:00") + s (read-string + (format "Restart timer with offset [%s]: " def))) + (unless (string-match "\\S-" s) (setq s def)) + (setq delta (org-timer-hms-to-secs (org-timer-fix-incomplete s))))) + (setq org-timer-start-time + (seconds-to-time + ;; Pass `current-time' result to `float-time' (instead + ;; of calling without arguments) so that only + ;; `current-time' has to be overridden in tests. + (- (float-time (current-time)) delta)))) + (setq org-timer-pause-time nil) + (org-timer-set-mode-line 'on) + (message "Timer start time set to %s, current value is %s" + (format-time-string "%T" org-timer-start-time) + (org-timer-secs-to-hms (or delta 0))) + (run-hooks 'org-timer-start-hook))))) + +(defun org-timer-pause-or-continue (&optional stop) + "Pause or continue the relative or countdown timer. +With prefix arg STOP, stop it entirely." + (interactive "P") + (cond + (stop (org-timer-stop)) + ((not org-timer-start-time) (error "No timer is running")) + (org-timer-pause-time + (let ((start-secs (float-time org-timer-start-time)) + (pause-secs (float-time org-timer-pause-time))) + (if org-timer-countdown-timer + (let ((new-secs (- start-secs pause-secs))) + (setq org-timer-countdown-timer + (org-timer--run-countdown-timer + new-secs org-timer-countdown-timer-title)) + (setq org-timer-start-time + (time-add (current-time) (seconds-to-time new-secs)))) + (setq org-timer-start-time + ;; Pass `current-time' result to `float-time' (instead + ;; of calling without arguments) so that only + ;; `current-time' has to be overridden in tests. + (seconds-to-time (- (float-time (current-time)) + (- pause-secs start-secs))))) + (setq org-timer-pause-time nil) + (org-timer-set-mode-line 'on) + (run-hooks 'org-timer-continue-hook) + (message "Timer continues at %s" (org-timer-value-string)))) + (t + ;; pause timer + (when org-timer-countdown-timer + (cancel-timer org-timer-countdown-timer) + (setq org-timer-countdown-timer 'paused)) + (run-hooks 'org-timer-pause-hook) + (setq org-timer-pause-time (current-time)) + (org-timer-set-mode-line 'paused) + (message "Timer paused at %s" (org-timer-value-string))))) + +(defun org-timer-stop () + "Stop the relative or countdown timer." + (interactive) + (unless org-timer-start-time + (user-error "No timer running")) + (when (timerp org-timer-countdown-timer) + (cancel-timer org-timer-countdown-timer)) + (run-hooks 'org-timer-stop-hook) + (setq org-timer-start-time nil + org-timer-pause-time nil + org-timer-countdown-timer nil) + (org-timer-set-mode-line 'off) + (message "Timer stopped")) + +;;;###autoload +(defun org-timer (&optional restart no-insert) + "Insert a H:MM:SS string from the timer into the buffer. +The first time this command is used, the timer is started. + +When used with a `\\[universal-argument]' prefix, force restarting the timer. + +When used with a `\\[universal-argument] \\[universal-argument]' \ +prefix, change all the timer strings +in the region by a fixed amount. This can be used to re-calibrate +a timer that was not started at the correct moment. + +If NO-INSERT is non-nil, return the string instead of inserting +it in the buffer." + (interactive "P") + (if (equal restart '(16)) + (org-timer-start restart) + (when (or (equal restart '(4)) (not org-timer-start-time)) + (org-timer-start)) + (if no-insert + (org-timer-value-string) + (insert (org-timer-value-string))))) + +(defun org-timer-value-string () + "Set the timer string." + (format org-timer-format + (org-timer-secs-to-hms + (abs (floor (org-timer-seconds)))))) + +(defun org-timer-seconds () + ;; Pass `current-time' result to `float-time' (instead of calling + ;; without arguments) so that only `current-time' has to be + ;; overridden in tests. + (if org-timer-countdown-timer + (- (float-time org-timer-start-time) + (float-time (or org-timer-pause-time (current-time)))) + (- (float-time (or org-timer-pause-time (current-time))) + (float-time org-timer-start-time)))) + +;;;###autoload +(defun org-timer-change-times-in-region (beg end delta) + "Change all h:mm:ss time in region by a DELTA." + (interactive + "r\nsEnter time difference like \"-1:08:26\". Default is first time to zero: ") + (let ((re "[-+]?[0-9]+:[0-9]\\{2\\}:[0-9]\\{2\\}") p) + (unless (string-match "\\S-" delta) + (save-excursion + (goto-char beg) + (when (re-search-forward re end t) + (setq delta (match-string 0)) + (if (equal (string-to-char delta) ?-) + (setq delta (substring delta 1)) + (setq delta (concat "-" delta)))))) + (setq delta (org-timer-hms-to-secs (org-timer-fix-incomplete delta))) + (when (= delta 0) (error "No change")) + (save-excursion + (goto-char end) + (while (re-search-backward re beg t) + (setq p (point)) + (replace-match + (save-match-data + (org-timer-secs-to-hms (+ (org-timer-hms-to-secs (match-string 0)) delta))) + t t) + (goto-char p))))) + +;;;###autoload +(defun org-timer-item (&optional arg) + "Insert a description-type item with the current timer value." + (interactive "P") + (let ((itemp (org-in-item-p)) (pos (point))) + (cond + ;; In a timer list, insert with `org-list-insert-item', + ;; then fix the list. + ((and itemp (goto-char itemp) (org-at-item-timer-p)) + (let* ((struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (s (concat (org-timer (when arg '(4)) t) ":: "))) + (setq struct (org-list-insert-item pos struct prevs nil s)) + (org-list-write-struct struct (org-list-parents-alist struct)) + (looking-at org-list-full-item-re) + (goto-char (match-end 0)))) + ;; In a list of another type, don't break anything: throw an error. + (itemp (goto-char pos) (error "This is not a timer list")) + ;; Else, start a new list. + (t + (beginning-of-line) + (org-indent-line) + (insert "- ") + (org-timer (when arg '(4))) + (insert ":: "))))) + +(defun org-timer-fix-incomplete (hms) + "If hms is a H:MM:SS string with missing hour or hour and minute, fix it." + (if (string-match "\\(?:\\([0-9]+:\\)?\\([0-9]+:\\)\\)?\\([0-9]+\\)" hms) + (replace-match + (format "%d:%02d:%02d" + (if (match-end 1) (string-to-number (match-string 1 hms)) 0) + (if (match-end 2) (string-to-number (match-string 2 hms)) 0) + (string-to-number (match-string 3 hms))) + t t hms) + (error "Cannot parse HMS string \"%s\"" hms))) + +(defun org-timer-hms-to-secs (hms) + "Convert h:mm:ss string to an integer time. +If the string starts with a minus sign, the integer will be negative." + (if (not (string-match + "\\([-+]?[0-9]+\\):\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)" + hms)) + 0 + (let* ((h (string-to-number (match-string 1 hms))) + (m (string-to-number (match-string 2 hms))) + (s (string-to-number (match-string 3 hms))) + (sign (equal (substring (match-string 1 hms) 0 1) "-"))) + (setq h (abs h)) + (* (if sign -1 1) (+ s (* 60 (+ m (* 60 h)))))))) + +(defun org-timer-secs-to-hms (s) + "Convert integer S into h:mm:ss. +If the integer is negative, the string will start with \"-\"." + (let (sign m h) + (setq sign (if (< s 0) "-" "") + s (abs s) + m (/ s 60) s (- s (* 60 m)) + h (/ m 60) m (- m (* 60 h))) + (format "%s%d:%02d:%02d" sign h m s))) + +(defvar org-timer-mode-line-timer nil) +(defvar org-timer-mode-line-string nil) + +(defun org-timer-set-mode-line (value) + "Set the mode-line display for relative or countdown timer. +VALUE can be `on', `off', or `paused'." + (when (or (eq org-timer-display 'mode-line) + (eq org-timer-display 'both)) + (or global-mode-string (setq global-mode-string '(""))) + (or (memq 'org-timer-mode-line-string global-mode-string) + (setq global-mode-string + (append global-mode-string '(org-timer-mode-line-string))))) + (when (or (eq org-timer-display 'frame-title) + (eq org-timer-display 'both)) + (or (memq 'org-timer-mode-line-string frame-title-format) + (setq frame-title-format + (append frame-title-format '(org-timer-mode-line-string))))) + (cl-case value + (off + (when org-timer-mode-line-timer + (cancel-timer org-timer-mode-line-timer) + (setq org-timer-mode-line-timer nil)) + (when (or (eq org-timer-display 'mode-line) + (eq org-timer-display 'both)) + (setq global-mode-string + (delq 'org-timer-mode-line-string global-mode-string))) + (when (or (eq org-timer-display 'frame-title) + (eq org-timer-display 'both)) + (setq frame-title-format + (delq 'org-timer-mode-line-string frame-title-format))) + (force-mode-line-update)) + (paused + (when org-timer-mode-line-timer + (cancel-timer org-timer-mode-line-timer) + (setq org-timer-mode-line-timer nil))) + (on + (when (or (eq org-timer-display 'mode-line) + (eq org-timer-display 'both)) + (or global-mode-string (setq global-mode-string '(""))) + (or (memq 'org-timer-mode-line-string global-mode-string) + (setq global-mode-string + (append global-mode-string '(org-timer-mode-line-string))))) + (when (or (eq org-timer-display 'frame-title) + (eq org-timer-display 'both)) + (or (memq 'org-timer-mode-line-string frame-title-format) + (setq frame-title-format + (append frame-title-format '(org-timer-mode-line-string))))) + (org-timer-update-mode-line) + (when org-timer-mode-line-timer + (cancel-timer org-timer-mode-line-timer) + (setq org-timer-mode-line-timer nil)) + (when org-timer-display + (setq org-timer-mode-line-timer + (run-with-timer 1 1 'org-timer-update-mode-line)))))) + +(defun org-timer-update-mode-line () + "Update the timer time in the mode line." + (if org-timer-pause-time + nil + (setq org-timer-mode-line-string + (concat " <" (substring (org-timer-value-string) 0 -1) ">")) + (force-mode-line-update))) + +(defun org-timer-show-remaining-time () + "Display the remaining time before the timer ends." + (interactive) + (require 'time) + (if (not org-timer-countdown-timer) + (message "No timer set") + (let* ((rtime (decode-time + (time-subtract (timer--time org-timer-countdown-timer) + (current-time)))) + (rsecs (nth 0 rtime)) + (rmins (nth 1 rtime))) + (message "%d minute(s) %d seconds left before next time out" + rmins rsecs)))) + +;;;###autoload +(defun org-timer-set-timer (&optional opt) + "Prompt for a duration in minutes or hh:mm:ss and set a timer. + +If `org-timer-default-timer' is not \"0\", suggest this value as +the default duration for the timer. If a timer is already set, +prompt the user if she wants to replace it. + +Called with a numeric prefix argument, use this numeric value as +the duration of the timer in minutes. + +Called with a `C-u' prefix arguments, use `org-timer-default-timer' +without prompting the user for a duration. + +With two `C-u' prefix arguments, use `org-timer-default-timer' +without prompting the user for a duration and automatically +replace any running timer. + +By default, the timer duration will be set to the number of +minutes in the Effort property, if any. You can ignore this by +using three `C-u' prefix arguments." + (interactive "P") + (when (and org-timer-start-time + (not org-timer-countdown-timer)) + (user-error "Relative timer is running. Stop first")) + (let* ((default-timer + ;; `org-timer-default-timer' used to be a number, don't choke: + (if (numberp org-timer-default-timer) + (number-to-string org-timer-default-timer) + org-timer-default-timer)) + (effort-minutes (ignore-errors (floor (org-get-at-eol 'effort-minutes 1)))) + (minutes (or (and (numberp opt) (number-to-string opt)) + (and (not (equal opt '(64))) + effort-minutes + (number-to-string effort-minutes)) + (and (consp opt) default-timer) + (and (stringp opt) opt) + (read-from-minibuffer + "How much time left? (minutes or h:mm:ss) " + (and (not (string-equal default-timer "0")) default-timer))))) + (when (string-match "\\`[0-9]+\\'" minutes) + (setq minutes (concat minutes ":00"))) + (if (not (string-match "[0-9]+" minutes)) + (org-timer-show-remaining-time) + (let ((secs (org-timer-hms-to-secs (org-timer-fix-incomplete minutes)))) + (if (and org-timer-countdown-timer + (not (or (equal opt '(16)) + (y-or-n-p "Replace current timer? ")))) + (message "No timer set") + (when (timerp org-timer-countdown-timer) + (cancel-timer org-timer-countdown-timer)) + (setq org-timer-countdown-timer-title + (org-timer--get-timer-title)) + (setq org-timer-countdown-timer + (org-timer--run-countdown-timer + secs org-timer-countdown-timer-title)) + (run-hooks 'org-timer-set-hook) + (setq org-timer-start-time + (time-add (current-time) (seconds-to-time secs))) + (setq org-timer-pause-time nil) + (org-timer-set-mode-line 'on)))))) + +(defun org-timer--run-countdown-timer (secs title) + "Start countdown timer that will last SECS. +TITLE will be appended to the notification message displayed when +time is up." + (let ((msg (format "%s: time out" title))) + (run-with-timer + secs nil `(lambda () + (setq org-timer-countdown-timer nil + org-timer-start-time nil) + (org-notify ,msg ,org-clock-sound) + (org-timer-set-mode-line 'off) + (run-hooks 'org-timer-done-hook))))) + +(defun org-timer--get-timer-title () + "Construct timer title from heading or file name of Org buffer." + (cond + ((derived-mode-p 'org-agenda-mode) + (let* ((marker (or (get-text-property (point) 'org-marker) + (org-agenda-error))) + (hdmarker (or (get-text-property (point) 'org-hd-marker) + marker))) + (with-current-buffer (marker-buffer marker) + (org-with-wide-buffer + (goto-char hdmarker) + (org-show-entry) + (or (ignore-errors (org-get-heading)) + (buffer-name (buffer-base-buffer))))))) + ((derived-mode-p 'org-mode) + (or (ignore-errors (org-get-heading)) + (buffer-name (buffer-base-buffer)))) + (t (error "Not in an Org buffer")))) + +(provide 'org-timer) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; org-timer.el ends here diff --git a/elpa/org-9.1.14/org-version.el b/elpa/org-9.1.14/org-version.el new file mode 100644 index 00000000..e62ba652 --- /dev/null +++ b/elpa/org-9.1.14/org-version.el @@ -0,0 +1,27 @@ +;;; org-version.el --- autogenerated file, do not edit +;; +;;; Code: +;;;###autoload +(defun org-release () + "The release version of Org. +Inserted by installing Org mode or when a release is made." + (let ((org-release "9.1.14")) + org-release)) +;;;###autoload +(defun org-git-version () + "The Git version of Org mode. +Inserted by installing Org or when a release is made." + (let ((org-git-version "9.1.14-1-g4931fc-elpa")) + org-git-version)) +;;;###autoload +(defvar org-odt-data-dir "/usr/share/emacs/etc/org" + "The location of ODT styles.") + +(provide 'org-version) + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; coding: utf-8 +;; End: +;;; org-version.el ends here diff --git a/elpa/org-9.1.14/org-w3m.el b/elpa/org-9.1.14/org-w3m.el new file mode 100644 index 00000000..b2dfc778 --- /dev/null +++ b/elpa/org-9.1.14/org-w3m.el @@ -0,0 +1,184 @@ +;;; org-w3m.el --- Support from Copy and Paste From w3m -*- lexical-binding: t; -*- + +;; Copyright (C) 2008-2018 Free Software Foundation, Inc. + +;; Author: Andy Stewart <lazycat dot manatee at gmail dot com> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; +;; This file is part of GNU Emacs. +;; +;; 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 3 of the License, 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: + +;; This file implements copying HTML content from a w3m buffer and +;; transforming the text on the fly so that it can be pasted into an +;; Org buffer with hot links. It will also work for regions in gnus +;; buffers that have been washed with w3m. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;;; Acknowledgments: + +;; Richard Riley <rileyrgdev at googlemail dot com> +;; +;; The idea of transforming the HTML content with Org syntax is +;; proposed by Richard, I'm just coding it. +;; + +;;; Code: + +(require 'org) + +(defvar w3m-current-url) +(defvar w3m-current-title) + +(org-link-set-parameters "w3m" :store #'org-w3m-store-link) +(defun org-w3m-store-link () + "Store a link to a w3m buffer." + (when (eq major-mode 'w3m-mode) + (org-store-link-props + :type "w3m" + :link w3m-current-url + :url (url-view-url t) + :description (or w3m-current-title w3m-current-url)))) + +(defun org-w3m-copy-for-org-mode () + "Copy current buffer content or active region with Org style links. +This will encode `link-title' and `link-location' with +`org-make-link-string', and insert the transformed test into the kill ring, +so that it can be yanked into an Org buffer with links working correctly." + (interactive) + (let* ((regionp (org-region-active-p)) + (transform-start (point-min)) + (transform-end (point-max)) + return-content + link-location link-title + temp-position out-bound) + (when regionp + (setq transform-start (region-beginning)) + (setq transform-end (region-end)) + ;; Deactivate mark if current mark is activate. + (if (fboundp 'deactivate-mark) (deactivate-mark))) + (message "Transforming links...") + (save-excursion + (goto-char transform-start) + (while (and (not out-bound) ; still inside region to copy + (not (org-w3m-no-next-link-p))) ; no next link current buffer + ;; store current point before jump next anchor + (setq temp-position (point)) + ;; move to next anchor when current point is not at anchor + (or (get-text-property (point) 'w3m-href-anchor) (org-w3m-get-next-link-start)) + (if (<= (point) transform-end) ; if point is inside transform bound + (progn + ;; get content between two links. + (if (> (point) temp-position) + (setq return-content (concat return-content + (buffer-substring + temp-position (point))))) + ;; get link location at current point. + (setq link-location (get-text-property (point) 'w3m-href-anchor)) + ;; get link title at current point. + (setq link-title (buffer-substring (point) + (org-w3m-get-anchor-end))) + ;; concat Org style url to `return-content'. + (setq return-content + (concat return-content + (if (org-string-nw-p link-location) + (org-make-link-string link-location link-title) + link-title)))) + (goto-char temp-position) ; reset point before jump next anchor + (setq out-bound t))) ; for break out `while' loop + ;; add the rest until end of the region to be copied + (if (< (point) transform-end) + (setq return-content + (concat return-content + (buffer-substring (point) transform-end)))) + (org-kill-new return-content) + (message "Transforming links...done, use C-y to insert text into Org file") + (message "Copy with link transformation complete.")))) + +(defun org-w3m-get-anchor-start () + "Move cursor to the start of current anchor. Return point." + ;; get start position of anchor or current point + (goto-char (or (previous-single-property-change (point) 'w3m-anchor-sequence) + (point)))) + +(defun org-w3m-get-anchor-end () + "Move cursor to the end of current anchor. Return point." + ;; get end position of anchor or point + (goto-char (or (next-single-property-change (point) 'w3m-anchor-sequence) + (point)))) + +(defun org-w3m-get-next-link-start () + "Move cursor to the start of next link. Return point." + (catch 'reach + (while (next-single-property-change (point) 'w3m-anchor-sequence) + ;; jump to next anchor + (goto-char (next-single-property-change (point) 'w3m-anchor-sequence)) + (when (get-text-property (point) 'w3m-href-anchor) + ;; return point when current is valid link + (throw 'reach nil)))) + (point)) + +(defun org-w3m-get-prev-link-start () + "Move cursor to the start of previous link. Return point." + (catch 'reach + (while (previous-single-property-change (point) 'w3m-anchor-sequence) + ;; jump to previous anchor + (goto-char (previous-single-property-change (point) 'w3m-anchor-sequence)) + (when (get-text-property (point) 'w3m-href-anchor) + ;; return point when current is valid link + (throw 'reach nil)))) + (point)) + +(defun org-w3m-no-next-link-p () + "Whether there is no next link after the cursor. +Return t if there is no next link; otherwise, return nil." + (save-excursion + (equal (point) (org-w3m-get-next-link-start)))) + +(defun org-w3m-no-prev-link-p () + "Whether there is no previous link after the cursor. +Return t if there is no previous link; otherwise, return nil." + (save-excursion + (equal (point) (org-w3m-get-prev-link-start)))) + +;; Install keys into the w3m keymap +(defvar w3m-mode-map) +(defvar w3m-minor-mode-map) +(when (and (boundp 'w3m-mode-map) + (keymapp w3m-mode-map)) + (define-key w3m-mode-map "\C-c\C-x\M-w" 'org-w3m-copy-for-org-mode) + (define-key w3m-mode-map "\C-c\C-x\C-w" 'org-w3m-copy-for-org-mode)) +(when (and (boundp 'w3m-minor-mode-map) + (keymapp w3m-minor-mode-map)) + (define-key w3m-minor-mode-map "\C-c\C-x\M-w" 'org-w3m-copy-for-org-mode) + (define-key w3m-minor-mode-map "\C-c\C-x\C-w" 'org-w3m-copy-for-org-mode)) +(add-hook + 'w3m-mode-hook + (lambda () + (define-key w3m-mode-map "\C-c\C-x\M-w" 'org-w3m-copy-for-org-mode) + (define-key w3m-mode-map "\C-c\C-x\C-w" 'org-w3m-copy-for-org-mode))) +(add-hook + 'w3m-minor-mode-hook + (lambda () + (define-key w3m-minor-mode-map "\C-c\C-x\M-w" 'org-w3m-copy-for-org-mode) + (define-key w3m-minor-mode-map "\C-c\C-x\C-w" 'org-w3m-copy-for-org-mode))) + +(provide 'org-w3m) + +;;; org-w3m.el ends here diff --git a/elpa/org-9.1.14/org.el b/elpa/org-9.1.14/org.el new file mode 100644 index 00000000..2cc9b6a1 --- /dev/null +++ b/elpa/org-9.1.14/org.el @@ -0,0 +1,24947 @@ +;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*- + +;; Carstens outline-mode for keeping track of everything. +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. +;; +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Maintainer: Carsten Dominik <carsten at orgmode dot org> +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org +;; Version: 9.1.14 +;; +;; This file is part of GNU Emacs. +;; +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: +;; +;; Org is a mode for keeping notes, maintaining ToDo lists, and doing +;; project planning with a fast and effective plain-text system. +;; +;; Org mode develops organizational tasks around NOTES files that +;; contain information about projects as plain text. Org mode is +;; implemented on top of outline-mode, which makes it possible to keep +;; the content of large files well structured. Visibility cycling and +;; structure editing help to work with the tree. Tables are easily +;; created with a built-in table editor. Org mode supports ToDo +;; items, deadlines, time stamps, and scheduling. It dynamically +;; compiles entries into an agenda that utilizes and smoothly +;; integrates much of the Emacs calendar and diary. Plain text +;; URL-like links connect to websites, emails, Usenet messages, BBDB +;; entries, and any files related to the projects. For printing and +;; sharing of notes, an Org file can be exported as a structured ASCII +;; file, as HTML, or (todo and agenda items only) as an iCalendar +;; file. It can also serve as a publishing tool for a set of linked +;; webpages. +;; +;; Installation and Activation +;; --------------------------- +;; See the corresponding sections in the manual at +;; +;; https://orgmode.org/org.html#Installation +;; +;; Documentation +;; ------------- +;; The documentation of Org mode can be found in the TeXInfo file. The +;; distribution also contains a PDF version of it. At the homepage of +;; Org mode, you can read the same text online as HTML. There is also an +;; excellent reference card made by Philip Rooke. This card can be found +;; in the doc/ directory. +;; +;; A list of recent changes can be found at +;; https://orgmode.org/Changes.html +;; +;;; Code: + +(defvar org-inhibit-highlight-removal nil) ; dynamically scoped param +(defvar-local org-table-formula-constants-local nil + "Local version of `org-table-formula-constants'.") + +;;;; Require other packages + +(require 'cl-lib) + +(eval-when-compile (require 'gnus-sum)) + +(require 'calendar) +(require 'find-func) +(require 'format-spec) + +(or (eq this-command 'eval-buffer) + (condition-case nil + (load (concat (file-name-directory load-file-name) + "org-loaddefs.el") + nil t t t) + (error + (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.") + (sit-for 3) + (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory") + (sit-for 3)))) + +(require 'org-macs) +(require 'org-compat) + +;; `org-outline-regexp' ought to be a defconst but is let-bound in +;; some places -- e.g. see the macro `org-with-limited-levels'. +;; +;; In Org buffers, the value of `outline-regexp' is that of +;; `org-outline-regexp'. The only function still directly relying on +;; `outline-regexp' is `org-overview' so that `org-cycle' can do its +;; job when `orgstruct-mode' is active. +(defvar org-outline-regexp "\\*+ " + "Regexp to match Org headlines.") + +(defvar org-outline-regexp-bol "^\\*+ " + "Regexp to match Org headlines. +This is similar to `org-outline-regexp' but additionally makes +sure that we are at the beginning of the line.") + +(defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$" + "Matches a headline, putting stars and text into groups. +Stars are put in group 1 and the trimmed body in group 2.") + +(declare-function calendar-check-holidays "holidays" (date)) +(declare-function cdlatex-environment "ext:cdlatex" (environment item)) +(declare-function isearch-no-upper-case-p "isearch" (string regexp-flag)) +(declare-function org-add-archive-files "org-archive" (files)) +(declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom)) +(declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour)) +(declare-function org-agenda-redo "org-agenda" (&optional all)) +(declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t) +(declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang)) +(declare-function org-beamer-mode "ox-beamer" (&optional prefix) t) +(declare-function org-clock-get-last-clock-out-time "org-clock" ()) +(declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time)) +(declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove)) +(declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname)) +(declare-function org-clock-sum-current-item "org-clock" (&optional tstart)) +(declare-function org-clock-timestamps-down "org-clock" (&optional n)) +(declare-function org-clock-timestamps-up "org-clock" (&optional n)) +(declare-function org-clock-update-time-maybe "org-clock" ()) +(declare-function org-clocking-buffer "org-clock" ()) +(declare-function org-clocktable-shift "org-clock" (dir n)) +(declare-function + org-duration-from-minutes "org-duration" (minutes &optional fmt canonical)) +(declare-function org-element-at-point "org-element" ()) +(declare-function org-element-cache-refresh "org-element" (pos)) +(declare-function org-element-cache-reset "org-element" (&optional all)) +(declare-function org-element-contents "org-element" (element)) +(declare-function org-element-context "org-element" (&optional element)) +(declare-function org-element-copy "org-element" (datum)) +(declare-function org-element-interpret-data "org-element" (data)) +(declare-function org-element-lineage "org-element" (blob &optional types with-self)) +(declare-function org-element-link-parser "org-element" ()) +(declare-function org-element-nested-p "org-element" (elem-a elem-b)) +(declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only)) +(declare-function org-element-property "org-element" (property element)) +(declare-function org-element-put-property "org-element" (element property value)) +(declare-function org-element-swap-A-B "org-element" (elem-a elem-b)) +(declare-function org-element-type "org-element" (element)) +(declare-function org-element-update-syntax "org-element" ()) +(declare-function org-id-find-id-file "org-id" (id)) +(declare-function org-id-get-create "org-id" (&optional force)) +(declare-function org-inlinetask-at-task-p "org-inlinetask" ()) +(declare-function org-inlinetask-outline-regexp "org-inlinetask" ()) +(declare-function org-inlinetask-toggle-visibility "org-inlinetask" ()) +(declare-function org-plot/gnuplot "org-plot" (&optional params)) +(declare-function org-table-align "org-table" ()) +(declare-function org-table-begin "org-table" (&optional table-type)) +(declare-function org-table-beginning-of-field "org-table" (&optional n)) +(declare-function org-table-blank-field "org-table" ()) +(declare-function org-table-calc-current-TBLFM "org-table" (&optional arg)) +(declare-function org-table-copy-region "org-table" (beg end &optional cut)) +(declare-function org-table-cut-region "org-table" (beg end)) +(declare-function org-table-edit-field "org-table" (arg)) +(declare-function org-table-end "org-table" (&optional table-type)) +(declare-function org-table-end-of-field "org-table" (&optional n)) +(declare-function org-table-insert-row "org-table" (&optional arg)) +(declare-function org-table-justify-field-maybe "org-table" (&optional new)) +(declare-function org-table-maybe-eval-formula "org-table" ()) +(declare-function org-table-maybe-recalculate-line "org-table" ()) +(declare-function org-table-next-row "org-table" ()) +(declare-function org-table-paste-rectangle "org-table" ()) +(declare-function org-table-recalculate "org-table" (&optional all noalign)) +(declare-function + org-table-sort-lines "org-table" + (&optional with-case sorting-type getkey-func compare-func interactive?)) +(declare-function org-table-wrap-region "org-table" (arg)) +(declare-function org-tags-view "org-agenda" (&optional todo-only match)) +(declare-function orgtbl-ascii-plot "org-table" (&optional ask)) +(declare-function orgtbl-mode "org-table" (&optional arg)) +(declare-function org-export-get-backend "ox" (name)) +(declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist)) +(declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?)) + +(defvar ffap-url-regexp) +(defvar org-element-paragraph-separate) + +(defsubst org-uniquify (list) + "Non-destructively remove duplicate elements from LIST." + (let ((res (copy-sequence list))) (delete-dups res))) + +(defsubst org-get-at-bol (property) + "Get text property PROPERTY at the beginning of line." + (get-text-property (point-at-bol) property)) + +(defsubst org-trim (s &optional keep-lead) + "Remove whitespace at the beginning and the end of string S. +When optional argument KEEP-LEAD is non-nil, removing blank lines +at the beginning of the string does not affect leading indentation." + (replace-regexp-in-string + (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") "" + (replace-regexp-in-string "[ \t\n\r]+\\'" "" s))) + +;; load languages based on value of `org-babel-load-languages' +(defvar org-babel-load-languages) + +;;;###autoload +(defun org-babel-do-load-languages (sym value) + "Load the languages defined in `org-babel-load-languages'." + (set-default sym value) + (dolist (pair org-babel-load-languages) + (let ((active (cdr pair)) (lang (symbol-name (car pair)))) + (if active + (require (intern (concat "ob-" lang))) + (funcall 'fmakunbound + (intern (concat "org-babel-execute:" lang))) + (funcall 'fmakunbound + (intern (concat "org-babel-expand-body:" lang))))))) + +(declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang)) +;;;###autoload +(defun org-babel-load-file (file &optional compile) + "Load Emacs Lisp source code blocks in the Org FILE. +This function exports the source code using `org-babel-tangle' +and then loads the resulting file using `load-file'. With prefix +arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp +file to byte-code before it is loaded." + (interactive "fFile to load: \nP") + (let* ((age (lambda (file) + (float-time + (time-subtract (current-time) + (nth 5 (or (file-attributes (file-truename file)) + (file-attributes file))))))) + (base-name (file-name-sans-extension file)) + (exported-file (concat base-name ".el"))) + ;; tangle if the Org file is newer than the elisp file + (unless (and (file-exists-p exported-file) + (> (funcall age file) (funcall age exported-file))) + ;; Tangle-file traversal returns reversed list of tangled files + ;; and we want to evaluate the first target. + (setq exported-file + (car (last (org-babel-tangle-file file exported-file "emacs-lisp"))))) + (message "%s %s" + (if compile + (progn (byte-compile-file exported-file 'load) + "Compiled and loaded") + (progn (load-file exported-file) "Loaded")) + exported-file))) + +(defcustom org-babel-load-languages '((emacs-lisp . t)) + "Languages which can be evaluated in Org buffers. +This list can be used to load support for any of the languages +below, note that each language will depend on a different set of +system executables and/or Emacs modes. When a language is +\"loaded\", then code blocks in that language can be evaluated +with `org-babel-execute-src-block' bound by default to C-c +C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can +be set to remove code block evaluation from the C-c C-c +keybinding. By default only Emacs Lisp (which has no +requirements) is loaded." + :group 'org-babel + :set 'org-babel-do-load-languages + :version "24.1" + :type '(alist :tag "Babel Languages" + :key-type + (choice + (const :tag "Awk" awk) + (const :tag "C" C) + (const :tag "R" R) + (const :tag "Asymptote" asymptote) + (const :tag "Calc" calc) + (const :tag "Clojure" clojure) + (const :tag "CSS" css) + (const :tag "Ditaa" ditaa) + (const :tag "Dot" dot) + (const :tag "Ebnf2ps" ebnf2ps) + (const :tag "Emacs Lisp" emacs-lisp) + (const :tag "Forth" forth) + (const :tag "Fortran" fortran) + (const :tag "Gnuplot" gnuplot) + (const :tag "Haskell" haskell) + (const :tag "hledger" hledger) + (const :tag "IO" io) + (const :tag "J" J) + (const :tag "Java" java) + (const :tag "Javascript" js) + (const :tag "LaTeX" latex) + (const :tag "Ledger" ledger) + (const :tag "Lilypond" lilypond) + (const :tag "Lisp" lisp) + (const :tag "Makefile" makefile) + (const :tag "Maxima" maxima) + (const :tag "Matlab" matlab) + (const :tag "Mscgen" mscgen) + (const :tag "Ocaml" ocaml) + (const :tag "Octave" octave) + (const :tag "Org" org) + (const :tag "Perl" perl) + (const :tag "Pico Lisp" picolisp) + (const :tag "PlantUML" plantuml) + (const :tag "Python" python) + (const :tag "Ruby" ruby) + (const :tag "Sass" sass) + (const :tag "Scala" scala) + (const :tag "Scheme" scheme) + (const :tag "Screen" screen) + (const :tag "Shell Script" shell) + (const :tag "Shen" shen) + (const :tag "Sql" sql) + (const :tag "Sqlite" sqlite) + (const :tag "Stan" stan) + (const :tag "Vala" vala)) + :value-type (boolean :tag "Activate" :value t))) + +;;;; Customization variables +(defcustom org-clone-delete-id nil + "Remove ID property of clones of a subtree. +When non-nil, clones of a subtree don't inherit the ID property. +Otherwise they inherit the ID property with a new unique +identifier." + :type 'boolean + :version "24.1" + :group 'org-id) + +;;; Version +(org-check-version) + +;;;###autoload +(defun org-version (&optional here full message) + "Show the Org version. +Interactively, or when MESSAGE is non-nil, show it in echo area. +With prefix argument, or when HERE is non-nil, insert it at point. +In non-interactive uses, a reduced version string is output unless +FULL is given." + (interactive (list current-prefix-arg t (not current-prefix-arg))) + (let ((org-dir (ignore-errors (org-find-library-dir "org"))) + (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes)) + (load-suffixes (list ".el")) + (org-install-dir + (ignore-errors (org-find-library-dir "org-loaddefs")))) + (unless (and (fboundp 'org-release) (fboundp 'org-git-version)) + (org-load-noerror-mustsuffix (concat org-dir "org-version"))) + (let* ((load-suffixes save-load-suffixes) + (release (org-release)) + (git-version (org-git-version)) + (version (format "Org mode version %s (%s @ %s)" + release + git-version + (if org-install-dir + (if (string= org-dir org-install-dir) + org-install-dir + (concat "mixed installation! " + org-install-dir + " and " + org-dir)) + "org-loaddefs.el can not be found!"))) + (version1 (if full version release))) + (when here (insert version1)) + (when message (message "%s" version1)) + version1))) + +(defconst org-version (org-version)) + + +;;; Syntax Constants + +;;;; Block + +(defconst org-block-regexp + "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$" + "Regular expression for hiding blocks.") + +(defconst org-dblock-start-re + "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?" + "Matches the start line of a dynamic block, with parameters.") + +(defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)" + "Matches the end of a dynamic block.") + +;;;; Clock and Planning + +(defconst org-clock-string "CLOCK:" + "String used as prefix for timestamps clocking work hours on an item.") + +(defvar org-closed-string "CLOSED:" + "String used as the prefix for timestamps logging closing a TODO entry.") + +(defvar org-deadline-string "DEADLINE:" + "String to mark deadline entries. +\\<org-mode-map> +A deadline is this string, followed by a time stamp. It must be +a word, terminated by a colon. You can insert a schedule keyword +and a timestamp with `\\[org-deadline]'.") + +(defvar org-scheduled-string "SCHEDULED:" + "String to mark scheduled TODO entries. +\\<org-mode-map> +A schedule is this string, followed by a time stamp. It must be +a word, terminated by a colon. You can insert a schedule keyword +and a timestamp with `\\[org-schedule]'.") + +(defconst org-ds-keyword-length + (+ 2 + (apply #'max + (mapcar #'length + (list org-deadline-string org-scheduled-string + org-clock-string org-closed-string)))) + "Maximum length of the DEADLINE and SCHEDULED keywords.") + +(defconst org-planning-line-re + (concat "^[ \t]*" + (regexp-opt + (list org-closed-string org-deadline-string org-scheduled-string) + t)) + "Matches a line with planning info. +Matched keyword is in group 1.") + +(defconst org-clock-line-re + (concat "^[ \t]*" org-clock-string) + "Matches a line with clock info.") + +(defconst org-deadline-regexp (concat "\\<" org-deadline-string) + "Matches the DEADLINE keyword.") + +(defconst org-deadline-time-regexp + (concat "\\<" org-deadline-string " *<\\([^>]+\\)>") + "Matches the DEADLINE keyword together with a time stamp.") + +(defconst org-deadline-time-hour-regexp + (concat "\\<" org-deadline-string + " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>") + "Matches the DEADLINE keyword together with a time-and-hour stamp.") + +(defconst org-deadline-line-regexp + (concat "\\<\\(" org-deadline-string "\\).*") + "Matches the DEADLINE keyword and the rest of the line.") + +(defconst org-scheduled-regexp (concat "\\<" org-scheduled-string) + "Matches the SCHEDULED keyword.") + +(defconst org-scheduled-time-regexp + (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>") + "Matches the SCHEDULED keyword together with a time stamp.") + +(defconst org-scheduled-time-hour-regexp + (concat "\\<" org-scheduled-string + " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>") + "Matches the SCHEDULED keyword together with a time-and-hour stamp.") + +(defconst org-closed-time-regexp + (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]") + "Matches the CLOSED keyword together with a time stamp.") + +(defconst org-keyword-time-regexp + (concat "\\<" + (regexp-opt + (list org-scheduled-string org-deadline-string org-closed-string + org-clock-string) + t) + " *[[<]\\([^]>]+\\)[]>]") + "Matches any of the 4 keywords, together with the time stamp.") + +(defconst org-keyword-time-not-clock-regexp + (concat + "\\<" + (regexp-opt + (list org-scheduled-string org-deadline-string org-closed-string) t) + " *[[<]\\([^]>]+\\)[]>]") + "Matches any of the 3 keywords, together with the time stamp.") + +(defconst org-maybe-keyword-time-regexp + (concat "\\(\\<" + (regexp-opt + (list org-scheduled-string org-deadline-string org-closed-string + org-clock-string) + t) + "\\)?" + " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]" + "\\|" + "<%%([^\r\n>]*>\\)") + "Matches a timestamp, possibly preceded by a keyword.") + +(defconst org-all-time-keywords + (mapcar (lambda (w) (substring w 0 -1)) + (list org-scheduled-string org-deadline-string + org-clock-string org-closed-string)) + "List of time keywords.") + +;;;; Drawer + +(defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$" + "Matches first or last line of a hidden block. +Group 1 contains drawer's name or \"END\".") + +(defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$" + "Regular expression matching the first line of a property drawer.") + +(defconst org-property-end-re "^[ \t]*:END:[ \t]*$" + "Regular expression matching the last line of a property drawer.") + +(defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$" + "Regular expression matching the first line of a clock drawer.") + +(defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$" + "Regular expression matching the last line of a clock drawer.") + +(defconst org-property-drawer-re + (concat "^[ \t]*:PROPERTIES:[ \t]*\n" + "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?" + "[ \t]*:END:[ \t]*$") + "Matches an entire property drawer.") + +(defconst org-clock-drawer-re + (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\(" + org-clock-drawer-end-re "\\)\n?") + "Matches an entire clock drawer.") + +;;;; Headline + +(defconst org-heading-keyword-regexp-format + "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$" + "Printf format for a regexp matching a headline with some keyword. +This regexp will match the headline of any node which has the +exact keyword that is put into the format. The keyword isn't in +any group by default, but the stars and the body are.") + +(defconst org-heading-keyword-maybe-regexp-format + "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$" + "Printf format for a regexp matching a headline, possibly with some keyword. +This regexp can match any headline with the specified keyword, or +without a keyword. The keyword isn't in any group by default, +but the stars and the body are.") + +(defconst org-archive-tag "ARCHIVE" + "The tag that marks a subtree as archived. +An archived subtree does not open during visibility cycling, and does +not contribute to the agenda listings.") + +(eval-and-compile + (defconst org-comment-string "COMMENT" + "Entries starting with this keyword will never be exported. +\\<org-mode-map> +An entry can be toggled between COMMENT and normal with +`\\[org-toggle-comment]'.")) + + +;;;; LaTeX Environments and Fragments + +(defconst org-latex-regexps + '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t) + ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil) + ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p + ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil) + ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil) + ("\\(" "\\\\([^\000]*?\\\\)" 0 nil) + ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil) + ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil)) + "Regular expressions for matching embedded LaTeX.") + +;;;; Node Property + +(defconst org-effort-property "Effort" + "The property that is being used to keep track of effort estimates. +Effort estimates given in this property need to have the format H:MM.") + +;;;; Table + +(defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)" + "Detect an org-type or table-type table.") + +(defconst org-table-line-regexp "^[ \t]*|" + "Detect an org-type table line.") + +(defconst org-table-dataline-regexp "^[ \t]*|[^-]" + "Detect an org-type table line.") + +(defconst org-table-hline-regexp "^[ \t]*|-" + "Detect an org-type table hline.") + +(defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]" + "Detect a table-type table hline.") + +(defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]" + "Detect the first line outside a table when searching from within it. +This works for both table types.") + +(defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: " + "Detect a #+TBLFM line.") + +;;;; Timestamp + +(defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>" + "Regular expression for fast time stamp matching.") + +(defconst org-ts-regexp-inactive + "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]" + "Regular expression for fast inactive time stamp matching.") + +(defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]" + "Regular expression for fast time stamp matching.") + +(defconst org-ts-regexp0 + "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)" + "Regular expression matching time strings for analysis. +This one does not require the space after the date, so it can be used +on a string that terminates immediately after the date.") + +(defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)" + "Regular expression matching time strings for analysis.") + +(defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>") + "Regular expression matching time stamps, with groups.") + +(defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]") + "Regular expression matching time stamps (also [..]), with groups.") + +(defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp) + "Regular expression matching a time stamp range.") + +(defconst org-tr-regexp-both + (concat org-ts-regexp-both "--?-?" org-ts-regexp-both) + "Regular expression matching a time stamp range.") + +(defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?" + org-ts-regexp "\\)?") + "Regular expression matching a time stamp or time stamp range.") + +(defconst org-tsr-regexp-both + (concat org-ts-regexp-both "\\(--?-?" + org-ts-regexp-both "\\)?") + "Regular expression matching a time stamp or time stamp range. +The time stamps may be either active or inactive.") + +(defconst org-repeat-re + "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)" + "Regular expression for specifying repeated events. +After a match, group 1 contains the repeat expression.") + +(defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>") + "Formats for `format-time-string' which are used for time stamps.") + + +;;; The custom variables + +(defgroup org nil + "Outline-based notes management and organizer." + :tag "Org" + :group 'outlines + :group 'calendar) + +(defcustom org-mode-hook nil + "Mode hook for Org mode, run after the mode was turned on." + :group 'org + :type 'hook) + +(defcustom org-load-hook nil + "Hook that is run after org.el has been loaded." + :group 'org + :type 'hook) + +(defcustom org-log-buffer-setup-hook nil + "Hook that is run after an Org log buffer is created." + :group 'org + :version "24.1" + :type 'hook) + +(defvar org-modules) ; defined below +(defvar org-modules-loaded nil + "Have the modules been loaded already?") + +(defun org-load-modules-maybe (&optional force) + "Load all extensions listed in `org-modules'." + (when (or force (not org-modules-loaded)) + (dolist (ext org-modules) + (condition-case nil (require ext) + (error (message "Problems while trying to load feature `%s'" ext)))) + (setq org-modules-loaded t))) + +(defun org-set-modules (var value) + "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag." + (set var value) + (when (featurep 'org) + (org-load-modules-maybe 'force) + (org-element-cache-reset 'all))) + +(defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail) + "Modules that should always be loaded together with org.el. + +If a description starts with <C>, the file is not part of Emacs +and loading it will require that you have downloaded and properly +installed the Org mode distribution. + +You can also use this system to load external packages (i.e. neither Org +core modules, nor modules from the CONTRIB directory). Just add symbols +to the end of the list. If the package is called org-xyz.el, then you need +to add the symbol `xyz', and the package must have a call to: + + (provide \\='org-xyz) + +For export specific modules, see also `org-export-backends'." + :group 'org + :set 'org-set-modules + :version "24.4" + :package-version '(Org . "8.0") + :type + '(set :greedy t + (const :tag " bbdb: Links to BBDB entries" org-bbdb) + (const :tag " bibtex: Links to BibTeX entries" org-bibtex) + (const :tag " crypt: Encryption of subtrees" org-crypt) + (const :tag " ctags: Access to Emacs tags with links" org-ctags) + (const :tag " docview: Links to doc-view buffers" org-docview) + (const :tag " eww: Store link to url of eww" org-eww) + (const :tag " gnus: Links to GNUS folders/messages" org-gnus) + (const :tag " habit: Track your consistency with habits" org-habit) + (const :tag " id: Global IDs for identifying entries" org-id) + (const :tag " info: Links to Info nodes" org-info) + (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask) + (const :tag " irc: Links to IRC/ERC chat sessions" org-irc) + (const :tag " mhe: Links to MHE folders/messages" org-mhe) + (const :tag " mouse: Additional mouse support" org-mouse) + (const :tag " protocol: Intercept calls from emacsclient" org-protocol) + (const :tag " rmail: Links to RMAIL folders/messages" org-rmail) + (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m) + + (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file) + (const :tag "C bookmark: Org links to bookmarks" org-bookmark) + (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist) + (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose) + (const :tag "C collector: Collect properties into tables" org-collector) + (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend) + (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill) + (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol) + (const :tag "C eshell Support for links to working directories in eshell" org-eshell) + (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light) + (const :tag "C eval: Include command output as text" org-eval) + (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry) + (const :tag "C favtable: Lookup table of favorite references and links" org-favtable) + (const :tag "C git-link: Provide org links to specific file version" org-git-link) + (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query) + (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice) + (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn) + (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal) + (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link) + (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix) + (const :tag "C man: Support for links to manpages in Org mode" org-man) + (const :tag "C mew: Links to Mew folders/messages" org-mew) + (const :tag "C mtags: Support for muse-like tags" org-mtags) + (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch) + (const :tag "C panel: Simple routines for us with bad memory" org-panel) + (const :tag "C registry: A registry for Org links" org-registry) + (const :tag "C screen: Visit screen sessions through Org links" org-screen) + (const :tag "C secretary: Team management with Org" org-secretary) + (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert) + (const :tag "C toc: Table of contents for Org buffer" org-toc) + (const :tag "C track: Keep up with Org mode development" org-track) + (const :tag "C velocity Something like Notational Velocity for Org" org-velocity) + (const :tag "C vm: Links to VM folders/messages" org-vm) + (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes) + (const :tag "C wl: Links to Wanderlust folders/messages" org-wl) + (repeat :tag "External packages" :inline t (symbol :tag "Package")))) + +(defvar org-export-registered-backends) ; From ox.el. +(declare-function org-export-derived-backend-p "ox" (backend &rest backends)) +(declare-function org-export-backend-name "ox" (backend) t) +(defcustom org-export-backends '(ascii html icalendar latex odt) + "List of export back-ends that should be always available. + +If a description starts with <C>, the file is not part of Emacs +and loading it will require that you have downloaded and properly +installed the Org mode distribution. + +Unlike to `org-modules', libraries in this list will not be +loaded along with Org, but only once the export framework is +needed. + +This variable needs to be set before org.el is loaded. If you +need to make a change while Emacs is running, use the customize +interface or run the following code, where VAL stands for the new +value of the variable, after updating it: + + (progn + (setq org-export-registered-backends + (cl-remove-if-not + (lambda (backend) + (let ((name (org-export-backend-name backend))) + (or (memq name val) + (catch \\='parentp + (dolist (b val) + (and (org-export-derived-backend-p b name) + (throw \\='parentp t))))))) + org-export-registered-backends)) + (let ((new-list (mapcar #\\='org-export-backend-name + org-export-registered-backends))) + (dolist (backend val) + (cond + ((not (load (format \"ox-%s\" backend) t t)) + (message \"Problems while trying to load export back-end \\=`%s\\='\" + backend)) + ((not (memq backend new-list)) (push backend new-list)))) + (set-default \\='org-export-backends new-list))) + +Adding a back-end to this list will also pull the back-end it +depends on, if any." + :group 'org + :group 'org-export + :version "26.1" + :package-version '(Org . "9.0") + :initialize 'custom-initialize-set + :set (lambda (var val) + (if (not (featurep 'ox)) (set-default var val) + ;; Any back-end not required anymore (not present in VAL and not + ;; a parent of any back-end in the new value) is removed from the + ;; list of registered back-ends. + (setq org-export-registered-backends + (cl-remove-if-not + (lambda (backend) + (let ((name (org-export-backend-name backend))) + (or (memq name val) + (catch 'parentp + (dolist (b val) + (and (org-export-derived-backend-p b name) + (throw 'parentp t))))))) + org-export-registered-backends)) + ;; Now build NEW-LIST of both new back-ends and required + ;; parents. + (let ((new-list (mapcar #'org-export-backend-name + org-export-registered-backends))) + (dolist (backend val) + (cond + ((not (load (format "ox-%s" backend) t t)) + (message "Problems while trying to load export back-end `%s'" + backend)) + ((not (memq backend new-list)) (push backend new-list)))) + ;; Set VAR to that list with fixed dependencies. + (set-default var new-list)))) + :type '(set :greedy t + (const :tag " ascii Export buffer to ASCII format" ascii) + (const :tag " beamer Export buffer to Beamer presentation" beamer) + (const :tag " html Export buffer to HTML format" html) + (const :tag " icalendar Export buffer to iCalendar format" icalendar) + (const :tag " latex Export buffer to LaTeX format" latex) + (const :tag " man Export buffer to MAN format" man) + (const :tag " md Export buffer to Markdown format" md) + (const :tag " odt Export buffer to ODT format" odt) + (const :tag " org Export buffer to Org format" org) + (const :tag " texinfo Export buffer to Texinfo format" texinfo) + (const :tag "C confluence Export buffer to Confluence Wiki format" confluence) + (const :tag "C deck Export buffer to deck.js presentations" deck) + (const :tag "C freemind Export buffer to Freemind mindmap format" freemind) + (const :tag "C groff Export buffer to Groff format" groff) + (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter) + (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss) + (const :tag "C s5 Export buffer to s5 presentations" s5) + (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler))) + +(eval-after-load 'ox + '(dolist (backend org-export-backends) + (condition-case nil (require (intern (format "ox-%s" backend))) + (error (message "Problems while trying to load export back-end `%s'" + backend))))) + +(defcustom org-support-shift-select nil + "Non-nil means make shift-cursor commands select text when possible. +\\<org-mode-map>\ + +In Emacs 23, when `shift-select-mode' is on, shifted cursor keys +start selecting a region, or enlarge regions started in this way. +In Org mode, in special contexts, these same keys are used for +other purposes, important enough to compete with shift selection. +Org tries to balance these needs by supporting `shift-select-mode' +outside these special contexts, under control of this variable. + +The default of this variable is nil, to avoid confusing behavior. Shifted +cursor keys will then execute Org commands in the following contexts: +- on a headline, changing TODO state (left/right) and priority (up/down) +- on a time stamp, changing the time +- in a plain list item, changing the bullet type +- in a property definition line, switching between allowed values +- in the BEGIN line of a clock table (changing the time block). +Outside these contexts, the commands will throw an error. + +When this variable is t and the cursor is not in a special +context, Org mode will support shift-selection for making and +enlarging regions. To make this more effective, the bullet +cycling will no longer happen anywhere in an item line, but only +if the cursor is exactly on the bullet. + +If you set this variable to the symbol `always', then the keys +will not be special in headlines, property lines, and item lines, +to make shift selection work there as well. If this is what you +want, you can use the following alternative commands: +`\\[org-todo]' and `\\[org-priority]' \ +to change TODO state and priority, +`\\[universal-argument] \\[universal-argument] \\[org-todo]' \ +can be used to switch TODO sets, +`\\[org-ctrl-c-minus]' to cycle item bullet types, +and properties can be edited by hand or in column view. + +However, when the cursor is on a timestamp, shift-cursor commands +will still edit the time stamp - this is just too good to give up." + :group 'org + :type '(choice + (const :tag "Never" nil) + (const :tag "When outside special context" t) + (const :tag "Everywhere except timestamps" always))) + +(defcustom org-loop-over-headlines-in-active-region nil + "Shall some commands act upon headlines in the active region? + +When set to t, some commands will be performed in all headlines +within the active region. + +When set to `start-level', some commands will be performed in all +headlines within the active region, provided that these headlines +are of the same level than the first one. + +When set to a string, those commands will be performed on the +matching headlines within the active region. Such string must be +a tags/property/todo match as it is used in the agenda tags view. + +The list of commands is: `org-schedule', `org-deadline', +`org-todo', `org-archive-subtree', `org-archive-set-tag' and +`org-archive-to-archive-sibling'. The archiving commands skip +already archived entries." + :type '(choice (const :tag "Don't loop" nil) + (const :tag "All headlines in active region" t) + (const :tag "In active region, headlines at the same level than the first one" start-level) + (string :tag "Tags/Property/Todo matcher")) + :version "24.1" + :group 'org-todo + :group 'org-archive) + +(defgroup org-startup nil + "Options concerning startup of Org mode." + :tag "Org Startup" + :group 'org) + +(defcustom org-startup-folded t + "Non-nil means entering Org mode will switch to OVERVIEW. + +This can also be configured on a per-file basis by adding one of +the following lines anywhere in the buffer: + + #+STARTUP: fold (or `overview', this is equivalent) + #+STARTUP: nofold (or `showall', this is equivalent) + #+STARTUP: content + #+STARTUP: showeverything + +Set `org-agenda-inhibit-startup' to a non-nil value if you want +to ignore this option when Org opens agenda files for the first +time." + :group 'org-startup + :type '(choice + (const :tag "nofold: show all" nil) + (const :tag "fold: overview" t) + (const :tag "content: all headlines" content) + (const :tag "show everything, even drawers" showeverything))) + +(defcustom org-startup-truncated t + "Non-nil means entering Org mode will set `truncate-lines'. +This is useful since some lines containing links can be very long and +uninteresting. Also tables look terrible when wrapped. + +The variable `org-startup-truncated' allows to configure +truncation for Org mode different to the other modes that use the +variable `truncate-lines' and as a shortcut instead of putting +the variable `truncate-lines' into the `org-mode-hook'. If one +wants to configure truncation for Org mode not statically but +dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then +the variable `truncate-lines' has to be used because in such a +case it is too late to set the variable `org-startup-truncated'." + :group 'org-startup + :type 'boolean) + +(defcustom org-startup-indented nil + "Non-nil means turn on `org-indent-mode' on startup. +This can also be configured on a per-file basis by adding one of +the following lines anywhere in the buffer: + + #+STARTUP: indent + #+STARTUP: noindent" + :group 'org-structure + :type '(choice + (const :tag "Not" nil) + (const :tag "Globally (slow on startup in large files)" t))) + +(defcustom org-use-sub-superscripts t + "Non-nil means interpret \"_\" and \"^\" for display. + +If you want to control how Org exports those characters, see +`org-export-with-sub-superscripts'. `org-use-sub-superscripts' +used to be an alias for `org-export-with-sub-superscripts' in +Org <8.0, it is not anymore. + +When this option is turned on, you can use TeX-like syntax for +sub- and superscripts within the buffer. Several characters after +\"_\" or \"^\" will be considered as a single item - so grouping +with {} is normally not needed. For example, the following things +will be parsed as single sub- or superscripts: + + 10^24 or 10^tau several digits will be considered 1 item. + 10^-12 or 10^-tau a leading sign with digits or a word + x^2-y^3 will be read as x^2 - y^3, because items are + terminated by almost any nonword/nondigit char. + x_{i^2} or x^(2-i) braces or parenthesis do grouping. + +Still, ambiguity is possible. So when in doubt, use {} to enclose +the sub/superscript. If you set this variable to the symbol `{}', +the braces are *required* in order to trigger interpretations as +sub/superscript. This can be helpful in documents that need \"_\" +frequently in plain text." + :group 'org-startup + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "Always interpret" t) + (const :tag "Only with braces" {}) + (const :tag "Never interpret" nil))) + +(defcustom org-startup-with-beamer-mode nil + "Non-nil means turn on `org-beamer-mode' on startup. +This can also be configured on a per-file basis by adding one of +the following lines anywhere in the buffer: + + #+STARTUP: beamer" + :group 'org-startup + :version "24.1" + :type 'boolean) + +(defcustom org-startup-align-all-tables nil + "Non-nil means align all tables when visiting a file. +This is useful when the column width in tables is forced with <N> cookies +in table fields. Such tables will look correct only after the first re-align. +This can also be configured on a per-file basis by adding one of +the following lines anywhere in the buffer: + #+STARTUP: align + #+STARTUP: noalign" + :group 'org-startup + :type 'boolean) + +(defcustom org-startup-with-inline-images nil + "Non-nil means show inline images when loading a new Org file. +This can also be configured on a per-file basis by adding one of +the following lines anywhere in the buffer: + #+STARTUP: inlineimages + #+STARTUP: noinlineimages" + :group 'org-startup + :version "24.1" + :type 'boolean) + +(defcustom org-startup-with-latex-preview nil + "Non-nil means preview LaTeX fragments when loading a new Org file. + +This can also be configured on a per-file basis by adding one of +the following lines anywhere in the buffer: + #+STARTUP: latexpreview + #+STARTUP: nolatexpreview" + :group 'org-startup + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-insert-mode-line-in-empty-file nil + "Non-nil means insert the first line setting Org mode in empty files. +When the function `org-mode' is called interactively in an empty file, this +normally means that the file name does not automatically trigger Org mode. +To ensure that the file will always be in Org mode in the future, a +line enforcing Org mode will be inserted into the buffer, if this option +has been set." + :group 'org-startup + :type 'boolean) + +(defcustom org-replace-disputed-keys nil + "Non-nil means use alternative key bindings for some keys. +Org mode uses S-<cursor> keys for changing timestamps and priorities. +These keys are also used by other packages like shift-selection-mode' +\(built into Emacs 23), `CUA-mode' or `windmove.el'. +If you want to use Org mode together with one of these other modes, +or more generally if you would like to move some Org mode commands to +other keys, set this variable and configure the keys with the variable +`org-disputed-keys'. + +This option is only relevant at load-time of Org mode, and must be set +*before* org.el is loaded. Changing it requires a restart of Emacs to +become effective." + :group 'org-startup + :type 'boolean) + +(defcustom org-use-extra-keys nil + "Non-nil means use extra key sequence definitions for certain commands. +This happens automatically if `window-system' is nil. This +variable lets you do the same manually. You must set it before +loading Org." + :group 'org-startup + :type 'boolean) + +(defvaralias 'org-CUA-compatible 'org-replace-disputed-keys) + +(defcustom org-disputed-keys + '(([(shift up)] . [(meta p)]) + ([(shift down)] . [(meta n)]) + ([(shift left)] . [(meta -)]) + ([(shift right)] . [(meta +)]) + ([(control shift right)] . [(meta shift +)]) + ([(control shift left)] . [(meta shift -)])) + "Keys for which Org mode and other modes compete. +This is an alist, cars are the default keys, second element specifies +the alternative to use when `org-replace-disputed-keys' is t. + +Keys can be specified in any syntax supported by `define-key'. +The value of this option takes effect only at Org mode startup, +therefore you'll have to restart Emacs to apply it after changing." + :group 'org-startup + :type 'alist) + +(defun org-key (key) + "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'. +Or return the original if not disputed." + (when org-replace-disputed-keys + (let* ((nkey (key-description key)) + (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey)) + org-disputed-keys))) + (setq key (if x (cdr x) key)))) + key) + +(defun org-defkey (keymap key def) + "Define a key, possibly translated, as returned by `org-key'." + (define-key keymap (org-key key) def)) + +(defcustom org-ellipsis nil + "The ellipsis to use in the Org mode outline. + +When nil, just use the standard three dots. When a non-empty string, +use that string instead. + +The change affects only Org mode (which will then use its own display table). +Changing this requires executing `\\[org-mode]' in a buffer to become +effective." + :group 'org-startup + :type '(choice (const :tag "Default" nil) + (string :tag "String" :value "...#")) + :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v))))) + +(defvar org-display-table nil + "The display table for Org mode, in case `org-ellipsis' is non-nil.") + +(defgroup org-keywords nil + "Keywords in Org mode." + :tag "Org Keywords" + :group 'org) + +(defcustom org-closed-keep-when-no-todo nil + "Remove CLOSED: time-stamp when switching back to a non-todo state?" + :group 'org-todo + :group 'org-keywords + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defgroup org-structure nil + "Options concerning the general structure of Org files." + :tag "Org Structure" + :group 'org) + +(defgroup org-reveal-location nil + "Options about how to make context of a location visible." + :tag "Org Reveal Location" + :group 'org-structure) + +(defcustom org-show-context-detail '((agenda . local) + (bookmark-jump . lineage) + (isearch . lineage) + (default . ancestors)) + "Alist between context and visibility span when revealing a location. + +\\<org-mode-map>Some actions may move point into invisible +locations. As a consequence, Org always expose a neighborhood +around point. How much is shown depends on the initial action, +or context. Valid contexts are + + agenda when exposing an entry from the agenda + org-goto when using the command `org-goto' (`\\[org-goto]') + occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /') + tags-tree when constructing a sparse tree based on tags matches + link-search when exposing search matches associated with a link + mark-goto when exposing the jump goal of a mark + bookmark-jump when exposing a bookmark location + isearch when exiting from an incremental search + default default for all contexts not set explicitly + +Allowed visibility spans are + + minimal show current headline; if point is not on headline, + also show entry + + local show current headline, entry and next headline + + ancestors show current headline and its direct ancestors; if + point is not on headline, also show entry + + lineage show current headline, its direct ancestors and all + their children; if point is not on headline, also show + entry and first child + + tree show current headline, its direct ancestors and all + their children; if point is not on headline, also show + entry and all children + + canonical show current headline, its direct ancestors along with + their entries and children; if point is not located on + the headline, also show current entry and all children + +As special cases, a nil or t value means show all contexts in +`minimal' or `canonical' view, respectively. + +Some views can make displayed information very compact, but also +make it harder to edit the location of the match. In such +a case, use the command `org-reveal' (`\\[org-reveal]') to show +more context." + :group 'org-reveal-location + :version "26.1" + :package-version '(Org . "9.0") + :type '(choice + (const :tag "Canonical" t) + (const :tag "Minimal" nil) + (repeat :greedy t :tag "Individual contexts" + (cons + (choice :tag "Context" + (const agenda) + (const org-goto) + (const occur-tree) + (const tags-tree) + (const link-search) + (const mark-goto) + (const bookmark-jump) + (const isearch) + (const default)) + (choice :tag "Detail level" + (const minimal) + (const local) + (const ancestors) + (const lineage) + (const tree) + (const canonical)))))) + +(defcustom org-indirect-buffer-display 'other-window + "How should indirect tree buffers be displayed? + +This applies to indirect buffers created with the commands +`org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'. + +Valid values are: +current-window Display in the current window +other-window Just display in another window. +dedicated-frame Create one new frame, and re-use it each time. +new-frame Make a new frame each time. Note that in this case + previously-made indirect buffers are kept, and you need to + kill these buffers yourself." + :group 'org-structure + :group 'org-agenda-windows + :type '(choice + (const :tag "In current window" current-window) + (const :tag "In current frame, other window" other-window) + (const :tag "Each time a new frame" new-frame) + (const :tag "One dedicated frame" dedicated-frame))) + +(defcustom org-use-speed-commands nil + "Non-nil means activate single letter commands at beginning of a headline. +This may also be a function to test for appropriate locations where speed +commands should be active. + +For example, to activate speed commands when the point is on any +star at the beginning of the headline, you can do this: + + (setq org-use-speed-commands + (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))" + :group 'org-structure + :type '(choice + (const :tag "Never" nil) + (const :tag "At beginning of headline stars" t) + (function))) + +(defcustom org-speed-commands-user nil + "Alist of additional speed commands. +This list will be checked before `org-speed-commands-default' +when the variable `org-use-speed-commands' is non-nil +and when the cursor is at the beginning of a headline. +The car of each entry is a string with a single letter, which must +be assigned to `self-insert-command' in the global map. +The cdr is either a command to be called interactively, a function +to be called, or a form to be evaluated. +An entry that is just a list with a single string will be interpreted +as a descriptive headline that will be added when listing the speed +commands in the Help buffer using the `?' speed command." + :group 'org-structure + :type '(repeat :value ("k" . ignore) + (choice :value ("k" . ignore) + (list :tag "Descriptive Headline" (string :tag "Headline")) + (cons :tag "Letter and Command" + (string :tag "Command letter") + (choice + (function) + (sexp)))))) + +(defcustom org-bookmark-names-plist + '(:last-capture "org-capture-last-stored" + :last-refile "org-refile-last-stored" + :last-capture-marker "org-capture-last-stored-marker") + "Names for bookmarks automatically set by some Org commands. +This can provide strings as names for a number of bookmarks Org sets +automatically. The following keys are currently implemented: + :last-capture + :last-capture-marker + :last-refile +When a key does not show up in the property list, the corresponding bookmark +is not set." + :group 'org-structure + :type 'plist) + +(defgroup org-cycle nil + "Options concerning visibility cycling in Org mode." + :tag "Org Cycle" + :group 'org-structure) + +(defcustom org-cycle-skip-children-state-if-no-children t + "Non-nil means skip CHILDREN state in entries that don't have any." + :group 'org-cycle + :type 'boolean) + +(defcustom org-cycle-max-level nil + "Maximum level which should still be subject to visibility cycling. +Levels higher than this will, for cycling, be treated as text, not a headline. +When `org-odd-levels-only' is set, a value of N in this variable actually +means 2N-1 stars as the limiting headline. +When nil, cycle all levels. +Note that the limiting level of cycling is also influenced by +`org-inlinetask-min-level'. When `org-cycle-max-level' is not set but +`org-inlinetask-min-level' is, cycling will be limited to levels one less +than its value." + :group 'org-cycle + :type '(choice + (const :tag "No limit" nil) + (integer :tag "Maximum level"))) + +(defcustom org-hide-block-startup nil + "Non-nil means entering Org mode will fold all blocks. +This can also be set in on a per-file basis with + +#+STARTUP: hideblocks +#+STARTUP: showblocks" + :group 'org-startup + :group 'org-cycle + :type 'boolean) + +(defcustom org-cycle-global-at-bob nil + "Cycle globally if cursor is at beginning of buffer and not at a headline. + +This makes it possible to do global cycling without having to use `S-TAB' +or `\\[universal-argument] TAB'. For this special case to work, the first \ +line of the buffer +must not be a headline -- it may be empty or some other text. + +When used in this way, `org-cycle-hook' is disabled temporarily to make +sure the cursor stays at the beginning of the buffer. + +When this option is nil, don't do anything special at the beginning of +the buffer." + :group 'org-cycle + :type 'boolean) + +(defcustom org-cycle-level-after-item/entry-creation t + "Non-nil means cycle entry level or item indentation in new empty entries. + +When the cursor is at the end of an empty headline, i.e., with only stars +and maybe a TODO keyword, TAB will then switch the entry to become a child, +and then all possible ancestor states, before returning to the original state. +This makes data entry extremely fast: M-RET to create a new headline, +on TAB to make it a child, two or more tabs to make it a (grand-)uncle. + +When the cursor is at the end of an empty plain list item, one TAB will +make it a subitem, two or more tabs will back up to make this an item +higher up in the item hierarchy." + :group 'org-cycle + :type 'boolean) + +(defcustom org-cycle-emulate-tab t + "Where should `org-cycle' emulate TAB. +nil Never +white Only in completely white lines +whitestart Only at the beginning of lines, before the first non-white char +t Everywhere except in headlines +exc-hl-bol Everywhere except at the start of a headline +If TAB is used in a place where it does not emulate TAB, the current subtree +visibility is cycled." + :group 'org-cycle + :type '(choice (const :tag "Never" nil) + (const :tag "Only in completely white lines" white) + (const :tag "Before first char in a line" whitestart) + (const :tag "Everywhere except in headlines" t) + (const :tag "Everywhere except at bol in headlines" exc-hl-bol))) + +(defcustom org-cycle-separator-lines 2 + "Number of empty lines needed to keep an empty line between collapsed trees. +If you leave an empty line between the end of a subtree and the following +headline, this empty line is hidden when the subtree is folded. +Org mode will leave (exactly) one empty line visible if the number of +empty lines is equal or larger to the number given in this variable. +So the default 2 means at least 2 empty lines after the end of a subtree +are needed to produce free space between a collapsed subtree and the +following headline. + +If the number is negative, and the number of empty lines is at least -N, +all empty lines are shown. + +Special case: when 0, never leave empty lines in collapsed view." + :group 'org-cycle + :type 'integer) +(put 'org-cycle-separator-lines 'safe-local-variable 'integerp) + +(defcustom org-pre-cycle-hook nil + "Hook that is run before visibility cycling is happening. +The function(s) in this hook must accept a single argument which indicates +the new state that will be set right after running this hook. The +argument is a symbol. Before a global state change, it can have the values +`overview', `content', or `all'. Before a local state change, it can have +the values `folded', `children', or `subtree'." + :group 'org-cycle + :type 'hook) + +(defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees + org-cycle-hide-drawers + org-cycle-show-empty-lines + org-optimize-window-after-visibility-change) + "Hook that is run after `org-cycle' has changed the buffer visibility. +The function(s) in this hook must accept a single argument which indicates +the new state that was set by the most recent `org-cycle' command. The +argument is a symbol. After a global state change, it can have the values +`overview', `contents', or `all'. After a local state change, it can have +the values `folded', `children', or `subtree'." + :group 'org-cycle + :type 'hook + :version "26.1" + :package-version '(Org . "8.3")) + +(defgroup org-edit-structure nil + "Options concerning structure editing in Org mode." + :tag "Org Edit Structure" + :group 'org-structure) + +(defcustom org-odd-levels-only nil + "Non-nil means skip even levels and only use odd levels for the outline. +This has the effect that two stars are being added/taken away in +promotion/demotion commands. It also influences how levels are +handled by the exporters. +Changing it requires restart of `font-lock-mode' to become effective +for fontification also in regions already fontified. +You may also set this on a per-file basis by adding one of the following +lines to the buffer: + + #+STARTUP: odd + #+STARTUP: oddeven" + :group 'org-edit-structure + :group 'org-appearance + :type 'boolean) + +(defcustom org-adapt-indentation t + "Non-nil means adapt indentation to outline node level. + +When this variable is set, Org assumes that you write outlines by +indenting text in each node to align with the headline (after the +stars). The following issues are influenced by this variable: + +- The indentation is increased by one space in a demotion + command, and decreased by one in a promotion command. However, + in the latter case, if shifting some line in the entry body + would alter document structure (e.g., insert a new headline), + indentation is not changed at all. + +- Property drawers and planning information is inserted indented + when this variable is set. When nil, they will not be indented. + +- TAB indents a line relative to current level. The lines below + a headline will be indented when this variable is set. + +Note that this is all about true indentation, by adding and +removing space characters. See also `org-indent.el' which does +level-dependent indentation in a virtual way, i.e. at display +time in Emacs." + :group 'org-edit-structure + :type 'boolean) + +(defcustom org-special-ctrl-a/e nil + "Non-nil means `C-a' and `C-e' behave specially in headlines and items. + +When t, `C-a' will bring back the cursor to the beginning of the +headline text, i.e. after the stars and after a possible TODO +keyword. In an item, this will be the position after bullet and +check-box, if any. When the cursor is already at that position, +another `C-a' will bring it to the beginning of the line. + +`C-e' will jump to the end of the headline, ignoring the presence +of tags in the headline. A second `C-e' will then jump to the +true end of the line, after any tags. This also means that, when +this variable is non-nil, `C-e' also will never jump beyond the +end of the heading of a folded section, i.e. not after the +ellipses. + +When set to the symbol `reversed', the first `C-a' or `C-e' works +normally, going to the true line boundary first. Only a directly +following, identical keypress will bring the cursor to the +special positions. + +This may also be a cons cell where the behavior for `C-a' and +`C-e' is set separately." + :group 'org-edit-structure + :type '(choice + (const :tag "off" nil) + (const :tag "on: after stars/bullet and before tags first" t) + (const :tag "reversed: true line boundary first" reversed) + (cons :tag "Set C-a and C-e separately" + (choice :tag "Special C-a" + (const :tag "off" nil) + (const :tag "on: after stars/bullet first" t) + (const :tag "reversed: before stars/bullet first" reversed)) + (choice :tag "Special C-e" + (const :tag "off" nil) + (const :tag "on: before tags first" t) + (const :tag "reversed: after tags first" reversed))))) +(defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e) + +(defcustom org-special-ctrl-k nil + "Non-nil means `C-k' will behave specially in headlines. +When nil, `C-k' will call the default `kill-line' command. +When t, the following will happen while the cursor is in the headline: + +- When the cursor is at the beginning of a headline, kill the entire + line and possible the folded subtree below the line. +- When in the middle of the headline text, kill the headline up to the tags. +- When after the headline text, kill the tags." + :group 'org-edit-structure + :type 'boolean) + +(defcustom org-ctrl-k-protect-subtree nil + "Non-nil means, do not delete a hidden subtree with C-k. +When set to the symbol `error', simply throw an error when C-k is +used to kill (part-of) a headline that has hidden text behind it. +Any other non-nil value will result in a query to the user, if it is +OK to kill that hidden subtree. When nil, kill without remorse." + :group 'org-edit-structure + :version "24.1" + :type '(choice + (const :tag "Do not protect hidden subtrees" nil) + (const :tag "Protect hidden subtrees with a security query" t) + (const :tag "Never kill a hidden subtree with C-k" error))) + +(defcustom org-special-ctrl-o t + "Non-nil means, make `C-o' insert a row in tables." + :group 'org-edit-structure + :type 'boolean) + +(defcustom org-catch-invisible-edits nil + "Check if in invisible region before inserting or deleting a character. +Valid values are: + +nil Do not check, so just do invisible edits. +error Throw an error and do nothing. +show Make point visible, and do the requested edit. +show-and-error Make point visible, then throw an error and abort the edit. +smart Make point visible, and do insertion/deletion if it is + adjacent to visible text and the change feels predictable. + Never delete a previously invisible character or add in the + middle or right after an invisible region. Basically, this + allows insertion and backward-delete right before ellipses. + FIXME: maybe in this case we should not even show?" + :group 'org-edit-structure + :version "24.1" + :type '(choice + (const :tag "Do not check" nil) + (const :tag "Throw error when trying to edit" error) + (const :tag "Unhide, but do not do the edit" show-and-error) + (const :tag "Show invisible part and do the edit" show) + (const :tag "Be smart and do the right thing" smart))) + +(defcustom org-yank-folded-subtrees t + "Non-nil means when yanking subtrees, fold them. +If the kill is a single subtree, or a sequence of subtrees, i.e. if +it starts with a heading and all other headings in it are either children +or siblings, then fold all the subtrees. However, do this only if no +text after the yank would be swallowed into a folded tree by this action." + :group 'org-edit-structure + :type 'boolean) + +(defcustom org-yank-adjusted-subtrees nil + "Non-nil means when yanking subtrees, adjust the level. +With this setting, `org-paste-subtree' is used to insert the subtree, see +this function for details." + :group 'org-edit-structure + :type 'boolean) + +(defcustom org-M-RET-may-split-line '((default . t)) + "Non-nil means M-RET will split the line at the cursor position. +When nil, it will go to the end of the line before making a +new line. +You may also set this option in a different way for different +contexts. Valid contexts are: + +headline when creating a new headline +item when creating a new item +table in a table field +default the value to be used for all contexts not explicitly + customized" + :group 'org-structure + :group 'org-table + :type '(choice + (const :tag "Always" t) + (const :tag "Never" nil) + (repeat :greedy t :tag "Individual contexts" + (cons + (choice :tag "Context" + (const headline) + (const item) + (const table) + (const default)) + (boolean))))) + + +(defcustom org-insert-heading-respect-content nil + "Non-nil means insert new headings after the current subtree. +\\<org-mode-map> +When nil, the new heading is created directly after the current line. +The commands `\\[org-insert-heading-respect-content]' and \ +`\\[org-insert-todo-heading-respect-content]' turn this variable on +for the duration of the command." + :group 'org-structure + :type 'boolean) + +(defcustom org-blank-before-new-entry '((heading . auto) + (plain-list-item . auto)) + "Should `org-insert-heading' leave a blank line before new heading/item? +The value is an alist, with `heading' and `plain-list-item' as CAR, +and a boolean flag as CDR. The cdr may also be the symbol `auto', in +which case Org will look at the surrounding headings/items and try to +make an intelligent decision whether to insert a blank line or not." + :group 'org-edit-structure + :type '(list + (cons (const heading) + (choice (const :tag "Never" nil) + (const :tag "Always" t) + (const :tag "Auto" auto))) + (cons (const plain-list-item) + (choice (const :tag "Never" nil) + (const :tag "Always" t) + (const :tag "Auto" auto))))) + +(defcustom org-insert-heading-hook nil + "Hook being run after inserting a new heading." + :group 'org-edit-structure + :type 'hook) + +(defcustom org-enable-fixed-width-editor t + "Non-nil means lines starting with \":\" are treated as fixed-width. +This currently only means they are never auto-wrapped. +When nil, such lines will be treated like ordinary lines." + :group 'org-edit-structure + :type 'boolean) + +(defcustom org-goto-auto-isearch t + "Non-nil means typing characters in `org-goto' starts incremental search. +When nil, you can use these keybindings to navigate the buffer: + + q Quit the org-goto interface + n Go to the next visible heading + p Go to the previous visible heading + f Go one heading forward on same level + b Go one heading backward on same level + u Go one heading up" + :group 'org-edit-structure + :type 'boolean) + +(defgroup org-sparse-trees nil + "Options concerning sparse trees in Org mode." + :tag "Org Sparse Trees" + :group 'org-structure) + +(defcustom org-highlight-sparse-tree-matches t + "Non-nil means highlight all matches that define a sparse tree. +The highlights will automatically disappear the next time the buffer is +changed by an edit command." + :group 'org-sparse-trees + :type 'boolean) + +(defcustom org-remove-highlights-with-change t + "Non-nil means any change to the buffer will remove temporary highlights. +\\<org-mode-map>\ +Such highlights are created by `org-occur' and `org-clock-display'. +When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \ +to get rid of the highlights. +The highlights created by `org-toggle-latex-fragment' always need +`\\[org-toggle-latex-fragment]' to be removed." + :group 'org-sparse-trees + :group 'org-time + :type 'boolean) + +(defcustom org-occur-case-fold-search t + "Non-nil means `org-occur' should be case-insensitive. +If set to `smart' the search will be case-insensitive only if it +doesn't specify any upper case character." + :group 'org-sparse-trees + :version "26.1" + :type '(choice + (const :tag "Case-sensitive" nil) + (const :tag "Case-insensitive" t) + (const :tag "Case-insensitive for lower case searches only" smart))) + +(defcustom org-occur-hook '(org-first-headline-recenter) + "Hook that is run after `org-occur' has constructed a sparse tree. +This can be used to recenter the window to show as much of the structure +as possible." + :group 'org-sparse-trees + :type 'hook) + +(defgroup org-imenu-and-speedbar nil + "Options concerning imenu and speedbar in Org mode." + :tag "Org Imenu and Speedbar" + :group 'org-structure) + +(defcustom org-imenu-depth 2 + "The maximum level for Imenu access to Org headlines. +This also applied for speedbar access." + :group 'org-imenu-and-speedbar + :type 'integer) + +(defgroup org-table nil + "Options concerning tables in Org mode." + :tag "Org Table" + :group 'org) + +(defcustom org-self-insert-cluster-for-undo nil + "Non-nil means cluster self-insert commands for undo when possible. +If this is set, then, like in the Emacs command loop, 20 consecutive +characters will be undone together. +This is configurable, because there is some impact on typing performance." + :group 'org-table + :type 'boolean) + +(defcustom org-table-tab-recognizes-table.el t + "Non-nil means TAB will automatically notice a table.el table. +When it sees such a table, it moves point into it and - if necessary - +calls `table-recognize-table'." + :group 'org-table-editing + :type 'boolean) + +(defgroup org-link nil + "Options concerning links in Org mode." + :tag "Org Link" + :group 'org) + +(defvar-local org-link-abbrev-alist-local nil + "Buffer-local version of `org-link-abbrev-alist', which see. +The value of this is taken from the #+LINK lines.") + +(defcustom org-link-parameters + '(("doi" :follow org--open-doi-link) + ("elisp" :follow org--open-elisp-link) + ("file" :complete org-file-complete-link) + ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path)))) + ("help" :follow org--open-help-link) + ("http" :follow (lambda (path) (browse-url (concat "http:" path)))) + ("https" :follow (lambda (path) (browse-url (concat "https:" path)))) + ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path)))) + ("news" :follow (lambda (path) (browse-url (concat "news:" path)))) + ("shell" :follow org--open-shell-link)) + "An alist of properties that defines all the links in Org mode. +The key in each association is a string of the link type. +Subsequent optional elements make up a p-list of link properties. + +:follow - A function that takes the link path as an argument. + +:export - A function that takes the link path, description and +export-backend as arguments. + +:store - A function responsible for storing the link. See the +function `org-store-link-functions'. + +:complete - A function that inserts a link with completion. The +function takes one optional prefix arg. + +:face - A face for the link, or a function that returns a face. +The function takes one argument which is the link path. The +default face is `org-link'. + +:mouse-face - The mouse-face. The default is `highlight'. + +:display - `full' will not fold the link in descriptive +display. Default is `org-link'. + +:help-echo - A string or function that takes (window object position) +as arguments and returns a string. + +:keymap - A keymap that is active on the link. The default is +`org-mouse-map'. + +:htmlize-link - A function for the htmlize-link. Defaults +to (list :uri \"type:path\") + +:activate-func - A function to run at the end of font-lock +activation. The function must accept (link-start link-end path bracketp) +as arguments." + :group 'org-link + :type '(alist :tag "Link display parameters" + :value-type plist) + :version "26.1" + :package-version '(Org . "9.1")) + +(defun org-link-get-parameter (type key) + "Get TYPE link property for KEY. +TYPE is a string and KEY is a plist keyword." + (plist-get + (cdr (assoc type org-link-parameters)) + key)) + +(defun org-link-set-parameters (type &rest parameters) + "Set link TYPE properties to PARAMETERS. + PARAMETERS should be :key val pairs." + (let ((data (assoc type org-link-parameters))) + (if data (setcdr data (org-combine-plists (cdr data) parameters)) + (push (cons type parameters) org-link-parameters) + (org-make-link-regexps) + (org-element-update-syntax)))) + +(defun org-link-types () + "Return a list of known link types." + (mapcar #'car org-link-parameters)) + +(defcustom org-link-abbrev-alist nil + "Alist of link abbreviations. +The car of each element is a string, to be replaced at the start of a link. +The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated +links in Org buffers can have an optional tag after a double colon, e.g., + + [[linkkey:tag][description]] + +The `linkkey' must be a single word, starting with a letter, followed +by letters, numbers, `-' or `_'. + +If REPLACE is a string, the tag will simply be appended to create the link. +If the string contains \"%s\", the tag will be inserted there. If the string +contains \"%h\", it will cause a url-encoded version of the tag to be inserted +at that point (see the function `url-hexify-string'). If the string contains +the specifier \"%(my-function)\", then the custom function `my-function' will +be invoked: this function takes the tag as its only argument and must return +a string. + +REPLACE may also be a function that will be called with the tag as the +only argument to create the link, which should be returned as a string. + +See the manual for examples." + :group 'org-link + :type '(repeat + (cons + (string :tag "Protocol") + (choice + (string :tag "Format") + (function))))) + +(defcustom org-descriptive-links t + "Non-nil means Org will display descriptive links. +E.g. [[https://orgmode.org][Org website]] will be displayed as +\"Org Website\", hiding the link itself and just displaying its +description. When set to nil, Org will display the full links +literally. + +You can interactively set the value of this variable by calling +`org-toggle-link-display' or from the menu Org>Hyperlinks menu." + :group 'org-link + :type 'boolean) + +(defcustom org-link-file-path-type 'adaptive + "How the path name in file links should be stored. +Valid values are: + +relative Relative to the current directory, i.e. the directory of the file + into which the link is being inserted. +absolute Absolute path, if possible with ~ for home directory. +noabbrev Absolute path, no abbreviation of home directory. +adaptive Use relative path for files in the current directory and sub- + directories of it. For other files, use an absolute path." + :group 'org-link + :type '(choice + (const relative) + (const absolute) + (const noabbrev) + (const adaptive))) + +(defvaralias 'org-activate-links 'org-highlight-links) +(defcustom org-highlight-links '(bracket angle plain radio tag date footnote) + "Types of links that should be highlighted in Org files. + +This is a list of symbols, each one of them leading to the +highlighting of a certain link type. + +You can still open links that are not highlighted. + +In principle, it does not hurt to turn on highlighting for all +link types. There may be a small gain when turning off unused +link types. The types are: + +bracket The recommended [[link][description]] or [[link]] links with hiding. +angle Links in angular brackets that may contain whitespace like + <bbdb:Carsten Dominik>. +plain Plain links in normal text, no whitespace, like http://google.com. +radio Text that is matched by a radio target, see manual for details. +tag Tag settings in a headline (link to tag search). +date Time stamps (link to calendar). +footnote Footnote labels. + +If you set this variable during an Emacs session, use `org-mode-restart' +in the Org buffer so that the change takes effect." + :group 'org-link + :group 'org-appearance + :type '(set :greedy t + (const :tag "Double bracket links" bracket) + (const :tag "Angular bracket links" angle) + (const :tag "Plain text links" plain) + (const :tag "Radio target matches" radio) + (const :tag "Tags" tag) + (const :tag "Timestamps" date) + (const :tag "Footnotes" footnote))) + +(defcustom org-make-link-description-function nil + "Function to use for generating link descriptions from links. +This function must take two parameters: the first one is the +link, the second one is the description generated by +`org-insert-link'. The function should return the description to +use." + :group 'org-link + :type '(choice (const nil) (function))) + +(defgroup org-link-store nil + "Options concerning storing links in Org mode." + :tag "Org Store Link" + :group 'org-link) + +(defcustom org-url-hexify-p t + "When non-nil, hexify URL when creating a link." + :type 'boolean + :version "24.3" + :group 'org-link-store) + +(defcustom org-email-link-description-format "Email %c: %.30s" + "Format of the description part of a link to an email or usenet message. +The following %-escapes will be replaced by corresponding information: + +%F full \"From\" field +%f name, taken from \"From\" field, address if no name +%T full \"To\" field +%t first name in \"To\" field, address if no name +%c correspondent. Usually \"from NAME\", but if you sent it yourself, it + will be \"to NAME\". See also the variable `org-from-is-user-regexp'. +%s subject +%d date +%m message-id. + +You may use normal field width specification between the % and the letter. +This is for example useful to limit the length of the subject. + +Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\"" + :group 'org-link-store + :type 'string) + +(defcustom org-from-is-user-regexp + (let (r1 r2) + (when (and user-mail-address (not (string= user-mail-address ""))) + (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>"))) + (when (and user-full-name (not (string= user-full-name ""))) + (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>"))) + (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2))) + "Regexp matched against the \"From:\" header of an email or usenet message. +It should match if the message is from the user him/herself." + :group 'org-link-store + :type 'regexp) + +(defcustom org-context-in-file-links t + "Non-nil means file links from `org-store-link' contain context. +\\<org-mode-map> +A search string will be added to the file name with :: as separator +and used to find the context when the link is activated by the command +`org-open-at-point'. When this option is t, the entire active region +will be placed in the search string of the file link. If set to a +positive integer, only the first n lines of context will be stored. + +Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \ +\\[org-store-link]') +negates this setting for the duration of the command." + :group 'org-link-store + :type '(choice boolean integer)) + +(defcustom org-keep-stored-link-after-insertion nil + "Non-nil means keep link in list for entire session. +\\<org-mode-map> +The command `org-store-link' adds a link pointing to the current +location to an internal list. These links accumulate during a session. +The command `org-insert-link' can be used to insert links into any +Org file (offering completion for all stored links). + +When this option is nil, every link which has been inserted once using +`\\[org-insert-link]' will be removed from the list, to make completing the \ +unused +links more efficient." + :group 'org-link-store + :type 'boolean) + +(defgroup org-link-follow nil + "Options concerning following links in Org mode." + :tag "Org Follow Link" + :group 'org-link) + +(defcustom org-link-translation-function nil + "Function to translate links with different syntax to Org syntax. +This can be used to translate links created for example by the Planner +or emacs-wiki packages to Org syntax. +The function must accept two parameters, a TYPE containing the link +protocol name like \"rmail\" or \"gnus\" as a string, and the linked path, +which is everything after the link protocol. It should return a cons +with possibly modified values of type and path. +Org contains a function for this, so if you set this variable to +`org-translate-link-from-planner', you should be able follow many +links created by planner." + :group 'org-link-follow + :type '(choice (const nil) (function))) + +(defcustom org-follow-link-hook nil + "Hook that is run after a link has been followed." + :group 'org-link-follow + :type 'hook) + +(defcustom org-tab-follows-link nil + "Non-nil means on links TAB will follow the link. +Needs to be set before org.el is loaded. +This really should not be used, it does not make sense, and the +implementation is bad." + :group 'org-link-follow + :type 'boolean) + +(defcustom org-return-follows-link nil + "Non-nil means on links RET will follow the link. +In tables, the special behavior of RET has precedence." + :group 'org-link-follow + :type 'boolean) + +(defcustom org-mouse-1-follows-link + (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t) + "Non-nil means mouse-1 on a link will follow the link. +A longer mouse click will still set point. Needs to be set +before org.el is loaded." + :group 'org-link-follow + :version "26.1" + :package-version '(Org . "8.3") + :type '(choice + (const :tag "A double click follows the link" double) + (const :tag "Unconditionally follow the link with mouse-1" t) + (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450))) + +(defcustom org-mark-ring-length 4 + "Number of different positions to be recorded in the ring. +Changing this requires a restart of Emacs to work correctly." + :group 'org-link-follow + :type 'integer) + +(defcustom org-link-search-must-match-exact-headline 'query-to-create + "Non-nil means internal fuzzy links can only match headlines. + +When nil, the a fuzzy link may point to a target or a named +construct in the document. When set to the special value +`query-to-create', offer to create a new headline when none +matched. + +Spaces and statistics cookies are ignored during heading searches." + :group 'org-link-follow + :version "24.1" + :type '(choice + (const :tag "Use fuzzy text search" nil) + (const :tag "Match only exact headline" t) + (const :tag "Match exact headline or query to create it" + query-to-create)) + :safe #'symbolp) + +(defcustom org-link-frame-setup + '((vm . vm-visit-folder-other-frame) + (vm-imap . vm-visit-imap-folder-other-frame) + (gnus . org-gnus-no-new-news) + (file . find-file-other-window) + (wl . wl-other-frame)) + "Setup the frame configuration for following links. +When following a link with Emacs, it may often be useful to display +this link in another window or frame. This variable can be used to +set this up for the different types of links. +For VM, use any of + `vm-visit-folder' + `vm-visit-folder-other-window' + `vm-visit-folder-other-frame' +For Gnus, use any of + `gnus' + `gnus-other-frame' + `org-gnus-no-new-news' +For FILE, use any of + `find-file' + `find-file-other-window' + `find-file-other-frame' +For Wanderlust use any of + `wl' + `wl-other-frame' +For the calendar, use the variable `calendar-setup'. +For BBDB, it is currently only possible to display the matches in +another window." + :group 'org-link-follow + :type '(list + (cons (const vm) + (choice + (const vm-visit-folder) + (const vm-visit-folder-other-window) + (const vm-visit-folder-other-frame))) + (cons (const vm-imap) + (choice + (const vm-visit-imap-folder) + (const vm-visit-imap-folder-other-window) + (const vm-visit-imap-folder-other-frame))) + (cons (const gnus) + (choice + (const gnus) + (const gnus-other-frame) + (const org-gnus-no-new-news))) + (cons (const file) + (choice + (const find-file) + (const find-file-other-window) + (const find-file-other-frame))) + (cons (const wl) + (choice + (const wl) + (const wl-other-frame))))) + +(defcustom org-display-internal-link-with-indirect-buffer nil + "Non-nil means use indirect buffer to display infile links. +Activating internal links (from one location in a file to another location +in the same file) normally just jumps to the location. When the link is +activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \ +is displayed in +another window. When this option is set, the other window actually displays +an indirect buffer clone of the current buffer, to avoid any visibility +changes to the current buffer." + :group 'org-link-follow + :type 'boolean) + +(defcustom org-open-non-existing-files nil + "Non-nil means `org-open-file' will open non-existing files. +When nil, an error will be generated. +This variable applies only to external applications because they +might choke on non-existing files. If the link is to a file that +will be opened in Emacs, the variable is ignored." + :group 'org-link-follow + :type 'boolean) + +(defcustom org-open-directory-means-index-dot-org nil + "Non-nil means a link to a directory really means to index.org. +When nil, following a directory link will run dired or open a finder/explorer +window on that directory." + :group 'org-link-follow + :type 'boolean) + +(defcustom org-confirm-shell-link-function 'yes-or-no-p + "Non-nil means ask for confirmation before executing shell links. +Shell links can be dangerous: just think about a link + + [[shell:rm -rf ~/*][Google Search]] + +This link would show up in your Org document as \"Google Search\", +but really it would remove your entire home directory. +Therefore we advise against setting this variable to nil. +Just change it to `y-or-n-p' if you want to confirm with a +single keystroke rather than having to type \"yes\"." + :group 'org-link-follow + :type '(choice + (const :tag "with yes-or-no (safer)" yes-or-no-p) + (const :tag "with y-or-n (faster)" y-or-n-p) + (const :tag "no confirmation (dangerous)" nil))) +(put 'org-confirm-shell-link-function + 'safe-local-variable + (lambda (x) (member x '(yes-or-no-p y-or-n-p)))) + +(defcustom org-confirm-shell-link-not-regexp "" + "A regexp to skip confirmation for shell links." + :group 'org-link-follow + :version "24.1" + :type 'regexp) + +(defcustom org-confirm-elisp-link-function 'yes-or-no-p + "Non-nil means ask for confirmation before executing Emacs Lisp links. +Elisp links can be dangerous: just think about a link + + [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]] + +This link would show up in your Org document as \"Google Search\", +but really it would remove your entire home directory. +Therefore we advise against setting this variable to nil. +Just change it to `y-or-n-p' if you want to confirm with a +single keystroke rather than having to type \"yes\"." + :group 'org-link-follow + :type '(choice + (const :tag "with yes-or-no (safer)" yes-or-no-p) + (const :tag "with y-or-n (faster)" y-or-n-p) + (const :tag "no confirmation (dangerous)" nil))) +(put 'org-confirm-shell-link-function + 'safe-local-variable + (lambda (x) (member x '(yes-or-no-p y-or-n-p)))) + +(defcustom org-confirm-elisp-link-not-regexp "" + "A regexp to skip confirmation for Elisp links." + :group 'org-link-follow + :version "24.1" + :type 'regexp) + +(defconst org-file-apps-defaults-gnu + '((remote . emacs) + (system . mailcap) + (t . mailcap)) + "Default file applications on a UNIX or GNU/Linux system. +See `org-file-apps'.") + +(defconst org-file-apps-defaults-macosx + '((remote . emacs) + (system . "open %s") + ("ps.gz" . "gv %s") + ("eps.gz" . "gv %s") + ("dvi" . "xdvi %s") + ("fig" . "xfig %s") + (t . "open %s")) + "Default file applications on a macOS system. +The system \"open\" is known as a default, but we use X11 applications +for some files for which the OS does not have a good default. +See `org-file-apps'.") + +(defconst org-file-apps-defaults-windowsnt + (list '(remote . emacs) + (cons 'system (lambda (file _path) + (with-no-warnings (w32-shell-execute "open" file)))) + (cons t (lambda (file _path) + (with-no-warnings (w32-shell-execute "open" file))))) + "Default file applications on a Windows NT system. +The system \"open\" is used for most files. +See `org-file-apps'.") + +(defcustom org-file-apps + '((auto-mode . emacs) + ("\\.mm\\'" . default) + ("\\.x?html?\\'" . default) + ("\\.pdf\\'" . default)) + "External applications for opening `file:path' items in a document. +\\<org-mode-map>\ + +Org mode uses system defaults for different file types, but +you can use this variable to set the application for a given file +extension. The entries in this list are cons cells where the car identifies +files and the cdr the corresponding command. + +Possible values for the file identifier are: + + \"string\" A string as a file identifier can be interpreted in different + ways, depending on its contents: + + - Alphanumeric characters only: + Match links with this file extension. + Example: (\"pdf\" . \"evince %s\") + to open PDFs with evince. + + - Regular expression: Match links where the + filename matches the regexp. If you want to + use groups here, use shy groups. + + Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\") + (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\") + to open *.html and *.xhtml with firefox. + + - Regular expression which contains (non-shy) groups: + Match links where the whole link, including \"::\", and + anything after that, matches the regexp. + In a custom command string, %1, %2, etc. are replaced with + the parts of the link that were matched by the groups. + For backwards compatibility, if a command string is given + that does not use any of the group matches, this case is + handled identically to the second one (i.e. match against + file name only). + In a custom function, you can access the group matches with + (match-string n link). + + Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \ +\"evince -p %1 %s\") + to open [[file:document.pdf::5]] with evince at page 5. + + `directory' Matches a directory + `remote' Matches a remote file, accessible through tramp or efs. + Remote files most likely should be visited through Emacs + because external applications cannot handle such paths. +`auto-mode' Matches files that are matched by any entry in `auto-mode-alist', + so all files Emacs knows how to handle. Using this with + command `emacs' will open most files in Emacs. Beware that this + will also open html files inside Emacs, unless you add + (\"html\" . default) to the list as well. + `system' The system command to open files, like `open' on Windows + and macOS, and mailcap under GNU/Linux. This is the command + that will be selected if you call `org-open-at-point' with a + double prefix argument (`\\[universal-argument] \ +\\[universal-argument] \\[org-open-at-point]'). + t Default for files not matched by any of the other options. + +Possible values for the command are: + + `emacs' The file will be visited by the current Emacs process. + `default' Use the default application for this file type, which is the + association for t in the list, most likely in the system-specific + part. This can be used to overrule an unwanted setting in the + system-specific variable. + `system' Use the system command for opening files, like \"open\". + This command is specified by the entry whose car is `system'. + Most likely, the system-specific version of this variable + does define this command, but you can overrule/replace it + here. +`mailcap' Use command specified in the mailcaps. + string A command to be executed by a shell; %s will be replaced + by the path to the file. + function A Lisp function, which will be called with two arguments: + the file path and the original link string, without the + \"file:\" prefix. + +For more examples, see the system specific constants +`org-file-apps-defaults-macosx' +`org-file-apps-defaults-windowsnt' +`org-file-apps-defaults-gnu'." + :group 'org-link-follow + :type '(repeat + (cons (choice :value "" + (string :tag "Extension") + (const :tag "System command to open files" system) + (const :tag "Default for unrecognized files" t) + (const :tag "Remote file" remote) + (const :tag "Links to a directory" directory) + (const :tag "Any files that have Emacs modes" + auto-mode)) + (choice :value "" + (const :tag "Visit with Emacs" emacs) + (const :tag "Use default" default) + (const :tag "Use the system command" system) + (string :tag "Command") + (function :tag "Function"))))) + +(defcustom org-doi-server-url "http://dx.doi.org/" + "The URL of the DOI server." + :type 'string + :version "24.3" + :group 'org-link-follow) + +(defgroup org-refile nil + "Options concerning refiling entries in Org mode." + :tag "Org Refile" + :group 'org) + +(defcustom org-directory "~/org" + "Directory with Org files. +This is just a default location to look for Org files. There is no need +at all to put your files into this directory. It is used in the +following situations: + +1. When a capture template specifies a target file that is not an + absolute path. The path will then be interpreted relative to + `org-directory' +2. When the value of variable `org-agenda-files' is a single file, any + relative paths in this file will be taken as relative to + `org-directory'." + :group 'org-refile + :group 'org-capture + :type 'directory) + +(defcustom org-default-notes-file (convert-standard-filename "~/.notes") + "Default target for storing notes. +Used as a fall back file for org-capture.el, for templates that +do not specify a target file." + :group 'org-refile + :group 'org-capture + :type 'file) + +(defcustom org-goto-interface 'outline + "The default interface to be used for `org-goto'. +Allowed values are: +outline The interface shows an outline of the relevant file + and the correct heading is found by moving through + the outline or by searching with incremental search. +outline-path-completion Headlines in the current buffer are offered via + completion. This is the interface also used by + the refile command." + :group 'org-refile + :type '(choice + (const :tag "Outline" outline) + (const :tag "Outline-path-completion" outline-path-completion))) + +(defcustom org-goto-max-level 5 + "Maximum target level when running `org-goto' with refile interface." + :group 'org-refile + :type 'integer) + +(defcustom org-reverse-note-order nil + "Non-nil means store new notes at the beginning of a file or entry. +When nil, new notes will be filed to the end of a file or entry. +This can also be a list with cons cells of regular expressions that +are matched against file names, and values." + :group 'org-capture + :group 'org-refile + :type '(choice + (const :tag "Reverse always" t) + (const :tag "Reverse never" nil) + (repeat :tag "By file name regexp" + (cons regexp boolean)))) + +(defcustom org-log-refile nil + "Information to record when a task is refiled. + +Possible values are: + +nil Don't add anything +time Add a time stamp to the task +note Prompt for a note and add it with template `org-log-note-headings' + +This option can also be set with on a per-file-basis with + + #+STARTUP: nologrefile + #+STARTUP: logrefile + #+STARTUP: lognoterefile + +You can have local logging settings for a subtree by setting the LOGGING +property to one or more of these keywords. + +When bulk-refiling from the agenda, the value `note' is forbidden and +will temporarily be changed to `time'." + :group 'org-refile + :group 'org-progress + :version "24.1" + :type '(choice + (const :tag "No logging" nil) + (const :tag "Record timestamp" time) + (const :tag "Record timestamp with note." note))) + +(defcustom org-refile-targets nil + "Targets for refiling entries with `\\[org-refile]'. +This is a list of cons cells. Each cell contains: +- a specification of the files to be considered, either a list of files, + or a symbol whose function or variable value will be used to retrieve + a file name or a list of file names. If you use `org-agenda-files' for + that, all agenda files will be scanned for targets. Nil means consider + headings in the current buffer. +- A specification of how to find candidate refile targets. This may be + any of: + - a cons cell (:tag . \"TAG\") to identify refile targets by a tag. + This tag has to be present in all target headlines, inheritance will + not be considered. + - a cons cell (:todo . \"KEYWORD\") to identify refile targets by + todo keyword. + - a cons cell (:regexp . \"REGEXP\") with a regular expression matching + headlines that are refiling targets. + - a cons cell (:level . N). Any headline of level N is considered a target. + Note that, when `org-odd-levels-only' is set, level corresponds to + order in hierarchy, not to the number of stars. + - a cons cell (:maxlevel . N). Any headline with level <= N is a target. + Note that, when `org-odd-levels-only' is set, level corresponds to + order in hierarchy, not to the number of stars. + +Each element of this list generates a set of possible targets. +The union of these sets is presented (with completion) to +the user by `org-refile'. + +You can set the variable `org-refile-target-verify-function' to a function +to verify each headline found by the simple criteria above. + +When this variable is nil, all top-level headlines in the current buffer +are used, equivalent to the value `((nil . (:level . 1))'." + :group 'org-refile + :type '(repeat + (cons + (choice :value org-agenda-files + (const :tag "All agenda files" org-agenda-files) + (const :tag "Current buffer" nil) + (function) (variable) (file)) + (choice :tag "Identify target headline by" + (cons :tag "Specific tag" (const :value :tag) (string)) + (cons :tag "TODO keyword" (const :value :todo) (string)) + (cons :tag "Regular expression" (const :value :regexp) (regexp)) + (cons :tag "Level number" (const :value :level) (integer)) + (cons :tag "Max Level number" (const :value :maxlevel) (integer)))))) + +(defcustom org-refile-target-verify-function nil + "Function to verify if the headline at point should be a refile target. +The function will be called without arguments, with point at the +beginning of the headline. It should return t and leave point +where it is if the headline is a valid target for refiling. + +If the target should not be selected, the function must return nil. +In addition to this, it may move point to a place from where the search +should be continued. For example, the function may decide that the entire +subtree of the current entry should be excluded and move point to the end +of the subtree." + :group 'org-refile + :type '(choice + (const nil) + (function))) + +(defcustom org-refile-use-cache nil + "Non-nil means cache refile targets to speed up the process. +\\<org-mode-map>\ +The cache for a particular file will be updated automatically when +the buffer has been killed, or when any of the marker used for flagging +refile targets no longer points at a live buffer. +If you have added new entries to a buffer that might themselves be targets, +you need to clear the cache manually by pressing `C-0 \\[org-refile]' or, +if you find that easier, \ +`\\[universal-argument] \\[universal-argument] \\[universal-argument] \ +\\[org-refile]'." + :group 'org-refile + :version "24.1" + :type 'boolean) + +(defcustom org-refile-use-outline-path nil + "Non-nil means provide refile targets as paths. +So a level 3 headline will be available as level1/level2/level3. + +When the value is `file', also include the file name (without directory) +into the path. In this case, you can also stop the completion after +the file name, to get entries inserted as top level in the file. + +When `full-file-path', include the full file path. + +When `buffer-name', use the buffer name." + :group 'org-refile + :type '(choice + (const :tag "Not" nil) + (const :tag "Yes" t) + (const :tag "Start with file name" file) + (const :tag "Start with full file path" full-file-path) + (const :tag "Start with buffer name" buffer-name))) + +(defcustom org-outline-path-complete-in-steps t + "Non-nil means complete the outline path in hierarchical steps. +When Org uses the refile interface to select an outline path (see +`org-refile-use-outline-path'), the completion of the path can be +done in a single go, or it can be done in steps down the headline +hierarchy. Going in steps is probably the best if you do not use +a special completion package like `ido' or `icicles'. However, +when using these packages, going in one step can be very fast, +while still showing the whole path to the entry." + :group 'org-refile + :type 'boolean) + +(defcustom org-refile-allow-creating-parent-nodes nil + "Non-nil means allow the creation of new nodes as refile targets. +New nodes are then created by adding \"/new node name\" to the completion +of an existing node. When the value of this variable is `confirm', +new node creation must be confirmed by the user (recommended). +When nil, the completion must match an existing entry. + +Note that, if the new heading is not seen by the criteria +listed in `org-refile-targets', multiple instances of the same +heading would be created by trying again to file under the new +heading." + :group 'org-refile + :type '(choice + (const :tag "Never" nil) + (const :tag "Always" t) + (const :tag "Prompt for confirmation" confirm))) + +(defcustom org-refile-active-region-within-subtree nil + "Non-nil means also refile active region within a subtree. + +By default `org-refile' doesn't allow refiling regions if they +don't contain a set of subtrees, but it might be convenient to +do so sometimes: in that case, the first line of the region is +converted to a headline before refiling." + :group 'org-refile + :version "24.1" + :type 'boolean) + +(defgroup org-todo nil + "Options concerning TODO items in Org mode." + :tag "Org TODO" + :group 'org) + +(defgroup org-progress nil + "Options concerning Progress logging in Org mode." + :tag "Org Progress" + :group 'org-time) + +(defvar org-todo-interpretation-widgets + '((:tag "Sequence (cycling hits every state)" sequence) + (:tag "Type (cycling directly to DONE)" type)) + "The available interpretation symbols for customizing `org-todo-keywords'. +Interested libraries should add to this list.") + +(defcustom org-todo-keywords '((sequence "TODO" "DONE")) + "List of TODO entry keyword sequences and their interpretation. +\\<org-mode-map>This is a list of sequences. + +Each sequence starts with a symbol, either `sequence' or `type', +indicating if the keywords should be interpreted as a sequence of +action steps, or as different types of TODO items. The first +keywords are states requiring action - these states will select a headline +for inclusion into the global TODO list Org produces. If one of the +\"keywords\" is the vertical bar, \"|\", the remaining keywords +signify that no further action is necessary. If \"|\" is not found, +the last keyword is treated as the only DONE state of the sequence. + +The command `\\[org-todo]' cycles an entry through these states, and one +additional state where no keyword is present. For details about this +cycling, see the manual. + +TODO keywords and interpretation can also be set on a per-file basis with +the special #+SEQ_TODO and #+TYP_TODO lines. + +Each keyword can optionally specify a character for fast state selection +\(in combination with the variable `org-use-fast-todo-selection') +and specifiers for state change logging, using the same syntax that +is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that +the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\" +indicates to record a time stamp each time this state is selected. + +Each keyword may also specify if a timestamp or a note should be +recorded when entering or leaving the state, by adding additional +characters in the parenthesis after the keyword. This looks like this: +\"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to +record only the time of the state change. With X and Y being either +\"@\" or \"!\", \"X/Y\" means use X when entering the state, and use +Y when leaving the state if and only if the *target* state does not +define X. You may omit any of the fast-selection key or X or /Y, +so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid. + +For backward compatibility, this variable may also be just a list +of keywords. In this case the interpretation (sequence or type) will be +taken from the (otherwise obsolete) variable `org-todo-interpretation'." + :group 'org-todo + :group 'org-keywords + :type '(choice + (repeat :tag "Old syntax, just keywords" + (string :tag "Keyword")) + (repeat :tag "New syntax" + (cons + (choice + :tag "Interpretation" + ;;Quick and dirty way to see + ;;`org-todo-interpretations'. This takes the + ;;place of item arguments + :convert-widget + (lambda (widget) + (widget-put widget + :args (mapcar + (lambda (x) + (widget-convert + (cons 'const x))) + org-todo-interpretation-widgets)) + widget)) + (repeat + (string :tag "Keyword")))))) + +(defvar-local org-todo-keywords-1 nil + "All TODO and DONE keywords active in a buffer.") +(defvar org-todo-keywords-for-agenda nil) +(defvar org-done-keywords-for-agenda nil) +(defvar org-todo-keyword-alist-for-agenda nil) +(defvar org-tag-alist-for-agenda nil + "Alist of all tags from all agenda files.") +(defvar org-tag-groups-alist-for-agenda nil + "Alist of all groups tags from all current agenda files.") +(defvar-local org-tag-groups-alist nil) +(defvar org-agenda-contributing-files nil) +(defvar-local org-current-tag-alist nil + "Alist of all tag groups in current buffer. +This variable takes into consideration `org-tag-alist', +`org-tag-persistent-alist' and TAGS keywords in the buffer.") +(defvar-local org-not-done-keywords nil) +(defvar-local org-done-keywords nil) +(defvar-local org-todo-heads nil) +(defvar-local org-todo-sets nil) +(defvar-local org-todo-log-states nil) +(defvar-local org-todo-kwd-alist nil) +(defvar-local org-todo-key-alist nil) +(defvar-local org-todo-key-trigger nil) + +(defcustom org-todo-interpretation 'sequence + "Controls how TODO keywords are interpreted. +This variable is in principle obsolete and is only used for +backward compatibility, if the interpretation of todo keywords is +not given already in `org-todo-keywords'. See that variable for +more information." + :group 'org-todo + :group 'org-keywords + :type '(choice (const sequence) + (const type))) + +(defcustom org-use-fast-todo-selection t + "\\<org-mode-map>\ +Non-nil means use the fast todo selection scheme with `\\[org-todo]'. +This variable describes if and under what circumstances the cycling +mechanism for TODO keywords will be replaced by a single-key, direct +selection scheme. + +When nil, fast selection is never used. + +When the symbol `prefix', it will be used when `org-todo' is called +with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \ +in an Org buffer, and +`\\[universal-argument] t' in an agenda buffer. + +When t, fast selection is used by default. In this case, the prefix +argument forces cycling instead. + +In all cases, the special interface is only used if access keys have +actually been assigned by the user, i.e. if keywords in the configuration +are followed by a letter in parenthesis, like TODO(t)." + :group 'org-todo + :type '(choice + (const :tag "Never" nil) + (const :tag "By default" t) + (const :tag "Only with C-u C-c C-t" prefix))) + +(defcustom org-provide-todo-statistics t + "Non-nil means update todo statistics after insert and toggle. +ALL-HEADLINES means update todo statistics by including headlines +with no TODO keyword as well, counting them as not done. +A list of TODO keywords means the same, but skip keywords that are +not in this list. +When set to a list of two lists, the first list contains keywords +to consider as TODO keywords, the second list contains keywords +to consider as DONE keywords. + +When this is set, todo statistics is updated in the parent of the +current entry each time a todo state is changed." + :group 'org-todo + :type '(choice + (const :tag "Yes, only for TODO entries" t) + (const :tag "Yes, including all entries" all-headlines) + (repeat :tag "Yes, for TODOs in this list" + (string :tag "TODO keyword")) + (list :tag "Yes, for TODOs and DONEs in these lists" + (repeat (string :tag "TODO keyword")) + (repeat (string :tag "DONE keyword"))) + (other :tag "No TODO statistics" nil))) + +(defcustom org-hierarchical-todo-statistics t + "Non-nil means TODO statistics covers just direct children. +When nil, all entries in the subtree are considered. +This has only an effect if `org-provide-todo-statistics' is set. +To set this to nil for only a single subtree, use a COOKIE_DATA +property and include the word \"recursive\" into the value." + :group 'org-todo + :type 'boolean) + +(defcustom org-after-todo-state-change-hook nil + "Hook which is run after the state of a TODO item was changed. +The new state (a string with a TODO keyword, or nil) is available in the +Lisp variable `org-state'." + :group 'org-todo + :type 'hook) + +(defvar org-blocker-hook nil + "Hook for functions that are allowed to block a state change. + +Functions in this hook should not modify the buffer. +Each function gets as its single argument a property list, +see `org-trigger-hook' for more information about this list. + +If any of the functions in this hook returns nil, the state change +is blocked.") + +(defvar org-trigger-hook nil + "Hook for functions that are triggered by a state change. + +Each function gets as its single argument a property list with at +least the following elements: + + (:type type-of-change :position pos-at-entry-start + :from old-state :to new-state) + +Depending on the type, more properties may be present. + +This mechanism is currently implemented for: + +TODO state changes +------------------ +:type todo-state-change +:from previous state (keyword as a string), or nil, or a symbol + `todo' or `done', to indicate the general type of state. +:to new state, like in :from") + +(defcustom org-enforce-todo-dependencies nil + "Non-nil means undone TODO entries will block switching the parent to DONE. +Also, if a parent has an :ORDERED: property, switching an entry to DONE will +be blocked if any prior sibling is not yet done. +Finally, if the parent is blocked because of ordered siblings of its own, +the child will also be blocked." + :set (lambda (var val) + (set var val) + (if val + (add-hook 'org-blocker-hook + 'org-block-todo-from-children-or-siblings-or-parent) + (remove-hook 'org-blocker-hook + 'org-block-todo-from-children-or-siblings-or-parent))) + :group 'org-todo + :type 'boolean) + +(defcustom org-enforce-todo-checkbox-dependencies nil + "Non-nil means unchecked boxes will block switching the parent to DONE. +When this is nil, checkboxes have no influence on switching TODO states. +When non-nil, you first need to check off all check boxes before the TODO +entry can be switched to DONE. +This variable needs to be set before org.el is loaded, and you need to +restart Emacs after a change to make the change effective. The only way +to change is while Emacs is running is through the customize interface." + :set (lambda (var val) + (set var val) + (if val + (add-hook 'org-blocker-hook + 'org-block-todo-from-checkboxes) + (remove-hook 'org-blocker-hook + 'org-block-todo-from-checkboxes))) + :group 'org-todo + :type 'boolean) + +(defcustom org-treat-insert-todo-heading-as-state-change nil + "Non-nil means inserting a TODO heading is treated as state change. +So when the command `\\[org-insert-todo-heading]' is used, state change +logging will apply if appropriate. When nil, the new TODO item will +be inserted directly, and no logging will take place." + :group 'org-todo + :type 'boolean) + +(defcustom org-treat-S-cursor-todo-selection-as-state-change t + "Non-nil means switching TODO states with S-cursor counts as state change. +This is the default behavior. However, setting this to nil allows a +convenient way to select a TODO state and bypass any logging associated +with that." + :group 'org-todo + :type 'boolean) + +(defcustom org-todo-state-tags-triggers nil + "Tag changes that should be triggered by TODO state changes. +This is a list. Each entry is + + (state-change (tag . flag) .......) + +State-change can be a string with a state, and empty string to indicate the +state that has no TODO keyword, or it can be one of the symbols `todo' +or `done', meaning any not-done or done state, respectively." + :group 'org-todo + :group 'org-tags + :type '(repeat + (cons (choice :tag "When changing to" + (const :tag "Not-done state" todo) + (const :tag "Done state" done) + (string :tag "State")) + (repeat + (cons :tag "Tag action" + (string :tag "Tag") + (choice (const :tag "Add" t) (const :tag "Remove" nil))))))) + +(defcustom org-log-done nil + "Information to record when a task moves to the DONE state. + +Possible values are: + +nil Don't add anything, just change the keyword +time Add a time stamp to the task +note Prompt for a note and add it with template `org-log-note-headings' + +This option can also be set with on a per-file-basis with + + #+STARTUP: nologdone + #+STARTUP: logdone + #+STARTUP: lognotedone + +You can have local logging settings for a subtree by setting the LOGGING +property to one or more of these keywords." + :group 'org-todo + :group 'org-progress + :type '(choice + (const :tag "No logging" nil) + (const :tag "Record CLOSED timestamp" time) + (const :tag "Record CLOSED timestamp with note." note))) + +;; Normalize old uses of org-log-done. +(cond + ((eq org-log-done t) (setq org-log-done 'time)) + ((and (listp org-log-done) (memq 'done org-log-done)) + (setq org-log-done 'note))) + +(defcustom org-log-reschedule nil + "Information to record when the scheduling date of a tasks is modified. + +Possible values are: + +nil Don't add anything, just change the date +time Add a time stamp to the task +note Prompt for a note and add it with template `org-log-note-headings' + +This option can also be set with on a per-file-basis with + + #+STARTUP: nologreschedule + #+STARTUP: logreschedule + #+STARTUP: lognotereschedule" + :group 'org-todo + :group 'org-progress + :type '(choice + (const :tag "No logging" nil) + (const :tag "Record timestamp" time) + (const :tag "Record timestamp with note." note))) + +(defcustom org-log-redeadline nil + "Information to record when the deadline date of a tasks is modified. + +Possible values are: + +nil Don't add anything, just change the date +time Add a time stamp to the task +note Prompt for a note and add it with template `org-log-note-headings' + +This option can also be set with on a per-file-basis with + + #+STARTUP: nologredeadline + #+STARTUP: logredeadline + #+STARTUP: lognoteredeadline + +You can have local logging settings for a subtree by setting the LOGGING +property to one or more of these keywords." + :group 'org-todo + :group 'org-progress + :type '(choice + (const :tag "No logging" nil) + (const :tag "Record timestamp" time) + (const :tag "Record timestamp with note." note))) + +(defcustom org-log-note-clock-out nil + "Non-nil means record a note when clocking out of an item. +This can also be configured on a per-file basis by adding one of +the following lines anywhere in the buffer: + + #+STARTUP: lognoteclock-out + #+STARTUP: nolognoteclock-out" + :group 'org-todo + :group 'org-progress + :type 'boolean) + +(defcustom org-log-done-with-time t + "Non-nil means the CLOSED time stamp will contain date and time. +When nil, only the date will be recorded." + :group 'org-progress + :type 'boolean) + +(defcustom org-log-note-headings + '((done . "CLOSING NOTE %t") + (state . "State %-12s from %-12S %t") + (note . "Note taken on %t") + (reschedule . "Rescheduled from %S on %t") + (delschedule . "Not scheduled, was %S on %t") + (redeadline . "New deadline from %S on %t") + (deldeadline . "Removed deadline, was %S on %t") + (refile . "Refiled on %t") + (clock-out . "")) + "Headings for notes added to entries. + +The value is an alist, with the car being a symbol indicating the +note context, and the cdr is the heading to be used. The heading +may also be the empty string. The following placeholders can be +used: + + %t a time stamp. + %T an active time stamp instead the default inactive one + %d a short-format time stamp. + %D an active short-format time stamp. + %s the new TODO state or time stamp (inactive), in double quotes. + %S the old TODO state or time stamp (inactive), in double quotes. + %u the user name. + %U full user name. + +In fact, it is not a good idea to change the `state' entry, +because Agenda Log mode depends on the format of these entries." + :group 'org-todo + :group 'org-progress + :type '(list :greedy t + (cons (const :tag "Heading when closing an item" done) string) + (cons (const :tag + "Heading when changing todo state (todo sequence only)" + state) string) + (cons (const :tag "Heading when just taking a note" note) string) + (cons (const :tag "Heading when rescheduling" reschedule) string) + (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string) + (cons (const :tag "Heading when changing deadline" redeadline) string) + (cons (const :tag "Heading when deleting a deadline" deldeadline) string) + (cons (const :tag "Heading when refiling" refile) string) + (cons (const :tag "Heading when clocking out" clock-out) string))) + +(unless (assq 'note org-log-note-headings) + (push '(note . "%t") org-log-note-headings)) + +(defcustom org-log-into-drawer nil + "Non-nil means insert state change notes and time stamps into a drawer. +When nil, state changes notes will be inserted after the headline and +any scheduling and clock lines, but not inside a drawer. + +The value of this variable should be the name of the drawer to use. +LOGBOOK is proposed as the default drawer for this purpose, you can +also set this to a string to define the drawer of your choice. + +A value of t is also allowed, representing \"LOGBOOK\". + +A value of t or nil can also be set with on a per-file-basis with + + #+STARTUP: logdrawer + #+STARTUP: nologdrawer + +If this variable is set, `org-log-state-notes-insert-after-drawers' +will be ignored. + +You can set the property LOG_INTO_DRAWER to overrule this setting for +a subtree. + +Do not check directly this variable in a Lisp program. Call +function `org-log-into-drawer' instead." + :group 'org-todo + :group 'org-progress + :type '(choice + (const :tag "Not into a drawer" nil) + (const :tag "LOGBOOK" t) + (string :tag "Other"))) + +(defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer) + +(defun org-log-into-drawer () + "Name of the log drawer, as a string, or nil. +This is the value of `org-log-into-drawer'. However, if the +current entry has or inherits a LOG_INTO_DRAWER property, it will +be used instead of the default value." + (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t))) + (cond ((equal p "nil") nil) + ((equal p "t") "LOGBOOK") + ((stringp p) p) + (p "LOGBOOK") + ((stringp org-log-into-drawer) org-log-into-drawer) + (org-log-into-drawer "LOGBOOK")))) + +(defcustom org-log-state-notes-insert-after-drawers nil + "Non-nil means insert state change notes after any drawers in entry. +Only the drawers that *immediately* follow the headline and the +deadline/scheduled line are skipped. +When nil, insert notes right after the heading and perhaps the line +with deadline/scheduling if present. + +This variable will have no effect if `org-log-into-drawer' is +set." + :group 'org-todo + :group 'org-progress + :type 'boolean) + +(defcustom org-log-states-order-reversed t + "Non-nil means the latest state note will be directly after heading. +When nil, the state change notes will be ordered according to time. + +This option can also be set with on a per-file-basis with + + #+STARTUP: logstatesreversed + #+STARTUP: nologstatesreversed" + :group 'org-todo + :group 'org-progress + :type 'boolean) + +(defcustom org-todo-repeat-to-state nil + "The TODO state to which a repeater should return the repeating task. +By default this is the first task in a TODO sequence, or the previous state +in a TODO_TYP set. But you can specify another task here. +alternatively, set the :REPEAT_TO_STATE: property of the entry." + :group 'org-todo + :version "24.1" + :type '(choice (const :tag "Head of sequence" nil) + (string :tag "Specific state"))) + +(defcustom org-log-repeat 'time + "Non-nil means record moving through the DONE state when triggering repeat. +An auto-repeating task is immediately switched back to TODO when +marked DONE. If you are not logging state changes (by adding \"@\" +or \"!\" to the TODO keyword definition), or set `org-log-done' to +record a closing note, there will be no record of the task moving +through DONE. This variable forces taking a note anyway. + +nil Don't force a record +time Record a time stamp +note Prompt for a note and add it with template `org-log-note-headings' + +This option can also be set with on a per-file-basis with + + #+STARTUP: nologrepeat + #+STARTUP: logrepeat + #+STARTUP: lognoterepeat + +You can have local logging settings for a subtree by setting the LOGGING +property to one or more of these keywords." + :group 'org-todo + :group 'org-progress + :type '(choice + (const :tag "Don't force a record" nil) + (const :tag "Force recording the DONE state" time) + (const :tag "Force recording a note with the DONE state" note))) + + +(defgroup org-priorities nil + "Priorities in Org mode." + :tag "Org Priorities" + :group 'org-todo) + +(defcustom org-enable-priority-commands t + "Non-nil means priority commands are active. +When nil, these commands will be disabled, so that you never accidentally +set a priority." + :group 'org-priorities + :type 'boolean) + +(defcustom org-highest-priority ?A + "The highest priority of TODO items. A character like ?A, ?B etc. +Must have a smaller ASCII number than `org-lowest-priority'." + :group 'org-priorities + :type 'character) + +(defcustom org-lowest-priority ?C + "The lowest priority of TODO items. A character like ?A, ?B etc. +Must have a larger ASCII number than `org-highest-priority'." + :group 'org-priorities + :type 'character) + +(defcustom org-default-priority ?B + "The default priority of TODO items. +This is the priority an item gets if no explicit priority is given. +When starting to cycle on an empty priority the first step in the cycle +depends on `org-priority-start-cycle-with-default'. The resulting first +step priority must not exceed the range from `org-highest-priority' to +`org-lowest-priority' which means that `org-default-priority' has to be +in this range exclusive or inclusive the range boundaries. Else the +first step refuses to set the default and the second will fall back +to (depending on the command used) the highest or lowest priority." + :group 'org-priorities + :type 'character) + +(defcustom org-priority-start-cycle-with-default t + "Non-nil means start with default priority when starting to cycle. +When this is nil, the first step in the cycle will be (depending on the +command used) one higher or lower than the default priority. +See also `org-default-priority'." + :group 'org-priorities + :type 'boolean) + +(defcustom org-get-priority-function nil + "Function to extract the priority from a string. +The string is normally the headline. If this is nil Org computes the +priority from the priority cookie like [#A] in the headline. It returns +an integer, increasing by 1000 for each priority level. +The user can set a different function here, which should take a string +as an argument and return the numeric priority." + :group 'org-priorities + :version "24.1" + :type '(choice + (const nil) + (function))) + +(defgroup org-time nil + "Options concerning time stamps and deadlines in Org mode." + :tag "Org Time" + :group 'org) + +(defcustom org-time-stamp-rounding-minutes '(0 5) + "Number of minutes to round time stamps to. +\\<org-mode-map>\ +These are two values, the first applies when first creating a time stamp. +The second applies when changing it with the commands `S-up' and `S-down'. +When changing the time stamp, this means that it will change in steps +of N minutes, as given by the second value. + +When a setting is 0 or 1, insert the time unmodified. Useful rounding +numbers should be factors of 60, so for example 5, 10, 15. + +When this is larger than 1, you can still force an exact time stamp by using +a double prefix argument to a time stamp command like \ +`\\[org-time-stamp]' or `\\[org-time-stamp-inactive], +and by using a prefix arg to `S-up/down' to specify the exact number +of minutes to shift." + :group 'org-time + :get (lambda (var) ; Make sure both elements are there + (if (integerp (default-value var)) + (list (default-value var) 5) + (default-value var))) + :type '(list + (integer :tag "when inserting times") + (integer :tag "when modifying times"))) + +;; Normalize old customizations of this variable. +(when (integerp org-time-stamp-rounding-minutes) + (setq org-time-stamp-rounding-minutes + (list org-time-stamp-rounding-minutes + org-time-stamp-rounding-minutes))) + +(defcustom org-display-custom-times nil + "Non-nil means overlay custom formats over all time stamps. +The formats are defined through the variable `org-time-stamp-custom-formats'. +To turn this on on a per-file basis, insert anywhere in the file: + #+STARTUP: customtime" + :group 'org-time + :set 'set-default + :type 'sexp) +(make-variable-buffer-local 'org-display-custom-times) + +(defcustom org-time-stamp-custom-formats + '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american + "Custom formats for time stamps. See `format-time-string' for the syntax. +These are overlaid over the default ISO format if the variable +`org-display-custom-times' is set. Time like %H:%M should be at the +end of the second format. The custom formats are also honored by export +commands, if custom time display is turned on at the time of export." + :group 'org-time + :type 'sexp) + +(defun org-time-stamp-format (&optional long inactive) + "Get the right format for a time string." + (let ((f (if long (cdr org-time-stamp-formats) + (car org-time-stamp-formats)))) + (if inactive + (concat "[" (substring f 1 -1) "]") + f))) + +(defcustom org-deadline-warning-days 14 + "Number of days before expiration during which a deadline becomes active. +This variable governs the display in sparse trees and in the agenda. +When 0 or negative, it means use this number (the absolute value of it) +even if a deadline has a different individual lead time specified. + +Custom commands can set this variable in the options section." + :group 'org-time + :group 'org-agenda-daily/weekly + :type 'integer) + +(defcustom org-scheduled-delay-days 0 + "Number of days before a scheduled item becomes active. +This variable governs the display in sparse trees and in the agenda. +The default value (i.e. 0) means: don't delay scheduled item. +When negative, it means use this number (the absolute value of it) +even if a scheduled item has a different individual delay time +specified. + +Custom commands can set this variable in the options section." + :group 'org-time + :group 'org-agenda-daily/weekly + :version "24.4" + :package-version '(Org . "8.0") + :type 'integer) + +(defcustom org-read-date-prefer-future t + "Non-nil means assume future for incomplete date input from user. +This affects the following situations: +1. The user gives a month but not a year. + For example, if it is April and you enter \"feb 2\", this will be read + as Feb 2, *next* year. \"May 5\", however, will be this year. +2. The user gives a day, but no month. + For example, if today is the 15th, and you enter \"3\", Org will read + this as the third of *next* month. However, if you enter \"17\", + it will be considered as *this* month. + +If you set this variable to the symbol `time', then also the following +will work: + +3. If the user gives a time. + If the time is before now, it will be interpreted as tomorrow. + +Currently none of this works for ISO week specifications. + +When this option is nil, the current day, month and year will always be +used as defaults. + +See also `org-agenda-jump-prefer-future'." + :group 'org-time + :type '(choice + (const :tag "Never" nil) + (const :tag "Check month and day" t) + (const :tag "Check month, day, and time" time))) + +(defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future + "Should the agenda jump command prefer the future for incomplete dates? +The default is to do the same as configured in `org-read-date-prefer-future'. +But you can also set a deviating value here. +This may t or nil, or the symbol `org-read-date-prefer-future'." + :group 'org-agenda + :group 'org-time + :version "24.1" + :type '(choice + (const :tag "Use org-read-date-prefer-future" + org-read-date-prefer-future) + (const :tag "Never" nil) + (const :tag "Always" t))) + +(defcustom org-read-date-force-compatible-dates t + "Should date/time prompt force dates that are guaranteed to work in Emacs? + +Depending on the system Emacs is running on, certain dates cannot +be represented with the type used internally to represent time. +Dates between 1970-1-1 and 2038-1-1 can always be represented +correctly. Some systems allow for earlier dates, some for later, +some for both. One way to find out it to insert any date into an +Org buffer, putting the cursor on the year and hitting S-up and +S-down to test the range. + +When this variable is set to t, the date/time prompt will not let +you specify dates outside the 1970-2037 range, so it is certain that +these dates will work in whatever version of Emacs you are +running, and also that you can move a file from one Emacs implementation +to another. WHenever Org is forcing the year for you, it will display +a message and beep. + +When this variable is nil, Org will check if the date is +representable in the specific Emacs implementation you are using. +If not, it will force a year, usually the current year, and beep +to remind you. Currently this setting is not recommended because +the likelihood that you will open your Org files in an Emacs that +has limited date range is not negligible. + +A workaround for this problem is to use diary sexp dates for time +stamps outside of this range." + :group 'org-time + :version "24.1" + :type 'boolean) + +(defcustom org-read-date-display-live t + "Non-nil means display current interpretation of date prompt live. +This display will be in an overlay, in the minibuffer." + :group 'org-time + :type 'boolean) + +(defcustom org-read-date-popup-calendar t + "Non-nil means pop up a calendar when prompting for a date. +In the calendar, the date can be selected with mouse-1. However, the +minibuffer will also be active, and you can simply enter the date as well. +When nil, only the minibuffer will be available." + :group 'org-time + :type 'boolean) +(defvaralias 'org-popup-calendar-for-date-prompt + 'org-read-date-popup-calendar) + +(defcustom org-extend-today-until 0 + "The hour when your day really ends. Must be an integer. +This has influence for the following applications: +- When switching the agenda to \"today\". It it is still earlier than + the time given here, the day recognized as TODAY is actually yesterday. +- When a date is read from the user and it is still before the time given + here, the current date and time will be assumed to be yesterday, 23:59. + Also, timestamps inserted in capture templates follow this rule. + +IMPORTANT: This is a feature whose implementation is and likely will +remain incomplete. Really, it is only here because past midnight seems to +be the favorite working time of John Wiegley :-)" + :group 'org-time + :type 'integer) + +(defcustom org-use-effective-time nil + "If non-nil, consider `org-extend-today-until' when creating timestamps. +For example, if `org-extend-today-until' is 8, and it's 4am, then the +\"effective time\" of any timestamps between midnight and 8am will be +23:59 of the previous day." + :group 'org-time + :version "24.1" + :type 'boolean) + +(defcustom org-use-last-clock-out-time-as-effective-time nil + "When non-nil, use the last clock out time for `org-todo'. +Note that this option has precedence over the combined use of +`org-use-effective-time' and `org-extend-today-until'." + :group 'org-time + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-edit-timestamp-down-means-later nil + "Non-nil means S-down will increase the time in a time stamp. +When nil, S-up will increase." + :group 'org-time + :type 'boolean) + +(defcustom org-calendar-follow-timestamp-change t + "Non-nil means make the calendar window follow timestamp changes. +When a timestamp is modified and the calendar window is visible, it will be +moved to the new date." + :group 'org-time + :type 'boolean) + +(defgroup org-tags nil + "Options concerning tags in Org mode." + :tag "Org Tags" + :group 'org) + +(defcustom org-tag-alist nil + "Default tags available in Org files. + +The value of this variable is an alist. Associations either: + + (TAG) + (TAG . SELECT) + (SPECIAL) + +where TAG is a tag as a string, SELECT is character, used to +select that tag through the fast tag selection interface, and +SPECIAL is one of the following keywords: `:startgroup', +`:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or +`:newline'. These keywords are used to define a hierarchy of +tags. See manual for details. + +When this variable is nil, Org mode bases tag input on what is +already in the buffer. The value can be overridden locally by +using a TAGS keyword, e.g., + + #+TAGS: tag1 tag2 + +See also `org-tag-persistent-alist' to sidestep this behavior." + :group 'org-tags + :type '(repeat + (choice + (cons :tag "Tag with key" + (string :tag "Tag name") + (character :tag "Access char")) + (list :tag "Tag" (string :tag "Tag name")) + (const :tag "Start radio group" (:startgroup)) + (const :tag "Start tag group, non distinct" (:startgrouptag)) + (const :tag "Group tags delimiter" (:grouptags)) + (const :tag "End radio group" (:endgroup)) + (const :tag "End tag group, non distinct" (:endgrouptag)) + (const :tag "New line" (:newline))))) + +(defcustom org-tag-persistent-alist nil + "Tags always available in Org files. + +The value of this variable is an alist. Associations either: + + (TAG) + (TAG . SELECT) + (SPECIAL) + +where TAG is a tag as a string, SELECT is a character, used to +select that tag through the fast tag selection interface, and +SPECIAL is one of the following keywords: `:startgroup', +`:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or +`:newline'. These keywords are used to define a hierarchy of +tags. See manual for details. + +Unlike to `org-tag-alist', tags defined in this variable do not +depend on a local TAGS keyword. Instead, to disable these tags +on a per-file basis, insert anywhere in the file: + + #+STARTUP: noptag" + :group 'org-tags + :type '(repeat + (choice + (cons :tag "Tag with key" + (string :tag "Tag name") + (character :tag "Access char")) + (list :tag "Tag" (string :tag "Tag name")) + (const :tag "Start radio group" (:startgroup)) + (const :tag "Start tag group, non distinct" (:startgrouptag)) + (const :tag "Group tags delimiter" (:grouptags)) + (const :tag "End radio group" (:endgroup)) + (const :tag "End tag group, non distinct" (:endgrouptag)) + (const :tag "New line" (:newline))))) + +(defcustom org-complete-tags-always-offer-all-agenda-tags nil + "If non-nil, always offer completion for all tags of all agenda files. +Instead of customizing this variable directly, you might want to +set it locally for capture buffers, because there no list of +tags in that file can be created dynamically (there are none). + + (add-hook \\='org-capture-mode-hook + (lambda () + (setq-local org-complete-tags-always-offer-all-agenda-tags t)))" + :group 'org-tags + :version "24.1" + :type 'boolean) + +(defvar org-file-tags nil + "List of tags that can be inherited by all entries in the file. +The tags will be inherited if the variable `org-use-tag-inheritance' +says they should be. +This variable is populated from #+FILETAGS lines.") + +(defcustom org-use-fast-tag-selection 'auto + "Non-nil means use fast tag selection scheme. +This is a special interface to select and deselect tags with single keys. +When nil, fast selection is never used. +When the symbol `auto', fast selection is used if and only if selection +characters for tags have been configured, either through the variable +`org-tag-alist' or through a #+TAGS line in the buffer. +When t, fast selection is always used and selection keys are assigned +automatically if necessary." + :group 'org-tags + :type '(choice + (const :tag "Always" t) + (const :tag "Never" nil) + (const :tag "When selection characters are configured" auto))) + +(defcustom org-fast-tag-selection-single-key nil + "Non-nil means fast tag selection exits after first change. +When nil, you have to press RET to exit it. +During fast tag selection, you can toggle this flag with `C-c'. +This variable can also have the value `expert'. In this case, the window +displaying the tags menu is not even shown, until you press C-c again." + :group 'org-tags + :type '(choice + (const :tag "No" nil) + (const :tag "Yes" t) + (const :tag "Expert" expert))) + +(defvar org-fast-tag-selection-include-todo nil + "Non-nil means fast tags selection interface will also offer TODO states. +This is an undocumented feature, you should not rely on it.") + +(defcustom org-tags-column -77 + "The column to which tags should be indented in a headline. +If this number is positive, it specifies the column. If it is negative, +it means that the tags should be flushright to that column. For example, +-80 works well for a normal 80 character screen. +When 0, place tags directly after headline text, with only one space in +between." + :group 'org-tags + :type 'integer) + +(defcustom org-auto-align-tags t + "Non-nil keeps tags aligned when modifying headlines. +Some operations (i.e. demoting) change the length of a headline and +therefore shift the tags around. With this option turned on, after +each such operation the tags are again aligned to `org-tags-column'." + :group 'org-tags + :type 'boolean) + +(defcustom org-use-tag-inheritance t + "Non-nil means tags in levels apply also for sublevels. +When nil, only the tags directly given in a specific line apply there. +This may also be a list of tags that should be inherited, or a regexp that +matches tags that should be inherited. Additional control is possible +with the variable `org-tags-exclude-from-inheritance' which gives an +explicit list of tags to be excluded from inheritance, even if the value of +`org-use-tag-inheritance' would select it for inheritance. + +If this option is t, a match early-on in a tree can lead to a large +number of matches in the subtree when constructing the agenda or creating +a sparse tree. If you only want to see the first match in a tree during +a search, check out the variable `org-tags-match-list-sublevels'." + :group 'org-tags + :type '(choice + (const :tag "Not" nil) + (const :tag "Always" t) + (repeat :tag "Specific tags" (string :tag "Tag")) + (regexp :tag "Tags matched by regexp"))) + +(defcustom org-tags-exclude-from-inheritance nil + "List of tags that should never be inherited. +This is a way to exclude a few tags from inheritance. For way to do +the opposite, to actively allow inheritance for selected tags, +see the variable `org-use-tag-inheritance'." + :group 'org-tags + :type '(repeat (string :tag "Tag"))) + +(defun org-tag-inherit-p (tag) + "Check if TAG is one that should be inherited." + (cond + ((member tag org-tags-exclude-from-inheritance) nil) + ((eq org-use-tag-inheritance t) t) + ((not org-use-tag-inheritance) nil) + ((stringp org-use-tag-inheritance) + (string-match org-use-tag-inheritance tag)) + ((listp org-use-tag-inheritance) + (member tag org-use-tag-inheritance)) + (t (error "Invalid setting of `org-use-tag-inheritance'")))) + +(defcustom org-tags-match-list-sublevels t + "Non-nil means list also sublevels of headlines matching a search. +This variable applies to tags/property searches, and also to stuck +projects because this search is based on a tags match as well. + +When set to the symbol `indented', sublevels are indented with +leading dots. + +Because of tag inheritance (see variable `org-use-tag-inheritance'), +the sublevels of a headline matching a tag search often also match +the same search. Listing all of them can create very long lists. +Setting this variable to nil causes subtrees of a match to be skipped. + +This variable is semi-obsolete and probably should always be true. It +is better to limit inheritance to certain tags using the variables +`org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'." + :group 'org-tags + :type '(choice + (const :tag "No, don't list them" nil) + (const :tag "Yes, do list them" t) + (const :tag "List them, indented with leading dots" indented))) + +(defcustom org-tags-sort-function nil + "When set, tags are sorted using this function as a comparator." + :group 'org-tags + :type '(choice + (const :tag "No sorting" nil) + (const :tag "Alphabetical" string<) + (const :tag "Reverse alphabetical" string>) + (function :tag "Custom function" nil))) + +(defvar org-tags-history nil + "History of minibuffer reads for tags.") +(defvar org-last-tags-completion-table nil + "The last used completion table for tags.") +(defvar org-after-tags-change-hook nil + "Hook that is run after the tags in a line have changed.") + +(defgroup org-properties nil + "Options concerning properties in Org mode." + :tag "Org Properties" + :group 'org) + +(defcustom org-property-format "%-10s %s" + "How property key/value pairs should be formatted by `indent-line'. +When `indent-line' hits a property definition, it will format the line +according to this format, mainly to make sure that the values are +lined-up with respect to each other." + :group 'org-properties + :type 'string) + +(defcustom org-properties-postprocess-alist nil + "Alist of properties and functions to adjust inserted values. +Elements of this alist must be of the form + + ([string] [function]) + +where [string] must be a property name and [function] must be a +lambda expression: this lambda expression must take one argument, +the value to adjust, and return the new value as a string. + +For example, this element will allow the property \"Remaining\" +to be updated wrt the relation between the \"Effort\" property +and the clock summary: + + ((\"Remaining\" (lambda(value) + (let ((clocksum (org-clock-sum-current-item)) + (effort (org-duration-to-minutes + (org-entry-get (point) \"Effort\")))) + (org-minutes-to-clocksum-string (- effort clocksum))))))" + :group 'org-properties + :version "24.1" + :type '(alist :key-type (string :tag "Property") + :value-type (function :tag "Function"))) + +(defcustom org-use-property-inheritance nil + "Non-nil means properties apply also for sublevels. + +This setting is chiefly used during property searches. Turning it on can +cause significant overhead when doing a search, which is why it is not +on by default. + +When nil, only the properties directly given in the current entry count. +When t, every property is inherited. The value may also be a list of +properties that should have inheritance, or a regular expression matching +properties that should be inherited. + +However, note that some special properties use inheritance under special +circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS, +and the properties ending in \"_ALL\" when they are used as descriptor +for valid values of a property. + +Note for programmers: +When querying an entry with `org-entry-get', you can control if inheritance +should be used. By default, `org-entry-get' looks only at the local +properties. You can request inheritance by setting the inherit argument +to t (to force inheritance) or to `selective' (to respect the setting +in this variable)." + :group 'org-properties + :type '(choice + (const :tag "Not" nil) + (const :tag "Always" t) + (repeat :tag "Specific properties" (string :tag "Property")) + (regexp :tag "Properties matched by regexp"))) + +(defun org-property-inherit-p (property) + "Return a non-nil value if PROPERTY should be inherited." + (cond + ((eq org-use-property-inheritance t) t) + ((not org-use-property-inheritance) nil) + ((stringp org-use-property-inheritance) + (string-match org-use-property-inheritance property)) + ((listp org-use-property-inheritance) + (member-ignore-case property org-use-property-inheritance)) + (t (error "Invalid setting of `org-use-property-inheritance'")))) + +(defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS" + "The default column format, if no other format has been defined. +This variable can be set on the per-file basis by inserting a line + +#+COLUMNS: %25ITEM ....." + :group 'org-properties + :type 'string) + +(defcustom org-columns-ellipses ".." + "The ellipses to be used when a field in column view is truncated. +When this is the empty string, as many characters as possible are shown, +but then there will be no visual indication that the field has been truncated. +When this is a string of length N, the last N characters of a truncated +field are replaced by this string. If the column is narrower than the +ellipses string, only part of the ellipses string will be shown." + :group 'org-properties + :type 'string) + +(defconst org-global-properties-fixed + '(("VISIBILITY_ALL" . "folded children content all") + ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto")) + "List of property/value pairs that can be inherited by any entry. + +These are fixed values, for the preset properties. The user variable +that can be used to add to this list is `org-global-properties'. + +The entries in this list are cons cells where the car is a property +name and cdr is a string with the value. If the value represents +multiple items like an \"_ALL\" property, separate the items by +spaces.") + +(defcustom org-global-properties nil + "List of property/value pairs that can be inherited by any entry. + +This list will be combined with the constant `org-global-properties-fixed'. + +The entries in this list are cons cells where the car is a property +name and cdr is a string with the value. + +You can set buffer-local values for the same purpose in the variable +`org-file-properties' this by adding lines like + +#+PROPERTY: NAME VALUE" + :group 'org-properties + :type '(repeat + (cons (string :tag "Property") + (string :tag "Value")))) + +(defvar-local org-file-properties nil + "List of property/value pairs that can be inherited by any entry. +Valid for the current buffer. +This variable is populated from #+PROPERTY lines.") + +(defgroup org-agenda nil + "Options concerning agenda views in Org mode." + :tag "Org Agenda" + :group 'org) + +(defvar-local org-category nil + "Variable used by Org files to set a category for agenda display. +Such files should use a file variable to set it, for example + +# -*- mode: org; org-category: \"ELisp\" + +or contain a special line + +#+CATEGORY: ELisp + +If the file does not specify a category, then file's base name +is used instead.") +(put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x)))) + +(defcustom org-agenda-files nil + "The files to be used for agenda display. + +If an entry is a directory, all files in that directory that are matched +by `org-agenda-file-regexp' will be part of the file list. + +If the value of the variable is not a list but a single file name, then +the list of agenda files is actually stored and maintained in that file, +one agenda file per line. In this file paths can be given relative to +`org-directory'. Tilde expansion and environment variable substitution +are also made. + +Entries may be added to this list with `\\[org-agenda-file-to-front]' +and removed with `\\[org-remove-file]'." + :group 'org-agenda + :type '(choice + (repeat :tag "List of files and directories" file) + (file :tag "Store list in a file\n" :value "~/.agenda_files"))) + +(defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'" + "Regular expression to match files for `org-agenda-files'. +If any element in the list in that variable contains a directory instead +of a normal file, all files in that directory that are matched by this +regular expression will be included." + :group 'org-agenda + :type 'regexp) + +(defcustom org-agenda-text-search-extra-files nil + "List of extra files to be searched by text search commands. +These files will be searched in addition to the agenda files by the +commands `org-search-view' (`\\[org-agenda] s') \ +and `org-occur-in-agenda-files'. +Note that these files will only be searched for text search commands, +not for the other agenda views like todo lists, tag searches or the weekly +agenda. This variable is intended to list notes and possibly archive files +that should also be searched by these two commands. +In fact, if the first element in the list is the symbol `agenda-archives', +then all archive files of all agenda files will be added to the search +scope." + :group 'org-agenda + :type '(set :greedy t + (const :tag "Agenda Archives" agenda-archives) + (repeat :inline t (file)))) + +(defvaralias 'org-agenda-multi-occur-extra-files + 'org-agenda-text-search-extra-files) + +(defcustom org-agenda-skip-unavailable-files nil + "Non-nil means to just skip non-reachable files in `org-agenda-files'. +A nil value means to remove them, after a query, from the list." + :group 'org-agenda + :type 'boolean) + +(defcustom org-calendar-to-agenda-key [?c] + "The key to be installed in `calendar-mode-map' for switching to the agenda. +The command `org-calendar-goto-agenda' will be bound to this key. The +default is the character `c' because then `c' can be used to switch back and +forth between agenda and calendar." + :group 'org-agenda + :type 'sexp) + +(defcustom org-calendar-insert-diary-entry-key [?i] + "The key to be installed in `calendar-mode-map' for adding diary entries. +This option is irrelevant until `org-agenda-diary-file' has been configured +to point to an Org file. When that is the case, the command +`org-agenda-diary-entry' will be bound to the key given here, by default +`i'. In the calendar, `i' normally adds entries to `diary-file'. So +if you want to continue doing this, you need to change this to a different +key." + :group 'org-agenda + :type 'sexp) + +(defcustom org-agenda-diary-file 'diary-file + "File to which to add new entries with the `i' key in agenda and calendar. +When this is the symbol `diary-file', the functionality in the Emacs +calendar will be used to add entries to the `diary-file'. But when this +points to a file, `org-agenda-diary-entry' will be used instead." + :group 'org-agenda + :type '(choice + (const :tag "The standard Emacs diary file" diary-file) + (file :tag "Special Org file diary entries"))) + +(eval-after-load "calendar" + '(progn + (org-defkey calendar-mode-map org-calendar-to-agenda-key + 'org-calendar-goto-agenda) + (add-hook 'calendar-mode-hook + (lambda () + (unless (eq org-agenda-diary-file 'diary-file) + (define-key calendar-mode-map + org-calendar-insert-diary-entry-key + 'org-agenda-diary-entry)))))) + +(defgroup org-latex nil + "Options for embedding LaTeX code into Org mode." + :tag "Org LaTeX" + :group 'org) + +(defcustom org-format-latex-options + '(:foreground default :background default :scale 1.0 + :html-foreground "Black" :html-background "Transparent" + :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\[")) + "Options for creating images from LaTeX fragments. +This is a property list with the following properties: +:foreground the foreground color for images embedded in Emacs, e.g. \"Black\". + `default' means use the foreground of the default face. + `auto' means use the foreground from the text face. +:background the background color, or \"Transparent\". + `default' means use the background of the default face. + `auto' means use the background from the text face. +:scale a scaling factor for the size of the images, to get more pixels +:html-foreground, :html-background, :html-scale + the same numbers for HTML export. +:matchers a list indicating which matchers should be used to + find LaTeX fragments. Valid members of this list are: + \"begin\" find environments + \"$1\" find single characters surrounded by $.$ + \"$\" find math expressions surrounded by $...$ + \"$$\" find math expressions surrounded by $$....$$ + \"\\(\" find math expressions surrounded by \\(...\\) + \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]" + :group 'org-latex + :type 'plist) + +(defcustom org-format-latex-signal-error t + "Non-nil means signal an error when image creation of LaTeX snippets fails. +When nil, just push out a message." + :group 'org-latex + :version "24.1" + :type 'boolean) + +(defcustom org-latex-to-mathml-jar-file nil + "Value of\"%j\" in `org-latex-to-mathml-convert-command'. +Use this to specify additional executable file say a jar file. + +When using MathToWeb as the converter, specify the full-path to +your mathtoweb.jar file." + :group 'org-latex + :version "24.1" + :type '(choice + (const :tag "None" nil) + (file :tag "JAR file" :must-match t))) + +(defcustom org-latex-to-mathml-convert-command nil + "Command to convert LaTeX fragments to MathML. +Replace format-specifiers in the command as noted below and use +`shell-command' to convert LaTeX to MathML. +%j: Executable file in fully expanded form as specified by + `org-latex-to-mathml-jar-file'. +%I: Input LaTeX file in fully expanded form. +%i: The latex fragment to be converted. +%o: Output MathML file. + +This command is used by `org-create-math-formula'. + +When using MathToWeb as the converter, set this option to +\"java -jar %j -unicode -force -df %o %I\". + +When using LaTeXML set this option to +\"latexmlmath \"%i\" --presentationmathml=%o\"." + :group 'org-latex + :version "24.1" + :type '(choice + (const :tag "None" nil) + (string :tag "\nShell command"))) + +(defcustom org-preview-latex-default-process 'dvipng + "The default process to convert LaTeX fragments to image files. +All available processes and theirs documents can be found in +`org-preview-latex-process-alist', which see." + :group 'org-latex + :version "26.1" + :package-version '(Org . "9.0") + :type 'symbol) + +(defcustom org-preview-latex-process-alist + '((dvipng + :programs ("latex" "dvipng") + :description "dvi > png" + :message "you need to install the programs: latex and dvipng." + :image-input-type "dvi" + :image-output-type "png" + :image-size-adjust (1.0 . 1.0) + :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f") + :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f")) + (dvisvgm + :programs ("latex" "dvisvgm") + :description "dvi > svg" + :message "you need to install the programs: latex and dvisvgm." + :use-xcolor t + :image-input-type "dvi" + :image-output-type "svg" + :image-size-adjust (1.7 . 1.5) + :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f") + :image-converter ("dvisvgm %f -n -b min -c %S -o %O")) + (imagemagick + :programs ("latex" "convert") + :description "pdf > png" + :message "you need to install the programs: latex and imagemagick." + :use-xcolor t + :image-input-type "pdf" + :image-output-type "png" + :image-size-adjust (1.0 . 1.0) + :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f") + :image-converter + ("convert -density %D -trim -antialias %f -quality 100 %O"))) + "Definitions of external processes for LaTeX previewing. +Org mode can use some external commands to generate TeX snippet's images for +previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells +`org-create-formula-image' how to call them. + +The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol. +PROPERTIES accepts the following attributes: + + :programs list of strings, required programs. + :description string, describe the process. + :message string, message it when required programs cannot be found. + :image-input-type string, input file type of image converter (e.g., \"dvi\"). + :image-output-type string, output file type of image converter (e.g., \"png\"). + :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to + deal with background and foreground color of image. + Otherwise, dvipng style background and foreground color + format are generated. You may then refer to them in + command options with \"%F\" and \"%B\". + :image-size-adjust cons of numbers, the car element is used to adjust LaTeX + image size showed in buffer and the cdr element is for + HTML file. This option is only useful for process + developers, users should use variable + `org-format-latex-options' instead. + :post-clean list of strings, files matched are to be cleaned up once + the image is generated. When nil, the files with \".dvi\", + \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\", + \".png\", \".jpg\", \".jpeg\" or \".out\" extension will + be cleaned up. + :latex-header list of strings, the LaTeX header of the snippet file. + When nil, the fallback value is used instead, which is + controlled by `org-format-latex-header', + `org-latex-default-packages-alist' and + `org-latex-packages-alist', which see. + :latex-compiler list of LaTeX commands, as strings. Each of them is given + to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are + replaced with values defined below. + :image-converter list of image converter commands strings. Each of them is + given to the shell and supports any of the following + place-holders defined below. + +Place-holders used by `:image-converter' and `:latex-compiler': + + %f input file name + %b base name of input file + %o base directory of input file + %O absolute output file name + +Place-holders only used by `:image-converter': + + %F foreground of image + %B background of image + %D dpi, which is used to adjust image size by some processing commands. + %S the image size scale ratio, which is used to adjust image size by some + processing commands." + :group 'org-latex + :version "26.1" + :package-version '(Org . "9.0") + :type '(alist :tag "LaTeX to image backends" + :value-type (plist))) + +(defcustom org-preview-latex-image-directory "ltximg/" + "Path to store latex preview images. +A relative path here creates many directories relative to the +processed Org files paths. An absolute path puts all preview +images at the same place." + :group 'org-latex + :version "26.1" + :package-version '(Org . "9.0") + :type 'string) + +(defun org-format-latex-mathml-available-p () + "Return t if `org-latex-to-mathml-convert-command' is usable." + (save-match-data + (when (and (boundp 'org-latex-to-mathml-convert-command) + org-latex-to-mathml-convert-command) + (let ((executable (car (split-string + org-latex-to-mathml-convert-command)))) + (when (executable-find executable) + (if (string-match + "%j" org-latex-to-mathml-convert-command) + (file-readable-p org-latex-to-mathml-jar-file) + t)))))) + +(defcustom org-format-latex-header "\\documentclass{article} +\\usepackage[usenames]{color} +\[PACKAGES] +\[DEFAULT-PACKAGES] +\\pagestyle{empty} % do not remove +% The settings below are copied from fullpage.sty +\\setlength{\\textwidth}{\\paperwidth} +\\addtolength{\\textwidth}{-3cm} +\\setlength{\\oddsidemargin}{1.5cm} +\\addtolength{\\oddsidemargin}{-2.54cm} +\\setlength{\\evensidemargin}{\\oddsidemargin} +\\setlength{\\textheight}{\\paperheight} +\\addtolength{\\textheight}{-\\headheight} +\\addtolength{\\textheight}{-\\headsep} +\\addtolength{\\textheight}{-\\footskip} +\\addtolength{\\textheight}{-3cm} +\\setlength{\\topmargin}{1.5cm} +\\addtolength{\\topmargin}{-2.54cm}" + "The document header used for processing LaTeX fragments. +It is imperative that this header make sure that no page number +appears on the page. The package defined in the variables +`org-latex-default-packages-alist' and `org-latex-packages-alist' +will either replace the placeholder \"[PACKAGES]\" in this +header, or they will be appended." + :group 'org-latex + :type 'string) + +(defun org-set-packages-alist (var val) + "Set the packages alist and make sure it has 3 elements per entry." + (set var (mapcar (lambda (x) + (if (and (consp x) (= (length x) 2)) + (list (car x) (nth 1 x) t) + x)) + val))) + +(defun org-get-packages-alist (var) + "Get the packages alist and make sure it has 3 elements per entry." + (mapcar (lambda (x) + (if (and (consp x) (= (length x) 2)) + (list (car x) (nth 1 x) t) + x)) + (default-value var))) + +(defcustom org-latex-default-packages-alist + '(("AUTO" "inputenc" t ("pdflatex")) + ("T1" "fontenc" t ("pdflatex")) + ("" "graphicx" t) + ("" "grffile" t) + ("" "longtable" nil) + ("" "wrapfig" nil) + ("" "rotating" nil) + ("normalem" "ulem" t) + ("" "amsmath" t) + ("" "textcomp" t) + ("" "amssymb" t) + ("" "capt-of" nil) + ("" "hyperref" nil)) + "Alist of default packages to be inserted in the header. + +Change this only if one of the packages here causes an +incompatibility with another package you are using. + +The packages in this list are needed by one part or another of +Org mode to function properly: + +- inputenc, fontenc: for basic font and character selection +- graphicx: for including images +- grffile: allow periods and spaces in graphics file names +- longtable: For multipage tables +- wrapfig: for figure placement +- rotating: for sideways figures and tables +- ulem: for underline and strike-through +- amsmath: for subscript and superscript and math environments +- textcomp, amssymb: for various symbols used + for interpreting the entities in `org-entities'. You can skip + some of these packages if you don't use any of their symbols. +- capt-of: for captions outside of floats +- hyperref: for cross references + +Therefore you should not modify this variable unless you know +what you are doing. The one reason to change it anyway is that +you might be loading some other package that conflicts with one +of the default packages. Each element is either a cell or +a string. + +A cell is of the format + + (\"options\" \"package\" SNIPPET-FLAG COMPILERS) + +If SNIPPET-FLAG is non-nil, the package also needs to be included +when compiling LaTeX snippets into images for inclusion into +non-LaTeX output. COMPILERS is a list of compilers that should +include the package, see `org-latex-compiler'. If the document +compiler is not in the list, and the list is non-nil, the package +will not be inserted in the final document. + +A string will be inserted as-is in the header of the document." + :group 'org-latex + :group 'org-export-latex + :set 'org-set-packages-alist + :get 'org-get-packages-alist + :version "26.1" + :package-version '(Org . "8.3") + :type '(repeat + (choice + (list :tag "options/package pair" + (string :tag "options") + (string :tag "package") + (boolean :tag "Snippet") + (choice + (const :tag "For all compilers" nil) + (repeat :tag "Allowed compiler" string))) + (string :tag "A line of LaTeX")))) + +(defcustom org-latex-packages-alist nil + "Alist of packages to be inserted in every LaTeX header. + +These will be inserted after `org-latex-default-packages-alist'. +Each element is either a cell or a string. + +A cell is of the format: + + (\"options\" \"package\" SNIPPET-FLAG) + +SNIPPET-FLAG, when non-nil, indicates that this package is also +needed when turning LaTeX snippets into images for inclusion into +non-LaTeX output. + +A string will be inserted as-is in the header of the document. + +Make sure that you only list packages here which: + + - you want in every file; + - do not conflict with the setup in `org-format-latex-header'; + - do not conflict with the default packages in + `org-latex-default-packages-alist'." + :group 'org-latex + :group 'org-export-latex + :set 'org-set-packages-alist + :get 'org-get-packages-alist + :type '(repeat + (choice + (list :tag "options/package pair" + (string :tag "options") + (string :tag "package") + (boolean :tag "Snippet")) + (string :tag "A line of LaTeX")))) + +(defgroup org-appearance nil + "Settings for Org mode appearance." + :tag "Org Appearance" + :group 'org) + +(defcustom org-level-color-stars-only nil + "Non-nil means fontify only the stars in each headline. +When nil, the entire headline is fontified. +Changing it requires restart of `font-lock-mode' to become effective +also in regions already fontified." + :group 'org-appearance + :type 'boolean) + +(defcustom org-hide-leading-stars nil + "Non-nil means hide the first N-1 stars in a headline. +This works by using the face `org-hide' for these stars. This +face is white for a light background, and black for a dark +background. You may have to customize the face `org-hide' to +make this work. +Changing it requires restart of `font-lock-mode' to become effective +also in regions already fontified. +You may also set this on a per-file basis by adding one of the following +lines to the buffer: + + #+STARTUP: hidestars + #+STARTUP: showstars" + :group 'org-appearance + :type 'boolean) + +(defcustom org-hidden-keywords nil + "List of symbols corresponding to keywords to be hidden in the Org buffer. +For example, a value \\='(title) for this list makes the document's title +appear in the buffer without the initial \"#+TITLE:\" part." + :group 'org-appearance + :version "24.1" + :type '(set (const :tag "#+AUTHOR" author) + (const :tag "#+DATE" date) + (const :tag "#+EMAIL" email) + (const :tag "#+TITLE" title))) + +(defcustom org-custom-properties nil + "List of properties (as strings) with a special meaning. +The default use of these custom properties is to let the user +hide them with `org-toggle-custom-properties-visibility'." + :group 'org-properties + :group 'org-appearance + :version "24.3" + :type '(repeat (string :tag "Property Name"))) + +(defcustom org-fontify-done-headline nil + "Non-nil means change the face of a headline if it is marked DONE. +Normally, only the TODO/DONE keyword indicates the state of a headline. +When this is non-nil, the headline after the keyword is set to the +`org-headline-done' as an additional indication." + :group 'org-appearance + :type 'boolean) + +(defcustom org-fontify-emphasized-text t + "Non-nil means fontify *bold*, /italic/ and _underlined_ text. +Changing this variable requires a restart of Emacs to take effect." + :group 'org-appearance + :type 'boolean) + +(defcustom org-fontify-whole-heading-line nil + "Non-nil means fontify the whole line for headings. +This is useful when setting a background color for the +org-level-* faces." + :group 'org-appearance + :type 'boolean) + +(defcustom org-highlight-latex-and-related nil + "Non-nil means highlight LaTeX related syntax in the buffer. +When non nil, the value should be a list containing any of the +following symbols: + `latex' Highlight LaTeX snippets and environments. + `script' Highlight subscript and superscript. + `entities' Highlight entities." + :group 'org-appearance + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "No highlighting" nil) + (set :greedy t :tag "Highlight" + (const :tag "LaTeX snippets and environments" latex) + (const :tag "Subscript and superscript" script) + (const :tag "Entities" entities)))) + +(defcustom org-hide-emphasis-markers nil + "Non-nil mean font-lock should hide the emphasis marker characters." + :group 'org-appearance + :type 'boolean) + +(defcustom org-hide-macro-markers nil + "Non-nil mean font-lock should hide the brackets marking macro calls." + :group 'org-appearance + :type 'boolean) + +(defcustom org-pretty-entities nil + "Non-nil means show entities as UTF8 characters. +When nil, the \\name form remains in the buffer." + :group 'org-appearance + :version "24.1" + :type 'boolean) + +(defcustom org-pretty-entities-include-sub-superscripts t + "Non-nil means, pretty entity display includes formatting sub/superscripts." + :group 'org-appearance + :version "24.1" + :type 'boolean) + +(defvar org-emph-re nil + "Regular expression for matching emphasis. +After a match, the match groups contain these elements: +0 The match of the full regular expression, including the characters + before and after the proper match +1 The character before the proper match, or empty at beginning of line +2 The proper match, including the leading and trailing markers +3 The leading marker like * or /, indicating the type of highlighting +4 The text between the emphasis markers, not including the markers +5 The character after the match, empty at the end of a line") + +(defvar org-verbatim-re nil + "Regular expression for matching verbatim text.") + +(defvar org-emphasis-regexp-components) ; defined just below +(defvar org-emphasis-alist) ; defined just below +(defun org-set-emph-re (var val) + "Set variable and compute the emphasis regular expression." + (set var val) + (when (and (boundp 'org-emphasis-alist) + (boundp 'org-emphasis-regexp-components) + org-emphasis-alist org-emphasis-regexp-components) + (pcase-let* + ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components) + (body (if (<= nl 0) body + (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl))) + (template + (format (concat "\\([%s]\\|^\\)" ;before markers + "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)" + "\\([%s]\\|$\\)") ;after markers + pre border border body border post))) + (setq org-emph-re (format template "*/_+")) + (setq org-verbatim-re (format template "=~"))))) + +;; This used to be a defcustom (Org <8.0) but allowing the users to +;; set this option proved cumbersome. See this message/thread: +;; http://article.gmane.org/gmane.emacs.orgmode/68681 +(defvar org-emphasis-regexp-components + '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1) + "Components used to build the regular expression for emphasis. +This is a list with five entries. Terminology: In an emphasis string +like \" *strong word* \", we call the initial space PREMATCH, the final +space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters +and \"trong wor\" is the body. The different components in this variable +specify what is allowed/forbidden in each part: + +pre Chars allowed as prematch. Beginning of line will be allowed too. +post Chars allowed as postmatch. End of line will be allowed too. +border The chars *forbidden* as border characters. +body-regexp A regexp like \".\" to match a body character. Don't use + non-shy groups here, and don't allow newline here. +newline The maximum number of newlines allowed in an emphasis exp. + +You need to reload Org or to restart Emacs after customizing this.") + +(defcustom org-emphasis-alist + '(("*" bold) + ("/" italic) + ("_" underline) + ("=" org-verbatim verbatim) + ("~" org-code verbatim) + ("+" (:strike-through t))) + "Alist of characters and faces to emphasize text. +Text starting and ending with a special character will be emphasized, +for example *bold*, _underlined_ and /italic/. This variable sets the +marker characters and the face to be used by font-lock for highlighting +in Org buffers. + +You need to reload Org or to restart Emacs after customizing this." + :group 'org-appearance + :set 'org-set-emph-re + :version "24.4" + :package-version '(Org . "8.0") + :type '(repeat + (list + (string :tag "Marker character") + (choice + (face :tag "Font-lock-face") + (plist :tag "Face property list")) + (option (const verbatim))))) + +(defvar org-protecting-blocks '("src" "example" "export") + "Blocks that contain text that is quoted, i.e. not processed as Org syntax. +This is needed for font-lock setup.") + +;;; Functions and variables from their packages +;; Declared here to avoid compiler warnings +(defvar mark-active) + +;; Various packages +(declare-function calc-eval "calc" (str &optional separator &rest args)) +(declare-function calendar-forward-day "cal-move" (arg)) +(declare-function calendar-goto-date "cal-move" (date)) +(declare-function calendar-goto-today "cal-move" ()) +(declare-function calendar-iso-from-absolute "cal-iso" (date)) +(declare-function calendar-iso-to-absolute "cal-iso" (date)) +(declare-function cdlatex-compute-tables "ext:cdlatex" ()) +(declare-function cdlatex-tab "ext:cdlatex" ()) +(declare-function dired-get-filename + "dired" + (&optional localp no-error-if-not-filep)) +(declare-function iswitchb-read-buffer + "iswitchb" + (prompt &optional + default require-match _predicate start matches-set)) +(declare-function org-agenda-change-all-lines + "org-agenda" + (newhead hdmarker &optional fixface just-this)) +(declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item + "org-agenda" + (&optional end)) +(declare-function org-agenda-copy-local-variable "org-agenda" (var)) +(declare-function org-agenda-format-item + "org-agenda" + (extra txt &optional level category tags dotime + remove-re habitp)) +(declare-function org-agenda-maybe-redo "org-agenda" ()) +(declare-function org-agenda-new-marker "org-agenda" (&optional pos)) +(declare-function org-agenda-save-markers-for-cut-and-paste + "org-agenda" + (beg end)) +(declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type)) +(declare-function org-agenda-skip "org-agenda" ()) +(declare-function org-attach-reveal "org-attach" (&optional if-exists)) +(declare-function org-gnus-follow-link "org-gnus" (&optional group article)) +(declare-function org-indent-mode "org-indent" (&optional arg)) +(declare-function org-inlinetask-goto-beginning "org-inlinetask" ()) +(declare-function org-inlinetask-goto-end "org-inlinetask" ()) +(declare-function org-inlinetask-in-task-p "org-inlinetask" ()) +(declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ()) +(declare-function orgtbl-send-table "org-table" (&optional maybe)) +(declare-function parse-time-string "parse-time" (string)) +(declare-function speedbar-line-directory "speedbar" (&optional depth)) + +(defvar align-mode-rules-list) +(defvar calc-embedded-close-formula) +(defvar calc-embedded-open-formula) +(defvar calc-embedded-open-mode) +(defvar font-lock-unfontify-region-function) +(defvar iswitchb-temp-buflist) +(defvar org-agenda-tags-todo-honor-ignore-options) +(defvar remember-data-file) +(defvar texmathp-why) + +;;;###autoload +(defun turn-on-orgtbl () + "Unconditionally turn on `orgtbl-mode'." + (require 'org-table) + (orgtbl-mode 1)) + +(defun org-at-table-p (&optional table-type) + "Non-nil if the cursor is inside an Org table. +If TABLE-TYPE is non-nil, also check for table.el-type tables." + (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|")) + (or (not (derived-mode-p 'org-mode)) + (let ((e (org-element-lineage (org-element-at-point) '(table) t))) + (and e (or table-type + (eq 'org (org-element-property :type e)))))))) + +(defun org-at-table.el-p () + "Non-nil when point is at a table.el table." + (and (org-match-line "[ \t]*[|+]") + (let ((element (org-element-at-point))) + (and (eq (org-element-type element) 'table) + (eq (org-element-property :type element) 'table.el))))) + +(defun org-at-table-hline-p () + "Non-nil when point is inside a hline in a table. +Assume point is already in a table." + (org-match-line org-table-hline-regexp)) + +(defun org-table-map-tables (function &optional quietly) + "Apply FUNCTION to the start of all tables in the buffer." + (org-with-wide-buffer + (goto-char (point-min)) + (while (re-search-forward org-table-any-line-regexp nil t) + (unless quietly + (message "Mapping tables: %d%%" + (floor (* 100.0 (point)) (buffer-size)))) + (beginning-of-line 1) + (when (and (looking-at org-table-line-regexp) + ;; Exclude tables in src/example/verbatim/clocktable blocks + (not (org-in-block-p '("src" "example" "verbatim" "clocktable")))) + (save-excursion (funcall function)) + (or (looking-at org-table-line-regexp) + (forward-char 1))) + (re-search-forward org-table-any-border-regexp nil 1))) + (unless quietly (message "Mapping tables: done"))) + +(declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end)) +(declare-function org-clock-update-mode-line "org-clock" ()) +(declare-function org-resolve-clocks "org-clock" + (&optional also-non-dangling-p prompt last-valid)) + +(defun org-at-TBLFM-p (&optional pos) + "Non-nil when point (or POS) is in #+TBLFM line." + (save-excursion + (goto-char (or pos (point))) + (beginning-of-line) + (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp)) + (eq (org-element-type (org-element-at-point)) 'table)))) + +(defvar org-clock-start-time) +(defvar org-clock-marker (make-marker) + "Marker recording the last clock-in.") +(defvar org-clock-hd-marker (make-marker) + "Marker recording the last clock-in, but the headline position.") +(defvar org-clock-heading "" + "The heading of the current clock entry.") +(defun org-clock-is-active () + "Return the buffer where the clock is currently running. +Return nil if no clock is running." + (marker-buffer org-clock-marker)) + +(defun org-check-running-clock () + "Check if the current buffer contains the running clock. +If yes, offer to stop it and to save the buffer with the changes." + (when (and (equal (marker-buffer org-clock-marker) (current-buffer)) + (y-or-n-p (format "Clock-out in buffer %s before killing it? " + (buffer-name)))) + (org-clock-out) + (when (y-or-n-p "Save changed buffer?") + (save-buffer)))) + +(defun org-clocktable-try-shift (dir n) + "Check if this line starts a clock table, if yes, shift the time block." + (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>") + (org-clocktable-shift dir n))) + +;;;###autoload +(defun org-clock-persistence-insinuate () + "Set up hooks for clock persistence." + (require 'org-clock) + (add-hook 'org-mode-hook 'org-clock-load) + (add-hook 'kill-emacs-hook 'org-clock-save)) + +(defgroup org-archive nil + "Options concerning archiving in Org mode." + :tag "Org Archive" + :group 'org-structure) + +(defcustom org-archive-location "%s_archive::" + "The location where subtrees should be archived. + +The value of this variable is a string, consisting of two parts, +separated by a double-colon. The first part is a filename and +the second part is a headline. + +When the filename is omitted, archiving happens in the same file. +%s in the filename will be replaced by the current file +name (without the directory part). Archiving to a different file +is useful to keep archived entries from contributing to the +Org Agenda. + +The archived entries will be filed as subtrees of the specified +headline. When the headline is omitted, the subtrees are simply +filed away at the end of the file, as top-level entries. Also in +the heading you can use %s to represent the file name, this can be +useful when using the same archive for a number of different files. + +Here are a few examples: +\"%s_archive::\" + If the current file is Projects.org, archive in file + Projects.org_archive, as top-level trees. This is the default. + +\"::* Archived Tasks\" + Archive in the current file, under the top-level headline + \"* Archived Tasks\". + +\"~/org/archive.org::\" + Archive in file ~/org/archive.org (absolute path), as top-level trees. + +\"~/org/archive.org::* From %s\" + Archive in file ~/org/archive.org (absolute path), under headlines + \"From FILENAME\" where file name is the current file name. + +\"~/org/datetree.org::datetree/* Finished Tasks\" + The \"datetree/\" string is special, signifying to archive + items to the datetree. Items are placed in either the CLOSED + date of the item, or the current date if there is no CLOSED date. + The heading will be a subentry to the current date. There doesn't + need to be a heading, but there always needs to be a slash after + datetree. For example, to store archived items directly in the + datetree, use \"~/org/datetree.org::datetree/\". + +\"basement::** Finished Tasks\" + Archive in file ./basement (relative path), as level 3 trees + below the level 2 heading \"** Finished Tasks\". + +You may set this option on a per-file basis by adding to the buffer a +line like + +#+ARCHIVE: basement::** Finished Tasks + +You may also define it locally for a subtree by setting an ARCHIVE property +in the entry. If such a property is found in an entry, or anywhere up +the hierarchy, it will be used." + :group 'org-archive + :type 'string) + +(defcustom org-agenda-skip-archived-trees t + "Non-nil means the agenda will skip any items located in archived trees. +An archived tree is a tree marked with the tag ARCHIVE. The use of this +variable is no longer recommended, you should leave it at the value t. +Instead, use the key `v' to cycle the archives-mode in the agenda." + :group 'org-archive + :group 'org-agenda-skip + :type 'boolean) + +(defcustom org-columns-skip-archived-trees t + "Non-nil means ignore archived trees when creating column view." + :group 'org-archive + :group 'org-properties + :type 'boolean) + +(defcustom org-cycle-open-archived-trees nil + "Non-nil means `org-cycle' will open archived trees. +An archived tree is a tree marked with the tag ARCHIVE. +When nil, archived trees will stay folded. You can still open them with +normal outline commands like `show-all', but not with the cycling commands." + :group 'org-archive + :group 'org-cycle + :type 'boolean) + +(defcustom org-sparse-tree-open-archived-trees nil + "Non-nil means sparse tree construction shows matches in archived trees. +When nil, matches in these trees are highlighted, but the trees are kept in +collapsed state." + :group 'org-archive + :group 'org-sparse-trees + :type 'boolean) + +(defcustom org-sparse-tree-default-date-type nil + "The default date type when building a sparse tree. +When this is nil, a date is a scheduled or a deadline timestamp. +Otherwise, these types are allowed: + + all: all timestamps + active: only active timestamps (<...>) + inactive: only inactive timestamps ([...]) + scheduled: only scheduled timestamps + deadline: only deadline timestamps" + :type '(choice (const :tag "Scheduled or deadline" nil) + (const :tag "All timestamps" all) + (const :tag "Only active timestamps" active) + (const :tag "Only inactive timestamps" inactive) + (const :tag "Only scheduled timestamps" scheduled) + (const :tag "Only deadline timestamps" deadline) + (const :tag "Only closed timestamps" closed)) + :version "26.1" + :package-version '(Org . "8.3") + :group 'org-sparse-trees) + +(defun org-cycle-hide-archived-subtrees (state) + "Re-hide all archived subtrees after a visibility state change. +STATE should be one of the symbols listed in the docstring of +`org-cycle-hook'." + (when (and (not org-cycle-open-archived-trees) + (not (memq state '(overview folded)))) + (save-excursion + (let* ((globalp (memq state '(contents all))) + (beg (if globalp (point-min) (point))) + (end (if globalp (point-max) (org-end-of-subtree t)))) + (org-hide-archived-subtrees beg end) + (goto-char beg) + (when (looking-at-p (concat ".*:" org-archive-tag ":")) + (message "%s" (substitute-command-keys + "Subtree is archived and stays closed. Use \ +`\\[org-force-cycle-archived]' to cycle it anyway."))))))) + +(defun org-force-cycle-archived () + "Cycle subtree even if it is archived." + (interactive) + (setq this-command 'org-cycle) + (let ((org-cycle-open-archived-trees t)) + (call-interactively 'org-cycle))) + +(defun org-hide-archived-subtrees (beg end) + "Re-hide all archived subtrees after a visibility state change." + (org-with-wide-buffer + (let ((case-fold-search nil) + (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":"))) + (goto-char beg) + ;; Include headline point is currently on. + (beginning-of-line) + (while (and (< (point) end) (re-search-forward re end t)) + (when (member org-archive-tag (org-get-tags)) + (org-flag-subtree t) + (org-end-of-subtree t)))))) + +(declare-function outline-end-of-heading "outline" ()) +(declare-function outline-flag-region "outline" (from to flag)) +(defun org-flag-subtree (flag) + (save-excursion + (org-back-to-heading t) + (outline-end-of-heading) + (outline-flag-region (point) + (progn (org-end-of-subtree t) (point)) + flag))) + +(defalias 'org-advertized-archive-subtree 'org-archive-subtree) + +;; Declare Column View Code + +(declare-function org-columns-get-format-and-top-level "org-colview" ()) +(declare-function org-columns-compute "org-colview" (property)) + +;; Declare ID code + +(declare-function org-id-store-link "org-id") +(declare-function org-id-locations-load "org-id") +(declare-function org-id-locations-save "org-id") +(defvar org-id-track-globally) + +;;; Variables for pre-computed regular expressions, all buffer local + +(defvar-local org-todo-regexp nil + "Matches any of the TODO state keywords. +Since TODO keywords are case-sensitive, `case-fold-search' is +expected to be bound to nil when matching against this regexp.") + +(defvar-local org-not-done-regexp nil + "Matches any of the TODO state keywords except the last one. +Since TODO keywords are case-sensitive, `case-fold-search' is +expected to be bound to nil when matching against this regexp.") + +(defvar-local org-not-done-heading-regexp nil + "Matches a TODO headline that is not done. +Since TODO keywords are case-sensitive, `case-fold-search' is +expected to be bound to nil when matching against this regexp.") + +(defvar-local org-todo-line-regexp nil + "Matches a headline and puts TODO state into group 2 if present. +Since TODO keywords are case-sensitive, `case-fold-search' is +expected to be bound to nil when matching against this regexp.") + +(defvar-local org-complex-heading-regexp nil + "Matches a headline and puts everything into groups: + +group 1: Stars +group 2: The TODO keyword, maybe +group 3: Priority cookie +group 4: True headline +group 5: Tags + +Since TODO keywords are case-sensitive, `case-fold-search' is +expected to be bound to nil when matching against this regexp.") + +(defvar-local org-complex-heading-regexp-format nil + "Printf format to make regexp to match an exact headline. +This regexp will match the headline of any node which has the +exact headline text that is put into the format, but may have any +TODO state, priority and tags.") + +(defvar-local org-todo-line-tags-regexp nil + "Matches a headline and puts TODO state into group 2 if present. +Also put tags into group 4 if tags are present.") + +(defconst org-plain-time-of-day-regexp + (concat + "\\(\\<[012]?[0-9]" + "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)" + "\\(--?" + "\\(\\<[012]?[0-9]" + "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)" + "\\)?") + "Regular expression to match a plain time or time range. +Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following +groups carry important information: +0 the full match +1 the first time, range or not +8 the second time, if it is a range.") + +(defconst org-plain-time-extension-regexp + (concat + "\\(\\<[012]?[0-9]" + "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)" + "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?") + "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40. +Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following +groups carry important information: +0 the full match +7 hours of duration +9 minutes of duration") + +(defconst org-stamp-time-of-day-regexp + (concat + "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)" + "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>" + "\\(--?" + "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?") + "Regular expression to match a timestamp time or time range. +After a match, the following groups carry important information: +0 the full match +1 date plus weekday, for back referencing to make sure both times are on the same day +2 the first time, range or not +4 the second time, if it is a range.") + +(defconst org-startup-options + '(("fold" org-startup-folded t) + ("overview" org-startup-folded t) + ("nofold" org-startup-folded nil) + ("showall" org-startup-folded nil) + ("showeverything" org-startup-folded showeverything) + ("content" org-startup-folded content) + ("indent" org-startup-indented t) + ("noindent" org-startup-indented nil) + ("hidestars" org-hide-leading-stars t) + ("showstars" org-hide-leading-stars nil) + ("odd" org-odd-levels-only t) + ("oddeven" org-odd-levels-only nil) + ("align" org-startup-align-all-tables t) + ("noalign" org-startup-align-all-tables nil) + ("inlineimages" org-startup-with-inline-images t) + ("noinlineimages" org-startup-with-inline-images nil) + ("latexpreview" org-startup-with-latex-preview t) + ("nolatexpreview" org-startup-with-latex-preview nil) + ("customtime" org-display-custom-times t) + ("logdone" org-log-done time) + ("lognotedone" org-log-done note) + ("nologdone" org-log-done nil) + ("lognoteclock-out" org-log-note-clock-out t) + ("nolognoteclock-out" org-log-note-clock-out nil) + ("logrepeat" org-log-repeat state) + ("lognoterepeat" org-log-repeat note) + ("logdrawer" org-log-into-drawer t) + ("nologdrawer" org-log-into-drawer nil) + ("logstatesreversed" org-log-states-order-reversed t) + ("nologstatesreversed" org-log-states-order-reversed nil) + ("nologrepeat" org-log-repeat nil) + ("logreschedule" org-log-reschedule time) + ("lognotereschedule" org-log-reschedule note) + ("nologreschedule" org-log-reschedule nil) + ("logredeadline" org-log-redeadline time) + ("lognoteredeadline" org-log-redeadline note) + ("nologredeadline" org-log-redeadline nil) + ("logrefile" org-log-refile time) + ("lognoterefile" org-log-refile note) + ("nologrefile" org-log-refile nil) + ("fninline" org-footnote-define-inline t) + ("nofninline" org-footnote-define-inline nil) + ("fnlocal" org-footnote-section nil) + ("fnauto" org-footnote-auto-label t) + ("fnprompt" org-footnote-auto-label nil) + ("fnconfirm" org-footnote-auto-label confirm) + ("fnplain" org-footnote-auto-label plain) + ("fnadjust" org-footnote-auto-adjust t) + ("nofnadjust" org-footnote-auto-adjust nil) + ("constcgs" constants-unit-system cgs) + ("constSI" constants-unit-system SI) + ("noptag" org-tag-persistent-alist nil) + ("hideblocks" org-hide-block-startup t) + ("nohideblocks" org-hide-block-startup nil) + ("beamer" org-startup-with-beamer-mode t) + ("entitiespretty" org-pretty-entities t) + ("entitiesplain" org-pretty-entities nil)) + "Variable associated with STARTUP options for Org. +Each element is a list of three items: the startup options (as written +in the #+STARTUP line), the corresponding variable, and the value to set +this variable to if the option is found. An optional forth element PUSH +means to push this value onto the list in the variable.") + +(defcustom org-group-tags t + "When non-nil (the default), use group tags. +This can be turned on/off through `org-toggle-tags-groups'." + :group 'org-tags + :group 'org-startup + :type 'boolean) + +(defvar org-inhibit-startup nil) ; Dynamically-scoped param. + +(defun org-toggle-tags-groups () + "Toggle support for group tags. +Support for group tags is controlled by the option +`org-group-tags', which is non-nil by default." + (interactive) + (setq org-group-tags (not org-group-tags)) + (cond ((and (derived-mode-p 'org-agenda-mode) + org-group-tags) + (org-agenda-redo)) + ((derived-mode-p 'org-mode) + (let ((org-inhibit-startup t)) (org-mode)))) + (message "Groups tags support has been turned %s" + (if org-group-tags "on" "off"))) + +(defun org--tag-add-to-alist (alist1 alist2) + "Merge tags from ALIST1 into ALIST2. + +Duplicates tags outside a group are removed. Keywords and order +are preserved. + +The function assumes ALIST1 and ALIST2 are proper tag alists. +See `org-tag-alist' for their structure." + (cond + ((null alist2) alist1) + ((null alist1) alist2) + (t + (let ((to-add nil) + (group-flag nil)) + (dolist (tag-pair alist1) + (pcase tag-pair + (`(,(or :startgrouptag :startgroup)) + (setq group-flag t) + (push tag-pair to-add)) + (`(,(or :endgrouptag :endgroup)) + (setq group-flag nil) + (push tag-pair to-add)) + (`(,(or :grouptags :newline)) + (push tag-pair to-add)) + (`(,tag . ,_) + ;; Remove duplicates from ALIST1, unless they are in + ;; a group. Indeed, it makes sense to have a tag appear in + ;; multiple groups. + (when (or group-flag (not (assoc tag alist2))) + (push tag-pair to-add))) + (_ (error "Invalid association in tag alist: %S" tag-pair)))) + ;; Preserve order of ALIST1. + (append (nreverse to-add) alist2))))) + +(defun org-set-regexps-and-options (&optional tags-only) + "Precompute regular expressions used in the current buffer. +When optional argument TAGS-ONLY is non-nil, only compute tags +related expressions." + (when (derived-mode-p 'org-mode) + (let ((alist (org--setup-collect-keywords + (org-make-options-regexp + (append '("FILETAGS" "TAGS" "SETUPFILE") + (and (not tags-only) + '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS" + "LINK" "OPTIONS" "PRIORITIES" "PROPERTY" + "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO"))))))) + ;; Startup options. Get this early since it does change + ;; behavior for other options (e.g., tags). + (let ((startup (cdr (assq 'startup alist)))) + (dolist (option startup) + (let ((entry (assoc-string option org-startup-options t))) + (when entry + (let ((var (nth 1 entry)) + (val (nth 2 entry))) + (if (not (nth 3 entry)) (set (make-local-variable var) val) + (unless (listp (symbol-value var)) + (set (make-local-variable var) nil)) + (add-to-list var val))))))) + (setq-local org-file-tags + (mapcar #'org-add-prop-inherited + (cdr (assq 'filetags alist)))) + (setq org-current-tag-alist + (org--tag-add-to-alist + org-tag-persistent-alist + (let ((tags (cdr (assq 'tags alist)))) + (if tags (org-tag-string-to-alist tags) + org-tag-alist)))) + (setq org-tag-groups-alist + (org-tag-alist-to-groups org-current-tag-alist)) + (unless tags-only + ;; File properties. + (setq-local org-file-properties (cdr (assq 'property alist))) + ;; Archive location. + (let ((archive (cdr (assq 'archive alist)))) + (when archive (setq-local org-archive-location archive))) + ;; Category. + (let ((cat (org-string-nw-p (cdr (assq 'category alist))))) + (when cat + (setq-local org-category (intern cat)) + (setq-local org-file-properties + (org--update-property-plist + "CATEGORY" cat org-file-properties)))) + ;; Columns. + (let ((column (cdr (assq 'columns alist)))) + (when column (setq-local org-columns-default-format column))) + ;; Constants. + (setq org-table-formula-constants-local (cdr (assq 'constants alist))) + ;; Link abbreviations. + (let ((links (cdr (assq 'link alist)))) + (when links (setq org-link-abbrev-alist-local (nreverse links)))) + ;; Priorities. + (let ((priorities (cdr (assq 'priorities alist)))) + (when priorities + (setq-local org-highest-priority (nth 0 priorities)) + (setq-local org-lowest-priority (nth 1 priorities)) + (setq-local org-default-priority (nth 2 priorities)))) + ;; Scripts. + (let ((scripts (assq 'scripts alist))) + (when scripts + (setq-local org-use-sub-superscripts (cdr scripts)))) + ;; TODO keywords. + (setq-local org-todo-kwd-alist nil) + (setq-local org-todo-key-alist nil) + (setq-local org-todo-key-trigger nil) + (setq-local org-todo-keywords-1 nil) + (setq-local org-done-keywords nil) + (setq-local org-todo-heads nil) + (setq-local org-todo-sets nil) + (setq-local org-todo-log-states nil) + (let ((todo-sequences + (or (nreverse (cdr (assq 'todo alist))) + (let ((d (default-value 'org-todo-keywords))) + (if (not (stringp (car d))) d + ;; XXX: Backward compatibility code. + (list (cons org-todo-interpretation d))))))) + (dolist (sequence todo-sequences) + (let* ((sequence (or (run-hook-with-args-until-success + 'org-todo-setup-filter-hook sequence) + sequence)) + (sequence-type (car sequence)) + (keywords (cdr sequence)) + (sep (member "|" keywords)) + names alist) + (dolist (k (remove "|" keywords)) + (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" + k) + (error "Invalid TODO keyword %s" k)) + (let ((name (match-string 1 k)) + (key (match-string 2 k)) + (log (org-extract-log-state-settings k))) + (push name names) + (push (cons name (and key (string-to-char key))) alist) + (when log (push log org-todo-log-states)))) + (let* ((names (nreverse names)) + (done (if sep (org-remove-keyword-keys (cdr sep)) + (last names))) + (head (car names)) + (tail (list sequence-type head (car done) (org-last done)))) + (add-to-list 'org-todo-heads head 'append) + (push names org-todo-sets) + (setq org-done-keywords (append org-done-keywords done nil)) + (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil)) + (setq org-todo-key-alist + (append org-todo-key-alist + (and alist + (append '((:startgroup)) + (nreverse alist) + '((:endgroup)))))) + (dolist (k names) (push (cons k tail) org-todo-kwd-alist)))))) + (setq org-todo-sets (nreverse org-todo-sets) + org-todo-kwd-alist (nreverse org-todo-kwd-alist) + org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist)) + org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)) + ;; Compute the regular expressions and other local variables. + ;; Using `org-outline-regexp-bol' would complicate them much, + ;; because of the fixed white space at the end of that string. + (unless org-done-keywords + (setq org-done-keywords + (and org-todo-keywords-1 (last org-todo-keywords-1)))) + (setq org-not-done-keywords + (org-delete-all org-done-keywords + (copy-sequence org-todo-keywords-1)) + org-todo-regexp (regexp-opt org-todo-keywords-1 t) + org-not-done-regexp (regexp-opt org-not-done-keywords t) + org-not-done-heading-regexp + (format org-heading-keyword-regexp-format org-not-done-regexp) + org-todo-line-regexp + (format org-heading-keyword-maybe-regexp-format org-todo-regexp) + org-complex-heading-regexp + (concat "^\\(\\*+\\)" + "\\(?: +" org-todo-regexp "\\)?" + "\\(?: +\\(\\[#.\\]\\)\\)?" + "\\(?: +\\(.*?\\)\\)??" + "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?" + "[ \t]*$") + org-complex-heading-regexp-format + (concat "^\\(\\*+\\)" + "\\(?: +" org-todo-regexp "\\)?" + "\\(?: +\\(\\[#.\\]\\)\\)?" + "\\(?: +" + ;; Stats cookies can be stuck to body. + "\\(?:\\[[0-9%%/]+\\] *\\)*" + "\\(%s\\)" + "\\(?: *\\[[0-9%%/]+\\]\\)*" + "\\)" + "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?" + "[ \t]*$") + org-todo-line-tags-regexp + (concat "^\\(\\*+\\)" + "\\(?: +" org-todo-regexp "\\)?" + "\\(?: +\\(.*?\\)\\)??" + "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?" + "[ \t]*$")) + (org-compute-latex-and-related-regexp))))) + +(defun org--setup-collect-keywords (regexp &optional files alist) + "Return setup keywords values as an alist. + +REGEXP matches a subset of setup keywords. FILES is a list of +file names already visited. It is used to avoid circular setup +files. ALIST, when non-nil, is the alist computed so far. + +Return value contains the following keys: `archive', `category', +`columns', `constants', `filetags', `link', `priorities', +`property', `scripts', `startup', `tags' and `todo'." + (org-with-wide-buffer + (goto-char (point-min)) + (let ((case-fold-search t)) + (while (re-search-forward regexp nil t) + (let ((element (org-element-at-point))) + (when (eq (org-element-type element) 'keyword) + (let ((key (org-element-property :key element)) + (value (org-element-property :value element))) + (cond + ((equal key "ARCHIVE") + (when (org-string-nw-p value) + (push (cons 'archive value) alist))) + ((equal key "CATEGORY") (push (cons 'category value) alist)) + ((equal key "COLUMNS") (push (cons 'columns value) alist)) + ((equal key "CONSTANTS") + (let* ((constants (assq 'constants alist)) + (store (cdr constants))) + (dolist (pair (split-string value)) + (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" + pair) + (let* ((name (match-string 1 pair)) + (value (match-string 2 pair)) + (old (assoc name store))) + (if old (setcdr old value) + (push (cons name value) store))))) + (if constants (setcdr constants store) + (push (cons 'constants store) alist)))) + ((equal key "FILETAGS") + (when (org-string-nw-p value) + (let ((old (assq 'filetags alist)) + (new (apply #'nconc + (mapcar (lambda (x) (org-split-string x ":")) + (split-string value))))) + (if old (setcdr old (append new (cdr old))) + (push (cons 'filetags new) alist))))) + ((equal key "LINK") + (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value) + (let ((links (assq 'link alist)) + (pair (cons (match-string-no-properties 1 value) + (match-string-no-properties 2 value)))) + (if links (push pair (cdr links)) + (push (list 'link pair) alist))))) + ((equal key "OPTIONS") + (when (and (org-string-nw-p value) + (string-match "\\^:\\(t\\|nil\\|{}\\)" value)) + (push (cons 'scripts (read (match-string 1 value))) alist))) + ((equal key "PRIORITIES") + (push (cons 'priorities + (let ((prio (split-string value))) + (if (< (length prio) 3) '(?A ?C ?B) + (mapcar #'string-to-char prio)))) + alist)) + ((equal key "PROPERTY") + (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value) + (let* ((property (assq 'property alist)) + (value (org--update-property-plist + (match-string-no-properties 1 value) + (match-string-no-properties 2 value) + (cdr property)))) + (if property (setcdr property value) + (push (cons 'property value) alist))))) + ((equal key "STARTUP") + (let ((startup (assq 'startup alist))) + (if startup + (setcdr startup + (append (cdr startup) (split-string value))) + (push (cons 'startup (split-string value)) alist)))) + ((equal key "TAGS") + (let ((tag-cell (assq 'tags alist))) + (if tag-cell + (setcdr tag-cell (concat (cdr tag-cell) "\n" value)) + (push (cons 'tags value) alist)))) + ((member key '("TODO" "SEQ_TODO" "TYP_TODO")) + (let ((todo (assq 'todo alist)) + (value (cons (if (equal key "TYP_TODO") 'type 'sequence) + (split-string value)))) + (if todo (push value (cdr todo)) + (push (list 'todo value) alist)))) + ((equal key "SETUPFILE") + (unless buffer-read-only ; Do not check in Gnus messages. + (let ((f (and (org-string-nw-p value) + (expand-file-name + (org-unbracket-string "\"" "\"" value))))) + (when (and f (file-readable-p f) (not (member f files))) + (with-temp-buffer + (setq default-directory (file-name-directory f)) + (insert-file-contents f) + (setq alist + ;; Fake Org mode to benefit from cache + ;; without recurring needlessly. + (let ((major-mode 'org-mode)) + (org--setup-collect-keywords + regexp (cons f files) alist))))))))))))))) + alist) + +(defun org-tag-string-to-alist (s) + "Return tag alist associated to string S. +S is a value for TAGS keyword or produced with +`org-tag-alist-to-string'. Return value is an alist suitable for +`org-tag-alist' or `org-tag-persistent-alist'." + (let ((lines (mapcar #'split-string (split-string s "\n" t))) + (tag-re (concat "\\`\\([[:alnum:]_@#%]+" + "\\|{.+?}\\)" ; regular expression + "\\(?:(\\(.\\))\\)?\\'")) + alist group-flag) + (dolist (tokens lines (cdr (nreverse alist))) + (push '(:newline) alist) + (while tokens + (let ((token (pop tokens))) + (pcase token + ("{" + (push '(:startgroup) alist) + (when (equal (nth 1 tokens) ":") (setq group-flag t))) + ("}" + (push '(:endgroup) alist) + (setq group-flag nil)) + ("[" + (push '(:startgrouptag) alist) + (when (equal (nth 1 tokens) ":") (setq group-flag t))) + ("]" + (push '(:endgrouptag) alist) + (setq group-flag nil)) + (":" + (push '(:grouptags) alist)) + ((guard (string-match tag-re token)) + (let ((tag (match-string 1 token)) + (key (and (match-beginning 2) + (string-to-char (match-string 2 token))))) + ;; Push all tags in groups, no matter if they already + ;; appear somewhere else in the list. + (when (or group-flag (not (assoc tag alist))) + (push (cons tag key) alist)))))))))) + +(defun org-tag-alist-to-string (alist &optional skip-key) + "Return tag string associated to ALIST. + +ALIST is an alist, as defined in `org-tag-alist' or +`org-tag-persistent-alist', or produced with +`org-tag-string-to-alist'. + +Return value is a string suitable as a value for \"TAGS\" +keyword. + +When optional argument SKIP-KEY is non-nil, skip selection keys +next to tags." + (mapconcat (lambda (token) + (pcase token + (`(:startgroup) "{") + (`(:endgroup) "}") + (`(:startgrouptag) "[") + (`(:endgrouptag) "]") + (`(:grouptags) ":") + (`(:newline) "\\n") + ((and + (guard (not skip-key)) + `(,(and tag (pred stringp)) . ,(and key (pred characterp)))) + (format "%s(%c)" tag key)) + (`(,(and tag (pred stringp)) . ,_) tag) + (_ (user-error "Invalid tag token: %S" token)))) + alist + " ")) + +(defun org-tag-alist-to-groups (alist) + "Return group alist from tag ALIST. +ALIST is an alist, as defined in `org-tag-alist' or +`org-tag-persistent-alist', or produced with +`org-tag-string-to-alist'. Return value is an alist following +the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as +a string, summarizing TAGS, as a list of strings." + (let (groups group-status current-group) + (dolist (token alist (nreverse groups)) + (pcase token + (`(,(or :startgroup :startgrouptag)) (setq group-status t)) + (`(,(or :endgroup :endgrouptag)) + (when (eq group-status 'append) + (push (nreverse current-group) groups)) + (setq group-status nil current-group nil)) + (`(:grouptags) (setq group-status 'append)) + ((and `(,tag . ,_) (guard group-status)) + (if (eq group-status 'append) (push tag current-group) + (setq current-group (list tag)))) + (_ nil))))) + +(defvar org--file-cache (make-hash-table :test #'equal) + "Hash table to store contents of files referenced via a URL. +This is the cache of file URLs read using `org-file-contents'.") + +(defun org-reset-file-cache () + "Reset the cache of files downloaded by `org-file-contents'." + (clrhash org--file-cache)) + +(defun org-file-url-p (file) + "Non-nil if FILE is a URL." + (require 'ffap) + (string-match-p ffap-url-regexp file)) + +(defun org-file-contents (file &optional noerror nocache) + "Return the contents of FILE, as a string. + +FILE can be a file name or URL. + +If FILE is a URL, download the contents. If the URL contents are +already cached in the `org--file-cache' hash table, the download step +is skipped. + +If NOERROR is non-nil, ignore the error when unable to read the FILE +from file or URL. + +If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version +is available. This option applies only if FILE is a URL." + (let* ((is-url (org-file-url-p file)) + (cache (and is-url + (not nocache) + (gethash file org--file-cache)))) + (cond + (cache) + (is-url + (with-current-buffer (url-retrieve-synchronously file) + (goto-char (point-min)) + ;; Move point to after the url-retrieve header. + (search-forward "\n\n" nil :move) + ;; Search for the success code only in the url-retrieve header. + (if (save-excursion + (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror)) + ;; Update the cache `org--file-cache' and return contents. + (puthash file + (buffer-substring-no-properties (point) (point-max)) + org--file-cache) + (funcall (if noerror #'message #'user-error) + "Unable to fetch file from %S" + file)))) + (t + (with-temp-buffer + (condition-case nil + (progn + (insert-file-contents file) + (buffer-string)) + (file-error + (funcall (if noerror #'message #'user-error) + "Unable to read file %S" + file)))))))) + +(defun org-extract-log-state-settings (x) + "Extract the log state setting from a TODO keyword string. +This will extract info from a string like \"WAIT(w@/!)\"." + (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x) + (let ((kw (match-string 1 x)) + (log1 (and (match-end 3) (match-string 3 x))) + (log2 (and (match-end 4) (match-string 4 x)))) + (and (or log1 log2) + (list kw + (and log1 (if (equal log1 "!") 'time 'note)) + (and log2 (if (equal log2 "!") 'time 'note))))))) + +(defun org-remove-keyword-keys (list) + "Remove a pair of parenthesis at the end of each string in LIST." + (mapcar (lambda (x) + (if (string-match "(.*)$" x) + (substring x 0 (match-beginning 0)) + x)) + list)) + +(defun org-assign-fast-keys (alist) + "Assign fast keys to a keyword-key alist. +Respect keys that are already there." + (let (new e (alt ?0)) + (while (setq e (pop alist)) + (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup)) + (cdr e)) ;; Key already assigned. + (push e new) + (let ((clist (string-to-list (downcase (car e)))) + (used (append new alist))) + (when (= (car clist) ?@) + (pop clist)) + (while (and clist (rassoc (car clist) used)) + (pop clist)) + (unless clist + (while (rassoc alt used) + (cl-incf alt))) + (push (cons (car e) (or (car clist) alt)) new)))) + (nreverse new))) + +;;; Some variables used in various places + +(defvar org-window-configuration nil + "Used in various places to store a window configuration.") +(defvar org-selected-window nil + "Used in various places to store a window configuration.") +(defvar org-finish-function nil + "Function to be called when `C-c C-c' is used. +This is for getting out of special buffers like capture.") +(defvar org-last-state) + +;; Defined somewhere in this file, but used before definition. +(defvar org-entities) ;; defined in org-entities.el +(defvar org-struct-menu) +(defvar org-org-menu) +(defvar org-tbl-menu) + +;;;; Define the Org mode + +;; We use a before-change function to check if a table might need +;; an update. +(defvar org-table-may-need-update t + "Indicates that a table might need an update. +This variable is set by `org-before-change-function'. +`org-table-align' sets it back to nil.") +(defun org-before-change-function (_beg _end) + "Every change indicates that a table might need an update." + (setq org-table-may-need-update t)) +(defvar org-mode-map) +(defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param. +(defvar org-agenda-keep-modes nil) ; Dynamically-scoped param. +(defvar org-inhibit-logging nil) ; Dynamically-scoped param. +(defvar org-inhibit-blocking nil) ; Dynamically-scoped param. +(defvar org-table-buffer-is-an nil) + +(defvar bidi-paragraph-direction) +(defvar buffer-face-mode-face) + +(require 'outline) + +;; Other stuff we need. +(require 'time-date) +(unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time)) +(require 'easymenu) +(autoload 'easy-menu-add "easymenu") +(require 'overlay) + +;; (require 'org-macs) moved higher up in the file before it is first used +(require 'org-entities) +;; (require 'org-compat) moved higher up in the file before it is first used +(require 'org-faces) +(require 'org-list) +(require 'org-pcomplete) +(require 'org-src) +(require 'org-footnote) +(require 'org-macro) + +;; babel +(require 'ob) + +;;;###autoload +(define-derived-mode org-mode outline-mode "Org" + "Outline-based notes management and organizer, alias +\"Carsten's outline-mode for keeping track of everything.\" + +Org mode develops organizational tasks around a NOTES file which +contains information about projects as plain text. Org mode is +implemented on top of Outline mode, which is ideal to keep the content +of large files well structured. It supports ToDo items, deadlines and +time stamps, which magically appear in the diary listing of the Emacs +calendar. Tables are easily created with a built-in table editor. +Plain text URL-like links connect to websites, emails (VM), Usenet +messages (Gnus), BBDB entries, and any files related to the project. +For printing and sharing of notes, an Org file (or a part of it) +can be exported as a structured ASCII or HTML file. + +The following commands are available: + +\\{org-mode-map}" + + ;; Get rid of Outline menus, they are not needed + ;; Need to do this here because define-derived-mode sets up + ;; the keymap so late. Still, it is a waste to call this each time + ;; we switch another buffer into Org mode. + (define-key org-mode-map [menu-bar headings] 'undefined) + (define-key org-mode-map [menu-bar hide] 'undefined) + (define-key org-mode-map [menu-bar show] 'undefined) + + (org-load-modules-maybe) + (org-install-agenda-files-menu) + (when org-descriptive-links (add-to-invisibility-spec '(org-link))) + (add-to-invisibility-spec '(org-cwidth)) + (add-to-invisibility-spec '(org-hide-block . t)) + (setq-local outline-regexp org-outline-regexp) + (setq-local outline-level 'org-outline-level) + (setq bidi-paragraph-direction 'left-to-right) + (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis))) + (unless org-display-table + (setq org-display-table (make-display-table))) + (set-display-table-slot + org-display-table 4 + (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis)) + org-ellipsis))) + (setq buffer-display-table org-display-table)) + (org-set-regexps-and-options) + (org-set-font-lock-defaults) + (when (and org-tag-faces (not org-tags-special-faces-re)) + ;; tag faces set outside customize.... force initialization. + (org-set-tag-faces 'org-tag-faces org-tag-faces)) + ;; Calc embedded + (setq-local calc-embedded-open-mode "# ") + ;; Modify a few syntax entries + (modify-syntax-entry ?@ "w") + (modify-syntax-entry ?\" "\"") + (modify-syntax-entry ?\\ "_") + (modify-syntax-entry ?~ "_") + (setq-local font-lock-unfontify-region-function 'org-unfontify-region) + ;; Activate before-change-function + (setq-local org-table-may-need-update t) + (add-hook 'before-change-functions 'org-before-change-function nil 'local) + ;; Check for running clock before killing a buffer + (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local) + ;; Initialize macros templates. + (org-macro-initialize-templates) + ;; Initialize radio targets. + (org-update-radio-target-regexp) + ;; Indentation. + (setq-local indent-line-function 'org-indent-line) + (setq-local indent-region-function 'org-indent-region) + ;; Filling and auto-filling. + (org-setup-filling) + ;; Comments. + (org-setup-comments-handling) + ;; Initialize cache. + (org-element-cache-reset) + ;; Beginning/end of defun + (setq-local beginning-of-defun-function 'org-backward-element) + (setq-local end-of-defun-function + (lambda () + (if (not (org-at-heading-p)) + (org-forward-element) + (org-forward-element) + (forward-char -1)))) + ;; Next error for sparse trees + (setq-local next-error-function 'org-occur-next-match) + ;; Make sure dependence stuff works reliably, even for users who set it + ;; too late :-( + (if org-enforce-todo-dependencies + (add-hook 'org-blocker-hook + 'org-block-todo-from-children-or-siblings-or-parent) + (remove-hook 'org-blocker-hook + 'org-block-todo-from-children-or-siblings-or-parent)) + (if org-enforce-todo-checkbox-dependencies + (add-hook 'org-blocker-hook + 'org-block-todo-from-checkboxes) + (remove-hook 'org-blocker-hook + 'org-block-todo-from-checkboxes)) + + ;; Align options lines + (setq-local + align-mode-rules-list + '((org-in-buffer-settings + (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+") + (modes . '(org-mode))))) + + ;; Imenu + (setq-local imenu-create-index-function 'org-imenu-get-tree) + + ;; Make isearch reveal context + (setq-local outline-isearch-open-invisible-function + (lambda (&rest _) (org-show-context 'isearch))) + + ;; Setup the pcomplete hooks + (setq-local pcomplete-command-completion-function 'org-pcomplete-initial) + (setq-local pcomplete-command-name-function 'org-command-at-point) + (setq-local pcomplete-default-completion-function 'ignore) + (setq-local pcomplete-parse-arguments-function 'org-parse-arguments) + (setq-local pcomplete-termination-string "") + (setq-local buffer-face-mode-face 'org-default) + + ;; If empty file that did not turn on Org mode automatically, make + ;; it to. + (when (and org-insert-mode-line-in-empty-file + (called-interactively-p 'any) + (= (point-min) (point-max))) + (insert "# -*- mode: org -*-\n\n")) + (unless org-inhibit-startup + (org-unmodified + (when org-startup-with-beamer-mode (org-beamer-mode)) + (when org-startup-align-all-tables + (org-table-map-tables #'org-table-align t)) + (when org-startup-with-inline-images (org-display-inline-images)) + (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16))) + (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility)) + (when org-startup-truncated (setq truncate-lines t)) + (when org-startup-indented (require 'org-indent) (org-indent-mode 1)) + (org-refresh-effort-properties))) + ;; Try to set `org-hide' face correctly. + (let ((foreground (org-find-invisible-foreground))) + (when foreground + (set-face-foreground 'org-hide foreground)))) + +;; Update `customize-package-emacs-version-alist' +(add-to-list 'customize-package-emacs-version-alist + '(Org ("8.0" . "24.4") + ("8.1" . "24.4") + ("8.2" . "24.4") + ("8.2.7" . "24.4") + ("8.3" . "26.1") + ("9.0" . "26.1") + ("9.1" . "26.1"))) + +(defvar org-mode-transpose-word-syntax-table + (let ((st (make-syntax-table text-mode-syntax-table))) + (dolist (c org-emphasis-alist st) + (modify-syntax-entry (string-to-char (car c)) "w p" st)))) + +(when (fboundp 'abbrev-table-put) + (abbrev-table-put org-mode-abbrev-table + :parents (list text-mode-abbrev-table))) + +(defun org-find-invisible-foreground () + (let ((candidates (remove + "unspecified-bg" + (nconc + (list (face-background 'default) + (face-background 'org-default)) + (mapcar + (lambda (alist) + (when (boundp alist) + (cdr (assq 'background-color (symbol-value alist))))) + '(default-frame-alist initial-frame-alist window-system-default-frame-alist)) + (list (face-foreground 'org-hide)))))) + (car (remove nil candidates)))) + +(defun org-current-time (&optional rounding-minutes past) + "Current time, possibly rounded to ROUNDING-MINUTES. +When ROUNDING-MINUTES is not an integer, fall back on the car of +`org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure +the rounding returns a past time." + (let ((r (or (and (integerp rounding-minutes) rounding-minutes) + (car org-time-stamp-rounding-minutes))) + (time (decode-time)) res) + (if (< r 1) + (current-time) + (setq res + (apply 'encode-time + (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r))))) + (nthcdr 2 time)))) + (if (and past (< (float-time (time-subtract (current-time) res)) 0)) + (seconds-to-time (- (float-time res) (* r 60))) + res)))) + +(defun org-today () + "Return today date, considering `org-extend-today-until'." + (time-to-days + (time-subtract (current-time) + (list 0 (* 3600 org-extend-today-until) 0)))) + +;;;; Font-Lock stuff, including the activators + +(defvar org-mouse-map (make-sparse-keymap)) +(org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse) +(org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse) +(when org-mouse-1-follows-link + (org-defkey org-mouse-map [follow-link] 'mouse-face)) +(when org-tab-follows-link + (org-defkey org-mouse-map [(tab)] 'org-open-at-point) + (org-defkey org-mouse-map "\C-i" 'org-open-at-point)) + +(require 'font-lock) + +(defconst org-non-link-chars "]\t\n\r<>") +(defvar org-link-types-re nil + "Matches a link that has a url-like prefix like \"http:\"") +(defvar org-link-re-with-space nil + "Matches a link with spaces, optional angular brackets around it.") +(defvar org-link-re-with-space2 nil + "Matches a link with spaces, optional angular brackets around it.") +(defvar org-link-re-with-space3 nil + "Matches a link with spaces, only for internal part in bracket links.") +(defvar org-angle-link-re nil + "Matches link with angular brackets, spaces are allowed.") +(defvar org-plain-link-re nil + "Matches plain link, without spaces.") +(defvar org-bracket-link-regexp nil + "Matches a link in double brackets.") +(defvar org-bracket-link-analytic-regexp nil + "Regular expression used to analyze links. +Here is what the match groups contain after a match: +1: http: +2: http +3: path +4: [desc] +5: desc") +(defvar org-bracket-link-analytic-regexp++ nil + "Like `org-bracket-link-analytic-regexp', but include coderef internal type.") +(defvar org-any-link-re nil + "Regular expression matching any link.") + +(defconst org-match-sexp-depth 3 + "Number of stacked braces for sub/superscript matching.") + +(defun org-create-multibrace-regexp (left right n) + "Create a regular expression which will match a balanced sexp. +Opening delimiter is LEFT, and closing delimiter is RIGHT, both given +as single character strings. +The regexp returned will match the entire expression including the +delimiters. It will also define a single group which contains the +match except for the outermost delimiters. The maximum depth of +stacked delimiters is N. Escaping delimiters is not possible." + (let* ((nothing (concat "[^" left right "]*?")) + (or "\\|") + (re nothing) + (next (concat "\\(?:" nothing left nothing right "\\)+" nothing))) + (while (> n 1) + (setq n (1- n) + re (concat re or next) + next (concat "\\(?:" nothing left next right "\\)+" nothing))) + (concat left "\\(" re "\\)" right))) + +(defconst org-match-substring-regexp + (concat + "\\(\\S-\\)\\([_^]\\)\\(" + "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)" + "\\|" + "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)" + "\\|" + "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)") + "The regular expression matching a sub- or superscript.") + +(defconst org-match-substring-with-braces-regexp + (concat + "\\(\\S-\\)\\([_^]\\)" + "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)") + "The regular expression matching a sub- or superscript, forcing braces.") + +(defun org-make-link-regexps () + "Update the link regular expressions. +This should be called after the variable `org-link-parameters' has changed." + (let ((types-re (regexp-opt (org-link-types) t))) + (setq org-link-types-re + (concat "\\`" types-re ":") + org-link-re-with-space + (concat "<?" types-re ":" + "\\([^" org-non-link-chars " ]" + "[^" org-non-link-chars "]*" + "[^" org-non-link-chars " ]\\)>?") + org-link-re-with-space2 + (concat "<?" types-re ":" + "\\([^" org-non-link-chars " ]" + "[^\t\n\r]*" + "[^" org-non-link-chars " ]\\)>?") + org-link-re-with-space3 + (concat "<?" types-re ":" + "\\([^" org-non-link-chars " ]" + "[^\t\n\r]*\\)") + org-angle-link-re + (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>" + types-re) + org-plain-link-re + (concat + "\\<" types-re ":" + "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)") + ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)") + org-bracket-link-regexp + "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]" + org-bracket-link-analytic-regexp + (concat + "\\[\\[" + "\\(" types-re ":\\)?" + "\\([^]]+\\)" + "\\]" + "\\(\\[" "\\([^]]+\\)" "\\]\\)?" + "\\]") + org-bracket-link-analytic-regexp++ + (concat + "\\[\\[" + "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?" + "\\([^]]+\\)" + "\\]" + "\\(\\[" "\\([^]]+\\)" "\\]\\)?" + "\\]") + org-any-link-re + (concat "\\(" org-bracket-link-regexp "\\)\\|\\(" + org-angle-link-re "\\)\\|\\(" + org-plain-link-re "\\)")))) + +(org-make-link-regexps) + +(defvar org-emph-face nil) + +(defun org-do-emphasis-faces (limit) + "Run through the buffer and emphasize strings." + (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)" + (car org-emphasis-regexp-components)))) + (catch :exit + (while (re-search-forward quick-re limit t) + (let* ((marker (match-string 2)) + (verbatim? (member marker '("~" "=")))) + (when (save-excursion + (goto-char (match-beginning 0)) + (and + ;; Do not match table hlines. + (not (and (equal marker "+") + (org-match-line + "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$"))) + ;; Do not match headline stars. Do not consider + ;; stars of a headline as closing marker for bold + ;; markup either. + (not (and (equal marker "*") + (save-excursion + (forward-char) + (skip-chars-backward "*") + (looking-at-p org-outline-regexp-bol)))) + ;; Match full emphasis markup regexp. + (looking-at (if verbatim? org-verbatim-re org-emph-re)) + ;; Do not span over paragraph boundaries. + (not (string-match-p org-element-paragraph-separate + (match-string 2))) + ;; Do not span over cells in table rows. + (not (and (save-match-data (org-match-line "[ \t]*|")) + (string-match-p "|" (match-string 4)))))) + (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))) + (font-lock-prepend-text-property + (match-beginning 2) (match-end 2) 'face face) + (when verbatim? + (org-remove-flyspell-overlays-in + (match-beginning 0) (match-end 0))) + (add-text-properties (match-beginning 2) (match-end 2) + '(font-lock-multiline t org-emphasis t)) + (when org-hide-emphasis-markers + (add-text-properties (match-end 4) (match-beginning 5) + '(invisible org-link)) + (add-text-properties (match-beginning 3) (match-end 3) + '(invisible org-link))) + (throw :exit t)))))))) + +(defun org-emphasize (&optional char) + "Insert or change an emphasis, i.e. a font like bold or italic. +If there is an active region, change that region to a new emphasis. +If there is no region, just insert the marker characters and position +the cursor between them. +CHAR should be the marker character. If it is a space, it means to +remove the emphasis of the selected region. +If CHAR is not given (for example in an interactive call) it will be +prompted for." + (interactive) + (let ((erc org-emphasis-regexp-components) + (string "") beg end move s) + (if (org-region-active-p) + (setq beg (region-beginning) + end (region-end) + string (buffer-substring beg end)) + (setq move t)) + + (unless char + (message "Emphasis marker or tag: [%s]" + (mapconcat #'car org-emphasis-alist "")) + (setq char (read-char-exclusive))) + (if (equal char ?\s) + (setq s "" + move nil) + (unless (assoc (char-to-string char) org-emphasis-alist) + (user-error "No such emphasis marker: \"%c\"" char)) + (setq s (char-to-string char))) + (while (and (> (length string) 1) + (equal (substring string 0 1) (substring string -1)) + (assoc (substring string 0 1) org-emphasis-alist)) + (setq string (substring string 1 -1))) + (setq string (concat s string s)) + (when beg (delete-region beg end)) + (unless (or (bolp) + (string-match (concat "[" (nth 0 erc) "\n]") + (char-to-string (char-before (point))))) + (insert " ")) + (unless (or (eobp) + (string-match (concat "[" (nth 1 erc) "\n]") + (char-to-string (char-after (point))))) + (insert " ") (backward-char 1)) + (insert string) + (and move (backward-char 1)))) + +(defconst org-nonsticky-props + '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link)) + +(defsubst org-rear-nonsticky-at (pos) + (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props))) + +(defun org-activate-links (limit) + "Add link properties to links. +This includes angle, plain, and bracket links." + (catch :exit + (while (re-search-forward org-any-link-re limit t) + (let* ((start (match-beginning 0)) + (end (match-end 0)) + (style (cond ((eq ?< (char-after start)) 'angle) + ((eq ?\[ (char-after (1+ start))) 'bracket) + (t 'plain)))) + (when (and (memq style org-highlight-links) + ;; Do not confuse plain links with tags. + (not (and (eq style 'plain) + (let ((face (get-text-property + (max (1- start) (point-min)) 'face))) + (if (consp face) (memq 'org-tag face) + (eq 'org-tag face)))))) + (let* ((link-object (save-excursion + (goto-char start) + (save-match-data (org-element-link-parser)))) + (link (org-element-property :raw-link link-object)) + (type (org-element-property :type link-object)) + (path (org-element-property :path link-object)) + (properties ;for link's visible part + (list + 'face (pcase (org-link-get-parameter type :face) + ((and (pred functionp) face) (funcall face path)) + ((and (pred facep) face) face) + ((and (pred consp) face) face) ;anonymous + (_ 'org-link)) + 'mouse-face (or (org-link-get-parameter type :mouse-face) + 'highlight) + 'keymap (or (org-link-get-parameter type :keymap) + org-mouse-map) + 'help-echo (pcase (org-link-get-parameter type :help-echo) + ((and (pred stringp) echo) echo) + ((and (pred functionp) echo) echo) + (_ (concat "LINK: " link))) + 'htmlize-link (pcase (org-link-get-parameter type + :htmlize-link) + ((and (pred functionp) f) (funcall f)) + (_ `(:uri ,link))) + 'font-lock-multiline t))) + (org-remove-flyspell-overlays-in start end) + (org-rear-nonsticky-at end) + (if (not (eq 'bracket style)) + (add-text-properties start end properties) + ;; Handle invisible parts in bracket links. + (remove-text-properties start end '(invisible nil)) + (let ((hidden + (append `(invisible + ,(or (org-link-get-parameter type :display) + 'org-link)) + properties)) + (visible-start (or (match-beginning 4) (match-beginning 2))) + (visible-end (or (match-end 4) (match-end 2)))) + (add-text-properties start visible-start hidden) + (add-text-properties visible-start visible-end properties) + (add-text-properties visible-end end hidden) + (org-rear-nonsticky-at visible-start) + (org-rear-nonsticky-at visible-end))) + (let ((f (org-link-get-parameter type :activate-func))) + (when (functionp f) + (funcall f start end path (eq style 'bracket)))) + (throw :exit t))))) ;signal success + nil)) + +(defun org-activate-code (limit) + (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t) + (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0)) + (remove-text-properties (match-beginning 0) (match-end 0) + '(display t invisible t intangible t)) + t)) + +(defcustom org-src-fontify-natively t + "When non-nil, fontify code in code blocks. +See also the `org-block' face." + :type 'boolean + :version "26.1" + :package-version '(Org . "8.3") + :group 'org-appearance + :group 'org-babel) + +(defcustom org-allow-promoting-top-level-subtree nil + "When non-nil, allow promoting a top level subtree. +The leading star of the top level headline will be replaced +by a #." + :type 'boolean + :version "24.1" + :group 'org-appearance) + +(defun org-fontify-meta-lines-and-blocks (limit) + (condition-case nil + (org-fontify-meta-lines-and-blocks-1 limit) + (error (message "Org mode fontification error in %S at %d" + (current-buffer) + (line-number-at-pos))))) + +(defun org-fontify-meta-lines-and-blocks-1 (limit) + "Fontify #+ lines and blocks." + (let ((case-fold-search t)) + (when (re-search-forward + "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)" + limit t) + (let ((beg (match-beginning 0)) + (block-start (match-end 0)) + (block-end nil) + (lang (match-string 7)) + (beg1 (line-beginning-position 2)) + (dc1 (downcase (match-string 2))) + (dc3 (downcase (match-string 3))) + end end1 quoting block-type) + (cond + ((and (match-end 4) (equal dc3 "+begin")) + ;; Truly a block + (setq block-type (downcase (match-string 5)) + quoting (member block-type org-protecting-blocks)) + (when (re-search-forward + (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*") + nil t) ;; on purpose, we look further than LIMIT + (setq end (min (point-max) (match-end 0)) + end1 (min (point-max) (1- (match-beginning 0)))) + (setq block-end (match-beginning 0)) + (when quoting + (org-remove-flyspell-overlays-in beg1 end1) + (remove-text-properties beg end + '(display t invisible t intangible t))) + (add-text-properties + beg end '(font-lock-fontified t font-lock-multiline t)) + (add-text-properties beg beg1 '(face org-meta-line)) + (org-remove-flyspell-overlays-in beg beg1) + (add-text-properties ; For end_src + end1 (min (point-max) (1+ end)) '(face org-meta-line)) + (org-remove-flyspell-overlays-in end1 end) + (cond + ((and lang (not (string= lang "")) org-src-fontify-natively) + (org-src-font-lock-fontify-block lang block-start block-end) + (add-text-properties beg1 block-end '(src-block t))) + (quoting + (add-text-properties beg1 (min (point-max) (1+ end1)) + (list 'face + (list :inherit + (let ((face-name + (intern (format "org-block-%s" lang)))) + (append (and (facep face-name) (list face-name)) + '(org-block))))))) ; end of source block + ((not org-fontify-quote-and-verse-blocks)) + ((string= block-type "quote") + (add-face-text-property + beg1 (min (point-max) (1+ end1)) 'org-quote t)) + ((string= block-type "verse") + (add-face-text-property + beg1 (min (point-max) (1+ end1)) 'org-verse t))) + (add-text-properties beg beg1 '(face org-block-begin-line)) + (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1)) + '(face org-block-end-line)) + t)) + ((member dc1 '("+title:" "+author:" "+email:" "+date:")) + (org-remove-flyspell-overlays-in + (match-beginning 0) + (if (equal "+title:" dc1) (match-end 2) (match-end 0))) + (add-text-properties + beg (match-end 3) + (if (member (intern (substring dc1 1 -1)) org-hidden-keywords) + '(font-lock-fontified t invisible t) + '(font-lock-fontified t face org-document-info-keyword))) + (add-text-properties + (match-beginning 6) (min (point-max) (1+ (match-end 6))) + (if (string-equal dc1 "+title:") + '(font-lock-fontified t face org-document-title) + '(font-lock-fontified t face org-document-info)))) + ((string-prefix-p "+caption" dc1) + (org-remove-flyspell-overlays-in (match-end 2) (match-end 0)) + (remove-text-properties (match-beginning 0) (match-end 0) + '(display t invisible t intangible t)) + ;; Handle short captions. + (save-excursion + (beginning-of-line) + (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*")) + (add-text-properties (line-beginning-position) (match-end 1) + '(font-lock-fontified t face org-meta-line)) + (add-text-properties (match-end 0) (line-end-position) + '(font-lock-fontified t face org-block)) + t) + ((member dc3 '(" " "")) + (org-remove-flyspell-overlays-in beg (match-end 0)) + (add-text-properties + beg (match-end 0) + '(font-lock-fontified t face font-lock-comment-face))) + (t ;; just any other in-buffer setting, but not indented + (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0)) + (remove-text-properties (match-beginning 0) (match-end 0) + '(display t invisible t intangible t)) + (add-text-properties beg (match-end 0) + '(font-lock-fontified t face org-meta-line)) + t)))))) + +(defun org-fontify-drawers (limit) + "Fontify drawers." + (when (re-search-forward org-drawer-regexp limit t) + (add-text-properties + (match-beginning 0) (match-end 0) + '(font-lock-fontified t face org-special-keyword)) + (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0)) + t)) + +(defun org-fontify-macros (limit) + "Fontify macros." + (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t) + (let ((begin (match-beginning 0)) + (opening-end (match-beginning 1))) + (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t) + (match-string 1)) + (let ((end (match-end 1)) + (closing-start (match-beginning 1))) + (add-text-properties + begin end + '(font-lock-multiline t font-lock-fontified t face org-macro)) + (org-remove-flyspell-overlays-in begin end) + (when org-hide-macro-markers + (add-text-properties begin opening-end '(invisible t)) + (add-text-properties closing-start end '(invisible t))) + t))))) + +(defun org-activate-footnote-links (limit) + "Add text properties for footnotes." + (let ((fn (org-footnote-next-reference-or-definition limit))) + (when fn + (let* ((beg (nth 1 fn)) + (end (nth 2 fn)) + (label (car fn)) + (referencep (/= (line-beginning-position) beg))) + (when (and referencep (nth 3 fn)) + (save-excursion + (goto-char beg) + (search-forward (or label "fn:")) + (org-remove-flyspell-overlays-in beg (match-end 0)))) + (add-text-properties beg end + (list 'mouse-face 'highlight + 'keymap org-mouse-map + 'help-echo + (if referencep "Footnote reference" + "Footnote definition") + 'font-lock-fontified t + 'font-lock-multiline t + 'face 'org-footnote)))))) + +(defun org-activate-dates (limit) + "Add text properties for dates." + (when (and (re-search-forward org-tsr-regexp-both limit t) + (not (equal (char-before (match-beginning 0)) 91))) + (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0)) + (add-text-properties (match-beginning 0) (match-end 0) + (list 'mouse-face 'highlight + 'keymap org-mouse-map)) + (org-rear-nonsticky-at (match-end 0)) + (when org-display-custom-times + ;; If it's a date range, activate custom time for second date. + (when (match-end 3) + (org-display-custom-time (match-beginning 3) (match-end 3))) + (org-display-custom-time (match-beginning 1) (match-end 1))) + t)) + +(defvar-local org-target-link-regexp nil + "Regular expression matching radio targets in plain text.") + +(defconst org-target-regexp (let ((border "[^<>\n\r \t]")) + (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>" + border border border)) + "Regular expression matching a link target.") + +(defconst org-radio-target-regexp (format "<%s>" org-target-regexp) + "Regular expression matching a radio target.") + +(defconst org-any-target-regexp + (format "%s\\|%s" org-radio-target-regexp org-target-regexp) + "Regular expression matching any target.") + +(defun org-activate-target-links (limit) + "Add text properties for target matches." + (when org-target-link-regexp + (let ((case-fold-search t)) + (when (re-search-forward org-target-link-regexp limit t) + (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1)) + (add-text-properties (match-beginning 1) (match-end 1) + (list 'mouse-face 'highlight + 'keymap org-mouse-map + 'help-echo "Radio target link" + 'org-linked-text t)) + (org-rear-nonsticky-at (match-end 1)) + t)))) + +(defun org-update-radio-target-regexp () + "Find all radio targets in this file and update the regular expression. +Also refresh fontification if needed." + (interactive) + (let ((old-regexp org-target-link-regexp) + (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(") + (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)") + (targets + (org-with-wide-buffer + (goto-char (point-min)) + (let (rtn) + (while (re-search-forward org-radio-target-regexp nil t) + ;; Make sure point is really within the object. + (backward-char) + (let ((obj (org-element-context))) + (when (eq (org-element-type obj) 'radio-target) + (cl-pushnew (org-element-property :value obj) rtn + :test #'equal)))) + rtn)))) + (setq org-target-link-regexp + (and targets + (concat before-re + (mapconcat + (lambda (x) + (replace-regexp-in-string + " +" "\\s-+" (regexp-quote x) t t)) + targets + "\\|") + after-re))) + (unless (equal old-regexp org-target-link-regexp) + ;; Clean-up cache. + (let ((regexp (cond ((not old-regexp) org-target-link-regexp) + ((not org-target-link-regexp) old-regexp) + (t + (concat before-re + (mapconcat + (lambda (re) + (substring re (length before-re) + (- (length after-re)))) + (list old-regexp org-target-link-regexp) + "\\|") + after-re))))) + (org-with-wide-buffer + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (org-element-cache-refresh (match-beginning 1))))) + ;; Re fontify buffer. + (when (memq 'radio org-highlight-links) + (org-restart-font-lock))))) + +(defun org-hide-wide-columns (limit) + (let (s e) + (setq s (text-property-any (point) (or limit (point-max)) + 'org-cwidth t)) + (when s + (setq e (next-single-property-change s 'org-cwidth)) + (add-text-properties s e '(invisible org-cwidth)) + (goto-char e) + t))) + +(defvar org-latex-and-related-regexp nil + "Regular expression for highlighting LaTeX, entities and sub/superscript.") + +(defun org-compute-latex-and-related-regexp () + "Compute regular expression for LaTeX, entities and sub/superscript. +Result depends on variable `org-highlight-latex-and-related'." + (setq-local + org-latex-and-related-regexp + (let* ((re-sub + (cond ((not (memq 'script org-highlight-latex-and-related)) nil) + ((eq org-use-sub-superscripts '{}) + (list org-match-substring-with-braces-regexp)) + (org-use-sub-superscripts (list org-match-substring-regexp)))) + (re-latex + (when (memq 'latex org-highlight-latex-and-related) + (let ((matchers (plist-get org-format-latex-options :matchers))) + (delq nil + (mapcar (lambda (x) + (and (member (car x) matchers) (nth 1 x))) + org-latex-regexps))))) + (re-entities + (when (memq 'entities org-highlight-latex-and-related) + (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)")))) + (mapconcat 'identity (append re-latex re-entities re-sub) "\\|")))) + +(defun org-do-latex-and-related (limit) + "Highlight LaTeX snippets and environments, entities and sub/superscript. +LIMIT bounds the search for syntax to highlight. Stop at first +highlighted object, if any. Return t if some highlighting was +done, nil otherwise." + (when (org-string-nw-p org-latex-and-related-regexp) + (catch 'found + (while (re-search-forward org-latex-and-related-regexp limit t) + (unless + (cl-some + (lambda (f) + (memq f '(org-code org-verbatim underline org-special-keyword))) + (save-excursion + (goto-char (1+ (match-beginning 0))) + (face-at-point nil t))) + (let ((offset (if (memq (char-after (1+ (match-beginning 0))) + '(?_ ?^)) + 1 + 0))) + (font-lock-prepend-text-property + (+ offset (match-beginning 0)) (match-end 0) + 'face 'org-latex-and-related) + (add-text-properties (+ offset (match-beginning 0)) (match-end 0) + '(font-lock-multiline t))) + (throw 'found t))) + nil))) + +(defun org-restart-font-lock () + "Restart `font-lock-mode', to force refontification." + (when (and (boundp 'font-lock-mode) font-lock-mode) + (font-lock-mode -1) + (font-lock-mode 1))) + +(defun org-activate-tags (limit) + (when (re-search-forward + "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t) + (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1)) + (add-text-properties (match-beginning 1) (match-end 1) + (list 'mouse-face 'highlight + 'keymap org-mouse-map)) + (org-rear-nonsticky-at (match-end 1)) + t)) + +(defun org-outline-level () + "Compute the outline level of the heading at point. + +If this is called at a normal headline, the level is the number +of stars. Use `org-reduced-level' to remove the effect of +`org-odd-levels'. Unlike to `org-current-level', this function +takes into consideration inlinetasks." + (org-with-wide-buffer + (end-of-line) + (if (re-search-backward org-outline-regexp-bol nil t) + (1- (- (match-end 0) (match-beginning 0))) + 0))) + +(defvar org-font-lock-keywords nil) + +(defsubst org-re-property (property &optional literal allow-null value) + "Return a regexp matching a PROPERTY line. + +When optional argument LITERAL is non-nil, do not quote PROPERTY. +This is useful when PROPERTY is a regexp. When ALLOW-NULL is +non-nil, match properties even without a value. + +Match group 3 is set to the value when it exists. If there is no +value and ALLOW-NULL is non-nil, it is set to the empty string. + +With optional argument VALUE, match only property lines with +that value; in this case, ALLOW-NULL is ignored. VALUE is quoted +unless LITERAL is non-nil." + (concat + "^\\(?4:[ \t]*\\)" + (format "\\(?1::\\(?2:%s\\):\\)" + (if literal property (regexp-quote property))) + (cond (value + (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$" + (if literal value (regexp-quote value)))) + (allow-null + "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$") + (t + "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))) + +(defconst org-property-re + (org-re-property "\\S-+" 'literal t) + "Regular expression matching a property line. +There are four matching groups: +1: :PROPKEY: including the leading and trailing colon, +2: PROPKEY without the leading and trailing colon, +3: PROPVAL without leading or trailing spaces, +4: the indentation of the current line, +5: trailing whitespace.") + +(defvar org-font-lock-hook nil + "Functions to be called for special font lock stuff.") + +(defvar org-font-lock-extra-keywords nil) ;Dynamically scoped. + +(defvar org-font-lock-set-keywords-hook nil + "Functions that can manipulate `org-font-lock-extra-keywords'. +This is called after `org-font-lock-extra-keywords' is defined, but before +it is installed to be used by font lock. This can be useful if something +needs to be inserted at a specific position in the font-lock sequence.") + +(defun org-font-lock-hook (limit) + "Run `org-font-lock-hook' within LIMIT." + (run-hook-with-args 'org-font-lock-hook limit)) + +(defun org-set-font-lock-defaults () + "Set font lock defaults for the current buffer." + (let* ((em org-fontify-emphasized-text) + (lk org-highlight-links) + (org-font-lock-extra-keywords + (list + ;; Call the hook + '(org-font-lock-hook) + ;; Headlines + `(,(if org-fontify-whole-heading-line + "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)" + "^\\(\\**\\)\\(\\* \\)\\(.*\\)") + (1 (org-get-level-face 1)) + (2 (org-get-level-face 2)) + (3 (org-get-level-face 3))) + ;; Table lines + '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)" + (1 'org-table t)) + ;; Table internals + '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t)) + '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t)) + '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t)) + '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t)) + ;; Drawers + '(org-fontify-drawers) + ;; Properties + (list org-property-re + '(1 'org-special-keyword t) + '(3 'org-property-value t)) + ;; Link related fontification. + '(org-activate-links) + (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend))) + (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t))) + (when (memq 'date lk) '(org-activate-dates (0 'org-date t))) + (when (memq 'footnote lk) '(org-activate-footnote-links)) + ;; Targets. + (list org-any-target-regexp '(0 'org-target t)) + ;; Diary sexps. + '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t)) + ;; Macro + '(org-fontify-macros) + '(org-hide-wide-columns (0 nil append)) + ;; TODO keyword + (list (format org-heading-keyword-regexp-format + org-todo-regexp) + '(2 (org-get-todo-face 2) t)) + ;; DONE + (if org-fontify-done-headline + (list (format org-heading-keyword-regexp-format + (concat + "\\(?:" + (mapconcat 'regexp-quote org-done-keywords "\\|") + "\\)")) + '(2 'org-headline-done t)) + nil) + ;; Priorities + '(org-font-lock-add-priority-faces) + ;; Tags + '(org-font-lock-add-tag-faces) + ;; Tags groups + (when (and org-group-tags org-tag-groups-alist) + (list (concat org-outline-regexp-bol ".+\\(:" + (regexp-opt (mapcar 'car org-tag-groups-alist)) + ":\\).*$") + '(1 'org-tag-group prepend))) + ;; Special keywords + (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t)) + (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t)) + (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t)) + (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t)) + ;; Emphasis + (when em '(org-do-emphasis-faces)) + ;; Checkboxes + '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)" + 1 'org-checkbox prepend) + (when (cdr (assq 'checkbox org-list-automatic-rules)) + '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]" + (0 (org-get-checkbox-statistics-face) t))) + ;; Description list items + '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)" + 1 'org-list-dt prepend) + ;; ARCHIVEd headings + (list (concat + org-outline-regexp-bol + "\\(.*:" org-archive-tag ":.*\\)") + '(1 'org-archived prepend)) + ;; Specials + '(org-do-latex-and-related) + '(org-fontify-entities) + '(org-raise-scripts) + ;; Code + '(org-activate-code (1 'org-code t)) + ;; COMMENT + (list (format + "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)" + org-todo-regexp + org-comment-string) + '(9 'org-special-keyword t)) + ;; Blocks and meta lines + '(org-fontify-meta-lines-and-blocks)))) + (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords)) + (run-hooks 'org-font-lock-set-keywords-hook) + ;; Now set the full font-lock-keywords + (setq-local org-font-lock-keywords org-font-lock-extra-keywords) + (setq-local font-lock-defaults + '(org-font-lock-keywords t nil nil backward-paragraph)) + (kill-local-variable 'font-lock-keywords) + nil)) + +(defun org-toggle-pretty-entities () + "Toggle the composition display of entities as UTF8 characters." + (interactive) + (setq-local org-pretty-entities (not org-pretty-entities)) + (org-restart-font-lock) + (if org-pretty-entities + (message "Entities are now displayed as UTF8 characters") + (save-restriction + (widen) + (decompose-region (point-min) (point-max)) + (message "Entities are now displayed as plain text")))) + +(defvar-local org-custom-properties-overlays nil + "List of overlays used for custom properties.") + +(defun org-toggle-custom-properties-visibility () + "Display or hide properties in `org-custom-properties'." + (interactive) + (if org-custom-properties-overlays + (progn (mapc #'delete-overlay org-custom-properties-overlays) + (setq org-custom-properties-overlays nil)) + (when org-custom-properties + (org-with-wide-buffer + (goto-char (point-min)) + (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t))) + (while (re-search-forward regexp nil t) + (let ((end (cdr (save-match-data (org-get-property-block))))) + (when (and end (< (point) end)) + ;; Hide first custom property in current drawer. + (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0))))) + (overlay-put o 'invisible t) + (overlay-put o 'org-custom-property t) + (push o org-custom-properties-overlays)) + ;; Hide additional custom properties in the same drawer. + (while (re-search-forward regexp end t) + (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0))))) + (overlay-put o 'invisible t) + (overlay-put o 'org-custom-property t) + (push o org-custom-properties-overlays))))) + ;; Each entry is limited to a single property drawer. + (outline-next-heading))))))) + +(defun org-fontify-entities (limit) + "Find an entity to fontify." + (let (ee) + (when org-pretty-entities + (catch 'match + ;; "\_ "-family is left out on purpose. Only the first one, + ;; i.e., "\_ ", could be fontified anyway, and it would be + ;; confusing when adding a second white space character. + (while (re-search-forward + "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)" + limit t) + (when (and (not (org-at-comment-p)) + (setq ee (org-entity-get (match-string 1))) + (= (length (nth 6 ee)) 1)) + (let* ((end (if (equal (match-string 2) "{}") + (match-end 2) + (match-end 1)))) + (add-text-properties + (match-beginning 0) end + (list 'font-lock-fontified t)) + (compose-region (match-beginning 0) end + (nth 6 ee) nil) + (backward-char 1) + (throw 'match t)))) + nil)))) + +(defun org-fontify-like-in-org-mode (s &optional odd-levels) + "Fontify string S like in Org mode." + (with-temp-buffer + (insert s) + (let ((org-odd-levels-only odd-levels)) + (org-mode) + (org-font-lock-ensure) + (buffer-string)))) + +(defvar org-m nil) +(defvar org-l nil) +(defvar org-f nil) +(defun org-get-level-face (n) + "Get the right face for match N in font-lock matching of headlines." + (setq org-l (- (match-end 2) (match-beginning 1) 1)) + (when org-odd-levels-only (setq org-l (1+ (/ org-l 2)))) + (if org-cycle-level-faces + (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces)) + (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces))) + (cond + ((eq n 1) (if org-hide-leading-stars 'org-hide org-f)) + ((eq n 2) org-f) + (t (unless org-level-color-stars-only org-f)))) + +(defun org-face-from-face-or-color (context inherit face-or-color) + "Create a face list that inherits INHERIT, but sets the foreground color. +When FACE-OR-COLOR is not a string, just return it." + (if (stringp face-or-color) + (list :inherit inherit + (cdr (assoc context org-faces-easy-properties)) + face-or-color) + face-or-color)) + +(defun org-get-todo-face (kwd) + "Get the right face for a TODO keyword KWD. +If KWD is a number, get the corresponding match group." + (when (numberp kwd) (setq kwd (match-string kwd))) + (or (org-face-from-face-or-color + 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces))) + (and (member kwd org-done-keywords) 'org-done) + 'org-todo)) + +(defun org-get-priority-face (priority) + "Get the right face for PRIORITY. +PRIORITY is a character." + (or (org-face-from-face-or-color + 'priority 'org-priority (cdr (assq priority org-priority-faces))) + 'org-priority)) + +(defun org-get-tag-face (tag) + "Get the right face for TAG. +If TAG is a number, get the corresponding match group." + (let ((tag (if (wholenump tag) (match-string tag) tag))) + (or (org-face-from-face-or-color + 'tag 'org-tag (cdr (assoc tag org-tag-faces))) + 'org-tag))) + +(defun org-font-lock-add-priority-faces (limit) + "Add the special priority faces." + (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t) + (add-text-properties + (match-beginning 1) (match-end 1) + (list 'face (org-get-priority-face (string-to-char (match-string 2))) + 'font-lock-fontified t)))) + +(defun org-font-lock-add-tag-faces (limit) + "Add the special tag faces." + (when (and org-tag-faces org-tags-special-faces-re) + (while (re-search-forward org-tags-special-faces-re limit t) + (add-text-properties (match-beginning 1) (match-end 1) + (list 'face (org-get-tag-face 1) + 'font-lock-fontified t)) + (backward-char 1)))) + +(defun org-unfontify-region (beg end &optional _maybe_loudly) + "Remove fontification and activation overlays from links." + (font-lock-default-unfontify-region beg end) + (let* ((buffer-undo-list t) + (inhibit-read-only t) (inhibit-point-motion-hooks t) + (inhibit-modification-hooks t) + deactivate-mark buffer-file-name buffer-file-truename) + (decompose-region beg end) + (remove-text-properties beg end + '(mouse-face t keymap t org-linked-text t + invisible t intangible t + org-emphasis t)) + (org-remove-font-lock-display-properties beg end))) + +(defconst org-script-display '(((raise -0.3) (height 0.7)) + ((raise 0.3) (height 0.7)) + ((raise -0.5)) + ((raise 0.5))) + "Display properties for showing superscripts and subscripts.") + +(defun org-remove-font-lock-display-properties (beg end) + "Remove specific display properties that have been added by font lock. +The will remove the raise properties that are used to show superscripts +and subscripts." + (let (next prop) + (while (< beg end) + (setq next (next-single-property-change beg 'display nil end) + prop (get-text-property beg 'display)) + (when (member prop org-script-display) + (put-text-property beg next 'display nil)) + (setq beg next)))) + +(defun org-raise-scripts (limit) + "Add raise properties to sub/superscripts." + (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts + (re-search-forward + (if (eq org-use-sub-superscripts t) + org-match-substring-regexp + org-match-substring-with-braces-regexp) + limit t)) + (let* ((pos (point)) table-p comment-p + (mpos (match-beginning 3)) + (emph-p (get-text-property mpos 'org-emphasis)) + (link-p (get-text-property mpos 'mouse-face)) + (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face)))) + (goto-char (point-at-bol)) + (setq table-p (looking-at-p org-table-dataline-regexp) + comment-p (looking-at-p "^[ \t]*#[ +]")) + (goto-char pos) + ;; Handle a_b^c + (when (member (char-after) '(?_ ?^)) (goto-char (1- pos))) + (unless (or comment-p emph-p link-p keyw-p) + (put-text-property (match-beginning 3) (match-end 0) + 'display + (if (equal (char-after (match-beginning 2)) ?^) + (nth (if table-p 3 1) org-script-display) + (nth (if table-p 2 0) org-script-display))) + (add-text-properties (match-beginning 2) (match-end 2) + (list 'invisible t)) + (when (and (eq (char-after (match-beginning 3)) ?{) + (eq (char-before (match-end 3)) ?})) + (add-text-properties (match-beginning 3) (1+ (match-beginning 3)) + (list 'invisible t)) + (add-text-properties (1- (match-end 3)) (match-end 3) + (list 'invisible t)))) + t))) + +;;;; Visibility cycling, including org-goto and indirect buffer + +;;; Cycling + +(defvar-local org-cycle-global-status nil) +(put 'org-cycle-global-status 'org-state t) +(defvar-local org-cycle-subtree-status nil) +(put 'org-cycle-subtree-status 'org-state t) + +(defvar org-inlinetask-min-level) + +(defun org-unlogged-message (&rest args) + "Display a message, but avoid logging it in the *Messages* buffer." + (let ((message-log-max nil)) + (apply 'message args))) + +;;;###autoload +(defun org-cycle (&optional arg) + "TAB-action and visibility cycling for Org mode. + +This is the command invoked in Org mode by the `TAB' key. Its main +purpose is outline visibility cycling, but it also invokes other actions +in special contexts. + +When this function is called with a `\\[universal-argument]' prefix, rotate \ +the entire +buffer through 3 states (global cycling) + 1. OVERVIEW: Show only top-level headlines. + 2. CONTENTS: Show all headlines of all levels, but no body text. + 3. SHOW ALL: Show everything. + +With a `\\[universal-argument] \\[universal-argument]' prefix argument, \ +switch to the startup visibility, +determined by the variable `org-startup-folded', and by any VISIBILITY +properties in the buffer. + +With a `\\[universal-argument] \\[universal-argument] \ +\\[universal-argument]' prefix argument, show the entire buffer, including +any drawers. + +When inside a table, re-align the table and move to the next field. + +When point is at the beginning of a headline, rotate the subtree started +by this line through 3 different states (local cycling) + 1. FOLDED: Only the main headline is shown. + 2. CHILDREN: The main headline and the direct children are shown. + From this state, you can move to one of the children + and zoom in further. + 3. SUBTREE: Show the entire subtree, including body text. +If there is no subtree, switch directly from CHILDREN to FOLDED. + +When point is at the beginning of an empty headline and the variable +`org-cycle-level-after-item/entry-creation' is set, cycle the level +of the headline by demoting and promoting it to likely levels. This +speeds up creation document structure by pressing `TAB' once or several +times right after creating a new headline. + +When there is a numeric prefix, go up to a heading with level ARG, do +a `show-subtree' and return to the previous cursor position. If ARG +is negative, go up that many levels. + +When point is not at the beginning of a headline, execute the global +binding for `TAB', which is re-indenting the line. See the option +`org-cycle-emulate-tab' for details. + +As a special case, if point is at the beginning of the buffer and there is +no headline in line 1, this function will act as if called with prefix arg +\(`\\[universal-argument] TAB', same as `S-TAB') also when called without \ +prefix arg, but only +if the variable `org-cycle-global-at-bob' is t." + (interactive "P") + (org-load-modules-maybe) + (unless (or (run-hook-with-args-until-success 'org-tab-first-hook) + (and org-cycle-level-after-item/entry-creation + (or (org-cycle-level) + (org-cycle-item-indentation)))) + (let* ((limit-level + (or org-cycle-max-level + (and (boundp 'org-inlinetask-min-level) + org-inlinetask-min-level + (1- org-inlinetask-min-level)))) + (nstars (and limit-level + (if org-odd-levels-only + (and limit-level (1- (* limit-level 2))) + limit-level))) + (org-outline-regexp + (if (not (derived-mode-p 'org-mode)) + outline-regexp + (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))) + (bob-special (and org-cycle-global-at-bob (not arg) (bobp) + (not (looking-at org-outline-regexp)))) + (org-cycle-hook + (if bob-special + (delq 'org-optimize-window-after-visibility-change + (copy-sequence org-cycle-hook)) + org-cycle-hook)) + (pos (point))) + + (cond + + ((equal arg '(16)) + (setq last-command 'dummy) + (org-set-startup-visibility) + (org-unlogged-message "Startup visibility, plus VISIBILITY properties")) + + ((equal arg '(64)) + (outline-show-all) + (org-unlogged-message "Entire buffer visible, including drawers")) + + ((equal arg '(4)) (org-cycle-internal-global)) + + ;; Try hiding block at point. + ((org-hide-block-toggle-maybe)) + + ;; Try cdlatex TAB completion + ((org-try-cdlatex-tab)) + + ;; Table: enter it or move to the next field. + ((org-at-table-p 'any) + (if (org-at-table.el-p) + (message "%s" (substitute-command-keys "\\<org-mode-map>\ +Use `\\[org-edit-special]' to edit table.el tables")) + (if arg (org-table-edit-field t) + (org-table-justify-field-maybe) + (call-interactively 'org-table-next-field)))) + + ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook)) + + ;; Global cycling: delegate to `org-cycle-internal-global'. + (bob-special (org-cycle-internal-global)) + + ;; Drawers: delegate to `org-flag-drawer'. + ((save-excursion + (beginning-of-line 1) + (looking-at org-drawer-regexp)) + (org-flag-drawer ; toggle block visibility + (not (get-char-property (match-end 0) 'invisible)))) + + ;; Show-subtree, ARG levels up from here. + ((integerp arg) + (save-excursion + (org-back-to-heading) + (outline-up-heading (if (< arg 0) (- arg) + (- (funcall outline-level) arg))) + (org-show-subtree))) + + ;; Inline task: delegate to `org-inlinetask-toggle-visibility'. + ((and (featurep 'org-inlinetask) + (org-inlinetask-at-task-p) + (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol)))) + (org-inlinetask-toggle-visibility)) + + ;; At an item/headline: delegate to `org-cycle-internal-local'. + ((and (or (and org-cycle-include-plain-lists (org-at-item-p)) + (save-excursion (move-beginning-of-line 1) + (looking-at org-outline-regexp))) + (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol)))) + (org-cycle-internal-local)) + + ;; From there: TAB emulation and template completion. + (buffer-read-only (org-back-to-heading)) + + ((run-hook-with-args-until-success + 'org-tab-after-check-for-cycling-hook)) + + ((org-try-structure-completion)) + + ((run-hook-with-args-until-success + 'org-tab-before-tab-emulation-hook)) + + ((and (eq org-cycle-emulate-tab 'exc-hl-bol) + (or (not (bolp)) + (not (looking-at org-outline-regexp)))) + (call-interactively (global-key-binding "\t"))) + + ((if (and (memq org-cycle-emulate-tab '(white whitestart)) + (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")) + (or (and (eq org-cycle-emulate-tab 'white) + (= (match-end 0) (point-at-eol))) + (and (eq org-cycle-emulate-tab 'whitestart) + (>= (match-end 0) pos)))) + t + (eq org-cycle-emulate-tab t)) + (call-interactively (global-key-binding "\t"))) + + (t (save-excursion + (org-back-to-heading) + (org-cycle))))))) + +(defun org-cycle-internal-global () + "Do the global cycling action." + ;; Hack to avoid display of messages for .org attachments in Gnus + (let ((ga (string-match "\\*fontification" (buffer-name)))) + (cond + ((and (eq last-command this-command) + (eq org-cycle-global-status 'overview)) + ;; We just created the overview - now do table of contents + ;; This can be slow in very large buffers, so indicate action + (run-hook-with-args 'org-pre-cycle-hook 'contents) + (unless ga (org-unlogged-message "CONTENTS...")) + (org-content) + (unless ga (org-unlogged-message "CONTENTS...done")) + (setq org-cycle-global-status 'contents) + (run-hook-with-args 'org-cycle-hook 'contents)) + + ((and (eq last-command this-command) + (eq org-cycle-global-status 'contents)) + ;; We just showed the table of contents - now show everything + (run-hook-with-args 'org-pre-cycle-hook 'all) + (outline-show-all) + (unless ga (org-unlogged-message "SHOW ALL")) + (setq org-cycle-global-status 'all) + (run-hook-with-args 'org-cycle-hook 'all)) + + (t + ;; Default action: go to overview + (run-hook-with-args 'org-pre-cycle-hook 'overview) + (org-overview) + (unless ga (org-unlogged-message "OVERVIEW")) + (setq org-cycle-global-status 'overview) + (run-hook-with-args 'org-cycle-hook 'overview))))) + +(defvar org-called-with-limited-levels nil + "Non-nil when `org-with-limited-levels' is currently active.") + +(defun org-invisible-p (&optional pos) + "Non-nil if the character after POS is invisible. +If POS is nil, use `point' instead." + (get-char-property (or pos (point)) 'invisible)) + +(defun org-cycle-internal-local () + "Do the local cycling action." + (let ((goal-column 0) eoh eol eos has-children children-skipped struct) + ;; First, determine end of headline (EOH), end of subtree or item + ;; (EOS), and if item or heading has children (HAS-CHILDREN). + (save-excursion + (if (org-at-item-p) + (progn + (beginning-of-line) + (setq struct (org-list-struct)) + (setq eoh (point-at-eol)) + (setq eos (org-list-get-item-end-before-blank (point) struct)) + (setq has-children (org-list-has-child-p (point) struct))) + (org-back-to-heading) + (setq eoh (save-excursion (outline-end-of-heading) (point))) + (setq eos (save-excursion (org-end-of-subtree t t) + (when (bolp) (backward-char)) (point))) + (setq has-children + (or (save-excursion + (let ((level (funcall outline-level))) + (outline-next-heading) + (and (org-at-heading-p t) + (> (funcall outline-level) level)))) + (save-excursion + (org-list-search-forward (org-item-beginning-re) eos t))))) + ;; Determine end invisible part of buffer (EOL) + (beginning-of-line 2) + (while (and (not (eobp)) ;This is like `next-line'. + (get-char-property (1- (point)) 'invisible)) + (goto-char (next-single-char-property-change (point) 'invisible)) + (and (eolp) (beginning-of-line 2))) + (setq eol (point))) + ;; Find out what to do next and set `this-command' + (cond + ((= eos eoh) + ;; Nothing is hidden behind this heading + (unless (org-before-first-heading-p) + (run-hook-with-args 'org-pre-cycle-hook 'empty)) + (org-unlogged-message "EMPTY ENTRY") + (setq org-cycle-subtree-status nil) + (save-excursion + (goto-char eos) + (outline-next-heading) + (when (org-invisible-p) (org-flag-heading nil)))) + ((and (or (>= eol eos) + (not (string-match "\\S-" (buffer-substring eol eos)))) + (or has-children + (not (setq children-skipped + org-cycle-skip-children-state-if-no-children)))) + ;; Entire subtree is hidden in one line: children view + (unless (org-before-first-heading-p) + (run-hook-with-args 'org-pre-cycle-hook 'children)) + (if (org-at-item-p) + (org-list-set-item-visibility (point-at-bol) struct 'children) + (org-show-entry) + (org-with-limited-levels (org-show-children)) + (org-show-set-visibility 'canonical) + ;; FIXME: This slows down the func way too much. + ;; How keep drawers hidden in subtree anyway? + ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook) + ;; (org-cycle-hide-drawers 'subtree)) + + ;; Fold every list in subtree to top-level items. + (when (eq org-cycle-include-plain-lists 'integrate) + (save-excursion + (org-back-to-heading) + (while (org-list-search-forward (org-item-beginning-re) eos t) + (beginning-of-line 1) + (let* ((struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (end (org-list-get-bottom-point struct))) + (dolist (e (org-list-get-all-items (point) struct prevs)) + (org-list-set-item-visibility e struct 'folded)) + (goto-char (if (< end eos) end eos))))))) + (org-unlogged-message "CHILDREN") + (save-excursion + (goto-char eos) + (outline-next-heading) + (when (org-invisible-p) (org-flag-heading nil))) + (setq org-cycle-subtree-status 'children) + (unless (org-before-first-heading-p) + (run-hook-with-args 'org-cycle-hook 'children))) + ((or children-skipped + (and (eq last-command this-command) + (eq org-cycle-subtree-status 'children))) + ;; We just showed the children, or no children are there, + ;; now show everything. + (unless (org-before-first-heading-p) + (run-hook-with-args 'org-pre-cycle-hook 'subtree)) + (outline-flag-region eoh eos nil) + (org-unlogged-message + (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE")) + (setq org-cycle-subtree-status 'subtree) + (unless (org-before-first-heading-p) + (run-hook-with-args 'org-cycle-hook 'subtree))) + (t + ;; Default action: hide the subtree. + (run-hook-with-args 'org-pre-cycle-hook 'folded) + (outline-flag-region eoh eos t) + (org-unlogged-message "FOLDED") + (setq org-cycle-subtree-status 'folded) + (unless (org-before-first-heading-p) + (run-hook-with-args 'org-cycle-hook 'folded)))))) + +;;;###autoload +(defun org-global-cycle (&optional arg) + "Cycle the global visibility. For details see `org-cycle'. +With `\\[universal-argument]' prefix ARG, switch to startup visibility. +With a numeric prefix, show all headlines up to that level." + (interactive "P") + (let ((org-cycle-include-plain-lists + (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil))) + (cond + ((integerp arg) + (outline-show-all) + (outline-hide-sublevels arg) + (setq org-cycle-global-status 'contents)) + ((equal arg '(4)) + (org-set-startup-visibility) + (org-unlogged-message "Startup visibility, plus VISIBILITY properties.")) + (t + (org-cycle '(4)))))) + +(defun org-set-startup-visibility () + "Set the visibility required by startup options and properties." + (cond + ((eq org-startup-folded t) + (org-overview)) + ((eq org-startup-folded 'content) + (org-content)) + ((or (eq org-startup-folded 'showeverything) + (eq org-startup-folded nil)) + (outline-show-all))) + (unless (eq org-startup-folded 'showeverything) + (when org-hide-block-startup (org-hide-block-all)) + (org-set-visibility-according-to-property 'no-cleanup) + (org-cycle-hide-archived-subtrees 'all) + (org-cycle-hide-drawers 'all) + (org-cycle-show-empty-lines t))) + +(defun org-set-visibility-according-to-property (&optional no-cleanup) + "Switch subtree visibilities according to :VISIBILITY: property." + (interactive) + (org-with-wide-buffer + (goto-char (point-min)) + (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t) + (if (not (org-at-property-p)) (outline-next-heading) + (let ((state (match-string 3))) + (save-excursion + (org-back-to-heading t) + (outline-hide-subtree) + (org-reveal)) + (cond + ((equal state "folded") + (outline-hide-subtree) + (org-end-of-subtree t t)) + ((equal state "children") + (org-show-hidden-entry) + (org-show-children)) + ((equal state "content") + (save-excursion + (save-restriction + (org-narrow-to-subtree) + (org-content))) + (org-end-of-subtree t t)) + ((member state '("all" "showall")) + (outline-show-subtree)))))) + (unless no-cleanup + (org-cycle-hide-archived-subtrees 'all) + (org-cycle-hide-drawers 'all) + (org-cycle-show-empty-lines 'all)))) + +;; This function uses outline-regexp instead of the more fundamental +;; org-outline-regexp so that org-cycle-global works outside of Org +;; buffers, where outline-regexp is needed. +(defun org-overview () + "Switch to overview mode, showing only top-level headlines. +This shows all headlines with a level equal or greater than the level +of the first headline in the buffer. This is important, because if the +first headline is not level one, then (hide-sublevels 1) gives confusing +results." + (interactive) + (save-excursion + (let ((level + (save-excursion + (goto-char (point-min)) + (when (re-search-forward (concat "^" outline-regexp) nil t) + (goto-char (match-beginning 0)) + (funcall outline-level))))) + (and level (outline-hide-sublevels level))))) + +(defun org-content (&optional arg) + "Show all headlines in the buffer, like a table of contents. +With numerical argument N, show content up to level N." + (interactive "P") + (org-overview) + (save-excursion + ;; Visit all headings and show their offspring + (and (integerp arg) (org-overview)) + (goto-char (point-max)) + (catch 'exit + (while (and (progn (condition-case nil + (outline-previous-visible-heading 1) + (error (goto-char (point-min)))) + t) + (looking-at org-outline-regexp)) + (if (integerp arg) + (org-show-children (1- arg)) + (outline-show-branches)) + (when (bobp) (throw 'exit nil)))))) + +(defun org-optimize-window-after-visibility-change (state) + "Adjust the window after a change in outline visibility. +This function is the default value of the hook `org-cycle-hook'." + (when (get-buffer-window (current-buffer)) + (cond + ((eq state 'content) nil) + ((eq state 'all) nil) + ((eq state 'folded) nil) + ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1))) + ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))) + +(defun org-remove-empty-overlays-at (pos) + "Remove outline overlays that do not contain non-white stuff." + (dolist (o (overlays-at pos)) + (and (eq 'outline (overlay-get o 'invisible)) + (not (string-match "\\S-" (buffer-substring (overlay-start o) + (overlay-end o)))) + (delete-overlay o)))) + +(defun org-clean-visibility-after-subtree-move () + "Fix visibility issues after moving a subtree." + ;; First, find a reasonable region to look at: + ;; Start two siblings above, end three below + (let* ((beg (save-excursion + (and (org-get-last-sibling) + (org-get-last-sibling)) + (point))) + (end (save-excursion + (and (org-get-next-sibling) + (org-get-next-sibling) + (org-get-next-sibling)) + (if (org-at-heading-p) + (point-at-eol) + (point)))) + (level (looking-at "\\*+")) + (re (when level (concat "^" (regexp-quote (match-string 0)) " ")))) + (save-excursion + (save-restriction + (narrow-to-region beg end) + (when re + ;; Properly fold already folded siblings + (goto-char (point-min)) + (while (re-search-forward re nil t) + (when (and (not (org-invisible-p)) + (save-excursion + (goto-char (point-at-eol)) (org-invisible-p))) + (outline-hide-entry)))) + (org-cycle-show-empty-lines 'overview) + (org-cycle-hide-drawers 'overview))))) + +(defun org-cycle-show-empty-lines (state) + "Show empty lines above all visible headlines. +The region to be covered depends on STATE when called through +`org-cycle-hook'. Lisp program can use t for STATE to get the +entire buffer covered. Note that an empty line is only shown if there +are at least `org-cycle-separator-lines' empty lines before the headline." + (when (/= org-cycle-separator-lines 0) + (save-excursion + (let* ((n (abs org-cycle-separator-lines)) + (re (cond + ((= n 1) "\\(\n[ \t]*\n\\*+\\) ") + ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ") + (t (let ((ns (number-to-string (- n 2)))) + (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}" + "[ \t]*\\(\n[ \t]*\n\\*+\\) "))))) + beg end) + (cond + ((memq state '(overview contents t)) + (setq beg (point-min) end (point-max))) + ((memq state '(children folded)) + (setq beg (point) + end (progn (org-end-of-subtree t t) + (line-beginning-position 2))))) + (when beg + (goto-char beg) + (while (re-search-forward re end t) + (unless (get-char-property (match-end 1) 'invisible) + (let ((e (match-end 1)) + (b (if (>= org-cycle-separator-lines 0) + (match-beginning 1) + (save-excursion + (goto-char (match-beginning 0)) + (skip-chars-backward " \t\n") + (line-end-position))))) + (outline-flag-region b e nil)))))))) + ;; Never hide empty lines at the end of the file. + (save-excursion + (goto-char (point-max)) + (outline-previous-heading) + (outline-end-of-heading) + (when (and (looking-at "[ \t\n]+") + (= (match-end 0) (point-max))) + (outline-flag-region (point) (match-end 0) nil)))) + +(defun org-show-empty-lines-in-parent () + "Move to the parent and re-show empty lines before visible headlines." + (save-excursion + (let ((context (if (org-up-heading-safe) 'children 'overview))) + (org-cycle-show-empty-lines context)))) + +(defun org-files-list () + "Return `org-agenda-files' list, plus all open Org files. +This is useful for operations that need to scan all of a user's +open and agenda-wise Org files." + (let ((files (mapcar #'expand-file-name (org-agenda-files)))) + (dolist (buf (buffer-list)) + (with-current-buffer buf + (when (and (derived-mode-p 'org-mode) (buffer-file-name)) + (cl-pushnew (expand-file-name (buffer-file-name)) files + :test #'equal)))) + files)) + +(defsubst org-entry-beginning-position () + "Return the beginning position of the current entry." + (save-excursion (org-back-to-heading t) (point))) + +(defsubst org-entry-end-position () + "Return the end position of the current entry." + (save-excursion (outline-next-heading) (point))) + +(defun org-cycle-hide-drawers (state &optional exceptions) + "Re-hide all drawers after a visibility state change. +STATE should be one of the symbols listed in the docstring of +`org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is +a list of strings specifying which drawers should not be hidden." + (when (and (derived-mode-p 'org-mode) + (not (memq state '(overview folded contents)))) + (save-excursion + (let* ((globalp (eq state 'all)) + (beg (if globalp (point-min) (point))) + (end (if globalp (point-max) + (if (eq state 'children) + (save-excursion (outline-next-heading) (point)) + (org-end-of-subtree t))))) + (goto-char beg) + (while (re-search-forward org-drawer-regexp (max end (point)) t) + (unless (member-ignore-case (match-string 1) exceptions) + (let ((drawer (org-element-at-point))) + (when (memq (org-element-type drawer) '(drawer property-drawer)) + (org-flag-drawer t drawer) + ;; Make sure to skip drawer entirely or we might flag + ;; it another time when matching its ending line with + ;; `org-drawer-regexp'. + (goto-char (org-element-property :end drawer)))))))))) + +(defun org-flag-drawer (flag &optional element) + "When FLAG is non-nil, hide the drawer we are at. +Otherwise make it visible. When optional argument ELEMENT is +a parsed drawer, as returned by `org-element-at-point', hide or +show that drawer instead." + (let ((drawer (or element + (and (save-excursion + (beginning-of-line) + (looking-at-p org-drawer-regexp)) + (org-element-at-point))))) + (when (memq (org-element-type drawer) '(drawer property-drawer)) + (let ((post (org-element-property :post-affiliated drawer))) + (save-excursion + (outline-flag-region + (progn (goto-char post) (line-end-position)) + (progn (goto-char (org-element-property :end drawer)) + (skip-chars-backward " \r\t\n") + (line-end-position)) + flag)) + ;; When the drawer is hidden away, make sure point lies in + ;; a visible part of the buffer. + (when (and flag (> (line-beginning-position) post)) + (goto-char post)))))) + +(defun org-subtree-end-visible-p () + "Is the end of the current subtree visible?" + (pos-visible-in-window-p + (save-excursion (org-end-of-subtree t) (point)))) + +(defun org-first-headline-recenter () + "Move cursor to the first headline and recenter the headline." + (let ((window (get-buffer-window))) + (when window + (goto-char (point-min)) + (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t) + (set-window-start window (line-beginning-position)))))) + +;;; Saving and restoring visibility + +(defun org-outline-overlay-data (&optional use-markers) + "Return a list of the locations of all outline overlays. +These are overlays with the `invisible' property value `outline'. +The return value is a list of cons cells, with start and stop +positions for each overlay. +If USE-MARKERS is set, return the positions as markers." + (let (beg end) + (org-with-wide-buffer + (delq nil + (mapcar (lambda (o) + (when (eq (overlay-get o 'invisible) 'outline) + (setq beg (overlay-start o) + end (overlay-end o)) + (and beg end (> end beg) + (if use-markers + (cons (copy-marker beg) + (copy-marker end t)) + (cons beg end))))) + (overlays-in (point-min) (point-max))))))) + +(defun org-set-outline-overlay-data (data) + "Create visibility overlays for all positions in DATA. +DATA should have been made by `org-outline-overlay-data'." + (org-with-wide-buffer + (outline-show-all) + (dolist (c data) (outline-flag-region (car c) (cdr c) t)))) + +;;; Folding of blocks + +(defvar-local org-hide-block-overlays nil + "Overlays hiding blocks.") + +(defun org-block-map (function &optional start end) + "Call FUNCTION at the head of all source blocks in the current buffer. +Optional arguments START and END can be used to limit the range." + (let ((start (or start (point-min))) + (end (or end (point-max)))) + (save-excursion + (goto-char start) + (while (and (< (point) end) (re-search-forward org-block-regexp end t)) + (save-excursion + (save-match-data + (goto-char (match-beginning 0)) + (funcall function))))))) + +(defun org-hide-block-toggle-all () + "Toggle the visibility of all blocks in the current buffer." + (org-block-map 'org-hide-block-toggle)) + +(defun org-hide-block-all () + "Fold all blocks in the current buffer." + (interactive) + (org-show-block-all) + (org-block-map 'org-hide-block-toggle-maybe)) + +(defun org-show-block-all () + "Unfold all blocks in the current buffer." + (interactive) + (mapc #'delete-overlay org-hide-block-overlays) + (setq org-hide-block-overlays nil)) + +(defun org-hide-block-toggle-maybe () + "Toggle visibility of block at point. +Unlike to `org-hide-block-toggle', this function does not throw +an error. Return a non-nil value when toggling is successful." + (interactive) + (ignore-errors (org-hide-block-toggle))) + +(defun org-hide-block-toggle (&optional force) + "Toggle the visibility of the current block. +When optional argument FORCE is `off', make block visible. If it +is non-nil, hide it unconditionally. Throw an error when not at +a block. Return a non-nil value when toggling is successful." + (interactive) + (let ((element (org-element-at-point))) + (unless (memq (org-element-type element) + '(center-block comment-block dynamic-block example-block + export-block quote-block special-block + src-block verse-block)) + (user-error "Not at a block")) + (let* ((start (save-excursion + (goto-char (org-element-property :post-affiliated element)) + (line-end-position))) + (end (save-excursion + (goto-char (org-element-property :end element)) + (skip-chars-backward " \r\t\n") + (line-end-position))) + (overlays (overlays-at start))) + (cond + ;; Do nothing when not before or at the block opening line or + ;; at the block closing line. + ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil) + ((and (not (eq force 'off)) + (not (memq t (mapcar + (lambda (o) + (eq (overlay-get o 'invisible) 'org-hide-block)) + overlays)))) + (let ((ov (make-overlay start end))) + (overlay-put ov 'invisible 'org-hide-block) + ;; Make the block accessible to `isearch'. + (overlay-put + ov 'isearch-open-invisible + (lambda (ov) + (when (memq ov org-hide-block-overlays) + (setq org-hide-block-overlays (delq ov org-hide-block-overlays))) + (when (eq (overlay-get ov 'invisible) 'org-hide-block) + (delete-overlay ov)))) + (push ov org-hide-block-overlays) + ;; When the block is hidden away, make sure point is left in + ;; a visible part of the buffer. + (when (> (line-beginning-position) start) + (goto-char start) + (beginning-of-line)) + ;; Signal successful toggling. + t)) + ((or (not force) (eq force 'off)) + (dolist (ov overlays t) + (when (memq ov org-hide-block-overlays) + (setq org-hide-block-overlays (delq ov org-hide-block-overlays))) + (when (eq (overlay-get ov 'invisible) 'org-hide-block) + (delete-overlay ov)))))))) + +;; Remove overlays when changing major mode +(add-hook 'org-mode-hook + (lambda () (add-hook 'change-major-mode-hook + 'org-show-block-all 'append 'local))) + +;;; Org-goto + +(defvar org-goto-window-configuration nil) +(defvar org-goto-marker nil) +(defvar org-goto-map) +(defun org-goto-map () + "Set the keymap `org-goto'." + (setq org-goto-map + (let ((map (make-sparse-keymap))) + (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command + mouse-drag-region universal-argument org-occur))) + (dolist (cmd cmds) + (substitute-key-definition cmd cmd map global-map))) + (suppress-keymap map) + (org-defkey map "\C-m" 'org-goto-ret) + (org-defkey map [(return)] 'org-goto-ret) + (org-defkey map [(left)] 'org-goto-left) + (org-defkey map [(right)] 'org-goto-right) + (org-defkey map [(control ?g)] 'org-goto-quit) + (org-defkey map "\C-i" 'org-cycle) + (org-defkey map [(tab)] 'org-cycle) + (org-defkey map [(down)] 'outline-next-visible-heading) + (org-defkey map [(up)] 'outline-previous-visible-heading) + (if org-goto-auto-isearch + (if (fboundp 'define-key-after) + (define-key-after map [t] 'org-goto-local-auto-isearch) + nil) + (org-defkey map "q" 'org-goto-quit) + (org-defkey map "n" 'outline-next-visible-heading) + (org-defkey map "p" 'outline-previous-visible-heading) + (org-defkey map "f" 'outline-forward-same-level) + (org-defkey map "b" 'outline-backward-same-level) + (org-defkey map "u" 'outline-up-heading)) + (org-defkey map "/" 'org-occur) + (org-defkey map "\C-c\C-n" 'outline-next-visible-heading) + (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading) + (org-defkey map "\C-c\C-f" 'outline-forward-same-level) + (org-defkey map "\C-c\C-b" 'outline-backward-same-level) + (org-defkey map "\C-c\C-u" 'outline-up-heading) + map))) + +(defconst org-goto-help + "Browse buffer copy, to find location or copy text.%s +RET=jump to location C-g=quit and return to previous location +\[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur") + +(defvar org-goto-start-pos) ; dynamically scoped parameter + +(defun org-goto (&optional alternative-interface) + "Look up a different location in the current file, keeping current visibility. + +When you want look-up or go to a different location in a +document, the fastest way is often to fold the entire buffer and +then dive into the tree. This method has the disadvantage, that +the previous location will be folded, which may not be what you +want. + +This command works around this by showing a copy of the current +buffer in an indirect buffer, in overview mode. You can dive +into the tree in that copy, use org-occur and incremental search +to find a location. When pressing RET or `Q', the command +returns to the original buffer in which the visibility is still +unchanged. After RET it will also jump to the location selected +in the indirect buffer and expose the headline hierarchy above. + +With a prefix argument, use the alternative interface: e.g., if +`org-goto-interface' is `outline' use `outline-path-completion'." + (interactive "P") + (org-goto-map) + (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level)))) + (org-refile-use-outline-path t) + (org-refile-target-verify-function nil) + (interface + (if (not alternative-interface) + org-goto-interface + (if (eq org-goto-interface 'outline) + 'outline-path-completion + 'outline))) + (org-goto-start-pos (point)) + (selected-point + (if (eq interface 'outline) + (car (org-get-location (current-buffer) org-goto-help)) + (let ((pa (org-refile-get-location "Goto"))) + (org-refile-check-position pa) + (nth 3 pa))))) + (if selected-point + (progn + (org-mark-ring-push org-goto-start-pos) + (goto-char selected-point) + (when (or (org-invisible-p) (org-invisible-p2)) + (org-show-context 'org-goto))) + (message "Quit")))) + +(defvar org-goto-selected-point nil) ; dynamically scoped parameter +(defvar org-goto-exit-command nil) ; dynamically scoped parameter +(defvar org-goto-local-auto-isearch-map) ; defined below + +(defun org-get-location (_buf help) + "Let the user select a location in current buffer. +This function uses a recursive edit. It returns the selected position +or nil." + (org-no-popups + (let ((isearch-mode-map org-goto-local-auto-isearch-map) + (isearch-hide-immediately nil) + (isearch-search-fun-function + (lambda () 'org-goto-local-search-headings)) + (org-goto-selected-point org-goto-exit-command)) + (save-excursion + (save-window-excursion + (delete-other-windows) + (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*")) + (pop-to-buffer-same-window + (condition-case nil + (make-indirect-buffer (current-buffer) "*org-goto*") + (error (make-indirect-buffer (current-buffer) "*org-goto*")))) + (with-output-to-temp-buffer "*Org Help*" + (princ (format help (if org-goto-auto-isearch + " Just type for auto-isearch." + " n/p/f/b/u to navigate, q to quit.")))) + (org-fit-window-to-buffer (get-buffer-window "*Org Help*")) + (setq buffer-read-only nil) + (let ((org-startup-truncated t) + (org-startup-folded nil) + (org-startup-align-all-tables nil)) + (org-mode) + (org-overview)) + (setq buffer-read-only t) + (if (and (boundp 'org-goto-start-pos) + (integer-or-marker-p org-goto-start-pos)) + (progn (goto-char org-goto-start-pos) + (when (org-invisible-p) + (org-show-set-visibility 'lineage))) + (goto-char (point-min))) + (let (org-special-ctrl-a/e) (org-beginning-of-line)) + (message "Select location and press RET") + (use-local-map org-goto-map) + (recursive-edit))) + (kill-buffer "*org-goto*") + (cons org-goto-selected-point org-goto-exit-command)))) + +(defvar org-goto-local-auto-isearch-map (make-sparse-keymap)) +(set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map) +;; `isearch-other-control-char' was removed in Emacs 24.4. +(if (fboundp 'isearch-other-control-char) + (progn + (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char) + (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)) + (define-key org-goto-local-auto-isearch-map "\C-i" nil) + (define-key org-goto-local-auto-isearch-map "\C-m" nil) + (define-key org-goto-local-auto-isearch-map [return] nil)) + +(defun org-goto-local-search-headings (string bound noerror) + "Search and make sure that any matches are in headlines." + (catch 'return + (while (if isearch-forward + (search-forward string bound noerror) + (search-backward string bound noerror)) + (when (save-match-data + (and (save-excursion + (beginning-of-line) + (looking-at org-complex-heading-regexp)) + (or (not (match-beginning 5)) + (< (point) (match-beginning 5))))) + (throw 'return (point)))))) + +(defun org-goto-local-auto-isearch () + "Start isearch." + (interactive) + (goto-char (point-min)) + (let ((keys (this-command-keys))) + (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char) + (isearch-mode t) + (isearch-process-search-char (string-to-char keys))))) + +(defun org-goto-ret (&optional _arg) + "Finish `org-goto' by going to the new location." + (interactive "P") + (setq org-goto-selected-point (point)) + (setq org-goto-exit-command 'return) + (throw 'exit nil)) + +(defun org-goto-left () + "Finish `org-goto' by going to the new location." + (interactive) + (if (org-at-heading-p) + (progn + (beginning-of-line 1) + (setq org-goto-selected-point (point) + org-goto-exit-command 'left) + (throw 'exit nil)) + (user-error "Not on a heading"))) + +(defun org-goto-right () + "Finish `org-goto' by going to the new location." + (interactive) + (if (org-at-heading-p) + (progn + (setq org-goto-selected-point (point) + org-goto-exit-command 'right) + (throw 'exit nil)) + (user-error "Not on a heading"))) + +(defun org-goto-quit () + "Finish `org-goto' without cursor motion." + (interactive) + (setq org-goto-selected-point nil) + (setq org-goto-exit-command 'quit) + (throw 'exit nil)) + +;;; Indirect buffer display of subtrees + +(defvar org-indirect-dedicated-frame nil + "This is the frame being used for indirect tree display.") +(defvar org-last-indirect-buffer nil) + +(defun org-tree-to-indirect-buffer (&optional arg) + "Create indirect buffer and narrow it to current subtree. + +With a numerical prefix ARG, go up to this level and then take that tree. +If ARG is negative, go up that many levels. + +If `org-indirect-buffer-display' is not `new-frame', the command removes the +indirect buffer previously made with this command, to avoid proliferation of +indirect buffers. However, when you call the command with a \ +`\\[universal-argument]' prefix, or +when `org-indirect-buffer-display' is `new-frame', the last buffer is kept +so that you can work with several indirect buffers at the same time. If +`org-indirect-buffer-display' is `dedicated-frame', the \ +`\\[universal-argument]' prefix also +requests that a new frame be made for the new buffer, so that the dedicated +frame is not changed." + (interactive "P") + (let ((cbuf (current-buffer)) + (cwin (selected-window)) + (pos (point)) + beg end level heading ibuf) + (save-excursion + (org-back-to-heading t) + (when (numberp arg) + (setq level (org-outline-level)) + (when (< arg 0) (setq arg (+ level arg))) + (while (> (setq level (org-outline-level)) arg) + (org-up-heading-safe))) + (setq beg (point) + heading (org-get-heading 'no-tags)) + (org-end-of-subtree t t) + (when (org-at-heading-p) (backward-char 1)) + (setq end (point))) + (when (and (buffer-live-p org-last-indirect-buffer) + (not (eq org-indirect-buffer-display 'new-frame)) + (not arg)) + (kill-buffer org-last-indirect-buffer)) + (setq ibuf (org-get-indirect-buffer cbuf heading) + org-last-indirect-buffer ibuf) + (cond + ((or (eq org-indirect-buffer-display 'new-frame) + (and arg (eq org-indirect-buffer-display 'dedicated-frame))) + (select-frame (make-frame)) + (delete-other-windows) + (pop-to-buffer-same-window ibuf) + (org-set-frame-title heading)) + ((eq org-indirect-buffer-display 'dedicated-frame) + (raise-frame + (select-frame (or (and org-indirect-dedicated-frame + (frame-live-p org-indirect-dedicated-frame) + org-indirect-dedicated-frame) + (setq org-indirect-dedicated-frame (make-frame))))) + (delete-other-windows) + (pop-to-buffer-same-window ibuf) + (org-set-frame-title (concat "Indirect: " heading))) + ((eq org-indirect-buffer-display 'current-window) + (pop-to-buffer-same-window ibuf)) + ((eq org-indirect-buffer-display 'other-window) + (pop-to-buffer ibuf)) + (t (error "Invalid value"))) + (narrow-to-region beg end) + (outline-show-all) + (goto-char pos) + (run-hook-with-args 'org-cycle-hook 'all) + (and (window-live-p cwin) (select-window cwin)))) + +(defun org-get-indirect-buffer (&optional buffer heading) + (setq buffer (or buffer (current-buffer))) + (let ((n 1) (base (buffer-name buffer)) bname) + (while (buffer-live-p + (get-buffer + (setq bname + (concat base "-" + (if heading (concat heading "-" (number-to-string n)) + (number-to-string n)))))) + (setq n (1+ n))) + (condition-case nil + (make-indirect-buffer buffer bname 'clone) + (error (make-indirect-buffer buffer bname))))) + +(defun org-set-frame-title (title) + "Set the title of the current frame to the string TITLE." + (modify-frame-parameters (selected-frame) (list (cons 'name title)))) + +;;;; Structure editing + +;;; Inserting headlines + +(defun org--line-empty-p (n) + "Is the Nth next line empty? + +Counts the current line as N = 1 and the previous line as N = 0; +see `beginning-of-line'." + (save-excursion + (and (not (bobp)) + (or (beginning-of-line n) t) + (save-match-data + (looking-at "[ \t]*$"))))) + +(defun org-previous-line-empty-p () + "Is the previous line a blank line? +When NEXT is non-nil, check the next line instead." + (org--line-empty-p 0)) + +(defun org-next-line-empty-p () + "Is the previous line a blank line? +When NEXT is non-nil, check the next line instead." + (org--line-empty-p 2)) + +(defun org--blank-before-heading-p (&optional parent) + "Non-nil when an empty line should precede a new heading here. +When optional argument PARENT is non-nil, consider parent +headline instead of current one." + (pcase (assq 'heading org-blank-before-new-entry) + (`(heading . auto) + (save-excursion + (org-with-limited-levels + (unless (and (org-before-first-heading-p) + (not (outline-next-heading))) + (org-back-to-heading t) + (when parent (org-up-heading-safe)) + (cond ((not (bobp)) + (org-previous-line-empty-p)) + ((outline-next-heading) + (org-previous-line-empty-p)) + ;; Ignore trailing spaces on last buffer line. + ((progn (skip-chars-backward " \t") (bolp)) + (org-previous-line-empty-p)) + (t nil)))))) + (`(heading . ,value) value) + (_ nil))) + +(defun org-insert-heading (&optional arg invisible-ok top) + "Insert a new heading or an item with the same depth at point. + +If point is at the beginning of a heading, insert a new heading +or a new headline above the current one. When at the beginning +of a regular line of text, turn it into a heading. + +If point is in the middle of a line, split it and create a new +headline with the text in the current line after point (see +`org-M-RET-may-split-line' on how to modify this behavior). As +a special case, on a headline, splitting can only happen on the +title itself. E.g., this excludes breaking stars or tags. + +With a `\\[universal-argument]' prefix, set \ +`org-insert-heading-respect-content' to +a non-nil value for the duration of the command. This forces the +insertion of a heading after the current subtree, independently +on the location of point. + +With a `\\[universal-argument] \\[universal-argument]' prefix, \ +insert the heading at the end of the tree +above the current heading. For example, if point is within a +2nd-level heading, then it will insert a 2nd-level heading at +the end of the 1st-level parent subtree. + +When INVISIBLE-OK is set, stop at invisible headlines when going +back. This is important for non-interactive uses of the +command. + +When optional argument TOP is non-nil, insert a level 1 heading, +unconditionally." + (interactive "P") + (let* ((blank? (org--blank-before-heading-p (equal arg '(16)))) + (level (org-current-level)) + (stars (make-string (if (and level (not top)) level 1) ?*))) + (cond + ((or org-insert-heading-respect-content + (member arg '((4) (16))) + (and (not invisible-ok) + (invisible-p (max (1- (point)) (point-min))))) + ;; Position point at the location of insertion. + (if (not level) ;before first headline + (org-with-limited-levels (outline-next-heading)) + ;; Make sure we end up on a visible headline if INVISIBLE-OK + ;; is nil. + (org-with-limited-levels (org-back-to-heading invisible-ok)) + (cond ((equal arg '(16)) + (org-up-heading-safe) + (org-end-of-subtree t t)) + (t + (org-end-of-subtree t t)))) + (unless (bolp) (insert "\n")) ;ensure final newline + (unless (and blank? (org-previous-line-empty-p)) + (org-N-empty-lines-before-current (if blank? 1 0))) + (insert stars " \n") + (forward-char -1)) + ;; At a headline... + ((org-at-heading-p) + (cond ((bolp) + (when blank? (save-excursion (insert "\n"))) + (save-excursion (insert stars " \n")) + (unless (and blank? (org-previous-line-empty-p)) + (org-N-empty-lines-before-current (if blank? 1 0))) + (end-of-line)) + ((and (org-get-alist-option org-M-RET-may-split-line 'headline) + (org-match-line org-complex-heading-regexp) + (org-pos-in-match-range (point) 4)) + ;; Grab the text that should moved to the new headline. + ;; Preserve tags. + (let ((split (delete-and-extract-region (point) (match-end 4)))) + (if (looking-at "[ \t]*$") (replace-match "") + (org-set-tags nil t)) + (end-of-line) + (when blank? (insert "\n")) + (insert "\n" stars " ") + (when (org-string-nw-p split) (insert split)) + (when (eobp) (save-excursion (insert "\n"))))) + (t + (end-of-line) + (when blank? (insert "\n")) + (insert "\n" stars " ") + (when (eobp) (save-excursion (insert "\n")))))) + ;; On regular text, turn line into a headline or split, if + ;; appropriate. + ((bolp) + (insert stars " ") + (unless (and blank? (org-previous-line-empty-p)) + (org-N-empty-lines-before-current (if blank? 1 0)))) + (t + (unless (org-get-alist-option org-M-RET-may-split-line 'headline) + (end-of-line)) + (insert "\n" stars " ") + (unless (and blank? (org-previous-line-empty-p)) + (org-N-empty-lines-before-current (if blank? 1 0)))))) + (run-hooks 'org-insert-heading-hook)) + +(defun org-N-empty-lines-before-current (n) + "Make the number of empty lines before current exactly N. +So this will delete or add empty lines." + (let ((column (current-column))) + (beginning-of-line) + (unless (bobp) + (let ((start (save-excursion + (skip-chars-backward " \r\t\n") + (line-end-position)))) + (delete-region start (line-end-position 0)))) + (insert (make-string n ?\n)) + (move-to-column column))) + +(defun org-get-heading (&optional no-tags no-todo no-priority no-comment) + "Return the heading of the current entry, without the stars. +When NO-TAGS is non-nil, don't include tags. +When NO-TODO is non-nil, don't include TODO keywords. +When NO-PRIORITY is non-nil, don't include priority cookie. +When NO-COMMENT is non-nil, don't include COMMENT string." + (save-excursion + (org-back-to-heading t) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp) + (let ((todo (and (not no-todo) (match-string 2))) + (priority (and (not no-priority) (match-string 3))) + (headline (pcase (match-string 4) + (`nil "") + ((and (guard no-comment) h) + (replace-regexp-in-string + (eval-when-compile + (format "\\`%s[ \t]+" org-comment-string)) + "" h)) + (h h))) + (tags (and (not no-tags) (match-string 5)))) + (mapconcat #'identity + (delq nil (list todo priority headline tags)) + " "))))) + +(defvar orgstruct-mode) ; defined below + +(defun org-heading-components () + "Return the components of the current heading. +This is a list with the following elements: +- the level as an integer +- the reduced level, different if `org-odd-levels-only' is set. +- the TODO keyword, or nil +- the priority character, like ?A, or nil if no priority is given +- the headline text itself, or the tags string if no headline text +- the tags string, or nil." + (save-excursion + (org-back-to-heading t) + (when (let (case-fold-search) + (looking-at + (if orgstruct-mode + org-heading-regexp + org-complex-heading-regexp))) + (if orgstruct-mode + (list (length (match-string 1)) + (org-reduced-level (length (match-string 1))) + nil + nil + (match-string 2) + nil) + (list (length (match-string 1)) + (org-reduced-level (length (match-string 1))) + (match-string-no-properties 2) + (and (match-end 3) (aref (match-string 3) 2)) + (match-string-no-properties 4) + (match-string-no-properties 5)))))) + +(defun org-get-entry () + "Get the entry text, after heading, entire subtree." + (save-excursion + (org-back-to-heading t) + (buffer-substring (point-at-bol 2) (org-end-of-subtree t)))) + +(defun org-edit-headline (&optional heading) + "Edit the current headline. +Set it to HEADING when provided." + (interactive) + (org-with-wide-buffer + (org-back-to-heading t) + (let ((case-fold-search nil)) + (when (looking-at org-complex-heading-regexp) + (let* ((old (match-string-no-properties 4)) + (new (save-match-data + (org-trim (or heading (read-string "Edit: " old)))))) + (unless (equal old new) + (if old (replace-match new t t nil 4) + (goto-char (or (match-end 3) (match-end 2) (match-end 1))) + (insert " " new)) + (org-set-tags nil t) + (when (looking-at "[ \t]*$") (replace-match "")))))))) + +(defun org-insert-heading-after-current () + "Insert a new heading with same level as current, after current subtree." + (interactive) + (org-back-to-heading) + (org-insert-heading) + (org-move-subtree-down) + (end-of-line 1)) + +(defun org-insert-heading-respect-content (&optional invisible-ok) + "Insert heading with `org-insert-heading-respect-content' set to t." + (interactive) + (org-insert-heading '(4) invisible-ok)) + +(defun org-insert-todo-heading-respect-content (&optional force-state) + "Insert TODO heading with `org-insert-heading-respect-content' set to t." + (interactive) + (org-insert-todo-heading force-state '(4))) + +(defun org-insert-todo-heading (arg &optional force-heading) + "Insert a new heading with the same level and TODO state as current heading. + +If the heading has no TODO state, or if the state is DONE, use +the first state (TODO by default). Also with one prefix arg, +force first state. With two prefix args, force inserting at the +end of the parent subtree. + +When called at a plain list item, insert a new item with an +unchecked check box." + (interactive "P") + (when (or force-heading (not (org-insert-item 'checkbox))) + (org-insert-heading (or (and (equal arg '(16)) '(16)) + force-heading)) + (save-excursion + (org-forward-heading-same-level -1) + (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))) + (let* ((new-mark-x + (if (or (equal arg '(4)) + (not (match-beginning 2)) + (member (match-string 2) org-done-keywords)) + (car org-todo-keywords-1) + (match-string 2))) + (new-mark + (or + (run-hook-with-args-until-success + 'org-todo-get-default-hook new-mark-x nil) + new-mark-x))) + (beginning-of-line 1) + (and (looking-at org-outline-regexp) (goto-char (match-end 0)) + (if org-treat-insert-todo-heading-as-state-change + (org-todo new-mark) + (insert new-mark " ")))) + (when org-provide-todo-statistics + (org-update-parent-todo-statistics)))) + +(defun org-insert-subheading (arg) + "Insert a new subheading and demote it. +Works for outline headings and for plain lists alike." + (interactive "P") + (org-insert-heading arg) + (cond + ((org-at-heading-p) (org-do-demote)) + ((org-at-item-p) (org-indent-item)))) + +(defun org-insert-todo-subheading (arg) + "Insert a new subheading with TODO keyword or checkbox and demote it. +Works for outline headings and for plain lists alike." + (interactive "P") + (org-insert-todo-heading arg) + (cond + ((org-at-heading-p) (org-do-demote)) + ((org-at-item-p) (org-indent-item)))) + +;;; Promotion and Demotion + +(defvar org-after-demote-entry-hook nil + "Hook run after an entry has been demoted. +The cursor will be at the beginning of the entry. +When a subtree is being demoted, the hook will be called for each node.") + +(defvar org-after-promote-entry-hook nil + "Hook run after an entry has been promoted. +The cursor will be at the beginning of the entry. +When a subtree is being promoted, the hook will be called for each node.") + +(defun org-promote-subtree () + "Promote the entire subtree. +See also `org-promote'." + (interactive) + (save-excursion + (org-with-limited-levels (org-map-tree 'org-promote))) + (org-fix-position-after-promote)) + +(defun org-demote-subtree () + "Demote the entire subtree. +See `org-demote' and `org-promote'." + (interactive) + (save-excursion + (org-with-limited-levels (org-map-tree 'org-demote))) + (org-fix-position-after-promote)) + +(defun org-do-promote () + "Promote the current heading higher up the tree. +If the region is active in `transient-mark-mode', promote all +headings in the region." + (interactive) + (save-excursion + (if (org-region-active-p) + (org-map-region 'org-promote (region-beginning) (region-end)) + (org-promote))) + (org-fix-position-after-promote)) + +(defun org-do-demote () + "Demote the current heading lower down the tree. +If the region is active in `transient-mark-mode', demote all +headings in the region." + (interactive) + (save-excursion + (if (org-region-active-p) + (org-map-region 'org-demote (region-beginning) (region-end)) + (org-demote))) + (org-fix-position-after-promote)) + +(defun org-fix-position-after-promote () + "Fix cursor position and indentation after demoting/promoting." + (let ((pos (point))) + (when (save-excursion + (beginning-of-line) + (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)) + (or (eq pos (match-end 1)) (eq pos (match-end 2)))) + (cond ((eobp) (insert " ")) + ((eolp) (insert " ")) + ((equal (char-after) ?\s) (forward-char 1)))))) + +(defun org-current-level () + "Return the level of the current entry, or nil if before the first headline. +The level is the number of stars at the beginning of the +headline. Use `org-reduced-level' to remove the effect of +`org-odd-levels'. Unlike to `org-outline-level', this function +ignores inlinetasks." + (let ((level (org-with-limited-levels (org-outline-level)))) + (and (> level 0) level))) + +(defun org-get-previous-line-level () + "Return the outline depth of the last headline before the current line. +Returns 0 for the first headline in the buffer, and nil if before the +first headline." + (and (org-current-level) + (or (and (/= (line-beginning-position) (point-min)) + (save-excursion (beginning-of-line 0) (org-current-level))) + 0))) + +(defun org-reduced-level (l) + "Compute the effective level of a heading. +This takes into account the setting of `org-odd-levels-only'." + (cond + ((zerop l) 0) + (org-odd-levels-only (1+ (floor (/ l 2)))) + (t l))) + +(defun org-level-increment () + "Return the number of stars that will be added or removed at a +time to headlines when structure editing, based on the value of +`org-odd-levels-only'." + (if org-odd-levels-only 2 1)) + +(defun org-get-valid-level (level &optional change) + "Rectify a level change under the influence of `org-odd-levels-only'. +LEVEL is a current level, CHANGE is by how much the level should +be modified. Even if CHANGE is nil, LEVEL may be returned +modified because even level numbers will become the next higher +odd number. Returns values greater than 0." + (if org-odd-levels-only + (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2)))) + ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2)))) + ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2)))))) + (max 1 (+ level (or change 0))))) + +(defun org-promote () + "Promote the current heading higher up the tree." + (org-with-wide-buffer + (org-back-to-heading t) + (let* ((after-change-functions (remq 'flyspell-after-change-function + after-change-functions)) + (level (save-match-data (funcall outline-level))) + (up-head (concat (make-string (org-get-valid-level level -1) ?*) " ")) + (diff (abs (- level (length up-head) -1)))) + (cond + ((and (= level 1) org-allow-promoting-top-level-subtree) + (replace-match "# " nil t)) + ((= level 1) + (user-error "Cannot promote to level 0. UNDO to recover if necessary")) + (t (replace-match up-head nil t))) + (unless (= level 1) + (when org-auto-align-tags (org-set-tags nil 'ignore-column)) + (when org-adapt-indentation (org-fixup-indentation (- diff)))) + (run-hooks 'org-after-promote-entry-hook)))) + +(defun org-demote () + "Demote the current heading lower down the tree." + (org-with-wide-buffer + (org-back-to-heading t) + (let* ((after-change-functions (remq 'flyspell-after-change-function + after-change-functions)) + (level (save-match-data (funcall outline-level))) + (down-head (concat (make-string (org-get-valid-level level 1) ?*) " ")) + (diff (abs (- level (length down-head) -1)))) + (replace-match down-head nil t) + (when org-auto-align-tags (org-set-tags nil 'ignore-column)) + (when org-adapt-indentation (org-fixup-indentation diff)) + (run-hooks 'org-after-demote-entry-hook)))) + +(defun org-cycle-level () + "Cycle the level of an empty headline through possible states. +This goes first to child, then to parent, level, then up the hierarchy. +After top level, it switches back to sibling level." + (interactive) + (let ((org-adapt-indentation nil)) + (when (org-point-at-end-of-empty-headline) + (setq this-command 'org-cycle-level) ; Only needed for caching + (let ((cur-level (org-current-level)) + (prev-level (org-get-previous-line-level))) + (cond + ;; If first headline in file, promote to top-level. + ((= prev-level 0) + (cl-loop repeat (/ (- cur-level 1) (org-level-increment)) + do (org-do-promote))) + ;; If same level as prev, demote one. + ((= prev-level cur-level) + (org-do-demote)) + ;; If parent is top-level, promote to top level if not already. + ((= prev-level 1) + (cl-loop repeat (/ (- cur-level 1) (org-level-increment)) + do (org-do-promote))) + ;; If top-level, return to prev-level. + ((= cur-level 1) + (cl-loop repeat (/ (- prev-level 1) (org-level-increment)) + do (org-do-demote))) + ;; If less than prev-level, promote one. + ((< cur-level prev-level) + (org-do-promote)) + ;; If deeper than prev-level, promote until higher than + ;; prev-level. + ((> cur-level prev-level) + (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment))) + do (org-do-promote)))) + t)))) + +(defun org-map-tree (fun) + "Call FUN for every heading underneath the current one." + (org-back-to-heading t) + (let ((level (funcall outline-level))) + (save-excursion + (funcall fun) + (while (and (progn + (outline-next-heading) + (> (funcall outline-level) level)) + (not (eobp))) + (funcall fun))))) + +(defun org-map-region (fun beg end) + "Call FUN for every heading between BEG and END." + (let ((org-ignore-region t)) + (save-excursion + (setq end (copy-marker end)) + (goto-char beg) + (when (and (re-search-forward org-outline-regexp-bol nil t) + (< (point) end)) + (funcall fun)) + (while (and (progn + (outline-next-heading) + (< (point) end)) + (not (eobp))) + (funcall fun))))) + +(defun org-fixup-indentation (diff) + "Change the indentation in the current entry by DIFF. + +DIFF is an integer. Indentation is done according to the +following rules: + + - Planning information and property drawers are always indented + according to the new level of the headline; + + - Footnote definitions and their contents are ignored; + + - Inlinetasks' boundaries are not shifted; + + - Empty lines are ignored; + + - Other lines' indentation are shifted by DIFF columns, unless + it would introduce a structural change in the document, in + which case no shifting is done at all. + +Assume point is at a heading or an inlinetask beginning." + (org-with-wide-buffer + (narrow-to-region (line-beginning-position) + (save-excursion + (if (org-with-limited-levels (org-at-heading-p)) + (org-with-limited-levels (outline-next-heading)) + (org-inlinetask-goto-end)) + (point))) + (forward-line) + ;; Indent properly planning info and property drawer. + (when (looking-at-p org-planning-line-re) + (org-indent-line) + (forward-line)) + (when (looking-at org-property-drawer-re) + (goto-char (match-end 0)) + (forward-line) + (save-excursion (org-indent-region (match-beginning 0) (match-end 0)))) + (catch 'no-shift + (when (zerop diff) (throw 'no-shift nil)) + ;; If DIFF is negative, first check if a shift is possible at all + ;; (e.g., it doesn't break structure). This can only happen if + ;; some contents are not properly indented. + (let ((case-fold-search t)) + (when (< diff 0) + (let ((diff (- diff)) + (forbidden-re (concat org-outline-regexp + "\\|" + (substring org-footnote-definition-re 1)))) + (save-excursion + (while (not (eobp)) + (cond + ((looking-at-p "[ \t]*$") (forward-line)) + ((and (looking-at-p org-footnote-definition-re) + (let ((e (org-element-at-point))) + (and (eq (org-element-type e) 'footnote-definition) + (goto-char (org-element-property :end e)))))) + ((looking-at-p org-outline-regexp) (forward-line)) + ;; Give up if shifting would move before column 0 or + ;; if it would introduce a headline or a footnote + ;; definition. + (t + (skip-chars-forward " \t") + (let ((ind (current-column))) + (when (or (< ind diff) + (and (= ind diff) (looking-at-p forbidden-re))) + (throw 'no-shift nil))) + ;; Ignore contents of example blocks and source + ;; blocks if their indentation is meant to be + ;; preserved. Jump to block's closing line. + (beginning-of-line) + (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)") + (let ((e (org-element-at-point))) + (and (memq (org-element-type e) + '(example-block src-block)) + (or org-src-preserve-indentation + (org-element-property :preserve-indent e)) + (goto-char (org-element-property :end e)) + (progn (skip-chars-backward " \r\t\n") + (beginning-of-line) + t)))) + (forward-line)))))))) + ;; Shift lines but footnote definitions, inlinetasks boundaries + ;; by DIFF. Also skip contents of source or example blocks + ;; when indentation is meant to be preserved. + (while (not (eobp)) + (cond + ((and (looking-at-p org-footnote-definition-re) + (let ((e (org-element-at-point))) + (and (eq (org-element-type e) 'footnote-definition) + (goto-char (org-element-property :end e)))))) + ((looking-at-p org-outline-regexp) (forward-line)) + ((looking-at-p "[ \t]*$") (forward-line)) + (t + (indent-line-to (+ (org-get-indentation) diff)) + (beginning-of-line) + (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)") + (let ((e (org-element-at-point))) + (and (memq (org-element-type e) + '(example-block src-block)) + (or org-src-preserve-indentation + (org-element-property :preserve-indent e)) + (goto-char (org-element-property :end e)) + (progn (skip-chars-backward " \r\t\n") + (beginning-of-line) + t)))) + (forward-line))))))))) + +(defun org-convert-to-odd-levels () + "Convert an Org file with all levels allowed to one with odd levels. +This will leave level 1 alone, convert level 2 to level 3, level 3 to +level 5 etc." + (interactive) + (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ") + (let ((outline-level 'org-outline-level) + (org-odd-levels-only nil) n) + (save-excursion + (goto-char (point-min)) + (while (re-search-forward "^\\*\\*+ " nil t) + (setq n (- (length (match-string 0)) 2)) + (while (>= (setq n (1- n)) 0) + (org-demote)) + (end-of-line 1)))))) + +(defun org-convert-to-oddeven-levels () + "Convert an Org file with only odd levels to one with odd/even levels. +This promotes level 3 to level 2, level 5 to level 3 etc. If the +file contains a section with an even level, conversion would +destroy the structure of the file. An error is signaled in this +case." + (interactive) + (goto-char (point-min)) + ;; First check if there are no even levels + (when (re-search-forward "^\\(\\*\\*\\)+ " nil t) + (org-show-set-visibility 'canonical) + (error "Not all levels are odd in this file. Conversion not possible")) + (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ") + (let ((outline-regexp org-outline-regexp) + (outline-level 'org-outline-level) + (org-odd-levels-only nil) n) + (save-excursion + (goto-char (point-min)) + (while (re-search-forward "^\\*\\*+ " nil t) + (setq n (/ (1- (length (match-string 0))) 2)) + (while (>= (setq n (1- n)) 0) + (org-promote)) + (end-of-line 1)))))) + +(defun org-tr-level (n) + "Make N odd if required." + (if org-odd-levels-only (1+ (/ n 2)) n)) + +;;; Vertical tree motion, cutting and pasting of subtrees + +(defun org-move-subtree-up (&optional arg) + "Move the current subtree up past ARG headlines of the same level." + (interactive "p") + (org-move-subtree-down (- (prefix-numeric-value arg)))) + +(defun org-move-subtree-down (&optional arg) + "Move the current subtree down past ARG headlines of the same level." + (interactive "p") + (setq arg (prefix-numeric-value arg)) + (let ((movfunc (if (> arg 0) 'org-get-next-sibling + 'org-get-last-sibling)) + (ins-point (make-marker)) + (cnt (abs arg)) + (col (current-column)) + beg beg0 end txt folded ne-beg ne-end ne-ins ins-end) + ;; Select the tree + (org-back-to-heading) + (setq beg0 (point)) + (save-excursion + (setq ne-beg (org-back-over-empty-lines)) + (setq beg (point))) + (save-match-data + (save-excursion (outline-end-of-heading) + (setq folded (org-invisible-p))) + (progn (org-end-of-subtree nil t) + (unless (eobp) (backward-char)))) + (outline-next-heading) + (setq ne-end (org-back-over-empty-lines)) + (setq end (point)) + (goto-char beg0) + (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg)) + ;; include less whitespace + (save-excursion + (goto-char beg) + (forward-line (- ne-beg ne-end)) + (setq beg (point)))) + ;; Find insertion point, with error handling + (while (> cnt 0) + (or (and (funcall movfunc) (looking-at org-outline-regexp)) + (progn (goto-char beg0) + (user-error "Cannot move past superior level or buffer limit"))) + (setq cnt (1- cnt))) + (when (> arg 0) + ;; Moving forward - still need to move over subtree + (org-end-of-subtree t t) + (save-excursion + (org-back-over-empty-lines) + (or (bolp) (newline)))) + (setq ne-ins (org-back-over-empty-lines)) + (move-marker ins-point (point)) + (setq txt (buffer-substring beg end)) + (org-save-markers-in-region beg end) + (delete-region beg end) + (org-remove-empty-overlays-at beg) + (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil)) + (or (bobp) (outline-flag-region (1- (point)) (point) nil)) + (and (not (bolp)) (looking-at "\n") (forward-char 1)) + (let ((bbb (point))) + (insert-before-markers txt) + (org-reinstall-markers-in-region bbb) + (move-marker ins-point bbb)) + (or (bolp) (insert "\n")) + (setq ins-end (point)) + (goto-char ins-point) + (org-skip-whitespace) + (when (and (< arg 0) + (org-first-sibling-p) + (> ne-ins ne-beg)) + ;; Move whitespace back to beginning + (save-excursion + (goto-char ins-end) + (let ((kill-whole-line t)) + (kill-line (- ne-ins ne-beg)) (point))) + (insert (make-string (- ne-ins ne-beg) ?\n))) + (move-marker ins-point nil) + (if folded + (outline-hide-subtree) + (org-show-entry) + (org-show-children) + (org-cycle-hide-drawers 'children)) + (org-clean-visibility-after-subtree-move) + ;; move back to the initial column we were at + (move-to-column col))) + +(defvar org-subtree-clip "" + "Clipboard for cut and paste of subtrees. +This is actually only a copy of the kill, because we use the normal kill +ring. We need it to check if the kill was created by `org-copy-subtree'.") + +(defvar org-subtree-clip-folded nil + "Was the last copied subtree folded? +This is used to fold the tree back after pasting.") + +(defun org-cut-subtree (&optional n) + "Cut the current subtree into the clipboard. +With prefix arg N, cut this many sequential subtrees. +This is a short-hand for marking the subtree and then cutting it." + (interactive "p") + (org-copy-subtree n 'cut)) + +(defun org-copy-subtree (&optional n cut force-store-markers nosubtrees) + "Copy the current subtree into the clipboard. +With prefix arg N, copy this many sequential subtrees. +This is a short-hand for marking the subtree and then copying it. +If CUT is non-nil, actually cut the subtree. +If FORCE-STORE-MARKERS is non-nil, store the relative locations +of some markers in the region, even if CUT is non-nil. This is +useful if the caller implements cut-and-paste as copy-then-paste-then-cut." + (interactive "p") + (let (beg end folded (beg0 (point))) + (if (called-interactively-p 'any) + (org-back-to-heading nil) ; take what looks like a subtree + (org-back-to-heading t)) ; take what is really there + (setq beg (point)) + (skip-chars-forward " \t\r\n") + (save-match-data + (if nosubtrees + (outline-next-heading) + (save-excursion (outline-end-of-heading) + (setq folded (org-invisible-p))) + (ignore-errors (org-forward-heading-same-level (1- n) t)) + (org-end-of-subtree t t))) + ;; Include the end of an inlinetask + (when (and (featurep 'org-inlinetask) + (looking-at-p (concat (org-inlinetask-outline-regexp) + "END[ \t]*$"))) + (end-of-line)) + (setq end (point)) + (goto-char beg0) + (when (> end beg) + (setq org-subtree-clip-folded folded) + (when (or cut force-store-markers) + (org-save-markers-in-region beg end)) + (if cut (kill-region beg end) (copy-region-as-kill beg end)) + (setq org-subtree-clip (current-kill 0)) + (message "%s: Subtree(s) with %d characters" + (if cut "Cut" "Copied") + (length org-subtree-clip))))) + +(defun org-paste-subtree (&optional level tree for-yank remove) + "Paste the clipboard as a subtree, with modification of headline level. +The entire subtree is promoted or demoted in order to match a new headline +level. + +If the cursor is at the beginning of a headline, the same level as +that headline is used to paste the tree. + +If not, the new level is derived from the *visible* headings +before and after the insertion point, and taken to be the inferior headline +level of the two. So if the previous visible heading is level 3 and the +next is level 4 (or vice versa), level 4 will be used for insertion. +This makes sure that the subtree remains an independent subtree and does +not swallow low level entries. + +You can also force a different level, either by using a numeric prefix +argument, or by inserting the heading marker by hand. For example, if the +cursor is after \"*****\", then the tree will be shifted to level 5. + +If optional TREE is given, use this text instead of the kill ring. + +When FOR-YANK is set, this is called by `org-yank'. In this case, do not +move back over whitespace before inserting, and move point to the end of +the inserted text when done. + +When REMOVE is non-nil, remove the subtree from the clipboard." + (interactive "P") + (setq tree (or tree (and kill-ring (current-kill 0)))) + (unless (org-kill-is-subtree-p tree) + (user-error "%s" + (substitute-command-keys + "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway"))) + (org-with-limited-levels + (let* ((visp (not (org-invisible-p))) + (txt tree) + (old-level (if (string-match org-outline-regexp-bol txt) + (- (match-end 0) (match-beginning 0) 1) + -1)) + (force-level (cond (level (prefix-numeric-value level)) + ((and (looking-at "[ \t]*$") + (string-match + "^\\*+$" (buffer-substring + (point-at-bol) (point)))) + (- (match-end 0) (match-beginning 0))) + ((and (bolp) + (looking-at org-outline-regexp)) + (- (match-end 0) (point) 1)))) + (previous-level (save-excursion + (condition-case nil + (progn + (outline-previous-visible-heading 1) + (if (looking-at org-outline-regexp-bol) + (- (match-end 0) (match-beginning 0) 1) + 1)) + (error 1)))) + (next-level (save-excursion + (condition-case nil + (progn + (or (looking-at org-outline-regexp) + (outline-next-visible-heading 1)) + (if (looking-at org-outline-regexp-bol) + (- (match-end 0) (match-beginning 0) 1) + 1)) + (error 1)))) + (new-level (or force-level (max previous-level next-level))) + (shift (if (or (= old-level -1) + (= new-level -1) + (= old-level new-level)) + 0 + (- new-level old-level))) + (delta (if (> shift 0) -1 1)) + (func (if (> shift 0) 'org-demote 'org-promote)) + (org-odd-levels-only nil) + beg end newend) + ;; Remove the forced level indicator + (when force-level + (delete-region (point-at-bol) (point))) + ;; Paste + (beginning-of-line (if (bolp) 1 2)) + (setq beg (point)) + (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt)) + (insert-before-markers txt) + (unless (string-suffix-p "\n" txt) (insert "\n")) + (setq newend (point)) + (org-reinstall-markers-in-region beg) + (setq end (point)) + (goto-char beg) + (skip-chars-forward " \t\n\r") + (setq beg (point)) + (when (and (org-invisible-p) visp) + (save-excursion (outline-show-heading))) + ;; Shift if necessary + (unless (= shift 0) + (save-restriction + (narrow-to-region beg end) + (while (not (= shift 0)) + (org-map-region func (point-min) (point-max)) + (setq shift (+ delta shift))) + (goto-char (point-min)) + (setq newend (point-max)))) + (when (or (called-interactively-p 'interactive) for-yank) + (message "Clipboard pasted as level %d subtree" new-level)) + (when (and (not for-yank) ; in this case, org-yank will decide about folding + kill-ring + (eq org-subtree-clip (current-kill 0)) + org-subtree-clip-folded) + ;; The tree was folded before it was killed/copied + (outline-hide-subtree)) + (and for-yank (goto-char newend)) + (and remove (setq kill-ring (cdr kill-ring)))))) + +(defun org-kill-is-subtree-p (&optional txt) + "Check if the current kill is an outline subtree, or a set of trees. +Returns nil if kill does not start with a headline, or if the first +headline level is not the largest headline level in the tree. +So this will actually accept several entries of equal levels as well, +which is OK for `org-paste-subtree'. +If optional TXT is given, check this string instead of the current kill." + (let* ((kill (or txt (and kill-ring (current-kill 0)) "")) + (re (org-get-limited-outline-regexp)) + (^re (concat "^" re)) + (start-level (and kill + (string-match + (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)") + kill) + (- (match-end 2) (match-beginning 2) 1))) + (start (1+ (or (match-beginning 2) -1)))) + (if (not start-level) + (progn + nil) ;; does not even start with a heading + (catch 'exit + (while (setq start (string-match ^re kill (1+ start))) + (when (< (- (match-end 0) (match-beginning 0) 1) start-level) + (throw 'exit nil))) + t)))) + +(defvar org-markers-to-move nil + "Markers that should be moved with a cut-and-paste operation. +Those markers are stored together with their positions relative to +the start of the region.") + +(defun org-save-markers-in-region (beg end) + "Check markers in region. +If these markers are between BEG and END, record their position relative +to BEG, so that after moving the block of text, we can put the markers back +into place. +This function gets called just before an entry or tree gets cut from the +buffer. After re-insertion, `org-reinstall-markers-in-region' must be +called immediately, to move the markers with the entries." + (setq org-markers-to-move nil) + (when (featurep 'org-clock) + (org-clock-save-markers-for-cut-and-paste beg end)) + (when (featurep 'org-agenda) + (org-agenda-save-markers-for-cut-and-paste beg end))) + +(defun org-check-and-save-marker (marker beg end) + "Check if MARKER is between BEG and END. +If yes, remember the marker and the distance to BEG." + (when (and (marker-buffer marker) + (equal (marker-buffer marker) (current-buffer)) + (>= marker beg) (< marker end)) + (push (cons marker (- marker beg)) org-markers-to-move))) + +(defun org-reinstall-markers-in-region (beg) + "Move all remembered markers to their position relative to BEG." + (dolist (x org-markers-to-move) + (move-marker (car x) (+ beg (cdr x)))) + (setq org-markers-to-move nil)) + +(defun org-narrow-to-subtree () + "Narrow buffer to the current subtree." + (interactive) + (save-excursion + (save-match-data + (org-with-limited-levels + (narrow-to-region + (progn (org-back-to-heading t) (point)) + (progn (org-end-of-subtree t t) + (when (and (org-at-heading-p) (not (eobp))) (backward-char 1)) + (point))))))) + +(defun org-narrow-to-block () + "Narrow buffer to the current block." + (interactive) + (let* ((case-fold-search t) + (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*" + "^[ \t]*#\\+end_.*"))) + (if blockp + (narrow-to-region (car blockp) (cdr blockp)) + (user-error "Not in a block")))) + +(defun org-clone-subtree-with-time-shift (n &optional shift) + "Clone the task (subtree) at point N times. +The clones will be inserted as siblings. + +In interactive use, the user will be prompted for the number of +clones to be produced. If the entry has a timestamp, the user +will also be prompted for a time shift, which may be a repeater +as used in time stamps, for example `+3d'. To disable this, +you can call the function with a universal prefix argument. + +When a valid repeater is given and the entry contains any time +stamps, the clones will become a sequence in time, with time +stamps in the subtree shifted for each clone produced. If SHIFT +is nil or the empty string, time stamps will be left alone. The +ID property of the original subtree is removed. + +In each clone, all the CLOCK entries will be removed. This +prevents Org from considering that the clocked times overlap. + +If the original subtree did contain time stamps with a repeater, +the following will happen: +- the repeater will be removed in each clone +- an additional clone will be produced, with the current, unshifted + date(s) in the entry. +- the original entry will be placed *after* all the clones, with + repeater intact. +- the start days in the repeater in the original entry will be shifted + to past the last clone. +In this way you can spell out a number of instances of a repeating task, +and still retain the repeater to cover future instances of the task. + +As described above, N+1 clones are produced when the original +subtree has a repeater. Setting N to 0, then, can be used to +remove the repeater from a subtree and create a shifted clone +with the original repeater." + (interactive "nNumber of clones to produce: ") + (unless (wholenump n) (user-error "Invalid number of replications %s" n)) + (when (org-before-first-heading-p) (user-error "No subtree to clone")) + (let* ((beg (save-excursion (org-back-to-heading t) (point))) + (end-of-tree (save-excursion (org-end-of-subtree t t) (point))) + (shift + (or shift + (if (and (not (equal current-prefix-arg '(4))) + (save-excursion + (goto-char beg) + (re-search-forward org-ts-regexp-both end-of-tree t))) + (read-from-minibuffer + "Date shift per clone (e.g. +1w, empty to copy unchanged): ") + ""))) ;No time shift + (doshift + (and (org-string-nw-p shift) + (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'" + shift) + (user-error "Invalid shift specification %s" shift))))) + (goto-char end-of-tree) + (unless (bolp) (insert "\n")) + (let* ((end (point)) + (template (buffer-substring beg end)) + (shift-n (and doshift (string-to-number (match-string 1 shift)))) + (shift-what (pcase (and doshift (match-string 2 shift)) + (`nil nil) + ("d" 'day) + ("w" (setq shift-n (* 7 shift-n)) 'day) + ("m" 'month) + ("y" 'year) + (_ (error "Unsupported time unit")))) + (nmin 1) + (nmax n) + (n-no-remove -1) + (idprop (org-entry-get nil "ID"))) + (when (and doshift + (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" + template)) + (delete-region beg end) + (setq end beg) + (setq nmin 0) + (setq nmax (1+ nmax)) + (setq n-no-remove nmax)) + (goto-char end) + (cl-loop for n from nmin to nmax do + (insert + ;; Prepare clone. + (with-temp-buffer + (insert template) + (org-mode) + (goto-char (point-min)) + (org-show-subtree) + (and idprop (if org-clone-delete-id + (org-entry-delete nil "ID") + (org-id-get-create t))) + (unless (= n 0) + (while (re-search-forward org-clock-line-re nil t) + (delete-region (line-beginning-position) + (line-beginning-position 2))) + (goto-char (point-min)) + (while (re-search-forward org-drawer-regexp nil t) + (org-remove-empty-drawer-at (point)))) + (goto-char (point-min)) + (when doshift + (while (re-search-forward org-ts-regexp-both nil t) + (org-timestamp-change (* n shift-n) shift-what)) + (unless (= n n-no-remove) + (goto-char (point-min)) + (while (re-search-forward org-ts-regexp nil t) + (save-excursion + (goto-char (match-beginning 0)) + (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)") + (delete-region (match-beginning 1) (match-end 1))))))) + (buffer-string))))) + (goto-char beg))) + +;;; Outline Sorting + +(defun org-sort (&optional with-case) + "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'. +Optional argument WITH-CASE means sort case-sensitively." + (interactive "P") + (org-call-with-arg + (cond ((org-at-table-p) #'org-table-sort-lines) + ((org-at-item-p) #'org-sort-list) + (t #'org-sort-entries)) + with-case)) + +(defun org-sort-remove-invisible (s) + "Remove invisible part of links and emphasis markers from string S." + (remove-text-properties 0 (length s) org-rm-props s) + (replace-regexp-in-string + org-verbatim-re (lambda (m) (format "%s " (match-string 4 m))) + (replace-regexp-in-string + org-emph-re (lambda (m) (format " %s " (match-string 4 m))) + (org-link-display-format s) + t t) t t)) + +(defvar org-priority-regexp) ; defined later in the file + +(defvar org-after-sorting-entries-or-items-hook nil + "Hook that is run after a bunch of entries or items have been sorted. +When children are sorted, the cursor is in the parent line when this +hook gets called. When a region or a plain list is sorted, the cursor +will be in the first entry of the sorted region/list.") + +(defun org-sort-entries + (&optional with-case sorting-type getkey-func compare-func property + interactive?) + "Sort entries on a certain level of an outline tree. +If there is an active region, the entries in the region are sorted. +Else, if the cursor is before the first entry, sort the top-level items. +Else, the children of the entry at point are sorted. + +Sorting can be alphabetically, numerically, by date/time as given by +a time stamp, by a property, by priority order, or by a custom function. + +The command prompts for the sorting type unless it has been given to the +function through the SORTING-TYPE argument, which needs to be a character, +\(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is +the precise meaning of each character: + +a Alphabetically, ignoring the TODO keyword and the priority, if any. +c By creation time, which is assumed to be the first inactive time stamp + at the beginning of a line. +d By deadline date/time. +k By clocking time. +n Numerically, by converting the beginning of the entry/item to a number. +o By order of TODO keywords. +p By priority according to the cookie. +r By the value of a property. +s By scheduled date/time. +t By date/time, either the first active time stamp in the entry, or, if + none exist, by the first inactive one. + +Capital letters will reverse the sort order. + +If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be +called with point at the beginning of the record. It must return a +value that is compatible with COMPARE-FUNC, the function used to +compare entries. + +Comparing entries ignores case by default. However, with an optional argument +WITH-CASE, the sorting considers case as well. + +Sorting is done against the visible part of the headlines, it ignores hidden +links. + +When sorting is done, call `org-after-sorting-entries-or-items-hook'. + +A non-nil value for INTERACTIVE? is used to signal that this +function is being called interactively." + (interactive (list current-prefix-arg nil nil nil nil t)) + (let ((case-func (if with-case 'identity 'downcase)) + start beg end stars re re2 + txt what tmp) + ;; Find beginning and end of region to sort + (cond + ((org-region-active-p) + ;; we will sort the region + (setq end (region-end) + what "region") + (goto-char (region-beginning)) + (unless (org-at-heading-p) (outline-next-heading)) + (setq start (point))) + ((or (org-at-heading-p) + (ignore-errors (progn (org-back-to-heading) t))) + ;; we will sort the children of the current headline + (org-back-to-heading) + (setq start (point) + end (progn (org-end-of-subtree t t) + (or (bolp) (insert "\n")) + (when (>= (org-back-over-empty-lines) 1) + (forward-line 1)) + (point)) + what "children") + (goto-char start) + (outline-show-subtree) + (outline-next-heading)) + (t + ;; we will sort the top-level entries in this file + (goto-char (point-min)) + (or (org-at-heading-p) (outline-next-heading)) + (setq start (point)) + (goto-char (point-max)) + (beginning-of-line 1) + (when (looking-at ".*?\\S-") + ;; File ends in a non-white line + (end-of-line 1) + (insert "\n")) + (setq end (point-max)) + (setq what "top-level") + (goto-char start) + (outline-show-all))) + + (setq beg (point)) + (when (>= beg end) (goto-char start) (user-error "Nothing to sort")) + + (looking-at "\\(\\*+\\)") + (setq stars (match-string 1) + re (concat "^" (regexp-quote stars) " +") + re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]") + txt (buffer-substring beg end)) + (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n"))) + (when (and (not (equal stars "*")) (string-match re2 txt)) + (user-error "Region to sort contains a level above the first entry")) + + (unless sorting-type + (message + "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc + [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing + A/N/P/R/O/F/T/S/D/C/K means reversed:" + what) + (setq sorting-type (read-char-exclusive))) + + (unless getkey-func + (and (= (downcase sorting-type) ?f) + (setq getkey-func + (or (and interactive? + (org-read-function + "Function for extracting keys: ")) + (error "Missing key extractor"))))) + + (and (= (downcase sorting-type) ?r) + (not property) + (setq property + (completing-read "Property: " + (mapcar #'list (org-buffer-property-keys t)) + nil t))) + + (when (member sorting-type '(?k ?K)) (org-clock-sum)) + (message "Sorting entries...") + + (save-restriction + (narrow-to-region start end) + (let ((restore-clock? + ;; The clock marker is lost when using `sort-subr'; mark + ;; the clock with temporary `:org-clock-marker-backup' + ;; text property. + (when (and (eq (org-clock-is-active) (current-buffer)) + (<= start (marker-position org-clock-marker)) + (>= end (marker-position org-clock-marker))) + (org-with-silent-modifications + (put-text-property (1- org-clock-marker) org-clock-marker + :org-clock-marker-backup t)) + t)) + (dcst (downcase sorting-type)) + (case-fold-search nil) + (now (current-time))) + (sort-subr + (/= dcst sorting-type) + ;; This function moves to the beginning character of the "record" to + ;; be sorted. + (lambda nil + (if (re-search-forward re nil t) + (goto-char (match-beginning 0)) + (goto-char (point-max)))) + ;; This function moves to the last character of the "record" being + ;; sorted. + (lambda nil + (save-match-data + (condition-case nil + (outline-forward-same-level 1) + (error + (goto-char (point-max)))))) + ;; This function returns the value that gets sorted against. + (lambda nil + (cond + ((= dcst ?n) + (if (looking-at org-complex-heading-regexp) + (string-to-number (org-sort-remove-invisible (match-string 4))) + nil)) + ((= dcst ?a) + (if (looking-at org-complex-heading-regexp) + (funcall case-func (org-sort-remove-invisible (match-string 4))) + nil)) + ((= dcst ?k) + (or (get-text-property (point) :org-clock-minutes) 0)) + ((= dcst ?t) + (let ((end (save-excursion (outline-next-heading) (point)))) + (if (or (re-search-forward org-ts-regexp end t) + (re-search-forward org-ts-regexp-both end t)) + (org-time-string-to-seconds (match-string 0)) + (float-time now)))) + ((= dcst ?c) + (let ((end (save-excursion (outline-next-heading) (point)))) + (if (re-search-forward + (concat "^[ \t]*\\[" org-ts-regexp1 "\\]") + end t) + (org-time-string-to-seconds (match-string 0)) + (float-time now)))) + ((= dcst ?s) + (let ((end (save-excursion (outline-next-heading) (point)))) + (if (re-search-forward org-scheduled-time-regexp end t) + (org-time-string-to-seconds (match-string 1)) + (float-time now)))) + ((= dcst ?d) + (let ((end (save-excursion (outline-next-heading) (point)))) + (if (re-search-forward org-deadline-time-regexp end t) + (org-time-string-to-seconds (match-string 1)) + (float-time now)))) + ((= dcst ?p) + (if (re-search-forward org-priority-regexp (point-at-eol) t) + (string-to-char (match-string 2)) + org-default-priority)) + ((= dcst ?r) + (or (org-entry-get nil property) "")) + ((= dcst ?o) + (when (looking-at org-complex-heading-regexp) + (let* ((m (match-string 2)) + (s (if (member m org-done-keywords) '- '+))) + (- 99 (funcall s (length (member m org-todo-keywords-1))))))) + ((= dcst ?f) + (if getkey-func + (progn + (setq tmp (funcall getkey-func)) + (when (stringp tmp) (setq tmp (funcall case-func tmp))) + tmp) + (error "Invalid key function `%s'" getkey-func))) + (t (error "Invalid sorting type `%c'" sorting-type)))) + nil + (cond + ((= dcst ?a) 'string<) + ((= dcst ?f) + (or compare-func + (and interactive? + (org-read-function + (concat "Function for comparing keys " + "(empty for default `sort-subr' predicate): ") + 'allow-empty)))) + ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))) + (when restore-clock? + (move-marker org-clock-marker + (1+ (next-single-property-change + start :org-clock-marker-backup))) + (remove-text-properties (1- org-clock-marker) org-clock-marker + '(:org-clock-marker-backup t))))) + (run-hooks 'org-after-sorting-entries-or-items-hook) + (message "Sorting entries...done"))) + +;;; The orgstruct minor mode + +;; Define a minor mode which can be used in other modes in order to +;; integrate the Org mode structure editing commands. + +;; This is really a hack, because the Org mode structure commands use +;; keys which normally belong to the major mode. Here is how it +;; works: The minor mode defines all the keys necessary to operate the +;; structure commands, but wraps the commands into a function which +;; tests if the cursor is currently at a headline or a plain list +;; item. If that is the case, the structure command is used, +;; temporarily setting many Org mode variables like regular +;; expressions for filling etc. However, when any of those keys is +;; used at a different location, function uses `key-binding' to look +;; up if the key has an associated command in another currently active +;; keymap (minor modes, major mode, global), and executes that +;; command. There might be problems if any of the keys is otherwise +;; used as a prefix key. + +(defcustom orgstruct-heading-prefix-regexp "" + "Regexp that matches the custom prefix of Org headlines in +orgstruct(++)-mode." + :group 'org + :version "26.1" + :package-version '(Org . "8.3") + :type 'regexp) +;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp) + +(defcustom orgstruct-setup-hook nil + "Hook run after orgstruct-mode-map is filled." + :group 'org + :version "24.4" + :package-version '(Org . "8.0") + :type 'hook) + +(defvar orgstruct-initialized nil) + +(defvar org-local-vars nil + "List of local variables, for use by `orgstruct-mode'.") + +;;;###autoload +(define-minor-mode orgstruct-mode + "Toggle the minor mode `orgstruct-mode'. +This mode is for using Org mode structure commands in other +modes. The following keys behave as if Org mode were active, if +the cursor is on a headline, or on a plain list item (both as +defined by Org mode)." + nil " OrgStruct" (make-sparse-keymap) + (funcall (if orgstruct-mode + 'add-to-invisibility-spec + 'remove-from-invisibility-spec) + '(outline . t)) + (when orgstruct-mode + (org-load-modules-maybe) + (unless orgstruct-initialized + (orgstruct-setup) + (setq orgstruct-initialized t)))) + +;;;###autoload +(defun turn-on-orgstruct () + "Unconditionally turn on `orgstruct-mode'." + (orgstruct-mode 1)) + +(defvar-local orgstruct-is-++ nil + "Is `orgstruct-mode' in ++ version in the current-buffer?") +(defvar-local org-fb-vars nil) +(defun orgstruct++-mode (&optional arg) + "Toggle `orgstruct-mode', the enhanced version of it. +In addition to setting orgstruct-mode, this also exports all +indentation and autofilling variables from Org mode into the +buffer. It will also recognize item context in multiline items." + (interactive "P") + (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1)))) + (if (< arg 1) + (progn (orgstruct-mode -1) + (dolist (v org-fb-vars) + (set (make-local-variable (car v)) + (if (eq (car-safe (cadr v)) 'quote) + (cl-cadadr v) + (nth 1 v))))) + (orgstruct-mode 1) + (setq org-fb-vars nil) + (unless org-local-vars + (setq org-local-vars (org-get-local-variables))) + (let (var val) + (dolist (x org-local-vars) + (when (string-match + "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\ +\\|fill-prefix\\|indent-\\)" + (symbol-name (car x))) + (setq var (car x) val (nth 1 x)) + (push (list var `(quote ,(eval var))) org-fb-vars) + (set (make-local-variable var) + (if (eq (car-safe val) 'quote) (nth 1 val) val)))) + (setq-local orgstruct-is-++ t)))) + +;;;###autoload +(defun turn-on-orgstruct++ () + "Unconditionally turn on `orgstruct++-mode'." + (orgstruct++-mode 1)) + +(defun orgstruct-error () + "Error when there is no default binding for a structure key." + (interactive) + (funcall (if (fboundp 'user-error) + 'user-error + 'error) + "This key has no function outside structure elements")) + +(defun orgstruct-setup () + "Setup orgstruct keymap." + (dolist (cell '((org-demote . t) + (org-metaleft . t) + (org-metaright . t) + (org-promote . t) + (org-shiftmetaleft . t) + (org-shiftmetaright . t) + org-backward-element + org-backward-heading-same-level + org-ctrl-c-ret + org-ctrl-c-minus + org-ctrl-c-star + org-cycle + org-force-cycle-archived + org-forward-heading-same-level + org-insert-heading + org-insert-heading-respect-content + org-kill-note-or-show-branches + org-mark-subtree + org-meta-return + org-metadown + org-metaup + org-narrow-to-subtree + org-promote-subtree + org-reveal + org-shiftdown + org-shiftleft + org-shiftmetadown + org-shiftmetaup + org-shiftright + org-shifttab + org-shifttab + org-shiftup + org-show-children + org-show-subtree + org-sort + org-up-element + outline-demote + outline-next-visible-heading + outline-previous-visible-heading + outline-promote + outline-up-heading)) + (let ((f (or (car-safe cell) cell)) + (disable-when-heading-prefix (cdr-safe cell))) + (when (fboundp f) + (let ((new-bindings)) + (dolist (binding (nconc (where-is-internal f org-mode-map) + (where-is-internal f outline-mode-map))) + (push binding new-bindings) + ;; TODO use local-function-key-map + (dolist (rep '(("<tab>" . "TAB") + ("<return>" . "RET") + ("<escape>" . "ESC") + ("<delete>" . "DEL"))) + (setq binding (read-kbd-macro + (let ((case-fold-search)) + (replace-regexp-in-string + (regexp-quote (cdr rep)) + (car rep) + (key-description binding))))) + (cl-pushnew binding new-bindings :test 'equal))) + (dolist (binding new-bindings) + (let ((key (lookup-key orgstruct-mode-map binding))) + (when (or (not key) (numberp key)) + (ignore-errors + (org-defkey orgstruct-mode-map + binding + (orgstruct-make-binding + f binding disable-when-heading-prefix)))))))))) + (run-hooks 'orgstruct-setup-hook)) + +(defun orgstruct-make-binding (fun key disable-when-heading-prefix) + "Create a function for binding in the structure minor mode. +FUN is the command to call inside a table. KEY is the key that +should be checked in for a command to execute outside of tables. +Non-nil `disable-when-heading-prefix' means to disable the command +if `orgstruct-heading-prefix-regexp' is not empty." + (let ((name (concat "orgstruct-hijacker-" (symbol-name fun)))) + (let ((nname name) + (i 0)) + (while (fboundp (intern nname)) + (setq nname (format "%s-%d" name (setq i (1+ i))))) + (setq name (intern nname))) + (eval + (let ((bindings '((org-heading-regexp + (concat "^" + orgstruct-heading-prefix-regexp + "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$")) + (org-outline-regexp + (concat orgstruct-heading-prefix-regexp "\\*+ ")) + (org-outline-regexp-bol + (concat "^" org-outline-regexp)) + (outline-regexp org-outline-regexp) + (outline-heading-end-regexp "\n") + (outline-level 'org-outline-level) + (outline-heading-alist)))) + `(defun ,name (arg) + ,(concat "In Structure, run `" (symbol-name fun) "'.\n" + "Outside of structure, run the binding of `" + (key-description key) "'." + (when disable-when-heading-prefix + (concat + "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n" + "back to the default binding due to limitations of Org's implementation of\n" + "`" (symbol-name fun) "'."))) + (interactive "p") + (let* ((disable + ,(and disable-when-heading-prefix + '(not (string= orgstruct-heading-prefix-regexp "")))) + (fallback + (or disable + (not + (let* ,bindings + (org-context-p 'headline 'item + ,(when (memq fun + '(org-insert-heading + org-insert-heading-respect-content + org-meta-return)) + '(when orgstruct-is-++ + 'item-body)))))))) + (if fallback + (let* ((orgstruct-mode) + (binding + (let ((key ,key)) + (catch 'exit + (dolist + (rep + '(nil + ("<\\([^>]*\\)tab>" . "\\1TAB") + ("<\\([^>]*\\)return>" . "\\1RET") + ("<\\([^>]*\\)escape>" . "\\1ESC") + ("<\\([^>]*\\)delete>" . "\\1DEL")) + nil) + (when rep + (setq key (read-kbd-macro + (let ((case-fold-search)) + (replace-regexp-in-string + (car rep) + (cdr rep) + (key-description key)))))) + (when (key-binding key) + (throw 'exit (key-binding key)))))))) + (if (keymapp binding) + (org-set-transient-map binding) + (let ((func (or binding + (unless disable + 'orgstruct-error)))) + (when func + (call-interactively func))))) + (org-run-like-in-org-mode + (lambda () + (interactive) + (let* ,bindings + (call-interactively ',fun))))))))) + name)) + +(defun org-contextualize-keys (alist contexts) + "Return valid elements in ALIST depending on CONTEXTS. + +`org-agenda-custom-commands' or `org-capture-templates' are the +values used for ALIST, and `org-agenda-custom-commands-contexts' +or `org-capture-templates-contexts' are the associated contexts +definitions." + (let ((contexts + ;; normalize contexts + (mapcar + (lambda(c) (cond ((listp (cadr c)) + (list (car c) (car c) (nth 1 c))) + ((string= "" (cadr c)) + (list (car c) (car c) (nth 2 c))) + (t c))) + contexts)) + (a alist) r s) + ;; loop over all commands or templates + (dolist (c a) + (let (vrules repl) + (cond + ((not (assoc (car c) contexts)) + (push c r)) + ((and (assoc (car c) contexts) + (setq vrules (org-contextualize-validate-key + (car c) contexts))) + (mapc (lambda (vr) + (unless (equal (car vr) (cadr vr)) + (setq repl vr))) + vrules) + (if (not repl) (push c r) + (push (cadr repl) s) + (push + (cons (car c) + (cdr (or (assoc (cadr repl) alist) + (error "Undefined key `%s' as contextual replacement for `%s'" + (cadr repl) (car c))))) + r)))))) + ;; Return limited ALIST, possibly with keys modified, and deduplicated + (delq + nil + (delete-dups + (mapcar (lambda (x) + (let ((tpl (car x))) + (unless (delq + nil + (mapcar (lambda (y) + (equal y tpl)) + s)) + x))) + (reverse r)))))) + +(defun org-contextualize-validate-key (key contexts) + "Check CONTEXTS for agenda or capture KEY." + (let (res) + (dolist (r contexts) + (dolist (rr (car (last r))) + (when + (and (equal key (car r)) + (if (functionp rr) (funcall rr) + (or (and (eq (car rr) 'in-file) + (buffer-file-name) + (string-match (cdr rr) (buffer-file-name))) + (and (eq (car rr) 'in-mode) + (string-match (cdr rr) (symbol-name major-mode))) + (and (eq (car rr) 'in-buffer) + (string-match (cdr rr) (buffer-name))) + (when (and (eq (car rr) 'not-in-file) + (buffer-file-name)) + (not (string-match (cdr rr) (buffer-file-name)))) + (when (eq (car rr) 'not-in-mode) + (not (string-match (cdr rr) (symbol-name major-mode)))) + (when (eq (car rr) 'not-in-buffer) + (not (string-match (cdr rr) (buffer-name))))))) + (push r res)))) + (delete-dups (delq nil res)))) + +(defun org-context-p (&rest contexts) + "Check if local context is any of CONTEXTS. +Possible values in the list of contexts are `table', `headline', and `item'." + (let ((pos (point))) + (goto-char (point-at-bol)) + (prog1 (or (and (memq 'table contexts) + (looking-at "[ \t]*|")) + (and (memq 'headline contexts) + (looking-at org-outline-regexp)) + (and (memq 'item contexts) + (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")) + (and (memq 'item-body contexts) + (org-in-item-p))) + (goto-char pos)))) + +;;;###autoload +(defun org-run-like-in-org-mode (cmd) + "Run a command, pretending that the current buffer is in Org mode. +This will temporarily bind local variables that are typically bound in +Org mode to the values they have in Org mode, and then interactively +call CMD." + (org-load-modules-maybe) + (unless org-local-vars + (setq org-local-vars (org-get-local-variables))) + (let (binds) + (dolist (var org-local-vars) + (when (or (not (boundp (car var))) + (eq (symbol-value (car var)) + (default-value (car var)))) + (push (list (car var) `(quote ,(cadr var))) binds))) + (eval `(let ,binds + (call-interactively (quote ,cmd)))))) + +(defun org-get-category (&optional pos force-refresh) + "Get the category applying to position POS." + (save-match-data + (when force-refresh (org-refresh-category-properties)) + (let ((pos (or pos (point)))) + (or (get-text-property pos 'org-category) + (progn (org-refresh-category-properties) + (get-text-property pos 'org-category)))))) + +;;; Refresh properties + +(defun org-refresh-properties (dprop tprop) + "Refresh buffer text properties. +DPROP is the drawer property and TPROP is either the +corresponding text property to set, or an alist with each element +being a text property (as a symbol) and a function to apply to +the value of the drawer property." + (let* ((case-fold-search t) + (inhibit-read-only t) + (inherit? (org-property-inherit-p dprop)) + (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t)) + (global (and inherit? (org--property-global-value dprop nil)))) + (org-with-silent-modifications + (org-with-point-at 1 + ;; Set global values (e.g., values defined through + ;; "#+PROPERTY:" keywords) to the whole buffer. + (when global (put-text-property (point-min) (point-max) tprop global)) + ;; Set local values. + (while (re-search-forward property-re nil t) + (when (org-at-property-p) + (org-refresh-property tprop (org-entry-get (point) dprop) inherit?)) + (outline-next-heading)))))) + +(defun org-refresh-property (tprop p &optional inherit) + "Refresh the buffer text property TPROP from the drawer property P. +The refresh happens only for the current headline, or the whole +sub-tree if optional argument INHERIT is non-nil." + (unless (org-before-first-heading-p) + (save-excursion + (org-back-to-heading t) + (let ((start (point)) + (end (save-excursion + (if inherit (org-end-of-subtree t t) + (or (outline-next-heading) (point-max)))))) + (if (symbolp tprop) + ;; TPROP is a text property symbol. + (put-text-property start end tprop p) + ;; TPROP is an alist with (property . function) elements. + (pcase-dolist (`(,prop . ,f) tprop) + (put-text-property start end prop (funcall f p)))))))) + +(defun org-refresh-category-properties () + "Refresh category text properties in the buffer." + (let ((case-fold-search t) + (inhibit-read-only t) + (default-category + (cond ((null org-category) + (if buffer-file-name + (file-name-sans-extension + (file-name-nondirectory buffer-file-name)) + "???")) + ((symbolp org-category) (symbol-name org-category)) + (t org-category)))) + (org-with-silent-modifications + (org-with-wide-buffer + ;; Set buffer-wide category. Search last #+CATEGORY keyword. + ;; This is the default category for the buffer. If none is + ;; found, fall-back to `org-category' or buffer file name. + (put-text-property + (point-min) (point-max) + 'org-category + (catch 'buffer-category + (goto-char (point-max)) + (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t) + (let ((element (org-element-at-point))) + (when (eq (org-element-type element) 'keyword) + (throw 'buffer-category + (org-element-property :value element))))) + default-category)) + ;; Set sub-tree specific categories. + (goto-char (point-min)) + (let ((regexp (org-re-property "CATEGORY"))) + (while (re-search-forward regexp nil t) + (let ((value (match-string-no-properties 3))) + (when (org-at-property-p) + (put-text-property + (save-excursion (org-back-to-heading t) (point)) + (save-excursion (org-end-of-subtree t t) (point)) + 'org-category + value))))))))) + +(defun org-refresh-stats-properties () + "Refresh stats text properties in the buffer." + (org-with-silent-modifications + (org-with-point-at 1 + (let ((regexp (concat org-outline-regexp-bol + ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]"))) + (while (re-search-forward regexp nil t) + (let* ((numerator (string-to-number (match-string 1))) + (denominator (and (match-end 2) + (string-to-number (match-string 2)))) + (stats (cond ((not denominator) numerator) ;percent + ((= denominator 0) 0) + (t (/ (* numerator 100) denominator))))) + (put-text-property (point) (progn (org-end-of-subtree t t) (point)) + 'org-stats stats))))))) + +(defun org-refresh-effort-properties () + "Refresh effort properties" + (org-refresh-properties + org-effort-property + '((effort . identity) + (effort-minutes . org-duration-to-minutes)))) + +;;;; Link Stuff + +;;; Link abbreviations + +(defun org-link-expand-abbrev (link) + "Apply replacements as defined in `org-link-abbrev-alist'." + (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link) + (let* ((key (match-string 1 link)) + (as (or (assoc key org-link-abbrev-alist-local) + (assoc key org-link-abbrev-alist))) + (tag (and (match-end 2) (match-string 3 link))) + rpl) + (if (not as) + link + (setq rpl (cdr as)) + (cond + ((symbolp rpl) (funcall rpl tag)) + ((string-match "%(\\([^)]+\\))" rpl) + (replace-match + (save-match-data + (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl)) + ((string-match "%s" rpl) (replace-match (or tag "") t t rpl)) + ((string-match "%h" rpl) + (replace-match (url-hexify-string (or tag "")) t t rpl)) + (t (concat rpl tag))))) + link)) + +;;; Storing and inserting links + +(defvar org-insert-link-history nil + "Minibuffer history for links inserted with `org-insert-link'.") + +(defvar org-stored-links nil + "Contains the links stored with `org-store-link'.") + +(defvar org-store-link-plist nil + "Plist with info about the most recently link created with `org-store-link'.") + +(defun org-store-link-functions () + "Return a list of functions that are called to create and store a link. +The functions defined in the :store property of +`org-link-parameters'. + +Each function will be called in turn until one returns a non-nil +value. Each function should check if it is responsible for +creating this link (for example by looking at the major mode). +If not, it must exit and return nil. If yes, it should return +a non-nil value after calling `org-store-link-props' with a list +of properties and values. Special properties are: + +:type The link prefix, like \"http\". This must be given. +:link The link, like \"http://www.astro.uva.nl/~dominik\". + This is obligatory as well. +:description Optional default description for the second pair + of brackets in an Org mode link. The user can still change + this when inserting this link into an Org mode buffer. + +In addition to these, any additional properties can be specified +and then used in capture templates." + (cl-loop for link in org-link-parameters + with store-func + do (setq store-func (org-link-get-parameter (car link) :store)) + if store-func + collect store-func)) + +(defvar org-agenda-buffer-name) ; Defined in org-agenda.el +(defvar org-id-link-to-org-use-id) ; Defined in org-id.el + +;;;###autoload +(defun org-store-link (arg) + "Store an org-link to the current location. +\\<org-mode-map> +This link is added to `org-stored-links' and can later be inserted +into an Org buffer with `org-insert-link' (`\\[org-insert-link]'). + +For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \ +A single +`\\[universal-argument]' negates `org-context-in-file-links' for file links or +`org-gnus-prefer-web-links' for links to Usenet articles. + +A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \ +skipping storing functions that are not +part of Org core. + +A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \ +prefix ARG forces storing a link for each line in the +active region." + (interactive "P") + (org-load-modules-maybe) + (if (and (equal arg '(64)) (org-region-active-p)) + (save-excursion + (let ((end (region-end))) + (goto-char (region-beginning)) + (set-mark (point)) + (while (< (point-at-eol) end) + (move-end-of-line 1) (activate-mark) + (let (current-prefix-arg) + (call-interactively 'org-store-link)) + (move-beginning-of-line 2) + (set-mark (point))))) + (setq org-store-link-plist nil) + (let (link cpltxt desc description search txt custom-id agenda-link) + (cond + ;; Store a link using an external link type, if any function is + ;; available. If more than one can generate a link from current + ;; location, ask which one to use. + ((and (not (equal arg '(16))) + (let ((results-alist nil)) + (dolist (f (org-store-link-functions)) + (when (funcall f) + ;; XXX: return value is not link's plist, so we + ;; store the new value before it is modified. It + ;; would be cleaner to ask store link functions to + ;; return the plist instead. + (push (cons f (copy-sequence org-store-link-plist)) + results-alist))) + (pcase results-alist + (`nil nil) + (`((,_ . ,_)) t) ;single choice: nothing to do + (`((,name . ,_) . ,_) + ;; Reinstate link plist associated to the chosen + ;; function. + (apply #'org-store-link-props + (cdr (assoc-string + (completing-read + "Which function for creating the link? " + (mapcar #'car results-alist) + nil t (symbol-name name)) + results-alist))) + t)))) + (setq link (plist-get org-store-link-plist :link)) + (setq desc (or (plist-get org-store-link-plist :description) + link))) + + ;; Store a link from a source code buffer. + ((org-src-edit-buffer-p) + (let ((coderef-format (org-src-coderef-format))) + (cond ((save-excursion + (beginning-of-line) + (looking-at (org-src-coderef-regexp coderef-format))) + (setq link (format "(%s)" (match-string-no-properties 3)))) + ((called-interactively-p 'any) + (let ((label (read-string "Code line label: "))) + (end-of-line) + (setq link (format coderef-format label)) + (let ((gc (- 79 (length link)))) + (if (< (current-column) gc) + (org-move-to-column gc t) + (insert " "))) + (insert link) + (setq link (concat "(" label ")")) + (setq desc nil))) + (t (setq link nil))))) + + ;; We are in the agenda, link to referenced location + ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name)) + (let ((m (or (get-text-property (point) 'org-hd-marker) + (get-text-property (point) 'org-marker)))) + (when m + (org-with-point-at m + (setq agenda-link + (if (called-interactively-p 'any) + (call-interactively 'org-store-link) + (org-store-link nil))))))) + + ((eq major-mode 'calendar-mode) + (let ((cd (calendar-cursor-to-date))) + (setq link + (format-time-string + (car org-time-stamp-formats) + (apply 'encode-time + (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd) + nil nil nil)))) + (org-store-link-props :type "calendar" :date cd))) + + ((eq major-mode 'help-mode) + (setq link (concat "help:" (save-excursion + (goto-char (point-min)) + (looking-at "^[^ ]+") + (match-string 0)))) + (org-store-link-props :type "help")) + + ((eq major-mode 'w3-mode) + (setq cpltxt (if (and (buffer-name) + (not (string-match "Untitled" (buffer-name)))) + (buffer-name) + (url-view-url t)) + link (url-view-url t)) + (org-store-link-props :type "w3" :url (url-view-url t))) + + ((eq major-mode 'image-mode) + (setq cpltxt (concat "file:" + (abbreviate-file-name buffer-file-name)) + link cpltxt) + (org-store-link-props :type "image" :file buffer-file-name)) + + ;; In dired, store a link to the file of the current line + ((derived-mode-p 'dired-mode) + (let ((file (dired-get-filename nil t))) + (setq file (if file + (abbreviate-file-name + (expand-file-name (dired-get-filename nil t))) + ;; otherwise, no file so use current directory. + default-directory)) + (setq cpltxt (concat "file:" file) + link cpltxt))) + + ((setq search (run-hook-with-args-until-success + 'org-create-file-search-functions)) + (setq link (concat "file:" (abbreviate-file-name buffer-file-name) + "::" search)) + (setq cpltxt (or description link))) + + ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode)) + (org-with-limited-levels + (setq custom-id (org-entry-get nil "CUSTOM_ID")) + (cond + ;; Store a link using the target at point + ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1) + (setq cpltxt + (concat "file:" + (abbreviate-file-name + (buffer-file-name (buffer-base-buffer))) + "::" (match-string 1)) + link cpltxt)) + ((and (featurep 'org-id) + (or (eq org-id-link-to-org-use-id t) + (and (called-interactively-p 'any) + (or (eq org-id-link-to-org-use-id 'create-if-interactive) + (and (eq org-id-link-to-org-use-id + 'create-if-interactive-and-no-custom-id) + (not custom-id)))) + (and org-id-link-to-org-use-id (org-entry-get nil "ID")))) + ;; Store a link using the ID at point + (setq link (condition-case nil + (prog1 (org-id-store-link) + (setq desc (or (plist-get org-store-link-plist + :description) + ""))) + (error + ;; Probably before first headline, link only to file + (concat "file:" + (abbreviate-file-name + (buffer-file-name (buffer-base-buffer)))))))) + (t + ;; Just link to current headline + (setq cpltxt (concat "file:" + (abbreviate-file-name + (buffer-file-name (buffer-base-buffer))))) + ;; Add a context search string + (when (org-xor org-context-in-file-links + (equal arg '(4))) + (let* ((element (org-element-at-point)) + (name (org-element-property :name element))) + (setq txt (cond + ((org-at-heading-p) nil) + (name) + ((org-region-active-p) + (buffer-substring (region-beginning) (region-end))))) + (when (or (null txt) (string-match "\\S-" txt)) + (setq cpltxt + (concat cpltxt "::" + (condition-case nil + (org-make-org-heading-search-string txt) + (error ""))) + desc (or name + (nth 4 (ignore-errors (org-heading-components))) + "NONE"))))) + (when (string-match "::\\'" cpltxt) + (setq cpltxt (substring cpltxt 0 -2))) + (setq link cpltxt))))) + + ((buffer-file-name (buffer-base-buffer)) + ;; Just link to this file here. + (setq cpltxt (concat "file:" + (abbreviate-file-name + (buffer-file-name (buffer-base-buffer))))) + ;; Add a context string. + (when (org-xor org-context-in-file-links + (equal arg '(4))) + (setq txt (if (org-region-active-p) + (buffer-substring (region-beginning) (region-end)) + (buffer-substring (point-at-bol) (point-at-eol)))) + ;; Only use search option if there is some text. + (when (string-match "\\S-" txt) + (setq cpltxt + (concat cpltxt "::" (org-make-org-heading-search-string txt)) + desc "NONE"))) + (setq link cpltxt)) + + ((called-interactively-p 'interactive) + (user-error "No method for storing a link from this buffer")) + + (t (setq link nil))) + + ;; We're done setting link and desc, clean up + (when (consp link) (setq cpltxt (car link) link (cdr link))) + (setq link (or link cpltxt) + desc (or desc cpltxt)) + (cond ((not desc)) + ((equal desc "NONE") (setq desc nil)) + (t (setq desc + (replace-regexp-in-string + org-bracket-link-analytic-regexp + (lambda (m) (or (match-string 5 m) (match-string 3 m))) + desc)))) + ;; Return the link + (if (not (and (or (called-interactively-p 'any) + executing-kbd-macro) + link)) + (or agenda-link (and link (org-make-link-string link desc))) + (push (list link desc) org-stored-links) + (message "Stored: %s" (or desc link)) + (when custom-id + (setq link (concat "file:" (abbreviate-file-name + (buffer-file-name)) "::#" custom-id)) + (push (list link desc) org-stored-links)) + (car org-stored-links))))) + +(defun org-store-link-props (&rest plist) + "Store link properties. +The properties are pre-processed by extracting names, addresses +and dates." + (let ((x (plist-get plist :from))) + (when x + (let ((adr (mail-extract-address-components x))) + (setq plist (plist-put plist :fromname (car adr))) + (setq plist (plist-put plist :fromaddress (nth 1 adr)))))) + (let ((x (plist-get plist :to))) + (when x + (let ((adr (mail-extract-address-components x))) + (setq plist (plist-put plist :toname (car adr))) + (setq plist (plist-put plist :toaddress (nth 1 adr)))))) + (let ((x (ignore-errors (date-to-time (plist-get plist :date))))) + (when x + (setq plist (plist-put plist :date-timestamp + (format-time-string + (org-time-stamp-format t) x))) + (setq plist (plist-put plist :date-timestamp-inactive + (format-time-string + (org-time-stamp-format t t) x))))) + (let ((from (plist-get plist :from)) + (to (plist-get plist :to))) + (when (and from to org-from-is-user-regexp) + (setq plist + (plist-put plist :fromto + (if (string-match org-from-is-user-regexp from) + (concat "to %t") + (concat "from %f")))))) + (setq org-store-link-plist plist)) + +(defun org-add-link-props (&rest plist) + "Add these properties to the link property list." + (let (key value) + (while plist + (setq key (pop plist) value (pop plist)) + (setq org-store-link-plist + (plist-put org-store-link-plist key value))))) + +(defun org-email-link-description (&optional fmt) + "Return the description part of an email link. +This takes information from `org-store-link-plist' and formats it +according to FMT (default from `org-email-link-description-format')." + (setq fmt (or fmt org-email-link-description-format)) + (let* ((p org-store-link-plist) + (to (plist-get p :toaddress)) + (from (plist-get p :fromaddress)) + (table + (list + (cons "%c" (plist-get p :fromto)) + (cons "%F" (plist-get p :from)) + (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?")) + (cons "%T" (plist-get p :to)) + (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?")) + (cons "%s" (plist-get p :subject)) + (cons "%d" (plist-get p :date)) + (cons "%m" (plist-get p :message-id))))) + (when (string-match "%c" fmt) + ;; Check if the user wrote this message + (if (and org-from-is-user-regexp from to + (save-match-data (string-match org-from-is-user-regexp from))) + (setq fmt (replace-match "to %t" t t fmt)) + (setq fmt (replace-match "from %f" t t fmt)))) + (org-replace-escapes fmt table))) + +(defun org-make-org-heading-search-string (&optional string) + "Make search string for the current headline or STRING." + (let ((s (or string + (and (derived-mode-p 'org-mode) + (save-excursion + (org-back-to-heading t) + (org-element-property :raw-value (org-element-at-point)))))) + (lines org-context-in-file-links)) + (unless string (setq s (concat "*" s))) ;Add * for headlines + (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s)) + (when (and string (integerp lines) (> lines 0)) + (let ((slines (org-split-string s "\n"))) + (when (< lines (length slines)) + (setq s (mapconcat + 'identity + (reverse (nthcdr (- (length slines) lines) + (reverse slines))) "\n"))))) + (mapconcat #'identity (split-string s) " "))) + +(defconst org-link-escape-chars + ;;%20 %5B %5D %25 + '(?\s ?\[ ?\] ?%) + "List of characters that should be escaped in a link when stored to Org. +This is the list that is used for internal purposes.") + +(defun org-make-link-string (link &optional description) + "Make a link with brackets, consisting of LINK and DESCRIPTION." + (unless (org-string-nw-p link) (error "Empty link")) + (let ((uri (cond ((string-match org-link-types-re link) + (concat (match-string 1 link) + (org-link-escape (substring link (match-end 1))))) + ((or (file-name-absolute-p link) + (string-match-p "\\`\\.\\.?/" link)) + (org-link-escape link)) + ;; For readability, do not encode space characters + ;; in fuzzy links. + (t (org-link-escape link (remq ?\s org-link-escape-chars))))) + (description + (and (org-string-nw-p description) + ;; Remove brackets from description, as they are fatal. + (replace-regexp-in-string + "[][]" (lambda (m) (if (equal "[" m) "{" "}")) + (org-trim description))))) + (format "[[%s]%s]" + uri + (if description (format "[%s]" description) "")))) + +(defun org-link-escape (text &optional table merge) + "Return percent escaped representation of TEXT. +TEXT is a string with the text to escape. +Optional argument TABLE is a list with characters that should be +escaped. When nil, `org-link-escape-chars' is used. +If optional argument MERGE is set, merge TABLE into +`org-link-escape-chars'." + (let ((characters-to-encode + (cond ((null table) org-link-escape-chars) + (merge (append org-link-escape-chars table)) + (t table)))) + (mapconcat + (lambda (c) + (if (or (memq c characters-to-encode) + (and org-url-hexify-p (or (< c 32) (> c 126)))) + (mapconcat (lambda (e) (format "%%%.2X" e)) + (or (encode-coding-char c 'utf-8) + (error "Unable to percent escape character: %c" c)) + "") + (char-to-string c))) + text ""))) + +(defun org-link-unescape (str) + "Unhex hexified Unicode parts in string STR. +E.g. `%C3%B6' becomes the german o-Umlaut. This is the +reciprocal of `org-link-escape', which see." + (if (org-string-nw-p str) + (replace-regexp-in-string + "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t) + str)) + +(defun org-link-unescape-compound (hex) + "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut. +Note: this function also decodes single byte encodings like +`%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group." + (save-match-data + (let* ((bytes (cdr (split-string hex "%"))) + (ret "") + (eat 0) + (sum 0)) + (while bytes + (let* ((val (string-to-number (pop bytes) 16)) + (shift-xor + (if (= 0 eat) + (cond + ((>= val 252) (cons 6 252)) + ((>= val 248) (cons 5 248)) + ((>= val 240) (cons 4 240)) + ((>= val 224) (cons 3 224)) + ((>= val 192) (cons 2 192)) + (t (cons 0 0))) + (cons 6 128)))) + (when (>= val 192) (setq eat (car shift-xor))) + (setq val (logxor val (cdr shift-xor))) + (setq sum (+ (lsh sum (car shift-xor)) val)) + (when (> eat 0) (setq eat (- eat 1))) + (cond + ((= 0 eat) ;multi byte + (setq ret (concat ret (char-to-string sum))) + (setq sum 0)) + ((not bytes) ; single byte(s) + (setq ret (org-link-unescape-single-byte-sequence hex)))))) + ret))) + +(defun org-link-unescape-single-byte-sequence (hex) + "Unhexify hex-encoded single byte character sequences." + (mapconcat (lambda (byte) + (char-to-string (string-to-number byte 16))) + (cdr (split-string hex "%")) "")) + +(defun org-xor (a b) + "Exclusive or." + (if a (not b) b)) + +(defun org-fixup-message-id-for-http (s) + "Replace special characters in a message id, so it can be used in an http query." + (when (string-match "%" s) + (setq s (mapconcat (lambda (c) + (if (eq c ?%) + "%25" + (char-to-string c))) + s ""))) + (while (string-match "<" s) + (setq s (replace-match "%3C" t t s))) + (while (string-match ">" s) + (setq s (replace-match "%3E" t t s))) + (while (string-match "@" s) + (setq s (replace-match "%40" t t s))) + s) + +(defun org-link-prettify (link) + "Return a human-readable representation of LINK. +The car of LINK must be a raw link. +The cdr of LINK must be either a link description or nil." + (let ((desc (or (cadr link) "<no description>"))) + (concat (format "%-45s" (substring desc 0 (min (length desc) 40))) + "<" (car link) ">"))) + +;;;###autoload +(defun org-insert-link-global () + "Insert a link like Org mode does. +This command can be called in any mode to insert a link in Org syntax." + (interactive) + (org-load-modules-maybe) + (org-run-like-in-org-mode 'org-insert-link)) + +(defun org-insert-all-links (arg &optional pre post) + "Insert all links in `org-stored-links'. +When a universal prefix, do not delete the links from `org-stored-links'. +When `ARG' is a number, insert the last N link(s). +`PRE' and `POST' are optional arguments to define a string to +prepend or to append." + (interactive "P") + (let ((org-keep-stored-link-after-insertion (equal arg '(4))) + (links (copy-sequence org-stored-links)) + (pr (or pre "- ")) + (po (or post "\n")) + (cnt 1) l) + (if (null org-stored-links) + (message "No link to insert") + (while (and (or (listp arg) (>= arg cnt)) + (setq l (if (listp arg) + (pop links) + (pop org-stored-links)))) + (setq cnt (1+ cnt)) + (insert pr) + (org-insert-link nil (car l) (or (cadr l) "<no description>")) + (insert po))))) + +(defun org-insert-last-stored-link (arg) + "Insert the last link stored in `org-stored-links'." + (interactive "p") + (org-insert-all-links arg "" "\n")) + +(defun org-link-fontify-links-to-this-file () + "Fontify links to the current file in `org-stored-links'." + (let ((f (buffer-file-name)) a b) + (setq a (mapcar (lambda(l) + (let ((ll (car l))) + (when (and (string-match "^file:\\(.+\\)::" ll) + (equal f (expand-file-name (match-string 1 ll)))) + ll))) + org-stored-links)) + (when (featurep 'org-id) + (setq b (mapcar (lambda(l) + (let ((ll (car l))) + (when (and (string-match "^id:\\(.+\\)$" ll) + (equal f (expand-file-name + (or (org-id-find-id-file + (match-string 1 ll)) "")))) + ll))) + org-stored-links))) + (mapcar (lambda(l) + (put-text-property 0 (length l) 'face 'font-lock-comment-face l)) + (delq nil (append a b))))) + +(defvar org--links-history nil) +(defun org-insert-link (&optional complete-file link-location default-description) + "Insert a link. At the prompt, enter the link. + +Completion can be used to insert any of the link protocol prefixes in use. + +The history can be used to select a link previously stored with +`org-store-link'. When the empty string is entered (i.e. if you just +press `RET' at the prompt), the link defaults to the most recently +stored link. As `SPC' triggers completion in the minibuffer, you need to +use `M-SPC' or `C-q SPC' to force the insertion of a space character. + +You will also be prompted for a description, and if one is given, it will +be displayed in the buffer instead of the link. + +If there is already a link at point, this command will allow you to edit +link and description parts. + +With a `\\[universal-argument]' prefix, prompts for a file to link to. The \ +file name can be +selected using completion. The path to the file will be relative to the +current directory if the file is in the current directory or a subdirectory. +Otherwise, the link will be the absolute path as completed in the minibuffer +\(i.e. normally ~/path/to/file). You can configure this behavior using the +option `org-link-file-path-type'. + +With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \ +absolute path even if the file is in +the current directory or below. + +A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \ +prefix negates `org-keep-stored-link-after-insertion'. + +If the LINK-LOCATION parameter is non-nil, this value will be used as +the link location instead of reading one interactively. + +If the DEFAULT-DESCRIPTION parameter is non-nil, this value will +be used as the default description. Otherwise, if +`org-make-link-description-function' is non-nil, this function +will be called with the link target, and the result will be the +default link description." + (interactive "P") + (let* ((wcf (current-window-configuration)) + (origbuf (current-buffer)) + (region (when (org-region-active-p) + (buffer-substring (region-beginning) (region-end)))) + (remove (and region (list (region-beginning) (region-end)))) + (desc region) + (link link-location) + (abbrevs org-link-abbrev-alist-local) + entry all-prefixes auto-desc) + (cond + (link-location) ; specified by arg, just use it. + ((org-in-regexp org-bracket-link-regexp 1) + ;; We do have a link at point, and we are going to edit it. + (setq remove (list (match-beginning 0) (match-end 0))) + (setq desc (when (match-end 3) (match-string-no-properties 3))) + (setq link (read-string "Link: " + (org-link-unescape + (match-string-no-properties 1))))) + ((or (org-in-regexp org-angle-link-re) + (org-in-regexp org-plain-link-re)) + ;; Convert to bracket link + (setq remove (list (match-beginning 0) (match-end 0)) + link (read-string "Link: " + (org-unbracket-string "<" ">" (match-string 0))))) + ((member complete-file '((4) (16))) + ;; Completing read for file names. + (setq link (org-file-complete-link complete-file))) + (t + ;; Read link, with completion for stored links. + (org-link-fontify-links-to-this-file) + (org-switch-to-buffer-other-window "*Org Links*") + (with-current-buffer "*Org Links*" + (erase-buffer) + (insert "Insert a link. +Use TAB to complete link prefixes, then RET for type-specific completion support\n") + (when org-stored-links + (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n") + (insert (mapconcat 'org-link-prettify + (reverse org-stored-links) "\n"))) + (goto-char (point-min))) + (let ((cw (selected-window))) + (select-window (get-buffer-window "*Org Links*" 'visible)) + (with-current-buffer "*Org Links*" (setq truncate-lines t)) + (unless (pos-visible-in-window-p (point-max)) + (org-fit-window-to-buffer)) + (and (window-live-p cw) (select-window cw))) + (setq all-prefixes (append (mapcar 'car abbrevs) + (mapcar 'car org-link-abbrev-alist) + (org-link-types))) + (unwind-protect + ;; Fake a link history, containing the stored links. + (let ((org--links-history + (append (mapcar #'car org-stored-links) + org-insert-link-history))) + (setq link + (org-completing-read + "Link: " + (append + (mapcar (lambda (x) (concat x ":")) all-prefixes) + (mapcar #'car org-stored-links)) + nil nil nil + 'org--links-history + (caar org-stored-links))) + (unless (org-string-nw-p link) (user-error "No link selected")) + (dolist (l org-stored-links) + (when (equal link (cadr l)) + (setq link (car l)) + (setq auto-desc t))) + (when (or (member link all-prefixes) + (and (equal ":" (substring link -1)) + (member (substring link 0 -1) all-prefixes) + (setq link (substring link 0 -1)))) + (setq link (with-current-buffer origbuf + (org-link-try-special-completion link))))) + (set-window-configuration wcf) + (kill-buffer "*Org Links*")) + (setq entry (assoc link org-stored-links)) + (or entry (push link org-insert-link-history)) + (setq desc (or desc (nth 1 entry))))) + + (when (funcall (if (equal complete-file '(64)) 'not 'identity) + (not org-keep-stored-link-after-insertion)) + (setq org-stored-links (delq (assoc link org-stored-links) + org-stored-links))) + + (when (and (string-match org-plain-link-re link) + (not (string-match org-ts-regexp link))) + ;; URL-like link, normalize the use of angular brackets. + (setq link (org-unbracket-string "<" ">" link))) + + ;; Check if we are linking to the current file with a search + ;; option If yes, simplify the link by using only the search + ;; option. + (when (and buffer-file-name + (let ((case-fold-search nil)) + (string-match "\\`file:\\(.+?\\)::" link))) + (let ((path (match-string-no-properties 1 link)) + (search (substring-no-properties link (match-end 0)))) + (save-match-data + (when (equal (file-truename buffer-file-name) (file-truename path)) + ;; We are linking to this same file, with a search option + (setq link search))))) + + ;; Check if we can/should use a relative path. If yes, simplify + ;; the link. + (let ((case-fold-search nil)) + (when (string-match "\\`\\(file\\|docview\\):" link) + (let* ((type (match-string-no-properties 0 link)) + (path-start (match-end 0)) + (search (and (string-match "::\\(.*\\)\\'" link) + (match-string 1 link))) + (path + (if search + (substring-no-properties + link path-start (match-beginning 0)) + (substring-no-properties link (match-end 0)))) + (origpath path)) + (cond + ((or (eq org-link-file-path-type 'absolute) + (equal complete-file '(16))) + (setq path (abbreviate-file-name (expand-file-name path)))) + ((eq org-link-file-path-type 'noabbrev) + (setq path (expand-file-name path))) + ((eq org-link-file-path-type 'relative) + (setq path (file-relative-name path))) + (t + (save-match-data + (if (string-match (concat "^" (regexp-quote + (expand-file-name + (file-name-as-directory + default-directory)))) + (expand-file-name path)) + ;; We are linking a file with relative path name. + (setq path (substring (expand-file-name path) + (match-end 0))) + (setq path (abbreviate-file-name (expand-file-name path))))))) + (setq link (concat type path (and search (concat "::" search)))) + (when (equal desc origpath) + (setq desc path))))) + + (unless auto-desc + (let ((initial-input + (cond + (default-description) + ((not org-make-link-description-function) desc) + (t (condition-case nil + (funcall org-make-link-description-function link desc) + (error + (message "Can't get link description from `%s'" + (symbol-name org-make-link-description-function)) + (sit-for 2) + nil)))))) + (setq desc (read-string "Description: " initial-input)))) + + (unless (string-match "\\S-" desc) (setq desc nil)) + (when remove (apply 'delete-region remove)) + (insert (org-make-link-string link desc)) + ;; Redisplay so as the new link has proper invisible characters. + (sit-for 0))) + +(defun org-link-try-special-completion (type) + "If there is completion support for link type TYPE, offer it." + (let ((fun (org-link-get-parameter type :complete))) + (if (functionp fun) + (funcall fun) + (read-string "Link (no completion support): " (concat type ":"))))) + +(defun org-file-complete-link (&optional arg) + "Create a file link using completion." + (let ((file (read-file-name "File: ")) + (pwd (file-name-as-directory (expand-file-name "."))) + (pwd1 (file-name-as-directory (abbreviate-file-name + (expand-file-name "."))))) + (cond ((equal arg '(16)) + (concat "file:" + (abbreviate-file-name (expand-file-name file)))) + ((string-match + (concat "^" (regexp-quote pwd1) "\\(.+\\)") file) + (concat "file:" (match-string 1 file))) + ((string-match + (concat "^" (regexp-quote pwd) "\\(.+\\)") + (expand-file-name file)) + (concat "file:" + (match-string 1 (expand-file-name file)))) + (t (concat "file:" file))))) + +(defun org-completing-read (&rest args) + "Completing-read with SPACE being a normal character." + (let ((enable-recursive-minibuffers t) + (minibuffer-local-completion-map + (copy-keymap minibuffer-local-completion-map))) + (org-defkey minibuffer-local-completion-map " " 'self-insert-command) + (org-defkey minibuffer-local-completion-map "?" 'self-insert-command) + (org-defkey minibuffer-local-completion-map (kbd "C-c !") + 'org-time-stamp-inactive) + (apply #'completing-read args))) + +;;; Opening/following a link + +(defvar org-link-search-failed nil) + +(defvar org-open-link-functions nil + "Hook for functions finding a plain text link. +These functions must take a single argument, the link content. +They will be called for links that look like [[link text][description]] +when LINK TEXT does not have a protocol like \"http:\" and does not look +like a filename (e.g. \"./blue.png\"). + +These functions will be called *before* Org attempts to resolve the +link by doing text searches in the current buffer - so if you want a +link \"[[target]]\" to still find \"<<target>>\", your function should +handle this as a special case. + +When the function does handle the link, it must return a non-nil value. +If it decides that it is not responsible for this link, it must return +nil to indicate that that Org can continue with other options like +exact and fuzzy text search.") + +(defun org-next-link (&optional search-backward) + "Move forward to the next link. +If the link is in hidden text, expose it." + (interactive "P") + (when (and org-link-search-failed (eq this-command last-command)) + (goto-char (point-min)) + (message "Link search wrapped back to beginning of buffer")) + (setq org-link-search-failed nil) + (let* ((pos (point)) + (ct (org-context)) + (a (assq :link ct)) + (srch-fun (if search-backward 're-search-backward 're-search-forward))) + (cond (a (goto-char (nth (if search-backward 1 2) a))) + ((looking-at org-any-link-re) + ;; Don't stay stuck at link without an org-link face + (forward-char (if search-backward -1 1)))) + (if (funcall srch-fun org-any-link-re nil t) + (progn + (goto-char (match-beginning 0)) + (when (org-invisible-p) (org-show-context))) + (goto-char pos) + (setq org-link-search-failed t) + (message "No further link found")))) + +(defun org-previous-link () + "Move backward to the previous link. +If the link is in hidden text, expose it." + (interactive) + (funcall 'org-next-link t)) + +(defun org-translate-link (s) + "Translate a link string if a translation function has been defined." + (with-temp-buffer + (insert (org-trim s)) + (org-trim (org-element-interpret-data (org-element-context))))) + +(defun org-translate-link-from-planner (type path) + "Translate a link from Emacs Planner syntax so that Org can follow it. +This is still an experimental function, your mileage may vary." + (cond + ((member type '("http" "https" "news" "ftp")) + ;; standard Internet links are the same. + nil) + ((and (equal type "irc") (string-match "^//" path)) + ;; Planner has two / at the beginning of an irc link, we have 1. + ;; We should have zero, actually.... + (setq path (substring path 1))) + ((and (equal type "lisp") (string-match "^/" path)) + ;; Planner has a slash, we do not. + (setq type "elisp" path (substring path 1))) + ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path) + ;; A typical message link. Planner has the id after the final slash, + ;; we separate it with a hash mark + (setq path (concat (match-string 1 path) "#" + (org-unbracket-string "<" ">" (match-string 2 path)))))) + (cons type path)) + +(defun org-find-file-at-mouse (ev) + "Open file link or URL at mouse." + (interactive "e") + (mouse-set-point ev) + (org-open-at-point 'in-emacs)) + +(defun org-open-at-mouse (ev) + "Open file link or URL at mouse. +See the docstring of `org-open-file' for details." + (interactive "e") + (mouse-set-point ev) + (when (eq major-mode 'org-agenda-mode) + (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)) + (org-open-at-point)) + +(defvar org-window-config-before-follow-link nil + "The window configuration before following a link. +This is saved in case the need arises to restore it.") + +;;;###autoload +(defun org-open-at-point-global () + "Follow a link or time-stamp like Org mode does. +This command can be called in any mode to follow an external link +or a time-stamp that has Org mode syntax. Its behavior is +undefined when called on internal links (e.g., fuzzy links). +Raise an error when there is nothing to follow. " + (interactive) + (cond ((org-in-regexp org-any-link-re) + (org-open-link-from-string (match-string-no-properties 0))) + ((or (org-in-regexp org-ts-regexp-both nil t) + (org-in-regexp org-tsr-regexp-both nil t)) + (org-follow-timestamp-link)) + (t (user-error "No link found")))) + +;;;###autoload +(defun org-open-link-from-string (s &optional arg reference-buffer) + "Open a link in the string S, as if it was in Org mode." + (interactive "sLink: \nP") + (let ((reference-buffer (or reference-buffer (current-buffer)))) + (with-temp-buffer + (let ((org-inhibit-startup (not reference-buffer))) + (org-mode) + (insert s) + (goto-char (point-min)) + (when reference-buffer + (setq org-link-abbrev-alist-local + (with-current-buffer reference-buffer + org-link-abbrev-alist-local))) + (org-open-at-point arg reference-buffer))))) + +(defvar org-open-at-point-functions nil + "Hook that is run when following a link at point. + +Functions in this hook must return t if they identify and follow +a link at point. If they don't find anything interesting at point, +they must return nil.") + +(defvar org-link-search-inhibit-query nil) +(defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el +(defun org--open-doi-link (path) + "Open a \"doi\" type link. +PATH is a the path to search for, as a string." + (browse-url (url-encode-url (concat org-doi-server-url path)))) + +(defun org--open-elisp-link (path) + "Open a \"elisp\" type link. +PATH is the sexp to evaluate, as a string." + (let ((cmd path)) + (if (or (and (org-string-nw-p + org-confirm-elisp-link-not-regexp) + (string-match-p org-confirm-elisp-link-not-regexp cmd)) + (not org-confirm-elisp-link-function) + (funcall org-confirm-elisp-link-function + (format "Execute \"%s\" as elisp? " + (org-add-props cmd nil 'face 'org-warning)))) + (message "%s => %s" cmd + (if (eq (string-to-char cmd) ?\() + (eval (read cmd)) + (call-interactively (read cmd)))) + (user-error "Abort")))) + +(defun org--open-help-link (path) + "Open a \"help\" type link. +PATH is a symbol name, as a string." + (pcase (intern path) + ((and (pred fboundp) variable) (describe-function variable)) + ((and (pred boundp) function) (describe-variable function)) + (name (user-error "Unknown function or variable: %s" name)))) + +(defun org--open-shell-link (path) + "Open a \"shell\" type link. +PATH is the command to execute, as a string." + (let ((buf (generate-new-buffer "*Org Shell Output*")) + (cmd path)) + (if (or (and (org-string-nw-p + org-confirm-shell-link-not-regexp) + (string-match + org-confirm-shell-link-not-regexp cmd)) + (not org-confirm-shell-link-function) + (funcall org-confirm-shell-link-function + (format "Execute \"%s\" in shell? " + (org-add-props cmd nil + 'face 'org-warning)))) + (progn + (message "Executing %s" cmd) + (shell-command cmd buf) + (when (featurep 'midnight) + (setq clean-buffer-list-kill-buffer-names + (cons (buffer-name buf) + clean-buffer-list-kill-buffer-names)))) + (user-error "Abort")))) + +(defun org-open-at-point (&optional arg reference-buffer) + "Open link, timestamp, footnote or tags at point. + +When point is on a link, follow it. Normally, files will be +opened by an appropriate application. If the optional prefix +argument ARG is non-nil, Emacs will visit the file. With +a double prefix argument, try to open outside of Emacs, in the +application the system uses for this file type. + +When point is on a timestamp, open the agenda at the day +specified. + +When point is a footnote definition, move to the first reference +found. If it is on a reference, move to the associated +definition. + +When point is on a headline, display a list of every link in the +entry, so it is possible to pick one, or all, of them. If point +is on a tag, call `org-tags-view' instead. + +When optional argument REFERENCE-BUFFER is non-nil, it should +specify a buffer from where the link search should happen. This +is used internally by `org-open-link-from-string'. + +On top of syntactically correct links, this function will also +try to open links and time-stamps in comments, example +blocks... i.e., whenever point is on something looking like +a timestamp or a link." + (interactive "P") + ;; On a code block, open block's results. + (unless (call-interactively 'org-babel-open-src-block-result) + (org-load-modules-maybe) + (setq org-window-config-before-follow-link (current-window-configuration)) + (org-remove-occur-highlights nil nil t) + (unless (run-hook-with-args-until-success 'org-open-at-point-functions) + (let* ((context + ;; Only consider supported types, even if they are not + ;; the closest one. + (org-element-lineage + (org-element-context) + '(clock footnote-definition footnote-reference headline + inlinetask link timestamp) + t)) + (type (org-element-type context)) + (value (org-element-property :value context))) + (cond + ;; On a headline or an inlinetask, but not on a timestamp, + ;; a link, a footnote reference. + ((memq type '(headline inlinetask)) + (org-match-line org-complex-heading-regexp) + (if (and (match-beginning 5) + (>= (point) (match-beginning 5)) + (< (point) (match-end 5))) + ;; On tags. + (org-tags-view arg (substring (match-string 5) 0 -1)) + ;; Not on tags. + (pcase (org-offer-links-in-entry (current-buffer) (point) arg) + (`(nil . ,_) + (require 'org-attach) + (org-attach-reveal 'if-exists)) + (`(,links . ,links-end) + (dolist (link (if (stringp links) (list links) links)) + (search-forward link nil links-end) + (goto-char (match-beginning 0)) + (org-open-at-point)))))) + ;; On a footnote reference or at definition's label. + ((or (eq type 'footnote-reference) + (and (eq type 'footnote-definition) + (save-excursion + ;; Do not validate action when point is on the + ;; spaces right after the footnote label, in + ;; order to be on par with behavior on links. + (skip-chars-forward " \t") + (let ((begin + (org-element-property :contents-begin context))) + (if begin (< (point) begin) + (= (org-element-property :post-affiliated context) + (line-beginning-position))))))) + (org-footnote-action)) + ;; No valid context. Ignore catch-all types like `headline'. + ;; If point is on something looking like a link or + ;; a time-stamp, try opening it. It may be useful in + ;; comments, example blocks... + ((memq type '(footnote-definition headline inlinetask nil)) + (call-interactively #'org-open-at-point-global)) + ;; On a clock line, make sure point is on the timestamp + ;; before opening it. + ((and (eq type 'clock) + value + (>= (point) (org-element-property :begin value)) + (<= (point) (org-element-property :end value))) + (org-follow-timestamp-link)) + ;; Do nothing on white spaces after an object. + ((>= (point) + (save-excursion + (goto-char (org-element-property :end context)) + (skip-chars-backward " \t") + (point))) + (user-error "No link found")) + ((eq type 'timestamp) (org-follow-timestamp-link)) + ((eq type 'link) + (let ((type (org-element-property :type context)) + (path (org-link-unescape (org-element-property :path context)))) + ;; Switch back to REFERENCE-BUFFER needed when called in + ;; a temporary buffer through `org-open-link-from-string'. + (with-current-buffer (or reference-buffer (current-buffer)) + (cond + ((equal type "file") + (if (string-match "[*?{]" (file-name-nondirectory path)) + (dired path) + ;; Look into `org-link-parameters' in order to find + ;; a DEDICATED-FUNCTION to open file. The function + ;; will be applied on raw link instead of parsed + ;; link due to the limitation in `org-add-link-type' + ;; ("open" function called with a single argument). + ;; If no such function is found, fallback to + ;; `org-open-file'. + (let* ((option (org-element-property :search-option context)) + (app (org-element-property :application context)) + (dedicated-function + (org-link-get-parameter + (if app (concat type "+" app) type) + :follow))) + (if dedicated-function + (funcall dedicated-function + (concat path + (and option (concat "::" option)))) + (apply #'org-open-file + path + (cond (arg) + ((equal app "emacs") 'emacs) + ((equal app "sys") 'system)) + (cond ((not option) nil) + ((string-match-p "\\`[0-9]+\\'" option) + (list (string-to-number option))) + (t (list nil + (org-link-unescape option))))))))) + ((functionp (org-link-get-parameter type :follow)) + (funcall (org-link-get-parameter type :follow) path)) + ((member type '("coderef" "custom-id" "fuzzy" "radio")) + (unless (run-hook-with-args-until-success + 'org-open-link-functions path) + (if (not arg) (org-mark-ring-push) + (switch-to-buffer-other-window + (org-get-buffer-for-internal-link (current-buffer)))) + (let ((destination + (org-with-wide-buffer + (if (equal type "radio") + (org-search-radio-target + (org-element-property :path context)) + (org-link-search + (if (member type '("custom-id" "coderef")) + (org-element-property :raw-link context) + path) + ;; Prevent fuzzy links from matching + ;; themselves. + (and (equal type "fuzzy") + (+ 2 (org-element-property :begin context))))) + (point)))) + (unless (and (<= (point-min) destination) + (>= (point-max) destination)) + (widen)) + (goto-char destination)))) + (t (browse-url-at-point)))))) + (t (user-error "No link found"))))) + (run-hook-with-args 'org-follow-link-hook))) + +(defun org-offer-links-in-entry (buffer marker &optional nth zero) + "Offer links in the current entry and return the selected link. +If there is only one link, return it. +If NTH is an integer, return the NTH link found. +If ZERO is a string, check also this string for a link, and if +there is one, return it." + (with-current-buffer buffer + (org-with-wide-buffer + (goto-char marker) + (let ((cnt ?0) + have-zero end links link c) + (when (and (stringp zero) (string-match org-bracket-link-regexp zero)) + (push (match-string 0 zero) links) + (setq cnt (1- cnt) have-zero t)) + (save-excursion + (org-back-to-heading t) + (setq end (save-excursion (outline-next-heading) (point))) + (while (re-search-forward org-any-link-re end t) + (push (match-string 0) links)) + (setq links (org-uniquify (reverse links)))) + (cond + ((null links) + (message "No links")) + ((equal (length links) 1) + (setq link (car links))) + ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth))) + (setq link (nth (if have-zero nth (1- nth)) links))) + (t ; we have to select a link + (save-excursion + (save-window-excursion + (delete-other-windows) + (with-output-to-temp-buffer "*Select Link*" + (dolist (l links) + (cond + ((not (string-match org-bracket-link-regexp l)) + (princ (format "[%c] %s\n" (cl-incf cnt) + (org-unbracket-string "<" ">" l)))) + ((match-end 3) + (princ (format "[%c] %s (%s)\n" (cl-incf cnt) + (match-string 3 l) (match-string 1 l)))) + (t (princ (format "[%c] %s\n" (cl-incf cnt) + (match-string 1 l))))))) + (org-fit-window-to-buffer (get-buffer-window "*Select Link*")) + (message "Select link to open, RET to open all:") + (setq c (read-char-exclusive)) + (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*")))) + (when (equal c ?q) (user-error "Abort")) + (if (equal c ?\C-m) + (setq link links) + (setq nth (- c ?0)) + (when have-zero (setq nth (1+ nth))) + (unless (and (integerp nth) (>= (length links) nth)) + (user-error "Invalid link selection")) + (setq link (nth (1- nth) links))))) + (cons link end))))) + +;; TODO: These functions are deprecated since `org-open-at-point' +;; hard-codes behavior for "file+emacs" and "file+sys" types. +(defun org-open-file-with-system (path) + "Open file at PATH using the system way of opening it." + (org-open-file path 'system)) +(defun org-open-file-with-emacs (path) + "Open file at PATH in Emacs." + (org-open-file path 'emacs)) + + +;;; File search + +(defvar org-create-file-search-functions nil + "List of functions to construct the right search string for a file link. +These functions are called in turn with point at the location to +which the link should point. + +A function in the hook should first test if it would like to +handle this file type, for example by checking the `major-mode' +or the file extension. If it decides not to handle this file, it +should just return nil to give other functions a chance. If it +does handle the file, it must return the search string to be used +when following the link. The search string will be part of the +file link, given after a double colon, and `org-open-at-point' +will automatically search for it. If special measures must be +taken to make the search successful, another function should be +added to the companion hook `org-execute-file-search-functions', +which see. + +A function in this hook may also use `setq' to set the variable +`description' to provide a suggestion for the descriptive text to +be used for this link when it gets inserted into an Org buffer +with \\[org-insert-link].") + +(defvar org-execute-file-search-functions nil + "List of functions to execute a file search triggered by a link. + +Functions added to this hook must accept a single argument, the +search string that was part of the file link, the part after the +double colon. The function must first check if it would like to +handle this search, for example by checking the `major-mode' or +the file extension. If it decides not to handle this search, it +should just return nil to give other functions a chance. If it +does handle the search, it must return a non-nil value to keep +other functions from trying. + +Each function can access the current prefix argument through the +variable `current-prefix-arg'. Note that a single prefix is used +to force opening a link in Emacs, so it may be good to only use a +numeric or double prefix to guide the search function. + +In case this is needed, a function in this hook can also restore +the window configuration before `org-open-at-point' was called using: + + (set-window-configuration org-window-config-before-follow-link)") + +(defun org-search-radio-target (target) + "Search a radio target matching TARGET in current buffer. +White spaces are not significant." + (let ((re (format "<<<%s>>>" + (mapconcat #'regexp-quote + (split-string target) + "[ \t]+\\(?:\n[ \t]*\\)?"))) + (origin (point))) + (goto-char (point-min)) + (catch :radio-match + (while (re-search-forward re nil t) + (backward-char) + (let ((object (org-element-context))) + (when (eq (org-element-type object) 'radio-target) + (goto-char (org-element-property :begin object)) + (org-show-context 'link-search) + (throw :radio-match nil)))) + (goto-char origin) + (user-error "No match for radio target: %s" target)))) + +(defun org-link-search (s &optional avoid-pos stealth) + "Search for a search string S. + +If S starts with \"#\", it triggers a custom ID search. + +If S is enclosed within parenthesis, it initiates a coderef +search. + +If S is surrounded by forward slashes, it is interpreted as +a regular expression. In Org mode files, this will create an +`org-occur' sparse tree. In ordinary files, `occur' will be used +to list matches. If the current buffer is in `dired-mode', grep +will be used to search in all files. + +When AVOID-POS is given, ignore matches near that position. + +When optional argument STEALTH is non-nil, do not modify +visibility around point, thus ignoring `org-show-context-detail' +variable. + +Search is case-insensitive and ignores white spaces. Return type +of matched result, which is either `dedicated' or `fuzzy'." + (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s)) + (let* ((case-fold-search t) + (origin (point)) + (normalized (replace-regexp-in-string "\n[ \t]*" " " s)) + (starred (eq (string-to-char normalized) ?*)) + (words (split-string (if starred (substring s 1) s))) + (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)")) + (s-single-re (mapconcat #'regexp-quote words "[ \t]+")) + type) + (cond + ;; Check if there are any special search functions. + ((run-hook-with-args-until-success 'org-execute-file-search-functions s)) + ((eq (string-to-char s) ?#) + ;; Look for a custom ID S if S starts with "#". + (let* ((id (substring normalized 1)) + (match (org-find-property "CUSTOM_ID" id))) + (if match (progn (goto-char match) (setf type 'dedicated)) + (error "No match for custom ID: %s" id)))) + ((string-match "\\`(\\(.*\\))\\'" normalized) + ;; Look for coderef targets if S is enclosed within parenthesis. + (let ((coderef (match-string-no-properties 1 normalized)) + (re (substring s-single-re 1 -1))) + (goto-char (point-min)) + (catch :coderef-match + (while (re-search-forward re nil t) + (let ((element (org-element-at-point))) + (when (and (memq (org-element-type element) + '(example-block src-block)) + ;; Build proper regexp according to current + ;; block's label format. + (let ((label-fmt + (regexp-quote + (or (org-element-property :label-fmt element) + org-coderef-label-format)))) + (save-excursion + (beginning-of-line) + (looking-at (format ".*?\\(%s\\)[ \t]*$" + (format label-fmt coderef)))))) + (setq type 'dedicated) + (goto-char (match-beginning 1)) + (throw :coderef-match nil)))) + (goto-char origin) + (error "No match for coderef: %s" coderef)))) + ((string-match "\\`/\\(.*\\)/\\'" normalized) + ;; Look for a regular expression. + (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur) + (match-string 1 s))) + ;; From here, we handle fuzzy links. + ;; + ;; Look for targets, only if not in a headline search. + ((and (not starred) + (let ((target (format "<<%s>>" s-multi-re))) + (catch :target-match + (goto-char (point-min)) + (while (re-search-forward target nil t) + (backward-char) + (let ((context (org-element-context))) + (when (eq (org-element-type context) 'target) + (setq type 'dedicated) + (goto-char (org-element-property :begin context)) + (throw :target-match t)))) + nil)))) + ;; Look for elements named after S, only if not in a headline + ;; search. + ((and (not starred) + (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re))) + (catch :name-match + (goto-char (point-min)) + (while (re-search-forward name nil t) + (let ((element (org-element-at-point))) + (when (equal words + (split-string + (org-element-property :name element))) + (setq type 'dedicated) + (beginning-of-line) + (throw :name-match t)))) + nil)))) + ;; Regular text search. Prefer headlines in Org mode buffers. + ;; Ignore COMMENT keyword, TODO keywords, priority cookies, + ;; statistics cookies and tags. + ((and (derived-mode-p 'org-mode) + (let ((title-re + (format "%s.*\\(?:%s[ \t]\\)?.*%s" + org-outline-regexp-bol + org-comment-string + (mapconcat #'regexp-quote words ".+"))) + (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]") + (comment-re (eval-when-compile + (format "\\`%s[ \t]+" org-comment-string)))) + (goto-char (point-min)) + (catch :found + (while (re-search-forward title-re nil t) + (when (equal words + (split-string + (replace-regexp-in-string + cookie-re "" + (replace-regexp-in-string + comment-re "" (org-get-heading t t t))))) + (throw :found t))) + nil))) + (beginning-of-line) + (setq type 'dedicated)) + ;; Offer to create non-existent headline depending on + ;; `org-link-search-must-match-exact-headline'. + ((and (derived-mode-p 'org-mode) + (not org-link-search-inhibit-query) + (eq org-link-search-must-match-exact-headline 'query-to-create) + (yes-or-no-p "No match - create this as a new heading? ")) + (goto-char (point-max)) + (unless (bolp) (newline)) + (org-insert-heading nil t t) + (insert s "\n") + (beginning-of-line 0)) + ;; Only headlines are looked after. No need to process + ;; further: throw an error. + ((and (derived-mode-p 'org-mode) + (or starred org-link-search-must-match-exact-headline)) + (goto-char origin) + (error "No match for fuzzy expression: %s" normalized)) + ;; Regular text search. + ((catch :fuzzy-match + (goto-char (point-min)) + (while (re-search-forward s-multi-re nil t) + ;; Skip match if it contains AVOID-POS or it is included in + ;; a link with a description but outside the description. + (unless (or (and avoid-pos + (<= (match-beginning 0) avoid-pos) + (> (match-end 0) avoid-pos)) + (and (save-match-data + (org-in-regexp org-bracket-link-regexp)) + (match-beginning 3) + (or (> (match-beginning 3) (point)) + (<= (match-end 3) (point))) + (org-element-lineage + (save-match-data (org-element-context)) + '(link) t))) + (goto-char (match-beginning 0)) + (setq type 'fuzzy) + (throw :fuzzy-match t))) + nil)) + ;; All failed. Throw an error. + (t (goto-char origin) + (error "No match for fuzzy expression: %s" normalized))) + ;; Disclose surroundings of match, if appropriate. + (when (and (derived-mode-p 'org-mode) (not stealth)) + (org-show-context 'link-search)) + type)) + +(defun org-get-buffer-for-internal-link (buffer) + "Return a buffer to be used for displaying the link target of internal links." + (cond + ((not org-display-internal-link-with-indirect-buffer) + buffer) + ((string-suffix-p "(Clone)" (buffer-name buffer)) + (message "Buffer is already a clone, not making another one") + ;; we also do not modify visibility in this case + buffer) + (t ; make a new indirect buffer for displaying the link + (let* ((bn (buffer-name buffer)) + (ibn (concat bn "(Clone)")) + (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone)))) + (with-current-buffer ib (org-overview)) + ib)))) + +(defun org-do-occur (regexp &optional cleanup) + "Call the Emacs command `occur'. +If CLEANUP is non-nil, remove the printout of the regular expression +in the *Occur* buffer. This is useful if the regex is long and not useful +to read." + (occur regexp) + (when cleanup + (let ((cwin (selected-window)) win beg end) + (when (setq win (get-buffer-window "*Occur*")) + (select-window win)) + (goto-char (point-min)) + (when (re-search-forward "match[a-z]+" nil t) + (setq beg (match-end 0)) + (when (re-search-forward "^[ \t]*[0-9]+" nil t) + (setq end (1- (match-beginning 0))))) + (and beg end (let ((inhibit-read-only t)) (delete-region beg end))) + (goto-char (point-min)) + (select-window cwin)))) + +;;; The mark ring for links jumps + +(defvar org-mark-ring nil + "Mark ring for positions before jumps in Org mode.") +(defvar org-mark-ring-last-goto nil + "Last position in the mark ring used to go back.") +;; Fill and close the ring +(setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded +(dotimes (_ org-mark-ring-length) + (push (make-marker) org-mark-ring)) +(setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring) + org-mark-ring) + +(defun org-mark-ring-push (&optional pos buffer) + "Put the current position or POS into the mark ring and rotate it." + (interactive) + (setq pos (or pos (point))) + (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring)) + (move-marker (car org-mark-ring) + (or pos (point)) + (or buffer (current-buffer))) + (message "%s" + (substitute-command-keys + "Position saved to mark ring, go back with \ +`\\[org-mark-ring-goto]'."))) + +(defun org-mark-ring-goto (&optional n) + "Jump to the previous position in the mark ring. +With prefix arg N, jump back that many stored positions. When +called several times in succession, walk through the entire ring. +Org mode commands jumping to a different position in the current file, +or to another Org file, automatically push the old position onto the ring." + (interactive "p") + (let (p m) + (if (eq last-command this-command) + (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring))) + (setq p org-mark-ring)) + (setq org-mark-ring-last-goto p) + (setq m (car p)) + (pop-to-buffer-same-window (marker-buffer m)) + (goto-char m) + (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto)))) + +(defun org-add-angle-brackets (s) + (unless (equal (substring s 0 1) "<") (setq s (concat "<" s))) + (unless (equal (substring s -1) ">") (setq s (concat s ">"))) + s) + +;;; Following specific links + +(defvar org-agenda-buffer-tmp-name) +(defvar org-agenda-start-on-weekday) +(defun org-follow-timestamp-link () + "Open an agenda view for the time-stamp date/range at point." + (cond + ((org-at-date-range-p t) + (let ((org-agenda-start-on-weekday) + (t1 (match-string 1)) + (t2 (match-string 2)) tt1 tt2) + (setq tt1 (time-to-days (org-time-string-to-time t1)) + tt2 (time-to-days (org-time-string-to-time t2))) + (let ((org-agenda-buffer-tmp-name + (format "*Org Agenda(a:%s)" + (concat (substring t1 0 10) "--" (substring t2 0 10))))) + (org-agenda-list nil tt1 (1+ (- tt2 tt1)))))) + ((org-at-timestamp-p 'lax) + (let ((org-agenda-buffer-tmp-name + (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10)))) + (org-agenda-list nil (time-to-days (org-time-string-to-time + (substring (match-string 1) 0 10))) + 1))) + (t (error "This should not happen")))) + + +;;; Following file links +(declare-function mailcap-parse-mailcaps "mailcap" (&optional path force)) +(declare-function mailcap-extension-to-mime "mailcap" (extn)) +(declare-function mailcap-mime-info + "mailcap" (string &optional request no-decode)) +(defvar org-wait nil) +(defun org-open-file (path &optional in-emacs line search) + "Open the file at PATH. +First, this expands any special file name abbreviations. Then the +configuration variable `org-file-apps' is checked if it contains an +entry for this file type, and if yes, the corresponding command is launched. + +If no application is found, Emacs simply visits the file. + +With optional prefix argument IN-EMACS, Emacs will visit the file. +With a double \\[universal-argument] \\[universal-argument] \ +prefix arg, Org tries to avoid opening in Emacs +and to use an external application to visit the file. + +Optional LINE specifies a line to go to, optional SEARCH a string +to search for. If LINE or SEARCH is given, the file will be +opened in Emacs, unless an entry from org-file-apps that makes +use of groups in a regexp matches. + +If you want to change the way frames are used when following a +link, please customize `org-link-frame-setup'. + +If the file does not exist, an error is thrown." + (let* ((file (if (equal path "") + buffer-file-name + (substitute-in-file-name (expand-file-name path)))) + (file-apps (append org-file-apps (org-default-apps))) + (apps (cl-remove-if + 'org-file-apps-entry-match-against-dlink-p file-apps)) + (apps-dlink (cl-remove-if-not + 'org-file-apps-entry-match-against-dlink-p file-apps)) + (remp (and (assq 'remote apps) (org-file-remote-p file))) + (dirp (unless remp (file-directory-p file))) + (file (if (and dirp org-open-directory-means-index-dot-org) + (concat (file-name-as-directory file) "index.org") + file)) + (a-m-a-p (assq 'auto-mode apps)) + (dfile (downcase file)) + ;; Reconstruct the original link from the PATH, LINE and + ;; SEARCH args. + (link (cond (line (concat file "::" (number-to-string line))) + (search (concat file "::" search)) + (t file))) + (dlink (downcase link)) + (ext + (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile) + (match-string 1 dfile))) + (save-position-maybe + (let ((old-buffer (current-buffer)) + (old-pos (point)) + (old-mode major-mode)) + (lambda () + (and (derived-mode-p 'org-mode) + (eq old-mode 'org-mode) + (or (not (eq old-buffer (current-buffer))) + (not (eq old-pos (point)))) + (org-mark-ring-push old-pos old-buffer))))) + cmd link-match-data) + (cond + ((member in-emacs '((16) system)) + (setq cmd (cdr (assq 'system apps)))) + (in-emacs (setq cmd 'emacs)) + (t + (setq cmd (or (and remp (cdr (assq 'remote apps))) + (and dirp (cdr (assq 'directory apps))) + ;; First, try matching against apps-dlink if we + ;; get a match here, store the match data for + ;; later. + (let ((match (assoc-default dlink apps-dlink + 'string-match))) + (if match + (progn (setq link-match-data (match-data)) + match) + (progn (setq in-emacs (or in-emacs line search)) + nil))) ; if we have no match in apps-dlink, + ; always open the file in emacs if line or search + ; is given (for backwards compatibility) + (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p) + 'string-match) + (cdr (assoc ext apps)) + (cdr (assq t apps)))))) + (when (eq cmd 'system) + (setq cmd (cdr (assq 'system apps)))) + (when (eq cmd 'default) + (setq cmd (cdr (assoc t apps)))) + (when (eq cmd 'mailcap) + (require 'mailcap) + (mailcap-parse-mailcaps) + (let* ((mime-type (mailcap-extension-to-mime (or ext ""))) + (command (mailcap-mime-info mime-type))) + (if (stringp command) + (setq cmd command) + (setq cmd 'emacs)))) + (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files + (not (file-exists-p file)) + (not org-open-non-existing-files)) + (user-error "No such file: %s" file)) + (cond + ((and (stringp cmd) (not (string-match "^\\s-*$" cmd))) + ;; Remove quotes around the file name - we'll use shell-quote-argument. + (while (string-match "['\"]%s['\"]" cmd) + (setq cmd (replace-match "%s" t t cmd))) + (setq cmd (replace-regexp-in-string + "%s" + (shell-quote-argument (convert-standard-filename file)) + cmd + nil t)) + + ;; Replace "%1", "%2" etc. in command with group matches from regex + (save-match-data + (let ((match-index 1) + (number-of-groups (- (/ (length link-match-data) 2) 1))) + (set-match-data link-match-data) + (while (<= match-index number-of-groups) + (let ((regex (concat "%" (number-to-string match-index))) + (replace-with (match-string match-index dlink))) + (while (string-match regex cmd) + (setq cmd (replace-match replace-with t t cmd)))) + (setq match-index (+ match-index 1))))) + + (save-window-excursion + (message "Running %s...done" cmd) + (start-process-shell-command cmd nil cmd) + (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait)))) + ((or (stringp cmd) + (eq cmd 'emacs)) + (funcall (cdr (assq 'file org-link-frame-setup)) file) + (widen) + (cond (line (org-goto-line line) + (when (derived-mode-p 'org-mode) (org-reveal))) + (search (condition-case err + (org-link-search search) + ;; Save position before error-ing out so user + ;; can easily move back to the original buffer. + (error (funcall save-position-maybe) + (error (nth 1 err))))))) + ((functionp cmd) + (save-match-data + (set-match-data link-match-data) + (condition-case nil + (funcall cmd file link) + ;; FIXME: Remove this check when most default installations + ;; of Emacs have at least Org 9.0. + ((debug wrong-number-of-arguments wrong-type-argument + invalid-function) + (user-error "Please see Org News for version 9.0 about \ +`org-file-apps'--Lisp error: %S" cmd))))) + ((consp cmd) + ;; FIXME: Remove this check when most default installations of + ;; Emacs have at least Org 9.0. Heads-up instead of silently + ;; fall back to `org-link-frame-setup' for an old usage of + ;; `org-file-apps' with sexp instead of a function for `cmd'. + (user-error "Please see Org News for version 9.0 about \ +`org-file-apps'--Error: Deprecated usage of %S" cmd)) + (t (funcall (cdr (assq 'file org-link-frame-setup)) file))) + (funcall save-position-maybe))) + +(defun org-file-apps-entry-match-against-dlink-p (entry) + "This function returns non-nil if `entry' uses a regular +expression which should be matched against the whole link by +org-open-file. + +It assumes that is the case when the entry uses a regular +expression which has at least one grouping construct and the +action is either a lisp form or a command string containing +`%1', i.e. using at least one subexpression match as a +parameter." + (let ((selector (car entry)) + (action (cdr entry))) + (if (stringp selector) + (and (> (regexp-opt-depth selector) 0) + (or (and (stringp action) + (string-match "%[0-9]" action)) + (consp action))) + nil))) + +(defun org-default-apps () + "Return the default applications for this operating system." + (cond + ((eq system-type 'darwin) + org-file-apps-defaults-macosx) + ((eq system-type 'windows-nt) + org-file-apps-defaults-windowsnt) + (t org-file-apps-defaults-gnu))) + +(defun org-apps-regexp-alist (list &optional add-auto-mode) + "Convert extensions to regular expressions in the cars of LIST. +Also, weed out any non-string entries, because the return value is used +only for regexp matching. +When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist' +point to the symbol `emacs', indicating that the file should +be opened in Emacs." + (append + (delq nil + (mapcar (lambda (x) + (unless (not (stringp (car x))) + (if (string-match "\\W" (car x)) + x + (cons (concat "\\." (car x) "\\'") (cdr x))))) + list)) + (when add-auto-mode + (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist)))) + +(defvar ange-ftp-name-format) +(defun org-file-remote-p (file) + "Test whether FILE specifies a location on a remote system. +Return non-nil if the location is indeed remote. + +For example, the filename \"/user@host:/foo\" specifies a location +on the system \"/user@host:\"." + (cond ((fboundp 'file-remote-p) + (file-remote-p file)) + ((fboundp 'tramp-handle-file-remote-p) + (tramp-handle-file-remote-p file)) + ((and (boundp 'ange-ftp-name-format) + (string-match (car ange-ftp-name-format) file)) + t))) + + +;;;; Refiling + +(defun org-get-org-file () + "Read a filename, with default directory `org-directory'." + (let ((default (or org-default-notes-file remember-data-file))) + (read-file-name (format "File name [%s]: " default) + (file-name-as-directory org-directory) + default))) + +(defun org-notes-order-reversed-p () + "Check if the current file should receive notes in reversed order." + (cond + ((not org-reverse-note-order) nil) + ((eq t org-reverse-note-order) t) + ((not (listp org-reverse-note-order)) nil) + (t (catch 'exit + (dolist (entry org-reverse-note-order) + (when (string-match (car entry) buffer-file-name) + (throw 'exit (cdr entry)))))))) + +(defvar org-refile-target-table nil + "The list of refile targets, created by `org-refile'.") + +(defvar org-agenda-new-buffers nil + "Buffers created to visit agenda files.") + +(defvar org-refile-cache nil + "Cache for refile targets.") + +(defvar org-refile-markers nil + "All the markers used for caching refile locations.") + +(defun org-refile-marker (pos) + "Get a new refile marker, but only if caching is in use." + (if (not org-refile-use-cache) + pos + (let ((m (make-marker))) + (move-marker m pos) + (push m org-refile-markers) + m))) + +(defun org-refile-cache-clear () + "Clear the refile cache and disable all the markers." + (dolist (m org-refile-markers) (move-marker m nil)) + (setq org-refile-markers nil) + (setq org-refile-cache nil) + (message "Refile cache has been cleared")) + +(defun org-refile-cache-check-set (set) + "Check if all the markers in the cache still have live buffers." + (let (marker) + (catch 'exit + (while (and set (setq marker (nth 3 (pop set)))) + ;; If `org-refile-use-outline-path' is 'file, marker may be nil + (when (and marker (null (marker-buffer marker))) + (message "Please regenerate the refile cache with `C-0 C-c C-w'") + (sit-for 3) + (throw 'exit nil))) + t))) + +(defun org-refile-cache-put (set &rest identifiers) + "Push the refile targets SET into the cache, under IDENTIFIERS." + (let* ((key (sha1 (prin1-to-string identifiers))) + (entry (assoc key org-refile-cache))) + (if entry + (setcdr entry set) + (push (cons key set) org-refile-cache)))) + +(defun org-refile-cache-get (&rest identifiers) + "Retrieve the cached value for refile targets given by IDENTIFIERS." + (cond + ((not org-refile-cache) nil) + ((not org-refile-use-cache) (org-refile-cache-clear) nil) + (t + (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers)) + org-refile-cache)))) + (and set (org-refile-cache-check-set set) set))))) + +(defvar org-outline-path-cache nil + "Alist between buffer positions and outline paths. +It value is an alist (POSITION . PATH) where POSITION is the +buffer position at the beginning of an entry and PATH is a list +of strings describing the outline path for that entry, in reverse +order.") + +(defun org-refile-get-targets (&optional default-buffer) + "Produce a table with refile targets." + (let ((case-fold-search nil) + ;; otherwise org confuses "TODO" as a kw and "Todo" as a word + (entries (or org-refile-targets '((nil . (:level . 1))))) + targets tgs files desc descre) + (message "Getting targets...") + (with-current-buffer (or default-buffer (current-buffer)) + (dolist (entry entries) + (setq files (car entry) desc (cdr entry)) + (cond + ((null files) (setq files (list (current-buffer)))) + ((eq files 'org-agenda-files) + (setq files (org-agenda-files 'unrestricted))) + ((and (symbolp files) (fboundp files)) + (setq files (funcall files))) + ((and (symbolp files) (boundp files)) + (setq files (symbol-value files)))) + (when (stringp files) (setq files (list files))) + (cond + ((eq (car desc) :tag) + (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":"))) + ((eq (car desc) :todo) + (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]"))) + ((eq (car desc) :regexp) + (setq descre (cdr desc))) + ((eq (car desc) :level) + (setq descre (concat "^\\*\\{" (number-to-string + (if org-odd-levels-only + (1- (* 2 (cdr desc))) + (cdr desc))) + "\\}[ \t]"))) + ((eq (car desc) :maxlevel) + (setq descre (concat "^\\*\\{1," (number-to-string + (if org-odd-levels-only + (1- (* 2 (cdr desc))) + (cdr desc))) + "\\}[ \t]"))) + (t (error "Bad refiling target description %s" desc))) + (dolist (f files) + (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)) + (or + (setq tgs (org-refile-cache-get (buffer-file-name) descre)) + (progn + (when (bufferp f) + (setq f (buffer-file-name (buffer-base-buffer f)))) + (setq f (and f (expand-file-name f))) + (when (eq org-refile-use-outline-path 'file) + (push (list (file-name-nondirectory f) f nil nil) tgs)) + (when (eq org-refile-use-outline-path 'buffer-name) + (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs)) + (when (eq org-refile-use-outline-path 'full-file-path) + (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs)) + (org-with-wide-buffer + (goto-char (point-min)) + (setq org-outline-path-cache nil) + (while (re-search-forward descre nil t) + (beginning-of-line) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp)) + (let ((begin (point)) + (heading (match-string-no-properties 4))) + (unless (or (and + org-refile-target-verify-function + (not + (funcall org-refile-target-verify-function))) + (not heading)) + (let ((re (format org-complex-heading-regexp-format + (regexp-quote heading))) + (target + (if (not org-refile-use-outline-path) heading + (mapconcat + #'identity + (append + (pcase org-refile-use-outline-path + (`file (list (file-name-nondirectory + (buffer-file-name + (buffer-base-buffer))))) + (`full-file-path + (list (buffer-file-name + (buffer-base-buffer)))) + (`buffer-name + (list (buffer-name + (buffer-base-buffer)))) + (_ nil)) + (mapcar (lambda (s) (replace-regexp-in-string + "/" "\\/" s nil t)) + (org-get-outline-path t t))) + "/")))) + (push (list target f re (org-refile-marker (point))) + tgs))) + (when (= (point) begin) + ;; Verification function has not moved point. + (end-of-line))))))) + (when org-refile-use-cache + (org-refile-cache-put tgs (buffer-file-name) descre)) + (setq targets (append tgs targets)))))) + (message "Getting targets...done") + (delete-dups (nreverse targets)))) + +(defun org--get-outline-path-1 (&optional use-cache) + "Return outline path to current headline. + +Outline path is a list of strings, in reverse order. When +optional argument USE-CACHE is non-nil, make use of a cache. See +`org-get-outline-path' for details. + +Assume buffer is widened and point is on a headline." + (or (and use-cache (cdr (assq (point) org-outline-path-cache))) + (let ((p (point)) + (heading (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp) + (if (not (match-end 4)) "" + ;; Remove statistics cookies. + (org-trim + (org-link-display-format + (replace-regexp-in-string + "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" + (match-string-no-properties 4)))))))) + (if (org-up-heading-safe) + (let ((path (cons heading (org--get-outline-path-1 use-cache)))) + (when use-cache + (push (cons p path) org-outline-path-cache)) + path) + ;; This is a new root node. Since we assume we are moving + ;; forward, we can drop previous cache so as to limit number + ;; of associations there. + (let ((path (list heading))) + (when use-cache (setq org-outline-path-cache (list (cons p path)))) + path))))) + +(defun org-get-outline-path (&optional with-self use-cache) + "Return the outline path to the current entry. + +An outline path is a list of ancestors for current headline, as +a list of strings. Statistics cookies are removed and links are +replaced with their description, if any, or their path otherwise. + +When optional argument WITH-SELF is non-nil, the path also +includes the current headline. + +When optional argument USE-CACHE is non-nil, cache outline paths +between calls to this function so as to avoid backtracking. This +argument is useful when planning to find more than one outline +path in the same document. In that case, there are two +conditions to satisfy: + - `org-outline-path-cache' is set to nil before starting the + process; + - outline paths are computed by increasing buffer positions." + (org-with-wide-buffer + (and (or (and with-self (org-back-to-heading t)) + (org-up-heading-safe)) + (reverse (org--get-outline-path-1 use-cache))))) + +(defun org-format-outline-path (path &optional width prefix separator) + "Format the outline path PATH for display. +WIDTH is the maximum number of characters that is available. +PREFIX is a prefix to be included in the returned string, +such as the file name. +SEPARATOR is inserted between the different parts of the path, +the default is \"/\"." + (setq width (or width 79)) + (setq path (delq nil path)) + (unless (> width 0) + (user-error "Argument `width' must be positive")) + (setq separator (or separator "/")) + (let* ((org-odd-levels-only nil) + (fpath (concat + prefix (and prefix path separator) + (mapconcat + (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s)) + (cl-loop for head in path + for n from 0 + collect (org-add-props + head nil 'face + (nth (% n org-n-level-faces) org-level-faces))) + separator)))) + (when (> (length fpath) width) + (if (< width 7) + ;; It's unlikely that `width' will be this small, but don't + ;; waste characters by adding ".." if it is. + (setq fpath (substring fpath 0 width)) + (setf (substring fpath (- width 2)) ".."))) + fpath)) + +(defun org-display-outline-path (&optional file current separator just-return-string) + "Display the current outline path in the echo area. + +If FILE is non-nil, prepend the output with the file name. +If CURRENT is non-nil, append the current heading to the output. +SEPARATOR is passed through to `org-format-outline-path'. It separates +the different parts of the path and defaults to \"/\". +If JUST-RETURN-STRING is non-nil, return a string, don't display a message." + (interactive "P") + (let* (case-fold-search + (bfn (buffer-file-name (buffer-base-buffer))) + (path (and (derived-mode-p 'org-mode) (org-get-outline-path))) + res) + (when current (setq path (append path + (save-excursion + (org-back-to-heading t) + (when (looking-at org-complex-heading-regexp) + (list (match-string 4))))))) + (setq res + (org-format-outline-path + path + (1- (frame-width)) + (and file bfn (concat (file-name-nondirectory bfn) separator)) + separator)) + (if just-return-string + (org-no-properties res) + (org-unlogged-message "%s" res)))) + +(defvar org-refile-history nil + "History for refiling operations.") + +(defvar org-after-refile-insert-hook nil + "Hook run after `org-refile' has inserted its stuff at the new location. +Note that this is still *before* the stuff will be removed from +the *old* location.") + +(defvar org-capture-last-stored-marker) +(defvar org-refile-keep nil + "Non-nil means `org-refile' will copy instead of refile.") + +(defun org-copy () + "Like `org-refile', but copy." + (interactive) + (let ((org-refile-keep t)) + (funcall 'org-refile nil nil nil "Copy"))) + +(defun org-refile (&optional arg default-buffer rfloc msg) + "Move the entry or entries at point to another heading. + +The list of target headings is compiled using the information in +`org-refile-targets', which see. + +At the target location, the entry is filed as a subitem of the +target heading. Depending on `org-reverse-note-order', the new +subitem will either be the first or the last subitem. + +If there is an active region, all entries in that region will be +refiled. However, the region must fulfill the requirement that +the first heading sets the top-level of the moved text. + +With a `\\[universal-argument]' ARG, the command will only visit the target \ +location +and not actually move anything. + +With a prefix `\\[universal-argument] \\[universal-argument]', go to the \ +location where the last +refiling operation has put the subtree. + +With a numeric prefix argument of `2', refile to the running clock. + +With a numeric prefix argument of `3', emulate `org-refile-keep' +being set to t and copy to the target location, don't move it. +Beware that keeping refiled entries may result in duplicated ID +properties. + +RFLOC can be a refile location obtained in a different way. + +MSG is a string to replace \"Refile\" in the default prompt with +another verb. E.g. `org-copy' sets this parameter to \"Copy\". + +See also `org-refile-use-outline-path'. + +If you are using target caching (see `org-refile-use-cache'), you +have to clear the target cache in order to find new targets. +This can be done with a `0' prefix (`C-0 C-c C-w') or a triple +prefix argument (`C-u C-u C-u C-c C-w')." + (interactive "P") + (if (member arg '(0 (64))) + (org-refile-cache-clear) + (let* ((actionmsg (cond (msg msg) + ((equal arg 3) "Refile (and keep)") + (t "Refile"))) + (regionp (org-region-active-p)) + (region-start (and regionp (region-beginning))) + (region-end (and regionp (region-end))) + (org-refile-keep (if (equal arg 3) t org-refile-keep)) + pos it nbuf file level reversed) + (setq last-command nil) + (when regionp + (goto-char region-start) + (or (bolp) (goto-char (point-at-bol))) + (setq region-start (point)) + (unless (or (org-kill-is-subtree-p + (buffer-substring region-start region-end)) + (prog1 org-refile-active-region-within-subtree + (let ((s (point-at-eol))) + (org-toggle-heading) + (setq region-end (+ (- (point-at-eol) s) region-end))))) + (user-error "The region is not a (sequence of) subtree(s)"))) + (if (equal arg '(16)) + (org-refile-goto-last-stored) + (when (or + (and (equal arg 2) + org-clock-hd-marker (marker-buffer org-clock-hd-marker) + (prog1 + (setq it (list (or org-clock-heading "running clock") + (buffer-file-name + (marker-buffer org-clock-hd-marker)) + "" + (marker-position org-clock-hd-marker))) + (setq arg nil))) + (setq it + (or rfloc + (let (heading-text) + (save-excursion + (unless (and arg (listp arg)) + (org-back-to-heading t) + (setq heading-text + (replace-regexp-in-string + org-bracket-link-regexp + "\\3" + (or (nth 4 (org-heading-components)) + "")))) + (org-refile-get-location + (cond ((and arg (listp arg)) "Goto") + (regionp (concat actionmsg " region to")) + (t (concat actionmsg " subtree \"" + heading-text "\" to"))) + default-buffer + (and (not (equal '(4) arg)) + org-refile-allow-creating-parent-nodes))))))) + (setq file (nth 1 it) + pos (nth 3 it)) + (when (and (not arg) + pos + (equal (buffer-file-name) file) + (if regionp + (and (>= pos region-start) + (<= pos region-end)) + (and (>= pos (point)) + (< pos (save-excursion + (org-end-of-subtree t t)))))) + (error "Cannot refile to position inside the tree or region")) + (setq nbuf (or (find-buffer-visiting file) + (find-file-noselect file))) + (if (and arg (not (equal arg 3))) + (progn + (pop-to-buffer-same-window nbuf) + (goto-char (cond (pos) + ((org-notes-order-reversed-p) (point-min)) + (t (point-max)))) + (org-show-context 'org-goto)) + (if regionp + (progn + (org-kill-new (buffer-substring region-start region-end)) + (org-save-markers-in-region region-start region-end)) + (org-copy-subtree 1 nil t)) + (with-current-buffer (setq nbuf (or (find-buffer-visiting file) + (find-file-noselect file))) + (setq reversed (org-notes-order-reversed-p)) + (org-with-wide-buffer + (if pos + (progn + (goto-char pos) + (setq level (org-get-valid-level (funcall outline-level) 1)) + (goto-char + (if reversed + (or (outline-next-heading) (point-max)) + (or (save-excursion (org-get-next-sibling)) + (org-end-of-subtree t t) + (point-max))))) + (setq level 1) + (if (not reversed) + (goto-char (point-max)) + (goto-char (point-min)) + (or (outline-next-heading) (goto-char (point-max))))) + (unless (bolp) (newline)) + (org-paste-subtree level nil nil t) + (when org-log-refile + (org-add-log-setup 'refile nil nil org-log-refile) + (unless (eq org-log-refile 'note) + (save-excursion (org-add-log-note)))) + (and org-auto-align-tags + (let ((org-loop-over-headlines-in-active-region nil)) + (org-set-tags nil t))) + (let ((bookmark-name (plist-get org-bookmark-names-plist + :last-refile))) + (when bookmark-name + (with-demoted-errors + (bookmark-set bookmark-name)))) + ;; If we are refiling for capture, make sure that the + ;; last-capture pointers point here + (when (bound-and-true-p org-capture-is-refiling) + (let ((bookmark-name (plist-get org-bookmark-names-plist + :last-capture-marker))) + (when bookmark-name + (with-demoted-errors + (bookmark-set bookmark-name)))) + (move-marker org-capture-last-stored-marker (point))) + (when (fboundp 'deactivate-mark) (deactivate-mark)) + (run-hooks 'org-after-refile-insert-hook))) + (unless org-refile-keep + (if regionp + (delete-region (point) (+ (point) (- region-end region-start))) + (delete-region + (and (org-back-to-heading t) (point)) + (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))) + (when (featurep 'org-inlinetask) + (org-inlinetask-remove-END-maybe)) + (setq org-markers-to-move nil) + (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file))))))) + +(defun org-refile-goto-last-stored () + "Go to the location where the last refile was stored." + (interactive) + (bookmark-jump (plist-get org-bookmark-names-plist :last-refile)) + (message "This is the location of the last refile")) + +(defun org-refile--get-location (refloc tbl) + "When user refile to REFLOC, find the associated target in TBL. +Also check `org-refile-target-table'." + (car (delq + nil + (mapcar + (lambda (r) (or (assoc r tbl) + (assoc r org-refile-target-table))) + (list (replace-regexp-in-string "/$" "" refloc) + (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc)))))) + +(defun org-refile-get-location (&optional prompt default-buffer new-nodes) + "Prompt the user for a refile location, using PROMPT. +PROMPT should not be suffixed with a colon and a space, because +this function appends the default value from +`org-refile-history' automatically, if that is not empty." + (let ((org-refile-targets org-refile-targets) + (org-refile-use-outline-path org-refile-use-outline-path)) + (setq org-refile-target-table (org-refile-get-targets default-buffer))) + (unless org-refile-target-table + (user-error "No refile targets")) + (let* ((cbuf (current-buffer)) + (cfn (buffer-file-name (buffer-base-buffer cbuf))) + (cfunc (if (and org-refile-use-outline-path + org-outline-path-complete-in-steps) + #'org-olpath-completing-read + #'completing-read)) + (extra (if org-refile-use-outline-path "/" "")) + (cbnex (concat (buffer-name) extra)) + (filename (and cfn (expand-file-name cfn))) + (tbl (mapcar + (lambda (x) + (if (and (not (member org-refile-use-outline-path + '(file full-file-path))) + (not (equal filename (nth 1 x)))) + (cons (concat (car x) extra " (" + (file-name-nondirectory (nth 1 x)) ")") + (cdr x)) + (cons (concat (car x) extra) (cdr x)))) + org-refile-target-table)) + (completion-ignore-case t) + cdef + (prompt (concat prompt + (or (and (car org-refile-history) + (concat " (default " (car org-refile-history) ")")) + (and (assoc cbnex tbl) (setq cdef cbnex) + (concat " (default " cbnex ")"))) ": ")) + pa answ parent-target child parent old-hist) + (setq old-hist org-refile-history) + (setq answ (funcall cfunc prompt tbl nil (not new-nodes) + nil 'org-refile-history (or cdef (car org-refile-history)))) + (if (setq pa (org-refile--get-location answ tbl)) + (progn + (org-refile-check-position pa) + (when (or (not org-refile-history) + (not (eq old-hist org-refile-history)) + (not (equal (car pa) (car org-refile-history)))) + (setq org-refile-history + (cons (car pa) (if (assoc (car org-refile-history) tbl) + org-refile-history + (cdr org-refile-history)))) + (when (equal (car org-refile-history) (nth 1 org-refile-history)) + (pop org-refile-history))) + pa) + (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ) + (progn + (setq parent (match-string 1 answ) + child (match-string 2 answ)) + (setq parent-target (org-refile--get-location parent tbl)) + (when (and parent-target + (or (eq new-nodes t) + (and (eq new-nodes 'confirm) + (y-or-n-p (format "Create new node \"%s\"? " + child))))) + (org-refile-new-child parent-target child))) + (user-error "Invalid target location"))))) + +(declare-function org-string-nw-p "org-macs" (s)) +(defun org-refile-check-position (refile-pointer) + "Check if the refile pointer matches the headline to which it points." + (let* ((file (nth 1 refile-pointer)) + (re (nth 2 refile-pointer)) + (pos (nth 3 refile-pointer)) + buffer) + (if (and (not (markerp pos)) (not file)) + (user-error "Please indicate a target file in the refile path") + (when (org-string-nw-p re) + (setq buffer (if (markerp pos) + (marker-buffer pos) + (or (find-buffer-visiting file) + (find-file-noselect file)))) + (with-current-buffer buffer + (org-with-wide-buffer + (goto-char pos) + (beginning-of-line 1) + (unless (looking-at-p re) + (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))) + +(defun org-refile-new-child (parent-target child) + "Use refile target PARENT-TARGET to add new CHILD below it." + (unless parent-target + (error "Cannot find parent for new node")) + (let ((file (nth 1 parent-target)) + (pos (nth 3 parent-target)) + level) + (with-current-buffer (or (find-buffer-visiting file) + (find-file-noselect file)) + (org-with-wide-buffer + (if pos + (goto-char pos) + (goto-char (point-max)) + (unless (bolp) (newline))) + (when (looking-at org-outline-regexp) + (setq level (funcall outline-level)) + (org-end-of-subtree t t)) + (org-back-over-empty-lines) + (insert "\n" (make-string + (if pos (org-get-valid-level level 1) 1) ?*) + " " child "\n") + (beginning-of-line 0) + (list (concat (car parent-target) "/" child) file "" (point)))))) + +(defun org-olpath-completing-read (prompt collection &rest args) + "Read an outline path like a file name." + (let ((thetable collection)) + (apply #'completing-read + prompt + (lambda (string predicate &optional flag) + (cond + ((eq flag nil) (try-completion string thetable)) + ((eq flag t) + (let ((l (length string))) + (mapcar (lambda (x) + (let ((r (substring x l)) + (f (if (string-match " ([^)]*)$" x) + (match-string 0 x) + ""))) + (if (string-match "/" r) + (concat string (substring r 0 (match-end 0)) f) + x))) + (all-completions string thetable predicate)))) + ;; Exact match? + ((eq flag 'lambda) (assoc string thetable)))) + args))) + +;;;; Dynamic blocks + +(defun org-find-dblock (name) + "Find the first dynamic block with name NAME in the buffer. +If not found, stay at current position and return nil." + (let ((case-fold-search t) pos) + (save-excursion + (goto-char (point-min)) + (setq pos (and (re-search-forward + (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t) + (match-beginning 0)))) + (when pos (goto-char pos)) + pos)) + +(defun org-create-dblock (plist) + "Create a dynamic block section, with parameters taken from PLIST. +PLIST must contain a :name entry which is used as the name of the block." + (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol))) + (end-of-line 1) + (newline)) + (let ((col (current-column)) + (name (plist-get plist :name))) + (insert "#+BEGIN: " name) + (while plist + (if (eq (car plist) :name) + (setq plist (cddr plist)) + (insert " " (prin1-to-string (pop plist))))) + (insert "\n\n" (make-string col ?\ ) "#+END:\n") + (beginning-of-line -2))) + +(defun org-prepare-dblock () + "Prepare dynamic block for refresh. +This empties the block, puts the cursor at the insert position and returns +the property list including an extra property :name with the block name." + (unless (looking-at org-dblock-start-re) + (user-error "Not at a dynamic block")) + (let* ((begdel (1+ (match-end 0))) + (name (org-no-properties (match-string 1))) + (params (append (list :name name) + (read (concat "(" (match-string 3) ")"))))) + (save-excursion + (beginning-of-line 1) + (skip-chars-forward " \t") + (setq params (plist-put params :indentation-column (current-column)))) + (unless (re-search-forward org-dblock-end-re nil t) + (error "Dynamic block not terminated")) + (setq params + (append params + (list :content (buffer-substring + begdel (match-beginning 0))))) + (delete-region begdel (match-beginning 0)) + (goto-char begdel) + (open-line 1) + params)) + +(defun org-map-dblocks (&optional command) + "Apply COMMAND to all dynamic blocks in the current buffer. +If COMMAND is not given, use `org-update-dblock'." + (let ((cmd (or command 'org-update-dblock))) + (save-excursion + (goto-char (point-min)) + (while (re-search-forward org-dblock-start-re nil t) + (goto-char (match-beginning 0)) + (save-excursion + (condition-case nil + (funcall cmd) + (error (message "Error during update of dynamic block")))) + (unless (re-search-forward org-dblock-end-re nil t) + (error "Dynamic block not terminated")))))) + +(defun org-dblock-update (&optional arg) + "User command for updating dynamic blocks. +Update the dynamic block at point. With prefix ARG, update all dynamic +blocks in the buffer." + (interactive "P") + (if arg + (org-update-all-dblocks) + (or (looking-at org-dblock-start-re) + (org-beginning-of-dblock)) + (org-update-dblock))) + +(defun org-update-dblock () + "Update the dynamic block at point. +This means to empty the block, parse for parameters and then call +the correct writing function." + (interactive) + (save-excursion + (let* ((win (selected-window)) + (pos (point)) + (line (org-current-line)) + (params (org-prepare-dblock)) + (name (plist-get params :name)) + (indent (plist-get params :indentation-column)) + (cmd (intern (concat "org-dblock-write:" name)))) + (message "Updating dynamic block `%s' at line %d..." name line) + (funcall cmd params) + (message "Updating dynamic block `%s' at line %d...done" name line) + (goto-char pos) + (when (and indent (> indent 0)) + (setq indent (make-string indent ?\ )) + (save-excursion + (select-window win) + (org-beginning-of-dblock) + (forward-line 1) + (while (not (looking-at org-dblock-end-re)) + (insert indent) + (beginning-of-line 2)) + (when (looking-at org-dblock-end-re) + (and (looking-at "[ \t]+") + (replace-match "")) + (insert indent))))))) + +(defun org-beginning-of-dblock () + "Find the beginning of the dynamic block at point. +Error if there is no such block at point." + (let ((pos (point)) + beg) + (end-of-line 1) + (if (and (re-search-backward org-dblock-start-re nil t) + (setq beg (match-beginning 0)) + (re-search-forward org-dblock-end-re nil t) + (> (match-end 0) pos)) + (goto-char beg) + (goto-char pos) + (error "Not in a dynamic block")))) + +(defun org-update-all-dblocks () + "Update all dynamic blocks in the buffer. +This function can be used in a hook." + (interactive) + (when (derived-mode-p 'org-mode) + (org-map-dblocks 'org-update-dblock))) + + +;;;; Completion + +(declare-function org-export-backend-options "ox" (cl-x) t) +(defun org-get-export-keywords () + "Return a list of all currently understood export keywords. +Export keywords include options, block names, attributes and +keywords relative to each registered export back-end." + (let (keywords) + (dolist (backend + (bound-and-true-p org-export-registered-backends) + (delq nil keywords)) + ;; Back-end name (for keywords, like #+LATEX:) + (push (upcase (symbol-name (org-export-backend-name backend))) keywords) + (dolist (option-entry (org-export-backend-options backend)) + ;; Back-end options. + (push (nth 1 option-entry) keywords))))) + +(defconst org-options-keywords + '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:" + "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:" + "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:" + "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:" + "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:")) + +(defcustom org-structure-template-alist + '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC") + ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE") + ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE") + ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE") + ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM") + ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER") + ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT") + ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT") + ("L" "#+LaTeX: ") + ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT") + ("H" "#+HTML: ") + ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT") + ("A" "#+ASCII: ") + ("i" "#+INDEX: ?") + ("I" "#+INCLUDE: %file ?")) + "Structure completion elements. +This is a list of abbreviation keys and values. The value gets inserted +if you type `<' followed by the key and then press the completion key, +usually `TAB'. %file will be replaced by a file name after prompting +for the file using completion. The cursor will be placed at the position +of the `?' in the template. +There are two templates for each key, the first uses the original Org syntax, +the second uses Emacs Muse-like syntax tags. These Muse-like tags become +the default when the /org-mtags.el/ module has been loaded. See also the +variable `org-mtags-prefer-muse-templates'." + :group 'org-edit-structure + :type '(repeat + (list + (string :tag "Key") + (string :tag "Template"))) + :version "26.1" + :package-version '(Org . "8.3")) + +(defun org-try-structure-completion () + "Try to complete a structure template before point. +This looks for strings like \"<e\" on an otherwise empty line and +expands them." + (let ((l (buffer-substring (point-at-bol) (point))) + a) + (when (and (looking-at "[ \t]*$") + (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l) + (setq a (assoc (match-string 1 l) org-structure-template-alist))) + (org-complete-expand-structure-template (+ -1 (point-at-bol) + (match-beginning 1)) a) + t))) + +(defun org-complete-expand-structure-template (start cell) + "Expand a structure template." + (let ((rpl (nth 1 cell)) + (ind "")) + (delete-region start (point)) + (when (string-match "\\`[ \t]*#\\+" rpl) + (cond + ((bolp)) + ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point)))) + (setq ind (buffer-substring (point-at-bol) (point)))) + (t (newline)))) + (setq start (point)) + (when (string-match "%file" rpl) + (setq rpl (replace-match + (concat + "\"" + (save-match-data + (abbreviate-file-name (read-file-name "Include file: "))) + "\"") + t t rpl))) + (setq rpl (mapconcat 'identity (split-string rpl "\n") + (concat "\n" ind))) + (insert rpl) + (when (re-search-backward "\\?" start t) (delete-char 1)))) + +;;;; TODO, DEADLINE, Comments + +(defun org-toggle-comment () + "Change the COMMENT state of an entry." + (interactive) + (save-excursion + (org-back-to-heading) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp)) + (goto-char (or (match-end 3) (match-end 2) (match-end 1))) + (skip-chars-forward " \t") + (unless (memq (char-before) '(?\s ?\t)) (insert " ")) + (if (org-in-commented-heading-p t) + (delete-region (point) + (progn (search-forward " " (line-end-position) 'move) + (skip-chars-forward " \t") + (point))) + (insert org-comment-string) + (unless (eolp) (insert " "))))) + +(defvar org-last-todo-state-is-todo nil + "This is non-nil when the last TODO state change led to a TODO state. +If the last change removed the TODO tag or switched to DONE, then +this is nil.") + +(defvar org-setting-tags nil) ; dynamically skipped + +(defvar org-todo-setup-filter-hook nil + "Hook for functions that pre-filter todo specs. +Each function takes a todo spec and returns either nil or the spec +transformed into canonical form." ) + +(defvar org-todo-get-default-hook nil + "Hook for functions that get a default item for todo. +Each function takes arguments (NEW-MARK OLD-MARK) and returns either +nil or a string to be used for the todo mark." ) + +(defvar org-agenda-headline-snapshot-before-repeat) + +(defun org-current-effective-time () + "Return current time adjusted for `org-extend-today-until' variable." + (let* ((ct (org-current-time)) + (dct (decode-time ct)) + (ct1 + (cond + (org-use-last-clock-out-time-as-effective-time + (or (org-clock-get-last-clock-out-time) ct)) + ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until)) + (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))) + (t ct)))) + ct1)) + +(defun org-todo-yesterday (&optional arg) + "Like `org-todo' but the time of change will be 23:59 of yesterday." + (interactive "P") + (if (eq major-mode 'org-agenda-mode) + (apply 'org-agenda-todo-yesterday arg) + (let* ((org-use-effective-time t) + (hour (nth 2 (decode-time (org-current-time)))) + (org-extend-today-until (1+ hour))) + (org-todo arg)))) + +(defvar org-block-entry-blocking "" + "First entry preventing the TODO state change.") + +(defun org-cancel-repeater () + "Cancel a repeater by setting its numeric value to zero." + (interactive) + (save-excursion + (org-back-to-heading t) + (let ((bound1 (point)) + (bound0 (save-excursion (outline-next-heading) (point)))) + (when (and (re-search-forward + (concat "\\(" org-scheduled-time-regexp "\\)\\|\\(" + org-deadline-time-regexp "\\)\\|\\(" + org-ts-regexp "\\)") + bound0 t) + (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" + bound1 t)) + (replace-match "0" t nil nil 1))))) + +(defvar org-state) +(defvar org-blocked-by-checkboxes) +(defun org-todo (&optional arg) + "Change the TODO state of an item. + +The state of an item is given by a keyword at the start of the heading, +like + *** TODO Write paper + *** DONE Call mom + +The different keywords are specified in the variable `org-todo-keywords'. +By default the available states are \"TODO\" and \"DONE\". So, for this +example: when the item starts with TODO, it is changed to DONE. +When it starts with DONE, the DONE is removed. And when neither TODO nor +DONE are present, add TODO at the beginning of the heading. + +With `\\[universal-argument]' prefix ARG, use completion to determine the new \ +state. +With numeric prefix ARG, switch to that state. +With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \ +next set of TODO \ +keywords (nextset). +With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \ +prefix, circumvent any state blocking. +With a numeric prefix arg of 0, inhibit note taking for the change. +With a numeric prefix arg of -1, cancel repeater to allow marking as DONE. + +When called through ELisp, arg is also interpreted in the following way: +`none' -> empty state +\"\" -> switch to empty state +`done' -> switch to DONE +`nextset' -> switch to the next set of keywords +`previousset' -> switch to the previous set of keywords +\"WAITING\" -> switch to the specified keyword, but only if it + really is a member of `org-todo-keywords'." + (interactive "P") + (if (and (org-region-active-p) org-loop-over-headlines-in-active-region) + (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level) + 'region-start-level 'region)) + org-loop-over-headlines-in-active-region) + (org-map-entries + `(org-todo ,arg) + org-loop-over-headlines-in-active-region + cl (when (org-invisible-p) (org-end-of-subtree nil t)))) + (when (equal arg '(16)) (setq arg 'nextset)) + (when (equal arg -1) (org-cancel-repeater) (setq arg nil)) + (let ((org-blocker-hook org-blocker-hook) + commentp + case-fold-search) + (when (equal arg '(64)) + (setq arg nil org-blocker-hook nil)) + (when (and org-blocker-hook + (or org-inhibit-blocking + (org-entry-get nil "NOBLOCKING"))) + (setq org-blocker-hook nil)) + (save-excursion + (catch 'exit + (org-back-to-heading t) + (when (org-in-commented-heading-p t) + (org-toggle-comment) + (setq commentp t)) + (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0)))) + (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)")) + (looking-at "\\(?: *\\|[ \t]*$\\)")) + (let* ((match-data (match-data)) + (startpos (copy-marker (line-beginning-position))) + (logging (save-match-data (org-entry-get nil "LOGGING" t t))) + (org-log-done org-log-done) + (org-log-repeat org-log-repeat) + (org-todo-log-states org-todo-log-states) + (org-inhibit-logging + (if (equal arg 0) + (progn (setq arg nil) 'note) org-inhibit-logging)) + (this (match-string 1)) + (hl-pos (match-beginning 0)) + (head (org-get-todo-sequence-head this)) + (ass (assoc head org-todo-kwd-alist)) + (interpret (nth 1 ass)) + (done-word (nth 3 ass)) + (final-done-word (nth 4 ass)) + (org-last-state (or this "")) + (completion-ignore-case t) + (member (member this org-todo-keywords-1)) + (tail (cdr member)) + (org-state (cond + ((and org-todo-key-trigger + (or (and (equal arg '(4)) + (eq org-use-fast-todo-selection 'prefix)) + (and (not arg) org-use-fast-todo-selection + (not (eq org-use-fast-todo-selection + 'prefix))))) + ;; Use fast selection. + (org-fast-todo-selection)) + ((and (equal arg '(4)) + (or (not org-use-fast-todo-selection) + (not org-todo-key-trigger))) + ;; Read a state with completion. + (completing-read + "State: " (mapcar #'list org-todo-keywords-1) + nil t)) + ((eq arg 'right) + (if this + (if tail (car tail) nil) + (car org-todo-keywords-1))) + ((eq arg 'left) + (unless (equal member org-todo-keywords-1) + (if this + (nth (- (length org-todo-keywords-1) + (length tail) 2) + org-todo-keywords-1) + (org-last org-todo-keywords-1)))) + ((and (eq org-use-fast-todo-selection t) (equal arg '(4)) + (setq arg nil))) ;hack to fall back to cycling + (arg + ;; User or caller requests a specific state. + (cond + ((equal arg "") nil) + ((eq arg 'none) nil) + ((eq arg 'done) (or done-word (car org-done-keywords))) + ((eq arg 'nextset) + (or (car (cdr (member head org-todo-heads))) + (car org-todo-heads))) + ((eq arg 'previousset) + (let ((org-todo-heads (reverse org-todo-heads))) + (or (car (cdr (member head org-todo-heads))) + (car org-todo-heads)))) + ((car (member arg org-todo-keywords-1))) + ((stringp arg) + (user-error "State `%s' not valid in this file" arg)) + ((nth (1- (prefix-numeric-value arg)) + org-todo-keywords-1)))) + ((null member) (or head (car org-todo-keywords-1))) + ((equal this final-done-word) nil) ;-> make empty + ((null tail) nil) ;-> first entry + ((memq interpret '(type priority)) + (if (eq this-command last-command) + (car tail) + (if (> (length tail) 0) + (or done-word (car org-done-keywords)) + nil))) + (t + (car tail)))) + (org-state (or + (run-hook-with-args-until-success + 'org-todo-get-default-hook org-state org-last-state) + org-state)) + (next (if org-state (concat " " org-state " ") " ")) + (change-plist (list :type 'todo-state-change :from this :to org-state + :position startpos)) + dolog now-done-p) + (when org-blocker-hook + (let (org-blocked-by-checkboxes block-reason) + (setq org-last-todo-state-is-todo + (not (member this org-done-keywords))) + (unless (save-excursion + (save-match-data + (org-with-wide-buffer + (run-hook-with-args-until-failure + 'org-blocker-hook change-plist)))) + (setq block-reason (if org-blocked-by-checkboxes + "contained checkboxes" + (format "\"%s\"" org-block-entry-blocking))) + (if (called-interactively-p 'interactive) + (user-error "TODO state change from %s to %s blocked (by %s)" + this org-state block-reason) + ;; Fail silently. + (message "TODO state change from %s to %s blocked (by %s)" + this org-state block-reason) + (throw 'exit nil))))) + (store-match-data match-data) + (replace-match next t t) + (cond ((equal this org-state) + (message "TODO state was already %s" (org-trim next))) + ((not (pos-visible-in-window-p hl-pos)) + (message "TODO state changed to %s" (org-trim next)))) + (unless head + (setq head (org-get-todo-sequence-head org-state) + ass (assoc head org-todo-kwd-alist) + interpret (nth 1 ass) + done-word (nth 3 ass) + final-done-word (nth 4 ass))) + (when (memq arg '(nextset previousset)) + (message "Keyword-Set %d/%d: %s" + (- (length org-todo-sets) -1 + (length (memq (assoc org-state org-todo-sets) org-todo-sets))) + (length org-todo-sets) + (mapconcat 'identity (assoc org-state org-todo-sets) " "))) + (setq org-last-todo-state-is-todo + (not (member org-state org-done-keywords))) + (setq now-done-p (and (member org-state org-done-keywords) + (not (member this org-done-keywords)))) + (and logging (org-local-logging logging)) + (when (and (or org-todo-log-states org-log-done) + (not (eq org-inhibit-logging t)) + (not (memq arg '(nextset previousset)))) + ;; We need to look at recording a time and note. + (setq dolog (or (nth 1 (assoc org-state org-todo-log-states)) + (nth 2 (assoc this org-todo-log-states)))) + (when (and (eq dolog 'note) (eq org-inhibit-logging 'note)) + (setq dolog 'time)) + (when (or (and (not org-state) (not org-closed-keep-when-no-todo)) + (and org-state + (member org-state org-not-done-keywords) + (not (member this org-not-done-keywords)))) + ;; This is now a todo state and was not one before + ;; If there was a CLOSED time stamp, get rid of it. + (org-add-planning-info nil nil 'closed)) + (when (and now-done-p org-log-done) + ;; It is now done, and it was not done before. + (org-add-planning-info 'closed (org-current-effective-time)) + (when (and (not dolog) (eq 'note org-log-done)) + (org-add-log-setup 'done org-state this 'note))) + (when (and org-state dolog) + ;; This is a non-nil state, and we need to log it. + (org-add-log-setup 'state org-state this dolog))) + ;; Fixup tag positioning. + (org-todo-trigger-tag-changes org-state) + (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t)) + (when org-provide-todo-statistics + (org-update-parent-todo-statistics)) + (run-hooks 'org-after-todo-state-change-hook) + (when (and arg (not (member org-state org-done-keywords))) + (setq head (org-get-todo-sequence-head org-state))) + (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head) + ;; Do we need to trigger a repeat? + (when now-done-p + (when (boundp 'org-agenda-headline-snapshot-before-repeat) + ;; This is for the agenda, take a snapshot of the headline. + (save-match-data + (setq org-agenda-headline-snapshot-before-repeat + (org-get-heading)))) + (org-auto-repeat-maybe org-state)) + ;; Fixup cursor location if close to the keyword. + (when (and (outline-on-heading-p) + (not (bolp)) + (save-excursion (beginning-of-line 1) + (looking-at org-todo-line-regexp)) + (< (point) (+ 2 (or (match-end 2) (match-end 1))))) + (goto-char (or (match-end 2) (match-end 1))) + (and (looking-at " ") (just-one-space))) + (when org-trigger-hook + (save-excursion + (run-hook-with-args 'org-trigger-hook change-plist))) + (when commentp (org-toggle-comment)))))))) + +(defun org-block-todo-from-children-or-siblings-or-parent (change-plist) + "Block turning an entry into a TODO, using the hierarchy. +This checks whether the current task should be blocked from state +changes. Such blocking occurs when: + + 1. The task has children which are not all in a completed state. + + 2. A task has a parent with the property :ORDERED:, and there + are siblings prior to the current task with incomplete + status. + + 3. The parent of the task is blocked because it has siblings that should + be done first, or is child of a block grandparent TODO entry." + + (if (not org-enforce-todo-dependencies) + t ; if locally turned off don't block + (catch 'dont-block + ;; If this is not a todo state change, or if this entry is already DONE, + ;; do not block + (when (or (not (eq (plist-get change-plist :type) 'todo-state-change)) + (member (plist-get change-plist :from) + (cons 'done org-done-keywords)) + (member (plist-get change-plist :to) + (cons 'todo org-not-done-keywords)) + (not (plist-get change-plist :to))) + (throw 'dont-block t)) + ;; If this task has children, and any are undone, it's blocked + (save-excursion + (org-back-to-heading t) + (let ((this-level (funcall outline-level))) + (outline-next-heading) + (let ((child-level (funcall outline-level))) + (while (and (not (eobp)) + (> child-level this-level)) + ;; this todo has children, check whether they are all + ;; completed + (when (and (not (org-entry-is-done-p)) + (org-entry-is-todo-p)) + (setq org-block-entry-blocking (org-get-heading)) + (throw 'dont-block nil)) + (outline-next-heading) + (setq child-level (funcall outline-level)))))) + ;; Otherwise, if the task's parent has the :ORDERED: property, and + ;; any previous siblings are undone, it's blocked + (save-excursion + (org-back-to-heading t) + (let* ((pos (point)) + (parent-pos (and (org-up-heading-safe) (point))) + (case-fold-search nil)) + (unless parent-pos (throw 'dont-block t)) ; no parent + (when (and (org-not-nil (org-entry-get (point) "ORDERED")) + (forward-line 1) + (re-search-forward org-not-done-heading-regexp pos t)) + (setq org-block-entry-blocking (match-string 0)) + (throw 'dont-block nil)) ; block, there is an older sibling not done. + ;; Search further up the hierarchy, to see if an ancestor is blocked + (while t + (goto-char parent-pos) + (unless (looking-at org-not-done-heading-regexp) + (throw 'dont-block t)) ; do not block, parent is not a TODO + (setq pos (point)) + (setq parent-pos (and (org-up-heading-safe) (point))) + (unless parent-pos (throw 'dont-block t)) ; no parent + (when (and (org-not-nil (org-entry-get (point) "ORDERED")) + (forward-line 1) + (re-search-forward org-not-done-heading-regexp pos t) + (setq org-block-entry-blocking (org-get-heading))) + (throw 'dont-block nil)))))))) ; block, older sibling not done. + +(defcustom org-track-ordered-property-with-tag nil + "Should the ORDERED property also be shown as a tag? +The ORDERED property decides if an entry should require subtasks to be +completed in sequence. Since a property is not very visible, setting +this option means that toggling the ORDERED property with the command +`org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is +not relevant for the behavior, but it makes things more visible. + +Note that toggling the tag with tags commands will not change the property +and therefore not influence behavior! + +This can be t, meaning the tag ORDERED should be used, It can also be a +string to select a different tag for this task." + :group 'org-todo + :type '(choice + (const :tag "No tracking" nil) + (const :tag "Track with ORDERED tag" t) + (string :tag "Use other tag"))) + +(defun org-toggle-ordered-property () + "Toggle the ORDERED property of the current entry. +For better visibility, you can track the value of this property with a tag. +See variable `org-track-ordered-property-with-tag'." + (interactive) + (let* ((t1 org-track-ordered-property-with-tag) + (tag (and t1 (if (stringp t1) t1 "ORDERED")))) + (save-excursion + (org-back-to-heading) + (if (org-entry-get nil "ORDERED") + (progn + (org-delete-property "ORDERED") + (and tag (org-toggle-tag tag 'off)) + (message "Subtasks can be completed in arbitrary order")) + (org-entry-put nil "ORDERED" "t") + (and tag (org-toggle-tag tag 'on)) + (message "Subtasks must be completed in sequence"))))) + +(defun org-block-todo-from-checkboxes (change-plist) + "Block turning an entry into a TODO, using checkboxes. +This checks whether the current task should be blocked from state +changes because there are unchecked boxes in this entry." + (if (not org-enforce-todo-checkbox-dependencies) + t ; if locally turned off don't block + (catch 'dont-block + ;; If this is not a todo state change, or if this entry is already DONE, + ;; do not block + (when (or (not (eq (plist-get change-plist :type) 'todo-state-change)) + (member (plist-get change-plist :from) + (cons 'done org-done-keywords)) + (member (plist-get change-plist :to) + (cons 'todo org-not-done-keywords)) + (not (plist-get change-plist :to))) + (throw 'dont-block t)) + ;; If this task has checkboxes that are not checked, it's blocked + (save-excursion + (org-back-to-heading t) + (let ((beg (point)) end) + (outline-next-heading) + (setq end (point)) + (goto-char beg) + (when (org-list-search-forward + (concat (org-item-beginning-re) + "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?" + "\\[[- ]\\]") + end t) + (when (boundp 'org-blocked-by-checkboxes) + (setq org-blocked-by-checkboxes t)) + (throw 'dont-block nil)))) + t))) ; do not block + +(defun org-entry-blocked-p () + "Non-nil if entry at point is blocked." + (and (not (org-entry-get nil "NOBLOCKING")) + (member (org-entry-get nil "TODO") org-not-done-keywords) + (not (run-hook-with-args-until-failure + 'org-blocker-hook + (list :type 'todo-state-change + :position (point) + :from 'todo + :to 'done))))) + +(defun org-update-statistics-cookies (all) + "Update the statistics cookie, either from TODO or from checkboxes. +This should be called with the cursor in a line with a statistics +cookie. When called with a \\[universal-argument] prefix, update +all statistics cookies in the buffer." + (interactive "P") + (if all + (progn + (org-update-checkbox-count 'all) + (org-map-entries 'org-update-parent-todo-statistics)) + (if (not (org-at-heading-p)) + (org-update-checkbox-count) + (let ((pos (point-marker)) + end l1 l2) + (ignore-errors (org-back-to-heading t)) + (if (not (org-at-heading-p)) + (org-update-checkbox-count) + (setq l1 (org-outline-level)) + (setq end (save-excursion + (outline-next-heading) + (when (org-at-heading-p) (setq l2 (org-outline-level))) + (point))) + (if (and (save-excursion + (re-search-forward + "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t)) + (not (save-excursion (re-search-forward + ":COOKIE_DATA:.*\\<todo\\>" end t)))) + (org-update-checkbox-count) + (if (and l2 (> l2 l1)) + (progn + (goto-char end) + (org-update-parent-todo-statistics)) + (goto-char pos) + (beginning-of-line 1) + (while (re-search-forward + "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)" + (point-at-eol) t) + (replace-match (if (match-end 2) "[100%]" "[0/0]") t t))))) + (goto-char pos) + (move-marker pos nil))))) + +(defvar org-entry-property-inherited-from) ;; defined below +(defun org-update-parent-todo-statistics () + "Update any statistics cookie in the parent of the current headline. +When `org-hierarchical-todo-statistics' is nil, statistics will cover +the entire subtree and this will travel up the hierarchy and update +statistics everywhere." + (let* ((prop (save-excursion (org-up-heading-safe) + (org-entry-get nil "COOKIE_DATA" 'inherit))) + (recursive (or (not org-hierarchical-todo-statistics) + (and prop (string-match "\\<recursive\\>" prop)))) + (lim (or (and prop (marker-position org-entry-property-inherited-from)) + 0)) + (first t) + (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)") + level ltoggle l1 new ndel + (cnt-all 0) (cnt-done 0) is-percent kwd + checkbox-beg cookie-present) + (catch 'exit + (save-excursion + (beginning-of-line 1) + (setq ltoggle (funcall outline-level)) + ;; Three situations are to consider: + + ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up + ;; to the top-level ancestor on the headline; + + ;; 2. If parent has "recursive" property, repeat up to the + ;; headline setting that property, taking inheritance into + ;; account; + + ;; 3. Else, move up to direct parent and proceed only once. + (while (and (setq level (org-up-heading-safe)) + (or recursive first) + (>= (point) lim)) + (setq first nil cookie-present nil) + (unless (and level + (not (string-match + "\\<checkbox\\>" + (downcase (or (org-entry-get nil "COOKIE_DATA") + ""))))) + (throw 'exit nil)) + (while (re-search-forward box-re (point-at-eol) t) + (setq cnt-all 0 cnt-done 0 cookie-present t) + (setq is-percent (match-end 2) checkbox-beg (match-beginning 0)) + (save-match-data + (unless (outline-next-heading) (throw 'exit nil)) + (while (and (looking-at org-complex-heading-regexp) + (> (setq l1 (length (match-string 1))) level)) + (setq kwd (and (or recursive (= l1 ltoggle)) + (match-string 2))) + (if (or (eq org-provide-todo-statistics 'all-headlines) + (and (eq org-provide-todo-statistics t) + (or (member kwd org-done-keywords))) + (and (listp org-provide-todo-statistics) + (stringp (car org-provide-todo-statistics)) + (or (member kwd org-provide-todo-statistics) + (member kwd org-done-keywords))) + (and (listp org-provide-todo-statistics) + (listp (car org-provide-todo-statistics)) + (or (member kwd (car org-provide-todo-statistics)) + (and (member kwd org-done-keywords) + (member kwd (cadr org-provide-todo-statistics)))))) + (setq cnt-all (1+ cnt-all)) + (and (eq org-provide-todo-statistics t) + kwd + (setq cnt-all (1+ cnt-all)))) + (when (or (and (member org-provide-todo-statistics '(t all-headlines)) + (member kwd org-done-keywords)) + (and (listp org-provide-todo-statistics) + (listp (car org-provide-todo-statistics)) + (member kwd org-done-keywords) + (member kwd (cadr org-provide-todo-statistics))) + (and (listp org-provide-todo-statistics) + (stringp (car org-provide-todo-statistics)) + (member kwd org-done-keywords))) + (setq cnt-done (1+ cnt-done))) + (outline-next-heading))) + (setq new + (if is-percent + (format "[%d%%]" (floor (* 100.0 cnt-done) + (max 1 cnt-all))) + (format "[%d/%d]" cnt-done cnt-all)) + ndel (- (match-end 0) checkbox-beg)) + (goto-char checkbox-beg) + (insert new) + (delete-region (point) (+ (point) ndel)) + (when org-auto-align-tags (org-fix-tags-on-the-fly))) + (when cookie-present + (run-hook-with-args 'org-after-todo-statistics-hook + cnt-done (- cnt-all cnt-done)))))) + (run-hooks 'org-todo-statistics-hook))) + +(defvar org-after-todo-statistics-hook nil + "Hook that is called after a TODO statistics cookie has been updated. +Each function is called with two arguments: the number of not-done entries +and the number of done entries. + +For example, the following function, when added to this hook, will switch +an entry to DONE when all children are done, and back to TODO when new +entries are set to a TODO status. Note that this hook is only called +when there is a statistics cookie in the headline! + + (defun org-summary-todo (n-done n-not-done) + \"Switch entry to DONE when all subentries are done, to TODO otherwise.\" + (let (org-log-done org-log-states) ; turn off logging + (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\")))) +") + +(defvar org-todo-statistics-hook nil + "Hook that is run whenever Org thinks TODO statistics should be updated. +This hook runs even if there is no statistics cookie present, in which case +`org-after-todo-statistics-hook' would not run.") + +(defun org-todo-trigger-tag-changes (state) + "Apply the changes defined in `org-todo-state-tags-triggers'." + (let ((l org-todo-state-tags-triggers) + changes) + (when (or (not state) (equal state "")) + (setq changes (append changes (cdr (assoc "" l))))) + (when (and (stringp state) (> (length state) 0)) + (setq changes (append changes (cdr (assoc state l))))) + (when (member state org-not-done-keywords) + (setq changes (append changes (cdr (assq 'todo l))))) + (when (member state org-done-keywords) + (setq changes (append changes (cdr (assq 'done l))))) + (dolist (c changes) + (org-toggle-tag (car c) (if (cdr c) 'on 'off))))) + +(defun org-local-logging (value) + "Get logging settings from a property VALUE." + ;; Directly set the variables, they are already local. + (setq org-log-done nil + org-log-repeat nil + org-todo-log-states nil) + (dolist (w (split-string value)) + (let (a) + (cond + ((setq a (assoc w org-startup-options)) + (and (member (nth 1 a) '(org-log-done org-log-repeat)) + (set (nth 1 a) (nth 2 a)))) + ((setq a (org-extract-log-state-settings w)) + (and (member (car a) org-todo-keywords-1) + (push a org-todo-log-states))))))) + +(defun org-get-todo-sequence-head (kwd) + "Return the head of the TODO sequence to which KWD belongs. +If KWD is not set, check if there is a text property remembering the +right sequence." + (let (p) + (cond + ((not kwd) + (or (get-text-property (point-at-bol) 'org-todo-head) + (progn + (setq p (next-single-property-change (point-at-bol) 'org-todo-head + nil (point-at-eol))) + (get-text-property p 'org-todo-head)))) + ((not (member kwd org-todo-keywords-1)) + (car org-todo-keywords-1)) + (t (nth 2 (assoc kwd org-todo-kwd-alist)))))) + +(defun org-fast-todo-selection () + "Fast TODO keyword selection with single keys. +Returns the new TODO keyword, or nil if no state change should occur." + (let* ((fulltable org-todo-key-alist) + (done-keywords org-done-keywords) ;; needed for the faces. + (maxlen (apply 'max (mapcar + (lambda (x) + (if (stringp (car x)) (string-width (car x)) 0)) + fulltable))) + (expert nil) + (fwidth (+ maxlen 3 1 3)) + (ncol (/ (- (window-width) 4) fwidth)) + tg cnt e c tbl + groups ingroup) + (save-excursion + (save-window-excursion + (if expert + (set-buffer (get-buffer-create " *Org todo*")) + (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*"))) + (erase-buffer) + (setq-local org-done-keywords done-keywords) + (setq tbl fulltable cnt 0) + (while (setq e (pop tbl)) + (cond + ((equal e '(:startgroup)) + (push '() groups) (setq ingroup t) + (unless (= cnt 0) + (setq cnt 0) + (insert "\n")) + (insert "{ ")) + ((equal e '(:endgroup)) + (setq ingroup nil cnt 0) + (insert "}\n")) + ((equal e '(:newline)) + (unless (= cnt 0) + (setq cnt 0) + (insert "\n") + (setq e (car tbl)) + (while (equal (car tbl) '(:newline)) + (insert "\n") + (setq tbl (cdr tbl))))) + (t + (setq tg (car e) c (cdr e)) + (when ingroup (push tg (car groups))) + (setq tg (org-add-props tg nil 'face + (org-get-todo-face tg))) + (when (and (= cnt 0) (not ingroup)) (insert " ")) + (insert "[" c "] " tg (make-string + (- fwidth 4 (length tg)) ?\ )) + (when (= (setq cnt (1+ cnt)) ncol) + (insert "\n") + (when ingroup (insert " ")) + (setq cnt 0))))) + (insert "\n") + (goto-char (point-min)) + (unless expert (org-fit-window-to-buffer)) + (message "[a-z..]:Set [SPC]:clear") + (setq c (let ((inhibit-quit t)) (read-char-exclusive))) + (cond + ((or (= c ?\C-g) + (and (= c ?q) (not (rassoc c fulltable)))) + (setq quit-flag t)) + ((= c ?\ ) nil) + ((setq e (rassoc c fulltable) tg (car e)) + tg) + (t (setq quit-flag t))))))) + +(defun org-entry-is-todo-p () + (member (org-get-todo-state) org-not-done-keywords)) + +(defun org-entry-is-done-p () + (member (org-get-todo-state) org-done-keywords)) + +(defun org-get-todo-state () + "Return the TODO keyword of the current subtree." + (save-excursion + (org-back-to-heading t) + (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)) + (match-end 2) + (match-string 2)))) + +(defun org-at-date-range-p (&optional inactive-ok) + "Non-nil if point is inside a date range. + +When optional argument INACTIVE-OK is non-nil, also consider +inactive time ranges. + +When this function returns a non-nil value, match data is set +according to `org-tr-regexp-both' or `org-tr-regexp', depending +on INACTIVE-OK." + (interactive) + (save-excursion + (catch 'exit + (let ((pos (point))) + (skip-chars-backward "^[<\r\n") + (skip-chars-backward "<[") + (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp)) + (>= (match-end 0) pos) + (throw 'exit t)) + (skip-chars-backward "^<[\r\n") + (skip-chars-backward "<[") + (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp)) + (>= (match-end 0) pos) + (throw 'exit t))) + nil))) + +(defun org-get-repeat (&optional timestamp) + "Check if there is a time-stamp with repeater in this entry. + +Return the repeater, as a string, or nil. Also return nil when +this function is called before first heading. + +When optional argument TIMESTAMP is a string, extract the +repeater from there instead." + (save-match-data + (cond (timestamp + (and (string-match org-repeat-re timestamp) + (match-string-no-properties 1 timestamp))) + ((org-before-first-heading-p) nil) + (t + (save-excursion + (org-back-to-heading t) + (let ((end (org-entry-end-position))) + (catch :repeat + (while (re-search-forward org-repeat-re end t) + (when (save-match-data (org-at-timestamp-p 'agenda)) + (throw :repeat (match-string-no-properties 1))))))))))) + +(defvar org-last-changed-timestamp) +(defvar org-last-inserted-timestamp) +(defvar org-log-post-message) +(defvar org-log-note-purpose) +(defvar org-log-note-how nil) +(defvar org-log-note-extra) +(defun org-auto-repeat-maybe (done-word) + "Check if the current headline contains a repeated time-stamp. + +If yes, set TODO state back to what it was and change the base date +of repeating deadline/scheduled time stamps to new date. + +This function is run automatically after each state change to a DONE state." + (let* ((repeat (org-get-repeat)) + (aa (assoc org-last-state org-todo-kwd-alist)) + (interpret (nth 1 aa)) + (head (nth 2 aa)) + (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year))) + (msg "Entry repeats: ") + (org-log-done nil) + (org-todo-log-states nil) + (end (copy-marker (org-entry-end-position)))) + (unwind-protect + (when (and repeat (not (zerop (string-to-number (substring repeat 1))))) + (when (eq org-log-repeat t) (setq org-log-repeat 'state)) + (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective) + org-todo-repeat-to-state))) + (org-todo (cond + ((and to-state (member to-state org-todo-keywords-1)) + to-state) + ((eq interpret 'type) org-last-state) + (head) + (t 'none)))) + (org-back-to-heading t) + (org-add-planning-info nil nil 'closed) + ;; When `org-log-repeat' is non-nil or entry contains + ;; a clock, set LAST_REPEAT property. + (when (or org-log-repeat + (catch :clock + (save-excursion + (while (re-search-forward org-clock-line-re end t) + (when (org-at-clock-log-p) (throw :clock t)))))) + (org-entry-put nil "LAST_REPEAT" (format-time-string + (org-time-stamp-format t t) + (current-time)))) + (when org-log-repeat + (if (or (memq 'org-add-log-note (default-value 'post-command-hook)) + (memq 'org-add-log-note post-command-hook)) + ;; We are already setup for some record. + (when (eq org-log-repeat 'note) + ;; Make sure we take a note, not only a time stamp. + (setq org-log-note-how 'note)) + ;; Set up for taking a record. + (org-add-log-setup 'state + (or done-word (car org-done-keywords)) + org-last-state + org-log-repeat))) + (let ((planning-re (regexp-opt + (list org-scheduled-string org-deadline-string)))) + (while (re-search-forward org-ts-regexp end t) + (let* ((ts (match-string 0)) + (planning? (org-at-planning-p)) + (type (if (not planning?) "Plain:" + (save-excursion + (re-search-backward + planning-re (line-beginning-position) t) + (match-string 0))))) + (cond + ;; Ignore fake time-stamps (e.g., within comments). + ((not (org-at-timestamp-p 'agenda))) + ;; Time-stamps without a repeater are usually + ;; skipped. However, a SCHEDULED time-stamp without + ;; one is removed, as they are no longer relevant. + ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" + ts)) + (when (equal type org-scheduled-string) + (org-remove-timestamp-with-keyword type))) + (t + (let ((n (string-to-number (match-string 2 ts))) + (what (match-string 3 ts))) + (when (equal what "w") (setq n (* n 7) what "d")) + (when (and (equal what "h") + (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" + ts))) + (user-error + "Cannot repeat in Repeat in %d hour(s) because no hour \ +has been set" + n)) + ;; Preparation, see if we need to modify the start + ;; date for the change. + (when (match-end 1) + (let ((time (save-match-data + (org-time-string-to-time ts)))) + (cond + ((equal (match-string 1 ts) ".") + ;; Shift starting date to today + (org-timestamp-change + (- (org-today) (time-to-days time)) + 'day)) + ((equal (match-string 1 ts) "+") + (let ((nshiftmax 10) + (nshift 0)) + (while (or (= nshift 0) + (not (time-less-p (current-time) time))) + (when (= (cl-incf nshift) nshiftmax) + (or (y-or-n-p + (format "%d repeater intervals were not \ +enough to shift date past today. Continue? " + nshift)) + (user-error "Abort"))) + (org-timestamp-change n (cdr (assoc what whata))) + (org-in-regexp org-ts-regexp3) + (setq ts (match-string 1)) + (setq time + (save-match-data + (org-time-string-to-time ts))))) + (org-timestamp-change (- n) (cdr (assoc what whata))) + ;; Rematch, so that we have everything in place + ;; for the real shift. + (org-in-regexp org-ts-regexp3) + (setq ts (match-string 1)) + (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" + ts))))) + (save-excursion + (org-timestamp-change n (cdr (assoc what whata)) nil t)) + (setq msg + (concat + msg type " " org-last-changed-timestamp " ")))))))) + (setq org-log-post-message msg) + (message "%s" msg)) + (set-marker end nil)))) + +(defun org-show-todo-tree (arg) + "Make a compact tree which shows all headlines marked with TODO. +The tree will show the lines where the regexp matches, and all higher +headlines above the match. +With a `\\[universal-argument]' prefix, prompt for a regexp to match. +With a numeric prefix N, construct a sparse tree for the Nth element +of `org-todo-keywords-1'." + (interactive "P") + (let ((case-fold-search nil) + (kwd-re + (cond ((null arg) org-not-done-regexp) + ((equal arg '(4)) + (let ((kwd + (completing-read "Keyword (or KWD1|KWD2|...): " + (mapcar #'list org-todo-keywords-1)))) + (concat "\\(" + (mapconcat 'identity (org-split-string kwd "|") "\\|") + "\\)\\>"))) + ((<= (prefix-numeric-value arg) (length org-todo-keywords-1)) + (regexp-quote (nth (1- (prefix-numeric-value arg)) + org-todo-keywords-1))) + (t (user-error "Invalid prefix argument: %s" arg))))) + (message "%d TODO entries found" + (org-occur (concat "^" org-outline-regexp " *" kwd-re ))))) + +(defun org--deadline-or-schedule (arg type time) + "Insert DEADLINE or SCHEDULE information in current entry. +TYPE is either `deadline' or `scheduled'. See `org-deadline' or +`org-schedule' for information about ARG and TIME arguments." + (let* ((deadline? (eq type 'deadline)) + (keyword (if deadline? org-deadline-string org-scheduled-string)) + (log (if deadline? org-log-redeadline org-log-reschedule)) + (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED"))) + (old-date-time (and old-date (org-time-string-to-time old-date))) + ;; Save repeater cookie from either TIME or current scheduled + ;; time stamp. We are going to insert it back at the end of + ;; the process. + (repeater (or (and (org-string-nw-p time) + ;; We use `org-repeat-re' because we need + ;; to tell the difference between a real + ;; repeater and a time delta, e.g. "+2d". + (string-match org-repeat-re time) + (match-string 1 time)) + (and (org-string-nw-p old-date) + (string-match "\\([.+-]+[0-9]+[hdwmy]\ +\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)" + old-date) + (match-string 1 old-date))))) + (pcase arg + (`(4) + (when (and old-date log) + (org-add-log-setup (if deadline? 'deldeadline 'delschedule) + nil old-date log)) + (org-remove-timestamp-with-keyword keyword) + (message (if deadline? "Item no longer has a deadline." + "Item is no longer scheduled."))) + (`(16) + (save-excursion + (org-back-to-heading t) + (let ((regexp (if deadline? org-deadline-time-regexp + org-scheduled-time-regexp))) + (if (not (re-search-forward regexp (line-end-position 2) t)) + (user-error (if deadline? "No deadline information to update" + "No scheduled information to update")) + (let* ((rpl0 (match-string 1)) + (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)) + (msg (if deadline? "Warn starting from" "Delay until"))) + (replace-match + (concat keyword + " <" rpl + (format " -%dd" + (abs (- (time-to-days + (save-match-data + (org-read-date + nil t nil msg old-date-time))) + (time-to-days old-date-time)))) + ">") t t)))))) + (_ + (org-add-planning-info type time 'closed) + (when (and old-date + log + (not (equal old-date org-last-inserted-timestamp))) + (org-add-log-setup (if deadline? 'redeadline 'reschedule) + org-last-inserted-timestamp + old-date + log)) + (when repeater + (save-excursion + (org-back-to-heading t) + (when (re-search-forward + (concat keyword " " org-last-inserted-timestamp) + (line-end-position 2) + t) + (goto-char (1- (match-end 0))) + (insert " " repeater) + (setq org-last-inserted-timestamp + (concat (substring org-last-inserted-timestamp 0 -1) + " " repeater + (substring org-last-inserted-timestamp -1)))))) + (message (if deadline? "Deadline on %s" "Scheduled to %s") + org-last-inserted-timestamp))))) + +(defun org-deadline (arg &optional time) + "Insert the \"DEADLINE:\" string with a timestamp to make a deadline. +With one universal prefix argument, remove any deadline from the item. +With two universal prefix arguments, prompt for a warning delay. +With argument TIME, set the deadline at the corresponding date. TIME +can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"." + (interactive "P") + (if (and (org-region-active-p) org-loop-over-headlines-in-active-region) + (org-map-entries + (lambda () (org--deadline-or-schedule arg 'deadline time)) + nil + (if (eq org-loop-over-headlines-in-active-region 'start-level) + 'region-start-level + 'region) + (lambda () (when (org-invisible-p) (org-end-of-subtree nil t)))) + (org--deadline-or-schedule arg 'deadline time))) + +(defun org-schedule (arg &optional time) + "Insert the SCHEDULED: string with a timestamp to schedule a TODO item. +With one universal prefix argument, remove any scheduling date from the item. +With two universal prefix arguments, prompt for a delay cookie. +With argument TIME, scheduled at the corresponding date. TIME can +either be an Org date like \"2011-07-24\" or a delta like \"+2d\"." + (interactive "P") + (if (and (org-region-active-p) org-loop-over-headlines-in-active-region) + (org-map-entries + (lambda () (org--deadline-or-schedule arg 'scheduled time)) + nil + (if (eq org-loop-over-headlines-in-active-region 'start-level) + 'region-start-level + 'region) + (lambda () (when (org-invisible-p) (org-end-of-subtree nil t)))) + (org--deadline-or-schedule arg 'scheduled time))) + +(defun org-get-scheduled-time (pom &optional inherit) + "Get the scheduled time as a time tuple, of a format suitable +for calling org-schedule with, or if there is no scheduling, +returns nil." + (let ((time (org-entry-get pom "SCHEDULED" inherit))) + (when time + (apply 'encode-time (org-parse-time-string time))))) + +(defun org-get-deadline-time (pom &optional inherit) + "Get the deadline as a time tuple, of a format suitable for +calling org-deadline with, or if there is no scheduling, returns +nil." + (let ((time (org-entry-get pom "DEADLINE" inherit))) + (when time + (apply 'encode-time (org-parse-time-string time))))) + +(defun org-remove-timestamp-with-keyword (keyword) + "Remove all time stamps with KEYWORD in the current entry." + (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*")) + beg) + (save-excursion + (org-back-to-heading t) + (setq beg (point)) + (outline-next-heading) + (while (re-search-backward re beg t) + (replace-match "") + (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point))) + (equal (char-before) ?\ )) + (backward-delete-char 1) + (when (string-match "^[ \t]*$" (buffer-substring + (point-at-bol) (point-at-eol))) + (delete-region (point-at-bol) + (min (point-max) (1+ (point-at-eol)))))))))) + +(defvar org-time-was-given) ; dynamically scoped parameter +(defvar org-end-time-was-given) ; dynamically scoped parameter + +(defun org-at-planning-p () + "Non-nil when point is on a planning info line." + ;; This is as accurate and faster than `org-element-at-point' since + ;; planning info location is fixed in the section. + (org-with-wide-buffer + (beginning-of-line) + (and (looking-at-p org-planning-line-re) + (eq (point) + (ignore-errors + (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p)) + (org-back-to-heading t) + (org-with-limited-levels (org-back-to-heading t))) + (line-beginning-position 2)))))) + +(defun org-add-planning-info (what &optional time &rest remove) + "Insert new timestamp with keyword in the planning line. +WHAT indicates what kind of time stamp to add. It is a symbol +among `closed', `deadline', `scheduled' and nil. TIME indicates +the time to use. If none is given, the user is prompted for +a date. REMOVE indicates what kind of entries to remove. An old +WHAT entry will also be removed." + (let (org-time-was-given org-end-time-was-given default-time default-input) + (catch 'exit + (when (and (memq what '(scheduled deadline)) + (or (not time) + (and (stringp time) + (string-match "^[-+]+[0-9]" time)))) + ;; Try to get a default date/time from existing timestamp + (save-excursion + (org-back-to-heading t) + (let ((end (save-excursion (outline-next-heading) (point))) ts) + (when (re-search-forward (if (eq what 'scheduled) + org-scheduled-time-regexp + org-deadline-time-regexp) + end t) + (setq ts (match-string 1) + default-time (apply 'encode-time (org-parse-time-string ts)) + default-input (and ts (org-get-compact-tod ts))))))) + (when what + (setq time + (if (stringp time) + ;; This is a string (relative or absolute), set + ;; proper date. + (apply #'encode-time + (org-read-date-analyze + time default-time (decode-time default-time))) + ;; If necessary, get the time from the user + (or time (org-read-date nil 'to-time nil nil + default-time default-input))))) + + (org-with-wide-buffer + (org-back-to-heading t) + (forward-line) + (unless (bolp) (insert "\n")) + (cond ((looking-at-p org-planning-line-re) + ;; Move to current indentation. + (skip-chars-forward " \t") + ;; Check if we have to remove something. + (dolist (type (if what (cons what remove) remove)) + (save-excursion + (when (re-search-forward + (cl-case type + (closed org-closed-time-regexp) + (deadline org-deadline-time-regexp) + (scheduled org-scheduled-time-regexp) + (otherwise + (error "Invalid planning type: %s" type))) + (line-end-position) t) + ;; Delete until next keyword or end of line. + (delete-region + (match-beginning 0) + (if (re-search-forward org-keyword-time-not-clock-regexp + (line-end-position) + t) + (match-beginning 0) + (line-end-position)))))) + ;; If there is nothing more to add and no more keyword + ;; is left, remove the line completely. + (if (and (looking-at-p "[ \t]*$") (not what)) + (delete-region (line-beginning-position) + (line-beginning-position 2)) + ;; If we removed last keyword, do not leave trailing + ;; white space at the end of line. + (let ((p (point))) + (save-excursion + (end-of-line) + (unless (= (skip-chars-backward " \t" p) 0) + (delete-region (point) (line-end-position))))))) + ((not what) (throw 'exit nil)) ; Nothing to do. + (t (insert-before-markers "\n") + (backward-char 1) + (when org-adapt-indentation + (indent-to-column (1+ (org-outline-level)))))) + (when what + ;; Insert planning keyword. + (insert (cl-case what + (closed org-closed-string) + (deadline org-deadline-string) + (scheduled org-scheduled-string) + (otherwise (error "Invalid planning type: %s" what))) + " ") + ;; Insert associated timestamp. + (let ((ts (org-insert-time-stamp + time + (or org-time-was-given + (and (eq what 'closed) org-log-done-with-time)) + (eq what 'closed) + nil nil (list org-end-time-was-given)))) + (unless (eolp) (insert " ")) + ts)))))) + +(defvar org-log-note-marker (make-marker) + "Marker pointing at the entry where the note is to be inserted.") +(defvar org-log-note-purpose nil) +(defvar org-log-note-state nil) +(defvar org-log-note-previous-state nil) +(defvar org-log-note-extra nil) +(defvar org-log-note-window-configuration nil) +(defvar org-log-note-return-to (make-marker)) +(defvar org-log-note-effective-time nil + "Remembered current time so that dynamically scoped +`org-extend-today-until' affects timestamps in state change log") + +(defvar org-log-post-message nil + "Message to be displayed after a log note has been stored. +The auto-repeater uses this.") + +(defun org-add-note () + "Add a note to the current entry. +This is done in the same way as adding a state change note." + (interactive) + (org-add-log-setup 'note)) + +(defun org-log-beginning (&optional create) + "Return expected start of log notes in current entry. +When optional argument CREATE is non-nil, the function creates +a drawer to store notes, if necessary. Returned position ignores +narrowing." + (org-with-wide-buffer + (let ((drawer (org-log-into-drawer))) + (cond + (drawer + (org-end-of-meta-data) + (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$")) + (end (if (org-at-heading-p) (point) + (save-excursion (outline-next-heading) (point)))) + (case-fold-search t)) + (catch 'exit + ;; Try to find existing drawer. + (while (re-search-forward regexp end t) + (let ((element (org-element-at-point))) + (when (eq (org-element-type element) 'drawer) + (let ((cend (org-element-property :contents-end element))) + (when (and (not org-log-states-order-reversed) cend) + (goto-char cend))) + (throw 'exit nil)))) + ;; No drawer found. Create one, if permitted. + (when create + (unless (bolp) (insert "\n")) + (let ((beg (point))) + (insert ":" drawer ":\n:END:\n") + (org-indent-region beg (point))) + (end-of-line -1))))) + (t + (org-end-of-meta-data org-log-state-notes-insert-after-drawers) + (skip-chars-forward " \t\n") + (beginning-of-line) + (unless org-log-states-order-reversed + (org-skip-over-state-notes) + (skip-chars-backward " \t\n") + (forward-line))))) + (if (bolp) (point) (line-beginning-position 2)))) + +(defun org-add-log-setup (&optional purpose state prev-state how extra) + "Set up the post command hook to take a note. +If this is about to TODO state change, the new state is expected in STATE. +HOW is an indicator what kind of note should be created. +EXTRA is additional text that will be inserted into the notes buffer." + (move-marker org-log-note-marker (point)) + (setq org-log-note-purpose purpose + org-log-note-state state + org-log-note-previous-state prev-state + org-log-note-how how + org-log-note-extra extra + org-log-note-effective-time (org-current-effective-time)) + (add-hook 'post-command-hook 'org-add-log-note 'append)) + +(defun org-skip-over-state-notes () + "Skip past the list of State notes in an entry." + (when (ignore-errors (goto-char (org-in-item-p))) + (let* ((struct (org-list-struct)) + (prevs (org-list-prevs-alist struct)) + (regexp + (concat "[ \t]*- +" + (replace-regexp-in-string + " +" " +" + (org-replace-escapes + (regexp-quote (cdr (assq 'state org-log-note-headings))) + `(("%d" . ,org-ts-regexp-inactive) + ("%D" . ,org-ts-regexp) + ("%s" . "\\(?:\"\\S-+\"\\)?") + ("%S" . "\\(?:\"\\S-+\"\\)?") + ("%t" . ,org-ts-regexp-inactive) + ("%T" . ,org-ts-regexp) + ("%u" . ".*?") + ("%U" . ".*?"))))))) + (while (looking-at-p regexp) + (goto-char (or (org-list-get-next-item (point) struct prevs) + (org-list-get-item-end (point) struct))))))) + +(defun org-add-log-note (&optional _purpose) + "Pop up a window for taking a note, and add this note later." + (remove-hook 'post-command-hook 'org-add-log-note) + (setq org-log-note-window-configuration (current-window-configuration)) + (delete-other-windows) + (move-marker org-log-note-return-to (point)) + (pop-to-buffer-same-window (marker-buffer org-log-note-marker)) + (goto-char org-log-note-marker) + (org-switch-to-buffer-other-window "*Org Note*") + (erase-buffer) + (if (memq org-log-note-how '(time state)) + (org-store-log-note) + (let ((org-inhibit-startup t)) (org-mode)) + (insert (format "# Insert note for %s. +# Finish with C-c C-c, or cancel with C-c C-k.\n\n" + (cond + ((eq org-log-note-purpose 'clock-out) "stopped clock") + ((eq org-log-note-purpose 'done) "closed todo item") + ((eq org-log-note-purpose 'state) + (format "state change from \"%s\" to \"%s\"" + (or org-log-note-previous-state "") + (or org-log-note-state ""))) + ((eq org-log-note-purpose 'reschedule) + "rescheduling") + ((eq org-log-note-purpose 'delschedule) + "no longer scheduled") + ((eq org-log-note-purpose 'redeadline) + "changing deadline") + ((eq org-log-note-purpose 'deldeadline) + "removing deadline") + ((eq org-log-note-purpose 'refile) + "refiling") + ((eq org-log-note-purpose 'note) + "this entry") + (t (error "This should not happen"))))) + (when org-log-note-extra (insert org-log-note-extra)) + (setq-local org-finish-function 'org-store-log-note) + (run-hooks 'org-log-buffer-setup-hook))) + +(defvar org-note-abort nil) ; dynamically scoped +(defun org-store-log-note () + "Finish taking a log note, and insert it to where it belongs." + (let ((txt (prog1 (buffer-string) + (kill-buffer))) + (note (cdr (assq org-log-note-purpose org-log-note-headings))) + lines) + (while (string-match "\\`# .*\n[ \t\n]*" txt) + (setq txt (replace-match "" t t txt))) + (when (string-match "\\s-+\\'" txt) + (setq txt (replace-match "" t t txt))) + (setq lines (and (not (equal "" txt)) (org-split-string txt "\n"))) + (when (org-string-nw-p note) + (setq note + (org-replace-escapes + note + (list (cons "%u" (user-login-name)) + (cons "%U" user-full-name) + (cons "%t" (format-time-string + (org-time-stamp-format 'long 'inactive) + org-log-note-effective-time)) + (cons "%T" (format-time-string + (org-time-stamp-format 'long nil) + org-log-note-effective-time)) + (cons "%d" (format-time-string + (org-time-stamp-format nil 'inactive) + org-log-note-effective-time)) + (cons "%D" (format-time-string + (org-time-stamp-format nil nil) + org-log-note-effective-time)) + (cons "%s" (cond + ((not org-log-note-state) "") + ((string-match-p org-ts-regexp + org-log-note-state) + (format "\"[%s]\"" + (substring org-log-note-state 1 -1))) + (t (format "\"%s\"" org-log-note-state)))) + (cons "%S" + (cond + ((not org-log-note-previous-state) "") + ((string-match-p org-ts-regexp + org-log-note-previous-state) + (format "\"[%s]\"" + (substring + org-log-note-previous-state 1 -1))) + (t (format "\"%s\"" + org-log-note-previous-state))))))) + (when lines (setq note (concat note " \\\\"))) + (push note lines)) + (when (and lines (not org-note-abort)) + (with-current-buffer (marker-buffer org-log-note-marker) + (org-with-wide-buffer + ;; Find location for the new note. + (goto-char org-log-note-marker) + (set-marker org-log-note-marker nil) + ;; Note associated to a clock is to be located right after + ;; the clock. Do not move point. + (unless (eq org-log-note-purpose 'clock-out) + (goto-char (org-log-beginning t))) + ;; Make sure point is at the beginning of an empty line. + (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n"))) + ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n")))) + ;; In an existing list, add a new item at the top level. + ;; Otherwise, indent line like a regular one. + (let ((itemp (org-in-item-p))) + (if itemp + (indent-line-to + (let ((struct (save-excursion + (goto-char itemp) (org-list-struct)))) + (org-list-get-ind (org-list-get-top-point struct) struct))) + (org-indent-line))) + (insert (org-list-bullet-string "-") (pop lines)) + (let ((ind (org-list-item-body-column (line-beginning-position)))) + (dolist (line lines) + (insert "\n") + (indent-line-to ind) + (insert line))) + (message "Note stored") + (org-back-to-heading t) + (org-cycle-hide-drawers 'children)) + ;; Fix `buffer-undo-list' when `org-store-log-note' is called + ;; from within `org-add-log-note' because `buffer-undo-list' + ;; is then modified outside of `org-with-remote-undo'. + (when (eq this-command 'org-agenda-todo) + (setcdr buffer-undo-list (cddr buffer-undo-list)))))) + ;; Don't add undo information when called from `org-agenda-todo'. + (let ((buffer-undo-list (eq this-command 'org-agenda-todo))) + (set-window-configuration org-log-note-window-configuration) + (with-current-buffer (marker-buffer org-log-note-return-to) + (goto-char org-log-note-return-to)) + (move-marker org-log-note-return-to nil) + (when org-log-post-message (message "%s" org-log-post-message)))) + +(defun org-remove-empty-drawer-at (pos) + "Remove an empty drawer at position POS. +POS may also be a marker." + (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer)) + (org-with-wide-buffer + (goto-char pos) + (let ((drawer (org-element-at-point))) + (when (and (memq (org-element-type drawer) '(drawer property-drawer)) + (not (org-element-property :contents-begin drawer))) + (delete-region (org-element-property :begin drawer) + (progn (goto-char (org-element-property :end drawer)) + (skip-chars-backward " \r\t\n") + (forward-line) + (point)))))))) + +(defvar org-ts-type nil) +(defun org-sparse-tree (&optional arg type) + "Create a sparse tree, prompt for the details. +This command can create sparse trees. You first need to select the type +of match used to create the tree: + +t Show all TODO entries. +T Show entries with a specific TODO keyword. +m Show entries selected by a tags/property match. +p Enter a property name and its value (both with completion on existing + names/values) and show entries with that property. +r Show entries matching a regular expression (`/' can be used as well). +b Show deadlines and scheduled items before a date. +a Show deadlines and scheduled items after a date. +d Show deadlines due within `org-deadline-warning-days'. +D Show deadlines and scheduled items between a date range." + (interactive "P") + (setq type (or type org-sparse-tree-default-date-type)) + (setq org-ts-type type) + (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty + \[d]eadlines [b]efore-date [a]fter-date [D]ates range + \[c]ycle through date types: %s" + (cl-case type + (all "all timestamps") + (scheduled "only scheduled") + (deadline "only deadline") + (active "only active timestamps") + (inactive "only inactive timestamps") + (closed "with a closed time-stamp") + (otherwise "scheduled/deadline"))) + (let ((answer (read-char-exclusive))) + (cl-case answer + (?c + (org-sparse-tree + arg + (cadr + (memq type '(nil all scheduled deadline active inactive closed))))) + (?d (call-interactively 'org-check-deadlines)) + (?b (call-interactively 'org-check-before-date)) + (?a (call-interactively 'org-check-after-date)) + (?D (call-interactively 'org-check-dates-range)) + (?t (call-interactively 'org-show-todo-tree)) + (?T (org-show-todo-tree '(4))) + (?m (call-interactively 'org-match-sparse-tree)) + ((?p ?P) + (let* ((kwd (completing-read + "Property: " (mapcar #'list (org-buffer-property-keys)))) + (value (completing-read + "Value: " (mapcar #'list (org-property-values kwd))))) + (unless (string-match "\\`{.*}\\'" value) + (setq value (concat "\"" value "\""))) + (org-match-sparse-tree arg (concat kwd "=" value)))) + ((?r ?R ?/) (call-interactively 'org-occur)) + (otherwise (user-error "No such sparse tree command \"%c\"" answer))))) + +(defvar-local org-occur-highlights nil + "List of overlays used for occur matches.") +(defvar-local org-occur-parameters nil + "Parameters of the active org-occur calls. +This is a list, each call to org-occur pushes as cons cell, +containing the regular expression and the callback, onto the list. +The list can contain several entries if `org-occur' has been called +several time with the KEEP-PREVIOUS argument. Otherwise, this list +will only contain one set of parameters. When the highlights are +removed (for example with `C-c C-c', or with the next edit (depending +on `org-remove-highlights-with-change'), this variable is emptied +as well.") + +(defun org-occur (regexp &optional keep-previous callback) + "Make a compact tree which shows all matches of REGEXP. + +The tree will show the lines where the regexp matches, and any other context +defined in `org-show-context-detail', which see. + +When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing +done by a previous call to `org-occur' will be kept, to allow stacking of +calls to this command. + +Optional argument CALLBACK can be a function of no argument. In this case, +it is called with point at the end of the match, match data being set +accordingly. Current match is shown only if the return value is non-nil. +The function must neither move point nor alter narrowing." + (interactive "sRegexp: \nP") + (when (equal regexp "") + (user-error "Regexp cannot be empty")) + (unless keep-previous + (org-remove-occur-highlights nil nil t)) + (push (cons regexp callback) org-occur-parameters) + (let ((cnt 0)) + (save-excursion + (goto-char (point-min)) + (when (or (not keep-previous) ; do not want to keep + (not org-occur-highlights)) ; no previous matches + ;; hide everything + (org-overview)) + (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart) + (isearch-no-upper-case-p regexp t) + org-occur-case-fold-search))) + (while (re-search-forward regexp nil t) + (when (or (not callback) + (save-match-data (funcall callback))) + (setq cnt (1+ cnt)) + (when org-highlight-sparse-tree-matches + (org-highlight-new-match (match-beginning 0) (match-end 0))) + (org-show-context 'occur-tree))))) + (when org-remove-highlights-with-change + (add-hook 'before-change-functions 'org-remove-occur-highlights + nil 'local)) + (unless org-sparse-tree-open-archived-trees + (org-hide-archived-subtrees (point-min) (point-max))) + (run-hooks 'org-occur-hook) + (when (called-interactively-p 'interactive) + (message "%d match(es) for regexp %s" cnt regexp)) + cnt)) + +(defun org-occur-next-match (&optional n _reset) + "Function for `next-error-function' to find sparse tree matches. +N is the number of matches to move, when negative move backwards. +This function always goes back to the starting point when no +match is found." + (let* ((limit (if (< n 0) (point-min) (point-max))) + (search-func (if (< n 0) + 'previous-single-char-property-change + 'next-single-char-property-change)) + (n (abs n)) + (pos (point)) + p1) + (catch 'exit + (while (setq p1 (funcall search-func (point) 'org-type)) + (when (equal p1 limit) + (goto-char pos) + (user-error "No more matches")) + (when (equal (get-char-property p1 'org-type) 'org-occur) + (setq n (1- n)) + (when (= n 0) + (goto-char p1) + (throw 'exit (point)))) + (goto-char p1)) + (goto-char p1) + (user-error "No more matches")))) + +(defun org-show-context (&optional key) + "Make sure point and context are visible. +Optional argument KEY, when non-nil, is a symbol. See +`org-show-context-detail' for allowed values and how much is to +be shown." + (org-show-set-visibility + (cond ((symbolp org-show-context-detail) org-show-context-detail) + ((cdr (assq key org-show-context-detail))) + (t (cdr (assq 'default org-show-context-detail)))))) + +(defun org-show-set-visibility (detail) + "Set visibility around point according to DETAIL. +DETAIL is either nil, `minimal', `local', `ancestors', `lineage', +`tree', `canonical' or t. See `org-show-context-detail' for more +information." + ;; Show current heading and possibly its entry, following headline + ;; or all children. + (if (and (org-at-heading-p) (not (eq detail 'local))) + (org-flag-heading nil) + (org-show-entry) + ;; If point is hidden within a drawer or a block, make sure to + ;; expose it. + (dolist (o (overlays-at (point))) + (when (memq (overlay-get o 'invisible) '(org-hide-block outline)) + (delete-overlay o))) + (unless (org-before-first-heading-p) + (org-with-limited-levels + (cl-case detail + ((tree canonical t) (org-show-children)) + ((nil minimal ancestors)) + (t (save-excursion + (outline-next-heading) + (org-flag-heading nil))))))) + ;; Show all siblings. + (when (eq detail 'lineage) (org-show-siblings)) + ;; Show ancestors, possibly with their children. + (when (memq detail '(ancestors lineage tree canonical t)) + (save-excursion + (while (org-up-heading-safe) + (org-flag-heading nil) + (when (memq detail '(canonical t)) (org-show-entry)) + (when (memq detail '(tree canonical t)) (org-show-children)))))) + +(defvar org-reveal-start-hook nil + "Hook run before revealing a location.") + +(defun org-reveal (&optional siblings) + "Show current entry, hierarchy above it, and the following headline. + +This can be used to show a consistent set of context around +locations exposed with `org-show-context'. + +With optional argument SIBLINGS, on each level of the hierarchy all +siblings are shown. This repairs the tree structure to what it would +look like when opened with hierarchical calls to `org-cycle'. + +With a \\[universal-argument] \\[universal-argument] prefix, \ +go to the parent and show the entire tree." + (interactive "P") + (run-hooks 'org-reveal-start-hook) + (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical)) + ((equal siblings '(16)) + (save-excursion + (when (org-up-heading-safe) + (org-show-subtree) + (run-hook-with-args 'org-cycle-hook 'subtree)))) + (t (org-show-set-visibility 'lineage)))) + +(defun org-highlight-new-match (beg end) + "Highlight from BEG to END and mark the highlight is an occur headline." + (let ((ov (make-overlay beg end))) + (overlay-put ov 'face 'secondary-selection) + (overlay-put ov 'org-type 'org-occur) + (push ov org-occur-highlights))) + +(defun org-remove-occur-highlights (&optional _beg _end noremove) + "Remove the occur highlights from the buffer. +BEG and END are ignored. If NOREMOVE is nil, remove this function +from the `before-change-functions' in the current buffer." + (interactive) + (unless org-inhibit-highlight-removal + (mapc #'delete-overlay org-occur-highlights) + (setq org-occur-highlights nil) + (setq org-occur-parameters nil) + (unless noremove + (remove-hook 'before-change-functions + 'org-remove-occur-highlights 'local)))) + +;;;; Priorities + +(defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)" + "Regular expression matching the priority indicator.") + +(defvar org-remove-priority-next-time nil) + +(defun org-priority-up () + "Increase the priority of the current item." + (interactive) + (org-priority 'up)) + +(defun org-priority-down () + "Decrease the priority of the current item." + (interactive) + (org-priority 'down)) + +(defun org-priority (&optional action _show) + "Change the priority of an item. +ACTION can be `set', `up', `down', or a character." + (interactive "P") + (if (equal action '(4)) + (org-show-priority) + (unless org-enable-priority-commands + (user-error "Priority commands are disabled")) + (setq action (or action 'set)) + (let (current new news have remove) + (save-excursion + (org-back-to-heading t) + (when (looking-at org-priority-regexp) + (setq current (string-to-char (match-string 2)) + have t)) + (cond + ((eq action 'remove) + (setq remove t new ?\ )) + ((or (eq action 'set) + (integerp action)) + (if (not (eq action 'set)) + (setq new action) + (message "Priority %c-%c, SPC to remove: " + org-highest-priority org-lowest-priority) + (save-match-data + (setq new (read-char-exclusive)))) + (when (and (= (upcase org-highest-priority) org-highest-priority) + (= (upcase org-lowest-priority) org-lowest-priority)) + (setq new (upcase new))) + (cond ((equal new ?\ ) (setq remove t)) + ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority)) + (user-error "Priority must be between `%c' and `%c'" + org-highest-priority org-lowest-priority)))) + ((eq action 'up) + (setq new (if have + (1- current) ; normal cycling + ;; last priority was empty + (if (eq last-command this-command) + org-lowest-priority ; wrap around empty to lowest + ;; default + (if org-priority-start-cycle-with-default + org-default-priority + (1- org-default-priority)))))) + ((eq action 'down) + (setq new (if have + (1+ current) ; normal cycling + ;; last priority was empty + (if (eq last-command this-command) + org-highest-priority ; wrap around empty to highest + ;; default + (if org-priority-start-cycle-with-default + org-default-priority + (1+ org-default-priority)))))) + (t (user-error "Invalid action"))) + (when (or (< (upcase new) org-highest-priority) + (> (upcase new) org-lowest-priority)) + (if (and (memq action '(up down)) + (not have) (not (eq last-command this-command))) + ;; `new' is from default priority + (error + "The default can not be set, see `org-default-priority' why") + ;; normal cycling: `new' is beyond highest/lowest priority + ;; and is wrapped around to the empty priority + (setq remove t))) + (setq news (format "%c" new)) + (if have + (if remove + (replace-match "" t t nil 1) + (replace-match news t t nil 2)) + (if remove + (user-error "No priority cookie found in line") + (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)) + (if (match-end 2) + (progn + (goto-char (match-end 2)) + (insert " [#" news "]")) + (goto-char (match-beginning 3)) + (insert "[#" news "] ")))) + (org-set-tags nil 'align)) + (if remove + (message "Priority removed") + (message "Priority of current item set to %s" news))))) + +(defun org-show-priority () + "Show the priority of the current item. +This priority is composed of the main priority given with the [#A] cookies, +and by additional input from the age of a schedules or deadline entry." + (interactive) + (let ((pri (if (eq major-mode 'org-agenda-mode) + (org-get-at-bol 'priority) + (save-excursion + (save-match-data + (beginning-of-line) + (and (looking-at org-heading-regexp) + (org-get-priority (match-string 0)))))))) + (message "Priority is %d" (if pri pri -1000)))) + +(defun org-get-priority (s) + "Find priority cookie and return priority." + (save-match-data + (if (functionp org-get-priority-function) + (funcall org-get-priority-function) + (if (not (string-match org-priority-regexp s)) + (* 1000 (- org-lowest-priority org-default-priority)) + (* 1000 (- org-lowest-priority + (string-to-char (match-string 2 s)))))))) + +;;;; Tags + +(defvar org-agenda-archives-mode) +(defvar org-map-continue-from nil + "Position from where mapping should continue. +Can be set by the action argument to `org-scan-tags' and `org-map-entries'.") + +(defvar org-scanner-tags nil + "The current tag list while the tags scanner is running.") + +(defvar org-trust-scanner-tags nil + "Should `org-get-tags-at' use the tags for the scanner. +This is for internal dynamical scoping only. +When this is non-nil, the function `org-get-tags-at' will return the value +of `org-scanner-tags' instead of building the list by itself. This +can lead to large speed-ups when the tags scanner is used in a file with +many entries, and when the list of tags is retrieved, for example to +obtain a list of properties. Building the tags list for each entry in such +a file becomes an N^2 operation - but with this variable set, it scales +as N.") + +(defvar org--matcher-tags-todo-only nil) + +(defun org-scan-tags (action matcher todo-only &optional start-level) + "Scan headline tags with inheritance and produce output ACTION. + +ACTION can be `sparse-tree' to produce a sparse tree in the current buffer, +or `agenda' to produce an entry list for an agenda view. It can also be +a Lisp form or a function that should be called at each matched headline, in +this case the return value is a list of all return values from these calls. + +MATCHER is a function accepting three arguments, returning +a non-nil value whenever a given set of tags qualifies a headline +for inclusion. See `org-make-tags-matcher' for more information. +As a special case, it can also be set to t (respectively nil) in +order to match all (respectively none) headline. + +When TODO-ONLY is non-nil, only lines with a TODO keyword are +included in the output. + +START-LEVEL can be a string with asterisks, reducing the scope to +headlines matching this string." + (require 'org-agenda) + (let* ((re (concat "^" + (if start-level + ;; Get the correct level to match + (concat "\\*\\{" (number-to-string start-level) "\\} ") + org-outline-regexp) + " *\\(\\<\\(" + (mapconcat #'regexp-quote org-todo-keywords-1 "\\|") + "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")) + (props (list 'face 'default + 'done-face 'org-agenda-done + 'undone-face 'default + 'mouse-face 'highlight + 'org-not-done-regexp org-not-done-regexp + 'org-todo-regexp org-todo-regexp + 'org-complex-heading-regexp org-complex-heading-regexp + 'help-echo + (format "mouse-2 or RET jump to Org file %S" + (abbreviate-file-name + (or (buffer-file-name (buffer-base-buffer)) + (buffer-name (buffer-base-buffer))))))) + (org-map-continue-from nil) + lspos tags tags-list + (tags-alist (list (cons 0 org-file-tags))) + (llast 0) rtn rtn1 level category i txt + todo marker entry priority + ts-date ts-date-type ts-date-pair) + (unless (or (member action '(agenda sparse-tree)) (functionp action)) + (setq action (list 'lambda nil action))) + (save-excursion + (goto-char (point-min)) + (when (eq action 'sparse-tree) + (org-overview) + (org-remove-occur-highlights)) + (while (let (case-fold-search) + (re-search-forward re nil t)) + (setq org-map-continue-from nil) + (catch :skip + ;; Ignore closing parts of inline tasks. + (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p)) + (throw :skip t)) + (setq todo + ;; TODO: is the 1-2 difference a bug? + (when (match-end 1) (match-string-no-properties 2)) + tags (when (match-end 4) (match-string-no-properties 4))) + (goto-char (setq lspos (match-beginning 0))) + (setq level (org-reduced-level (org-outline-level)) + category (org-get-category)) + (when (eq action 'agenda) + (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point)) + ts-date (car ts-date-pair) + ts-date-type (cdr ts-date-pair))) + (setq i llast llast level) + ;; remove tag lists from same and sublevels + (while (>= i level) + (when (setq entry (assoc i tags-alist)) + (setq tags-alist (delete entry tags-alist))) + (setq i (1- i))) + ;; add the next tags + (when tags + (setq tags (org-split-string tags ":") + tags-alist + (cons (cons level tags) tags-alist))) + ;; compile tags for current headline + (setq tags-list + (if org-use-tag-inheritance + (apply 'append (mapcar 'cdr (reverse tags-alist))) + tags) + org-scanner-tags tags-list) + (when org-use-tag-inheritance + (setcdr (car tags-alist) + (mapcar (lambda (x) + (setq x (copy-sequence x)) + (org-add-prop-inherited x)) + (cdar tags-alist)))) + (when (and tags org-use-tag-inheritance + (or (not (eq t org-use-tag-inheritance)) + org-tags-exclude-from-inheritance)) + ;; Selective inheritance, remove uninherited ones. + (setcdr (car tags-alist) + (org-remove-uninherited-tags (cdar tags-alist)))) + (when (and + + ;; eval matcher only when the todo condition is OK + (and (or (not todo-only) (member todo org-todo-keywords-1)) + (if (functionp matcher) + (let ((case-fold-search t) (org-trust-scanner-tags t)) + (funcall matcher todo tags-list level)) + matcher)) + + ;; Call the skipper, but return t if it does not + ;; skip, so that the `and' form continues evaluating. + (progn + (unless (eq action 'sparse-tree) (org-agenda-skip)) + t) + + ;; Check if timestamps are deselecting this entry + (or (not todo-only) + (and (member todo org-todo-keywords-1) + (or (not org-agenda-tags-todo-honor-ignore-options) + (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))) + + ;; select this headline + (cond + ((eq action 'sparse-tree) + (and org-highlight-sparse-tree-matches + (org-get-heading) (match-end 0) + (org-highlight-new-match + (match-beginning 1) (match-end 1))) + (org-show-context 'tags-tree)) + ((eq action 'agenda) + (setq txt (org-agenda-format-item + "" + (concat + (if (eq org-tags-match-list-sublevels 'indented) + (make-string (1- level) ?.) "") + (org-get-heading)) + (make-string level ?\s) + category + tags-list) + priority (org-get-priority txt)) + (goto-char lspos) + (setq marker (org-agenda-new-marker)) + (org-add-props txt props + 'org-marker marker 'org-hd-marker marker 'org-category category + 'todo-state todo + 'ts-date ts-date + 'priority priority + 'type (concat "tagsmatch" ts-date-type)) + (push txt rtn)) + ((functionp action) + (setq org-map-continue-from nil) + (save-excursion + (setq rtn1 (funcall action)) + (push rtn1 rtn))) + (t (user-error "Invalid action"))) + + ;; if we are to skip sublevels, jump to end of subtree + (unless org-tags-match-list-sublevels + (org-end-of-subtree t) + (backward-char 1)))) + ;; Get the correct position from where to continue + (if org-map-continue-from + (goto-char org-map-continue-from) + (and (= (point) lspos) (end-of-line 1))))) + (when (and (eq action 'sparse-tree) + (not org-sparse-tree-open-archived-trees)) + (org-hide-archived-subtrees (point-min) (point-max))) + (nreverse rtn))) + +(defun org-remove-uninherited-tags (tags) + "Remove all tags that are not inherited from the list TAGS." + (cond + ((eq org-use-tag-inheritance t) + (if org-tags-exclude-from-inheritance + (org-delete-all org-tags-exclude-from-inheritance tags) + tags)) + ((not org-use-tag-inheritance) nil) + ((stringp org-use-tag-inheritance) + (delq nil (mapcar + (lambda (x) + (if (and (string-match org-use-tag-inheritance x) + (not (member x org-tags-exclude-from-inheritance))) + x nil)) + tags))) + ((listp org-use-tag-inheritance) + (delq nil (mapcar + (lambda (x) + (if (member x org-use-tag-inheritance) x nil)) + tags))))) + +(defun org-match-sparse-tree (&optional todo-only match) + "Create a sparse tree according to tags string MATCH. + +MATCH is a string with match syntax. It can contain a selection +of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and +TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of +those. See the manual for details. + +If optional argument TODO-ONLY is non-nil, only select lines that +are also TODO tasks." + (interactive "P") + (org-agenda-prepare-buffers (list (current-buffer))) + (let ((org--matcher-tags-todo-only todo-only)) + (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) + org--matcher-tags-todo-only))) + +(defalias 'org-tags-sparse-tree 'org-match-sparse-tree) + +(defvar org-cached-props nil) +(defun org-cached-entry-get (pom property) + (if (or (eq t org-use-property-inheritance) + (and (stringp org-use-property-inheritance) + (let ((case-fold-search t)) + (string-match-p org-use-property-inheritance property))) + (and (listp org-use-property-inheritance) + (member-ignore-case property org-use-property-inheritance))) + ;; Caching is not possible, check it directly. + (org-entry-get pom property 'inherit) + ;; Get all properties, so we can do complicated checks easily. + (cdr (assoc-string property + (or org-cached-props + (setq org-cached-props (org-entry-properties pom))) + t)))) + +(defun org-global-tags-completion-table (&optional files) + "Return the list of all tags in all agenda buffer/files. +Optional FILES argument is a list of files which can be used +instead of the agenda files." + (save-excursion + (org-uniquify + (delq nil + (apply #'append + (mapcar + (lambda (file) + (set-buffer (find-file-noselect file)) + (org--tag-add-to-alist + (org-get-buffer-tags) + (mapcar (lambda (x) + (and (stringp (car-safe x)) + (list (car-safe x)))) + org-current-tag-alist))) + (if (car-safe files) files + (org-agenda-files)))))))) + +(defun org-make-tags-matcher (match) + "Create the TAGS/TODO matcher form for the selection string MATCH. + +Returns a cons of the selection string MATCH and a function +implementing the matcher. + +The matcher is to be called at an Org entry, with point on the +headline, and returns non-nil if the entry matches the selection +string MATCH. It must be called with three arguments: the TODO +keyword at the entry (or nil if none), the list of all tags at +the entry including inherited ones and the reduced level of the +headline. Additionally, the category of the entry, if any, must +be specified as the text property `org-category' on the headline. + +This function sets the variable `org--matcher-tags-todo-only' to +a non-nil value if the matcher restricts matching to TODO +entries, otherwise it is not touched. + +See also `org-scan-tags'." + (unless match + ;; Get a new match request, with completion against the global + ;; tags table and the local tags in current buffer. + (let ((org-last-tags-completion-table + (org--tag-add-to-alist + (org-get-buffer-tags) + (org-global-tags-completion-table)))) + (setq match + (completing-read + "Match: " + 'org-tags-completion-function nil nil nil 'org-tags-history)))) + + (let ((match0 match) + (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)") + (start 0) + tagsmatch todomatch tagsmatcher todomatcher) + + ;; Expand group tags. + (setq match (org-tags-expand match)) + + ;; Check if there is a TODO part of this match, which would be the + ;; part after a "/". To make sure that this slash is not part of + ;; a property value to be matched against, we also check that + ;; there is no / after that slash. First, find the last slash. + (let ((s 0)) + (while (string-match "/+" match s) + (setq start (match-beginning 0)) + (setq s (match-end 0)))) + (if (and (string-match "/+" match start) + (not (string-match-p "\"" match start))) + ;; Match contains also a TODO-matching request. + (progn + (setq tagsmatch (substring match 0 (match-beginning 0))) + (setq todomatch (substring match (match-end 0))) + (when (string-prefix-p "!" todomatch) + (setq org--matcher-tags-todo-only t) + (setq todomatch (substring todomatch 1))) + (when (string-match "\\`\\s-*\\'" todomatch) + (setq todomatch nil))) + ;; Only matching tags. + (setq tagsmatch match) + (setq todomatch nil)) + + ;; Make the tags matcher. + (when (org-string-nw-p tagsmatch) + (let ((orlist nil) + (orterms (org-split-string tagsmatch "|")) + term) + (while (setq term (pop orterms)) + (while (and (equal (substring term -1) "\\") orterms) + (setq term (concat term "|" (pop orterms)))) ;repair bad split. + (while (string-match re term) + (let* ((rest (substring term (match-end 0))) + (minus (and (match-end 1) + (equal (match-string 1 term) "-"))) + (tag (save-match-data + (replace-regexp-in-string + "\\\\-" "-" (match-string 2 term)))) + (regexp (eq (string-to-char tag) ?{)) + (levelp (match-end 4)) + (propp (match-end 5)) + (mm + (cond + (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list)) + (levelp + `(,(org-op-to-function (match-string 3 term)) + level + ,(string-to-number (match-string 4 term)))) + (propp + (let* ((gv (pcase (upcase (match-string 5 term)) + ("CATEGORY" + '(get-text-property (point) 'org-category)) + ("TODO" 'todo) + (p `(org-cached-entry-get nil ,p)))) + (pv (match-string 7 term)) + (regexp (eq (string-to-char pv) ?{)) + (strp (eq (string-to-char pv) ?\")) + (timep (string-match-p "^\"[[<].*[]>]\"$" pv)) + (po (org-op-to-function (match-string 6 term) + (if timep 'time strp)))) + (setq pv (if (or regexp strp) (substring pv 1 -1) pv)) + (when timep (setq pv (org-matcher-time pv))) + (cond ((and regexp (eq po 'org<>)) + `(not (string-match ,pv (or ,gv "")))) + (regexp `(string-match ,pv (or ,gv ""))) + (strp `(,po (or ,gv "") ,pv)) + (t + `(,po + (string-to-number (or ,gv "")) + ,(string-to-number pv)))))) + (t `(member ,tag tags-list))))) + (push (if minus `(not ,mm) mm) tagsmatcher) + (setq term rest))) + (push `(and ,@tagsmatcher) orlist) + (setq tagsmatcher nil)) + (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist))))) + + ;; Make the TODO matcher. + (when (org-string-nw-p todomatch) + (let ((orlist nil)) + (dolist (term (org-split-string todomatch "|")) + (while (string-match re term) + (let* ((minus (and (match-end 1) + (equal (match-string 1 term) "-"))) + (kwd (match-string 2 term)) + (regexp (eq (string-to-char kwd) ?{)) + (mm (if regexp `(string-match ,(substring kwd 1 -1) todo) + `(equal todo ,kwd)))) + (push (if minus `(not ,mm) mm) todomatcher)) + (setq term (substring term (match-end 0)))) + (push (if (> (length todomatcher) 1) + (cons 'and todomatcher) + (car todomatcher)) + orlist) + (setq todomatcher nil)) + (setq todomatcher (cons 'or orlist)))) + + ;; Return the string and function of the matcher. If no + ;; tags-specific or todo-specific matcher exists, match + ;; everything. + (let ((matcher (if (and tagsmatcher todomatcher) + `(and ,tagsmatcher ,todomatcher) + (or tagsmatcher todomatcher t)))) + (when org--matcher-tags-todo-only + (setq matcher `(and (member todo org-not-done-keywords) ,matcher))) + (cons match0 `(lambda (todo tags-list level) ,matcher))))) + +(defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded) + "Expand group tags in MATCH. + +This replaces every group tag in MATCH with a regexp tag search. +For example, a group tag \"Work\" defined as { Work : Lab Conf } +will be replaced like this: + + Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>} + +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>} + -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>} + +Replacing by a regexp preserves the structure of the match. +E.g., this expansion + + Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home + +will match anything tagged with \"Lab\" and \"Home\", or tagged +with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\". + +A group tag in MATCH can contain regular expressions of its own. +For example, a group tag \"Proj\" defined as { Proj : {P@.+} } +will be replaced like this: + + Proj => {\\<\\(?:Proj\\)\\>\\|P@.+} + +When the optional argument SINGLE-AS-LIST is non-nil, MATCH is +assumed to be a single group tag, and the function will return +the list of tags in this group. + +When DOWNCASE is non-nil, expand downcased TAGS." + (if org-group-tags + (let* ((case-fold-search t) + (stable org-mode-syntax-table) + (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist)) + (taggroups (if downcased + (mapcar (lambda (tg) (mapcar #'downcase tg)) + taggroups) + taggroups)) + (taggroups-keys (mapcar #'car taggroups)) + (return-match (if downcased (downcase match) match)) + (count 0) + (work-already-expanded tags-already-expanded) + regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped) + ;; @ and _ are allowed as word-components in tags. + (modify-syntax-entry ?@ "w" stable) + (modify-syntax-entry ?_ "w" stable) + ;; Temporarily replace regexp-expressions in the match-expression. + (while (string-match "{.+?}" return-match) + (cl-incf count) + (push (match-string 0 return-match) regexps-in-match) + (setq return-match (replace-match (format "<%d>" count) t nil return-match))) + (while (and taggroups-keys + (with-syntax-table stable + (string-match + (concat "\\(?1:[+-]?\\)\\(?2:\\<" + (regexp-opt taggroups-keys) "\\>\\)") + return-match))) + (let* ((dir (match-string 1 return-match)) + (tag (match-string 2 return-match)) + (tag (if downcased (downcase tag) tag))) + (unless (or (get-text-property 0 'grouptag (match-string 2 return-match)) + (member tag tags-already-expanded)) + (setq tags-in-group (assoc tag taggroups)) + (push tag work-already-expanded) + ;; Recursively expand each tag in the group, if the tag hasn't + ;; already been expanded. Restore the match-data after all recursive calls. + (save-match-data + (let (tags-expanded) + (dolist (x (cdr tags-in-group)) + (if (and (member x taggroups-keys) + (not (member x work-already-expanded))) + (setq tags-expanded + (delete-dups + (append + (org-tags-expand x t downcased + work-already-expanded) + tags-expanded))) + (setq tags-expanded + (append (list x) tags-expanded))) + (setq work-already-expanded + (delete-dups + (append tags-expanded + work-already-expanded)))) + (setq tags-in-group + (delete-dups (cons (car tags-in-group) + tags-expanded))))) + ;; Filter tag-regexps from tags. + (setq regexp-in-group-escaped + (delq nil (mapcar (lambda (x) + (if (stringp x) + (and (equal "{" (substring x 0 1)) + (equal "}" (substring x -1)) + x) + x)) + tags-in-group)) + regexp-in-group + (mapcar (lambda (x) + (substring x 1 -1)) + regexp-in-group-escaped) + tags-in-group + (delq nil (mapcar (lambda (x) + (if (stringp x) + (and (not (equal "{" (substring x 0 1))) + (not (equal "}" (substring x -1))) + x) + x)) + tags-in-group))) + ;; If single-as-list, do no more in the while-loop. + (if (not single-as-list) + (progn + (when regexp-in-group + (setq regexp-in-group + (concat "\\|" + (mapconcat 'identity regexp-in-group + "\\|")))) + (setq tags-in-group + (concat dir + "{\\<" + (regexp-opt tags-in-group) + "\\>" + regexp-in-group + "}")) + (when (stringp tags-in-group) + (org-add-props tags-in-group '(grouptag t))) + (setq return-match + (replace-match tags-in-group t t return-match))) + (setq tags-in-group + (append regexp-in-group-escaped tags-in-group)))) + (setq taggroups-keys (delete tag taggroups-keys)))) + ;; Add the regular expressions back into the match-expression again. + (while regexps-in-match + (setq return-match (replace-regexp-in-string (format "<%d>" count) + (pop regexps-in-match) + return-match t t)) + (cl-decf count)) + (if single-as-list + (if tags-in-group tags-in-group (list return-match)) + return-match)) + (if single-as-list + (list (if downcased (downcase match) match)) + match))) + +(defun org-op-to-function (op &optional stringp) + "Turn an operator into the appropriate function." + (setq op + (cond + ((equal op "<" ) '(< string< org-time<)) + ((equal op ">" ) '(> org-string> org-time>)) + ((member op '("<=" "=<")) '(<= org-string<= org-time<=)) + ((member op '(">=" "=>")) '(>= org-string>= org-time>=)) + ((member op '("=" "==")) '(= string= org-time=)) + ((member op '("<>" "!=")) '(org<> org-string<> org-time<>)))) + (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op)) + +(defun org<> (a b) (not (= a b))) +(defun org-string<= (a b) (or (string= a b) (string< a b))) +(defun org-string>= (a b) (not (string< a b))) +(defun org-string> (a b) (and (not (string= a b)) (not (string< a b)))) +(defun org-string<> (a b) (not (string= a b))) +(defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b))) +(defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b))) +(defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b))) +(defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b))) +(defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b))) +(defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b))) +(defun org-2ft (s) + "Convert S to a floating point time. +If S is already a number, just return it. If it is a string, parse +it as a time string and apply `float-time' to it. If S is nil, just return 0." + (cond + ((numberp s) s) + ((stringp s) + (condition-case nil + (float-time (apply #'encode-time (org-parse-time-string s))) + (error 0.))) + (t 0.))) + +(defun org-time-today () + "Time in seconds today at 0:00. +Returns the float number of seconds since the beginning of the +epoch to the beginning of today (00:00)." + (float-time (apply 'encode-time + (append '(0 0 0) (nthcdr 3 (decode-time)))))) + +(defun org-matcher-time (s) + "Interpret a time comparison value." + (save-match-data + (cond + ((string= s "<now>") (float-time)) + ((string= s "<today>") (org-time-today)) + ((string= s "<tomorrow>") (+ 86400.0 (org-time-today))) + ((string= s "<yesterday>") (- (org-time-today) 86400.0)) + ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s) + (+ (org-time-today) + (* (string-to-number (match-string 1 s)) + (cdr (assoc (match-string 2 s) + '(("d" . 86400.0) ("w" . 604800.0) + ("m" . 2678400.0) ("y" . 31557600.0))))))) + (t (org-2ft s))))) + +(defun org-match-any-p (re list) + "Does re match any element of list?" + (setq list (mapcar (lambda (x) (string-match re x)) list)) + (delq nil list)) + +(defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param +(defvar org-tags-overlay (make-overlay 1 1)) +(delete-overlay org-tags-overlay) + +(defun org-get-local-tags-at (&optional pos) + "Get a list of tags defined in the current headline." + (org-get-tags-at pos 'local)) + +(defun org-get-local-tags () + "Get a list of tags defined in the current headline." + (org-get-tags-at nil 'local)) + +(defun org-get-tags-at (&optional pos local) + "Get a list of all headline tags applicable at POS. +POS defaults to point. If tags are inherited, the list contains +the targets in the same sequence as the headlines appear, i.e. +the tags of the current headline come last. +When LOCAL is non-nil, only return tags from the current headline, +ignore inherited ones." + (interactive) + (if (and org-trust-scanner-tags + (or (not pos) (equal pos (point))) + (not local)) + org-scanner-tags + (let (tags ltags lastpos parent) + (save-excursion + (save-restriction + (widen) + (goto-char (or pos (point))) + (save-match-data + (catch 'done + (condition-case nil + (progn + (org-back-to-heading t) + (while (not (equal lastpos (point))) + (setq lastpos (point)) + (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$") + (setq ltags (org-split-string + (match-string-no-properties 1) ":")) + (when parent + (setq ltags (mapcar 'org-add-prop-inherited ltags))) + (setq tags (append + (if parent + (org-remove-uninherited-tags ltags) + ltags) + tags))) + (or org-use-tag-inheritance (throw 'done t)) + (when local (throw 'done t)) + (or (org-up-heading-safe) (error nil)) + (setq parent t))) + (error nil))))) + (if local + tags + (reverse (delete-dups + (reverse (append + (org-remove-uninherited-tags + org-file-tags) + tags))))))))) + +(defun org-add-prop-inherited (s) + (add-text-properties 0 (length s) '(inherited t) s) + s) + +(defun org-toggle-tag (tag &optional onoff) + "Toggle the tag TAG for the current line. +If ONOFF is `on' or `off', don't toggle but set to this state." + (save-excursion + (org-back-to-heading t) + (let ((current + (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$" + (line-end-position) t) + (let ((tags (match-string 1))) + ;; Clear current tags. + (replace-match "") + ;; Reverse the tags list so any new tag is appended to + ;; the current list of tags. + (nreverse (org-split-string tags ":"))))) + res) + (pcase onoff + (`off (setq current (delete tag current))) + ((or `on (guard (not (member tag current)))) + (setq res t) + (cl-pushnew tag current :test #'equal)) + (_ (setq current (delete tag current)))) + (end-of-line) + (if current + (progn + (insert " :" (mapconcat #'identity (nreverse current) ":") ":") + (org-set-tags nil t)) + (delete-horizontal-space)) + (run-hooks 'org-after-tags-change-hook) + res))) + +(defun org--align-tags-here (to-col) + "Align tags on the current headline to TO-COL. +Assume point is on a headline." + (let ((pos (point))) + (beginning-of-line) + (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")) + (>= pos (match-beginning 2))) + ;; No tags or point within tags: do not align. + (goto-char pos) + (goto-char (match-beginning 1)) + (let ((shift (max (- (if (>= to-col 0) to-col + (- (abs to-col) (string-width (match-string 2)))) + (current-column)) + 1))) + (replace-match (make-string shift ?\s) nil nil nil 1) + ;; Preserve initial position, if possible. In any case, stop + ;; before tags. + (when (< pos (point)) (goto-char pos)))))) + +(defun org-set-tags-command (&optional arg just-align) + "Call the set-tags command for the current entry." + (interactive "P") + (if (or (org-at-heading-p) (and arg (org-before-first-heading-p))) + (org-set-tags arg just-align) + (save-excursion + (unless (and (org-region-active-p) + org-loop-over-headlines-in-active-region) + (org-back-to-heading t)) + (org-set-tags arg just-align)))) + +(defun org-set-tags-to (data) + "Set the tags of the current entry to DATA, replacing current tags. +DATA may be a tags string like \":aa:bb:cc:\", or a list of tags. +If DATA is nil or the empty string, all tags are removed." + (interactive "sTags: ") + (let ((data + (pcase (if (stringp data) (org-trim data) data) + ((or `nil "") nil) + ((pred listp) (format ":%s:" (mapconcat #'identity data ":"))) + ((pred stringp) + (format ":%s:" + (mapconcat #'identity (org-split-string data ":+") ":"))) + (_ (error "Invalid tag specification: %S" data))))) + (org-with-wide-buffer + (org-back-to-heading t) + (let ((case-fold-search nil)) (looking-at org-complex-heading-regexp)) + (when (or (match-end 5) data) + (goto-char (or (match-beginning 5) (line-end-position))) + (skip-chars-backward " \t") + (delete-region (point) (line-end-position)) + (when data + (insert " " data) + (org-set-tags nil 'align)))))) + +(defun org-align-all-tags () + "Align the tags in all headings." + (interactive) + (save-excursion + (or (ignore-errors (org-back-to-heading t)) + (outline-next-heading)) + (if (org-at-heading-p) + (org-set-tags t) + (message "No headings")))) + +(defvar org-indent-indentation-per-level) +(defun org-set-tags (&optional arg just-align) + "Set the tags for the current headline. +With prefix ARG, realign all tags in headings in the current buffer. +When JUST-ALIGN is non-nil, only align tags." + (interactive "P") + (if (and (org-region-active-p) org-loop-over-headlines-in-active-region) + (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level) + 'region-start-level + 'region)) + org-loop-over-headlines-in-active-region) + (org-map-entries + ;; We don't use ARG and JUST-ALIGN here because these args + ;; are not useful when looping over headlines. + #'org-set-tags + org-loop-over-headlines-in-active-region + cl + '(when (org-invisible-p) (org-end-of-subtree nil t)))) + (let ((org-setting-tags t)) + (if arg + (save-excursion + (goto-char (point-min)) + (while (re-search-forward org-outline-regexp-bol nil t) + (org-set-tags nil t) + (end-of-line)) + (message "All tags realigned to column %d" org-tags-column)) + (let* ((current (org-get-tags-string)) + (tags + (if just-align current + ;; Get a new set of tags from the user. + (save-excursion + (let* ((table + (setq + org-last-tags-completion-table + (org--tag-add-to-alist + (and + org-complete-tags-always-offer-all-agenda-tags + (org-global-tags-completion-table + (org-agenda-files))) + (or org-current-tag-alist + (org-get-buffer-tags))))) + (current-tags (org-split-string current ":")) + (inherited-tags + (nreverse (nthcdr (length current-tags) + (nreverse (org-get-tags-at)))))) + (replace-regexp-in-string + "\\([-+&]+\\|,\\)" + ":" + (if (or (eq t org-use-fast-tag-selection) + (and org-use-fast-tag-selection + (delq nil (mapcar #'cdr table)))) + (org-fast-tag-selection + current-tags inherited-tags table + (and org-fast-tag-selection-include-todo + org-todo-key-alist)) + (let ((org-add-colon-after-tag-completion + (< 1 (length table)))) + (org-trim + (completing-read + "Tags: " + #'org-tags-completion-function + nil nil current 'org-tags-history)))))))))) + + (when org-tags-sort-function + (setq tags + (mapconcat + #'identity + (sort (org-split-string tags "[^[:alnum:]_@#%]+") + org-tags-sort-function) + ":"))) + + (if (or (string= ":" tags) + (string= "::" tags)) + (setq tags "")) + (if (not (org-string-nw-p tags)) (setq tags "") + (unless (string-suffix-p ":" tags) (setq tags (concat tags ":"))) + (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags)))) + + ;; Insert new tags at the correct column. + (unless (equal current tags) + (save-excursion + (beginning-of-line) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp)) + ;; Remove current tags, if any. + (when (match-end 5) (replace-match "" nil nil nil 5)) + ;; Insert new tags, if any. Otherwise, remove trailing + ;; white spaces. + (end-of-line) + (if (not (equal tags "")) + ;; When text is being inserted on an invisible + ;; region boundary, it can be inadvertently sucked + ;; into invisibility. + (outline-flag-region (point) (progn (insert " " tags) (point)) nil) + (skip-chars-backward " \t") + (delete-region (point) (line-end-position))))) + ;; Align tags, if any. Fix tags column if `org-indent-mode' + ;; is on. + (unless (equal tags "") + (let* ((level (save-excursion + (beginning-of-line) + (skip-chars-forward "\\*"))) + (offset (if (bound-and-true-p org-indent-mode) + (* (1- org-indent-indentation-per-level) + (1- level)) + 0)) + (tags-column + (+ org-tags-column + (if (> org-tags-column 0) (- offset) offset)))) + (org--align-tags-here tags-column)))) + (unless just-align (run-hooks 'org-after-tags-change-hook)))))) + +(defun org-change-tag-in-region (beg end tag off) + "Add or remove TAG for each entry in the region. +This works in the agenda, and also in an Org buffer." + (interactive + (list (region-beginning) (region-end) + (let ((org-last-tags-completion-table + (if (derived-mode-p 'org-mode) + (org--tag-add-to-alist + (org-get-buffer-tags) + (org-global-tags-completion-table)) + (org-global-tags-completion-table)))) + (completing-read + "Tag: " 'org-tags-completion-function nil nil nil + 'org-tags-history)) + (progn + (message "[s]et or [r]emove? ") + (equal (read-char-exclusive) ?r)))) + (when (fboundp 'deactivate-mark) (deactivate-mark)) + (let ((agendap (equal major-mode 'org-agenda-mode)) + l1 l2 m buf pos newhead (cnt 0)) + (goto-char end) + (setq l2 (1- (org-current-line))) + (goto-char beg) + (setq l1 (org-current-line)) + (cl-loop for l from l1 to l2 do + (org-goto-line l) + (setq m (get-text-property (point) 'org-hd-marker)) + (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p)) + (and agendap m)) + (setq buf (if agendap (marker-buffer m) (current-buffer)) + pos (if agendap m (point))) + (with-current-buffer buf + (save-excursion + (save-restriction + (goto-char pos) + (setq cnt (1+ cnt)) + (org-toggle-tag tag (if off 'off 'on)) + (setq newhead (org-get-heading))))) + (and agendap (org-agenda-change-all-lines newhead m)))) + (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt))) + +(defun org-tags-completion-function (string _predicate &optional flag) + (let (s1 s2 rtn (ctable org-last-tags-completion-table) + (confirm (lambda (x) (stringp (car x))))) + (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string) + (setq s1 (match-string 1 string) + s2 (match-string 2 string)) + (setq s1 "" s2 string)) + (cond + ((eq flag nil) + ;; try completion + (setq rtn (try-completion s2 ctable confirm)) + (when (stringp rtn) + (setq rtn + (concat s1 s2 (substring rtn (length s2)) + (if (and org-add-colon-after-tag-completion + (assoc rtn ctable)) + ":" "")))) + rtn) + ((eq flag t) + ;; all-completions + (all-completions s2 ctable confirm)) + ((eq flag 'lambda) + ;; exact match? + (assoc s2 ctable))))) + +(defun org-fast-tag-insert (kwd tags face &optional end) + "Insert KDW, and the TAGS, the latter with face FACE. +Also insert END." + (insert (format "%-12s" (concat kwd ":")) + (org-add-props (mapconcat 'identity tags " ") nil 'face face) + (or end ""))) + +(defun org-fast-tag-show-exit (flag) + (save-excursion + (org-goto-line 3) + (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t) + (replace-match "")) + (when flag + (end-of-line 1) + (org-move-to-column (- (window-width) 19) t) + (insert (org-add-props " Next change exits" nil 'face 'org-warning))))) + +(defun org-set-current-tags-overlay (current prefix) + "Add an overlay to CURRENT tag with PREFIX." + (let ((s (concat ":" (mapconcat 'identity current ":") ":"))) + (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s) + (org-overlay-display org-tags-overlay (concat prefix s)))) + +(defvar org-last-tag-selection-key nil) +(defun org-fast-tag-selection (current inherited table &optional todo-table) + "Fast tag selection with single keys. +CURRENT is the current list of tags in the headline, INHERITED is the +list of inherited tags, and TABLE is an alist of tags and corresponding keys, +possibly with grouping information. TODO-TABLE is a similar table with +TODO keywords, should these have keys assigned to them. +If the keys are nil, a-z are automatically assigned. +Returns the new tags string, or nil to not change the current settings." + (let* ((fulltable (append table todo-table)) + (maxlen (if (null fulltable) 0 + (apply #'max + (mapcar (lambda (x) + (if (stringp (car x)) (string-width (car x)) + 0)) + fulltable)))) + (buf (current-buffer)) + (expert (eq org-fast-tag-selection-single-key 'expert)) + (buffer-tags nil) + (fwidth (+ maxlen 3 1 3)) + (ncol (/ (- (window-width) 4) fwidth)) + (i-face 'org-done) + (c-face 'org-todo) + tg cnt e c char c1 c2 ntable tbl rtn + ov-start ov-end ov-prefix + (exit-after-next org-fast-tag-selection-single-key) + (done-keywords org-done-keywords) + groups ingroup intaggroup) + (save-excursion + (beginning-of-line 1) + (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") + (setq ov-start (match-beginning 1) + ov-end (match-end 1) + ov-prefix "") + (setq ov-start (1- (point-at-eol)) + ov-end (1+ ov-start)) + (skip-chars-forward "^\n\r") + (setq ov-prefix + (concat + (buffer-substring (1- (point)) (point)) + (if (> (current-column) org-tags-column) + " " + (make-string (- org-tags-column (current-column)) ?\ )))))) + (move-overlay org-tags-overlay ov-start ov-end) + (save-window-excursion + (if expert + (set-buffer (get-buffer-create " *Org tags*")) + (delete-other-windows) + (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*")) + (org-switch-to-buffer-other-window " *Org tags*")) + (erase-buffer) + (setq-local org-done-keywords done-keywords) + (org-fast-tag-insert "Inherited" inherited i-face "\n") + (org-fast-tag-insert "Current" current c-face "\n\n") + (org-fast-tag-show-exit exit-after-next) + (org-set-current-tags-overlay current ov-prefix) + (setq tbl fulltable char ?a cnt 0) + (while (setq e (pop tbl)) + (cond + ((eq (car e) :startgroup) + (push '() groups) (setq ingroup t) + (unless (zerop cnt) + (setq cnt 0) + (insert "\n")) + (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ ")) + ((eq (car e) :endgroup) + (setq ingroup nil cnt 0) + (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n")) + ((eq (car e) :startgrouptag) + (setq intaggroup t) + (unless (zerop cnt) + (setq cnt 0) + (insert "\n")) + (insert "[ ")) + ((eq (car e) :endgrouptag) + (setq intaggroup nil cnt 0) + (insert "]\n")) + ((equal e '(:newline)) + (unless (zerop cnt) + (setq cnt 0) + (insert "\n") + (setq e (car tbl)) + (while (equal (car tbl) '(:newline)) + (insert "\n") + (setq tbl (cdr tbl))))) + ((equal e '(:grouptags)) (insert " : ")) + (t + (setq tg (copy-sequence (car e)) c2 nil) + (if (cdr e) + (setq c (cdr e)) + ;; automatically assign a character. + (setq c1 (string-to-char + (downcase (substring + tg (if (= (string-to-char tg) ?@) 1 0))))) + (if (or (rassoc c1 ntable) (rassoc c1 table)) + (while (or (rassoc char ntable) (rassoc char table)) + (setq char (1+ char))) + (setq c2 c1)) + (setq c (or c2 char))) + (when ingroup (push tg (car groups))) + (setq tg (org-add-props tg nil 'face + (cond + ((not (assoc tg table)) + (org-get-todo-face tg)) + ((member tg current) c-face) + ((member tg inherited) i-face)))) + (when (equal (caar tbl) :grouptags) + (org-add-props tg nil 'face 'org-tag-group)) + (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " ")) + (insert "[" c "] " tg (make-string + (- fwidth 4 (length tg)) ?\ )) + (push (cons tg c) ntable) + (when (= (cl-incf cnt) ncol) + (insert "\n") + (when (or ingroup intaggroup) (insert " ")) + (setq cnt 0))))) + (setq ntable (nreverse ntable)) + (insert "\n") + (goto-char (point-min)) + (unless expert (org-fit-window-to-buffer)) + (setq rtn + (catch 'exit + (while t + (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s" + (if (not groups) "no " "") + (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi"))) + (setq c (let ((inhibit-quit t)) (read-char-exclusive))) + (setq org-last-tag-selection-key c) + (cond + ((= c ?\r) (throw 'exit t)) + ((= c ?!) + (setq groups (not groups)) + (goto-char (point-min)) + (while (re-search-forward "[{}]" nil t) (replace-match " "))) + ((= c ?\C-c) + (if (not expert) + (org-fast-tag-show-exit + (setq exit-after-next (not exit-after-next))) + (setq expert nil) + (delete-other-windows) + (set-window-buffer (split-window-vertically) " *Org tags*") + (org-switch-to-buffer-other-window " *Org tags*") + (org-fit-window-to-buffer))) + ((or (= c ?\C-g) + (and (= c ?q) (not (rassoc c ntable)))) + (delete-overlay org-tags-overlay) + (setq quit-flag t)) + ((= c ?\ ) + (setq current nil) + (when exit-after-next (setq exit-after-next 'now))) + ((= c ?\t) + (condition-case nil + (setq tg (completing-read + "Tag: " + (or buffer-tags + (with-current-buffer buf + (setq buffer-tags + (org-get-buffer-tags)))))) + (quit (setq tg ""))) + (when (string-match "\\S-" tg) + (cl-pushnew (list tg) buffer-tags :test #'equal) + (if (member tg current) + (setq current (delete tg current)) + (push tg current))) + (when exit-after-next (setq exit-after-next 'now))) + ((setq e (rassoc c todo-table) tg (car e)) + (with-current-buffer buf + (save-excursion (org-todo tg))) + (when exit-after-next (setq exit-after-next 'now))) + ((setq e (rassoc c ntable) tg (car e)) + (if (member tg current) + (setq current (delete tg current)) + (cl-loop for g in groups do + (when (member tg g) + (dolist (x g) (setq current (delete x current))))) + (push tg current)) + (when exit-after-next (setq exit-after-next 'now)))) + + ;; Create a sorted list + (setq current + (sort current + (lambda (a b) + (assoc b (cdr (memq (assoc a ntable) ntable)))))) + (when (eq exit-after-next 'now) (throw 'exit t)) + (goto-char (point-min)) + (beginning-of-line 2) + (delete-region (point) (point-at-eol)) + (org-fast-tag-insert "Current" current c-face) + (org-set-current-tags-overlay current ov-prefix) + (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t) + (setq tg (match-string 1)) + (add-text-properties + (match-beginning 1) (match-end 1) + (list 'face + (cond + ((member tg current) c-face) + ((member tg inherited) i-face) + (t (get-text-property (match-beginning 1) 'face)))))) + (goto-char (point-min))))) + (delete-overlay org-tags-overlay) + (if rtn + (mapconcat 'identity current ":") + nil)))) + +(defun org-get-tags-string () + "Get the TAGS string in the current headline." + (unless (org-at-heading-p t) + (user-error "Not on a heading")) + (save-excursion + (beginning-of-line 1) + (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") + (match-string-no-properties 1) + ""))) + +(defun org-get-tags () + "Get the list of tags specified in the current headline." + (org-split-string (org-get-tags-string) ":")) + +(defun org-get-buffer-tags () + "Get a table of all tags used in the buffer, for completion." + (org-with-wide-buffer + (goto-char (point-min)) + (let ((tag-re (concat org-outline-regexp-bol + "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")) + tags) + (while (re-search-forward tag-re nil t) + (dolist (tag (org-split-string (match-string-no-properties 1) ":")) + (push tag tags))) + (mapcar #'list (append org-file-tags (org-uniquify tags)))))) + +;;;; The mapping API + +(defvar org-agenda-skip-comment-trees) +(defvar org-agenda-skip-function) +(defun org-map-entries (func &optional match scope &rest skip) + "Call FUNC at each headline selected by MATCH in SCOPE. + +FUNC is a function or a lisp form. The function will be called without +arguments, with the cursor positioned at the beginning of the headline. +The return values of all calls to the function will be collected and +returned as a list. + +The call to FUNC will be wrapped into a save-excursion form, so FUNC +does not need to preserve point. After evaluation, the cursor will be +moved to the end of the line (presumably of the headline of the +processed entry) and search continues from there. Under some +circumstances, this may not produce the wanted results. For example, +if you have removed (e.g. archived) the current (sub)tree it could +mean that the next entry will be skipped entirely. In such cases, you +can specify the position from where search should continue by making +FUNC set the variable `org-map-continue-from' to the desired buffer +position. + +MATCH is a tags/property/todo match as it is used in the agenda tags view. +Only headlines that are matched by this query will be considered during +the iteration. When MATCH is nil or t, all headlines will be +visited by the iteration. + +SCOPE determines the scope of this command. It can be any of: + +nil The current buffer, respecting the restriction if any +tree The subtree started with the entry at point +region The entries within the active region, if any +region-start-level + The entries within the active region, but only those at + the same level than the first one. +file The current buffer, without restriction +file-with-archives + The current buffer, and any archives associated with it +agenda All agenda files +agenda-with-archives + All agenda files with any archive files associated with them +\(file1 file2 ...) + If this is a list, all files in the list will be scanned + +The remaining args are treated as settings for the skipping facilities of +the scanner. The following items can be given here: + + archive skip trees with the archive tag + comment skip trees with the COMMENT keyword + function or Emacs Lisp form: + will be used as value for `org-agenda-skip-function', so + whenever the function returns a position, FUNC will not be + called for that entry and search will continue from the + position returned + +If your function needs to retrieve the tags including inherited tags +at the *current* entry, you can use the value of the variable +`org-scanner-tags' which will be much faster than getting the value +with `org-get-tags-at'. If your function gets properties with +`org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags' +to t around the call to `org-entry-properties' to get the same speedup. +Note that if your function moves around to retrieve tags and properties at +a *different* entry, you cannot use these techniques." + (unless (and (or (eq scope 'region) (eq scope 'region-start-level)) + (not (org-region-active-p))) + (let* ((org-agenda-archives-mode nil) ; just to make sure + (org-agenda-skip-archived-trees (memq 'archive skip)) + (org-agenda-skip-comment-trees (memq 'comment skip)) + (org-agenda-skip-function + (car (org-delete-all '(comment archive) skip))) + (org-tags-match-list-sublevels t) + (start-level (eq scope 'region-start-level)) + matcher res + org-todo-keywords-for-agenda + org-done-keywords-for-agenda + org-todo-keyword-alist-for-agenda + org-tag-alist-for-agenda + org--matcher-tags-todo-only) + + (cond + ((eq match t) (setq matcher t)) + ((eq match nil) (setq matcher t)) + (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t)))) + + (save-excursion + (save-restriction + (cond ((eq scope 'tree) + (org-back-to-heading t) + (org-narrow-to-subtree) + (setq scope nil)) + ((and (or (eq scope 'region) (eq scope 'region-start-level)) + (org-region-active-p)) + ;; If needed, set start-level to a string like "2" + (when start-level + (save-excursion + (goto-char (region-beginning)) + (unless (org-at-heading-p) (outline-next-heading)) + (setq start-level (org-current-level)))) + (narrow-to-region (region-beginning) + (save-excursion + (goto-char (region-end)) + (unless (and (bolp) (org-at-heading-p)) + (outline-next-heading)) + (point))) + (setq scope nil))) + + (if (not scope) + (progn + (org-agenda-prepare-buffers + (and buffer-file-name (list buffer-file-name))) + (setq res + (org-scan-tags + func matcher org--matcher-tags-todo-only start-level))) + ;; Get the right scope + (cond + ((and scope (listp scope) (symbolp (car scope))) + (setq scope (eval scope))) + ((eq scope 'agenda) + (setq scope (org-agenda-files t))) + ((eq scope 'agenda-with-archives) + (setq scope (org-agenda-files t)) + (setq scope (org-add-archive-files scope))) + ((eq scope 'file) + (setq scope (and buffer-file-name (list buffer-file-name)))) + ((eq scope 'file-with-archives) + (setq scope (org-add-archive-files (list (buffer-file-name)))))) + (org-agenda-prepare-buffers scope) + (dolist (file scope) + (with-current-buffer (org-find-base-buffer-visiting file) + (org-with-wide-buffer + (goto-char (point-min)) + (setq res + (append + res + (org-scan-tags + func matcher org--matcher-tags-todo-only))))))))) + res))) + +;;; Properties API + +(defconst org-special-properties + '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE" + "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO") + "The special properties valid in Org mode. +These are properties that are not defined in the property drawer, +but in some other way.") + +(defconst org-default-properties + '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID" + "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY" + "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE" + "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME" + "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED" + "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE" + "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS") + "Some properties that are used by Org mode for various purposes. +Being in this list makes sure that they are offered for completion.") + +(defun org--valid-property-p (property) + "Non nil when string PROPERTY is a valid property name." + (not + (or (equal property "") + (string-match-p "\\s-" property)))) + +(defun org--update-property-plist (key val props) + "Associate KEY to VAL in alist PROPS. +Modifications are made by side-effect. Return new alist." + (let* ((appending (string= (substring key -1) "+")) + (key (if appending (substring key 0 -1) key)) + (old (assoc-string key props t))) + (if (not old) (cons (cons key val) props) + (setcdr old (if appending (concat (cdr old) " " val) val)) + props))) + +(defun org-get-property-block (&optional beg force) + "Return the (beg . end) range of the body of the property drawer. +BEG is the beginning of the current subtree, or of the part +before the first headline. If it is not given, it will be found. +If the drawer does not exist, create it if FORCE is non-nil, or +return nil." + (org-with-wide-buffer + (when beg (goto-char beg)) + (unless (org-before-first-heading-p) + (let ((beg (cond (beg) + ((or (not (featurep 'org-inlinetask)) + (org-inlinetask-in-task-p)) + (org-back-to-heading t)) + (t (org-with-limited-levels (org-back-to-heading t)))))) + (forward-line) + (when (looking-at-p org-planning-line-re) (forward-line)) + (cond ((looking-at org-property-drawer-re) + (forward-line) + (cons (point) (progn (goto-char (match-end 0)) + (line-beginning-position)))) + (force + (goto-char beg) + (org-insert-property-drawer) + (let ((pos (save-excursion (search-forward ":END:") + (line-beginning-position)))) + (cons pos pos)))))))) + +(defun org-at-property-p () + "Non-nil when point is inside a property drawer. +See `org-property-re' for match data, if applicable." + (save-excursion + (beginning-of-line) + (and (looking-at org-property-re) + (let ((property-drawer (save-match-data (org-get-property-block)))) + (and property-drawer + (>= (point) (car property-drawer)) + (< (point) (cdr property-drawer))))))) + +(defun org-property-action () + "Do an action on properties." + (interactive) + (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute") + (let ((c (read-char-exclusive))) + (cl-case c + (?s (call-interactively #'org-set-property)) + (?d (call-interactively #'org-delete-property)) + (?D (call-interactively #'org-delete-property-globally)) + (?c (call-interactively #'org-compute-property-at-point)) + (otherwise (user-error "No such property action %c" c))))) + +(defun org-inc-effort () + "Increment the value of the effort property in the current entry." + (interactive) + (org-set-effort nil t)) + +(defvar org-clock-effort) ; Defined in org-clock.el. +(defvar org-clock-current-task) ; Defined in org-clock.el. +(defun org-set-effort (&optional value increment) + "Set the effort property of the current entry. +With numerical prefix arg, use the nth allowed value, 0 stands for the +10th allowed value. + +When INCREMENT is non-nil, set the property to the next allowed value." + (interactive "P") + (when (equal value 0) (setq value 10)) + (let* ((completion-ignore-case t) + (prop org-effort-property) + (cur (org-entry-get nil prop)) + (allowed (org-property-get-allowed-values nil prop 'table)) + (existing (mapcar 'list (org-property-values prop))) + (heading (nth 4 (org-heading-components))) + rpl + (val (cond + ((stringp value) value) + ((and allowed (integerp value)) + (or (car (nth (1- value) allowed)) + (car (org-last allowed)))) + ((and allowed increment) + (or (cl-caadr (member (list cur) allowed)) + (user-error "Allowed effort values are not set"))) + (allowed + (message "Select 1-9,0, [RET%s]: %s" + (if cur (concat "=" cur) "") + (mapconcat 'car allowed " ")) + (setq rpl (read-char-exclusive)) + (if (equal rpl ?\r) + cur + (setq rpl (- rpl ?0)) + (when (equal rpl 0) (setq rpl 10)) + (if (and (> rpl 0) (<= rpl (length allowed))) + (car (nth (1- rpl) allowed)) + (org-completing-read "Effort: " allowed nil)))) + (t + (org-completing-read + (concat "Effort" (and cur (string-match "\\S-" cur) + (concat " [" cur "]")) + ": ") + existing nil nil "" nil cur))))) + (unless (equal (org-entry-get nil prop) val) + (org-entry-put nil prop val)) + (org-refresh-property + '((effort . identity) + (effort-minutes . org-duration-to-minutes)) + val) + (when (equal heading (bound-and-true-p org-clock-current-task)) + (setq org-clock-effort (get-text-property (point-at-bol) 'effort)) + (org-clock-update-mode-line)) + (message "%s is now %s" prop val))) + +(defun org-entry-properties (&optional pom which) + "Get all properties of the current entry. + +When POM is a buffer position, get all properties from the entry +there instead. + +This includes the TODO keyword, the tags, time strings for +deadline, scheduled, and clocking, and any additional properties +defined in the entry. + +If WHICH is nil or `all', get all properties. If WHICH is +`special' or `standard', only get that subclass. If WHICH is +a string, only get that property. + +Return value is an alist. Keys are properties, as upcased +strings." + (org-with-point-at pom + (when (and (derived-mode-p 'org-mode) + (ignore-errors (org-back-to-heading t))) + (catch 'exit + (let* ((beg (point)) + (specific (and (stringp which) (upcase which))) + (which (cond ((not specific) which) + ((member specific org-special-properties) 'special) + (t 'standard))) + props) + ;; Get the special properties, like TODO and TAGS. + (when (memq which '(nil all special)) + (when (or (not specific) (string= specific "CLOCKSUM")) + (let ((clocksum (get-text-property (point) :org-clock-minutes))) + (when clocksum + (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum)) + props))) + (when specific (throw 'exit props))) + (when (or (not specific) (string= specific "CLOCKSUM_T")) + (let ((clocksumt (get-text-property (point) + :org-clock-minutes-today))) + (when clocksumt + (push (cons "CLOCKSUM_T" + (org-duration-from-minutes clocksumt)) + props))) + (when specific (throw 'exit props))) + (when (or (not specific) (string= specific "ITEM")) + (let ((case-fold-search nil)) + (when (looking-at org-complex-heading-regexp) + (push (cons "ITEM" + (let ((title (match-string-no-properties 4))) + (if (org-string-nw-p title) + (org-remove-tabs title) + ""))) + props))) + (when specific (throw 'exit props))) + (when (or (not specific) (string= specific "TODO")) + (let ((case-fold-search nil)) + (when (and (looking-at org-todo-line-regexp) (match-end 2)) + (push (cons "TODO" (match-string-no-properties 2)) props))) + (when specific (throw 'exit props))) + (when (or (not specific) (string= specific "PRIORITY")) + (push (cons "PRIORITY" + (if (looking-at org-priority-regexp) + (match-string-no-properties 2) + (char-to-string org-default-priority))) + props) + (when specific (throw 'exit props))) + (when (or (not specific) (string= specific "FILE")) + (push (cons "FILE" (buffer-file-name (buffer-base-buffer))) + props) + (when specific (throw 'exit props))) + (when (or (not specific) (string= specific "TAGS")) + (let ((value (org-string-nw-p (org-get-tags-string)))) + (when value (push (cons "TAGS" value) props))) + (when specific (throw 'exit props))) + (when (or (not specific) (string= specific "ALLTAGS")) + (let ((value (org-get-tags-at))) + (when value + (push (cons "ALLTAGS" + (format ":%s:" (mapconcat #'identity value ":"))) + props))) + (when specific (throw 'exit props))) + (when (or (not specific) (string= specific "BLOCKED")) + (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props) + (when specific (throw 'exit props))) + (when (or (not specific) + (member specific '("CLOSED" "DEADLINE" "SCHEDULED"))) + (forward-line) + (when (looking-at-p org-planning-line-re) + (end-of-line) + (let ((bol (line-beginning-position)) + ;; Backward compatibility: time keywords used to + ;; be configurable (before 8.3). Make sure we + ;; get the correct keyword. + (key-assoc `(("CLOSED" . ,org-closed-string) + ("DEADLINE" . ,org-deadline-string) + ("SCHEDULED" . ,org-scheduled-string)))) + (dolist (pair (if specific (list (assoc specific key-assoc)) + key-assoc)) + (save-excursion + (when (search-backward (cdr pair) bol t) + (goto-char (match-end 0)) + (skip-chars-forward " \t") + (and (looking-at org-ts-regexp-both) + (push (cons (car pair) + (match-string-no-properties 0)) + props))))))) + (when specific (throw 'exit props))) + (when (or (not specific) + (member specific '("TIMESTAMP" "TIMESTAMP_IA"))) + (let ((find-ts + (lambda (end ts) + ;; Fix next time-stamp before END. TS is the + ;; list of time-stamps found so far. + (let ((ts ts) + (regexp (cond + ((string= specific "TIMESTAMP") + org-ts-regexp) + ((string= specific "TIMESTAMP_IA") + org-ts-regexp-inactive) + ((assoc "TIMESTAMP_IA" ts) + org-ts-regexp) + ((assoc "TIMESTAMP" ts) + org-ts-regexp-inactive) + (t org-ts-regexp-both)))) + (catch 'next + (while (re-search-forward regexp end t) + (backward-char) + (let ((object (org-element-context))) + ;; Accept to match timestamps in node + ;; properties, too. + (when (memq (org-element-type object) + '(node-property timestamp)) + (let ((type + (org-element-property :type object))) + (cond + ((and (memq type '(active active-range)) + (not (equal specific "TIMESTAMP_IA"))) + (unless (assoc "TIMESTAMP" ts) + (push (cons "TIMESTAMP" + (org-element-property + :raw-value object)) + ts) + (when specific (throw 'exit ts)))) + ((and (memq type '(inactive inactive-range)) + (not (string= specific "TIMESTAMP"))) + (unless (assoc "TIMESTAMP_IA" ts) + (push (cons "TIMESTAMP_IA" + (org-element-property + :raw-value object)) + ts) + (when specific (throw 'exit ts)))))) + ;; Both timestamp types are found, + ;; move to next part. + (when (= (length ts) 2) (throw 'next ts))))) + ts))))) + (goto-char beg) + ;; First look for timestamps within headline. + (let ((ts (funcall find-ts (line-end-position) nil))) + (if (= (length ts) 2) (setq props (nconc ts props)) + ;; Then find timestamps in the section, skipping + ;; planning line. + (let ((end (save-excursion (outline-next-heading)))) + (forward-line) + (when (looking-at-p org-planning-line-re) (forward-line)) + (setq props (nconc (funcall find-ts end ts) props)))))))) + ;; Get the standard properties, like :PROP:. + (when (memq which '(nil all standard)) + ;; If we are looking after a specific property, delegate + ;; to `org-entry-get', which is faster. However, make an + ;; exception for "CATEGORY", since it can be also set + ;; through keywords (i.e. #+CATEGORY). + (if (and specific (not (equal specific "CATEGORY"))) + (let ((value (org-entry-get beg specific nil t))) + (throw 'exit (and value (list (cons specific value))))) + (let ((range (org-get-property-block beg))) + (when range + (let ((end (cdr range)) seen-base) + (goto-char (car range)) + ;; Unlike to `org--update-property-plist', we + ;; handle the case where base values is found + ;; after its extension. We also forbid standard + ;; properties to be named as special properties. + (while (re-search-forward org-property-re end t) + (let* ((key (upcase (match-string-no-properties 2))) + (extendp (string-match-p "\\+\\'" key)) + (key-base (if extendp (substring key 0 -1) key)) + (value (match-string-no-properties 3))) + (cond + ((member-ignore-case key-base org-special-properties)) + (extendp + (setq props + (org--update-property-plist key value props))) + ((member key seen-base)) + (t (push key seen-base) + (let ((p (assoc-string key props t))) + (if p (setcdr p (concat value " " (cdr p))) + (push (cons key value) props)))))))))))) + (unless (assoc "CATEGORY" props) + (push (cons "CATEGORY" (org-get-category beg)) props) + (when (string= specific "CATEGORY") (throw 'exit props))) + ;; Return value. + props))))) + +(defun org--property-local-values (property literal-nil) + "Return value for PROPERTY in current entry. +Value is a list whose car is the base value for PROPERTY and cdr +a list of accumulated values. Return nil if neither is found in +the entry. Also return nil when PROPERTY is set to \"nil\", +unless LITERAL-NIL is non-nil." + (let ((range (org-get-property-block))) + (when range + (goto-char (car range)) + (let* ((case-fold-search t) + (end (cdr range)) + (value + ;; Base value. + (save-excursion + (let ((v (and (re-search-forward + (org-re-property property nil t) end t) + (match-string-no-properties 3)))) + (list (if literal-nil v (org-not-nil v))))))) + ;; Find additional values. + (let* ((property+ (org-re-property (concat property "+") nil t))) + (while (re-search-forward property+ end t) + (push (match-string-no-properties 3) value))) + ;; Return final values. + (and (not (equal value '(nil))) (nreverse value)))))) + +(defun org--property-global-value (property literal-nil) + "Return value for PROPERTY in current buffer. +Return value is a string. Return nil if property is not set +globally. Also return nil when PROPERTY is set to \"nil\", +unless LITERAL-NIL is non-nil." + (let ((global + (cdr (or (assoc-string property org-file-properties t) + (assoc-string property org-global-properties t) + (assoc-string property org-global-properties-fixed t))))) + (if literal-nil global (org-not-nil global)))) + +(defun org-entry-get (pom property &optional inherit literal-nil) + "Get value of PROPERTY for entry or content at point-or-marker POM. + +If INHERIT is non-nil and the entry does not have the property, +then also check higher levels of the hierarchy. If INHERIT is +the symbol `selective', use inheritance only if the setting in +`org-use-property-inheritance' selects PROPERTY for inheritance. + +If the property is present but empty, the return value is the +empty string. If the property is not present at all, nil is +returned. In any other case, return the value as a string. +Search is case-insensitive. + +If LITERAL-NIL is set, return the string value \"nil\" as +a string, do not interpret it as the list atom nil. This is used +for inheritance when a \"nil\" value can supersede a non-nil +value higher up the hierarchy." + (org-with-point-at pom + (cond + ((member-ignore-case property (cons "CATEGORY" org-special-properties)) + ;; We need a special property. Use `org-entry-properties' to + ;; retrieve it, but specify the wanted property. + (cdr (assoc-string property (org-entry-properties nil property)))) + ((and inherit + (or (not (eq inherit 'selective)) (org-property-inherit-p property))) + (org-entry-get-with-inheritance property literal-nil)) + (t + (let* ((local (org--property-local-values property literal-nil)) + (value (and local (mapconcat #'identity (delq nil local) " ")))) + (if literal-nil value (org-not-nil value))))))) + +(defun org-property-or-variable-value (var &optional inherit) + "Check if there is a property fixing the value of VAR. +If yes, return this value. If not, return the current value of the variable." + (let ((prop (org-entry-get nil (symbol-name var) inherit))) + (if (and prop (stringp prop) (string-match "\\S-" prop)) + (read prop) + (symbol-value var)))) + +(defun org-entry-delete (pom property) + "Delete PROPERTY from entry at point-or-marker POM. +Accumulated properties, i.e. PROPERTY+, are also removed. Return +non-nil when a property was removed." + (org-with-point-at pom + (pcase (org-get-property-block) + (`(,begin . ,origin) + (let* ((end (copy-marker origin)) + (re (org-re-property + (concat (regexp-quote property) "\\+?") t t))) + (goto-char begin) + (while (re-search-forward re end t) + (delete-region (match-beginning 0) (line-beginning-position 2))) + ;; If drawer is empty, remove it altogether. + (when (= begin end) + (delete-region (line-beginning-position 0) + (line-beginning-position 2))) + ;; Return non-nil if some property was removed. + (prog1 (/= end origin) (set-marker end nil)))) + (_ nil)))) + +;; Multi-values properties are properties that contain multiple values +;; These values are assumed to be single words, separated by whitespace. +(defun org-entry-add-to-multivalued-property (pom property value) + "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM." + (let* ((old (org-entry-get pom property)) + (values (and old (split-string old)))) + (setq value (org-entry-protect-space value)) + (unless (member value values) + (setq values (append values (list value))) + (org-entry-put pom property (mapconcat #'identity values " "))))) + +(defun org-entry-remove-from-multivalued-property (pom property value) + "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM." + (let* ((old (org-entry-get pom property)) + (values (and old (split-string old)))) + (setq value (org-entry-protect-space value)) + (when (member value values) + (setq values (delete value values)) + (org-entry-put pom property (mapconcat #'identity values " "))))) + +(defun org-entry-member-in-multivalued-property (pom property value) + "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?" + (let* ((old (org-entry-get pom property)) + (values (and old (split-string old)))) + (setq value (org-entry-protect-space value)) + (member value values))) + +(defun org-entry-get-multivalued-property (pom property) + "Return a list of values in a multivalued property." + (let* ((value (org-entry-get pom property)) + (values (and value (split-string value)))) + (mapcar #'org-entry-restore-space values))) + +(defun org-entry-put-multivalued-property (pom property &rest values) + "Set multivalued PROPERTY at point-or-marker POM to VALUES. +VALUES should be a list of strings. Spaces will be protected." + (org-entry-put pom property (mapconcat #'org-entry-protect-space values " ")) + (let* ((value (org-entry-get pom property)) + (values (and value (split-string value)))) + (mapcar #'org-entry-restore-space values))) + +(defun org-entry-protect-space (s) + "Protect spaces and newline in string S." + (while (string-match " " s) + (setq s (replace-match "%20" t t s))) + (while (string-match "\n" s) + (setq s (replace-match "%0A" t t s))) + s) + +(defun org-entry-restore-space (s) + "Restore spaces and newline in string S." + (while (string-match "%20" s) + (setq s (replace-match " " t t s))) + (while (string-match "%0A" s) + (setq s (replace-match "\n" t t s))) + s) + +(defvar org-entry-property-inherited-from (make-marker) + "Marker pointing to the entry from where a property was inherited. +Each call to `org-entry-get-with-inheritance' will set this marker to the +location of the entry where the inheritance search matched. If there was +no match, the marker will point nowhere. +Note that also `org-entry-get' calls this function, if the INHERIT flag +is set.") + +(defun org-entry-get-with-inheritance (property &optional literal-nil) + "Get PROPERTY of entry or content at point, search higher levels if needed. +The search will stop at the first ancestor which has the property defined. +If the value found is \"nil\", return nil to show that the property +should be considered as undefined (this is the meaning of nil here). +However, if LITERAL-NIL is set, return the string value \"nil\" instead." + (move-marker org-entry-property-inherited-from nil) + (org-with-wide-buffer + (let (value) + (catch 'exit + (while t + (let ((v (org--property-local-values property literal-nil))) + (when v + (setq value + (concat (mapconcat #'identity (delq nil v) " ") + (and value " ") + value))) + (cond + ((car v) + (org-back-to-heading t) + (move-marker org-entry-property-inherited-from (point)) + (throw 'exit nil)) + ((org-up-heading-safe)) + (t + (let ((global (org--property-global-value property literal-nil))) + (cond ((not global)) + (value (setq value (concat global " " value))) + (t (setq value global)))) + (throw 'exit nil)))))) + (if literal-nil value (org-not-nil value))))) + +(defvar org-property-changed-functions nil + "Hook called when the value of a property has changed. +Each hook function should accept two arguments, the name of the property +and the new value.") + +(defun org-entry-put (pom property value) + "Set PROPERTY to VALUE for entry at point-or-marker POM. + +If the value is nil, it is converted to the empty string. If it +is not a string, an error is raised. Also raise an error on +invalid property names. + +PROPERTY can be any regular property (see +`org-special-properties'). It can also be \"TODO\", +\"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\". + +For the last two properties, VALUE may have any of the special +values \"earlier\" and \"later\". The function then increases or +decreases scheduled or deadline date by one day." + (cond ((null value) (setq value "")) + ((not (stringp value)) (error "Properties values should be strings")) + ((not (org--valid-property-p property)) + (user-error "Invalid property name: \"%s\"" property))) + (org-with-point-at pom + (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p)) + (org-back-to-heading t) + (org-with-limited-levels (org-back-to-heading t))) + (let ((beg (point))) + (cond + ((equal property "TODO") + (cond ((not (org-string-nw-p value)) (setq value 'none)) + ((not (member value org-todo-keywords-1)) + (user-error "\"%s\" is not a valid TODO state" value))) + (org-todo value) + (org-set-tags nil 'align)) + ((equal property "PRIORITY") + (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s)) + (org-set-tags nil 'align)) + ((equal property "SCHEDULED") + (forward-line) + (if (and (looking-at-p org-planning-line-re) + (re-search-forward + org-scheduled-time-regexp (line-end-position) t)) + (cond ((string= value "earlier") (org-timestamp-change -1 'day)) + ((string= value "later") (org-timestamp-change 1 'day)) + ((string= value "") (org-schedule '(4))) + (t (org-schedule nil value))) + (if (member value '("earlier" "later" "")) + (call-interactively #'org-schedule) + (org-schedule nil value)))) + ((equal property "DEADLINE") + (forward-line) + (if (and (looking-at-p org-planning-line-re) + (re-search-forward + org-deadline-time-regexp (line-end-position) t)) + (cond ((string= value "earlier") (org-timestamp-change -1 'day)) + ((string= value "later") (org-timestamp-change 1 'day)) + ((string= value "") (org-deadline '(4))) + (t (org-deadline nil value))) + (if (member value '("earlier" "later" "")) + (call-interactively #'org-deadline) + (org-deadline nil value)))) + ((member property org-special-properties) + (error "The %s property cannot be set with `org-entry-put'" property)) + (t + (let* ((range (org-get-property-block beg 'force)) + (end (cdr range)) + (case-fold-search t)) + (goto-char (car range)) + (if (re-search-forward (org-re-property property nil t) end t) + (progn (delete-region (match-beginning 0) (match-end 0)) + (goto-char (match-beginning 0))) + (goto-char end) + (insert "\n") + (backward-char)) + (insert ":" property ":") + (when value (insert " " value)) + (org-indent-line))))) + (run-hook-with-args 'org-property-changed-functions property value))) + +(defun org-buffer-property-keys + (&optional specials defaults columns ignore-malformed) + "Get all property keys in the current buffer. + +When SPECIALS is non-nil, also list the special properties that +reflect things like tags and TODO state. + +When DEFAULTS is non-nil, also include properties that has +special meaning internally: ARCHIVE, CATEGORY, SUMMARY, +DESCRIPTION, LOCATION, and LOGGING and others. + +When COLUMNS in non-nil, also include property names given in +COLUMN formats in the current buffer. + +When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be +automatically performed, such drawers will be silently ignored." + (let ((case-fold-search t) + (props (append + (and specials org-special-properties) + (and defaults (cons org-effort-property org-default-properties)) + nil))) + (org-with-wide-buffer + (goto-char (point-min)) + (while (re-search-forward org-property-start-re nil t) + (let ((range (org-get-property-block))) + (catch 'skip + (unless range + (when (and (not ignore-malformed) + (not (org-before-first-heading-p)) + (y-or-n-p (format "Malformed drawer at %d, repair?" + (line-beginning-position)))) + (org-get-property-block nil t)) + (throw 'skip nil)) + (goto-char (car range)) + (let ((begin (car range)) + (end (cdr range))) + ;; Make sure that found property block is not located + ;; before current point, as it would generate an infloop. + ;; It can happen, for example, in the following + ;; situation: + ;; + ;; * Headline + ;; :PROPERTIES: + ;; ... + ;; :END: + ;; *************** Inlinetask + ;; #+BEGIN_EXAMPLE + ;; :PROPERTIES: + ;; #+END_EXAMPLE + ;; + (if (< begin (point)) (throw 'skip nil) (goto-char begin)) + (while (< (point) end) + (let ((p (progn (looking-at org-property-re) + (match-string-no-properties 2)))) + ;; Only add true property name, not extension symbol. + (push (if (not (string-match-p "\\+\\'" p)) p + (substring p 0 -1)) + props)) + (forward-line)))) + (outline-next-heading))) + (when columns + (goto-char (point-min)) + (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t) + (let ((element (org-element-at-point))) + (when (memq (org-element-type element) '(keyword node-property)) + (let ((value (org-element-property :value element)) + (start 0)) + (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\ +\\(?:{[^}]+}\\)?" + value start) + (setq start (match-end 0)) + (let ((p (match-string-no-properties 1 value))) + (unless (member-ignore-case p org-special-properties) + (push p props)))))))))) + (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b)))))) + +(defun org-property-values (key) + "List all non-nil values of property KEY in current buffer." + (org-with-wide-buffer + (goto-char (point-min)) + (let ((case-fold-search t) + (re (org-re-property key)) + values) + (while (re-search-forward re nil t) + (push (org-entry-get (point) key) values)) + (delete-dups values)))) + +(defun org-insert-property-drawer () + "Insert a property drawer into the current entry." + (org-with-wide-buffer + (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p)) + (org-back-to-heading t) + (org-with-limited-levels (org-back-to-heading t))) + (forward-line) + (when (looking-at-p org-planning-line-re) (forward-line)) + (unless (looking-at-p org-property-drawer-re) + ;; Make sure we start editing a line from current entry, not from + ;; next one. It prevents extending text properties or overlays + ;; belonging to the latter. + (when (bolp) (backward-char)) + (let ((begin (1+ (point))) + (inhibit-read-only t)) + (insert "\n:PROPERTIES:\n:END:") + (when (eobp) (insert "\n")) + (org-indent-region begin (point)))))) + +(defun org-insert-drawer (&optional arg drawer) + "Insert a drawer at point. + +When optional argument ARG is non-nil, insert a property drawer. + +Optional argument DRAWER, when non-nil, is a string representing +drawer's name. Otherwise, the user is prompted for a name. + +If a region is active, insert the drawer around that region +instead. + +Point is left between drawer's boundaries." + (interactive "P") + (let* ((drawer (if arg "PROPERTIES" + (or drawer (read-from-minibuffer "Drawer: "))))) + (cond + ;; With C-u, fall back on `org-insert-property-drawer' + (arg (org-insert-property-drawer)) + ;; Check validity of suggested drawer's name. + ((not (string-match-p org-drawer-regexp (format ":%s:" drawer))) + (user-error "Invalid drawer name")) + ;; With an active region, insert a drawer at point. + ((not (org-region-active-p)) + (progn + (unless (bolp) (insert "\n")) + (insert (format ":%s:\n\n:END:\n" drawer)) + (forward-line -2))) + ;; Otherwise, insert the drawer at point + (t + (let ((rbeg (region-beginning)) + (rend (copy-marker (region-end)))) + (unwind-protect + (progn + (goto-char rbeg) + (beginning-of-line) + (when (save-excursion + (re-search-forward org-outline-regexp-bol rend t)) + (user-error "Drawers cannot contain headlines")) + ;; Position point at the beginning of the first + ;; non-blank line in region. Insert drawer's opening + ;; there, then indent it. + (org-skip-whitespace) + (beginning-of-line) + (insert ":" drawer ":\n") + (forward-line -1) + (indent-for-tab-command) + ;; Move point to the beginning of the first blank line + ;; after the last non-blank line in region. Insert + ;; drawer's closing, then indent it. + (goto-char rend) + (skip-chars-backward " \r\t\n") + (insert "\n:END:") + (deactivate-mark t) + (indent-for-tab-command) + (unless (eolp) (insert "\n"))) + ;; Clear marker, whatever the outcome of insertion is. + (set-marker rend nil))))))) + +(defvar org-property-set-functions-alist nil + "Property set function alist. +Each entry should have the following format: + + (PROPERTY . READ-FUNCTION) + +The read function will be called with the same argument as +`org-completing-read'.") + +(defun org-set-property-function (property) + "Get the function that should be used to set PROPERTY. +This is computed according to `org-property-set-functions-alist'." + (or (cdr (assoc property org-property-set-functions-alist)) + 'org-completing-read)) + +(defun org-read-property-value (property) + "Read PROPERTY value from user." + (let* ((completion-ignore-case t) + (allowed (org-property-get-allowed-values nil property 'table)) + (cur (org-entry-get nil property)) + (prompt (concat property " value" + (if (and cur (string-match "\\S-" cur)) + (concat " [" cur "]") "") ": ")) + (set-function (org-set-property-function property)) + (val (if allowed + (funcall set-function prompt allowed nil + (not (get-text-property 0 'org-unrestricted + (caar allowed)))) + (funcall set-function prompt + (mapcar 'list (org-property-values property)) + nil nil "" nil cur)))) + (org-trim val))) + +(defvar org-last-set-property nil) +(defvar org-last-set-property-value nil) +(defun org-read-property-name () + "Read a property name." + (let ((completion-ignore-case t) + (default-prop (or (and (org-at-property-p) + (match-string-no-properties 2)) + org-last-set-property))) + (org-completing-read + (concat "Property" + (if default-prop (concat " [" default-prop "]") "") + ": ") + (mapcar #'list (org-buffer-property-keys nil t t)) + nil nil nil nil default-prop))) + +(defun org-set-property-and-value (use-last) + "Allow to set [PROPERTY]: [value] direction from prompt. +When use-default, don't even ask, just use the last +\"[PROPERTY]: [value]\" string from the history." + (interactive "P") + (let* ((completion-ignore-case t) + (pv (or (and use-last org-last-set-property-value) + (org-completing-read + "Enter a \"[Property]: [value]\" pair: " + nil nil nil nil nil + org-last-set-property-value))) + prop val) + (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv) + (setq prop (match-string 1 pv) + val (match-string 2 pv)) + (org-set-property prop val)))) + +(defun org-set-property (property value) + "In the current entry, set PROPERTY to VALUE. + +When called interactively, this will prompt for a property name, offering +completion on existing and default properties. And then it will prompt +for a value, offering completion either on allowed values (via an inherited +xxx_ALL property) or on existing values in other instances of this property +in the current file. + +Throw an error when trying to set a property with an invalid name." + (interactive (list nil nil)) + (let ((property (or property (org-read-property-name)))) + ;; `org-entry-put' also makes the following check, but this one + ;; avoids polluting `org-last-set-property' and + ;; `org-last-set-property-value' needlessly. + (unless (org--valid-property-p property) + (user-error "Invalid property name: \"%s\"" property)) + (let ((value (or value (org-read-property-value property))) + (fn (cdr (assoc-string property org-properties-postprocess-alist t)))) + (setq org-last-set-property property) + (setq org-last-set-property-value (concat property ": " value)) + ;; Possibly postprocess the inserted value: + (when fn (setq value (funcall fn value))) + (unless (equal (org-entry-get nil property) value) + (org-entry-put nil property value))))) + +(defun org-find-property (property &optional value) + "Find first entry in buffer that sets PROPERTY. + +When optional argument VALUE is non-nil, only consider an entry +if it contains PROPERTY set to this value. If PROPERTY should be +explicitly set to nil, use string \"nil\" for VALUE. + +Return position where the entry begins, or nil if there is no +such entry. If narrowing is in effect, only search the visible +part of the buffer." + (save-excursion + (goto-char (point-min)) + (let ((case-fold-search t) + (re (org-re-property property nil (not value) value))) + (catch 'exit + (while (re-search-forward re nil t) + (when (if value (org-at-property-p) + (org-entry-get (point) property nil t)) + (throw 'exit (progn (org-back-to-heading t) (point))))))))) + +(defun org-delete-property (property) + "In the current entry, delete PROPERTY." + (interactive + (let* ((completion-ignore-case t) + (cat (org-entry-get (point) "CATEGORY")) + (props0 (org-entry-properties nil 'standard)) + (props (if cat props0 + (delete `("CATEGORY" . ,(org-get-category)) props0))) + (prop (if (< 1 (length props)) + (completing-read "Property: " props nil t) + (caar props)))) + (list prop))) + (if (not property) + (message "No property to delete in this entry") + (org-entry-delete nil property) + (message "Property \"%s\" deleted" property))) + +(defun org-delete-property-globally (property) + "Remove PROPERTY globally, from all entries. +This function ignores narrowing, if any." + (interactive + (let* ((completion-ignore-case t) + (prop (completing-read + "Globally remove property: " + (mapcar #'list (org-buffer-property-keys))))) + (list prop))) + (org-with-wide-buffer + (goto-char (point-min)) + (let ((count 0) + (re (org-re-property (concat (regexp-quote property) "\\+?") t t))) + (while (re-search-forward re nil t) + (when (org-entry-delete (point) property) (cl-incf count))) + (message "Property \"%s\" removed from %d entries" property count)))) + +(defvar org-columns-current-fmt-compiled) ; defined in org-colview.el + +(defun org-compute-property-at-point () + "Compute the property at point. +This looks for an enclosing column format, extracts the operator and +then applies it to the property in the column format's scope." + (interactive) + (unless (org-at-property-p) + (user-error "Not at a property")) + (let ((prop (match-string-no-properties 2))) + (org-columns-get-format-and-top-level) + (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t)) + (user-error "No operator defined for property %s" prop)) + (org-columns-compute prop))) + +(defvar org-property-allowed-value-functions nil + "Hook for functions supplying allowed values for a specific property. +The functions must take a single argument, the name of the property, and +return a flat list of allowed values. If \":ETC\" is one of +the values, this means that these values are intended as defaults for +completion, but that other values should be allowed too. +The functions must return nil if they are not responsible for this +property.") + +(defun org-property-get-allowed-values (pom property &optional table) + "Get allowed values for the property PROPERTY. +When TABLE is non-nil, return an alist that can directly be used for +completion." + (let (vals) + (cond + ((equal property "TODO") + (setq vals (org-with-point-at pom + (append org-todo-keywords-1 '(""))))) + ((equal property "PRIORITY") + (let ((n org-lowest-priority)) + (while (>= n org-highest-priority) + (push (char-to-string n) vals) + (setq n (1- n))))) + ((equal property "CATEGORY")) + ((member property org-special-properties)) + ((setq vals (run-hook-with-args-until-success + 'org-property-allowed-value-functions property))) + (t + (setq vals (org-entry-get pom (concat property "_ALL") 'inherit)) + (when (and vals (string-match "\\S-" vals)) + (setq vals (car (read-from-string (concat "(" vals ")")))) + (setq vals (mapcar (lambda (x) + (cond ((stringp x) x) + ((numberp x) (number-to-string x)) + ((symbolp x) (symbol-name x)) + (t "???"))) + vals))))) + (when (member ":ETC" vals) + (setq vals (remove ":ETC" vals)) + (org-add-props (car vals) '(org-unrestricted t))) + (if table (mapcar 'list vals) vals))) + +(defun org-property-previous-allowed-value (&optional _previous) + "Switch to the next allowed value for this property." + (interactive) + (org-property-next-allowed-value t)) + +(defun org-property-next-allowed-value (&optional previous) + "Switch to the next allowed value for this property." + (interactive) + (unless (org-at-property-p) + (user-error "Not at a property")) + (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":")))) + (key (match-string 2)) + (value (match-string 3)) + (allowed (or (org-property-get-allowed-values (point) key) + (and (member value '("[ ]" "[-]" "[X]")) + '("[ ]" "[X]")))) + (heading (save-match-data (nth 4 (org-heading-components)))) + nval) + (unless allowed + (user-error "Allowed values for this property have not been defined")) + (when previous (setq allowed (reverse allowed))) + (when (member value allowed) + (setq nval (car (cdr (member value allowed))))) + (setq nval (or nval (car allowed))) + (when (equal nval value) + (user-error "Only one allowed value for this property")) + (org-at-property-p) + (replace-match (concat " :" key ": " nval) t t) + (org-indent-line) + (beginning-of-line 1) + (skip-chars-forward " \t") + (when (equal prop org-effort-property) + (org-refresh-property + '((effort . identity) + (effort-minutes . org-duration-to-minutes)) + nval) + (when (string= org-clock-current-task heading) + (setq org-clock-effort nval) + (org-clock-update-mode-line))) + (run-hook-with-args 'org-property-changed-functions key nval))) + +(defun org-find-olp (path &optional this-buffer) + "Return a marker pointing to the entry at outline path OLP. +If anything goes wrong, throw an error. +You can wrap this call to catch the error like this: + + (condition-case msg + (org-mobile-locate-entry (match-string 4)) + (error (nth 1 msg))) + +The return value will then be either a string with the error message, +or a marker if everything is OK. + +If THIS-BUFFER is set, the outline path does not contain a file, +only headings." + (let* ((file (if this-buffer buffer-file-name (pop path))) + (buffer (if this-buffer (current-buffer) (find-file-noselect file))) + (level 1) + (lmin 1) + (lmax 1) + end found flevel) + (unless buffer (error "File not found :%s" file)) + (with-current-buffer buffer + (unless (derived-mode-p 'org-mode) + (error "Buffer %s needs to be in Org mode" buffer)) + (org-with-wide-buffer + (goto-char (point-min)) + (dolist (heading path) + (let ((re (format org-complex-heading-regexp-format + (regexp-quote heading))) + (cnt 0)) + (while (re-search-forward re end t) + (setq level (- (match-end 1) (match-beginning 1))) + (when (and (>= level lmin) (<= level lmax)) + (setq found (match-beginning 0) flevel level cnt (1+ cnt)))) + (when (= cnt 0) + (error "Heading not found on level %d: %s" lmax heading)) + (when (> cnt 1) + (error "Heading not unique on level %d: %s" lmax heading)) + (goto-char found) + (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0))) + (setq end (save-excursion (org-end-of-subtree t t))))) + (when (org-at-heading-p) + (point-marker)))))) + +(defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only) + "Find node HEADING in BUFFER. +Return a marker to the heading if it was found, or nil if not. +If POS-ONLY is set, return just the position instead of a marker. + +The heading text must match exact, but it may have a TODO keyword, +a priority cookie and tags in the standard locations." + (with-current-buffer (or buffer (current-buffer)) + (org-with-wide-buffer + (goto-char (point-min)) + (let (case-fold-search) + (when (re-search-forward + (format org-complex-heading-regexp-format + (regexp-quote heading)) nil t) + (if pos-only + (match-beginning 0) + (move-marker (make-marker) (match-beginning 0)))))))) + +(defun org-find-exact-heading-in-directory (heading &optional dir) + "Find Org node headline HEADING in all \".org\" files in directory DIR. +When the target headline is found, return a marker to this location." + (let ((files (directory-files (or dir default-directory) + t "\\`[^.#].*\\.org\\'")) + visiting m buffer) + (catch 'found + (dolist (file files) + (message "trying %s" file) + (setq visiting (org-find-base-buffer-visiting file)) + (setq buffer (or visiting (find-file-noselect file))) + (setq m (org-find-exact-headline-in-buffer + heading buffer)) + (when (and (not m) (not visiting)) (kill-buffer buffer)) + (and m (throw 'found m)))))) + +(defun org-find-entry-with-id (ident) + "Locate the entry that contains the ID property with exact value IDENT. +IDENT can be a string, a symbol or a number, this function will search for +the string representation of it. +Return the position where this entry starts, or nil if there is no such entry." + (interactive "sID: ") + (let ((id (cond + ((stringp ident) ident) + ((symbolp ident) (symbol-name ident)) + ((numberp ident) (number-to-string ident)) + (t (error "IDENT %s must be a string, symbol or number" ident))))) + (org-with-wide-buffer (org-find-property "ID" id)))) + +;;;; Timestamps + +(defvar org-last-changed-timestamp nil) +(defvar org-last-inserted-timestamp nil + "The last time stamp inserted with `org-insert-time-stamp'.") + +(defun org-time-stamp (arg &optional inactive) + "Prompt for a date/time and insert a time stamp. + +If the user specifies a time like HH:MM or if this command is +called with at least one prefix argument, the time stamp contains +the date and the time. Otherwise, only the date is included. + +All parts of a date not specified by the user are filled in from +the timestamp at point, if any, or the current date/time +otherwise. + +If there is already a timestamp at the cursor, it is replaced. + +With two universal prefix arguments, insert an active timestamp +with the current time without prompting the user. + +When called from lisp, the timestamp is inactive if INACTIVE is +non-nil." + (interactive "P") + (let* ((ts (cond + ((org-at-date-range-p t) + (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2))) + ((org-at-timestamp-p 'lax) (match-string 0)))) + ;; Default time is either the timestamp at point or today. + ;; When entering a range, only the range start is considered. + (default-time (if (not ts) (current-time) + (apply #'encode-time (org-parse-time-string ts)))) + (default-input (and ts (org-get-compact-tod ts))) + (repeater (and ts + (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts) + (match-string 0 ts))) + org-time-was-given + org-end-time-was-given + (time + (and (if (equal arg '(16)) (current-time) + ;; Preserve `this-command' and `last-command'. + (let ((this-command this-command) + (last-command last-command)) + (org-read-date + arg 'totime nil nil default-time default-input + inactive)))))) + (cond + ((and ts + (memq last-command '(org-time-stamp org-time-stamp-inactive)) + (memq this-command '(org-time-stamp org-time-stamp-inactive))) + (insert "--") + (org-insert-time-stamp time (or org-time-was-given arg) inactive)) + (ts + ;; Make sure we're on a timestamp. When in the middle of a date + ;; range, move arbitrarily to range end. + (unless (org-at-timestamp-p 'lax) + (skip-chars-forward "-") + (org-at-timestamp-p 'lax)) + (replace-match "") + (setq org-last-changed-timestamp + (org-insert-time-stamp + time (or org-time-was-given arg) + inactive nil nil (list org-end-time-was-given))) + (when repeater + (backward-char) + (insert " " repeater) + (setq org-last-changed-timestamp + (concat (substring org-last-inserted-timestamp 0 -1) + " " repeater ">"))) + (message "Timestamp updated")) + ((equal arg '(16)) (org-insert-time-stamp time t inactive)) + (t (org-insert-time-stamp + time (or org-time-was-given arg) inactive nil nil + (list org-end-time-was-given)))))) + +;; FIXME: can we use this for something else, like computing time differences? +(defun org-get-compact-tod (s) + (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s) + (let* ((t1 (match-string 1 s)) + (h1 (string-to-number (match-string 2 s))) + (m1 (string-to-number (match-string 3 s))) + (t2 (and (match-end 4) (match-string 5 s))) + (h2 (and t2 (string-to-number (match-string 6 s)))) + (m2 (and t2 (string-to-number (match-string 7 s)))) + dh dm) + (if (not t2) + t1 + (setq dh (- h2 h1) dm (- m2 m1)) + (when (< dm 0) (setq dm (+ dm 60) dh (1- dh))) + (concat t1 "+" (number-to-string dh) + (and (/= 0 dm) (format ":%02d" dm))))))) + +(defun org-time-stamp-inactive (&optional arg) + "Insert an inactive time stamp. + +An inactive time stamp is enclosed in square brackets instead of angle +brackets. It is inactive in the sense that it does not trigger agenda entries, +does not link to the calendar and cannot be changed with the S-cursor keys. +So these are more for recording a certain time/date. + +If the user specifies a time like HH:MM or if this command is called with +at least one prefix argument, the time stamp contains the date and the time. +Otherwise, only the date is included. + +When called with two universal prefix arguments, insert an active time stamp +with the current time without prompting the user." + (interactive "P") + (org-time-stamp arg 'inactive)) + +(defvar org-date-ovl (make-overlay 1 1)) +(overlay-put org-date-ovl 'face 'org-date-selected) +(delete-overlay org-date-ovl) + +(defvar org-ans1) ; dynamically scoped parameter +(defvar org-ans2) ; dynamically scoped parameter + +(defvar org-plain-time-of-day-regexp) ; defined below + +(defvar org-overriding-default-time nil) ; dynamically scoped +(defvar org-read-date-overlay nil) +(defvar org-dcst nil) ; dynamically scoped +(defvar org-read-date-history nil) +(defvar org-read-date-final-answer nil) +(defvar org-read-date-analyze-futurep nil) +(defvar org-read-date-analyze-forced-year nil) +(defvar org-read-date-inactive) + +(defvar org-read-date-minibuffer-local-map + (let* ((map (make-sparse-keymap))) + (set-keymap-parent map minibuffer-local-map) + (org-defkey map (kbd ".") + (lambda () (interactive) + ;; Are we at the beginning of the prompt? + (if (looking-back "^[^:]+: " + (let ((inhibit-field-text-motion t)) + (line-beginning-position))) + (org-eval-in-calendar '(calendar-goto-today)) + (insert ".")))) + (org-defkey map (kbd "C-.") + (lambda () (interactive) + (org-eval-in-calendar '(calendar-goto-today)))) + (org-defkey map [(meta shift left)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-backward-month 1)))) + (org-defkey map [(meta shift right)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-forward-month 1)))) + (org-defkey map [(meta shift up)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-backward-year 1)))) + (org-defkey map [(meta shift down)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-forward-year 1)))) + (org-defkey map [?\e (shift left)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-backward-month 1)))) + (org-defkey map [?\e (shift right)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-forward-month 1)))) + (org-defkey map [?\e (shift up)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-backward-year 1)))) + (org-defkey map [?\e (shift down)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-forward-year 1)))) + (org-defkey map [(shift up)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-backward-week 1)))) + (org-defkey map [(shift down)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-forward-week 1)))) + (org-defkey map [(shift left)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-backward-day 1)))) + (org-defkey map [(shift right)] + (lambda () (interactive) + (org-eval-in-calendar '(calendar-forward-day 1)))) + (org-defkey map "!" + (lambda () (interactive) + (org-eval-in-calendar '(diary-view-entries)) + (message ""))) + (org-defkey map ">" + (lambda () (interactive) + (org-eval-in-calendar '(calendar-scroll-left 1)))) + (org-defkey map "<" + (lambda () (interactive) + (org-eval-in-calendar '(calendar-scroll-right 1)))) + (org-defkey map "\C-v" + (lambda () (interactive) + (org-eval-in-calendar + '(calendar-scroll-left-three-months 1)))) + (org-defkey map "\M-v" + (lambda () (interactive) + (org-eval-in-calendar + '(calendar-scroll-right-three-months 1)))) + map) + "Keymap for minibuffer commands when using `org-read-date'.") + +(defvar org-def) +(defvar org-defdecode) +(defvar org-with-time) + +(defvar calendar-setup) ; Dynamically scoped. +(defun org-read-date (&optional with-time to-time from-string prompt + default-time default-input inactive) + "Read a date, possibly a time, and make things smooth for the user. +The prompt will suggest to enter an ISO date, but you can also enter anything +which will at least partially be understood by `parse-time-string'. +Unrecognized parts of the date will default to the current day, month, year, +hour and minute. If this command is called to replace a timestamp at point, +or to enter the second timestamp of a range, the default time is taken +from the existing stamp. Furthermore, the command prefers the future, +so if you are giving a date where the year is not given, and the day-month +combination is already past in the current year, it will assume you +mean next year. For details, see the manual. A few examples: + + 3-2-5 --> 2003-02-05 + feb 15 --> currentyear-02-15 + 2/15 --> currentyear-02-15 + sep 12 9 --> 2009-09-12 + 12:45 --> today 12:45 + 22 sept 0:34 --> currentyear-09-22 0:34 + 12 --> currentyear-currentmonth-12 + Fri --> nearest Friday after today + -Tue --> last Tuesday + etc. + +Furthermore you can specify a relative date by giving, as the *first* thing +in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate +change in days weeks, months, years. +With a single plus or minus, the date is relative to today. With a double +plus or minus, it is relative to the date in DEFAULT-TIME. E.g. + +4d --> four days from today + +4 --> same as above + +2w --> two weeks from today + ++5 --> five days from default date + +The function understands only English month and weekday abbreviations. + +While prompting, a calendar is popped up - you can also select the +date with the mouse (button 1). The calendar shows a period of three +months. To scroll it to other months, use the keys `>' and `<'. +If you don't like the calendar, turn it off with + (setq org-read-date-popup-calendar nil) + +With optional argument TO-TIME, the date will immediately be converted +to an internal time. +With an optional argument WITH-TIME, the prompt will suggest to +also insert a time. Note that when WITH-TIME is not set, you can +still enter a time, and this function will inform the calling routine +about this change. The calling routine may then choose to change the +format used to insert the time stamp into the buffer to include the time. +With optional argument FROM-STRING, read from this string instead from +the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is +the time/date that is used for everything that is not specified by the +user." + (require 'parse-time) + (let* ((org-with-time with-time) + (org-time-stamp-rounding-minutes + (if (equal org-with-time '(16)) + '(0 0) + org-time-stamp-rounding-minutes)) + (org-dcst org-display-custom-times) + (ct (org-current-time)) + (org-def (or org-overriding-default-time default-time ct)) + (org-defdecode (decode-time org-def)) + (cur-frame (selected-frame)) + (mouse-autoselect-window nil) ; Don't let the mouse jump + (calendar-setup + (and (eq calendar-setup 'calendar-only) 'calendar-only)) + (calendar-move-hook nil) + (calendar-view-diary-initially-flag nil) + (calendar-view-holidays-initially-flag nil) + ans (org-ans0 "") org-ans1 org-ans2 final cal-frame) + ;; Rationalize `org-def' and `org-defdecode', if required. + (when (< (nth 2 org-defdecode) org-extend-today-until) + (setf (nth 2 org-defdecode) -1) + (setf (nth 1 org-defdecode) 59) + (setq org-def (apply #'encode-time org-defdecode)) + (setq org-defdecode (decode-time org-def))) + (let* ((timestr (format-time-string + (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") + org-def)) + (prompt (concat (if prompt (concat prompt " ") "") + (format "Date+time [%s]: " timestr)))) + (cond + (from-string (setq ans from-string)) + (org-read-date-popup-calendar + (save-excursion + (save-window-excursion + (calendar) + (when (eq calendar-setup 'calendar-only) + (setq cal-frame + (window-frame (get-buffer-window "*Calendar*" 'visible))) + (select-frame cal-frame)) + (org-eval-in-calendar '(setq cursor-type nil) t) + (unwind-protect + (progn + (calendar-forward-day (- (time-to-days org-def) + (calendar-absolute-from-gregorian + (calendar-current-date)))) + (org-eval-in-calendar nil t) + (let* ((old-map (current-local-map)) + (map (copy-keymap calendar-mode-map)) + (minibuffer-local-map + (copy-keymap org-read-date-minibuffer-local-map))) + (org-defkey map (kbd "RET") 'org-calendar-select) + (org-defkey map [mouse-1] 'org-calendar-select-mouse) + (org-defkey map [mouse-2] 'org-calendar-select-mouse) + (unwind-protect + (progn + (use-local-map map) + (setq org-read-date-inactive inactive) + (add-hook 'post-command-hook 'org-read-date-display) + (setq org-ans0 + (read-string prompt + default-input + 'org-read-date-history + nil)) + ;; org-ans0: from prompt + ;; org-ans1: from mouse click + ;; org-ans2: from calendar motion + (setq ans + (concat org-ans0 " " (or org-ans1 org-ans2)))) + (remove-hook 'post-command-hook 'org-read-date-display) + (use-local-map old-map) + (when org-read-date-overlay + (delete-overlay org-read-date-overlay) + (setq org-read-date-overlay nil))))) + (bury-buffer "*Calendar*") + (when cal-frame + (delete-frame cal-frame) + (select-frame-set-input-focus cur-frame)))))) + + (t ; Naked prompt only + (unwind-protect + (setq ans (read-string prompt default-input + 'org-read-date-history timestr)) + (when org-read-date-overlay + (delete-overlay org-read-date-overlay) + (setq org-read-date-overlay nil)))))) + + (setq final (org-read-date-analyze ans org-def org-defdecode)) + + (when org-read-date-analyze-forced-year + (message "Year was forced into %s" + (if org-read-date-force-compatible-dates + "compatible range (1970-2037)" + "range representable on this machine")) + (ding)) + + ;; One round trip to get rid of 34th of August and stuff like that.... + (setq final (decode-time (apply 'encode-time final))) + + (setq org-read-date-final-answer ans) + + (if to-time + (apply 'encode-time final) + (if (and (boundp 'org-time-was-given) org-time-was-given) + (format "%04d-%02d-%02d %02d:%02d" + (nth 5 final) (nth 4 final) (nth 3 final) + (nth 2 final) (nth 1 final)) + (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final)))))) + +(defun org-read-date-display () + "Display the current date prompt interpretation in the minibuffer." + (when org-read-date-display-live + (when org-read-date-overlay + (delete-overlay org-read-date-overlay)) + (when (minibufferp (current-buffer)) + (save-excursion + (end-of-line 1) + (while (not (equal (buffer-substring + (max (point-min) (- (point) 4)) (point)) + " ")) + (insert " "))) + (let* ((ans (concat (buffer-substring (point-at-bol) (point-max)) + " " (or org-ans1 org-ans2))) + (org-end-time-was-given nil) + (f (org-read-date-analyze ans org-def org-defdecode)) + (fmts (if org-dcst + org-time-stamp-custom-formats + org-time-stamp-formats)) + (fmt (if (or org-with-time + (and (boundp 'org-time-was-given) org-time-was-given)) + (cdr fmts) + (car fmts))) + (txt (format-time-string fmt (apply 'encode-time f))) + (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt)) + (txt (concat "=> " txt))) + (when (and org-end-time-was-given + (string-match org-plain-time-of-day-regexp txt)) + (setq txt (concat (substring txt 0 (match-end 0)) "-" + org-end-time-was-given + (substring txt (match-end 0))))) + (when org-read-date-analyze-futurep + (setq txt (concat txt " (=>F)"))) + (setq org-read-date-overlay + (make-overlay (1- (point-at-eol)) (point-at-eol))) + (org-overlay-display org-read-date-overlay txt 'secondary-selection))))) + +(defun org-read-date-analyze (ans def defdecode) + "Analyze the combined answer of the date prompt." + ;; FIXME: cleanup and comment + ;; Pass `current-time' result to `decode-time' (instead of calling + ;; without arguments) so that only `current-time' has to be + ;; overridden in tests. + (let ((org-def def) + (org-defdecode defdecode) + (nowdecode (decode-time (current-time))) + delta deltan deltaw deltadef year month day + hour minute second wday pm h2 m2 tl wday1 + iso-year iso-weekday iso-week iso-date futurep kill-year) + (setq org-read-date-analyze-futurep nil + org-read-date-analyze-forced-year nil) + (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans) + (setq ans "+0")) + + (when (setq delta (org-read-date-get-relative ans (current-time) org-def)) + (setq ans (replace-match "" t t ans) + deltan (car delta) + deltaw (nth 1 delta) + deltadef (nth 2 delta))) + + ;; Check if there is an iso week date in there. If yes, store the + ;; info and postpone interpreting it until the rest of the parsing + ;; is done. + (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans) + (setq iso-year (when (match-end 1) + (org-small-year-to-year + (string-to-number (match-string 1 ans)))) + iso-weekday (when (match-end 3) + (string-to-number (match-string 3 ans))) + iso-week (string-to-number (match-string 2 ans))) + (setq ans (replace-match "" t t ans))) + + ;; Help matching ISO dates with single digit month or day, like 2006-8-11. + (when (string-match + "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans) + (setq year (if (match-end 2) + (string-to-number (match-string 2 ans)) + (progn (setq kill-year t) + (string-to-number (format-time-string "%Y")))) + month (string-to-number (match-string 3 ans)) + day (string-to-number (match-string 4 ans))) + (setq year (org-small-year-to-year year)) + (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day) + t nil ans))) + + ;; Help matching dotted european dates + (when (string-match + "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans) + (setq year (if (match-end 3) (string-to-number (match-string 3 ans)) + (setq kill-year t) + (string-to-number (format-time-string "%Y"))) + day (string-to-number (match-string 1 ans)) + month (string-to-number (match-string 2 ans)) + ans (replace-match (format "%04d-%02d-%02d" year month day) + t nil ans))) + + ;; Help matching american dates, like 5/30 or 5/30/7 + (when (string-match + "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans) + (setq year (if (match-end 4) + (string-to-number (match-string 4 ans)) + (progn (setq kill-year t) + (string-to-number (format-time-string "%Y")))) + month (string-to-number (match-string 1 ans)) + day (string-to-number (match-string 2 ans))) + (setq year (org-small-year-to-year year)) + (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day) + t nil ans))) + ;; Help matching am/pm times, because `parse-time-string' does not do that. + ;; If there is a time with am/pm, and *no* time without it, we convert + ;; so that matching will be successful. + (cl-loop for i from 1 to 2 do ; twice, for end time as well + (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans)) + (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans)) + (setq hour (string-to-number (match-string 1 ans)) + minute (if (match-end 3) + (string-to-number (match-string 3 ans)) + 0) + pm (equal ?p + (string-to-char (downcase (match-string 4 ans))))) + (if (and (= hour 12) (not pm)) + (setq hour 0) + (when (and pm (< hour 12)) (setq hour (+ 12 hour)))) + (setq ans (replace-match (format "%02d:%02d" hour minute) + t t ans)))) + + ;; Check if a time range is given as a duration + (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans) + (setq hour (string-to-number (match-string 1 ans)) + h2 (+ hour (string-to-number (match-string 3 ans))) + minute (string-to-number (match-string 2 ans)) + m2 (+ minute (if (match-end 5) (string-to-number + (match-string 5 ans))0))) + (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60))) + (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) + t t ans))) + + ;; Check if there is a time range + (when (boundp 'org-end-time-was-given) + (setq org-time-was-given nil) + (when (and (string-match org-plain-time-of-day-regexp ans) + (match-end 8)) + (setq org-end-time-was-given (match-string 8 ans)) + (setq ans (concat (substring ans 0 (match-beginning 7)) + (substring ans (match-end 7)))))) + + (setq tl (parse-time-string ans) + day (or (nth 3 tl) (nth 3 org-defdecode)) + month + (cond ((nth 4 tl)) + ((not org-read-date-prefer-future) (nth 4 org-defdecode)) + ;; Day was specified. Make sure DAY+MONTH + ;; combination happens in the future. + ((nth 3 tl) + (setq futurep t) + (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode)) + (nth 4 nowdecode))) + (t (nth 4 org-defdecode))) + year + (cond ((and (not kill-year) (nth 5 tl))) + ((not org-read-date-prefer-future) (nth 5 org-defdecode)) + ;; Month was guessed in the future and is at least + ;; equal to NOWDECODE's. Fix year accordingly. + (futurep + (if (or (> month (nth 4 nowdecode)) + (>= day (nth 3 nowdecode))) + (nth 5 nowdecode) + (1+ (nth 5 nowdecode)))) + ;; Month was specified. Make sure MONTH+YEAR + ;; combination happens in the future. + ((nth 4 tl) + (setq futurep t) + (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode)) + ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode))) + ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode))) + (t (nth 5 nowdecode)))) + (t (nth 5 org-defdecode))) + hour (or (nth 2 tl) (nth 2 org-defdecode)) + minute (or (nth 1 tl) (nth 1 org-defdecode)) + second (or (nth 0 tl) 0) + wday (nth 6 tl)) + + (when (and (eq org-read-date-prefer-future 'time) + (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl)) + (equal day (nth 3 nowdecode)) + (equal month (nth 4 nowdecode)) + (equal year (nth 5 nowdecode)) + (nth 2 tl) + (or (< (nth 2 tl) (nth 2 nowdecode)) + (and (= (nth 2 tl) (nth 2 nowdecode)) + (nth 1 tl) + (< (nth 1 tl) (nth 1 nowdecode))))) + (setq day (1+ day) + futurep t)) + + ;; Special date definitions below + (cond + (iso-week + ;; There was an iso week + (require 'cal-iso) + (setq futurep nil) + (setq year (or iso-year year) + day (or iso-weekday wday 1) + wday nil ; to make sure that the trigger below does not match + iso-date (calendar-gregorian-from-absolute + (calendar-iso-to-absolute + (list iso-week day year)))) + ; FIXME: Should we also push ISO weeks into the future? + ; (when (and org-read-date-prefer-future + ; (not iso-year) + ; (< (calendar-absolute-from-gregorian iso-date) + ; (time-to-days (current-time)))) + ; (setq year (1+ year) + ; iso-date (calendar-gregorian-from-absolute + ; (calendar-iso-to-absolute + ; (list iso-week day year))))) + (setq month (car iso-date) + year (nth 2 iso-date) + day (nth 1 iso-date))) + (deltan + (setq futurep nil) + (unless deltadef + ;; Pass `current-time' result to `decode-time' (instead of + ;; calling without arguments) so that only `current-time' has + ;; to be overridden in tests. + (let ((now (decode-time (current-time)))) + (setq day (nth 3 now) month (nth 4 now) year (nth 5 now)))) + (cond ((member deltaw '("d" "")) (setq day (+ day deltan))) + ((equal deltaw "w") (setq day (+ day (* 7 deltan)))) + ((equal deltaw "m") (setq month (+ month deltan))) + ((equal deltaw "y") (setq year (+ year deltan))))) + ((and wday (not (nth 3 tl))) + ;; Weekday was given, but no day, so pick that day in the week + ;; on or after the derived date. + (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year)))) + (unless (equal wday wday1) + (setq day (+ day (% (- wday wday1 -7) 7)))))) + (when (and (boundp 'org-time-was-given) + (nth 2 tl)) + (setq org-time-was-given t)) + (when (< year 100) (setq year (+ 2000 year))) + ;; Check of the date is representable + (if org-read-date-force-compatible-dates + (progn + (when (< year 1970) + (setq year 1970 org-read-date-analyze-forced-year t)) + (when (> year 2037) + (setq year 2037 org-read-date-analyze-forced-year t))) + (condition-case nil + (ignore (encode-time second minute hour day month year)) + (error + (setq year (nth 5 org-defdecode)) + (setq org-read-date-analyze-forced-year t)))) + (setq org-read-date-analyze-futurep futurep) + (list second minute hour day month year))) + +(defvar parse-time-weekdays) +(defun org-read-date-get-relative (s today default) + "Check string S for special relative date string. +TODAY and DEFAULT are internal times, for today and for a default. +Return shift list (N what def-flag) +WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year. +N is the number of WHATs to shift. +DEF-FLAG is t when a double ++ or -- indicates shift relative to + the DEFAULT date rather than TODAY." + (require 'parse-time) + (when (and + (string-match + (concat + "\\`[ \t]*\\([-+]\\{0,2\\}\\)" + "\\([0-9]+\\)?" + "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?" + "\\([ \t]\\|$\\)") s) + (or (> (match-end 1) (match-beginning 1)) (match-end 4))) + (let* ((dir (if (> (match-end 1) (match-beginning 1)) + (string-to-char (substring (match-string 1 s) -1)) + ?+)) + (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1))))) + (n (if (match-end 2) (string-to-number (match-string 2 s)) 1)) + (what (if (match-end 3) (match-string 3 s) "d")) + (wday1 (cdr (assoc (downcase what) parse-time-weekdays))) + (date (if rel default today)) + (wday (nth 6 (decode-time date))) + delta) + (if wday1 + (progn + (setq delta (mod (+ 7 (- wday1 wday)) 7)) + (when (= delta 0) (setq delta 7)) + (when (= dir ?-) + (setq delta (- delta 7)) + (when (= delta 0) (setq delta -7))) + (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7))))) + (list delta "d" rel)) + (list (* n (if (= dir ?-) -1 1)) what rel))))) + +(defun org-order-calendar-date-args (arg1 arg2 arg3) + "Turn a user-specified date into the internal representation. +The internal representation needed by the calendar is (month day year). +This is a wrapper to handle the brain-dead convention in calendar that +user function argument order change dependent on argument order." + (pcase calendar-date-style + (`american (list arg1 arg2 arg3)) + (`european (list arg2 arg1 arg3)) + (`iso (list arg2 arg3 arg1)))) + +(defun org-eval-in-calendar (form &optional keepdate) + "Eval FORM in the calendar window and return to current window. +Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date." + (let ((sf (selected-frame)) + (sw (selected-window))) + (select-window (get-buffer-window "*Calendar*" t)) + (eval form) + (when (and (not keepdate) (calendar-cursor-to-date)) + (let* ((date (calendar-cursor-to-date)) + (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date)))) + (setq org-ans2 (format-time-string "%Y-%m-%d" time)))) + (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer)) + (select-window sw) + (select-frame-set-input-focus sf))) + +(defun org-calendar-select () + "Return to `org-read-date' with the date currently selected. +This is used by `org-read-date' in a temporary keymap for the calendar buffer." + (interactive) + (when (calendar-cursor-to-date) + (let* ((date (calendar-cursor-to-date)) + (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date)))) + (setq org-ans1 (format-time-string "%Y-%m-%d" time))) + (when (active-minibuffer-window) (exit-minibuffer)))) + +(defun org-insert-time-stamp (time &optional with-hm inactive pre post extra) + "Insert a date stamp for the date given by the internal TIME. +See `format-time-string' for the format of TIME. +WITH-HM means use the stamp format that includes the time of the day. +INACTIVE means use square brackets instead of angular ones, so that the +stamp will not contribute to the agenda. +PRE and POST are optional strings to be inserted before and after the +stamp. +The command returns the inserted time stamp." + (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats)) + stamp) + (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]"))) + (insert-before-markers (or pre "")) + (when (listp extra) + (setq extra (car extra)) + (if (and (stringp extra) + (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra)) + (setq extra (format "-%02d:%02d" + (string-to-number (match-string 1 extra)) + (string-to-number (match-string 2 extra)))) + (setq extra nil))) + (when extra + (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1)))) + (insert-before-markers (setq stamp (format-time-string fmt time))) + (insert-before-markers (or post "")) + (setq org-last-inserted-timestamp stamp))) + +(defun org-toggle-time-stamp-overlays () + "Toggle the use of custom time stamp formats." + (interactive) + (setq org-display-custom-times (not org-display-custom-times)) + (unless org-display-custom-times + (let ((p (point-min)) (bmp (buffer-modified-p))) + (while (setq p (next-single-property-change p 'display)) + (when (and (get-text-property p 'display) + (eq (get-text-property p 'face) 'org-date)) + (remove-text-properties + p (setq p (next-single-property-change p 'display)) + '(display t)))) + (set-buffer-modified-p bmp))) + (org-restart-font-lock) + (setq org-table-may-need-update t) + (if org-display-custom-times + (message "Time stamps are overlaid with custom format") + (message "Time stamp overlays removed"))) + +(defun org-display-custom-time (beg end) + "Overlay modified time stamp format over timestamp between BEG and END." + (let* ((ts (buffer-substring beg end)) + t1 with-hm tf time str (off 0)) + (save-match-data + (setq t1 (org-parse-time-string ts t)) + (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts) + (setq off (- (match-end 0) (match-beginning 0))))) + (setq end (- end off)) + (setq with-hm (and (nth 1 t1) (nth 2 t1)) + tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats) + time (org-fix-decoded-time t1) + str (org-add-props + (format-time-string + (substring tf 1 -1) (apply 'encode-time time)) + nil 'mouse-face 'highlight)) + (put-text-property beg end 'display str))) + +(defun org-fix-decoded-time (time) + "Set 0 instead of nil for the first 6 elements of time. +Don't touch the rest." + (let ((n 0)) + (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time))) + +(defun org-time-stamp-to-now (timestamp-string &optional seconds) + "Difference between TIMESTAMP-STRING and now in days. +If SECONDS is non-nil, return the difference in seconds." + (let ((fdiff (if seconds #'float-time #'time-to-days))) + (- (funcall fdiff (org-time-string-to-time timestamp-string)) + (funcall fdiff (current-time))))) + +(defun org-deadline-close-p (timestamp-string &optional ndays) + "Is the time in TIMESTAMP-STRING close to the current date?" + (setq ndays (or ndays (org-get-wdays timestamp-string))) + (and (<= (org-time-stamp-to-now timestamp-string) ndays) + (not (org-entry-is-done-p)))) + +(defun org-get-wdays (ts &optional delay zero-delay) + "Get the deadline lead time appropriate for timestring TS. +When DELAY is non-nil, get the delay time for scheduled items +instead of the deadline lead time. When ZERO-DELAY is non-nil +and `org-scheduled-delay-days' is 0, enforce 0 as the delay, +don't try to find the delay cookie in the scheduled timestamp." + (let ((tv (if delay org-scheduled-delay-days + org-deadline-warning-days))) + (cond + ((or (and delay (< tv 0)) + (and delay zero-delay (<= tv 0)) + (and (not delay) (<= tv 0))) + ;; Enforce this value no matter what + (- tv)) + ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts) + ;; lead time is specified. + (floor (* (string-to-number (match-string 1 ts)) + (cdr (assoc (match-string 2 ts) + '(("d" . 1) ("w" . 7) + ("m" . 30.4) ("y" . 365.25) + ("h" . 0.041667))))))) + ;; go for the default. + (t tv)))) + +(defun org-calendar-select-mouse (ev) + "Return to `org-read-date' with the date currently selected. +This is used by `org-read-date' in a temporary keymap for the calendar buffer." + (interactive "e") + (mouse-set-point ev) + (when (calendar-cursor-to-date) + (let* ((date (calendar-cursor-to-date)) + (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date)))) + (setq org-ans1 (format-time-string "%Y-%m-%d" time))) + (when (active-minibuffer-window) (exit-minibuffer)))) + +(defun org-check-deadlines (ndays) + "Check if there are any deadlines due or past due. +A deadline is considered due if it happens within `org-deadline-warning-days' +days from today's date. If the deadline appears in an entry marked DONE, +it is not shown. A numeric prefix argument NDAYS can be used to test that +many days. If the prefix is a raw `\\[universal-argument]', all deadlines \ +are shown." + (interactive "P") + (let* ((org-warn-days + (cond + ((equal ndays '(4)) 100000) + (ndays (prefix-numeric-value ndays)) + (t (abs org-deadline-warning-days)))) + (case-fold-search nil) + (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")) + (callback + (lambda () (org-deadline-close-p (match-string 1) org-warn-days)))) + (message "%d deadlines past-due or due within %d days" + (org-occur regexp nil callback) + org-warn-days))) + +(defsubst org-re-timestamp (type) + "Return a regexp for timestamp TYPE. +Allowed values for TYPE are: + + all: all timestamps + active: only active timestamps (<...>) + inactive: only inactive timestamps ([...]) + scheduled: only scheduled timestamps + deadline: only deadline timestamps + closed: only closed time-stamps + +When TYPE is nil, fall back on returning a regexp that matches +both scheduled and deadline timestamps." + (cl-case type + (all org-ts-regexp-both) + (active org-ts-regexp) + (inactive org-ts-regexp-inactive) + (scheduled org-scheduled-time-regexp) + (deadline org-deadline-time-regexp) + (closed org-closed-time-regexp) + (otherwise + (concat "\\<" + (regexp-opt (list org-deadline-string org-scheduled-string)) + " *<\\([^>]+\\)>")))) + +(defun org-check-before-date (d) + "Check if there are deadlines or scheduled entries before date D." + (interactive (list (org-read-date))) + (let* ((case-fold-search nil) + (regexp (org-re-timestamp org-ts-type)) + (ts-type org-ts-type) + (callback + (lambda () + (let ((match (match-string 1))) + (and (if (memq ts-type '(active inactive all)) + (eq (org-element-type (save-excursion + (backward-char) + (org-element-context))) + 'timestamp) + (org-at-planning-p)) + (time-less-p + (org-time-string-to-time match) + (org-time-string-to-time d))))))) + (message "%d entries before %s" + (org-occur regexp nil callback) + d))) + +(defun org-check-after-date (d) + "Check if there are deadlines or scheduled entries after date D." + (interactive (list (org-read-date))) + (let* ((case-fold-search nil) + (regexp (org-re-timestamp org-ts-type)) + (ts-type org-ts-type) + (callback + (lambda () + (let ((match (match-string 1))) + (and (if (memq ts-type '(active inactive all)) + (eq (org-element-type (save-excursion + (backward-char) + (org-element-context))) + 'timestamp) + (org-at-planning-p)) + (not (time-less-p + (org-time-string-to-time match) + (org-time-string-to-time d)))))))) + (message "%d entries after %s" + (org-occur regexp nil callback) + d))) + +(defun org-check-dates-range (start-date end-date) + "Check for deadlines/scheduled entries between START-DATE and END-DATE." + (interactive (list (org-read-date nil nil nil "Range starts") + (org-read-date nil nil nil "Range end"))) + (let ((case-fold-search nil) + (regexp (org-re-timestamp org-ts-type)) + (callback + (let ((type org-ts-type)) + (lambda () + (let ((match (match-string 1))) + (and + (if (memq type '(active inactive all)) + (eq (org-element-type (save-excursion + (backward-char) + (org-element-context))) + 'timestamp) + (org-at-planning-p)) + (not (time-less-p + (org-time-string-to-time match) + (org-time-string-to-time start-date))) + (time-less-p + (org-time-string-to-time match) + (org-time-string-to-time end-date)))))))) + (message "%d entries between %s and %s" + (org-occur regexp nil callback) start-date end-date))) + +(defun org-evaluate-time-range (&optional to-buffer) + "Evaluate a time range by computing the difference between start and end. +Normally the result is just printed in the echo area, but with prefix arg +TO-BUFFER, the result is inserted just after the date stamp into the buffer. +If the time range is actually in a table, the result is inserted into the +next column. +For time difference computation, a year is assumed to be exactly 365 +days in order to avoid rounding problems." + (interactive "P") + (or + (org-clock-update-time-maybe) + (save-excursion + (unless (org-at-date-range-p t) + (goto-char (point-at-bol)) + (re-search-forward org-tr-regexp-both (point-at-eol) t)) + (unless (org-at-date-range-p t) + (user-error "Not at a time-stamp range, and none found in current line"))) + (let* ((ts1 (match-string 1)) + (ts2 (match-string 2)) + (havetime (or (> (length ts1) 15) (> (length ts2) 15))) + (match-end (match-end 0)) + (time1 (org-time-string-to-time ts1)) + (time2 (org-time-string-to-time ts2)) + (t1 (float-time time1)) + (t2 (float-time time2)) + (diff (abs (- t2 t1))) + (negative (< (- t2 t1) 0)) + ;; (ys (floor (* 365 24 60 60))) + (ds (* 24 60 60)) + (hs (* 60 60)) + (fy "%dy %dd %02d:%02d") + (fy1 "%dy %dd") + (fd "%dd %02d:%02d") + (fd1 "%dd") + (fh "%02d:%02d") + y d h m align) + (if havetime + (setq ; y (floor (/ diff ys)) diff (mod diff ys) + y 0 + d (floor (/ diff ds)) diff (mod diff ds) + h (floor (/ diff hs)) diff (mod diff hs) + m (floor (/ diff 60))) + (setq ; y (floor (/ diff ys)) diff (mod diff ys) + y 0 + d (floor (+ (/ diff ds) 0.5)) + h 0 m 0)) + (if (not to-buffer) + (message "%s" (org-make-tdiff-string y d h m)) + (if (org-at-table-p) + (progn + (goto-char match-end) + (setq align t) + (and (looking-at " *|") (goto-char (match-end 0)))) + (goto-char match-end)) + (when (looking-at + "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]") + (replace-match "")) + (when negative (insert " -")) + (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m)) + (if (> d 0) (insert " " (format (if havetime fd fd1) d h m)) + (insert " " (format fh h m)))) + (when align (org-table-align)) + (message "Time difference inserted"))))) + +(defun org-make-tdiff-string (y d h m) + (let ((fmt "") + (l nil)) + (when (> y 0) + (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")) + (push y l)) + (when (> d 0) + (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")) + (push d l)) + (when (> h 0) + (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")) + (push h l)) + (when (> m 0) + (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")) + (push m l)) + (apply 'format fmt (nreverse l)))) + +(defun org-time-string-to-time (s) + "Convert timestamp string S into internal time." + (apply #'encode-time (org-parse-time-string s))) + +(defun org-time-string-to-seconds (s) + "Convert a timestamp string S into a number of seconds." + (float-time (org-time-string-to-time s))) + +(org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp") + +(defun org-time-string-to-absolute (s &optional daynr prefer buffer pos) + "Convert time stamp S to an absolute day number. + +If DAYNR in non-nil, and there is a specifier for a cyclic time +stamp, get the closest date to DAYNR. If PREFER is +`past' (respectively `future') return a date past (respectively +after) or equal to DAYNR. + +POS is the location of time stamp S, as a buffer position in +BUFFER. + +Diary sexp timestamps are matched against DAYNR, when non-nil. +If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is +signaled." + (cond + ((string-match "\\`%%\\((.*)\\)" s) + ;; Sexp timestamp: try to match DAYNR, if available, since we're + ;; only able to match individual dates. If it fails, raise an + ;; error. + (if (and daynr + (org-diary-sexp-entry + (match-string 1 s) "" (calendar-gregorian-from-absolute daynr))) + daynr + (signal 'org-diary-sexp-no-match (list s)))) + (daynr (org-closest-date s daynr prefer)) + (t (time-to-days + (condition-case errdata + (apply #'encode-time (org-parse-time-string s)) + (error (error "Bad timestamp `%s'%s\nError was: %s" + s + (if (not (and buffer pos)) "" + (format-message " at %d in buffer `%s'" pos buffer)) + (cdr errdata)))))))) + +(defun org-days-to-iso-week (days) + "Return the iso week number." + (require 'cal-iso) + (car (calendar-iso-from-absolute days))) + +(defun org-small-year-to-year (year) + "Convert 2-digit years into 4-digit years. +YEAR is expanded into one of the 30 next years, if possible, or +into a past one. Any year larger than 99 is returned unchanged." + (if (>= year 100) year + (let* ((current (string-to-number (format-time-string "%Y" (current-time)))) + (century (/ current 100)) + (offset (- year (% current 100)))) + (cond ((> offset 30) (+ (* (1- century) 100) year)) + ((> offset -70) (+ (* century 100) year)) + (t (+ (* (1+ century) 100) year)))))) + +(defun org-time-from-absolute (d) + "Return the time corresponding to date D. +D may be an absolute day number, or a calendar-type list (month day year)." + (when (numberp d) (setq d (calendar-gregorian-from-absolute d))) + (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d))) + +(defvar org-agenda-current-date) +(defun org-calendar-holiday () + "List of holidays, for Diary display in Org mode." + (require 'holidays) + (let ((hl (calendar-check-holidays org-agenda-current-date))) + (and hl (mapconcat #'identity hl "; ")))) + +(defun org-diary-sexp-entry (sexp entry d) + "Process a SEXP diary ENTRY for date D." + (require 'diary-lib) + ;; `org-anniversary' and alike expect ENTRY and DATE to be bound + ;; dynamically. + (let* ((sexp `(let ((entry ,entry) + (date ',d)) + ,(car (read-from-string sexp)))) + (result (if calendar-debug-sexp (eval sexp) + (condition-case nil + (eval sexp) + (error + (beep) + (message "Bad sexp at line %d in %s: %s" + (org-current-line) + (buffer-file-name) sexp) + (sleep-for 2)))))) + (cond ((stringp result) (split-string result "; ")) + ((and (consp result) + (not (consp (cdr result))) + (stringp (cdr result))) (cdr result)) + ((and (consp result) + (stringp (car result))) result) + (result entry)))) + +(defun org-diary-to-ical-string (frombuf) + "Get iCalendar entries from diary entries in buffer FROMBUF. +This uses the icalendar.el library." + (let* ((tmpdir temporary-file-directory) + (tmpfile (make-temp-name + (expand-file-name "orgics" tmpdir))) + buf rtn b e) + (with-current-buffer frombuf + (icalendar-export-region (point-min) (point-max) tmpfile) + (setq buf (find-buffer-visiting tmpfile)) + (set-buffer buf) + (goto-char (point-min)) + (when (re-search-forward "^BEGIN:VEVENT" nil t) + (setq b (match-beginning 0))) + (goto-char (point-max)) + (when (re-search-backward "^END:VEVENT" nil t) + (setq e (match-end 0))) + (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") ""))) + (kill-buffer buf) + (delete-file tmpfile) + rtn)) + +(defun org-closest-date (start current prefer) + "Return closest date to CURRENT starting from START. + +CURRENT and START are both time stamps. + +When PREFER is `past', return a date that is either CURRENT or +past. When PREFER is `future', return a date that is either +CURRENT or future. + +Only time stamps with a repeater are modified. Any other time +stamp stay unchanged. In any case, return value is an absolute +day number." + (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start)) + ;; No repeater. Do not shift time stamp. + (time-to-days (apply #'encode-time (org-parse-time-string start))) + (let ((value (string-to-number (match-string 1 start))) + (type (match-string 2 start))) + (if (= 0 value) + ;; Repeater with a 0-value is considered as void. + (time-to-days (apply #'encode-time (org-parse-time-string start))) + (let* ((base (org-date-to-gregorian start)) + (target (org-date-to-gregorian current)) + (sday (calendar-absolute-from-gregorian base)) + (cday (calendar-absolute-from-gregorian target)) + n1 n2) + ;; If START is already past CURRENT, just return START. + (if (<= cday sday) sday + ;; Compute closest date before (N1) and closest date past + ;; (N2) CURRENT. + (pcase type + ("h" + (let ((missing-hours + (mod (+ (- (* 24 (- cday sday)) + (nth 2 (org-parse-time-string start))) + org-extend-today-until) + value))) + (setf n1 (if (= missing-hours 0) cday + (- cday (1+ (/ missing-hours 24))))) + (setf n2 (+ cday (/ (- value missing-hours) 24))))) + ((or "d" "w") + (let ((value (if (equal type "w") (* 7 value) value))) + (setf n1 (+ sday (* value (/ (- cday sday) value)))) + (setf n2 (+ n1 value)))) + ("m" + (let* ((add-months + (lambda (d n) + ;; Add N months to gregorian date D, i.e., + ;; a list (MONTH DAY YEAR). Return a valid + ;; gregorian date. + (let ((m (+ (nth 0 d) n))) + (list (mod m 12) + (nth 1 d) + (+ (/ m 12) (nth 2 d)))))) + (months ; Complete months to TARGET. + (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base))) + (- (nth 0 target) (nth 0 base)) + ;; If START's day is greater than + ;; TARGET's, remove incomplete month. + (if (> (nth 1 target) (nth 1 base)) 0 -1)) + value) + value)) + (before (funcall add-months base months))) + (setf n1 (calendar-absolute-from-gregorian before)) + (setf n2 + (calendar-absolute-from-gregorian + (funcall add-months before value))))) + (_ + (let* ((d (nth 1 base)) + (m (nth 0 base)) + (y (nth 2 base)) + (years ; Complete years to TARGET. + (* (/ (- (nth 2 target) + y + ;; If START's month and day are + ;; greater than TARGET's, remove + ;; incomplete year. + (if (or (> (nth 0 target) m) + (and (= (nth 0 target) m) + (> (nth 1 target) d))) + 0 + 1)) + value) + value)) + (before (list m d (+ y years)))) + (setf n1 (calendar-absolute-from-gregorian before)) + (setf n2 (calendar-absolute-from-gregorian + (list m d (+ (nth 2 before) value))))))) + ;; Handle PREFER parameter, if any. + (cond + ((eq prefer 'past) (if (= cday n2) n2 n1)) + ((eq prefer 'future) (if (= cday n1) n1 n2)) + (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1))))))))) + +(defun org-date-to-gregorian (d) + "Turn any specification of date D into a Gregorian date for the calendar." + (cond ((integerp d) (calendar-gregorian-from-absolute d)) + ((and (listp d) (= (length d) 3)) d) + ((stringp d) + (let ((d (org-parse-time-string d))) + (list (nth 4 d) (nth 3 d) (nth 5 d)))) + ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d))))) + +(defun org-parse-time-string (s &optional nodefault) + "Parse the standard Org time string. + +This should be a lot faster than the normal `parse-time-string'. + +If time is not given, defaults to 0:00. However, with optional +NODEFAULT, hour and minute fields will be nil if not given." + (cond ((string-match org-ts-regexp0 s) + (list 0 + (when (or (match-beginning 8) (not nodefault)) + (string-to-number (or (match-string 8 s) "0"))) + (when (or (match-beginning 7) (not nodefault)) + (string-to-number (or (match-string 7 s) "0"))) + (string-to-number (match-string 4 s)) + (string-to-number (match-string 3 s)) + (string-to-number (match-string 2 s)) + nil nil nil)) + ((string-match "^<[^>]+>$" s) + ;; FIXME: `decode-time' needs to be called with ZONE as its + ;; second argument. However, this requires at least Emacs + ;; 25.1. We can do it when we switch to this version as our + ;; minimal requirement. + (decode-time (seconds-to-time (org-matcher-time s)))) + (t (error "Not a standard Org time string: %s" s)))) + +(defun org-timestamp-up (&optional arg) + "Increase the date item at the cursor by one. +If the cursor is on the year, change the year. If it is on the month, +the day or the time, change that. If the cursor is on the enclosing +bracket, change the timestamp type. +With prefix ARG, change by that many units." + (interactive "p") + (org-timestamp-change (prefix-numeric-value arg) nil 'updown)) + +(defun org-timestamp-down (&optional arg) + "Decrease the date item at the cursor by one. +If the cursor is on the year, change the year. If it is on the month, +the day or the time, change that. If the cursor is on the enclosing +bracket, change the timestamp type. +With prefix ARG, change by that many units." + (interactive "p") + (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown)) + +(defun org-timestamp-up-day (&optional arg) + "Increase the date in the time stamp by one day. +With prefix ARG, change that many days." + (interactive "p") + (if (and (not (org-at-timestamp-p 'lax)) + (org-at-heading-p)) + (org-todo 'up) + (org-timestamp-change (prefix-numeric-value arg) 'day 'updown))) + +(defun org-timestamp-down-day (&optional arg) + "Decrease the date in the time stamp by one day. +With prefix ARG, change that many days." + (interactive "p") + (if (and (not (org-at-timestamp-p 'lax)) + (org-at-heading-p)) + (org-todo 'down) + (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown)) + +(defun org-at-timestamp-p (&optional extended) + "Non-nil if point is inside a timestamp. + +By default, the function only consider syntactically valid active +timestamps. However, the caller may have a broader definition +for timestamps. As a consequence, optional argument EXTENDED can +be set to the following values + + `inactive' + + Include also syntactically valid inactive timestamps. + + `agenda' + + Include timestamps allowed in Agenda, i.e., those in + properties drawers, planning lines and clock lines. + + `lax' + + Ignore context. The function matches any part of the + document looking like a timestamp. This includes comments, + example blocks... + +For backward-compatibility with Org 9.0, every other non-nil +value is equivalent to `inactive'. + +When at a timestamp, return the position of the point as a symbol +among `bracket', `after', `year', `month', `hour', `minute', +`day' or a number of character from the last know part of the +time stamp. + +When matching, the match groups are the following: + group 1: year + group 2: month + group 3: day number + group 4: day name + group 5: hours, if any + group 6: minutes, if any" + (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2)) + (pos (point)) + (match? + (let ((boundaries (org-in-regexp regexp))) + (save-match-data + (cond ((null boundaries) nil) + ((eq extended 'lax) t) + (t + (or (and (eq extended 'agenda) + (or (org-at-planning-p) + (org-at-property-p) + (and (bound-and-true-p + org-agenda-include-inactive-timestamps) + (org-at-clock-log-p)))) + (eq 'timestamp + (save-excursion + (when (= pos (cdr boundaries)) (forward-char -1)) + (org-element-type (org-element-context))))))))))) + (cond + ((not match?) nil) + ((= pos (match-beginning 0)) 'bracket) + ;; Distinguish location right before the closing bracket from + ;; right after it. + ((= pos (1- (match-end 0))) 'bracket) + ((= pos (match-end 0)) 'after) + ((org-pos-in-match-range pos 2) 'year) + ((org-pos-in-match-range pos 3) 'month) + ((org-pos-in-match-range pos 7) 'hour) + ((org-pos-in-match-range pos 8) 'minute) + ((or (org-pos-in-match-range pos 4) + (org-pos-in-match-range pos 5)) 'day) + ((and (> pos (or (match-end 8) (match-end 5))) + (< pos (match-end 0))) + (- pos (or (match-end 8) (match-end 5)))) + (t 'day)))) + +(defun org-toggle-timestamp-type () + "Toggle the type (<active> or [inactive]) of a time stamp." + (interactive) + (when (org-at-timestamp-p 'lax) + (let ((beg (match-beginning 0)) (end (match-end 0)) + (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]")))) + (save-excursion + (goto-char beg) + (while (re-search-forward "[][<>]" end t) + (replace-match (cdr (assoc (char-after (match-beginning 0)) map)) + t t))) + (message "Timestamp is now %sactive" + (if (equal (char-after beg) ?<) "" "in"))))) + +(defun org-at-clock-log-p () + "Non-nil if point is on a clock log line." + (and (org-match-line org-clock-line-re) + (eq (org-element-type (save-match-data (org-element-at-point))) 'clock))) + +(defvar org-clock-history) ; defined in org-clock.el +(defvar org-clock-adjust-closest nil) ; defined in org-clock.el +(defun org-timestamp-change (n &optional what updown suppress-tmp-delay) + "Change the date in the time stamp at point. +The date will be changed by N times WHAT. WHAT can be `day', `month', +`year', `minute', `second'. If WHAT is not given, the cursor position +in the timestamp determines what will be changed. +When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"." + (let ((origin (point)) + (timestamp? (org-at-timestamp-p 'lax)) + origin-cat + with-hm inactive + (dm (max (nth 1 org-time-stamp-rounding-minutes) 1)) + extra rem + ts time time0 fixnext clrgx) + (unless timestamp? (user-error "Not at a timestamp")) + (if (and (not what) (eq timestamp? 'bracket)) + (org-toggle-timestamp-type) + ;; Point isn't on brackets. Remember the part of the time-stamp + ;; the point was in. Indeed, size of time-stamps may change, + ;; but point must be kept in the same category nonetheless. + (setq origin-cat timestamp?) + (when (and (not what) (not (eq timestamp? 'day)) + org-display-custom-times + (get-text-property (point) 'display) + (not (get-text-property (1- (point)) 'display))) + (setq timestamp? 'day)) + (setq timestamp? (or what timestamp?) + inactive (= (char-after (match-beginning 0)) ?\[) + ts (match-string 0)) + (replace-match "") + (when (string-match + "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]" + ts) + (setq extra (match-string 1 ts)) + (when suppress-tmp-delay + (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra)))) + (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts) + (setq with-hm t)) + (setq time0 (org-parse-time-string ts)) + (when (and updown + (eq timestamp? 'minute) + (not current-prefix-arg)) + ;; This looks like s-up and s-down. Change by one rounding step. + (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0)))) + (unless (= 0 (setq rem (% (nth 1 time0) dm))) + (setcar (cdr time0) (+ (nth 1 time0) + (if (> n 0) (- rem) (- dm rem)))))) + (setq time + (apply #'encode-time + (or (car time0) 0) + (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0)) + (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0)) + (+ (if (eq timestamp? 'day) n 0) (nth 3 time0)) + (+ (if (eq timestamp? 'month) n 0) (nth 4 time0)) + (+ (if (eq timestamp? 'year) n 0) (nth 5 time0)) + (nthcdr 6 time0))) + (when (and (memq timestamp? '(hour minute)) + extra + (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra)) + (setq extra (org-modify-ts-extra + extra + (if (eq timestamp? 'hour) 2 5) + n dm))) + (when (integerp timestamp?) + (setq extra (org-modify-ts-extra extra timestamp? n dm))) + (when (eq what 'calendar) + (let ((cal-date (org-get-date-from-calendar))) + (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month + (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day + (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year + (setcar time0 (or (car time0) 0)) + (setcar (nthcdr 1 time0) (or (nth 1 time0) 0)) + (setcar (nthcdr 2 time0) (or (nth 2 time0) 0)) + (setq time (apply 'encode-time time0)))) + ;; Insert the new time-stamp, and ensure point stays in the same + ;; category as before (i.e. not after the last position in that + ;; category). + (let ((pos (point))) + ;; Stay before inserted string. `save-excursion' is of no use. + (setq org-last-changed-timestamp + (org-insert-time-stamp time with-hm inactive nil nil extra)) + (goto-char pos)) + (save-match-data + (looking-at org-ts-regexp3) + (goto-char + (pcase origin-cat + ;; `day' category ends before `hour' if any, or at the end + ;; of the day name. + (`day (min (or (match-beginning 7) (1- (match-end 5))) origin)) + (`hour (min (match-end 7) origin)) + (`minute (min (1- (match-end 8)) origin)) + ((pred integerp) (min (1- (match-end 0)) origin)) + ;; Point was right after the time-stamp. However, the + ;; time-stamp length might have changed, so refer to + ;; (match-end 0) instead. + (`after (match-end 0)) + ;; `year' and `month' have both fixed size: point couldn't + ;; have moved into another part. + (_ origin)))) + ;; Update clock if on a CLOCK line. + (org-clock-update-time-maybe) + ;; Maybe adjust the closest clock in `org-clock-history' + (when org-clock-adjust-closest + (if (not (and (org-at-clock-log-p) + (< 1 (length (delq nil (mapcar 'marker-position + org-clock-history)))))) + (message "No clock to adjust") + (cond ((save-excursion ; fix previous clock? + (re-search-backward org-ts-regexp0 nil t) + (looking-back (concat org-clock-string " \\[") + (line-beginning-position))) + (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$"))) + ((save-excursion ; fix next clock? + (re-search-backward org-ts-regexp0 nil t) + (looking-at (concat org-ts-regexp0 "\\] =>"))) + (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0)))) + (save-window-excursion + ;; Find closest clock to point, adjust the previous/next one in history + (let* ((p (save-excursion (org-back-to-heading t))) + (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history)) + (clfixnth + (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100)))) + (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history)))) + (if (not clfixpos) + (message "No clock to adjust") + (save-excursion + (org-goto-marker-or-bmk clfixpos) + (org-show-subtree) + (when (re-search-forward clrgx nil t) + (goto-char (match-beginning 1)) + (let (org-clock-adjust-closest) + (org-timestamp-change n timestamp? updown)) + (message "Clock adjusted in %s for heading: %s" + (file-name-nondirectory (buffer-file-name)) + (org-get-heading t t))))))))) + ;; Try to recenter the calendar window, if any. + (when (and org-calendar-follow-timestamp-change + (get-buffer-window "*Calendar*" t) + (memq timestamp? '(day month year))) + (org-recenter-calendar (time-to-days time)))))) + +(defun org-modify-ts-extra (s pos n dm) + "Change the different parts of the lead-time and repeat fields in timestamp." + (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4))) + ng h m new rem) + (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s) + (cond + ((or (org-pos-in-match-range pos 2) + (org-pos-in-match-range pos 3)) + (setq m (string-to-number (match-string 3 s)) + h (string-to-number (match-string 2 s))) + (if (org-pos-in-match-range pos 2) + (setq h (+ h n)) + (setq n (* dm (with-no-warnings (signum n)))) + (unless (= 0 (setq rem (% m dm))) + (setq m (+ m (if (> n 0) (- rem) (- dm rem))))) + (setq m (+ m n))) + (when (< m 0) (setq m (+ m 60) h (1- h))) + (when (> m 59) (setq m (- m 60) h (1+ h))) + (setq h (mod h 24)) + (setq ng 1 new (format "-%02d:%02d" h m))) + ((org-pos-in-match-range pos 6) + (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx)))) + ((org-pos-in-match-range pos 5) + (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))) + + ((org-pos-in-match-range pos 9) + (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx)))) + ((org-pos-in-match-range pos 8) + (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s)))))))) + + (when ng + (setq s (concat + (substring s 0 (match-beginning ng)) + new + (substring s (match-end ng)))))) + s)) + +(defun org-recenter-calendar (d) + "If the calendar is visible, recenter it to date D." + (let ((cwin (get-buffer-window "*Calendar*" t))) + (when cwin + (let ((calendar-move-hook nil)) + (with-selected-window cwin + (calendar-goto-date + (if (listp d) d (calendar-gregorian-from-absolute d)))))))) + +(defun org-goto-calendar (&optional arg) + "Go to the Emacs calendar at the current date. +If there is a time stamp in the current line, go to that date. +A prefix ARG can be used to force the current date." + (interactive "P") + (let ((calendar-move-hook nil) + (calendar-view-holidays-initially-flag nil) + (calendar-view-diary-initially-flag nil) + diff) + (when (or (org-at-timestamp-p 'lax) + (org-match-line (concat ".*" org-ts-regexp))) + (let ((d1 (time-to-days (current-time))) + (d2 (time-to-days (org-time-string-to-time (match-string 1))))) + (setq diff (- d2 d1)))) + (calendar) + (calendar-goto-today) + (when (and diff (not arg)) (calendar-forward-day diff)))) + +(defun org-get-date-from-calendar () + "Return a list (month day year) of date at point in calendar." + (with-current-buffer "*Calendar*" + (save-match-data + (calendar-cursor-to-date)))) + +(defun org-date-from-calendar () + "Insert time stamp corresponding to cursor date in *Calendar* buffer. +If there is already a time stamp at the cursor position, update it." + (interactive) + (if (org-at-timestamp-p 'lax) + (org-timestamp-change 0 'calendar) + (let ((cal-date (org-get-date-from-calendar))) + (org-insert-time-stamp + (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date)))))) + +(defcustom org-effort-durations + `(("min" . 1) + ("h" . 60) + ("d" . ,(* 60 8)) + ("w" . ,(* 60 8 5)) + ("m" . ,(* 60 8 5 4)) + ("y" . ,(* 60 8 5 40))) + "Conversion factor to minutes for an effort modifier. + +Each entry has the form (MODIFIER . MINUTES). + +In an effort string, a number followed by MODIFIER is multiplied +by the specified number of MINUTES to obtain an effort in +minutes. + +For example, if the value of this variable is ((\"hours\" . 60)), then an +effort string \"2hours\" is equivalent to 120 minutes." + :group 'org-agenda + :version "26.1" + :package-version '(Org . "8.3") + :type '(alist :key-type (string :tag "Modifier") + :value-type (number :tag "Minutes"))) + +(defcustom org-image-actual-width t + "Should we use the actual width of images when inlining them? + +When set to t, always use the image width. + +When set to a number, use imagemagick (when available) to set +the image's width to this value. + +When set to a number in a list, try to get the width from any +#+ATTR.* keyword if it matches a width specification like + + #+ATTR_HTML: :width 300px + +and fall back on that number if none is found. + +When set to nil, try to get the width from an #+ATTR.* keyword +and fall back on the original width if none is found. + +This requires Emacs >= 24.1, build with imagemagick support." + :group 'org-appearance + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "Use the image width" t) + (integer :tag "Use a number of pixels") + (list :tag "Use #+ATTR* or a number of pixels" (integer)) + (const :tag "Use #+ATTR* or don't resize" nil))) + +(defcustom org-agenda-inhibit-startup nil + "Inhibit startup when preparing agenda buffers. +When this variable is t, the initialization of the Org agenda +buffers is inhibited: e.g. the visibility state is not set, the +tables are not re-aligned, etc." + :type 'boolean + :version "24.3" + :group 'org-agenda) + +(defcustom org-agenda-ignore-properties nil + "Avoid updating text properties when building the agenda. +Properties are used to prepare buffers for effort estimates, +appointments, statistics and subtree-local categories. +If you don't use these in the agenda, you can add them to this +list and agenda building will be a bit faster. +The value is a list, with zero or more of the symbols `effort', `appt', +`stats' or `category'." + :type '(set :greedy t + (const effort) + (const appt) + (const stats) + (const category)) + :version "26.1" + :package-version '(Org . "8.3") + :group 'org-agenda) + +;;;; Files + +(defun org-save-all-org-buffers () + "Save all Org buffers without user confirmation." + (interactive) + (message "Saving all Org buffers...") + (save-some-buffers t (lambda () (derived-mode-p 'org-mode))) + (when (featurep 'org-id) (org-id-locations-save)) + (message "Saving all Org buffers... done")) + +(defun org-revert-all-org-buffers () + "Revert all Org buffers. +Prompt for confirmation when there are unsaved changes. +Be sure you know what you are doing before letting this function +overwrite your changes. + +This function is useful in a setup where one tracks Org files +with a version control system, to revert on one machine after pulling +changes from another. I believe the procedure must be like this: + +1. M-x org-save-all-org-buffers +2. Pull changes from the other machine, resolve conflicts +3. M-x org-revert-all-org-buffers" + (interactive) + (unless (yes-or-no-p "Revert all Org buffers from their files? ") + (user-error "Abort")) + (save-excursion + (save-window-excursion + (dolist (b (buffer-list)) + (when (and (with-current-buffer b (derived-mode-p 'org-mode)) + (with-current-buffer b buffer-file-name)) + (pop-to-buffer-same-window b) + (revert-buffer t 'no-confirm))) + (when (and (featurep 'org-id) org-id-track-globally) + (org-id-locations-load))))) + +;;;; Agenda files + +;;;###autoload +(defun org-switchb (&optional arg) + "Switch between Org buffers. + +With `\\[universal-argument]' prefix, restrict available buffers to files. + +With `\\[universal-argument] \\[universal-argument]' \ +prefix, restrict available buffers to agenda files." + (interactive "P") + (let ((blist (org-buffer-list + (cond ((equal arg '(4)) 'files) + ((equal arg '(16)) 'agenda))))) + (pop-to-buffer-same-window + (completing-read "Org buffer: " + (mapcar #'list (mapcar #'buffer-name blist)) + nil t)))) + +(defun org-buffer-list (&optional predicate exclude-tmp) + "Return a list of Org buffers. +PREDICATE can be `export', `files' or `agenda'. + +export restrict the list to Export buffers. +files restrict the list to buffers visiting Org files. +agenda restrict the list to buffers visiting agenda files. + +If EXCLUDE-TMP is non-nil, ignore temporary buffers." + (let* ((bfn nil) + (agenda-files (and (eq predicate 'agenda) + (mapcar 'file-truename (org-agenda-files t)))) + (filter + (cond + ((eq predicate 'files) + (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode)))) + ((eq predicate 'export) + (lambda (b) (string-match "\\*Org .*Export" (buffer-name b)))) + ((eq predicate 'agenda) + (lambda (b) + (with-current-buffer b + (and (derived-mode-p 'org-mode) + (setq bfn (buffer-file-name b)) + (member (file-truename bfn) agenda-files))))) + (t (lambda (b) (with-current-buffer b + (or (derived-mode-p 'org-mode) + (string-match "\\*Org .*Export" + (buffer-name b))))))))) + (delq nil + (mapcar + (lambda(b) + (if (and (funcall filter b) + (or (not exclude-tmp) + (not (string-match "tmp" (buffer-name b))))) + b + nil)) + (buffer-list))))) + +(defun org-agenda-files (&optional unrestricted archives) + "Get the list of agenda files. +Optional UNRESTRICTED means return the full list even if a restriction +is currently in place. +When ARCHIVES is t, include all archive files that are really being +used by the agenda files. If ARCHIVE is `ifmode', do this only if +`org-agenda-archives-mode' is t." + (let ((files + (cond + ((and (not unrestricted) (get 'org-agenda-files 'org-restrict))) + ((stringp org-agenda-files) (org-read-agenda-file-list)) + ((listp org-agenda-files) org-agenda-files) + (t (error "Invalid value of `org-agenda-files'"))))) + (setq files (apply 'append + (mapcar (lambda (f) + (if (file-directory-p f) + (directory-files + f t org-agenda-file-regexp) + (list f))) + files))) + (when org-agenda-skip-unavailable-files + (setq files (delq nil + (mapcar (function + (lambda (file) + (and (file-readable-p file) file))) + files)))) + (when (or (eq archives t) + (and (eq archives 'ifmode) (eq org-agenda-archives-mode t))) + (setq files (org-add-archive-files files))) + files)) + +(defun org-agenda-file-p (&optional file) + "Return non-nil, if FILE is an agenda file. +If FILE is omitted, use the file associated with the current +buffer." + (let ((fname (or file (buffer-file-name)))) + (and fname + (member (file-truename fname) + (mapcar #'file-truename (org-agenda-files t)))))) + +(defun org-edit-agenda-file-list () + "Edit the list of agenda files. +Depending on setup, this either uses customize to edit the variable +`org-agenda-files', or it visits the file that is holding the list. In the +latter case, the buffer is set up in a way that saving it automatically kills +the buffer and restores the previous window configuration." + (interactive) + (if (stringp org-agenda-files) + (let ((cw (current-window-configuration))) + (find-file org-agenda-files) + (setq-local org-window-configuration cw) + (add-hook 'after-save-hook + (lambda () + (set-window-configuration + (prog1 org-window-configuration + (kill-buffer (current-buffer)))) + (org-install-agenda-files-menu) + (message "New agenda file list installed")) + nil 'local) + (message "%s" (substitute-command-keys + "Edit list and finish with \\[save-buffer]"))) + (customize-variable 'org-agenda-files))) + +(defun org-store-new-agenda-file-list (list) + "Set new value for the agenda file list and save it correctly." + (if (stringp org-agenda-files) + (let ((fe (org-read-agenda-file-list t)) b u) + (while (setq b (find-buffer-visiting org-agenda-files)) + (kill-buffer b)) + (with-temp-file org-agenda-files + (insert + (mapconcat + (lambda (f) ;; Keep un-expanded entries. + (if (setq u (assoc f fe)) + (cdr u) + f)) + list "\n") + "\n"))) + (let ((org-mode-hook nil) (org-inhibit-startup t) + (org-insert-mode-line-in-empty-file nil)) + (setq org-agenda-files list) + (customize-save-variable 'org-agenda-files org-agenda-files)))) + +(defun org-read-agenda-file-list (&optional pair-with-expansion) + "Read the list of agenda files from a file. +If PAIR-WITH-EXPANSION is t return pairs with un-expanded +filenames, used by `org-store-new-agenda-file-list' to write back +un-expanded file names." + (when (file-directory-p org-agenda-files) + (error "`org-agenda-files' cannot be a single directory")) + (when (stringp org-agenda-files) + (with-temp-buffer + (insert-file-contents org-agenda-files) + (mapcar + (lambda (f) + (let ((e (expand-file-name (substitute-in-file-name f) + org-directory))) + (if pair-with-expansion + (cons e f) + e))) + (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))) + +;;;###autoload +(defun org-cycle-agenda-files () + "Cycle through the files in `org-agenda-files'. +If the current buffer visits an agenda file, find the next one in the list. +If the current buffer does not, find the first agenda file." + (interactive) + (let* ((fs (or (org-agenda-files t) + (user-error "No agenda files"))) + (files (copy-sequence fs)) + (tcf (and buffer-file-name (file-truename buffer-file-name))) + file) + (when tcf + (while (and (setq file (pop files)) + (not (equal (file-truename file) tcf))))) + (find-file (car (or files fs))) + (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer))))) + +(defun org-agenda-file-to-front (&optional to-end) + "Move/add the current file to the top of the agenda file list. +If the file is not present in the list, it is added to the front. If it is +present, it is moved there. With optional argument TO-END, add/move to the +end of the list." + (interactive "P") + (let ((org-agenda-skip-unavailable-files nil) + (file-alist (mapcar (lambda (x) + (cons (file-truename x) x)) + (org-agenda-files t))) + (ctf (file-truename + (or buffer-file-name + (user-error "Please save the current buffer to a file")))) + x had) + (setq x (assoc ctf file-alist) had x) + + (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name)))) + (if to-end + (setq file-alist (append (delq x file-alist) (list x))) + (setq file-alist (cons x (delq x file-alist)))) + (org-store-new-agenda-file-list (mapcar 'cdr file-alist)) + (org-install-agenda-files-menu) + (message "File %s to %s of agenda file list" + (if had "moved" "added") (if to-end "end" "front")))) + +(defun org-remove-file (&optional file) + "Remove current file from the list of files in variable `org-agenda-files'. +These are the files which are being checked for agenda entries. +Optional argument FILE means use this file instead of the current." + (interactive) + (let* ((org-agenda-skip-unavailable-files nil) + (file (or file buffer-file-name + (user-error "Current buffer does not visit a file"))) + (true-file (file-truename file)) + (afile (abbreviate-file-name file)) + (files (delq nil (mapcar + (lambda (x) + (unless (equal true-file + (file-truename x)) + x)) + (org-agenda-files t))))) + (if (not (= (length files) (length (org-agenda-files t)))) + (progn + (org-store-new-agenda-file-list files) + (org-install-agenda-files-menu) + (message "Removed from Org Agenda list: %s" afile)) + (message "File was not in list: %s (not removed)" afile)))) + +(defun org-file-menu-entry (file) + (vector file (list 'find-file file) t)) + +(defun org-check-agenda-file (file) + "Make sure FILE exists. If not, ask user what to do." + (unless (file-exists-p file) + (message "Non-existent agenda file %s. [R]emove from list or [A]bort?" + (abbreviate-file-name file)) + (let ((r (downcase (read-char-exclusive)))) + (cond + ((equal r ?r) + (org-remove-file file) + (throw 'nextfile t)) + (t (user-error "Abort")))))) + +(defun org-get-agenda-file-buffer (file) + "Get an agenda buffer visiting FILE. +If the buffer needs to be created, add it to the list of buffers +which might be released later." + (let ((buf (org-find-base-buffer-visiting file))) + (if buf + buf ; just return it + ;; Make a new buffer and remember it + (setq buf (find-file-noselect file)) + (when buf (push buf org-agenda-new-buffers)) + buf))) + +(defun org-release-buffers (blist) + "Release all buffers in list, asking the user for confirmation when needed. +When a buffer is unmodified, it is just killed. When modified, it is saved +\(if the user agrees) and then killed." + (let (file) + (dolist (buf blist) + (setq file (buffer-file-name buf)) + (when (and (buffer-modified-p buf) + file + (y-or-n-p (format "Save file %s? " file))) + (with-current-buffer buf (save-buffer))) + (kill-buffer buf)))) + +(defun org-agenda-prepare-buffers (files) + "Create buffers for all agenda files, protect archived trees and comments." + (interactive) + (let ((pa '(:org-archived t)) + (pc '(:org-comment t)) + (pall '(:org-archived t :org-comment t)) + (inhibit-read-only t) + (org-inhibit-startup org-agenda-inhibit-startup) + (rea (concat ":" org-archive-tag ":")) + re pos) + (setq org-tag-alist-for-agenda nil + org-tag-groups-alist-for-agenda nil) + (save-excursion + (save-restriction + (dolist (file files) + (catch 'nextfile + (if (bufferp file) + (set-buffer file) + (org-check-agenda-file file) + (set-buffer (org-get-agenda-file-buffer file))) + (widen) + (org-set-regexps-and-options 'tags-only) + (setq pos (point)) + (or (memq 'category org-agenda-ignore-properties) + (org-refresh-category-properties)) + (or (memq 'stats org-agenda-ignore-properties) + (org-refresh-stats-properties)) + (or (memq 'effort org-agenda-ignore-properties) + (org-refresh-effort-properties)) + (or (memq 'appt org-agenda-ignore-properties) + (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)) + (setq org-todo-keywords-for-agenda + (append org-todo-keywords-for-agenda org-todo-keywords-1)) + (setq org-done-keywords-for-agenda + (append org-done-keywords-for-agenda org-done-keywords)) + (setq org-todo-keyword-alist-for-agenda + (append org-todo-keyword-alist-for-agenda org-todo-key-alist)) + (setq org-tag-alist-for-agenda + (org--tag-add-to-alist + org-tag-alist-for-agenda + org-current-tag-alist)) + ;; Merge current file's tag groups into global + ;; `org-tag-groups-alist-for-agenda'. + (when org-group-tags + (dolist (alist org-tag-groups-alist) + (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda))) + (if old + (setcdr old (org-uniquify (append (cdr old) (cdr alist)))) + (push alist org-tag-groups-alist-for-agenda))))) + (org-with-silent-modifications + (save-excursion + (remove-text-properties (point-min) (point-max) pall) + (when org-agenda-skip-archived-trees + (goto-char (point-min)) + (while (re-search-forward rea nil t) + (when (org-at-heading-p t) + (add-text-properties (point-at-bol) (org-end-of-subtree t) pa)))) + (goto-char (point-min)) + (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string)) + (while (re-search-forward re nil t) + (when (save-match-data (org-in-commented-heading-p t)) + (add-text-properties + (match-beginning 0) (org-end-of-subtree t) pc))))) + (goto-char pos))))) + (setq org-todo-keywords-for-agenda + (org-uniquify org-todo-keywords-for-agenda)) + (setq org-todo-keyword-alist-for-agenda + (org-uniquify org-todo-keyword-alist-for-agenda)))) + + +;;;; CDLaTeX minor mode + +(defvar org-cdlatex-mode-map (make-sparse-keymap) + "Keymap for the minor `org-cdlatex-mode'.") + +(org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret) +(org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret) +(org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol) +(org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify) +(org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent) + +(defvar org-cdlatex-texmathp-advice-is-done nil + "Flag remembering if we have applied the advice to texmathp already.") + +(define-minor-mode org-cdlatex-mode + "Toggle the minor `org-cdlatex-mode'. +This mode supports entering LaTeX environment and math in LaTeX fragments +in Org mode. +\\{org-cdlatex-mode-map}" + nil " OCDL" nil + (when org-cdlatex-mode + (require 'cdlatex) + (run-hooks 'cdlatex-mode-hook) + (cdlatex-compute-tables)) + (unless org-cdlatex-texmathp-advice-is-done + (setq org-cdlatex-texmathp-advice-is-done t) + (defadvice texmathp (around org-math-always-on activate) + "Always return t in Org buffers. +This is because we want to insert math symbols without dollars even outside +the LaTeX math segments. If Org mode thinks that point is actually inside +an embedded LaTeX fragment, let `texmathp' do its job. +`\\[org-cdlatex-mode-map]'" + (interactive) + (let (p) + (cond + ((not (derived-mode-p 'org-mode)) ad-do-it) + ((eq this-command 'cdlatex-math-symbol) + (setq ad-return-value t + texmathp-why '("cdlatex-math-symbol in org-mode" . 0))) + (t + (let ((p (org-inside-LaTeX-fragment-p))) + (if (and p (member (car p) (plist-get org-format-latex-options :matchers))) + (setq ad-return-value t + texmathp-why '("Org mode embedded math" . 0)) + (when p ad-do-it))))))))) + +(defun turn-on-org-cdlatex () + "Unconditionally turn on `org-cdlatex-mode'." + (org-cdlatex-mode 1)) + +(defun org-try-cdlatex-tab () + "Check if it makes sense to execute `cdlatex-tab', and do it if yes. +It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is + - inside a LaTeX fragment, or + - after the first word in a line, where an abbreviation expansion could + insert a LaTeX environment." + (when org-cdlatex-mode + (cond + ;; Before any word on the line: No expansion possible. + ((save-excursion (skip-chars-backward " \t") (bolp)) nil) + ;; Just after first word on the line: Expand it. Make sure it + ;; cannot happen on headlines, though. + ((save-excursion + (skip-chars-backward "a-zA-Z0-9*") + (skip-chars-backward " \t") + (and (bolp) (not (org-at-heading-p)))) + (cdlatex-tab) t) + ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t)))) + +(defun org-cdlatex-underscore-caret (&optional _arg) + "Execute `cdlatex-sub-superscript' in LaTeX fragments. +Revert to the normal definition outside of these fragments." + (interactive "P") + (if (org-inside-LaTeX-fragment-p) + (call-interactively 'cdlatex-sub-superscript) + (let (org-cdlatex-mode) + (call-interactively (key-binding (vector last-input-event)))))) + +(defun org-cdlatex-math-modify (&optional _arg) + "Execute `cdlatex-math-modify' in LaTeX fragments. +Revert to the normal definition outside of these fragments." + (interactive "P") + (if (org-inside-LaTeX-fragment-p) + (call-interactively 'cdlatex-math-modify) + (let (org-cdlatex-mode) + (call-interactively (key-binding (vector last-input-event)))))) + +(defun org-cdlatex-environment-indent (&optional environment item) + "Execute `cdlatex-environment' and indent the inserted environment. + +ENVIRONMENT and ITEM are passed to `cdlatex-environment'. + +The inserted environment is indented to current indentation +unless point is at the beginning of the line, in which the +environment remains unintended." + (interactive) + ;; cdlatex-environment always return nil. Therefore, capture output + ;; first and determine if an environment was selected. + (let* ((beg (point-marker)) + (end (copy-marker (point) t)) + (inserted (progn + (ignore-errors (cdlatex-environment environment item)) + (< beg end))) + ;; Figure out how many lines to move forward after the + ;; environment has been inserted. + (lines (when inserted + (save-excursion + (- (cl-loop while (< beg (point)) + with x = 0 + do (forward-line -1) + (cl-incf x) + finally return x) + (if (progn (goto-char beg) + (and (progn (skip-chars-forward " \t") (eolp)) + (progn (skip-chars-backward " \t") (bolp)))) + 1 0))))) + (env (org-trim (delete-and-extract-region beg end)))) + (when inserted + ;; Get indentation of next line unless at column 0. + (let ((ind (if (bolp) 0 + (save-excursion + (org-return-indent) + (prog1 (org-get-indentation) + (when (progn (skip-chars-forward " \t") (eolp)) + (delete-region beg (point))))))) + (bol (progn (skip-chars-backward " \t") (bolp)))) + ;; Insert a newline before environment unless at column zero + ;; to "escape" the current line. Insert a newline if + ;; something is one the same line as \end{ENVIRONMENT}. + (insert + (concat (unless bol "\n") env + (when (and (skip-chars-forward " \t") (not (eolp))) "\n"))) + (unless (zerop ind) + (save-excursion + (goto-char beg) + (while (< (point) end) + (unless (eolp) (indent-line-to ind)) + (forward-line)))) + (goto-char beg) + (forward-line lines) + (indent-line-to ind))) + (set-marker beg nil) + (set-marker end nil))) + + +;;;; LaTeX fragments + +(defun org-inside-LaTeX-fragment-p () + "Test if point is inside a LaTeX fragment. +I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing +sequence appearing also before point. +Even though the matchers for math are configurable, this function assumes +that \\begin, \\(, \\[, and $$ are always used. Only the single dollar +delimiters are skipped when they have been removed by customization. +The return value is nil, or a cons cell with the delimiter and the +position of this delimiter. + +This function does a reasonably good job, but can locally be fooled by +for example currency specifications. For example it will assume being in +inline math after \"$22.34\". The LaTeX fragment formatter will only format +fragments that are properly closed, but during editing, we have to live +with the uncertainty caused by missing closing delimiters. This function +looks only before point, not after." + (catch 'exit + (let ((pos (point)) + (dodollar (member "$" (plist-get org-format-latex-options :matchers))) + (lim (save-excursion (org-backward-paragraph) (point))) + dd-on str (start 0) m re) + (goto-char pos) + (when dodollar + (setq str (concat (buffer-substring lim (point)) "\000 X$.") + re (nth 1 (assoc "$" org-latex-regexps))) + (while (string-match re str start) + (cond + ((= (match-end 0) (length str)) + (throw 'exit (cons "$" (+ lim (match-beginning 0) 1)))) + ((= (match-end 0) (- (length str) 5)) + (throw 'exit nil)) + (t (setq start (match-end 0)))))) + (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t)) + (goto-char pos) + (and (match-beginning 1) (throw 'exit (cons (match-string 1) m))) + (and (match-beginning 2) (throw 'exit nil)) + ;; count $$ + (while (re-search-backward "\\$\\$" lim t) + (setq dd-on (not dd-on))) + (goto-char pos) + (when dd-on (cons "$$" m)))))) + +(defun org-inside-latex-macro-p () + "Is point inside a LaTeX macro or its arguments?" + (save-match-data + (org-in-regexp + "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*"))) + +(defun org--format-latex-make-overlay (beg end image &optional imagetype) + "Build an overlay between BEG and END using IMAGE file. +Argument IMAGETYPE is the extension of the displayed image, +as a string. It defaults to \"png\"." + (let ((ov (make-overlay beg end)) + (imagetype (or (intern imagetype) 'png))) + (overlay-put ov 'org-overlay-type 'org-latex-overlay) + (overlay-put ov 'evaporate t) + (overlay-put ov + 'modification-hooks + (list (lambda (o _flag _beg _end &optional _l) + (delete-overlay o)))) + (overlay-put ov + 'display + (list 'image :type imagetype :file image :ascent 'center)))) + +(defun org--list-latex-overlays (&optional beg end) + "List all Org LaTeX overlays in current buffer. +Limit to overlays between BEG and END when those are provided." + (cl-remove-if-not + (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)) + (overlays-in (or beg (point-min)) (or end (point-max))))) + +(defun org-remove-latex-fragment-image-overlays (&optional beg end) + "Remove all overlays with LaTeX fragment images in current buffer. +When optional arguments BEG and END are non-nil, remove all +overlays between them instead. Return a non-nil value when some +overlays were removed, nil otherwise." + (let ((overlays (org--list-latex-overlays beg end))) + (mapc #'delete-overlay overlays) + overlays)) + +(defun org-toggle-latex-fragment (&optional arg) + "Preview the LaTeX fragment at point, or all locally or globally. + +If the cursor is on a LaTeX fragment, create the image and overlay +it over the source code, if there is none. Remove it otherwise. +If there is no fragment at point, display all fragments in the +current section. + +With prefix ARG, preview or clear image for all fragments in the +current subtree or in the whole buffer when used before the first +headline. With a prefix ARG `\\[universal-argument] \ +\\[universal-argument]' preview or clear images +for all fragments in the buffer." + (interactive "P") + (when (display-graphic-p) + (catch 'exit + (save-excursion + (let (beg end msg) + (cond + ((or (equal arg '(16)) + (and (equal arg '(4)) + (org-with-limited-levels (org-before-first-heading-p)))) + (if (org-remove-latex-fragment-image-overlays) + (progn (message "LaTeX fragments images removed from buffer") + (throw 'exit nil)) + (setq msg "Creating images for buffer..."))) + ((equal arg '(4)) + (org-with-limited-levels (org-back-to-heading t)) + (setq beg (point)) + (setq end (progn (org-end-of-subtree t) (point))) + (if (org-remove-latex-fragment-image-overlays beg end) + (progn + (message "LaTeX fragment images removed from subtree") + (throw 'exit nil)) + (setq msg "Creating images for subtree..."))) + ((let ((datum (org-element-context))) + (when (memq (org-element-type datum) + '(latex-environment latex-fragment)) + (setq beg (org-element-property :begin datum)) + (setq end (org-element-property :end datum)) + (if (org-remove-latex-fragment-image-overlays beg end) + (progn (message "LaTeX fragment image removed") + (throw 'exit nil)) + (setq msg "Creating image..."))))) + (t + (org-with-limited-levels + (setq beg (if (org-at-heading-p) (line-beginning-position) + (outline-previous-heading) + (point))) + (setq end (progn (outline-next-heading) (point))) + (if (org-remove-latex-fragment-image-overlays beg end) + (progn + (message "LaTeX fragment images removed from section") + (throw 'exit nil)) + (setq msg "Creating images for section..."))))) + (let ((file (buffer-file-name (buffer-base-buffer)))) + (org-format-latex + (concat org-preview-latex-image-directory "org-ltximg") + beg end + ;; Emacs cannot overlay images from remote hosts. Create + ;; it in `temporary-file-directory' instead. + (if (or (not file) (file-remote-p file)) + temporary-file-directory + default-directory) + 'overlays msg 'forbuffer org-preview-latex-default-process)) + (message (concat msg "done"))))))) + +(defun org-format-latex + (prefix &optional beg end dir overlays msg forbuffer processing-type) + "Replace LaTeX fragments with links to an image. + +The function takes care of creating the replacement image. + +Only consider fragments between BEG and END when those are +provided. + +When optional argument OVERLAYS is non-nil, display the image on +top of the fragment instead of replacing it. + +PROCESSING-TYPE is the conversion method to use, as a symbol. + +Some of the options can be changed using the variable +`org-format-latex-options', which see." + (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache)) + (unless (eq processing-type 'verbatim) + (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}") + (cnt 0) + checkdir-flag) + (goto-char (or beg (point-min))) + ;; Optimize overlay creation: (info "(elisp) Managing Overlays"). + (when (and overlays (memq processing-type '(dvipng imagemagick))) + (overlay-recenter (or end (point-max)))) + (while (re-search-forward math-regexp end t) + (unless (and overlays + (eq (get-char-property (point) 'org-overlay-type) + 'org-latex-overlay)) + (let* ((context (org-element-context)) + (type (org-element-type context))) + (when (memq type '(latex-environment latex-fragment)) + (let ((block-type (eq type 'latex-environment)) + (value (org-element-property :value context)) + (beg (org-element-property :begin context)) + (end (save-excursion + (goto-char (org-element-property :end context)) + (skip-chars-backward " \r\t\n") + (point)))) + (cond + ((eq processing-type 'mathjax) + ;; Prepare for MathJax processing. + (if (not (string-match "\\`\\$\\$?" value)) + (goto-char end) + (delete-region beg end) + (if (string= (match-string 0 value) "$$") + (insert "\\[" (substring value 2 -2) "\\]") + (insert "\\(" (substring value 1 -1) "\\)")))) + ((assq processing-type org-preview-latex-process-alist) + ;; Process to an image. + (cl-incf cnt) + (goto-char beg) + (let* ((processing-info + (cdr (assq processing-type org-preview-latex-process-alist))) + (face (face-at-point)) + ;; Get the colors from the face at point. + (fg + (let ((color (plist-get org-format-latex-options + :foreground))) + (if (and forbuffer (eq color 'auto)) + (face-attribute face :foreground nil 'default) + color))) + (bg + (let ((color (plist-get org-format-latex-options + :background))) + (if (and forbuffer (eq color 'auto)) + (face-attribute face :background nil 'default) + color))) + (hash (sha1 (prin1-to-string + (list org-format-latex-header + org-latex-default-packages-alist + org-latex-packages-alist + org-format-latex-options + forbuffer value fg bg)))) + (imagetype (or (plist-get processing-info :image-output-type) "png")) + (absprefix (expand-file-name prefix dir)) + (linkfile (format "%s_%s.%s" prefix hash imagetype)) + (movefile (format "%s_%s.%s" absprefix hash imagetype)) + (sep (and block-type "\n\n")) + (link (concat sep "[[file:" linkfile "]]" sep)) + (options + (org-combine-plists + org-format-latex-options + `(:foreground ,fg :background ,bg)))) + (when msg (message msg cnt)) + (unless checkdir-flag ; Ensure the directory exists. + (setq checkdir-flag t) + (let ((todir (file-name-directory absprefix))) + (unless (file-directory-p todir) + (make-directory todir t)))) + (unless (file-exists-p movefile) + (org-create-formula-image + value movefile options forbuffer processing-type)) + (if overlays + (progn + (dolist (o (overlays-in beg end)) + (when (eq (overlay-get o 'org-overlay-type) + 'org-latex-overlay) + (delete-overlay o))) + (org--format-latex-make-overlay beg end movefile imagetype) + (goto-char end)) + (delete-region beg end) + (insert + (org-add-props link + (list 'org-latex-src + (replace-regexp-in-string "\"" "" value) + 'org-latex-src-embed-type + (if block-type 'paragraph 'character))))))) + ((eq processing-type 'mathml) + ;; Process to MathML. + (unless (org-format-latex-mathml-available-p) + (user-error "LaTeX to MathML converter not configured")) + (cl-incf cnt) + (when msg (message msg cnt)) + (goto-char beg) + (delete-region beg end) + (insert (org-format-latex-as-mathml + value block-type prefix dir))) + (t + (error "Unknown conversion process %s for LaTeX fragments" + processing-type))))))))))) + +(defun org-create-math-formula (latex-frag &optional mathml-file) + "Convert LATEX-FRAG to MathML and store it in MATHML-FILE. +Use `org-latex-to-mathml-convert-command'. If the conversion is +sucessful, return the portion between \"<math...> </math>\" +elements otherwise return nil. When MATHML-FILE is specified, +write the results in to that file. When invoked as an +interactive command, prompt for LATEX-FRAG, with initial value +set to the current active region and echo the results for user +inspection." + (interactive (list (let ((frag (when (org-region-active-p) + (buffer-substring-no-properties + (region-beginning) (region-end))))) + (read-string "LaTeX Fragment: " frag nil frag)))) + (unless latex-frag (user-error "Invalid LaTeX fragment")) + (let* ((tmp-in-file + (let ((file (file-relative-name + (make-temp-name (expand-file-name "ltxmathml-in"))))) + (write-region latex-frag nil file) + file)) + (tmp-out-file (file-relative-name + (make-temp-name (expand-file-name "ltxmathml-out")))) + (cmd (format-spec + org-latex-to-mathml-convert-command + `((?j . ,(and org-latex-to-mathml-jar-file + (shell-quote-argument + (expand-file-name + org-latex-to-mathml-jar-file)))) + (?I . ,(shell-quote-argument tmp-in-file)) + (?i . ,latex-frag) + (?o . ,(shell-quote-argument tmp-out-file))))) + mathml shell-command-output) + (when (called-interactively-p 'any) + (unless (org-format-latex-mathml-available-p) + (user-error "LaTeX to MathML converter not configured"))) + (message "Running %s" cmd) + (setq shell-command-output (shell-command-to-string cmd)) + (setq mathml + (when (file-readable-p tmp-out-file) + (with-current-buffer (find-file-noselect tmp-out-file t) + (goto-char (point-min)) + (when (re-search-forward + (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>" + (regexp-quote + "xmlns=\"http://www.w3.org/1998/Math/MathML\"")) + nil t) + (prog1 (match-string 0) (kill-buffer)))))) + (cond + (mathml + (setq mathml + (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml)) + (when mathml-file + (write-region mathml nil mathml-file)) + (when (called-interactively-p 'any) + (message mathml))) + ((message "LaTeX to MathML conversion failed") + (message shell-command-output))) + (delete-file tmp-in-file) + (when (file-exists-p tmp-out-file) + (delete-file tmp-out-file)) + mathml)) + +(defun org-format-latex-as-mathml (latex-frag latex-frag-type + prefix &optional dir) + "Use `org-create-math-formula' but check local cache first." + (let* ((absprefix (expand-file-name prefix dir)) + (print-length nil) (print-level nil) + (formula-id (concat + "formula-" + (sha1 + (prin1-to-string + (list latex-frag + org-latex-to-mathml-convert-command))))) + (formula-cache (format "%s-%s.mathml" absprefix formula-id)) + (formula-cache-dir (file-name-directory formula-cache))) + + (unless (file-directory-p formula-cache-dir) + (make-directory formula-cache-dir t)) + + (unless (file-exists-p formula-cache) + (org-create-math-formula latex-frag formula-cache)) + + (if (file-exists-p formula-cache) + ;; Successful conversion. Return the link to MathML file. + (org-add-props + (format "[[file:%s]]" (file-relative-name formula-cache dir)) + (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag) + 'org-latex-src-embed-type (if latex-frag-type + 'paragraph 'character))) + ;; Failed conversion. Return the LaTeX fragment verbatim + latex-frag))) + +(defun org--get-display-dpi () + "Get the DPI of the display. +The function assumes that the display has the same pixel width in +the horizontal and vertical directions." + (if (display-graphic-p) + (round (/ (display-pixel-height) + (/ (display-mm-height) 25.4))) + (error "Attempt to calculate the dpi of a non-graphic display"))) + +(defun org-create-formula-image + (string tofile options buffer &optional processing-type) + "Create an image from LaTeX source using external processes. + +The LaTeX STRING is saved to a temporary LaTeX file, then +converted to an image file by process PROCESSING-TYPE defined in +`org-preview-latex-process-alist'. A nil value defaults to +`org-preview-latex-default-process'. + +The generated image file is eventually moved to TOFILE. + +The OPTIONS argument controls the size, foreground color and +background color of the generated image. + +When BUFFER non-nil, this function is used for LaTeX previewing. +Otherwise, it is used to deal with LaTeX snippets showed in +a HTML file." + (let* ((processing-type (or processing-type + org-preview-latex-default-process)) + (processing-info + (cdr (assq processing-type org-preview-latex-process-alist))) + (programs (plist-get processing-info :programs)) + (error-message (or (plist-get processing-info :message) "")) + (use-xcolor (plist-get processing-info :use-xcolor)) + (image-input-type (plist-get processing-info :image-input-type)) + (image-output-type (plist-get processing-info :image-output-type)) + (post-clean (or (plist-get processing-info :post-clean) + '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log" + ".svg" ".png" ".jpg" ".jpeg" ".out"))) + (latex-header + (or (plist-get processing-info :latex-header) + (org-latex-make-preamble + (org-export-get-environment (org-export-get-backend 'latex)) + org-format-latex-header + 'snippet))) + (latex-compiler (plist-get processing-info :latex-compiler)) + (image-converter (plist-get processing-info :image-converter)) + (tmpdir temporary-file-directory) + (texfilebase (make-temp-name + (expand-file-name "orgtex" tmpdir))) + (texfile (concat texfilebase ".tex")) + (image-size-adjust (or (plist-get processing-info :image-size-adjust) + '(1.0 . 1.0))) + (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust)) + (or (plist-get options (if buffer :scale :html-scale)) 1.0))) + (dpi (* scale (if buffer (org--get-display-dpi) 140.0))) + (fg (or (plist-get options (if buffer :foreground :html-foreground)) + "Black")) + (bg (or (plist-get options (if buffer :background :html-background)) + "Transparent")) + (log-buf (get-buffer-create "*Org Preview LaTeX Output*")) + (resize-mini-windows nil)) ;Fix Emacs flicker when creating image. + (dolist (program programs) + (org-check-external-command program error-message)) + (if use-xcolor + (progn (if (eq fg 'default) + (setq fg (org-latex-color :foreground)) + (setq fg (org-latex-color-format fg))) + (if (eq bg 'default) + (setq bg (org-latex-color :background)) + (setq bg (org-latex-color-format + (if (string= bg "Transparent") "white" bg)))) + (with-temp-file texfile + (insert latex-header) + (insert "\n\\begin{document}\n" + "\\definecolor{fg}{rgb}{" fg "}\n" + "\\definecolor{bg}{rgb}{" bg "}\n" + "\n\\pagecolor{bg}\n" + "\n{\\color{fg}\n" + string + "\n}\n" + "\n\\end{document}\n"))) + (if (eq fg 'default) + (setq fg (org-dvipng-color :foreground)) + (unless (string= fg "Transparent") + (setq fg (org-dvipng-color-format fg)))) + (if (eq bg 'default) + (setq bg (org-dvipng-color :background)) + (unless (string= bg "Transparent") + (setq bg (org-dvipng-color-format bg)))) + (with-temp-file texfile + (insert latex-header) + (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))) + + (let* ((err-msg (format "Please adjust `%s' part of \ +`org-preview-latex-process-alist'." + processing-type)) + (image-input-file + (org-compile-file + texfile latex-compiler image-input-type err-msg log-buf)) + (image-output-file + (org-compile-file + image-input-file image-converter image-output-type err-msg log-buf + `((?F . ,(shell-quote-argument fg)) + (?B . ,(shell-quote-argument bg)) + (?D . ,(shell-quote-argument (format "%s" dpi))) + (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0)))))))) + (copy-file image-output-file tofile 'replace) + (dolist (e post-clean) + (when (file-exists-p (concat texfilebase e)) + (delete-file (concat texfilebase e)))) + image-output-file))) + +(defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra) + "Fill a LaTeX header template TPL. +In the template, the following place holders will be recognized: + + [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG + [NO-DEFAULT-PACKAGES] do not include DEF-PKG + [PACKAGES] \\usepackage statements for PKG + [NO-PACKAGES] do not include PKG + [EXTRA] the string EXTRA + [NO-EXTRA] do not include EXTRA + +For backward compatibility, if both the positive and the negative place +holder is missing, the positive one (without the \"NO-\") will be +assumed to be present at the end of the template. +DEF-PKG and PKG are assumed to be alists of options/packagename lists. +EXTRA is a string. +SNIPPETS-P indicates if this is run to create snippet images for HTML." + (let (rpl (end "")) + (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl) + (setq rpl (if (or (match-end 1) (not def-pkg)) + "" (org-latex-packages-to-string def-pkg snippets-p t)) + tpl (replace-match rpl t t tpl)) + (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p)))) + + (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl) + (setq rpl (if (or (match-end 1) (not pkg)) + "" (org-latex-packages-to-string pkg snippets-p t)) + tpl (replace-match rpl t t tpl)) + (when pkg (setq end + (concat end "\n" + (org-latex-packages-to-string pkg snippets-p))))) + + (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl) + (setq rpl (if (or (match-end 1) (not extra)) + "" (concat extra "\n")) + tpl (replace-match rpl t t tpl)) + (when (and extra (string-match "\\S-" extra)) + (setq end (concat end "\n" extra)))) + + (if (string-match "\\S-" end) + (concat tpl "\n" end) + tpl))) + +(defun org-latex-packages-to-string (pkg &optional snippets-p newline) + "Turn an alist of packages into a string with the \\usepackage macros." + (setq pkg (mapconcat (lambda(p) + (cond + ((stringp p) p) + ((and snippets-p (>= (length p) 3) (not (nth 2 p))) + (format "%% Package %s omitted" (cadr p))) + ((equal "" (car p)) + (format "\\usepackage{%s}" (cadr p))) + (t + (format "\\usepackage[%s]{%s}" + (car p) (cadr p))))) + pkg + "\n")) + (if newline (concat pkg "\n") pkg)) + +(defun org-dvipng-color (attr) + "Return a RGB color specification for dvipng." + (org-dvipng-color-format (face-attribute 'default attr nil))) + +(defun org-dvipng-color-format (color-name) + "Convert COLOR-NAME to a RGB color value for dvipng." + (apply #'format "rgb %s %s %s" + (mapcar 'org-normalize-color + (color-values color-name)))) + +(defun org-latex-color (attr) + "Return a RGB color for the LaTeX color package." + (org-latex-color-format (face-attribute 'default attr nil))) + +(defun org-latex-color-format (color-name) + "Convert COLOR-NAME to a RGB color value." + (apply #'format "%s,%s,%s" + (mapcar 'org-normalize-color + (color-values color-name)))) + +(defun org-normalize-color (value) + "Return string to be used as color value for an RGB component." + (format "%g" (/ value 65535.0))) + + + +;; Image display + +(defvar-local org-inline-image-overlays nil) + +(defun org-toggle-inline-images (&optional include-linked) + "Toggle the display of inline images. +INCLUDE-LINKED is passed to `org-display-inline-images'." + (interactive "P") + (if org-inline-image-overlays + (progn + (org-remove-inline-images) + (when (called-interactively-p 'interactive) + (message "Inline image display turned off"))) + (org-display-inline-images include-linked) + (when (called-interactively-p 'interactive) + (message (if org-inline-image-overlays + (format "%d images displayed inline" + (length org-inline-image-overlays)) + "No images to display inline"))))) + +(defun org-redisplay-inline-images () + "Refresh the display of inline images." + (interactive) + (if (not org-inline-image-overlays) + (org-toggle-inline-images) + (org-toggle-inline-images) + (org-toggle-inline-images))) + +(defun org-display-inline-images (&optional include-linked refresh beg end) + "Display inline images. + +An inline image is a link which follows either of these +conventions: + + 1. Its path is a file with an extension matching return value + from `image-file-name-regexp' and it has no contents. + + 2. Its description consists in a single link of the previous + type. + +When optional argument INCLUDE-LINKED is non-nil, also links with +a text description part will be inlined. This can be nice for +a quick look at those images, but it does not reflect what +exported files will look like. + +When optional argument REFRESH is non-nil, refresh existing +images between BEG and END. This will create new image displays +only if necessary. BEG and END default to the buffer +boundaries." + (interactive "P") + (when (display-graphic-p) + (unless refresh + (org-remove-inline-images) + (when (fboundp 'clear-image-cache) (clear-image-cache))) + (org-with-wide-buffer + (goto-char (or beg (point-min))) + (let* ((case-fold-search t) + (file-extension-re (image-file-name-regexp)) + (link-abbrevs (mapcar #'car + (append org-link-abbrev-alist-local + org-link-abbrev-alist))) + ;; Check absolute, relative file names and explicit + ;; "file:" links. Also check link abbreviations since + ;; some might expand to "file" links. + (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)" + (if (not link-abbrevs) "" + (format "\\|\\(?:%s:\\)" + (regexp-opt link-abbrevs)))))) + (while (re-search-forward file-types-re end t) + (let ((link (save-match-data (org-element-context)))) + ;; Check if we're at an inline image, i.e., an image file + ;; link without a description (unless INCLUDE-LINKED is + ;; non-nil). + (when (and (equal "file" (org-element-property :type link)) + (or include-linked + (null (org-element-contents link))) + (string-match-p file-extension-re + (org-element-property :path link))) + (let ((file (expand-file-name + (org-link-unescape + (org-element-property :path link))))) + (when (file-exists-p file) + (let ((width + ;; Apply `org-image-actual-width' specifications. + (cond + ((not (image-type-available-p 'imagemagick)) nil) + ((eq org-image-actual-width t) nil) + ((listp org-image-actual-width) + (or + ;; First try to find a width among + ;; attributes associated to the paragraph + ;; containing link. + (let ((paragraph + (let ((e link)) + (while (and (setq e (org-element-property + :parent e)) + (not (eq (org-element-type e) + 'paragraph)))) + e))) + (when paragraph + (save-excursion + (goto-char (org-element-property :begin paragraph)) + (when + (re-search-forward + "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)" + (org-element-property + :post-affiliated paragraph) + t) + (string-to-number (match-string 1)))))) + ;; Otherwise, fall-back to provided number. + (car org-image-actual-width))) + ((numberp org-image-actual-width) + org-image-actual-width))) + (old (get-char-property-and-overlay + (org-element-property :begin link) + 'org-image-overlay))) + (if (and (car-safe old) refresh) + (image-refresh (overlay-get (cdr old) 'display)) + (let ((image (create-image file + (and width 'imagemagick) + nil + :width width))) + (when image + (let ((ov (make-overlay + (org-element-property :begin link) + (progn + (goto-char + (org-element-property :end link)) + (skip-chars-backward " \t") + (point))))) + (overlay-put ov 'display image) + (overlay-put ov 'face 'default) + (overlay-put ov 'org-image-overlay t) + (overlay-put + ov 'modification-hooks + (list 'org-display-inline-remove-overlay)) + (push ov org-inline-image-overlays))))))))))))))) + +(defun org-display-inline-remove-overlay (ov after _beg _end &optional _len) + "Remove inline-display overlay if a corresponding region is modified." + (let ((inhibit-modification-hooks t)) + (when (and ov after) + (delete ov org-inline-image-overlays) + (delete-overlay ov)))) + +(defun org-remove-inline-images () + "Remove inline display of images." + (interactive) + (mapc #'delete-overlay org-inline-image-overlays) + (setq org-inline-image-overlays nil)) + +;;;; Key bindings + +(defun org-remap (map &rest commands) + "In MAP, remap the functions given in COMMANDS. +COMMANDS is a list of alternating OLDDEF NEWDEF command names." + (let (new old) + (while commands + (setq old (pop commands) new (pop commands)) + (org-defkey map (vector 'remap old) new)))) + +;; Outline functions from `outline-mode-prefix-map' +;; that can be remapped in Org: +(define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree) +(define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree) +(define-key org-mode-map [remap outline-forward-same-level] + 'org-forward-heading-same-level) +(define-key org-mode-map [remap outline-backward-same-level] + 'org-backward-heading-same-level) +(define-key org-mode-map [remap outline-show-branches] + 'org-kill-note-or-show-branches) +(define-key org-mode-map [remap outline-promote] 'org-promote-subtree) +(define-key org-mode-map [remap outline-demote] 'org-demote-subtree) +(define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret) +(define-key org-mode-map [remap outline-next-visible-heading] + 'org-next-visible-heading) +(define-key org-mode-map [remap outline-previous-visible-heading] + 'org-previous-visible-heading) +(define-key org-mode-map [remap show-children] 'org-show-children) + +;; Outline functions from `outline-mode-prefix-map' that can not +;; be remapped in Org: + +;; - the column "key binding" shows whether the Outline function is still +;; available in Org mode on the same key that it has been bound to in +;; Outline mode: +;; - "overridden": key used for a different functionality in Org mode +;; - else: key still bound to the same Outline function in Org mode + +;; | Outline function | key binding | Org replacement | +;; |------------------------------------+-------------+--------------------------| +;; | `outline-up-heading' | `C-c C-u' | still same function | +;; | `outline-move-subtree-up' | overridden | better: org-shiftup | +;; | `outline-move-subtree-down' | overridden | better: org-shiftdown | +;; | `show-entry' | overridden | no replacement | +;; | `show-branches' | `C-c C-k' | still same function | +;; | `show-subtree' | overridden | visibility cycling | +;; | `show-all' | overridden | no replacement | +;; | `hide-subtree' | overridden | visibility cycling | +;; | `hide-body' | overridden | no replacement | +;; | `hide-entry' | overridden | visibility cycling | +;; | `hide-leaves' | overridden | no replacement | +;; | `hide-sublevels' | overridden | no replacement | +;; | `hide-other' | overridden | no replacement | + +;; Make `C-c C-x' a prefix key +(org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap)) + +;; TAB key with modifiers +(org-defkey org-mode-map "\C-i" 'org-cycle) +(org-defkey org-mode-map [(tab)] 'org-cycle) +(org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived) +(org-defkey org-mode-map "\M-\t" #'pcomplete) + +;; The following line is necessary under Suse GNU/Linux +(org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab) +(org-defkey org-mode-map [(shift tab)] 'org-shifttab) +(define-key org-mode-map [backtab] 'org-shifttab) + +(org-defkey org-mode-map [(shift return)] 'org-table-copy-down) +(org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading) +(org-defkey org-mode-map (kbd "M-RET") #'org-meta-return) + +;; Cursor keys with modifiers +(org-defkey org-mode-map [(meta left)] 'org-metaleft) +(org-defkey org-mode-map [(meta right)] 'org-metaright) +(org-defkey org-mode-map [(meta up)] 'org-metaup) +(org-defkey org-mode-map [(meta down)] 'org-metadown) + +(org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point) +(org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point) +(org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft) +(org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright) +(org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup) +(org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown) + +(org-defkey org-mode-map [(shift up)] 'org-shiftup) +(org-defkey org-mode-map [(shift down)] 'org-shiftdown) +(org-defkey org-mode-map [(shift left)] 'org-shiftleft) +(org-defkey org-mode-map [(shift right)] 'org-shiftright) + +(org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright) +(org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft) +(org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup) +(org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown) + +;; Babel keys +(define-key org-mode-map org-babel-key-prefix org-babel-map) +(dolist (pair org-babel-key-bindings) + (define-key org-babel-map (car pair) (cdr pair))) + +;;; Extra keys for tty access. +;; We only set them when really needed because otherwise the +;; menus don't show the simple keys + +(when (or org-use-extra-keys (not window-system)) + (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down) + (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) + (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return) + (org-defkey org-mode-map [?\e (return)] 'org-meta-return) + (org-defkey org-mode-map [?\e (left)] 'org-metaleft) + (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft) + (org-defkey org-mode-map [?\e (right)] 'org-metaright) + (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright) + (org-defkey org-mode-map [?\e (up)] 'org-metaup) + (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup) + (org-defkey org-mode-map [?\e (down)] 'org-metadown) + (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown) + (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) + (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright) + (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup) + (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown) + (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup) + (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown) + (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft) + (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright) + (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright) + (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft) + (org-defkey org-mode-map [?\e (tab)] #'pcomplete) + (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading) + (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft) + (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright) + (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup) + (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown)) + +;; All the other keys +(org-remap org-mode-map + 'self-insert-command 'org-self-insert-command + 'delete-char 'org-delete-char + 'delete-backward-char 'org-delete-backward-char) +(org-defkey org-mode-map "|" 'org-force-self-insert) + +(org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up. +(org-defkey org-mode-map "\C-c\C-r" 'org-reveal) +(if (boundp 'narrow-map) + (org-defkey narrow-map "s" 'org-narrow-to-subtree) + (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)) +(if (boundp 'narrow-map) + (org-defkey narrow-map "b" 'org-narrow-to-block) + (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block)) +(if (boundp 'narrow-map) + (org-defkey narrow-map "e" 'org-narrow-to-element) + (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element)) +(org-defkey org-mode-map "\C-\M-t" 'org-transpose-element) +(org-defkey org-mode-map "\M-}" 'org-forward-element) +(org-defkey org-mode-map "\M-{" 'org-backward-element) +(org-defkey org-mode-map "\C-c\C-^" 'org-up-element) +(org-defkey org-mode-map "\C-c\C-_" 'org-down-element) +(org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level) +(org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level) +(org-defkey org-mode-map "\C-c\M-f" 'org-next-block) +(org-defkey org-mode-map "\C-c\M-b" 'org-previous-block) +(org-defkey org-mode-map "\C-c$" 'org-archive-subtree) +(org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree) +(org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default) +(org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer) +(org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag) +(org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling) +(org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer) +(org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups) +(org-defkey org-mode-map "\C-c\C-j" 'org-goto) +(org-defkey org-mode-map "\C-c\C-t" 'org-todo) +(org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command) +(org-defkey org-mode-map "\C-c\C-s" 'org-schedule) +(org-defkey org-mode-map "\C-c\C-d" 'org-deadline) +(org-defkey org-mode-map "\C-c;" 'org-toggle-comment) +(org-defkey org-mode-map "\C-c\C-w" 'org-refile) +(org-defkey org-mode-map "\C-c\M-w" 'org-copy) +(org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved +(org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res. +(org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret) +(org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift) +(org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible) +(org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content) +(org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content) +(org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link) +(org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link) +(org-defkey org-mode-map "\C-c\C-l" 'org-insert-link) +(org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link) +(org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links) +(org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point) +(org-defkey org-mode-map "\C-c%" 'org-mark-ring-push) +(org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto) +(org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding +(org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved +(org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r. +(org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved +(org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range) +(org-defkey org-mode-map "\C-c>" 'org-goto-calendar) +(org-defkey org-mode-map "\C-c<" 'org-date-from-calendar) +(org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files) +(org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files) +(org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front) +(org-defkey org-mode-map "\C-c]" 'org-remove-file) +(org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock) +(org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock) +(org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus) +(org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star) +(org-defkey org-mode-map "\C-c^" 'org-sort) +(org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c) +(org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches) +(org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies) +(org-defkey org-mode-map [remap open-line] 'org-open-line) +(org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim) +(org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph) +(org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph) +(org-defkey org-mode-map "\M-^" 'org-delete-indentation) +(org-defkey org-mode-map "\C-m" 'org-return) +(org-defkey org-mode-map "\C-j" 'org-return-indent) +(org-defkey org-mode-map "\C-c?" 'org-table-field-info) +(org-defkey org-mode-map "\C-c " 'org-table-blank-field) +(org-defkey org-mode-map "\C-c+" 'org-table-sum) +(org-defkey org-mode-map "\C-c=" 'org-table-eval-formula) +(org-defkey org-mode-map "\C-c'" 'org-edit-special) +(org-defkey org-mode-map "\C-c`" 'org-table-edit-field) +(org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot) +(org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot) +(org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region) +(org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks) +(org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el) +(org-defkey org-mode-map "\C-c\C-a" 'org-attach) +(org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays) +(org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger) +(org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch) +(org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width) +(org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize) +(org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action) +(org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull) +(org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push) +(org-defkey org-mode-map "\C-c@" 'org-mark-subtree) +(org-defkey org-mode-map "\M-h" 'org-mark-element) +(org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree) +;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree) + +(org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special) +(org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special) +(org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special) + +(org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays) +(org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in) +(org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last) +(org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks) +(org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out) +(org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto) +(org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel) +(org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display) +(org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report) +(org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update) +(org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment) +(org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images) +(org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images) +(org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities) +(org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox) +(org-defkey org-mode-map "\C-c\C-xp" 'org-set-property) +(org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value) +(org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort) +(org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort) +(org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property) +(org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock) +(org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer) + +(org-defkey org-mode-map "\C-c\C-x." 'org-timer) +(org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item) +(org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start) +(org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop) +(org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue) + +(define-key org-mode-map "\C-c\C-x\C-c" 'org-columns) + +(define-key org-mode-map "\C-c\C-x!" 'org-reload) + +(define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all) +(define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox) + +(define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation) + + +(defconst org-speed-commands-default + '( + ("Outline Navigation") + ("n" . (org-speed-move-safe 'org-next-visible-heading)) + ("p" . (org-speed-move-safe 'org-previous-visible-heading)) + ("f" . (org-speed-move-safe 'org-forward-heading-same-level)) + ("b" . (org-speed-move-safe 'org-backward-heading-same-level)) + ("F" . org-next-block) + ("B" . org-previous-block) + ("u" . (org-speed-move-safe 'outline-up-heading)) + ("j" . org-goto) + ("g" . (org-refile t)) + ("Outline Visibility") + ("c" . org-cycle) + ("C" . org-shifttab) + (" " . org-display-outline-path) + ("s" . org-narrow-to-subtree) + ("=" . org-columns) + ("Outline Structure Editing") + ("U" . org-metaup) + ("D" . org-metadown) + ("r" . org-metaright) + ("l" . org-metaleft) + ("R" . org-shiftmetaright) + ("L" . org-shiftmetaleft) + ("i" . (progn (forward-char 1) (call-interactively + 'org-insert-heading-respect-content))) + ("^" . org-sort) + ("w" . org-refile) + ("a" . org-archive-subtree-default-with-confirmation) + ("@" . org-mark-subtree) + ("#" . org-toggle-comment) + ("Clock Commands") + ("I" . org-clock-in) + ("O" . org-clock-out) + ("Meta Data Editing") + ("t" . org-todo) + ("," . (org-priority)) + ("0" . (org-priority ?\ )) + ("1" . (org-priority ?A)) + ("2" . (org-priority ?B)) + ("3" . (org-priority ?C)) + (":" . org-set-tags-command) + ("e" . org-set-effort) + ("E" . org-inc-effort) + ("W" . (lambda(m) (interactive "sMinutes before warning: ") + (org-entry-put (point) "APPT_WARNTIME" m))) + ("Agenda Views etc") + ("v" . org-agenda) + ("/" . org-sparse-tree) + ("Misc") + ("o" . org-open-at-point) + ("?" . org-speed-command-help) + ("<" . (org-agenda-set-restriction-lock 'subtree)) + (">" . (org-agenda-remove-restriction-lock)) + ) + "The default speed commands.") + +(defun org-print-speed-command (e) + (if (> (length (car e)) 1) + (progn + (princ "\n") + (princ (car e)) + (princ "\n") + (princ (make-string (length (car e)) ?-)) + (princ "\n")) + (princ (car e)) + (princ " ") + (if (symbolp (cdr e)) + (princ (symbol-name (cdr e))) + (prin1 (cdr e))) + (princ "\n"))) + +(defun org-speed-command-help () + "Show the available speed commands." + (interactive) + (if (not org-use-speed-commands) + (user-error "Speed commands are not activated, customize `org-use-speed-commands'") + (with-output-to-temp-buffer "*Help*" + (princ "User-defined Speed commands\n===========================\n") + (mapc #'org-print-speed-command org-speed-commands-user) + (princ "\n") + (princ "Built-in Speed commands\n=======================\n") + (mapc #'org-print-speed-command org-speed-commands-default)) + (with-current-buffer "*Help*" + (setq truncate-lines t)))) + +(defun org-speed-move-safe (cmd) + "Execute CMD, but make sure that the cursor always ends up in a headline. +If not, return to the original position and throw an error." + (interactive) + (let ((pos (point))) + (call-interactively cmd) + (unless (and (bolp) (org-at-heading-p)) + (goto-char pos) + (error "Boundary reached while executing %s" cmd)))) + +(defvar org-self-insert-command-undo-counter 0) + +(defvar org-table-auto-blank-field) ; defined in org-table.el +(defvar org-speed-command nil) + +(defun org-speed-command-activate (keys) + "Hook for activating single-letter speed commands. +`org-speed-commands-default' specifies a minimal command set. +Use `org-speed-commands-user' for further customization." + (when (or (and (bolp) (looking-at org-outline-regexp)) + (and (functionp org-use-speed-commands) + (funcall org-use-speed-commands))) + (cdr (assoc keys (append org-speed-commands-user + org-speed-commands-default))))) + +(defun org-babel-speed-command-activate (keys) + "Hook for activating single-letter code block commands." + (when (and (bolp) (looking-at org-babel-src-block-regexp)) + (cdr (assoc keys org-babel-key-bindings)))) + +(defcustom org-speed-command-hook + '(org-speed-command-activate org-babel-speed-command-activate) + "Hook for activating speed commands at strategic locations. +Hook functions are called in sequence until a valid handler is +found. + +Each hook takes a single argument, a user-pressed command key +which is also a `self-insert-command' from the global map. + +Within the hook, examine the cursor position and the command key +and return nil or a valid handler as appropriate. Handler could +be one of an interactive command, a function, or a form. + +Set `org-use-speed-commands' to non-nil value to enable this +hook. The default setting is `org-speed-command-activate'." + :group 'org-structure + :version "24.1" + :type 'hook) + +(defun org-self-insert-command (N) + "Like `self-insert-command', use overwrite-mode for whitespace in tables. +If the cursor is in a table looking at whitespace, the whitespace is +overwritten, and the table is not marked as requiring realignment." + (interactive "p") + (org-check-before-invisible-edit 'insert) + (cond + ((and org-use-speed-commands + (let ((kv (this-command-keys-vector))) + (setq org-speed-command + (run-hook-with-args-until-success + 'org-speed-command-hook + (make-string 1 (aref kv (1- (length kv)))))))) + (cond + ((commandp org-speed-command) + (setq this-command org-speed-command) + (call-interactively org-speed-command)) + ((functionp org-speed-command) + (funcall org-speed-command)) + ((and org-speed-command (listp org-speed-command)) + (eval org-speed-command)) + (t (let (org-use-speed-commands) + (call-interactively 'org-self-insert-command))))) + ((and + (org-at-table-p) + (eq N 1) + (not (org-region-active-p)) + (progn + ;; Check if we blank the field, and if that triggers align. + (and (featurep 'org-table) org-table-auto-blank-field + (memq last-command + '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c)) + (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |")) + ;; Got extra space, this field does not determine + ;; column width. + (let (org-table-may-need-update) (org-table-blank-field)) + ;; No extra space, this field may determine column + ;; width. + (org-table-blank-field))) + t) + (looking-at "[^|\n]* \\( \\)|")) + ;; There is room for insertion without re-aligning the table. + (delete-region (match-beginning 1) (match-end 1)) + (self-insert-command N)) + (t + (setq org-table-may-need-update t) + (self-insert-command N) + (org-fix-tags-on-the-fly) + (when org-self-insert-cluster-for-undo + (if (not (eq last-command 'org-self-insert-command)) + (setq org-self-insert-command-undo-counter 1) + (if (>= org-self-insert-command-undo-counter 20) + (setq org-self-insert-command-undo-counter 1) + (and (> org-self-insert-command-undo-counter 0) + buffer-undo-list (listp buffer-undo-list) + (not (cadr buffer-undo-list)) ; remove nil entry + (setcdr buffer-undo-list (cddr buffer-undo-list))) + (setq org-self-insert-command-undo-counter + (1+ org-self-insert-command-undo-counter)))))))) + +(defun org-check-before-invisible-edit (kind) + "Check is editing if kind KIND would be dangerous with invisible text around. +The detailed reaction depends on the user option `org-catch-invisible-edits'." + ;; First, try to get out of here as quickly as possible, to reduce overhead + (when (and org-catch-invisible-edits + (or (not (boundp 'visible-mode)) (not visible-mode)) + (or (get-char-property (point) 'invisible) + (get-char-property (max (point-min) (1- (point))) 'invisible))) + ;; OK, we need to take a closer look. Do not consider + ;; invisibility obtained through text properties (e.g., link + ;; fontification), as it cannot be toggled. + (let* ((invisible-at-point + (pcase (get-char-property-and-overlay (point) 'invisible) + (`(,_ . ,(and (pred overlayp) o)) o))) + ;; Assume that point cannot land in the middle of an + ;; overlay, or between two overlays. + (invisible-before-point + (and (not invisible-at-point) + (not (bobp)) + (pcase (get-char-property-and-overlay (1- (point)) 'invisible) + (`(,_ . ,(and (pred overlayp) o)) o)))) + (border-and-ok-direction + (or + ;; Check if we are acting predictably before invisible + ;; text. + (and invisible-at-point + (memq kind '(insert delete-backward))) + ;; Check if we are acting predictably after invisible text + ;; This works not well, and I have turned it off. It seems + ;; better to always show and stop after invisible text. + ;; (and (not invisible-at-point) invisible-before-point + ;; (memq kind '(insert delete))) + ))) + (when (or invisible-at-point invisible-before-point) + (when (eq org-catch-invisible-edits 'error) + (user-error "Editing in invisible areas is prohibited, make them visible first")) + (if (and org-custom-properties-overlays + (y-or-n-p "Display invisible properties in this buffer? ")) + (org-toggle-custom-properties-visibility) + ;; Make the area visible + (save-excursion + (when invisible-before-point + (goto-char + (previous-single-char-property-change (point) 'invisible))) + ;; Remove whatever overlay is currently making yet-to-be + ;; edited text invisible. Also remove nested invisibility + ;; related overlays. + (delete-overlay (or invisible-at-point invisible-before-point)) + (let ((origin (if invisible-at-point (point) (1- (point))))) + (while (pcase (get-char-property-and-overlay origin 'invisible) + (`(,_ . ,(and (pred overlayp) o)) + (delete-overlay o) + t))))) + (cond + ((eq org-catch-invisible-edits 'show) + ;; That's it, we do the edit after showing + (message + "Unfolding invisible region around point before editing") + (sit-for 1)) + ((and (eq org-catch-invisible-edits 'smart) + border-and-ok-direction) + (message "Unfolding invisible region around point before editing")) + (t + ;; Don't do the edit, make the user repeat it in full visibility + (user-error "Edit in invisible region aborted, repeat to confirm with text visible")))))))) + +(defun org-fix-tags-on-the-fly () + "Align tags in headline at point. +Unlike to `org-set-tags', it ignores region and sorting." + (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit + (org-at-heading-p)) + (let ((org-ignore-region t) + (org-tags-sort-function nil)) + (org-set-tags nil t)))) + +(defun org-delete-backward-char (N) + "Like `delete-backward-char', insert whitespace at field end in tables. +When deleting backwards, in tables this function will insert whitespace in +front of the next \"|\" separator, to keep the table aligned. The table will +still be marked for re-alignment if the field did fill the entire column, +because, in this case the deletion might narrow the column." + (interactive "p") + (save-match-data + (org-check-before-invisible-edit 'delete-backward) + (if (and (org-at-table-p) + (eq N 1) + (not (org-region-active-p)) + (string-match "|" (buffer-substring (point-at-bol) (point))) + (looking-at ".*?|")) + (let ((pos (point)) + (noalign (looking-at "[^|\n\r]* |")) + (c org-table-may-need-update)) + (backward-delete-char N) + (unless overwrite-mode + (skip-chars-forward "^|") + (insert " ") + (goto-char (1- pos))) + ;; noalign: if there were two spaces at the end, this field + ;; does not determine the width of the column. + (when noalign (setq org-table-may-need-update c))) + (backward-delete-char N) + (org-fix-tags-on-the-fly)))) + +(defun org-delete-char (N) + "Like `delete-char', but insert whitespace at field end in tables. +When deleting characters, in tables this function will insert whitespace in +front of the next \"|\" separator, to keep the table aligned. The table will +still be marked for re-alignment if the field did fill the entire column, +because, in this case the deletion might narrow the column." + (interactive "p") + (save-match-data + (org-check-before-invisible-edit 'delete) + (if (and (org-at-table-p) + (not (bolp)) + (not (= (char-after) ?|)) + (eq N 1)) + (if (looking-at ".*?|") + (let ((pos (point)) + (noalign (looking-at "[^|\n\r]* |")) + (c org-table-may-need-update)) + (replace-match + (concat (substring (match-string 0) 1 -1) " |") nil t) + (goto-char pos) + ;; noalign: if there were two spaces at the end, this field + ;; does not determine the width of the column. + (when noalign (setq org-table-may-need-update c))) + (delete-char N)) + (delete-char N) + (org-fix-tags-on-the-fly)))) + +;; Make `delete-selection-mode' work with Org mode and Orgtbl mode +(put 'org-self-insert-command 'delete-selection + (lambda () + (not (run-hook-with-args-until-success + 'self-insert-uses-region-functions)))) +(put 'orgtbl-self-insert-command 'delete-selection + (lambda () + (not (run-hook-with-args-until-success + 'self-insert-uses-region-functions)))) +(put 'org-delete-char 'delete-selection 'supersede) +(put 'org-delete-backward-char 'delete-selection 'supersede) +(put 'org-yank 'delete-selection 'yank) + +;; Make `flyspell-mode' delay after some commands +(put 'org-self-insert-command 'flyspell-delayed t) +(put 'orgtbl-self-insert-command 'flyspell-delayed t) +(put 'org-delete-char 'flyspell-delayed t) +(put 'org-delete-backward-char 'flyspell-delayed t) + +;; Make pabbrev-mode expand after Org mode commands +(put 'org-self-insert-command 'pabbrev-expand-after-command t) +(put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t) + +(defun org-transpose-words () + "Transpose words for Org. +This uses the `org-mode-transpose-word-syntax-table' syntax +table, which interprets characters in `org-emphasis-alist' as +word constituents." + (interactive) + (with-syntax-table org-mode-transpose-word-syntax-table + (call-interactively 'transpose-words))) +(org-remap org-mode-map 'transpose-words 'org-transpose-words) + +(defvar org-ctrl-c-ctrl-c-hook nil + "Hook for functions attaching themselves to `C-c C-c'. + +This can be used to add additional functionality to the C-c C-c +key which executes context-dependent commands. This hook is run +before any other test, while `org-ctrl-c-ctrl-c-final-hook' is +run after the last test. + +Each function will be called with no arguments. The function +must check if the context is appropriate for it to act. If yes, +it should do its thing and then return a non-nil value. If the +context is wrong, just do nothing and return nil.") + +(defvar org-ctrl-c-ctrl-c-final-hook nil + "Hook for functions attaching themselves to `C-c C-c'. + +This can be used to add additional functionality to the C-c C-c +key which executes context-dependent commands. This hook is run +after any other test, while `org-ctrl-c-ctrl-c-hook' is run +before the first test. + +Each function will be called with no arguments. The function +must check if the context is appropriate for it to act. If yes, +it should do its thing and then return a non-nil value. If the +context is wrong, just do nothing and return nil.") + +(defvar org-tab-first-hook nil + "Hook for functions to attach themselves to TAB. +See `org-ctrl-c-ctrl-c-hook' for more information. +This hook runs as the first action when TAB is pressed, even before +`org-cycle' messes around with the `outline-regexp' to cater for +inline tasks and plain list item folding. +If any function in this hook returns t, any other actions that +would have been caused by TAB (such as table field motion or visibility +cycling) will not occur.") + +(defvar org-tab-after-check-for-table-hook nil + "Hook for functions to attach themselves to TAB. +See `org-ctrl-c-ctrl-c-hook' for more information. +This hook runs after it has been established that the cursor is not in a +table, but before checking if the cursor is in a headline or if global cycling +should be done. +If any function in this hook returns t, not other actions like visibility +cycling will be done.") + +(defvar org-tab-after-check-for-cycling-hook nil + "Hook for functions to attach themselves to TAB. +See `org-ctrl-c-ctrl-c-hook' for more information. +This hook runs after it has been established that not table field motion and +not visibility should be done because of current context. This is probably +the place where a package like yasnippets can hook in.") + +(defvar org-tab-before-tab-emulation-hook nil + "Hook for functions to attach themselves to TAB. +See `org-ctrl-c-ctrl-c-hook' for more information. +This hook runs after every other options for TAB have been exhausted, but +before indentation and \t insertion takes place.") + +(defvar org-metaleft-hook nil + "Hook for functions attaching themselves to `M-left'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-metaright-hook nil + "Hook for functions attaching themselves to `M-right'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-metaup-hook nil + "Hook for functions attaching themselves to `M-up'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-metadown-hook nil + "Hook for functions attaching themselves to `M-down'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftmetaleft-hook nil + "Hook for functions attaching themselves to `M-S-left'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftmetaright-hook nil + "Hook for functions attaching themselves to `M-S-right'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftmetaup-hook nil + "Hook for functions attaching themselves to `M-S-up'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftmetadown-hook nil + "Hook for functions attaching themselves to `M-S-down'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-metareturn-hook nil + "Hook for functions attaching themselves to `M-RET'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftup-hook nil + "Hook for functions attaching themselves to `S-up'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftup-final-hook nil + "Hook for functions attaching themselves to `S-up'. +This one runs after all other options except shift-select have been excluded. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftdown-hook nil + "Hook for functions attaching themselves to `S-down'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftdown-final-hook nil + "Hook for functions attaching themselves to `S-down'. +This one runs after all other options except shift-select have been excluded. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftleft-hook nil + "Hook for functions attaching themselves to `S-left'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftleft-final-hook nil + "Hook for functions attaching themselves to `S-left'. +This one runs after all other options except shift-select have been excluded. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftright-hook nil + "Hook for functions attaching themselves to `S-right'. +See `org-ctrl-c-ctrl-c-hook' for more information.") +(defvar org-shiftright-final-hook nil + "Hook for functions attaching themselves to `S-right'. +This one runs after all other options except shift-select have been excluded. +See `org-ctrl-c-ctrl-c-hook' for more information.") + +(defun org-modifier-cursor-error () + "Throw an error, a modified cursor command was applied in wrong context." + (user-error "This command is active in special context like tables, headlines or items")) + +(defun org-shiftselect-error () + "Throw an error because Shift-Cursor command was applied in wrong context." + (if (and (boundp 'shift-select-mode) shift-select-mode) + (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'") + (user-error "This command works only in special context like headlines or timestamps"))) + +(defun org-call-for-shift-select (cmd) + (let ((this-command-keys-shift-translated t)) + (call-interactively cmd))) + +(defun org-shifttab (&optional arg) + "Global visibility cycling or move to previous table field. +Call `org-table-previous-field' within a table. +When ARG is nil, cycle globally through visibility states. +When ARG is a numeric prefix, show contents of this level." + (interactive "P") + (cond + ((org-at-table-p) (call-interactively 'org-table-previous-field)) + ((integerp arg) + (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg))) + (message "Content view to level: %d" arg) + (org-content (prefix-numeric-value arg2)) + (org-cycle-show-empty-lines t) + (setq org-cycle-global-status 'overview))) + (t (call-interactively 'org-global-cycle)))) + +(defun org-shiftmetaleft () + "Promote subtree or delete table column. +Calls `org-promote-subtree', `org-outdent-item-tree', or +`org-table-delete-column', depending on context. See the +individual commands for more information." + (interactive) + (cond + ((run-hook-with-args-until-success 'org-shiftmetaleft-hook)) + ((org-at-table-p) (call-interactively 'org-table-delete-column)) + ((org-at-heading-p) (call-interactively 'org-promote-subtree)) + ((if (not (org-region-active-p)) (org-at-item-p) + (save-excursion (goto-char (region-beginning)) + (org-at-item-p))) + (call-interactively 'org-outdent-item-tree)) + (t (org-modifier-cursor-error)))) + +(defun org-shiftmetaright () + "Demote subtree or insert table column. +Calls `org-demote-subtree', `org-indent-item-tree', or +`org-table-insert-column', depending on context. See the +individual commands for more information." + (interactive) + (cond + ((run-hook-with-args-until-success 'org-shiftmetaright-hook)) + ((org-at-table-p) (call-interactively 'org-table-insert-column)) + ((org-at-heading-p) (call-interactively 'org-demote-subtree)) + ((if (not (org-region-active-p)) (org-at-item-p) + (save-excursion (goto-char (region-beginning)) + (org-at-item-p))) + (call-interactively 'org-indent-item-tree)) + (t (org-modifier-cursor-error)))) + +(defun org-shiftmetaup (&optional _arg) + "Drag the line at point up. +In a table, kill the current row. +On a clock timestamp, update the value of the timestamp like `S-<up>' +but also adjust the previous clocked item in the clock history. +Everywhere else, drag the line at point up." + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-shiftmetaup-hook)) + ((org-at-table-p) (call-interactively 'org-table-kill-row)) + ((org-at-clock-log-p) (let ((org-clock-adjust-closest t)) + (call-interactively 'org-timestamp-up))) + (t (call-interactively 'org-drag-line-backward)))) + +(defun org-shiftmetadown (&optional _arg) + "Drag the line at point down. +In a table, insert an empty row at the current line. +On a clock timestamp, update the value of the timestamp like `S-<down>' +but also adjust the previous clocked item in the clock history. +Everywhere else, drag the line at point down." + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-shiftmetadown-hook)) + ((org-at-table-p) (call-interactively 'org-table-insert-row)) + ((org-at-clock-log-p) (let ((org-clock-adjust-closest t)) + (call-interactively 'org-timestamp-down))) + (t (call-interactively 'org-drag-line-forward)))) + +(defsubst org-hidden-tree-error () + (user-error + "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>")) + +(defun org-metaleft (&optional _arg) + "Promote heading, list item at point or move table column left. + +Calls `org-do-promote', `org-outdent-item' or `org-table-move-column', +depending on context. With no specific context, calls the Emacs +default `backward-word'. See the individual commands for more +information. + +This function runs the hook `org-metaleft-hook' as a first step, +and returns at first non-nil value." + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-metaleft-hook)) + ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left)) + ((org-with-limited-levels + (or (org-at-heading-p) + (and (org-region-active-p) + (save-excursion + (goto-char (region-beginning)) + (org-at-heading-p))))) + (when (org-check-for-hidden 'headlines) (org-hidden-tree-error)) + (call-interactively 'org-do-promote)) + ;; At an inline task. + ((org-at-heading-p) + (call-interactively 'org-inlinetask-promote)) + ((or (org-at-item-p) + (and (org-region-active-p) + (save-excursion + (goto-char (region-beginning)) + (org-at-item-p)))) + (when (org-check-for-hidden 'items) (org-hidden-tree-error)) + (call-interactively 'org-outdent-item)) + (t (call-interactively 'backward-word)))) + +(defun org-metaright (&optional _arg) + "Demote heading, list item at point or move table column right. + +In front of a drawer or a block keyword, indent it correctly. + +Calls `org-do-demote', `org-indent-item', `org-table-move-column', +`org-indent-drawer' or `org-indent-block' depending on context. +With no specific context, calls the Emacs default `forward-word'. +See the individual commands for more information. + +This function runs the hook `org-metaright-hook' as a first step, +and returns at first non-nil value." + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-metaright-hook)) + ((org-at-table-p) (call-interactively 'org-table-move-column)) + ((org-at-drawer-p) (call-interactively 'org-indent-drawer)) + ((org-at-block-p) (call-interactively 'org-indent-block)) + ((org-with-limited-levels + (or (org-at-heading-p) + (and (org-region-active-p) + (save-excursion + (goto-char (region-beginning)) + (org-at-heading-p))))) + (when (org-check-for-hidden 'headlines) (org-hidden-tree-error)) + (call-interactively 'org-do-demote)) + ;; At an inline task. + ((org-at-heading-p) + (call-interactively 'org-inlinetask-demote)) + ((or (org-at-item-p) + (and (org-region-active-p) + (save-excursion + (goto-char (region-beginning)) + (org-at-item-p)))) + (when (org-check-for-hidden 'items) (org-hidden-tree-error)) + (call-interactively 'org-indent-item)) + (t (call-interactively 'forward-word)))) + +(defun org-check-for-hidden (what) + "Check if there are hidden headlines/items in the current visual line. +WHAT can be either `headlines' or `items'. If the current line is +an outline or item heading and it has a folded subtree below it, +this function returns t, nil otherwise." + (let ((re (cond + ((eq what 'headlines) org-outline-regexp-bol) + ((eq what 'items) (org-item-beginning-re)) + (t (error "This should not happen")))) + beg end) + (save-excursion + (catch 'exit + (unless (org-region-active-p) + (setq beg (point-at-bol)) + (beginning-of-line 2) + (while (and (not (eobp)) ;; this is like `next-line' + (get-char-property (1- (point)) 'invisible)) + (beginning-of-line 2)) + (setq end (point)) + (goto-char beg) + (goto-char (point-at-eol)) + (setq end (max end (point))) + (while (re-search-forward re end t) + (when (get-char-property (match-beginning 0) 'invisible) + (throw 'exit t)))) + nil)))) + +(defun org-metaup (&optional _arg) + "Move subtree up or move table row up. +Calls `org-move-subtree-up' or `org-table-move-row' or +`org-move-item-up', depending on context. See the individual commands +for more information." + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-metaup-hook)) + ((org-region-active-p) + (let* ((a (min (region-beginning) (region-end))) + (b (1- (max (region-beginning) (region-end)))) + (c (save-excursion (goto-char a) + (move-beginning-of-line 0))) + (d (save-excursion (goto-char a) + (move-end-of-line 0) (point)))) + (transpose-regions a b c d) + (goto-char c))) + ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up)) + ((org-at-heading-p) (call-interactively 'org-move-subtree-up)) + ((org-at-item-p) (call-interactively 'org-move-item-up)) + (t (org-drag-element-backward)))) + +(defun org-metadown (&optional _arg) + "Move subtree down or move table row down. +Calls `org-move-subtree-down' or `org-table-move-row' or +`org-move-item-down', depending on context. See the individual +commands for more information." + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-metadown-hook)) + ((org-region-active-p) + (let* ((a (min (region-beginning) (region-end))) + (b (max (region-beginning) (region-end))) + (c (save-excursion (goto-char b) + (move-beginning-of-line 1))) + (d (save-excursion (goto-char b) + (move-end-of-line 1) (1+ (point))))) + (transpose-regions a b c d) + (goto-char d))) + ((org-at-table-p) (call-interactively 'org-table-move-row)) + ((org-at-heading-p) (call-interactively 'org-move-subtree-down)) + ((org-at-item-p) (call-interactively 'org-move-item-down)) + (t (org-drag-element-forward)))) + +(defun org-shiftup (&optional arg) + "Increase item in timestamp or increase priority of current headline. +Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item', +depending on context. See the individual commands for more information." + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-shiftup-hook)) + ((and org-support-shift-select (org-region-active-p)) + (org-call-for-shift-select 'previous-line)) + ((org-at-timestamp-p 'lax) + (call-interactively (if org-edit-timestamp-down-means-later + 'org-timestamp-down 'org-timestamp-up))) + ((and (not (eq org-support-shift-select 'always)) + org-enable-priority-commands + (org-at-heading-p)) + (call-interactively 'org-priority-up)) + ((and (not org-support-shift-select) (org-at-item-p)) + (call-interactively 'org-previous-item)) + ((org-clocktable-try-shift 'up arg)) + ((run-hook-with-args-until-success 'org-shiftup-final-hook)) + (org-support-shift-select + (org-call-for-shift-select 'previous-line)) + (t (org-shiftselect-error)))) + +(defun org-shiftdown (&optional arg) + "Decrease item in timestamp or decrease priority of current headline. +Calls `org-timestamp-down' or `org-priority-down', or `org-next-item' +depending on context. See the individual commands for more information." + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-shiftdown-hook)) + ((and org-support-shift-select (org-region-active-p)) + (org-call-for-shift-select 'next-line)) + ((org-at-timestamp-p 'lax) + (call-interactively (if org-edit-timestamp-down-means-later + 'org-timestamp-up 'org-timestamp-down))) + ((and (not (eq org-support-shift-select 'always)) + org-enable-priority-commands + (org-at-heading-p)) + (call-interactively 'org-priority-down)) + ((and (not org-support-shift-select) (org-at-item-p)) + (call-interactively 'org-next-item)) + ((org-clocktable-try-shift 'down arg)) + ((run-hook-with-args-until-success 'org-shiftdown-final-hook)) + (org-support-shift-select + (org-call-for-shift-select 'next-line)) + (t (org-shiftselect-error)))) + +(defun org-shiftright (&optional arg) + "Cycle the thing at point or in the current line, depending on context. +Depending on context, this does one of the following: + +- switch a timestamp at point one day into the future +- on a headline, switch to the next TODO keyword. +- on an item, switch entire list to the next bullet type +- on a property line, switch to the next allowed value +- on a clocktable definition line, move time block into the future" + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-shiftright-hook)) + ((and org-support-shift-select (org-region-active-p)) + (org-call-for-shift-select 'forward-char)) + ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day)) + ((and (not (eq org-support-shift-select 'always)) + (org-at-heading-p)) + (let ((org-inhibit-logging + (not org-treat-S-cursor-todo-selection-as-state-change)) + (org-inhibit-blocking + (not org-treat-S-cursor-todo-selection-as-state-change))) + (org-call-with-arg 'org-todo 'right))) + ((or (and org-support-shift-select + (not (eq org-support-shift-select 'always)) + (org-at-item-bullet-p)) + (and (not org-support-shift-select) (org-at-item-p))) + (org-call-with-arg 'org-cycle-list-bullet nil)) + ((and (not (eq org-support-shift-select 'always)) + (org-at-property-p)) + (call-interactively 'org-property-next-allowed-value)) + ((org-clocktable-try-shift 'right arg)) + ((run-hook-with-args-until-success 'org-shiftright-final-hook)) + (org-support-shift-select + (org-call-for-shift-select 'forward-char)) + (t (org-shiftselect-error)))) + +(defun org-shiftleft (&optional arg) + "Cycle the thing at point or in the current line, depending on context. +Depending on context, this does one of the following: + +- switch a timestamp at point one day into the past +- on a headline, switch to the previous TODO keyword. +- on an item, switch entire list to the previous bullet type +- on a property line, switch to the previous allowed value +- on a clocktable definition line, move time block into the past" + (interactive "P") + (cond + ((run-hook-with-args-until-success 'org-shiftleft-hook)) + ((and org-support-shift-select (org-region-active-p)) + (org-call-for-shift-select 'backward-char)) + ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day)) + ((and (not (eq org-support-shift-select 'always)) + (org-at-heading-p)) + (let ((org-inhibit-logging + (not org-treat-S-cursor-todo-selection-as-state-change)) + (org-inhibit-blocking + (not org-treat-S-cursor-todo-selection-as-state-change))) + (org-call-with-arg 'org-todo 'left))) + ((or (and org-support-shift-select + (not (eq org-support-shift-select 'always)) + (org-at-item-bullet-p)) + (and (not org-support-shift-select) (org-at-item-p))) + (org-call-with-arg 'org-cycle-list-bullet 'previous)) + ((and (not (eq org-support-shift-select 'always)) + (org-at-property-p)) + (call-interactively 'org-property-previous-allowed-value)) + ((org-clocktable-try-shift 'left arg)) + ((run-hook-with-args-until-success 'org-shiftleft-final-hook)) + (org-support-shift-select + (org-call-for-shift-select 'backward-char)) + (t (org-shiftselect-error)))) + +(defun org-shiftcontrolright () + "Switch to next TODO set." + (interactive) + (cond + ((and org-support-shift-select (org-region-active-p)) + (org-call-for-shift-select 'forward-word)) + ((and (not (eq org-support-shift-select 'always)) + (org-at-heading-p)) + (org-call-with-arg 'org-todo 'nextset)) + (org-support-shift-select + (org-call-for-shift-select 'forward-word)) + (t (org-shiftselect-error)))) + +(defun org-shiftcontrolleft () + "Switch to previous TODO set." + (interactive) + (cond + ((and org-support-shift-select (org-region-active-p)) + (org-call-for-shift-select 'backward-word)) + ((and (not (eq org-support-shift-select 'always)) + (org-at-heading-p)) + (org-call-with-arg 'org-todo 'previousset)) + (org-support-shift-select + (org-call-for-shift-select 'backward-word)) + (t (org-shiftselect-error)))) + +(defun org-shiftcontrolup (&optional n) + "Change timestamps synchronously up in CLOCK log lines. +Optional argument N tells to change by that many units." + (interactive "P") + (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax)) + (let (org-support-shift-select) + (org-clock-timestamps-up n)) + (user-error "Not at a clock log"))) + +(defun org-shiftcontroldown (&optional n) + "Change timestamps synchronously down in CLOCK log lines. +Optional argument N tells to change by that many units." + (interactive "P") + (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax)) + (let (org-support-shift-select) + (org-clock-timestamps-down n)) + (user-error "Not at a clock log"))) + +(defun org-increase-number-at-point (&optional inc) + "Increment the number at point. +With an optional prefix numeric argument INC, increment using +this numeric value." + (interactive "p") + (if (not (number-at-point)) + (user-error "Not on a number") + (unless inc (setq inc 1)) + (let ((pos (point)) + (beg (skip-chars-backward "-+^/*0-9eE.")) + (end (skip-chars-forward "-+^/*0-9eE^.")) nap) + (setq nap (buffer-substring-no-properties + (+ pos beg) (+ pos beg end))) + (delete-region (+ pos beg) (+ pos beg end)) + (insert (calc-eval (concat (number-to-string inc) "+" nap)))) + (when (org-at-table-p) + (org-table-align) + (org-table-end-of-field 1)))) + +(defun org-decrease-number-at-point (&optional inc) + "Decrement the number at point. +With an optional prefix numeric argument INC, decrement using +this numeric value." + (interactive "p") + (org-increase-number-at-point (- (or inc 1)))) + +(defun org-ctrl-c-ret () + "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context." + (interactive) + (cond + ((org-at-table-p) (call-interactively 'org-table-hline-and-move)) + (t (call-interactively 'org-insert-heading)))) + +(defun org-find-visible () + (let ((s (point))) + (while (and (not (= (point-max) (setq s (next-overlay-change s)))) + (get-char-property s 'invisible))) + s)) +(defun org-find-invisible () + (let ((s (point))) + (while (and (not (= (point-max) (setq s (next-overlay-change s)))) + (not (get-char-property s 'invisible)))) + s)) + +(defun org-copy-visible (beg end) + "Copy the visible parts of the region." + (interactive "r") + (let ((result "")) + (while (/= beg end) + (when (get-char-property beg 'invisible) + (setq beg (next-single-char-property-change beg 'invisible nil end))) + (let ((next (next-single-char-property-change beg 'invisible nil end))) + (setq result (concat result (buffer-substring beg next))) + (setq beg next))) + (kill-new result))) + +(defun org-copy-special () + "Copy region in table or copy current subtree. +Calls `org-table-copy-region' or `org-copy-subtree', depending on +context. See the individual commands for more information." + (interactive) + (call-interactively + (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree))) + +(defun org-cut-special () + "Cut region in table or cut current subtree. +Calls `org-table-cut-region' or `org-cut-subtree', depending on +context. See the individual commands for more information." + (interactive) + (call-interactively + (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree))) + +(defun org-paste-special (arg) + "Paste rectangular region into table, or past subtree relative to level. +Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context. +See the individual commands for more information." + (interactive "P") + (if (org-at-table-p) + (org-table-paste-rectangle) + (org-paste-subtree arg))) + +(defun org-edit-special (&optional arg) + "Call a special editor for the element at point. +When at a table, call the formula editor with `org-table-edit-formulas'. +When in a source code block, call `org-edit-src-code'. +When in a fixed-width region, call `org-edit-fixed-width-region'. +When in an export block, call `org-edit-export-block'. +When in a LaTeX environment, call `org-edit-latex-environment'. +When at an #+INCLUDE keyword, visit the included file. +When at a footnote reference, call `org-edit-footnote-reference' +On a link, call `ffap' to visit the link at point. +Otherwise, return a user error." + (interactive "P") + (let ((element (org-element-at-point))) + (barf-if-buffer-read-only) + (pcase (org-element-type element) + (`src-block + (if (not arg) (org-edit-src-code) + (let* ((info (org-babel-get-src-block-info)) + (lang (nth 0 info)) + (params (nth 2 info)) + (session (cdr (assq :session params)))) + (if (not session) (org-edit-src-code) + ;; At a src-block with a session and function called with + ;; an ARG: switch to the buffer related to the inferior + ;; process. + (switch-to-buffer + (funcall (intern (concat "org-babel-prep-session:" lang)) + session params)))))) + (`keyword + (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE")) + (org-open-link-from-string + (format "[[%s]]" + (expand-file-name + (let ((value (org-element-property :value element))) + (cond ((org-file-url-p value) + (user-error "The file is specified as a URL, cannot be edited")) + ((not (org-string-nw-p value)) + (user-error "No file to edit")) + ((string-match "\\`\"\\(.*?\\)\"" value) + (match-string 1 value)) + ((string-match "\\`[^ \t\"]\\S-*" value) + (match-string 0 value)) + (t (user-error "No valid file specified"))))))) + (user-error "No special environment to edit here"))) + (`table + (if (eq (org-element-property :type element) 'table.el) + (org-edit-table.el) + (call-interactively 'org-table-edit-formulas))) + ;; Only Org tables contain `table-row' type elements. + (`table-row (call-interactively 'org-table-edit-formulas)) + (`example-block (org-edit-src-code)) + (`export-block (org-edit-export-block)) + (`fixed-width (org-edit-fixed-width-region)) + (`latex-environment (org-edit-latex-environment)) + (_ + ;; No notable element at point. Though, we may be at a link or + ;; a footnote reference, which are objects. Thus, scan deeper. + (let ((context (org-element-context element))) + (pcase (org-element-type context) + (`footnote-reference (org-edit-footnote-reference)) + (`inline-src-block (org-edit-inline-src-code)) + (`link (call-interactively #'ffap)) + (_ (user-error "No special environment to edit here")))))))) + +(defvar org-table-coordinate-overlays) ; defined in org-table.el +(defun org-ctrl-c-ctrl-c (&optional arg) + "Set tags in headline, or update according to changed information at point. + +This command does many different things, depending on context: + +- If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location, + this is what we do. + +- If the cursor is on a statistics cookie, update it. + +- If the cursor is in a headline, prompt for tags and insert them + into the current line, aligned to `org-tags-column'. When called + with prefix arg, realign all tags in the current buffer. + +- If the cursor is in one of the special #+KEYWORD lines, this + triggers scanning the buffer for these lines and updating the + information. + +- If the cursor is inside a table, realign the table. This command + works even if the automatic table editor has been turned off. + +- If the cursor is on a #+TBLFM line, re-apply the formulas to + the entire table. + +- If the cursor is at a footnote reference or definition, jump to + the corresponding definition or references, respectively. + +- If the cursor is a the beginning of a dynamic block, update it. + +- If the current buffer is a capture buffer, close note and file it. + +- If the cursor is on a <<<target>>>, update radio targets and + corresponding links in this buffer. + +- If the cursor is on a numbered item in a plain list, renumber the + ordered list. + +- If the cursor is on a checkbox, toggle it. + +- If the cursor is on a code block, evaluate it. The variable + `org-confirm-babel-evaluate' can be used to control prompting + before code block evaluation, by default every code block + evaluation requires confirmation. Code block evaluation can be + inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'." + (interactive "P") + (cond + ((or (bound-and-true-p org-clock-overlays) org-occur-highlights) + (when (boundp 'org-clock-overlays) (org-clock-remove-overlays)) + (org-remove-occur-highlights) + (message "Temporary highlights/overlays removed from current buffer")) + ((and (local-variable-p 'org-finish-function) + (fboundp org-finish-function)) + (funcall org-finish-function)) + ((org-babel-hash-at-point)) + ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook)) + (t + (let* ((context + (org-element-lineage + (org-element-context) + ;; Limit to supported contexts. + '(babel-call clock dynamic-block footnote-definition + footnote-reference inline-babel-call inline-src-block + inlinetask item keyword node-property paragraph + plain-list planning property-drawer radio-target + src-block statistics-cookie table table-cell table-row + timestamp) + t)) + (type (org-element-type context))) + ;; For convenience: at the first line of a paragraph on the same + ;; line as an item, apply function on that item instead. + (when (eq type 'paragraph) + (let ((parent (org-element-property :parent context))) + (when (and (eq (org-element-type parent) 'item) + (= (line-beginning-position) + (org-element-property :begin parent))) + (setq context parent) + (setq type 'item)))) + ;; Act according to type of element or object at point. + ;; + ;; Do nothing on a blank line, except if it is contained in + ;; a src block. Hence, we first check if point is in such + ;; a block and then if it is at a blank line. + (pcase type + ((or `inline-src-block `src-block) + (unless org-babel-no-eval-on-ctrl-c-ctrl-c + (org-babel-eval-wipe-error-buffer) + (org-babel-execute-src-block + current-prefix-arg (org-babel-get-src-block-info nil context)))) + ((guard (org-match-line "[ \t]*$")) + (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) + (user-error + (substitute-command-keys + "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here")))) + ((or `babel-call `inline-babel-call) + (let ((info (org-babel-lob-get-info context))) + (when info (org-babel-execute-src-block nil info)))) + (`clock (org-clock-update-time-maybe)) + (`dynamic-block + (save-excursion + (goto-char (org-element-property :post-affiliated context)) + (org-update-dblock))) + (`footnote-definition + (goto-char (org-element-property :post-affiliated context)) + (call-interactively 'org-footnote-action)) + (`footnote-reference (call-interactively #'org-footnote-action)) + ((or `headline `inlinetask) + (save-excursion (goto-char (org-element-property :begin context)) + (call-interactively #'org-set-tags))) + (`item + ;; At an item: `C-u C-u' sets checkbox to "[-]" + ;; unconditionally, whereas `C-u' will toggle its presence. + ;; Without a universal argument, if the item has a checkbox, + ;; toggle it. Otherwise repair the list. + (let* ((box (org-element-property :checkbox context)) + (struct (org-element-property :structure context)) + (old-struct (copy-tree struct)) + (parents (org-list-parents-alist struct)) + (prevs (org-list-prevs-alist struct)) + (orderedp (org-not-nil (org-entry-get nil "ORDERED")))) + (org-list-set-checkbox + (org-element-property :begin context) struct + (cond ((equal arg '(16)) "[-]") + ((and (not box) (equal arg '(4))) "[ ]") + ((or (not box) (equal arg '(4))) nil) + ((eq box 'on) "[ ]") + (t "[X]"))) + ;; Mimic `org-list-write-struct' but with grabbing a return + ;; value from `org-list-struct-fix-box'. + (org-list-struct-fix-ind struct parents 2) + (org-list-struct-fix-item-end struct) + (org-list-struct-fix-bul struct prevs) + (org-list-struct-fix-ind struct parents) + (let ((block-item + (org-list-struct-fix-box struct parents prevs orderedp))) + (if (and box (equal struct old-struct)) + (if (equal arg '(16)) + (message "Checkboxes already reset") + (user-error "Cannot toggle this checkbox: %s" + (if (eq box 'on) + "all subitems checked" + "unchecked subitems"))) + (org-list-struct-apply-struct struct old-struct) + (org-update-checkbox-count-maybe)) + (when block-item + (message "Checkboxes were removed due to empty box at line %d" + (org-current-line block-item)))))) + (`keyword + (let ((org-inhibit-startup-visibility-stuff t) + (org-startup-align-all-tables nil)) + (when (boundp 'org-table-coordinate-overlays) + (mapc #'delete-overlay org-table-coordinate-overlays) + (setq org-table-coordinate-overlays nil)) + (org-save-outline-visibility 'use-markers (org-mode-restart))) + (message "Local setup has been refreshed")) + (`plain-list + ;; At a plain list, with a double C-u argument, set + ;; checkboxes of each item to "[-]", whereas a single one + ;; will toggle their presence according to the state of the + ;; first item in the list. Without an argument, repair the + ;; list. + (let* ((begin (org-element-property :contents-begin context)) + (beginm (move-marker (make-marker) begin)) + (struct (org-element-property :structure context)) + (old-struct (copy-tree struct)) + (first-box (save-excursion + (goto-char begin) + (looking-at org-list-full-item-re) + (match-string-no-properties 3))) + (new-box (cond ((equal arg '(16)) "[-]") + ((equal arg '(4)) (unless first-box "[ ]")) + ((equal first-box "[X]") "[ ]") + (t "[X]")))) + (cond + (arg + (dolist (pos + (org-list-get-all-items + begin struct (org-list-prevs-alist struct))) + (org-list-set-checkbox pos struct new-box))) + ((and first-box (eq (point) begin)) + ;; For convenience, when point is at bol on the first + ;; item of the list and no argument is provided, simply + ;; toggle checkbox of that item, if any. + (org-list-set-checkbox begin struct new-box))) + (org-list-write-struct + struct (org-list-parents-alist struct) old-struct) + (org-update-checkbox-count-maybe) + (save-excursion (goto-char beginm) (org-list-send-list 'maybe)))) + ((or `property-drawer `node-property) + (call-interactively #'org-property-action)) + (`radio-target + (call-interactively #'org-update-radio-target-regexp)) + (`statistics-cookie + (call-interactively #'org-update-statistics-cookies)) + ((or `table `table-cell `table-row) + ;; At a table, recalculate every field and align it. Also + ;; send the table if necessary. If the table has + ;; a `table.el' type, just give up. At a table row or cell, + ;; maybe recalculate line but always align table. + (if (eq (org-element-property :type context) 'table.el) + (message "%s" (substitute-command-keys "\\<org-mode-map>\ +Use `\\[org-edit-special]' to edit table.el tables")) + (if (or (eq type 'table) + ;; Check if point is at a TBLFM line. + (and (eq type 'table-row) + (= (point) (org-element-property :end context)))) + (save-excursion + (if (org-at-TBLFM-p) + (progn (require 'org-table) + (org-table-calc-current-TBLFM)) + (goto-char (org-element-property :contents-begin context)) + (org-call-with-arg 'org-table-recalculate (or arg t)) + (orgtbl-send-table 'maybe))) + (org-table-maybe-eval-formula) + (cond (arg (call-interactively #'org-table-recalculate)) + ((org-table-maybe-recalculate-line)) + (t (org-table-align)))))) + ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax)))) + (org-timestamp-change 0 'day)) + ((and `nil (guard (org-at-heading-p))) + ;; When point is on an unsupported object type, we can miss + ;; the fact that it also is at a heading. Handle it here. + (call-interactively #'org-set-tags)) + ((guard + (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook))) + (_ + (user-error + (substitute-command-keys + "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here")))))))) + +(defun org-mode-restart () + (interactive) + (let ((indent-status (bound-and-true-p org-indent-mode))) + (funcall major-mode) + (hack-local-variables) + (when (and indent-status (not (bound-and-true-p org-indent-mode))) + (org-indent-mode -1)) + (org-reset-file-cache)) + (message "%s restarted" major-mode)) + +(defun org-kill-note-or-show-branches () + "Abort storing current note, or call `outline-show-branches'." + (interactive) + (if (not org-finish-function) + (save-excursion + (save-restriction + (org-narrow-to-subtree) + (org-flag-subtree t) + (call-interactively 'outline-show-branches) + (org-hide-archived-subtrees (point-min) (point-max)))) + (let ((org-note-abort t)) + (funcall org-finish-function)))) + +(defun org-delete-indentation (&optional arg) + "Join current line to previous and fix whitespace at join. + +If previous line is a headline add to headline title. Otherwise +the function calls `delete-indentation'. + +With a non-nil optional argument, join it to the following one." + (interactive "*P") + (if (save-excursion + (beginning-of-line (if arg 1 0)) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp))) + ;; At headline. + (let ((tags-column (when (match-beginning 5) + (save-excursion (goto-char (match-beginning 5)) + (current-column)))) + (string (concat " " (progn (when arg (forward-line 1)) + (org-trim (delete-and-extract-region + (line-beginning-position) + (line-end-position))))))) + (unless (bobp) (delete-region (point) (1- (point)))) + (goto-char (or (match-end 4) + (match-beginning 5) + (match-end 0))) + (skip-chars-backward " \t") + (save-excursion (insert string)) + ;; Adjust alignment of tags. + (cond + ((not tags-column)) ;no tags + (org-auto-align-tags (org-set-tags nil t)) + (t (org--align-tags-here tags-column)))) ;preserve tags column + (delete-indentation arg))) + +(defun org-open-line (n) + "Insert a new row in tables, call `open-line' elsewhere. +If `org-special-ctrl-o' is nil, just call `open-line' everywhere. +As a special case, when a document starts with a table, allow to +call `open-line' on the very first character." + (interactive "*p") + (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p)) + (org-table-insert-row) + (open-line n))) + +(defun org-return (&optional indent) + "Goto next table row or insert a newline. + +Calls `org-table-next-row' or `newline', depending on context. + +When optional INDENT argument is non-nil, call +`newline-and-indent' instead of `newline'. + +When `org-return-follows-link' is non-nil and point is on +a timestamp or a link, call `org-open-at-point'. However, it +will not happen if point is in a table or on a \"dead\" +object (e.g., within a comment). In these case, you need to use +`org-open-at-point' directly." + (interactive) + (let ((context (if org-return-follows-link (org-element-context) + (org-element-at-point)))) + (cond + ;; In a table, call `org-table-next-row'. However, before first + ;; column or after last one, split the table. + ((or (and (eq (org-element-type context) 'table) + (>= (point) (org-element-property :contents-begin context)) + (< (point) (org-element-property :contents-end context))) + (org-element-lineage context '(table-row table-cell) t)) + (if (or (looking-at-p "[ \t]*$") + (save-excursion (skip-chars-backward " \t") (bolp))) + (insert "\n") + (org-table-justify-field-maybe) + (call-interactively #'org-table-next-row))) + ;; On a link or a timestamp, call `org-open-at-point' if + ;; `org-return-follows-link' allows it. Tolerate fuzzy + ;; locations, e.g., in a comment, as `org-open-at-point'. + ((and org-return-follows-link + (or (and (eq 'link (org-element-type context)) + ;; Ensure point is not on the white spaces after + ;; the link. + (let ((origin (point))) + (org-with-point-at (org-element-property :end context) + (skip-chars-backward " \t") + (> (point) origin)))) + (org-in-regexp org-ts-regexp-both nil t) + (org-in-regexp org-tsr-regexp-both nil t) + (org-in-regexp org-any-link-re nil t))) + (call-interactively #'org-open-at-point)) + ;; Insert newline in heading, but preserve tags. + ((and (not (bolp)) + (save-excursion (beginning-of-line) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp)))) + ;; At headline. Split line. However, if point is on keyword, + ;; priority cookie or tags, do not break any of them: add + ;; a newline after the headline instead. + (let ((tags-column (and (match-beginning 5) + (save-excursion (goto-char (match-beginning 5)) + (current-column)))) + (string + (when (and (match-end 4) (org-point-in-group (point) 4)) + (delete-and-extract-region (point) (match-end 4))))) + ;; Adjust tag alignment. + (cond + ((not (and tags-column string))) + (org-auto-align-tags (org-set-tags nil t)) + (t (org--align-tags-here tags-column))) ;preserve tags column + (end-of-line) + (org-show-entry) + (if indent (newline-and-indent) (newline)) + (when string (save-excursion (insert (org-trim string)))))) + ;; In a list, make sure indenting keeps trailing text within. + ((and indent + (not (eolp)) + (org-element-lineage context '(item))) + (let ((trailing-data + (delete-and-extract-region (point) (line-end-position)))) + (newline-and-indent) + (save-excursion (insert trailing-data)))) + (t + ;; Do not auto-fill when point is in an Org property drawer. + (let ((auto-fill-function (and (not (org-at-property-p)) + auto-fill-function))) + (if indent + (newline-and-indent) + (newline))))))) + +(defun org-return-indent () + "Goto next table row or insert a newline and indent. +Calls `org-table-next-row' or `newline-and-indent', depending on +context. See the individual commands for more information." + (interactive) + (org-return t)) + +(defun org-ctrl-c-star () + "Compute table, or change heading status of lines. +Calls `org-table-recalculate' or `org-toggle-heading', +depending on context." + (interactive) + (cond + ((org-at-table-p) + (call-interactively 'org-table-recalculate)) + (t + ;; Convert all lines in region to list items + (call-interactively 'org-toggle-heading)))) + +(defun org-ctrl-c-minus () + "Insert separator line in table or modify bullet status of line. +Also turns a plain line or a region of lines into list items. +Calls `org-table-insert-hline', `org-toggle-item', or +`org-cycle-list-bullet', depending on context." + (interactive) + (cond + ((org-at-table-p) + (call-interactively 'org-table-insert-hline)) + ((org-region-active-p) + (call-interactively 'org-toggle-item)) + ((org-in-item-p) + (call-interactively 'org-cycle-list-bullet)) + (t + (call-interactively 'org-toggle-item)))) + +(defun org-toggle-heading (&optional nstars) + "Convert headings to normal text, or items or text to headings. +If there is no active region, only convert the current line. + +With a `\\[universal-argument]' prefix, convert the whole list at +point into heading. + +In a region: + +- If the first non blank line is a headline, remove the stars + from all headlines in the region. + +- If it is a normal line, turn each and every normal line (i.e., + not an heading or an item) in the region into headings. If you + want to convert only the first line of this region, use one + universal prefix argument. + +- If it is a plain list item, turn all plain list items into headings. + +When converting a line into a heading, the number of stars is chosen +such that the lines become children of the current entry. However, +when a numeric prefix argument is given, its value determines the +number of stars to add." + (interactive "P") + (let ((skip-blanks + (function + ;; Return beginning of first non-blank line, starting from + ;; line at POS. + (lambda (pos) + (save-excursion + (goto-char pos) + (while (org-at-comment-p) (forward-line)) + (skip-chars-forward " \r\t\n") + (point-at-bol))))) + beg end toggled) + ;; Determine boundaries of changes. If a universal prefix has + ;; been given, put the list in a region. If region ends at a bol, + ;; do not consider the last line to be in the region. + + (when (and current-prefix-arg (org-at-item-p)) + (when (listp current-prefix-arg) (setq current-prefix-arg 1)) + (org-mark-element)) + + (if (org-region-active-p) + (setq beg (funcall skip-blanks (region-beginning)) + end (copy-marker (save-excursion + (goto-char (region-end)) + (if (bolp) (point) (point-at-eol))))) + (setq beg (funcall skip-blanks (point-at-bol)) + end (copy-marker (point-at-eol)))) + ;; Ensure inline tasks don't count as headings. + (org-with-limited-levels + (save-excursion + (goto-char beg) + (cond + ;; Case 1. Started at an heading: de-star headings. + ((org-at-heading-p) + (while (< (point) end) + (when (org-at-heading-p t) + (looking-at org-outline-regexp) (replace-match "") + (setq toggled t)) + (forward-line))) + ;; Case 2. Started at an item: change items into headlines. + ;; One star will be added by `org-list-to-subtree'. + ((org-at-item-p) + (while (< (point) end) + (when (org-at-item-p) + ;; Pay attention to cases when region ends before list. + (let* ((struct (org-list-struct)) + (list-end + (min (org-list-get-bottom-point struct) (1+ end)))) + (save-restriction + (narrow-to-region (point) list-end) + (insert (org-list-to-subtree (org-list-to-lisp t)) "\n"))) + (setq toggled t)) + (forward-line))) + ;; Case 3. Started at normal text: make every line an heading, + ;; skipping headlines and items. + (t (let* ((stars + (make-string + (if (numberp nstars) nstars (or (org-current-level) 0)) ?*)) + (add-stars + (cond (nstars "") ; stars from prefix only + ((equal stars "") "*") ; before first heading + (org-odd-levels-only "**") ; inside heading, odd + (t "*"))) ; inside heading, oddeven + (rpl (concat stars add-stars " ")) + (lend (when (listp nstars) (save-excursion (end-of-line) (point))))) + (while (< (point) (if (equal nstars '(4)) lend end)) + (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p))) + (looking-at "\\([ \t]*\\)\\(\\S-\\)")) + (replace-match (concat rpl (match-string 2))) (setq toggled t)) + (forward-line))))))) + (unless toggled (message "Cannot toggle heading from here")))) + +(defun org-meta-return (&optional arg) + "Insert a new heading or wrap a region in a table. +Calls `org-insert-heading', `org-insert-item' or +`org-table-wrap-region', depending on context. When called with +an argument, unconditionally call `org-insert-heading'." + (interactive "P") + (org-check-before-invisible-edit 'insert) + (or (run-hook-with-args-until-success 'org-metareturn-hook) + (call-interactively (cond (arg #'org-insert-heading) + ((org-at-table-p) #'org-table-wrap-region) + ((org-in-item-p) #'org-insert-item) + (t #'org-insert-heading))))) + +;;; Menu entries + +(defsubst org-in-subtree-not-table-p () + "Are we in a subtree and not in a table?" + (and (not (org-before-first-heading-p)) + (not (org-at-table-p)))) + +;; Define the Org mode menus +(easy-menu-define org-tbl-menu org-mode-map "Tbl menu" + '("Tbl" + ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)] + ["Next Field" org-cycle (org-at-table-p)] + ["Previous Field" org-shifttab (org-at-table-p)] + ["Next Row" org-return (org-at-table-p)] + "--" + ["Blank Field" org-table-blank-field (org-at-table-p)] + ["Edit Field" org-table-edit-field (org-at-table-p)] + ["Copy Field from Above" org-table-copy-down (org-at-table-p)] + "--" + ("Column" + ["Move Column Left" org-metaleft (org-at-table-p)] + ["Move Column Right" org-metaright (org-at-table-p)] + ["Delete Column" org-shiftmetaleft (org-at-table-p)] + ["Insert Column" org-shiftmetaright (org-at-table-p)]) + ("Row" + ["Move Row Up" org-metaup (org-at-table-p)] + ["Move Row Down" org-metadown (org-at-table-p)] + ["Delete Row" org-shiftmetaup (org-at-table-p)] + ["Insert Row" org-shiftmetadown (org-at-table-p)] + ["Sort lines in region" org-table-sort-lines (org-at-table-p)] + "--" + ["Insert Hline" org-ctrl-c-minus (org-at-table-p)]) + ("Rectangle" + ["Copy Rectangle" org-copy-special (org-at-table-p)] + ["Cut Rectangle" org-cut-special (org-at-table-p)] + ["Paste Rectangle" org-paste-special (org-at-table-p)] + ["Fill Rectangle" org-table-wrap-region (org-at-table-p)]) + "--" + ("Calculate" + ["Set Column Formula" org-table-eval-formula (org-at-table-p)] + ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="] + ["Edit Formulas" org-edit-special (org-at-table-p)] + "--" + ["Recalculate line" org-table-recalculate (org-at-table-p)] + ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"] + ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"] + "--" + ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)] + "--" + ["Sum Column/Rectangle" org-table-sum + (or (org-at-table-p) (org-region-active-p))] + ["Which Column?" org-table-current-column (org-at-table-p)]) + ["Debug Formulas" + org-table-toggle-formula-debugger + :style toggle :selected (bound-and-true-p org-table-formula-debug)] + ["Show Col/Row Numbers" + org-table-toggle-coordinate-overlays + :style toggle + :selected (bound-and-true-p org-table-overlay-coordinates)] + "--" + ["Create" org-table-create (not (org-at-table-p))] + ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))] + ["Import from File" org-table-import (not (org-at-table-p))] + ["Export to File" org-table-export (org-at-table-p)] + "--" + ["Create/Convert from/to table.el" org-table-create-with-table.el t] + "--" + ("Plot" + ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"] + ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"]))) + +(easy-menu-define org-org-menu org-mode-map "Org menu" + '("Org" + ("Show/Hide" + ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))] + ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))] + ["Sparse Tree..." org-sparse-tree t] + ["Reveal Context" org-reveal t] + ["Show All" outline-show-all t] + "--" + ["Subtree to indirect buffer" org-tree-to-indirect-buffer t]) + "--" + ["New Heading" org-insert-heading t] + ("Navigate Headings" + ["Up" outline-up-heading t] + ["Next" outline-next-visible-heading t] + ["Previous" outline-previous-visible-heading t] + ["Next Same Level" outline-forward-same-level t] + ["Previous Same Level" outline-backward-same-level t] + "--" + ["Jump" org-goto t]) + ("Edit Structure" + ["Refile Subtree" org-refile (org-in-subtree-not-table-p)] + "--" + ["Move Subtree Up" org-metaup (org-at-heading-p)] + ["Move Subtree Down" org-metadown (org-at-heading-p)] + "--" + ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)] + ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)] + ["Paste Subtree" org-paste-special (not (org-at-table-p))] + "--" + ["Clone subtree, shift time" org-clone-subtree-with-time-shift t] + "--" + ["Copy visible text" org-copy-visible t] + "--" + ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)] + ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)] + ["Demote Heading" org-metaright (org-in-subtree-not-table-p)] + ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)] + "--" + ["Sort Region/Children" org-sort t] + "--" + ["Convert to odd levels" org-convert-to-odd-levels t] + ["Convert to odd/even levels" org-convert-to-oddeven-levels t]) + ("Editing" + ["Emphasis..." org-emphasize t] + ["Edit Source Example" org-edit-special t] + "--" + ["Footnote new/jump" org-footnote-action t] + ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"]) + ("Archive" + ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)] + "--" + ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)] + ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)] + ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)] + ) + "--" + ("Hyperlinks" + ["Store Link (Global)" org-store-link t] + ["Find existing link to here" org-occur-link-in-agenda-files t] + ["Insert Link" org-insert-link t] + ["Follow Link" org-open-at-point t] + "--" + ["Next link" org-next-link t] + ["Previous link" org-previous-link t] + "--" + ["Descriptive Links" + org-toggle-link-display + :style radio + :selected org-descriptive-links + ] + ["Literal Links" + org-toggle-link-display + :style radio + :selected (not org-descriptive-links)]) + "--" + ("TODO Lists" + ["TODO/DONE/-" org-todo t] + ("Select keyword" + ["Next keyword" org-shiftright (org-at-heading-p)] + ["Previous keyword" org-shiftleft (org-at-heading-p)] + ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))] + ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))] + ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]) + ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"] + ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"] + "--" + ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies) + :selected org-enforce-todo-dependencies :style toggle :active t] + "Settings for tree at point" + ["Do Children sequentially" org-toggle-ordered-property :style radio + :selected (org-entry-get nil "ORDERED") + :active org-enforce-todo-dependencies :keys "C-c C-x o"] + ["Do Children parallel" org-toggle-ordered-property :style radio + :selected (not (org-entry-get nil "ORDERED")) + :active org-enforce-todo-dependencies :keys "C-c C-x o"] + "--" + ["Set Priority" org-priority t] + ["Priority Up" org-shiftup t] + ["Priority Down" org-shiftdown t] + "--" + ["Get news from all feeds" org-feed-update-all t] + ["Go to the inbox of a feed..." org-feed-goto-inbox t] + ["Customize feeds" (customize-variable 'org-feed-alist) t]) + ("TAGS and Properties" + ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))] + ["Change tag in region" org-change-tag-in-region (org-region-active-p)] + "--" + ["Set property" org-set-property (not (org-before-first-heading-p))] + ["Column view of properties" org-columns t] + ["Insert Column View DBlock" org-columns-insert-dblock t]) + ("Dates and Scheduling" + ["Timestamp" org-time-stamp (not (org-before-first-heading-p))] + ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))] + ("Change Date" + ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)] + ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)] + ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)] + ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)]) + ["Compute Time Range" org-evaluate-time-range t] + ["Schedule Item" org-schedule (not (org-before-first-heading-p))] + ["Deadline" org-deadline (not (org-before-first-heading-p))] + "--" + ["Custom time format" org-toggle-time-stamp-overlays + :style radio :selected org-display-custom-times] + "--" + ["Goto Calendar" org-goto-calendar t] + ["Date from Calendar" org-date-from-calendar t] + "--" + ["Start/Restart Timer" org-timer-start t] + ["Pause/Continue Timer" org-timer-pause-or-continue t] + ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"] + ["Insert Timer String" org-timer t] + ["Insert Timer Item" org-timer-item t]) + ("Logging work" + ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"] + ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"] + ["Clock out" org-clock-out t] + ["Clock cancel" org-clock-cancel t] + "--" + ["Mark as default task" org-clock-mark-default-task t] + ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"] + ["Goto running clock" org-clock-goto t] + "--" + ["Display times" org-clock-display t] + ["Create clock table" org-clock-report t] + "--" + ["Record DONE time" + (progn (setq org-log-done (not org-log-done)) + (message "Switching to %s will %s record a timestamp" + (car org-done-keywords) + (if org-log-done "automatically" "not"))) + :style toggle :selected org-log-done]) + "--" + ["Agenda Command..." org-agenda t] + ["Set Restriction Lock" org-agenda-set-restriction-lock t] + ("File List for Agenda") + ("Special views current file" + ["TODO Tree" org-show-todo-tree t] + ["Check Deadlines" org-check-deadlines t] + ["Tags/Property tree" org-match-sparse-tree t]) + "--" + ["Export/Publish..." org-export-dispatch t] + ("LaTeX" + ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t) + :style toggle :selected org-cdlatex-mode] + ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)] + ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)] + ["Modify math symbol" org-cdlatex-math-modify + (org-inside-LaTeX-fragment-p)] + ["Insert citation" org-reftex-citation t]) + "--" + ("MobileOrg" + ["Push Files and Views" org-mobile-push t] + ["Get Captured and Flagged" org-mobile-pull t] + ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"] + "--" + ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t]) + "--" + ("Documentation" + ["Show Version" org-version t] + ["Info Documentation" org-info t]) + ("Customize" + ["Browse Org Group" org-customize t] + "--" + ["Expand This Menu" org-create-customize-menu + (fboundp 'customize-menu-create)]) + ["Send bug report" org-submit-bug-report t] + "--" + ("Refresh/Reload" + ["Refresh setup current buffer" org-mode-restart t] + ["Reload Org (after update)" org-reload t] + ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"]) + )) + +(defun org-info (&optional node) + "Read documentation for Org in the info system. +With optional NODE, go directly to that node." + (interactive) + (info (format "(org)%s" (or node "")))) + +;;;###autoload +(defun org-submit-bug-report () + "Submit a bug report on Org via mail. + +Don't hesitate to report any problems or inaccurate documentation. + +If you don't have setup sending mail from (X)Emacs, please copy the +output buffer into your mail program, as it gives us important +information about your Org version and configuration." + (interactive) + (require 'reporter) + (defvar reporter-prompt-for-summary-p) + (org-load-modules-maybe) + (org-require-autoloaded-modules) + (let ((reporter-prompt-for-summary-p "Bug report subject: ")) + (reporter-submit-bug-report + "emacs-orgmode@gnu.org" + (org-version nil 'full) + (let (list) + (save-window-excursion + (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*")) + (delete-other-windows) + (erase-buffer) + (insert "You are about to submit a bug report to the Org mailing list. + +We would like to add your full Org and Outline configuration to the +bug report. This greatly simplifies the work of the maintainer and +other experts on the mailing list. + +HOWEVER, some variables you have customized may contain private +information. The names of customers, colleagues, or friends, might +appear in the form of file names, tags, todo states, or search strings. +If you answer yes to the prompt, you might want to check and remove +such private information before sending the email.") + (add-text-properties (point-min) (point-max) '(face org-warning)) + (when (yes-or-no-p "Include your Org configuration ") + (mapatoms + (lambda (v) + (and (boundp v) + (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v)) + (or (and (symbol-value v) + (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v))) + (and + (get v 'custom-type) (get v 'standard-value) + (not (equal (symbol-value v) (eval (car (get v 'standard-value))))))) + (push v list))))) + (kill-buffer (get-buffer "*Warn about privacy*")) + list)) + nil nil + "Remember to cover the basics, that is, what you expected to happen and +what in fact did happen. You don't know how to make a good report? See + + https://orgmode.org/manual/Feedback.html#Feedback + +Your bug report will be posted to the Org mailing list. +------------------------------------------------------------------------") + (save-excursion + (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t) + (replace-match "\\1Bug: \\3 [\\2]"))))) + + +(defun org-install-agenda-files-menu () + (let ((bl (buffer-list))) + (save-excursion + (while bl + (set-buffer (pop bl)) + (when (derived-mode-p 'org-mode) (setq bl nil))) + (when (derived-mode-p 'org-mode) + (easy-menu-change + '("Org") "File List for Agenda" + (append + (list + ["Edit File List" (org-edit-agenda-file-list) t] + ["Add/Move Current File to Front of List" org-agenda-file-to-front t] + ["Remove Current File from List" org-remove-file t] + ["Cycle through agenda files" org-cycle-agenda-files t] + ["Occur in all agenda files" org-occur-in-agenda-files t] + "--") + (mapcar 'org-file-menu-entry + ;; Prevent initialization from failing. + (ignore-errors (org-agenda-files t))))))))) + +;;;; Documentation + +(defun org-require-autoloaded-modules () + (interactive) + (mapc #'require + '(org-agenda org-archive org-attach org-clock org-colview org-id + org-table org-timer))) + +;;;###autoload +(defun org-reload (&optional uncompiled) + "Reload all Org Lisp files. +With prefix arg UNCOMPILED, load the uncompiled versions." + (interactive "P") + (require 'loadhist) + (let* ((org-dir (org-find-library-dir "org")) + (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir)) + (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?") + (remove-re (format "\\`%s\\'" + (regexp-opt '("org" "org-loaddefs" "org-version")))) + (feats (delete-dups + (mapcar 'file-name-sans-extension + (mapcar 'file-name-nondirectory + (delq nil + (mapcar 'feature-file + features)))))) + (lfeat (append + (sort + (setq feats + (delq nil (mapcar + (lambda (f) + (if (and (string-match feature-re f) + (not (string-match remove-re f))) + f nil)) + feats))) + 'string-lessp) + (list "org-version" "org"))) + (load-suffixes (when (boundp 'load-suffixes) load-suffixes)) + (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes)) + load-uncore load-misses) + (setq load-misses + (delq 't + (mapcar (lambda (f) + (or (org-load-noerror-mustsuffix (concat org-dir f)) + (and (string= org-dir contrib-dir) + (org-load-noerror-mustsuffix (concat contrib-dir f))) + (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f)) + (add-to-list 'load-uncore f 'append) + 't) + f)) + lfeat))) + (when load-uncore + (message "The following feature%s found in load-path, please check if that's correct:\n%s" + (if (> (length load-uncore) 1) "s were" " was") load-uncore)) + (if load-misses + (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s" + (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full)) + (message "Successfully reloaded Org\n%s" (org-version nil 'full))))) + +;;;###autoload +(defun org-customize () + "Call the customize function with org as argument." + (interactive) + (org-load-modules-maybe) + (org-require-autoloaded-modules) + (customize-browse 'org)) + +(defun org-create-customize-menu () + "Create a full customization menu for Org mode, insert it into the menu." + (interactive) + (org-load-modules-maybe) + (org-require-autoloaded-modules) + (if (fboundp 'customize-menu-create) + (progn + (easy-menu-change + '("Org") "Customize" + `(["Browse Org group" org-customize t] + "--" + ,(customize-menu-create 'org) + ["Set" Custom-set t] + ["Save" Custom-save t] + ["Reset to Current" Custom-reset-current t] + ["Reset to Saved" Custom-reset-saved t] + ["Reset to Standard Settings" Custom-reset-standard t])) + (message "\"Org\"-menu now contains full customization menu")) + (error "Cannot expand menu (outdated version of cus-edit.el)"))) + +;;;; Miscellaneous stuff + +;;; Generally useful functions + +(defun org-get-at-eol (property n) + "Get text property PROPERTY at the end of line less N characters." + (get-text-property (- (point-at-eol) n) property)) + +(defun org-find-text-property-in-string (prop s) + "Return the first non-nil value of property PROP in string S." + (or (get-text-property 0 prop s) + (get-text-property (or (next-single-property-change 0 prop s) 0) + prop s))) + +(defun org-display-warning (message) + "Display the given MESSAGE as a warning." + (display-warning 'org message :warning)) + +(defun org-eval (form) + "Eval FORM and return result." + (condition-case error + (eval form) + (error (format "%%![Error: %s]" error)))) + +(defun org-in-clocktable-p () + "Check if the cursor is in a clocktable." + (let ((pos (point)) start) + (save-excursion + (end-of-line 1) + (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t) + (setq start (match-beginning 0)) + (re-search-forward "^[ \t]*#\\+END:.*" nil t) + (>= (match-end 0) pos) + start)))) + +(defun org-in-verbatim-emphasis () + (save-match-data + (and (org-in-regexp org-verbatim-re 2) + (>= (point) (match-beginning 3)) + (<= (point) (match-end 4))))) + +(defun org-overlay-display (ovl text &optional face evap) + "Make overlay OVL display TEXT with face FACE." + (overlay-put ovl 'display text) + (if face (overlay-put ovl 'face face)) + (if evap (overlay-put ovl 'evaporate t))) + +(defun org-overlay-before-string (ovl text &optional face evap) + "Make overlay OVL display TEXT with face FACE." + (if face (org-add-props text nil 'face face)) + (overlay-put ovl 'before-string text) + (if evap (overlay-put ovl 'evaporate t))) + +(defun org-find-overlays (prop &optional pos delete) + "Find all overlays specifying PROP at POS or point. +If DELETE is non-nil, delete all those overlays." + (let (found) + (dolist (ov (overlays-at (or pos (point))) found) + (cond ((not (overlay-get ov prop))) + (delete (delete-overlay ov)) + (t (push ov found)))))) + +(defun org-goto-marker-or-bmk (marker &optional bookmark) + "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK." + (if (and marker (marker-buffer marker) + (buffer-live-p (marker-buffer marker))) + (progn + (pop-to-buffer-same-window (marker-buffer marker)) + (when (or (> marker (point-max)) (< marker (point-min))) + (widen)) + (goto-char marker) + (org-show-context 'org-goto)) + (if bookmark + (bookmark-jump bookmark) + (error "Cannot find location")))) + +(defun org-quote-csv-field (s) + "Quote field for inclusion in CSV material." + (if (string-match "[\",]" s) + (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"") + s)) + +(defun org-force-self-insert (N) + "Needed to enforce self-insert under remapping." + (interactive "p") + (self-insert-command N)) + +(defun org-shorten-string (s maxlength) + "Shorten string S so that it is no longer than MAXLENGTH characters. +If the string is shorter or has length MAXLENGTH, just return the +original string. If it is longer, the functions finds a space in the +string, breaks this string off at that locations and adds three dots +as ellipsis. Including the ellipsis, the string will not be longer +than MAXLENGTH. If finding a good breaking point in the string does +not work, the string is just chopped off in the middle of a word +if necessary." + (if (<= (length s) maxlength) + s + (let* ((n (max (- maxlength 4) 1)) + (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)"))) + (if (string-match re s) + (concat (match-string 1 s) "...") + (concat (substring s 0 (max (- maxlength 3) 0)) "..."))))) + +(defun org-get-indentation (&optional line) + "Get the indentation of the current line, interpreting tabs. +When LINE is given, assume it represents a line and compute its indentation." + (if line + (when (string-match "^ *" (org-remove-tabs line)) + (match-end 0)) + (save-excursion + (beginning-of-line 1) + (skip-chars-forward " \t") + (current-column)))) + +(defun org-get-string-indentation (s) + "What indentation has S due to SPACE and TAB at the beginning of the string?" + (let ((n -1) (i 0) (w tab-width) c) + (catch 'exit + (while (< (setq n (1+ n)) (length s)) + (setq c (aref s n)) + (cond ((= c ?\ ) (setq i (1+ i))) + ((= c ?\t) (setq i (* (/ (+ w i) w) w))) + (t (throw 'exit t))))) + i)) + +(defun org-remove-tabs (s &optional width) + "Replace tabulators in S with spaces. +Assumes that s is a single line, starting in column 0." + (setq width (or width tab-width)) + (while (string-match "\t" s) + (setq s (replace-match + (make-string + (- (* width (/ (+ (match-beginning 0) width) width)) + (match-beginning 0)) ?\ ) + t t s))) + s) + +(defun org-fix-indentation (line ind) + "Fix indentation in LINE. +IND is a cons cell with target and minimum indentation. +If the current indentation in LINE is smaller than the minimum, +leave it alone. If it is larger than ind, set it to the target." + (let* ((l (org-remove-tabs line)) + (i (org-get-indentation l)) + (i1 (car ind)) (i2 (cdr ind))) + (when (>= i i2) (setq l (substring line i2))) + (if (> i1 0) + (concat (make-string i1 ?\ ) l) + l))) + +(defun org-remove-indentation (code &optional n) + "Remove maximum common indentation in string CODE and return it. +N may optionally be the number of columns to remove. Return CODE +as-is if removal failed." + (with-temp-buffer + (insert code) + (if (org-do-remove-indentation n) (buffer-string) code))) + +(defun org-do-remove-indentation (&optional n) + "Remove the maximum common indentation from the buffer. +When optional argument N is a positive integer, remove exactly +that much characters from indentation, if possible. Return nil +if it fails." + (catch :exit + (goto-char (point-min)) + ;; Find maximum common indentation, if not specified. + (let ((n (or n + (let ((min-ind (point-max))) + (save-excursion + (while (re-search-forward "^[ \t]*\\S-" nil t) + (let ((ind (1- (current-column)))) + (if (zerop ind) (throw :exit nil) + (setq min-ind (min min-ind ind)))))) + min-ind)))) + (if (zerop n) (throw :exit nil) + ;; Remove exactly N indentation, but give up if not possible. + (while (not (eobp)) + (let ((ind (progn (skip-chars-forward " \t") (current-column)))) + (cond ((eolp) (delete-region (line-beginning-position) (point))) + ((< ind n) (throw :exit nil)) + (t (indent-line-to (- ind n)))) + (forward-line))) + ;; Signal success. + t)))) + +(defun org-fill-template (template alist) + "Find each %key of ALIST in TEMPLATE and replace it." + (let ((case-fold-search nil)) + (dolist (entry (sort (copy-sequence alist) + (lambda (a b) (< (length (car a)) (length (car b)))))) + (setq template + (replace-regexp-in-string + (concat "%" (regexp-quote (car entry))) + (or (cdr entry) "") template t t))) + template)) + +(defun org-base-buffer (buffer) + "Return the base buffer of BUFFER, if it has one. Else return the buffer." + (if (not buffer) + buffer + (or (buffer-base-buffer buffer) + buffer))) + +(defun org-wrap (string &optional width lines) + "Wrap string to either a number of lines, or a width in characters. +If WIDTH is non-nil, the string is wrapped to that width, however many lines +that costs. If there is a word longer than WIDTH, the text is actually +wrapped to the length of that word. +IF WIDTH is nil and LINES is non-nil, the string is forced into at most that +many lines, whatever width that takes. +The return value is a list of lines, without newlines at the end." + (let* ((words (split-string string)) + (maxword (apply 'max (mapcar 'org-string-width words))) + w ll) + (cond (width + (org-do-wrap words (max maxword width))) + (lines + (setq w maxword) + (setq ll (org-do-wrap words maxword)) + (if (<= (length ll) lines) + ll + (setq ll words) + (while (> (length ll) lines) + (setq w (1+ w)) + (setq ll (org-do-wrap words w))) + ll)) + (t (error "Cannot wrap this"))))) + +(defun org-do-wrap (words width) + "Create lines of maximum width WIDTH (in characters) from word list WORDS." + (let (lines line) + (while words + (setq line (pop words)) + (while (and words (< (+ (length line) (length (car words))) width)) + (setq line (concat line " " (pop words)))) + (setq lines (push line lines))) + (nreverse lines))) + +(defun org-quote-vert (s) + "Replace \"|\" with \"\\vert\"." + (while (string-match "|" s) + (setq s (replace-match "\\vert" t t s))) + s) + +(defun org-uuidgen-p (s) + "Is S an ID created by UUIDGEN?" + (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s))) + +(defun org-in-src-block-p (&optional inside) + "Whether point is in a code source block. +When INSIDE is non-nil, don't consider we are within a src block +when point is at #+BEGIN_SRC or #+END_SRC." + (let ((case-fold-search t)) + (or (and (eq (get-char-property (point) 'src-block) t)) + (and (not inside) + (save-match-data + (save-excursion + (beginning-of-line) + (looking-at ".*#\\+\\(begin\\|end\\)_src"))))))) + +(defun org-context () + "Return a list of contexts of the current cursor position. +If several contexts apply, all are returned. +Each context entry is a list with a symbol naming the context, and +two positions indicating start and end of the context. Possible +contexts are: + +:headline anywhere in a headline +:headline-stars on the leading stars in a headline +:todo-keyword on a TODO keyword (including DONE) in a headline +:tags on the TAGS in a headline +:priority on the priority cookie in a headline +:item on the first line of a plain list item +:item-bullet on the bullet/number of a plain list item +:checkbox on the checkbox in a plain list item +:table in an Org table +:table-special on a special filed in a table +:table-table in a table.el table +:clocktable in a clocktable +:src-block in a source block +:link on a hyperlink +:keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT. +:target on a <<target>> +:radio-target on a <<<radio-target>>> +:latex-fragment on a LaTeX fragment +:latex-preview on a LaTeX fragment with overlaid preview image + +This function expects the position to be visible because it uses font-lock +faces as a help to recognize the following contexts: :table-special, :link, +and :keyword." + (let* ((f (get-text-property (point) 'face)) + (faces (if (listp f) f (list f))) + (case-fold-search t) + (p (point)) clist o) + ;; First the large context + (cond + ((org-at-heading-p t) + (push (list :headline (point-at-bol) (point-at-eol)) clist) + (when (progn + (beginning-of-line 1) + (looking-at org-todo-line-tags-regexp)) + (push (org-point-in-group p 1 :headline-stars) clist) + (push (org-point-in-group p 2 :todo-keyword) clist) + (push (org-point-in-group p 4 :tags) clist)) + (goto-char p) + (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1)) + (when (looking-at "\\[#[A-Z0-9]\\]") + (push (org-point-in-group p 0 :priority) clist))) + + ((org-at-item-p) + (push (org-point-in-group p 2 :item-bullet) clist) + (push (list :item (point-at-bol) + (save-excursion (org-end-of-item) (point))) + clist) + (and (org-at-item-checkbox-p) + (push (org-point-in-group p 0 :checkbox) clist))) + + ((org-at-table-p) + (push (list :table (org-table-begin) (org-table-end)) clist) + (when (memq 'org-formula faces) + (push (list :table-special + (previous-single-property-change p 'face) + (next-single-property-change p 'face)) clist))) + ((org-at-table-p 'any) + (push (list :table-table) clist))) + (goto-char p) + + (let ((case-fold-search t)) + ;; New the "medium" contexts: clocktables, source blocks + (cond ((org-in-clocktable-p) + (push (list :clocktable + (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)") + (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t)) + (match-beginning 1)) + (and (re-search-forward "[ \t]*#\\+END:?" nil t) + (match-end 0))) clist)) + ((org-in-src-block-p) + (push (list :src-block + (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)") + (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t)) + (match-beginning 1)) + (and (search-forward "#+END_SRC" nil t) + (match-beginning 0))) clist)))) + (goto-char p) + + ;; Now the small context + (cond + ((org-at-timestamp-p) + (push (org-point-in-group p 0 :timestamp) clist)) + ((memq 'org-link faces) + (push (list :link + (previous-single-property-change p 'face) + (next-single-property-change p 'face)) clist)) + ((memq 'org-special-keyword faces) + (push (list :keyword + (previous-single-property-change p 'face) + (next-single-property-change p 'face)) clist)) + ((org-at-target-p) + (push (org-point-in-group p 0 :target) clist) + (goto-char (1- (match-beginning 0))) + (when (looking-at org-radio-target-regexp) + (push (org-point-in-group p 0 :radio-target) clist)) + (goto-char p)) + ((setq o (cl-some + (lambda (o) + (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay) + o)) + (overlays-at (point)))) + (push (list :latex-fragment + (overlay-start o) (overlay-end o)) clist) + (push (list :latex-preview + (overlay-start o) (overlay-end o)) clist)) + ((org-inside-LaTeX-fragment-p) + ;; FIXME: positions wrong. + (push (list :latex-fragment (point) (point)) clist))) + + (setq clist (nreverse (delq nil clist))) + clist)) + +(defun org-in-regexp (regexp &optional nlines visually) + "Check if point is inside a match of REGEXP. + +Normally only the current line is checked, but you can include +NLINES extra lines around point into the search. If VISUALLY is +set, require that the cursor is not after the match but really +on, so that the block visually is on the match. + +Return nil or a cons cell (BEG . END) where BEG and END are, +respectively, the positions at the beginning and the end of the +match." + (catch :exit + (let ((pos (point)) + (eol (line-end-position (if nlines (1+ nlines) 1)))) + (save-excursion + (beginning-of-line (- 1 (or nlines 0))) + (while (and (re-search-forward regexp eol t) + (<= (match-beginning 0) pos)) + (let ((end (match-end 0))) + (when (or (> end pos) (and (= end pos) (not visually))) + (throw :exit (cons (match-beginning 0) (match-end 0)))))))))) + +(defun org-between-regexps-p (start-re end-re &optional lim-up lim-down) + "Non-nil when point is between matches of START-RE and END-RE. + +Also return a non-nil value when point is on one of the matches. + +Optional arguments LIM-UP and LIM-DOWN bound the search; they are +buffer positions. Default values are the positions of headlines +surrounding the point. + +The functions returns a cons cell whose car (resp. cdr) is the +position before START-RE (resp. after END-RE)." + (save-match-data + (let ((pos (point)) + (limit-up (or lim-up (save-excursion (outline-previous-heading)))) + (limit-down (or lim-down (save-excursion (outline-next-heading)))) + beg end) + (save-excursion + ;; Point is on a block when on START-RE or if START-RE can be + ;; found before it... + (and (or (org-in-regexp start-re) + (re-search-backward start-re limit-up t)) + (setq beg (match-beginning 0)) + ;; ... and END-RE after it... + (goto-char (match-end 0)) + (re-search-forward end-re limit-down t) + (> (setq end (match-end 0)) pos) + ;; ... without another START-RE in-between. + (goto-char (match-beginning 0)) + (not (re-search-backward start-re (1+ beg) t)) + ;; Return value. + (cons beg end)))))) + +(defun org-in-block-p (names) + "Non-nil when point belongs to a block whose name belongs to NAMES. + +NAMES is a list of strings containing names of blocks. + +Return first block name matched, or nil. Beware that in case of +nested blocks, the returned name may not belong to the closest +block from point." + (save-match-data + (catch 'exit + (let ((case-fold-search t) + (lim-up (save-excursion (outline-previous-heading))) + (lim-down (save-excursion (outline-next-heading)))) + (dolist (name names) + (let ((n (regexp-quote name))) + (when (org-between-regexps-p + (concat "^[ \t]*#\\+begin_" n) + (concat "^[ \t]*#\\+end_" n) + lim-up lim-down) + (throw 'exit n))))) + nil))) + +(defun org-occur-in-agenda-files (regexp &optional _nlines) + "Call `multi-occur' with buffers for all agenda files." + (interactive "sOrg-files matching: ") + (let* ((files (org-agenda-files)) + (tnames (mapcar #'file-truename files)) + (extra org-agenda-text-search-extra-files)) + (when (eq (car extra) 'agenda-archives) + (setq extra (cdr extra)) + (setq files (org-add-archive-files files))) + (dolist (f extra) + (unless (member (file-truename f) tnames) + (unless (member f files) (setq files (append files (list f)))) + (setq tnames (append tnames (list (file-truename f)))))) + (multi-occur + (mapcar (lambda (x) + (with-current-buffer + ;; FIXME: Why not just (find-file-noselect x)? + ;; Is it to avoid the "revert buffer" prompt? + (or (get-file-buffer x) (find-file-noselect x)) + (widen) + (current-buffer))) + files) + regexp))) + +(add-hook 'occur-mode-find-occurrence-hook + (lambda () (when (derived-mode-p 'org-mode) (org-reveal)))) + +(defun org-occur-link-in-agenda-files () + "Create a link and search for it in the agendas. +The link is not stored in `org-stored-links', it is just created +for the search purpose." + (interactive) + (let ((link (condition-case nil + (org-store-link nil) + (error "Unable to create a link to here")))) + (org-occur-in-agenda-files (regexp-quote link)))) + +(defun org-reverse-string (string) + "Return the reverse of STRING." + (apply 'string (reverse (string-to-list string)))) + +;; defsubst org-uniquify must be defined before first use + +(defun org-uniquify-alist (alist) + "Merge elements of ALIST with the same key. + +For example, in this alist: + +\(org-uniquify-alist \\='((a 1) (b 2) (a 3))) + => \\='((a 1 3) (b 2)) + +merge (a 1) and (a 3) into (a 1 3). + +The function returns the new ALIST." + (let (rtn) + (dolist (e alist rtn) + (let (n) + (if (not (assoc (car e) rtn)) + (push e rtn) + (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e)))) + (setq rtn (assq-delete-all (car e) rtn)) + (push n rtn)))))) + +(defun org-delete-all (elts list) + "Remove all elements in ELTS from LIST. +Comparison is done with `equal'. It is a destructive operation +that may remove elements by altering the list structure." + (while elts + (setq list (delete (pop elts) list))) + list) + +(defun org-back-over-empty-lines () + "Move backwards over whitespace, to the beginning of the first empty line. +Returns the number of empty lines passed." + (let ((pos (point))) + (if (cdr (assq 'heading org-blank-before-new-entry)) + (skip-chars-backward " \t\n\r") + (unless (eobp) + (forward-line -1))) + (beginning-of-line 2) + (goto-char (min (point) pos)) + (count-lines (point) pos))) + +(defun org-skip-whitespace () + (skip-chars-forward " \t\n\r")) + +(defun org-point-in-group (point group &optional context) + "Check if POINT is in match-group GROUP. +If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the +match. If the match group does not exist or point is not inside it, +return nil." + (and (match-beginning group) + (>= point (match-beginning group)) + (<= point (match-end group)) + (if context + (list context (match-beginning group) (match-end group)) + t))) + +(defun org-switch-to-buffer-other-window (&rest args) + "Switch to buffer in a second window on the current frame. +In particular, do not allow pop-up frames. +Returns the newly created buffer." + (org-no-popups + (apply 'switch-to-buffer-other-window args))) + +(defun org-combine-plists (&rest plists) + "Create a single property list from all plists in PLISTS. +The process starts by copying the first list, and then setting properties +from the other lists. Settings in the last list are the most significant +ones and overrule settings in the other lists." + (let ((rtn (copy-sequence (pop plists))) + p v ls) + (while plists + (setq ls (pop plists)) + (while ls + (setq p (pop ls) v (pop ls)) + (setq rtn (plist-put rtn p v)))) + rtn)) + +(defun org-replace-escapes (string table) + "Replace %-escapes in STRING with values in TABLE. +TABLE is an association list with keys like \"%a\" and string values. +The sequences in STRING may contain normal field width and padding information, +for example \"%-5s\". Replacements happen in the sequence given by TABLE, +so values can contain further %-escapes if they are define later in TABLE." + (let ((tbl (copy-alist table)) + (case-fold-search nil) + (pchg 0) + re rpl) + (dolist (e tbl) + (setq re (concat "%-?[0-9.]*" (substring (car e) 1))) + (when (and (cdr e) (string-match re (cdr e))) + (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0))) + (safe "SREF")) + (add-text-properties 0 3 (list 'sref sref) safe) + (setcdr e (replace-match safe t t (cdr e))))) + (while (string-match re string) + (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s") + (cdr e))) + (setq string (replace-match rpl t t string)))) + (while (setq pchg (next-property-change pchg string)) + (let ((sref (get-text-property pchg 'sref string))) + (when (and sref (string-match "SREF" string pchg)) + (setq string (replace-match sref t t string))))) + string)) + +(defun org-find-base-buffer-visiting (file) + "Like `find-buffer-visiting' but always return the base buffer and +not an indirect buffer." + (let ((buf (or (get-file-buffer file) + (find-buffer-visiting file)))) + (if buf + (or (buffer-base-buffer buf) buf) + nil))) + +;;; TODO: Only called once, from ox-odt which should probably use +;;; org-export-inline-image-p or something. +(defun org-file-image-p (file) + "Return non-nil if FILE is an image." + (save-match-data + (string-match (image-file-name-regexp) file))) + +(defun org-get-cursor-date (&optional with-time) + "Return the date at cursor in as a time. +This works in the calendar and in the agenda, anywhere else it just +returns the current time. +If WITH-TIME is non-nil, returns the time of the event at point (in +the agenda) or the current time of the day." + (let (date day defd tp hod mod) + (when with-time + (setq tp (get-text-property (point) 'time)) + (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp)) + (setq hod (string-to-number (match-string 1 tp)) + mod (string-to-number (match-string 2 tp)))) + (or tp (let ((now (decode-time))) + (setq hod (nth 2 now) + mod (nth 1 now))))) + (cond + ((eq major-mode 'calendar-mode) + (setq date (calendar-cursor-to-date) + defd (encode-time 0 (or mod 0) (or hod 0) + (nth 1 date) (nth 0 date) (nth 2 date)))) + ((eq major-mode 'org-agenda-mode) + (setq day (get-text-property (point) 'day)) + (when day + (setq date (calendar-gregorian-from-absolute day) + defd (encode-time 0 (or mod 0) (or hod 0) + (nth 1 date) (nth 0 date) (nth 2 date)))))) + (or defd (current-time)))) + +(defun org-mark-subtree (&optional up) + "Mark the current subtree. +This puts point at the start of the current subtree, and mark at +the end. If a numeric prefix UP is given, move up into the +hierarchy of headlines by UP levels before marking the subtree." + (interactive "P") + (org-with-limited-levels + (cond ((org-at-heading-p) (beginning-of-line)) + ((org-before-first-heading-p) (user-error "Not in a subtree")) + (t (outline-previous-visible-heading 1)))) + (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up))) + (if (called-interactively-p 'any) + (call-interactively 'org-mark-element) + (org-mark-element))) + +(defun org-file-newer-than-p (file time) + "Non-nil if FILE is newer than TIME. +FILE is a filename, as a string, TIME is a list of integers, as +returned by, e.g., `current-time'." + (and (file-exists-p file) + ;; Only compare times up to whole seconds as some file-systems + ;; (e.g. HFS+) do not retain any finer granularity. As + ;; a consequence, make sure we return non-nil when the two + ;; times are equal. + (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2) + (cl-subseq time 0 2))))) + +(defun org-compile-file (source process ext &optional err-msg log-buf spec) + "Compile a SOURCE file using PROCESS. + +PROCESS is either a function or a list of shell commands, as +strings. EXT is a file extension, without the leading dot, as +a string. It is used to check if the process actually succeeded. + +PROCESS must create a file with the same base name and directory +as SOURCE, but ending with EXT. The function then returns its +filename. Otherwise, it raises an error. The error message can +then be refined by providing string ERR-MSG, which is appended to +the standard message. + +If PROCESS is a function, it is called with a single argument: +the SOURCE file. + +If it is a list of commands, each of them is called using +`shell-command'. By default, in each command, %b, %f, %F, %o and +%O are replaced with, respectively, SOURCE base name, name, full +name, directory and absolute output file name. It is possible, +however, to use more place-holders by specifying them in optional +argument SPEC, as an alist following the pattern + + (CHARACTER . REPLACEMENT-STRING). + +When PROCESS is a list of commands, optional argument LOG-BUF can +be set to a buffer or a buffer name. `shell-command' then uses +it for output." + (let* ((base-name (file-name-base source)) + (full-name (file-truename source)) + (out-dir (or (file-name-directory source) "./")) + (output (expand-file-name (concat base-name "." ext) out-dir)) + (time (current-time)) + (err-msg (if (stringp err-msg) (concat ". " err-msg) ""))) + (save-window-excursion + (pcase process + ((pred functionp) (funcall process (shell-quote-argument source))) + ((pred consp) + (let ((log-buf (and log-buf (get-buffer-create log-buf))) + (spec (append spec + `((?b . ,(shell-quote-argument base-name)) + (?f . ,(shell-quote-argument source)) + (?F . ,(shell-quote-argument full-name)) + (?o . ,(shell-quote-argument out-dir)) + (?O . ,(shell-quote-argument output)))))) + (dolist (command process) + (shell-command (format-spec command spec) log-buf)) + (when log-buf (with-current-buffer log-buf (compilation-mode))))) + (_ (error "No valid command to process %S%s" source err-msg)))) + ;; Check for process failure. Output file is expected to be + ;; located in the same directory as SOURCE. + (unless (org-file-newer-than-p output time) + (error (format "File %S wasn't produced%s" output err-msg))) + output)) + +;;; Indentation + +(defvar org-element-greater-elements) +(defun org--get-expected-indentation (element contentsp) + "Expected indentation column for current line, according to ELEMENT. +ELEMENT is an element containing point. CONTENTSP is non-nil +when indentation is to be computed according to contents of +ELEMENT." + (let ((type (org-element-type element)) + (start (org-element-property :begin element)) + (post-affiliated (org-element-property :post-affiliated element))) + (org-with-wide-buffer + (cond + (contentsp + (cl-case type + ((diary-sexp footnote-definition) 0) + ((headline inlinetask nil) + (if (not org-adapt-indentation) 0 + (let ((level (org-current-level))) + (if level (1+ level) 0)))) + ((item plain-list) (org-list-item-body-column post-affiliated)) + (t + (goto-char start) + (org-get-indentation)))) + ((memq type '(headline inlinetask nil)) + (if (org-match-line "[ \t]*$") + (org--get-expected-indentation element t) + 0)) + ((memq type '(diary-sexp footnote-definition)) 0) + ;; First paragraph of a footnote definition or an item. + ;; Indent like parent. + ((< (line-beginning-position) start) + (org--get-expected-indentation + (org-element-property :parent element) t)) + ;; At first line: indent according to previous sibling, if any, + ;; ignoring footnote definitions and inline tasks, or parent's + ;; contents. + ((= (line-beginning-position) start) + (catch 'exit + (while t + (if (= (point-min) start) (throw 'exit 0) + (goto-char (1- start)) + (let* ((previous (org-element-at-point)) + (parent previous)) + (while (and parent (<= (org-element-property :end parent) start)) + (setq previous parent + parent (org-element-property :parent parent))) + (cond + ((not previous) (throw 'exit 0)) + ((> (org-element-property :end previous) start) + (throw 'exit (org--get-expected-indentation previous t))) + ((memq (org-element-type previous) + '(footnote-definition inlinetask)) + (setq start (org-element-property :begin previous))) + (t (goto-char (org-element-property :begin previous)) + (throw 'exit + (if (bolp) (org-get-indentation) + ;; At first paragraph in an item or + ;; a footnote definition. + (org--get-expected-indentation + (org-element-property :parent previous) t)))))))))) + ;; Otherwise, move to the first non-blank line above. + (t + (beginning-of-line) + (let ((pos (point))) + (skip-chars-backward " \r\t\n") + (cond + ;; Two blank lines end a footnote definition or a plain + ;; list. When we indent an empty line after them, the + ;; containing list or footnote definition is over, so it + ;; qualifies as a previous sibling. Therefore, we indent + ;; like its first line. + ((and (memq type '(footnote-definition plain-list)) + (> (count-lines (point) pos) 2)) + (goto-char start) + (org-get-indentation)) + ;; Line above is the first one of a paragraph at the + ;; beginning of an item or a footnote definition. Indent + ;; like parent. + ((< (line-beginning-position) start) + (org--get-expected-indentation + (org-element-property :parent element) t)) + ;; Line above is the beginning of an element, i.e., point + ;; was originally on the blank lines between element's start + ;; and contents. + ((= (line-beginning-position) post-affiliated) + (org--get-expected-indentation element t)) + ;; POS is after contents in a greater element. Indent like + ;; the beginning of the element. + ((and (memq type org-element-greater-elements) + (let ((cend (org-element-property :contents-end element))) + (and cend (<= cend pos)))) + ;; As a special case, if point is at the end of a footnote + ;; definition or an item, indent like the very last element + ;; within. If that last element is an item, indent like + ;; its contents. + (if (memq type '(footnote-definition item plain-list)) + (let ((last (org-element-at-point))) + (goto-char pos) + (org--get-expected-indentation + last (eq (org-element-type last) 'item))) + (goto-char start) + (org-get-indentation))) + ;; In any other case, indent like the current line. + (t (org-get-indentation))))))))) + +(defun org--align-node-property () + "Align node property at point. +Alignment is done according to `org-property-format', which see." + (when (save-excursion + (beginning-of-line) + (looking-at org-property-re)) + (replace-match + (concat (match-string 4) + (org-trim + (format org-property-format (match-string 1) (match-string 3)))) + t t))) + +(defun org-indent-line () + "Indent line depending on context. + +Indentation is done according to the following rules: + + - Footnote definitions, diary sexps, headlines and inline tasks + have to start at column 0. + + - On the very first line of an element, consider, in order, the + next rules until one matches: + + 1. If there's a sibling element before, ignoring footnote + definitions and inline tasks, indent like its first line. + + 2. If element has a parent, indent like its contents. More + precisely, if parent is an item, indent after the + description part, if any, or the bullet (see + `org-list-description-max-indent'). Else, indent like + parent's first line. + + 3. Otherwise, indent relatively to current level, if + `org-adapt-indentation' is non-nil, or to left margin. + + - On a blank line at the end of an element, indent according to + the type of the element. More precisely + + 1. If element is a plain list, an item, or a footnote + definition, indent like the very last element within. + + 2. If element is a paragraph, indent like its last non blank + line. + + 3. Otherwise, indent like its very first line. + + - In the code part of a source block, use language major mode + to indent current line if `org-src-tab-acts-natively' is + non-nil. If it is nil, do nothing. + + - Otherwise, indent like the first non-blank line above. + +The function doesn't indent an item as it could break the whole +list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \ +`\\[org-shiftmetaright]'. + +Also align node properties according to `org-property-format'." + (interactive) + (cond + (orgstruct-is-++ + (let ((indent-line-function + (cl-cadadr (assq 'indent-line-function org-fb-vars)))) + (indent-according-to-mode))) + ((org-at-heading-p) 'noindent) + (t + (let* ((element (save-excursion (beginning-of-line) (org-element-at-point))) + (type (org-element-type element))) + (cond ((and (memq type '(plain-list item)) + (= (line-beginning-position) + (org-element-property :post-affiliated element))) + 'noindent) + ((and (eq type 'latex-environment) + (>= (point) (org-element-property :post-affiliated element)) + (< (point) (org-with-wide-buffer + (goto-char (org-element-property :end element)) + (skip-chars-backward " \r\t\n") + (line-beginning-position 2)))) + 'noindent) + ((and (eq type 'src-block) + org-src-tab-acts-natively + (> (line-beginning-position) + (org-element-property :post-affiliated element)) + (< (line-beginning-position) + (org-with-wide-buffer + (goto-char (org-element-property :end element)) + (skip-chars-backward " \r\t\n") + (line-beginning-position)))) + (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))) + (t + (let ((column (org--get-expected-indentation element nil))) + ;; Preserve current column. + (if (<= (current-column) (current-indentation)) + (indent-line-to column) + (save-excursion (indent-line-to column)))) + ;; Align node property. Also preserve current column. + (when (eq type 'node-property) + (let ((column (current-column))) + (org--align-node-property) + (org-move-to-column column))))))))) + +(defun org-indent-region (start end) + "Indent each non-blank line in the region. +Called from a program, START and END specify the region to +indent. The function will not indent contents of example blocks, +verse blocks and export blocks as leading white spaces are +assumed to be significant there." + (interactive "r") + (save-excursion + (goto-char start) + (skip-chars-forward " \r\t\n") + (unless (eobp) (beginning-of-line)) + (let ((indent-to + (lambda (ind pos) + ;; Set IND as indentation for all lines between point and + ;; POS. Blank lines are ignored. Leave point after POS + ;; once done. + (let ((limit (copy-marker pos))) + (while (< (point) limit) + (unless (looking-at-p "[ \t]*$") (indent-line-to ind)) + (forward-line)) + (set-marker limit nil)))) + (end (copy-marker end))) + (while (< (point) end) + (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line) + (let* ((element (org-element-at-point)) + (type (org-element-type element)) + (element-end (copy-marker (org-element-property :end element))) + (ind (org--get-expected-indentation element nil))) + (cond + ;; Element indented as a single block. Example blocks + ;; preserving indentation are a special case since the + ;; "contents" must not be indented whereas the block + ;; boundaries can. + ((or (memq type '(export-block latex-environment)) + (and (eq type 'example-block) + (not + (or org-src-preserve-indentation + (org-element-property :preserve-indent element))))) + (let ((offset (- ind (org-get-indentation)))) + (unless (zerop offset) + (indent-rigidly (org-element-property :begin element) + (org-element-property :end element) + offset))) + (goto-char element-end)) + ;; Elements indented line wise. Be sure to exclude + ;; example blocks (preserving indentation) and source + ;; blocks from this category as they are treated + ;; specially later. + ((or (memq type '(paragraph table table-row)) + (not (or (org-element-property :contents-begin element) + (memq type '(example-block src-block))))) + (when (eq type 'node-property) + (org--align-node-property) + (beginning-of-line)) + (funcall indent-to ind (min element-end end))) + ;; Elements consisting of three parts: before the + ;; contents, the contents, and after the contents. The + ;; contents are treated specially, according to the + ;; element type, or not indented at all. Other parts are + ;; indented as a single block. + (t + (let* ((post (copy-marker + (org-element-property :post-affiliated element))) + (cbeg + (copy-marker + (cond + ((not (org-element-property :contents-begin element)) + ;; Fake contents for source blocks. + (org-with-wide-buffer + (goto-char post) + (line-beginning-position 2))) + ((memq type '(footnote-definition item plain-list)) + ;; Contents in these elements could start on + ;; the same line as the beginning of the + ;; element. Make sure we start indenting + ;; from the second line. + (org-with-wide-buffer + (goto-char post) + (end-of-line) + (skip-chars-forward " \r\t\n") + (if (eobp) (point) (line-beginning-position)))) + (t (org-element-property :contents-begin element))))) + (cend (copy-marker + (or (org-element-property :contents-end element) + ;; Fake contents for source blocks. + (org-with-wide-buffer + (goto-char element-end) + (skip-chars-backward " \r\t\n") + (line-beginning-position))) + t))) + ;; Do not change items indentation individually as it + ;; might break the list as a whole. On the other + ;; hand, when at a plain list, indent it as a whole. + (cond ((eq type 'plain-list) + (let ((offset (- ind (org-get-indentation)))) + (unless (zerop offset) + (indent-rigidly (org-element-property :begin element) + (org-element-property :end element) + offset)) + (goto-char cbeg))) + ((eq type 'item) (goto-char cbeg)) + (t (funcall indent-to ind (min cbeg end)))) + (when (< (point) end) + (cl-case type + ((example-block verse-block)) + (src-block + ;; In a source block, indent source code + ;; according to language major mode, but only if + ;; `org-src-tab-acts-natively' is non-nil. + (when (and (< (point) end) org-src-tab-acts-natively) + (ignore-errors + (org-babel-do-in-edit-buffer + (indent-region (point-min) (point-max)))))) + (t (org-indent-region (point) (min cend end)))) + (goto-char (min cend end)) + (when (< (point) end) + (funcall indent-to ind (min element-end end)))) + (set-marker post nil) + (set-marker cbeg nil) + (set-marker cend nil)))) + (set-marker element-end nil)))) + (set-marker end nil)))) + +(defun org-indent-drawer () + "Indent the drawer at point." + (interactive) + (unless (save-excursion + (beginning-of-line) + (looking-at-p org-drawer-regexp)) + (user-error "Not at a drawer")) + (let ((element (org-element-at-point))) + (unless (memq (org-element-type element) '(drawer property-drawer)) + (user-error "Not at a drawer")) + (org-with-wide-buffer + (org-indent-region (org-element-property :begin element) + (org-element-property :end element)))) + (message "Drawer at point indented")) + +(defun org-indent-block () + "Indent the block at point." + (interactive) + (unless (save-excursion + (beginning-of-line) + (let ((case-fold-search t)) + (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_"))) + (user-error "Not at a block")) + (let ((element (org-element-at-point))) + (unless (memq (org-element-type element) + '(comment-block center-block dynamic-block example-block + export-block quote-block special-block + src-block verse-block)) + (user-error "Not at a block")) + (org-with-wide-buffer + (org-indent-region (org-element-property :begin element) + (org-element-property :end element)))) + (message "Block at point indented")) + + +;;; Filling + +;; We use our own fill-paragraph and auto-fill functions. + +;; `org-fill-paragraph' relies on adaptive filling and context +;; checking. Appropriate `fill-prefix' is computed with +;; `org-adaptive-fill-function'. + +;; `org-auto-fill-function' takes care of auto-filling. It calls +;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with +;; `org-adaptive-fill-function' value. Internally, +;; `org-comment-line-break-function' breaks the line. + +;; `org-setup-filling' installs filling and auto-filling related +;; variables during `org-mode' initialization. + +(defun org-setup-filling () + (require 'org-element) + ;; Prevent auto-fill from inserting unwanted new items. + (when (boundp 'fill-nobreak-predicate) + (setq-local + fill-nobreak-predicate + (org-uniquify + (append fill-nobreak-predicate + '(org-fill-line-break-nobreak-p + org-fill-n-macro-as-item-nobreak-p + org-fill-paragraph-with-timestamp-nobreak-p))))) + (let ((paragraph-ending (substring org-element-paragraph-separate 1))) + (setq-local paragraph-start paragraph-ending) + (setq-local paragraph-separate paragraph-ending)) + (setq-local fill-paragraph-function 'org-fill-paragraph) + (setq-local auto-fill-inhibit-regexp nil) + (setq-local adaptive-fill-function 'org-adaptive-fill-function) + (setq-local normal-auto-fill-function 'org-auto-fill-function) + (setq-local comment-line-break-function 'org-comment-line-break-function)) + +(defun org-fill-line-break-nobreak-p () + "Non-nil when a new line at point would create an Org line break." + (save-excursion + (skip-chars-backward "[ \t]") + (skip-chars-backward "\\\\") + (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)"))) + +(defun org-fill-paragraph-with-timestamp-nobreak-p () + "Non-nil when a new line at point would split a timestamp." + (and (org-at-timestamp-p 'lax) + (not (looking-at org-ts-regexp-both)))) + +(defun org-fill-n-macro-as-item-nobreak-p () + "Non-nil when a new line at point would create a new list." + ;; During export, a "n" macro followed by a dot or a closing + ;; parenthesis can end up being parsed as a new list item. + (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)")) + +(declare-function message-in-body-p "message" ()) +(defvar orgtbl-line-start-regexp) ; From org-table.el +(defun org-adaptive-fill-function () + "Compute a fill prefix for the current line. +Return fill prefix, as a string, or nil if current line isn't +meant to be filled. For convenience, if `adaptive-fill-regexp' +matches in paragraphs or comments, use it." + (catch 'exit + (when (derived-mode-p 'message-mode) + (save-excursion + (beginning-of-line) + (cond ((not (message-in-body-p)) (throw 'exit nil)) + ((looking-at-p org-table-line-regexp) (throw 'exit nil)) + ((looking-at message-cite-prefix-regexp) + (throw 'exit (match-string-no-properties 0))) + ((looking-at org-outline-regexp) + (throw 'exit (make-string (length (match-string 0)) ?\s)))))) + (org-with-wide-buffer + (unless (org-at-heading-p) + (let* ((p (line-beginning-position)) + (element (save-excursion + (beginning-of-line) + (org-element-at-point))) + (type (org-element-type element)) + (post-affiliated (org-element-property :post-affiliated element))) + (unless (< p post-affiliated) + (cl-case type + (comment + (save-excursion + (beginning-of-line) + (looking-at "[ \t]*") + (concat (match-string 0) "# "))) + (footnote-definition "") + ((item plain-list) + (make-string (org-list-item-body-column post-affiliated) ?\s)) + (paragraph + ;; Fill prefix is usually the same as the current line, + ;; unless the paragraph is at the beginning of an item. + (let ((parent (org-element-property :parent element))) + (save-excursion + (beginning-of-line) + (cond ((eq (org-element-type parent) 'item) + (make-string (org-list-item-body-column + (org-element-property :begin parent)) + ?\s)) + ((and adaptive-fill-regexp + ;; Locally disable + ;; `adaptive-fill-function' to let + ;; `fill-context-prefix' handle + ;; `adaptive-fill-regexp' variable. + (let (adaptive-fill-function) + (fill-context-prefix + post-affiliated + (org-element-property :end element))))) + ((looking-at "[ \t]+") (match-string 0)) + (t ""))))) + (comment-block + ;; Only fill contents if P is within block boundaries. + (let* ((cbeg (save-excursion (goto-char post-affiliated) + (forward-line) + (point))) + (cend (save-excursion + (goto-char (org-element-property :end element)) + (skip-chars-backward " \r\t\n") + (line-beginning-position)))) + (when (and (>= p cbeg) (< p cend)) + (if (save-excursion (beginning-of-line) (looking-at "[ \t]+")) + (match-string 0) + ""))))))))))) + +(declare-function message-goto-body "message" ()) +(defvar message-cite-prefix-regexp) ; From message.el + +(defun org-fill-element (&optional justify) + "Fill element at point, when applicable. + +This function only applies to comment blocks, comments, example +blocks and paragraphs. Also, as a special case, re-align table +when point is at one. + +If JUSTIFY is non-nil (interactively, with prefix argument), +justify as well. If `sentence-end-double-space' is non-nil, then +period followed by one space does not end a sentence, so don't +break a line there. The variable `fill-column' controls the +width for filling. + +For convenience, when point is at a plain list, an item or +a footnote definition, try to fill the first paragraph within." + (with-syntax-table org-mode-transpose-word-syntax-table + ;; Move to end of line in order to get the first paragraph within + ;; a plain list or a footnote definition. + (let ((element (save-excursion (end-of-line) (org-element-at-point)))) + ;; First check if point is in a blank line at the beginning of + ;; the buffer. In that case, ignore filling. + (cl-case (org-element-type element) + ;; Use major mode filling function is src blocks. + (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q"))) + ;; Align Org tables, leave table.el tables as-is. + (table-row (org-table-align) t) + (table + (when (eq (org-element-property :type element) 'org) + (save-excursion + (goto-char (org-element-property :post-affiliated element)) + (org-table-align))) + t) + (paragraph + ;; Paragraphs may contain `line-break' type objects. + (let ((beg (max (point-min) + (org-element-property :contents-begin element))) + (end (min (point-max) + (org-element-property :contents-end element)))) + ;; Do nothing if point is at an affiliated keyword. + (if (< (line-end-position) beg) t + (when (derived-mode-p 'message-mode) + ;; In `message-mode', do not fill following citation + ;; in current paragraph nor text before message body. + (let ((body-start (save-excursion (message-goto-body)))) + (when body-start (setq beg (max body-start beg)))) + (when (save-excursion + (re-search-forward + (concat "^" message-cite-prefix-regexp) end t)) + (setq end (match-beginning 0)))) + ;; Fill paragraph, taking line breaks into account. + (save-excursion + (goto-char beg) + (let ((cuts (list beg))) + (while (re-search-forward "\\\\\\\\[ \t]*\n" end t) + (when (eq 'line-break + (org-element-type + (save-excursion (backward-char) + (org-element-context)))) + (push (point) cuts))) + (dolist (c (delq end cuts)) + (fill-region-as-paragraph c end justify) + (setq end c)))) + t))) + ;; Contents of `comment-block' type elements should be + ;; filled as plain text, but only if point is within block + ;; markers. + (comment-block + (let* ((case-fold-search t) + (beg (save-excursion + (goto-char (org-element-property :begin element)) + (re-search-forward "^[ \t]*#\\+begin_comment" nil t) + (forward-line) + (point))) + (end (save-excursion + (goto-char (org-element-property :end element)) + (re-search-backward "^[ \t]*#\\+end_comment" nil t) + (line-beginning-position)))) + (if (or (< (point) beg) (> (point) end)) t + (fill-region-as-paragraph + (save-excursion (end-of-line) + (re-search-backward "^[ \t]*$" beg 'move) + (line-beginning-position)) + (save-excursion (beginning-of-line) + (re-search-forward "^[ \t]*$" end 'move) + (line-beginning-position)) + justify)))) + ;; Fill comments. + (comment + (let ((begin (org-element-property :post-affiliated element)) + (end (org-element-property :end element))) + (when (and (>= (point) begin) (<= (point) end)) + (let ((begin (save-excursion + (end-of-line) + (if (re-search-backward "^[ \t]*#[ \t]*$" begin t) + (progn (forward-line) (point)) + begin))) + (end (save-excursion + (end-of-line) + (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move) + (1- (line-beginning-position)) + (skip-chars-backward " \r\t\n") + (line-end-position))))) + ;; Do not fill comments when at a blank line. + (when (> end begin) + (let ((fill-prefix + (save-excursion + (beginning-of-line) + (looking-at "[ \t]*#") + (let ((comment-prefix (match-string 0))) + (goto-char (match-end 0)) + (if (looking-at adaptive-fill-regexp) + (concat comment-prefix (match-string 0)) + (concat comment-prefix " ")))))) + (save-excursion + (fill-region-as-paragraph begin end justify)))))) + t)) + ;; Ignore every other element. + (otherwise t))))) + +(defun org-fill-paragraph (&optional justify region) + "Fill element at point, when applicable. + +This function only applies to comment blocks, comments, example +blocks and paragraphs. Also, as a special case, re-align table +when point is at one. + +For convenience, when point is at a plain list, an item or +a footnote definition, try to fill the first paragraph within. + +If JUSTIFY is non-nil (interactively, with prefix argument), +justify as well. If `sentence-end-double-space' is non-nil, then +period followed by one space does not end a sentence, so don't +break a line there. The variable `fill-column' controls the +width for filling. + +The REGION argument is non-nil if called interactively; in that +case, if Transient Mark mode is enabled and the mark is active, +fill each of the elements in the active region, instead of just +filling the current element." + (interactive (progn + (barf-if-buffer-read-only) + (list (if current-prefix-arg 'full) t))) + (cond + ((and (derived-mode-p 'message-mode) + (or (not (message-in-body-p)) + (save-excursion (move-beginning-of-line 1) + (looking-at message-cite-prefix-regexp)))) + ;; First ensure filling is correct in message-mode. + (let ((fill-paragraph-function + (cl-cadadr (assq 'fill-paragraph-function org-fb-vars))) + (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars))) + (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars))) + (paragraph-separate + (cl-cadadr (assq 'paragraph-separate org-fb-vars)))) + (fill-paragraph nil))) + ((and region transient-mark-mode mark-active + (not (eq (region-beginning) (region-end)))) + (let ((origin (point-marker)) + (start (region-beginning))) + (unwind-protect + (progn + (goto-char (region-end)) + (while (> (point) start) + (org-backward-paragraph) + (org-fill-element justify))) + (goto-char origin) + (set-marker origin nil)))) + (t (org-fill-element justify)))) +(org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph) + +(defun org-auto-fill-function () + "Auto-fill function." + ;; Check if auto-filling is meaningful. + (let ((fc (current-fill-column))) + (when (and fc (> (current-column) fc)) + (let* ((fill-prefix (org-adaptive-fill-function)) + ;; Enforce empty fill prefix, if required. Otherwise, it + ;; will be computed again. + (adaptive-fill-mode (not (equal fill-prefix "")))) + (when fill-prefix (do-auto-fill)))))) + +(defun org-comment-line-break-function (&optional soft) + "Break line at point and indent, continuing comment if within one. +The inserted newline is marked hard if variable +`use-hard-newlines' is true, unless optional argument SOFT is +non-nil." + (if soft (insert-and-inherit ?\n) (newline 1)) + (save-excursion (forward-char -1) (delete-horizontal-space)) + (delete-horizontal-space) + (indent-to-left-margin) + (insert-before-markers-and-inherit fill-prefix)) + + +;;; Fixed Width Areas + +(defun org-toggle-fixed-width () + "Toggle fixed-width markup. + +Add or remove fixed-width markup on current line, whenever it +makes sense. Return an error otherwise. + +If a region is active and if it contains only fixed-width areas +or blank lines, remove all fixed-width markup in it. If the +region contains anything else, convert all non-fixed-width lines +to fixed-width ones. + +Blank lines at the end of the region are ignored unless the +region only contains such lines." + (interactive) + (if (not (org-region-active-p)) + ;; No region: + ;; + ;; Remove fixed width marker only in a fixed-with element. + ;; + ;; Add fixed width maker in paragraphs, in blank lines after + ;; elements or at the beginning of a headline or an inlinetask, + ;; and before any one-line elements (e.g., a clock). + (progn + (beginning-of-line) + (let* ((element (org-element-at-point)) + (type (org-element-type element))) + (cond + ((and (eq type 'fixed-width) + (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")) + (replace-match + "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1))) + ((and (memq type '(babel-call clock comment diary-sexp headline + horizontal-rule keyword paragraph + planning)) + (<= (org-element-property :post-affiliated element) (point))) + (skip-chars-forward " \t") + (insert ": ")) + ((and (looking-at-p "[ \t]*$") + (or (eq type 'inlinetask) + (save-excursion + (skip-chars-forward " \r\t\n") + (<= (org-element-property :end element) (point))))) + (delete-region (point) (line-end-position)) + (org-indent-line) + (insert ": ")) + (t (user-error "Cannot insert a fixed-width line here"))))) + ;; Region active. + (let* ((begin (save-excursion + (goto-char (region-beginning)) + (line-beginning-position))) + (end (copy-marker + (save-excursion + (goto-char (region-end)) + (unless (eolp) (beginning-of-line)) + (if (save-excursion (re-search-backward "\\S-" begin t)) + (progn (skip-chars-backward " \r\t\n") (point)) + (point))))) + (all-fixed-width-p + (catch 'not-all-p + (save-excursion + (goto-char begin) + (skip-chars-forward " \r\t\n") + (when (eobp) (throw 'not-all-p nil)) + (while (< (point) end) + (let ((element (org-element-at-point))) + (if (eq (org-element-type element) 'fixed-width) + (goto-char (org-element-property :end element)) + (throw 'not-all-p nil)))) + t)))) + (if all-fixed-width-p + (save-excursion + (goto-char begin) + (while (< (point) end) + (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)") + (replace-match + "" nil nil nil + (if (= (line-end-position) (match-end 0)) 0 1))) + (forward-line))) + (let ((min-ind (point-max))) + ;; Find minimum indentation across all lines. + (save-excursion + (goto-char begin) + (if (not (save-excursion (re-search-forward "\\S-" end t))) + (setq min-ind 0) + (catch 'zerop + (while (< (point) end) + (unless (looking-at-p "[ \t]*$") + (let ((ind (org-get-indentation))) + (setq min-ind (min min-ind ind)) + (when (zerop ind) (throw 'zerop t)))) + (forward-line))))) + ;; Loop over all lines and add fixed-width markup everywhere + ;; but in fixed-width lines. + (save-excursion + (goto-char begin) + (while (< (point) end) + (cond + ((org-at-heading-p) + (insert ": ") + (forward-line) + (while (and (< (point) end) (looking-at-p "[ \t]*$")) + (insert ":") + (forward-line))) + ((looking-at-p "[ \t]*:\\( \\|$\\)") + (let* ((element (org-element-at-point)) + (element-end (org-element-property :end element))) + (if (eq (org-element-type element) 'fixed-width) + (progn (goto-char element-end) + (skip-chars-backward " \r\t\n") + (forward-line)) + (let ((limit (min end element-end))) + (while (< (point) limit) + (org-move-to-column min-ind t) + (insert ": ") + (forward-line)))))) + (t + (org-move-to-column min-ind t) + (insert ": ") + (forward-line))))))) + (set-marker end nil)))) + + +;;; Comments + +;; Org comments syntax is quite complex. It requires the entire line +;; to be just a comment. Also, even with the right syntax at the +;; beginning of line, some elements (e.g., verse-block or +;; example-block) don't accept comments. Usual Emacs comment commands +;; cannot cope with those requirements. Therefore, Org replaces them. + +;; Org still relies on `comment-dwim', but cannot trust +;; `comment-only-p'. So, `comment-region-function' and +;; `uncomment-region-function' both point +;; to`org-comment-or-uncomment-region'. Eventually, +;; `org-insert-comment' takes care of insertion of comments at the +;; beginning of line. + +;; `org-setup-comments-handling' install comments related variables +;; during `org-mode' initialization. + +(defun org-setup-comments-handling () + (interactive) + (setq-local comment-use-syntax nil) + (setq-local comment-start "# ") + (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)") + (setq-local comment-insert-comment-function 'org-insert-comment) + (setq-local comment-region-function 'org-comment-or-uncomment-region) + (setq-local uncomment-region-function 'org-comment-or-uncomment-region)) + +(defun org-insert-comment () + "Insert an empty comment above current line. +If the line is empty, insert comment at its beginning. When +point is within a source block, comment according to the related +major mode." + (if (let ((element (org-element-at-point))) + (and (eq (org-element-type element) 'src-block) + (< (save-excursion + (goto-char (org-element-property :post-affiliated element)) + (line-end-position)) + (point)) + (> (save-excursion + (goto-char (org-element-property :end element)) + (skip-chars-backward " \r\t\n") + (line-beginning-position)) + (point)))) + (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim)) + (beginning-of-line) + (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol)) + (open-line 1)) + (org-indent-line) + (insert "# "))) + +(defvar comment-empty-lines) ; From newcomment.el. +(defun org-comment-or-uncomment-region (beg end &rest _) + "Comment or uncomment each non-blank line in the region. +Uncomment each non-blank line between BEG and END if it only +contains commented lines. Otherwise, comment them. If region is +strictly within a source block, use appropriate comment syntax." + (if (let ((element (org-element-at-point))) + (and (eq (org-element-type element) 'src-block) + (< (save-excursion + (goto-char (org-element-property :post-affiliated element)) + (line-end-position)) + beg) + (>= (save-excursion + (goto-char (org-element-property :end element)) + (skip-chars-backward " \r\t\n") + (line-beginning-position)) + end))) + ;; Translate region boundaries for the Org buffer to the source + ;; buffer. + (let ((offset (- end beg))) + (save-excursion + (goto-char beg) + (org-babel-do-in-edit-buffer + (comment-or-uncomment-region (point) (+ offset (point)))))) + (save-restriction + ;; Restrict region + (narrow-to-region (save-excursion (goto-char beg) + (skip-chars-forward " \r\t\n" end) + (line-beginning-position)) + (save-excursion (goto-char end) + (skip-chars-backward " \r\t\n" beg) + (line-end-position))) + (let ((uncommentp + ;; UNCOMMENTP is non-nil when every non blank line between + ;; BEG and END is a comment. + (save-excursion + (goto-char (point-min)) + (while (and (not (eobp)) + (let ((element (org-element-at-point))) + (and (eq (org-element-type element) 'comment) + (goto-char (min (point-max) + (org-element-property + :end element))))))) + (eobp)))) + (if uncommentp + ;; Only blank lines and comments in region: uncomment it. + (save-excursion + (goto-char (point-min)) + (while (not (eobp)) + (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)") + (replace-match "" nil nil nil 1)) + (forward-line))) + ;; Comment each line in region. + (let ((min-indent (point-max))) + ;; First find the minimum indentation across all lines. + (save-excursion + (goto-char (point-min)) + (while (and (not (eobp)) (not (zerop min-indent))) + (unless (looking-at "[ \t]*$") + (setq min-indent (min min-indent (current-indentation)))) + (forward-line))) + ;; Then loop over all lines. + (save-excursion + (goto-char (point-min)) + (while (not (eobp)) + (unless (and (not comment-empty-lines) (looking-at "[ \t]*$")) + ;; Don't get fooled by invisible text (e.g. link path) + ;; when moving to column MIN-INDENT. + (let ((buffer-invisibility-spec nil)) + (org-move-to-column min-indent t)) + (insert comment-start)) + (forward-line))))))))) + +(defun org-comment-dwim (_arg) + "Call `comment-dwim' within a source edit buffer if needed." + (interactive "*P") + (if (org-in-src-block-p) + (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim)) + (call-interactively 'comment-dwim))) + + +;;; Timestamps API + +;; This section contains tools to operate on timestamp objects, as +;; returned by, e.g. `org-element-context'. + +(defun org-timestamp--to-internal-time (timestamp &optional end) + "Encode TIMESTAMP object into Emacs internal time. +Use end of date range or time range when END is non-nil." + (apply #'encode-time + (cons 0 + (mapcar + (lambda (prop) (or (org-element-property prop timestamp) 0)) + (if end '(:minute-end :hour-end :day-end :month-end :year-end) + '(:minute-start :hour-start :day-start :month-start + :year-start)))))) + +(defun org-timestamp-has-time-p (timestamp) + "Non-nil when TIMESTAMP has a time specified." + (org-element-property :hour-start timestamp)) + +(defun org-timestamp-format (timestamp format &optional end utc) + "Format a TIMESTAMP object into a string. + +FORMAT is a format specifier to be passed to +`format-time-string'. + +When optional argument END is non-nil, use end of date-range or +time-range, if possible. + +When optional argument UTC is non-nil, time will be expressed as +Universal Time." + (format-time-string + format (org-timestamp--to-internal-time timestamp end) + (and utc t))) + +(defun org-timestamp-split-range (timestamp &optional end) + "Extract a TIMESTAMP object from a date or time range. + +END, when non-nil, means extract the end of the range. +Otherwise, extract its start. + +Return a new timestamp object." + (let ((type (org-element-property :type timestamp))) + (if (memq type '(active inactive diary)) timestamp + (let ((split-ts (org-element-copy timestamp))) + ;; Set new type. + (org-element-put-property + split-ts :type (if (eq type 'active-range) 'active 'inactive)) + ;; Copy start properties over end properties if END is + ;; non-nil. Otherwise, copy end properties over `start' ones. + (let ((p-alist '((:minute-start . :minute-end) + (:hour-start . :hour-end) + (:day-start . :day-end) + (:month-start . :month-end) + (:year-start . :year-end)))) + (dolist (p-cell p-alist) + (org-element-put-property + split-ts + (funcall (if end #'car #'cdr) p-cell) + (org-element-property + (funcall (if end #'cdr #'car) p-cell) split-ts))) + ;; Eventually refresh `:raw-value'. + (org-element-put-property split-ts :raw-value nil) + (org-element-put-property + split-ts :raw-value (org-element-interpret-data split-ts))))))) + +(defun org-timestamp-translate (timestamp &optional boundary) + "Translate TIMESTAMP object to custom format. + +Format string is defined in `org-time-stamp-custom-formats', +which see. + +When optional argument BOUNDARY is non-nil, it is either the +symbol `start' or `end'. In this case, only translate the +starting or ending part of TIMESTAMP if it is a date or time +range. Otherwise, translate both parts. + +Return timestamp as-is if `org-display-custom-times' is nil or if +it has a `diary' type." + (let ((type (org-element-property :type timestamp))) + (if (or (not org-display-custom-times) (eq type 'diary)) + (org-element-interpret-data timestamp) + (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car) + org-time-stamp-custom-formats))) + (if (and (not boundary) (memq type '(active-range inactive-range))) + (concat (org-timestamp-format timestamp fmt) + "--" + (org-timestamp-format timestamp fmt t)) + (org-timestamp-format timestamp fmt (eq boundary 'end))))))) + + + +;;; Other stuff. + +(defvar reftex-docstruct-symbol) +(defvar org--rds) + +(defun org-reftex-citation () + "Use reftex-citation to insert a citation into the buffer. +This looks for a line like + +#+BIBLIOGRAPHY: foo plain option:-d + +and derives from it that foo.bib is the bibliography file relevant +for this document. It then installs the necessary environment for RefTeX +to work in this buffer and calls `reftex-citation' to insert a citation +into the buffer. + +Export of such citations to both LaTeX and HTML is handled by the contributed +package ox-bibtex by Taru Karttunen." + (interactive) + (let ((reftex-docstruct-symbol 'org--rds) + org--rds bib) + (org-with-wide-buffer + (let ((case-fold-search t) + (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)")) + (if (not (save-excursion + (or (re-search-forward re nil t) + (re-search-backward re nil t)))) + (user-error "No bibliography defined in file") + (setq bib (concat (match-string 1) ".bib") + org--rds (list (list 'bib bib)))))) + (call-interactively 'reftex-citation))) + +;;;; Functions extending outline functionality + +(defun org-beginning-of-line (&optional n) + "Go to the beginning of the current visible line. + +If this is a headline, and `org-special-ctrl-a/e' is set, ignore +tags on the first attempt, and only move to after the tags when +the cursor is already beyond the end of the headline. + +With argument N not nil or 1, move forward N - 1 lines first." + (interactive "^p") + (let ((origin (point)) + (special (pcase org-special-ctrl-a/e + (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e))) + deactivate-mark) + ;; First move to a visible line. + (if (bound-and-true-p visual-line-mode) + (beginning-of-visual-line n) + (move-beginning-of-line n) + ;; `move-beginning-of-line' may leave point after invisible + ;; characters if line starts with such of these (e.g., with + ;; a link at column 0). Really move to the beginning of the + ;; current visible line. + (beginning-of-line)) + (cond + ;; No special behavior. Point is already at the beginning of + ;; a line, logical or visual. + ((not special)) + ;; `beginning-of-visual-line' left point before logical beginning + ;; of line: point is at the beginning of a visual line. Bail + ;; out. + ((and (bound-and-true-p visual-line-mode) (not (bolp)))) + ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp)) + ;; At a headline, special position is before the title, but + ;; after any TODO keyword or priority cookie. + (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1))) + (line-end-position))) + (bol (point))) + (if (eq special 'reversed) + (when (and (= origin bol) (eq last-command this-command)) + (goto-char refpos)) + (when (or (> origin refpos) (= origin bol)) + (goto-char refpos))))) + ((and (looking-at org-list-full-item-re) + (memq (org-element-type (save-match-data (org-element-at-point))) + '(item plain-list))) + ;; Set special position at first white space character after + ;; bullet, and check-box, if any. + (let ((after-bullet + (let ((box (match-end 3))) + (cond ((not box) (match-end 1)) + ((eq (char-after box) ?\s) (1+ box)) + (t box))))) + (if (eq special 'reversed) + (when (and (= (point) origin) (eq last-command this-command)) + (goto-char after-bullet)) + (when (or (> origin after-bullet) (= (point) origin)) + (goto-char after-bullet))))) + ;; No special context. Point is already at beginning of line. + (t nil)))) + +(defun org-end-of-line (&optional n) + "Go to the end of the line, but before ellipsis, if any. + +If this is a headline, and `org-special-ctrl-a/e' is set, ignore +tags on the first attempt, and only move to after the tags when +the cursor is already beyond the end of the headline. + +With argument N not nil or 1, move forward N - 1 lines first." + (interactive "^p") + (let ((origin (point)) + (special (pcase org-special-ctrl-a/e + (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e))) + deactivate-mark) + ;; First move to a visible line. + (if (bound-and-true-p visual-line-mode) + (beginning-of-visual-line n) + (move-beginning-of-line n)) + (cond + ;; At a headline, with tags. + ((and special + (save-excursion + (beginning-of-line) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp))) + (match-end 5)) + (let ((tags (save-excursion + (goto-char (match-beginning 5)) + (skip-chars-backward " \t") + (point))) + (visual-end (and (bound-and-true-p visual-line-mode) + (save-excursion + (end-of-visual-line) + (point))))) + ;; If `end-of-visual-line' brings us before end of line or + ;; even tags, i.e., the headline spans over multiple visual + ;; lines, move there. + (cond ((and visual-end + (< visual-end tags) + (<= origin visual-end)) + (goto-char visual-end)) + ((eq special 'reversed) + (if (and (= origin (line-end-position)) + (eq this-command last-command)) + (goto-char tags) + (end-of-line))) + (t + (if (or (< origin tags) (= origin (line-end-position))) + (goto-char tags) + (end-of-line)))))) + ((bound-and-true-p visual-line-mode) + (let ((bol (line-beginning-position))) + (end-of-visual-line) + ;; If `end-of-visual-line' gets us past the ellipsis at the + ;; end of a line, backtrack and use `end-of-line' instead. + (when (/= bol (line-beginning-position)) + (goto-char bol) + (end-of-line)))) + (t (end-of-line))))) + +(define-key org-mode-map "\C-a" 'org-beginning-of-line) +(define-key org-mode-map "\C-e" 'org-end-of-line) + +(defun org-backward-sentence (&optional _arg) + "Go to beginning of sentence, or beginning of table field. +This will call `backward-sentence' or `org-table-beginning-of-field', +depending on context." + (interactive) + (let* ((element (org-element-at-point)) + (contents-begin (org-element-property :contents-begin element)) + (table (org-element-lineage element '(table) t))) + (if (and table + (> (point) contents-begin) + (<= (point) (org-element-property :contents-end table))) + (call-interactively #'org-table-beginning-of-field) + (save-restriction + (when (and contents-begin + (< (point-min) contents-begin) + (> (point) contents-begin)) + (narrow-to-region contents-begin + (org-element-property :contents-end element))) + (call-interactively #'backward-sentence))))) + +(defun org-forward-sentence (&optional _arg) + "Go to end of sentence, or end of table field. +This will call `forward-sentence' or `org-table-end-of-field', +depending on context." + (interactive) + (if (and (org-at-heading-p) + (save-restriction (skip-chars-forward " \t") (not (eolp)))) + (save-restriction + (narrow-to-region (line-beginning-position) (line-end-position)) + (call-interactively #'forward-sentence)) + (let* ((element (org-element-at-point)) + (contents-end (org-element-property :contents-end element)) + (table (org-element-lineage element '(table) t))) + (if (and table + (>= (point) (org-element-property :contents-begin table)) + (< (point) contents-end)) + (call-interactively #'org-table-end-of-field) + (save-restriction + (when (and contents-end + (> (point-max) contents-end) + ;; Skip blank lines between elements. + (< (org-element-property :end element) + (save-excursion (goto-char contents-end) + (skip-chars-forward " \r\t\n")))) + (narrow-to-region (org-element-property :contents-begin element) + contents-end)) + ;; End of heading is considered as the end of a sentence. + (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$"))) + (call-interactively #'forward-sentence))))))) + +(define-key org-mode-map "\M-a" 'org-backward-sentence) +(define-key org-mode-map "\M-e" 'org-forward-sentence) + +(defun org-kill-line (&optional _arg) + "Kill line, to tags or end of line." + (interactive) + (cond + ((or (not org-special-ctrl-k) + (bolp) + (not (org-at-heading-p))) + (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible) + org-ctrl-k-protect-subtree + (or (eq org-ctrl-k-protect-subtree 'error) + (not (y-or-n-p "Kill hidden subtree along with headline? ")))) + (user-error + (substitute-command-keys + "`\\[org-kill-line]' aborted as it would kill a hidden subtree"))) + (call-interactively + (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line))) + ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$") + (kill-region (point) (match-beginning 1)) + (org-set-tags nil t)) + (t (kill-region (point) (point-at-eol))))) + +(define-key org-mode-map "\C-k" 'org-kill-line) + +(defun org-yank (&optional arg) + "Yank. If the kill is a subtree, treat it specially. +This command will look at the current kill and check if is a single +subtree, or a series of subtrees[1]. If it passes the test, and if the +cursor is at the beginning of a line or after the stars of a currently +empty headline, then the yank is handled specially. How exactly depends +on the value of the following variables. + +`org-yank-folded-subtrees' + By default, this variable is non-nil, which results in + subtree(s) being folded after insertion, except if doing so + would swallow text after the yanked text. + +`org-yank-adjusted-subtrees' + When non-nil (the default value is nil), the subtree will be + promoted or demoted in order to fit into the local outline tree + structure, which means that the level will be adjusted so that it + becomes the smaller one of the two *visible* surrounding headings. + +Any prefix to this command will cause `yank' to be called directly with +no special treatment. In particular, a simple `\\[universal-argument]' prefix \ +will just +plainly yank the text as it is. + +\[1] The test checks if the first non-white line is a heading + and if there are no other headings with fewer stars." + (interactive "P") + (org-yank-generic 'yank arg)) + +(defun org-yank-generic (command arg) + "Perform some yank-like command. + +This function implements the behavior described in the `org-yank' +documentation. However, it has been generalized to work for any +interactive command with similar behavior." + + ;; pretend to be command COMMAND + (setq this-command command) + + (if arg + (call-interactively command) + + (let ((subtreep ; is kill a subtree, and the yank position appropriate? + (and (org-kill-is-subtree-p) + (or (bolp) + (and (looking-at "[ \t]*$") + (string-match + "\\`\\*+\\'" + (buffer-substring (point-at-bol) (point))))))) + swallowp) + (cond + ((and subtreep org-yank-folded-subtrees) + (let ((beg (point)) + end) + (if (and subtreep org-yank-adjusted-subtrees) + (org-paste-subtree nil nil 'for-yank) + (call-interactively command)) + + (setq end (point)) + (goto-char beg) + (when (and (bolp) subtreep + (not (setq swallowp + (org-yank-folding-would-swallow-text beg end)))) + (org-with-limited-levels + (or (looking-at org-outline-regexp) + (re-search-forward org-outline-regexp-bol end t)) + (while (and (< (point) end) (looking-at org-outline-regexp)) + (outline-hide-subtree) + (org-cycle-show-empty-lines 'folded) + (condition-case nil + (outline-forward-same-level 1) + (error (goto-char end)))))) + (when swallowp + (message + "Inserted text not folded because that would swallow text")) + + (goto-char end) + (skip-chars-forward " \t\n\r") + (beginning-of-line 1) + (push-mark beg 'nomsg))) + ((and subtreep org-yank-adjusted-subtrees) + (let ((beg (point-at-bol))) + (org-paste-subtree nil nil 'for-yank) + (push-mark beg 'nomsg))) + (t + (call-interactively command)))))) + +(defun org-yank-folding-would-swallow-text (beg end) + "Would hide-subtree at BEG swallow any text after END?" + (let (level) + (org-with-limited-levels + (save-excursion + (goto-char beg) + (when (or (looking-at org-outline-regexp) + (re-search-forward org-outline-regexp-bol end t)) + (setq level (org-outline-level))) + (goto-char end) + (skip-chars-forward " \t\r\n\v\f") + (not (or (eobp) + (and (bolp) (looking-at-p org-outline-regexp) + (<= (org-outline-level) level)))))))) + +(define-key org-mode-map "\C-y" 'org-yank) + +(defun org-truely-invisible-p () + "Check if point is at a character currently not visible. +This version does not only check the character property, but also +`visible-mode'." + (unless (bound-and-true-p visible-mode) + (org-invisible-p))) + +(defun org-invisible-p2 () + "Check if point is at a character currently not visible. + +If the point is at EOL (and not at the beginning of a buffer too), +move it back by one char before doing this check." + (save-excursion + (when (and (eolp) (not (bobp))) + (backward-char 1)) + (org-invisible-p))) + +(defun org-back-to-heading (&optional invisible-ok) + "Call `outline-back-to-heading', but provide a better error message." + (condition-case nil + (outline-back-to-heading invisible-ok) + (error (error "Before first headline at position %d in buffer %s" + (point) (current-buffer))))) + +(defun org-before-first-heading-p () + "Before first heading?" + (save-excursion + (end-of-line) + (null (re-search-backward org-outline-regexp-bol nil t)))) + +(defun org-at-heading-p (&optional ignored) + (outline-on-heading-p t)) + +(defun org-in-commented-heading-p (&optional no-inheritance) + "Non-nil if point is under a commented heading. +This function also checks ancestors of the current headline, +unless optional argument NO-INHERITANCE is non-nil." + (cond + ((org-before-first-heading-p) nil) + ((let ((headline (nth 4 (org-heading-components)))) + (and headline + (let ((case-fold-search nil)) + (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)") + headline))))) + (no-inheritance nil) + (t + (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p)))))) + +(defun org-at-comment-p nil + "Is cursor in a commented line?" + (save-excursion + (save-match-data + (beginning-of-line) + (looking-at "^[ \t]*# ")))) + +(defun org-at-drawer-p nil + "Is cursor at a drawer keyword?" + (save-excursion + (move-beginning-of-line 1) + (looking-at org-drawer-regexp))) + +(defun org-at-block-p nil + "Is cursor at a block keyword?" + (save-excursion + (move-beginning-of-line 1) + (looking-at org-block-regexp))) + +(defun org-point-at-end-of-empty-headline () + "If point is at the end of an empty headline, return t, else nil. +If the heading only contains a TODO keyword, it is still still considered +empty." + (let ((case-fold-search nil)) + (and (looking-at "[ \t]*$") + org-todo-line-regexp + (save-excursion + (beginning-of-line) + (looking-at org-todo-line-regexp) + (string= (match-string 3) ""))))) + +(defun org-at-heading-or-item-p () + (or (org-at-heading-p) (org-at-item-p))) + +(defun org-at-target-p () + (or (org-in-regexp org-radio-target-regexp) + (org-in-regexp org-target-regexp))) +;; Compatibility alias with Org versions < 7.8.03 +(defalias 'org-on-target-p 'org-at-target-p) + +(defun org-up-heading-all (arg) + "Move to the heading line of which the present line is a subheading. +This function considers both visible and invisible heading lines. +With argument, move up ARG levels." + (outline-up-heading arg t)) + +(defun org-up-heading-safe () + "Move to the heading line of which the present line is a subheading. +This version will not throw an error. It will return the level of the +headline found, or nil if no higher level is found. + +Also, this function will be a lot faster than `outline-up-heading', +because it relies on stars being the outline starters. This can really +make a significant difference in outlines with very many siblings." + (when (ignore-errors (org-back-to-heading t)) + (let ((level-up (1- (funcall outline-level)))) + (and (> level-up 0) + (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t) + (funcall outline-level))))) + +(defun org-first-sibling-p () + "Is this heading the first child of its parents?" + (interactive) + (let ((re org-outline-regexp-bol) + level l) + (unless (org-at-heading-p t) + (user-error "Not at a heading")) + (setq level (funcall outline-level)) + (save-excursion + (if (not (re-search-backward re nil t)) + t + (setq l (funcall outline-level)) + (< l level))))) + +(defun org-goto-sibling (&optional previous) + "Goto the next sibling, even if it is invisible. +When PREVIOUS is set, go to the previous sibling instead. Returns t +when a sibling was found. When none is found, return nil and don't +move point." + (let ((fun (if previous 're-search-backward 're-search-forward)) + (pos (point)) + (re org-outline-regexp-bol) + level l) + (when (ignore-errors (org-back-to-heading t)) + (setq level (funcall outline-level)) + (catch 'exit + (or previous (forward-char 1)) + (while (funcall fun re nil t) + (setq l (funcall outline-level)) + (when (< l level) (goto-char pos) (throw 'exit nil)) + (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t))) + (goto-char pos) + nil)))) + +(defun org-show-siblings () + "Show all siblings of the current headline." + (save-excursion + (while (org-goto-sibling) (org-flag-heading nil))) + (save-excursion + (while (org-goto-sibling 'previous) + (org-flag-heading nil)))) + +(defun org-goto-first-child () + "Goto the first child, even if it is invisible. +Return t when a child was found. Otherwise don't move point and +return nil." + (let (level (pos (point)) (re org-outline-regexp-bol)) + (when (ignore-errors (org-back-to-heading t)) + (setq level (outline-level)) + (forward-char 1) + (if (and (re-search-forward re nil t) (> (outline-level) level)) + (progn (goto-char (match-beginning 0)) t) + (goto-char pos) nil)))) + +(defun org-show-hidden-entry () + "Show an entry where even the heading is hidden." + (save-excursion + (org-show-entry))) + +(defun org-flag-heading (flag &optional entry) + "Flag the current heading. FLAG non-nil means make invisible. +When ENTRY is non-nil, show the entire entry." + (save-excursion + (org-back-to-heading t) + ;; Check if we should show the entire entry + (if entry + (progn + (org-show-entry) + (save-excursion + (and (outline-next-heading) + (org-flag-heading nil)))) + (outline-flag-region (max (point-min) (1- (point))) + (save-excursion (outline-end-of-heading) (point)) + flag)))) + +(defun org-get-next-sibling () + "Move to next heading of the same level, and return point. +If there is no such heading, return nil. +This is like outline-next-sibling, but invisible headings are ok." + (let ((level (funcall outline-level))) + (outline-next-heading) + (while (and (not (eobp)) (> (funcall outline-level) level)) + (outline-next-heading)) + (unless (or (eobp) (< (funcall outline-level) level)) + (point)))) + +(defun org-get-last-sibling () + "Move to previous heading of the same level, and return point. +If there is no such heading, return nil." + (let ((opoint (point)) + (level (funcall outline-level))) + (outline-previous-heading) + (when (and (/= (point) opoint) (outline-on-heading-p t)) + (while (and (> (funcall outline-level) level) + (not (bobp))) + (outline-previous-heading)) + (unless (< (funcall outline-level) level) + (point))))) + +(defun org-end-of-subtree (&optional invisible-ok to-heading) + "Goto to the end of a subtree." + ;; This contains an exact copy of the original function, but it uses + ;; `org-back-to-heading', to make it work also in invisible + ;; trees. And is uses an invisible-ok argument. + ;; Under Emacs this is not needed, but the old outline.el needs this fix. + ;; Furthermore, when used inside Org, finding the end of a large subtree + ;; with many children and grandchildren etc, this can be much faster + ;; than the outline version. + (org-back-to-heading invisible-ok) + (let ((first t) + (level (funcall outline-level))) + (if (and (derived-mode-p 'org-mode) (< level 1000)) + ;; A true heading (not a plain list item), in Org + ;; This means we can easily find the end by looking + ;; only for the right number of stars. Using a regexp to do + ;; this is so much faster than using a Lisp loop. + (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} "))) + (forward-char 1) + (and (re-search-forward re nil 'move) (beginning-of-line 1))) + ;; something else, do it the slow way + (while (and (not (eobp)) + (or first (> (funcall outline-level) level))) + (setq first nil) + (outline-next-heading))) + (unless to-heading + (when (memq (preceding-char) '(?\n ?\^M)) + ;; Go to end of line before heading + (forward-char -1) + (when (memq (preceding-char) '(?\n ?\^M)) + ;; leave blank line before heading + (forward-char -1))))) + (point)) + +(defun org-end-of-meta-data (&optional full) + "Skip planning line and properties drawer in current entry. +When optional argument FULL is non-nil, also skip empty lines, +clocking lines and regular drawers at the beginning of the +entry." + (org-back-to-heading t) + (forward-line) + (when (looking-at-p org-planning-line-re) (forward-line)) + (when (looking-at org-property-drawer-re) + (goto-char (match-end 0)) + (forward-line)) + (when (and full (not (org-at-heading-p))) + (catch 'exit + (let ((end (save-excursion (outline-next-heading) (point))) + (re (concat "[ \t]*$" "\\|" org-clock-line-re))) + (while (not (eobp)) + (cond ((looking-at-p org-drawer-regexp) + (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t) + (forward-line) + (throw 'exit t))) + ((looking-at-p re) (forward-line)) + (t (throw 'exit t)))))))) + +(defun org-forward-heading-same-level (arg &optional invisible-ok) + "Move forward to the ARG'th subheading at same level as this one. +Stop at the first and last subheadings of a superior heading. +Normally this only looks at visible headings, but when INVISIBLE-OK is +non-nil it will also look at invisible ones." + (interactive "p") + (let ((backward? (and arg (< arg 0)))) + (if (org-before-first-heading-p) + (if backward? (goto-char (point-min)) (outline-next-heading)) + (org-back-to-heading invisible-ok) + (unless backward? (end-of-line)) ;do not match current headline + (let ((level (- (match-end 0) (match-beginning 0) 1)) + (f (if backward? #'re-search-backward #'re-search-forward)) + (count (if arg (abs arg) 1)) + (result (point))) + (while (and (> count 0) + (funcall f org-outline-regexp-bol nil 'move)) + (let ((l (- (match-end 0) (match-beginning 0) 1))) + (cond ((< l level) (setq count 0)) + ((and (= l level) + (or invisible-ok + (not (org-invisible-p + (line-beginning-position))))) + (cl-decf count) + (when (= l level) (setq result (point))))))) + (goto-char result)) + (beginning-of-line)))) + +(defun org-backward-heading-same-level (arg &optional invisible-ok) + "Move backward to the ARG'th subheading at same level as this one. +Stop at the first and last subheadings of a superior heading." + (interactive "p") + (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok)) + +(defun org-next-visible-heading (arg) + "Move to the next visible heading. + +This function wraps `outline-next-visible-heading' with +`org-with-limited-levels' in order to skip over inline tasks and +respect customization of `org-odd-levels-only'." + (interactive "p") + (org-with-limited-levels + (outline-next-visible-heading arg))) + +(defun org-previous-visible-heading (arg) + "Move to the previous visible heading. + +This function wraps `outline-previous-visible-heading' with +`org-with-limited-levels' in order to skip over inline tasks and +respect customization of `org-odd-levels-only'." + (interactive "p") + (org-with-limited-levels + (outline-previous-visible-heading arg))) + +(defun org-next-block (arg &optional backward block-regexp) + "Jump to the next block. + +With a prefix argument ARG, jump forward ARG many blocks. + +When BACKWARD is non-nil, jump to the previous block. + +When BLOCK-REGEXP is non-nil, use this regexp to find blocks. +Match data is set according to this regexp when the function +returns. + +Return point at beginning of the opening line of found block. +Throw an error if no block is found." + (interactive "p") + (let ((re (or block-regexp "^[ \t]*#\\+BEGIN")) + (case-fold-search t) + (search-fn (if backward #'re-search-backward #'re-search-forward)) + (count (or arg 1)) + (origin (point)) + last-element) + (if backward (beginning-of-line) (end-of-line)) + (while (and (> count 0) (funcall search-fn re nil t)) + (let ((element (save-excursion + (goto-char (match-beginning 0)) + (save-match-data (org-element-at-point))))) + (when (and (memq (org-element-type element) + '(center-block comment-block dynamic-block + example-block export-block quote-block + special-block src-block verse-block)) + (<= (match-beginning 0) + (org-element-property :post-affiliated element))) + (setq last-element element) + (cl-decf count)))) + (if (= count 0) + (prog1 (goto-char (org-element-property :post-affiliated last-element)) + (save-match-data (org-show-context))) + (goto-char origin) + (user-error "No %s code blocks" (if backward "previous" "further"))))) + +(defun org-previous-block (arg &optional block-regexp) + "Jump to the previous block. +With a prefix argument ARG, jump backward ARG many source blocks. +When BLOCK-REGEXP is non-nil, use this regexp to find blocks." + (interactive "p") + (org-next-block arg t block-regexp)) + +(defun org-forward-paragraph () + "Move forward to beginning of next paragraph or equivalent. + +The function moves point to the beginning of the next visible +structural element, which can be a paragraph, a table, a list +item, etc. It also provides some special moves for convenience: + + - On an affiliated keyword, jump to the beginning of the + relative element. + - On an item or a footnote definition, move to the second + element inside, if any. + - On a table or a property drawer, jump after it. + - On a verse or source block, stop after blank lines." + (interactive) + (unless (eobp) + (let* ((deactivate-mark nil) + (element (org-element-at-point)) + (type (org-element-type element)) + (post-affiliated (org-element-property :post-affiliated element)) + (contents-begin (org-element-property :contents-begin element)) + (contents-end (org-element-property :contents-end element)) + (end (let ((end (org-element-property :end element)) (parent element)) + (while (and (setq parent (org-element-property :parent parent)) + (= (org-element-property :contents-end parent) end)) + (setq end (org-element-property :end parent))) + end))) + (cond ((not element) + (skip-chars-forward " \r\t\n") + (or (eobp) (beginning-of-line))) + ;; On affiliated keywords, move to element's beginning. + ((< (point) post-affiliated) + (goto-char post-affiliated)) + ;; At a table row, move to the end of the table. Similarly, + ;; at a node property, move to the end of the property + ;; drawer. + ((memq type '(node-property table-row)) + (goto-char (org-element-property + :end (org-element-property :parent element)))) + ((memq type '(property-drawer table)) (goto-char end)) + ;; Consider blank lines as separators in verse and source + ;; blocks to ease editing. + ((memq type '(src-block verse-block)) + (when (eq type 'src-block) + (setq contents-end + (save-excursion (goto-char end) + (skip-chars-backward " \r\t\n") + (line-beginning-position)))) + (beginning-of-line) + (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n")) + (if (not (re-search-forward "^[ \t]*$" contents-end t)) + (goto-char end) + (skip-chars-forward " \r\t\n") + (if (= (point) contents-end) (goto-char end) + (beginning-of-line)))) + ;; With no contents, just skip element. + ((not contents-begin) (goto-char end)) + ;; If contents are invisible, skip the element altogether. + ((org-invisible-p (line-end-position)) + (cl-case type + (headline + (org-with-limited-levels (outline-next-visible-heading 1))) + ;; At a plain list, make sure we move to the next item + ;; instead of skipping the whole list. + (plain-list (forward-char) + (org-forward-paragraph)) + (otherwise (goto-char end)))) + ((>= (point) contents-end) (goto-char end)) + ((>= (point) contents-begin) + ;; This can only happen on paragraphs and plain lists. + (cl-case type + (paragraph (goto-char end)) + ;; At a plain list, try to move to second element in + ;; first item, if possible. + (plain-list (end-of-line) + (org-forward-paragraph)))) + ;; When contents start on the middle of a line (e.g. in + ;; items and footnote definitions), try to reach first + ;; element starting after current line. + ((> (line-end-position) contents-begin) + (end-of-line) + (org-forward-paragraph)) + (t (goto-char contents-begin)))))) + +(defun org-backward-paragraph () + "Move backward to start of previous paragraph or equivalent. + +The function moves point to the beginning of the current +structural element, which can be a paragraph, a table, a list +item, etc., or to the beginning of the previous visible one if +point is already there. It also provides some special moves for +convenience: + + - On an affiliated keyword, jump to the first one. + - On a table or a property drawer, move to its beginning. + - On comment, example, export, src and verse blocks, stop + before blank lines." + (interactive) + (unless (bobp) + (let* ((deactivate-mark nil) + (element (org-element-at-point)) + (type (org-element-type element)) + (contents-end (org-element-property :contents-end element)) + (post-affiliated (org-element-property :post-affiliated element)) + (begin (org-element-property :begin element)) + (special? ;blocks handled specially + (memq type '(comment-block example-block export-block src-block + verse-block))) + (contents-begin + (if special? + ;; These types have no proper contents. Fake line + ;; below the block opening line as contents beginning. + (save-excursion (goto-char begin) (line-beginning-position 2)) + (org-element-property :contents-begin element)))) + (cond + ((not element) (goto-char (point-min))) + ((= (point) begin) + (backward-char) + (org-backward-paragraph)) + ((<= (point) post-affiliated) (goto-char begin)) + ;; Special behavior: on a table or a property drawer, move to + ;; its beginning. + ((memq type '(node-property table-row)) + (goto-char (org-element-property + :post-affiliated (org-element-property :parent element)))) + (special? + (if (<= (point) contents-begin) (goto-char post-affiliated) + ;; Inside a verse block, see blank lines as paragraph + ;; separators. + (let ((origin (point))) + (skip-chars-backward " \r\t\n" contents-begin) + (when (re-search-backward "^[ \t]*$" contents-begin 'move) + (skip-chars-forward " \r\t\n" origin) + (if (= (point) origin) (goto-char contents-begin) + (beginning-of-line)))))) + ((eq type 'paragraph) (goto-char contents-begin) + ;; When at first paragraph in an item or a footnote definition, + ;; move directly to beginning of line. + (let ((parent-contents + (org-element-property + :contents-begin (org-element-property :parent element)))) + (when (and parent-contents (= parent-contents contents-begin)) + (beginning-of-line)))) + ;; At the end of a greater element, move to the beginning of + ;; the last element within. + ((and contents-end (>= (point) contents-end)) + (goto-char (1- contents-end)) + (org-backward-paragraph)) + (t (goto-char (or post-affiliated begin)))) + ;; Ensure we never leave point invisible. + (when (org-invisible-p (point)) (beginning-of-visual-line))))) + +(defun org-forward-element () + "Move forward by one element. +Move to the next element at the same level, when possible." + (interactive) + (cond ((eobp) (user-error "Cannot move further down")) + ((org-with-limited-levels (org-at-heading-p)) + (let ((origin (point))) + (goto-char (org-end-of-subtree nil t)) + (unless (org-with-limited-levels (org-at-heading-p)) + (goto-char origin) + (user-error "Cannot move further down")))) + (t + (let* ((elem (org-element-at-point)) + (end (org-element-property :end elem)) + (parent (org-element-property :parent elem))) + (cond ((and parent (= (org-element-property :contents-end parent) end)) + (goto-char (org-element-property :end parent))) + ((integer-or-marker-p end) (goto-char end)) + (t (message "No element at point"))))))) + +(defun org-backward-element () + "Move backward by one element. +Move to the previous element at the same level, when possible." + (interactive) + (cond ((bobp) (user-error "Cannot move further up")) + ((org-with-limited-levels (org-at-heading-p)) + ;; At a headline, move to the previous one, if any, or stay + ;; here. + (let ((origin (point))) + (org-with-limited-levels (org-backward-heading-same-level 1)) + ;; When current headline has no sibling above, move to its + ;; parent. + (when (= (point) origin) + (or (org-with-limited-levels (org-up-heading-safe)) + (progn (goto-char origin) + (user-error "Cannot move further up")))))) + (t + (let* ((elem (org-element-at-point)) + (beg (org-element-property :begin elem))) + (cond + ;; Move to beginning of current element if point isn't + ;; there already. + ((null beg) (message "No element at point")) + ((/= (point) beg) (goto-char beg)) + (t (goto-char beg) + (skip-chars-backward " \r\t\n") + (unless (bobp) + (let ((prev (org-element-at-point))) + (goto-char (org-element-property :begin prev)) + (while (and (setq prev (org-element-property :parent prev)) + (<= (org-element-property :end prev) beg)) + (goto-char (org-element-property :begin prev))))))))))) + +(defun org-up-element () + "Move to upper element." + (interactive) + (if (org-with-limited-levels (org-at-heading-p)) + (unless (org-up-heading-safe) (user-error "No surrounding element")) + (let* ((elem (org-element-at-point)) + (parent (org-element-property :parent elem))) + (if parent (goto-char (org-element-property :begin parent)) + (if (org-with-limited-levels (org-before-first-heading-p)) + (user-error "No surrounding element") + (org-with-limited-levels (org-back-to-heading))))))) + +(defun org-down-element () + "Move to inner element." + (interactive) + (let ((element (org-element-at-point))) + (cond + ((memq (org-element-type element) '(plain-list table)) + (goto-char (org-element-property :contents-begin element)) + (forward-char)) + ((memq (org-element-type element) org-element-greater-elements) + ;; If contents are hidden, first disclose them. + (when (org-invisible-p (line-end-position)) (org-cycle)) + (goto-char (or (org-element-property :contents-begin element) + (user-error "No content for this element")))) + (t (user-error "No inner element"))))) + +(defun org-drag-element-backward () + "Move backward element at point." + (interactive) + (let ((elem (or (org-element-at-point) + (user-error "No element at point")))) + (if (eq (org-element-type elem) 'headline) + ;; Preserve point when moving a whole tree, even if point was + ;; on blank lines below the headline. + (let ((offset (skip-chars-backward " \t\n"))) + (unwind-protect (org-move-subtree-up) + (forward-char (- offset)))) + (let ((prev-elem + (save-excursion + (goto-char (org-element-property :begin elem)) + (skip-chars-backward " \r\t\n") + (unless (bobp) + (let* ((beg (org-element-property :begin elem)) + (prev (org-element-at-point)) + (up prev)) + (while (and (setq up (org-element-property :parent up)) + (<= (org-element-property :end up) beg)) + (setq prev up)) + prev))))) + ;; Error out if no previous element or previous element is + ;; a parent of the current one. + (if (or (not prev-elem) (org-element-nested-p elem prev-elem)) + (user-error "Cannot drag element backward") + (let ((pos (point))) + (org-element-swap-A-B prev-elem elem) + (goto-char (+ (org-element-property :begin prev-elem) + (- pos (org-element-property :begin elem)))))))))) + +(defun org-drag-element-forward () + "Move forward element at point." + (interactive) + (let* ((pos (point)) + (elem (or (org-element-at-point) + (user-error "No element at point")))) + (when (= (point-max) (org-element-property :end elem)) + (user-error "Cannot drag element forward")) + (goto-char (org-element-property :end elem)) + (let ((next-elem (org-element-at-point))) + (when (or (org-element-nested-p elem next-elem) + (and (eq (org-element-type next-elem) 'headline) + (not (eq (org-element-type elem) 'headline)))) + (goto-char pos) + (user-error "Cannot drag element forward")) + ;; Compute new position of point: it's shifted by NEXT-ELEM + ;; body's length (without final blanks) and by the length of + ;; blanks between ELEM and NEXT-ELEM. + (let ((size-next (- (save-excursion + (goto-char (org-element-property :end next-elem)) + (skip-chars-backward " \r\t\n") + (forward-line) + ;; Small correction if buffer doesn't end + ;; with a newline character. + (if (and (eolp) (not (bolp))) (1+ (point)) (point))) + (org-element-property :begin next-elem))) + (size-blank (- (org-element-property :end elem) + (save-excursion + (goto-char (org-element-property :end elem)) + (skip-chars-backward " \r\t\n") + (forward-line) + (point))))) + (org-element-swap-A-B elem next-elem) + (goto-char (+ pos size-next size-blank)))))) + +(defun org-drag-line-forward (arg) + "Drag the line at point ARG lines forward." + (interactive "p") + (dotimes (_ (abs arg)) + (let ((c (current-column))) + (if (< 0 arg) + (progn + (beginning-of-line 2) + (transpose-lines 1) + (beginning-of-line 0)) + (transpose-lines 1) + (beginning-of-line -1)) + (org-move-to-column c)))) + +(defun org-drag-line-backward (arg) + "Drag the line at point ARG lines backward." + (interactive "p") + (org-drag-line-forward (- arg))) + +(defun org-mark-element () + "Put point at beginning of this element, mark at end. + +Interactively, if this command is repeated or (in Transient Mark +mode) if the mark is active, it marks the next element after the +ones already marked." + (interactive) + (let (deactivate-mark) + (if (and (called-interactively-p 'any) + (or (and (eq last-command this-command) (mark t)) + (and transient-mark-mode mark-active))) + (set-mark + (save-excursion + (goto-char (mark)) + (goto-char (org-element-property :end (org-element-at-point))))) + (let ((element (org-element-at-point))) + (end-of-line) + (push-mark (org-element-property :end element) t t) + (goto-char (org-element-property :begin element)))))) + +(defun org-narrow-to-element () + "Narrow buffer to current element." + (interactive) + (let ((elem (org-element-at-point))) + (cond + ((eq (car elem) 'headline) + (narrow-to-region + (org-element-property :begin elem) + (org-element-property :end elem))) + ((memq (car elem) org-element-greater-elements) + (narrow-to-region + (org-element-property :contents-begin elem) + (org-element-property :contents-end elem))) + (t + (narrow-to-region + (org-element-property :begin elem) + (org-element-property :end elem)))))) + +(defun org-transpose-element () + "Transpose current and previous elements, keeping blank lines between. +Point is moved after both elements." + (interactive) + (org-skip-whitespace) + (let ((end (org-element-property :end (org-element-at-point)))) + (org-drag-element-backward) + (goto-char end))) + +(defun org-unindent-buffer () + "Un-indent the visible part of the buffer. +Relative indentation (between items, inside blocks, etc.) isn't +modified." + (interactive) + (unless (eq major-mode 'org-mode) + (user-error "Cannot un-indent a buffer not in Org mode")) + (letrec ((parse-tree (org-element-parse-buffer 'greater-element)) + (unindent-tree + (lambda (contents) + (dolist (element (reverse contents)) + (if (memq (org-element-type element) '(headline section)) + (funcall unindent-tree (org-element-contents element)) + (save-excursion + (save-restriction + (narrow-to-region + (org-element-property :begin element) + (org-element-property :end element)) + (org-do-remove-indentation)))))))) + (funcall unindent-tree (org-element-contents parse-tree)))) + +(defun org-show-children (&optional level) + "Show all direct subheadings of this heading. +Prefix arg LEVEL is how many levels below the current level +should be shown. Default is enough to cause the following +heading to appear." + (interactive "p") + ;; If `orgstruct-mode' is active, use the slower version. + (if orgstruct-mode (call-interactively #'outline-show-children) + (save-excursion + (org-back-to-heading t) + (let* ((current-level (funcall outline-level)) + (max-level (org-get-valid-level + current-level + (if level (prefix-numeric-value level) 1))) + (end (save-excursion (org-end-of-subtree t t))) + (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)") + (past-first-child nil) + ;; Make sure to skip inlinetasks. + (re (format regexp-fmt + current-level + (cond + ((not (featurep 'org-inlinetask)) "") + (org-odd-levels-only (- (* 2 org-inlinetask-min-level) + 3)) + (t (1- org-inlinetask-min-level)))))) + ;; Display parent heading. + (outline-flag-region (line-end-position 0) (line-end-position) nil) + (forward-line) + ;; Display children. First child may be deeper than expected + ;; MAX-LEVEL. Since we want to display it anyway, adjust + ;; MAX-LEVEL accordingly. + (while (re-search-forward re end t) + (unless past-first-child + (setq re (format regexp-fmt + current-level + (max (funcall outline-level) max-level))) + (setq past-first-child t)) + (outline-flag-region + (line-end-position 0) (line-end-position) nil)))))) + +(defun org-show-subtree () + "Show everything after this heading at deeper levels." + (interactive) + (outline-flag-region + (point) + (save-excursion + (org-end-of-subtree t t)) + nil)) + +(defun org-show-entry () + "Show the body directly following this heading. +Show the heading too, if it is currently invisible." + (interactive) + (save-excursion + (ignore-errors + (org-back-to-heading t) + (outline-flag-region + (max (point-min) (1- (point))) + (save-excursion + (if (re-search-forward + (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t) + (match-beginning 1) + (point-max))) + nil) + (org-cycle-hide-drawers 'children)))) + +(defun org-make-options-regexp (kwds &optional extra) + "Make a regular expression for keyword lines. +KWDS is a list of keywords, as strings. Optional argument EXTRA, +when non-nil, is a regexp matching keywords names." + (concat "^[ \t]*#\\+\\(" + (regexp-opt kwds) + (and extra (concat (and kwds "\\|") extra)) + "\\):[ \t]*\\(.*\\)")) + +;;;; Integration with and fixes for other packages + +;;; Imenu support + +(defvar-local org-imenu-markers nil + "All markers currently used by Imenu.") + +(defun org-imenu-new-marker (&optional pos) + "Return a new marker for use by Imenu, and remember the marker." + (let ((m (make-marker))) + (move-marker m (or pos (point))) + (push m org-imenu-markers) + m)) + +(defun org-imenu-get-tree () + "Produce the index for Imenu." + (dolist (x org-imenu-markers) (move-marker x nil)) + (setq org-imenu-markers nil) + (let* ((case-fold-search nil) + (n org-imenu-depth) + (re (concat "^" (org-get-limited-outline-regexp))) + (subs (make-vector (1+ n) nil)) + (last-level 0) + m level head0 head) + (org-with-wide-buffer + (goto-char (point-max)) + (while (re-search-backward re nil t) + (setq level (org-reduced-level (funcall outline-level))) + (when (and (<= level n) + (looking-at org-complex-heading-regexp) + (setq head0 (match-string-no-properties 4))) + (setq head (org-link-display-format head0) + m (org-imenu-new-marker)) + (org-add-props head nil 'org-imenu-marker m 'org-imenu t) + (if (>= level last-level) + (push (cons head m) (aref subs level)) + (push (cons head (aref subs (1+ level))) (aref subs level)) + (cl-loop for i from (1+ level) to n do (aset subs i nil))) + (setq last-level level)))) + (aref subs 1))) + +(eval-after-load "imenu" + '(progn + (add-hook 'imenu-after-jump-hook + (lambda () + (when (derived-mode-p 'org-mode) + (org-show-context 'org-goto)))))) + +(defun org-link-display-format (s) + "Replace links in string S with their description. +If there is no description, use the link target." + (save-match-data + (replace-regexp-in-string + org-bracket-link-analytic-regexp + (lambda (m) + (if (match-end 5) (match-string 5 m) + (concat (match-string 1 m) (match-string 3 m)))) + s nil t))) + +(defun org-toggle-link-display () + "Toggle the literal or descriptive display of links." + (interactive) + (if org-descriptive-links + (progn (org-remove-from-invisibility-spec '(org-link)) + (org-restart-font-lock) + (setq org-descriptive-links nil)) + (progn (add-to-invisibility-spec '(org-link)) + (org-restart-font-lock) + (setq org-descriptive-links t)))) + +;; Speedbar support + +(defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1) + "Overlay marking the agenda restriction line in speedbar.") +(overlay-put org-speedbar-restriction-lock-overlay + 'face 'org-agenda-restriction-lock) +(overlay-put org-speedbar-restriction-lock-overlay + 'help-echo "Agendas are currently limited to this item.") +(delete-overlay org-speedbar-restriction-lock-overlay) + +(defun org-speedbar-set-agenda-restriction () + "Restrict future agenda commands to the location at point in speedbar. +To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'." + (interactive) + (require 'org-agenda) + (let (p m tp np dir txt) + (cond + ((setq p (text-property-any (point-at-bol) (point-at-eol) + 'org-imenu t)) + (setq m (get-text-property p 'org-imenu-marker)) + (with-current-buffer (marker-buffer m) + (goto-char m) + (org-agenda-set-restriction-lock 'subtree))) + ((setq p (text-property-any (point-at-bol) (point-at-eol) + 'speedbar-function 'speedbar-find-file)) + (setq tp (previous-single-property-change + (1+ p) 'speedbar-function) + np (next-single-property-change + tp 'speedbar-function) + dir (speedbar-line-directory) + txt (buffer-substring-no-properties (or tp (point-min)) + (or np (point-max)))) + (with-current-buffer (find-file-noselect + (let ((default-directory dir)) + (expand-file-name txt))) + (unless (derived-mode-p 'org-mode) + (user-error "Cannot restrict to non-Org mode file")) + (org-agenda-set-restriction-lock 'file))) + (t (user-error "Don't know how to restrict Org mode agenda"))) + (move-overlay org-speedbar-restriction-lock-overlay + (point-at-bol) (point-at-eol)) + (setq current-prefix-arg nil) + (org-agenda-maybe-redo))) + +(defvar speedbar-file-key-map) +(declare-function speedbar-add-supported-extension "speedbar" (extension)) +(eval-after-load "speedbar" + '(progn + (speedbar-add-supported-extension ".org") + (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction) + (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction) + (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock) + (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock) + (add-hook 'speedbar-visiting-tag-hook + (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto)))))) + +;;; Fixes and Hacks for problems with other packages + +(defun org--flyspell-object-check-p (element) + "Non-nil when Flyspell can check object at point. +ELEMENT is the element at point." + (let ((object (save-excursion + (when (looking-at-p "\\>") (backward-char)) + (org-element-context element)))) + (cl-case (org-element-type object) + ;; Prevent checks in links due to keybinding conflict with + ;; Flyspell. + ((code entity export-snippet inline-babel-call + inline-src-block line-break latex-fragment link macro + statistics-cookie target timestamp verbatim) + nil) + (footnote-reference + ;; Only in inline footnotes, within the definition. + (and (eq (org-element-property :type object) 'inline) + (< (save-excursion + (goto-char (org-element-property :begin object)) + (search-forward ":" nil t 2)) + (point)))) + (otherwise t)))) + +(defun org-mode-flyspell-verify () + "Function used for `flyspell-generic-check-word-predicate'." + (if (org-at-heading-p) + ;; At a headline or an inlinetask, check title only. This is + ;; faster than relying on `org-element-at-point'. + (and (save-excursion (beginning-of-line) + (and (let ((case-fold-search t)) + (not (looking-at-p "\\*+ END[ \t]*$"))) + (let ((case-fold-search nil)) + (looking-at org-complex-heading-regexp)))) + (match-beginning 4) + (>= (point) (match-beginning 4)) + (or (not (match-beginning 5)) + (< (point) (match-beginning 5)))) + (let* ((element (org-element-at-point)) + (post-affiliated (org-element-property :post-affiliated element))) + (cond + ;; Ignore checks in all affiliated keywords but captions. + ((< (point) post-affiliated) + (and (save-excursion + (beginning-of-line) + (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:"))) + (> (point) (match-end 0)) + (org--flyspell-object-check-p element))) + ;; Ignore checks in LOGBOOK (or equivalent) drawer. + ((let ((log (org-log-into-drawer))) + (and log + (let ((drawer (org-element-lineage element '(drawer)))) + (and drawer + (eq (compare-strings + log nil nil + (org-element-property :drawer-name drawer) nil nil t) + t))))) + nil) + (t + (cl-case (org-element-type element) + ((comment quote-section) t) + (comment-block + ;; Allow checks between block markers, not on them. + (and (> (line-beginning-position) post-affiliated) + (save-excursion + (end-of-line) + (skip-chars-forward " \r\t\n") + (< (point) (org-element-property :end element))))) + ;; Arbitrary list of keywords where checks are meaningful. + ;; Make sure point is on the value part of the element. + (keyword + (and (member (org-element-property :key element) + '("DESCRIPTION" "TITLE")) + (save-excursion + (search-backward ":" (line-beginning-position) t)))) + ;; Check is globally allowed in paragraphs verse blocks and + ;; table rows (after affiliated keywords) but some objects + ;; must not be affected. + ((paragraph table-row verse-block) + (let ((cbeg (org-element-property :contents-begin element)) + (cend (org-element-property :contents-end element))) + (and cbeg (>= (point) cbeg) (< (point) cend) + (org--flyspell-object-check-p element)))))))))) +(put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify) + +(defun org-remove-flyspell-overlays-in (beg end) + "Remove flyspell overlays in region." + (and (bound-and-true-p flyspell-mode) + (fboundp 'flyspell-delete-region-overlays) + (flyspell-delete-region-overlays beg end))) + +(defvar flyspell-delayed-commands) +(eval-after-load "flyspell" + '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command)) + +;; Make `bookmark-jump' shows the jump location if it was hidden. +(eval-after-load "bookmark" + '(if (boundp 'bookmark-after-jump-hook) + ;; We can use the hook + (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide) + ;; Hook not available, use advice + (defadvice bookmark-jump (after org-make-visible activate) + "Make the position visible." + (org-bookmark-jump-unhide)))) + +;; Make sure saveplace shows the location if it was hidden +(eval-after-load "saveplace" + '(defadvice save-place-find-file-hook (after org-make-visible activate) + "Make the position visible." + (org-bookmark-jump-unhide))) + +;; Make sure ecb shows the location if it was hidden +(eval-after-load "ecb" + '(defadvice ecb-method-clicked (after esf/org-show-context activate) + "Make hierarchy visible when jumping into location from ECB tree buffer." + (when (derived-mode-p 'org-mode) + (org-show-context)))) + +(defun org-bookmark-jump-unhide () + "Unhide the current position, to show the bookmark location." + (and (derived-mode-p 'org-mode) + (or (org-invisible-p) + (save-excursion (goto-char (max (point-min) (1- (point)))) + (org-invisible-p))) + (org-show-context 'bookmark-jump))) + +(defun org-mark-jump-unhide () + "Make the point visible with `org-show-context' after jumping to the mark." + (when (and (derived-mode-p 'org-mode) + (org-invisible-p)) + (org-show-context 'mark-goto))) + +(eval-after-load "simple" + '(defadvice pop-to-mark-command (after org-make-visible activate) + "Make the point visible with `org-show-context'." + (org-mark-jump-unhide))) + +(eval-after-load "simple" + '(defadvice exchange-point-and-mark (after org-make-visible activate) + "Make the point visible with `org-show-context'." + (org-mark-jump-unhide))) + +(eval-after-load "simple" + '(defadvice pop-global-mark (after org-make-visible activate) + "Make the point visible with `org-show-context'." + (org-mark-jump-unhide))) + +;; Make session.el ignore our circular variable +(defvar session-globals-exclude) +(eval-after-load "session" + '(add-to-list 'session-globals-exclude 'org-mark-ring)) + +;;;; Finish up + +(provide 'org) + +(run-hooks 'org-load-hook) + +;;; org.el ends here diff --git a/elpa/org-9.1.14/orgcard.pdf b/elpa/org-9.1.14/orgcard.pdf new file mode 100644 index 00000000..3f3f8df4 Binary files /dev/null and b/elpa/org-9.1.14/orgcard.pdf differ diff --git a/elpa/org-9.1.14/ox-ascii.el b/elpa/org-9.1.14/ox-ascii.el new file mode 100644 index 00000000..c3ccb596 --- /dev/null +++ b/elpa/org-9.1.14/ox-ascii.el @@ -0,0 +1,2182 @@ +;;; ox-ascii.el --- ASCII Back-End for Org Export Engine -*- lexical-binding: t; -*- + +;; Copyright (C) 2012-2018 Free Software Foundation, Inc. + +;; Author: Nicolas Goaziou <n.goaziou at gmail dot com> +;; Keywords: outlines, hypermedia, calendar, wp + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: +;; +;; This library implements an ASCII back-end for Org generic exporter. +;; See Org manual for more information. + +;;; Code: + +(require 'ox) +(require 'ox-publish) +(require 'cl-lib) + +(declare-function aa2u "ext:ascii-art-to-unicode" ()) + +;;; Define Back-End +;; +;; The following setting won't allow modifying preferred charset +;; through a buffer keyword or an option item, but, since the property +;; will appear in communication channel nonetheless, it allows +;; overriding `org-ascii-charset' variable on the fly by the ext-plist +;; mechanism. +;; +;; We also install a filter for headlines and sections, in order to +;; control blank lines separating them in output string. + +(org-export-define-backend 'ascii + '((bold . org-ascii-bold) + (center-block . org-ascii-center-block) + (clock . org-ascii-clock) + (code . org-ascii-code) + (drawer . org-ascii-drawer) + (dynamic-block . org-ascii-dynamic-block) + (entity . org-ascii-entity) + (example-block . org-ascii-example-block) + (export-block . org-ascii-export-block) + (export-snippet . org-ascii-export-snippet) + (fixed-width . org-ascii-fixed-width) + (footnote-reference . org-ascii-footnote-reference) + (headline . org-ascii-headline) + (horizontal-rule . org-ascii-horizontal-rule) + (inline-src-block . org-ascii-inline-src-block) + (inlinetask . org-ascii-inlinetask) + (inner-template . org-ascii-inner-template) + (italic . org-ascii-italic) + (item . org-ascii-item) + (keyword . org-ascii-keyword) + (latex-environment . org-ascii-latex-environment) + (latex-fragment . org-ascii-latex-fragment) + (line-break . org-ascii-line-break) + (link . org-ascii-link) + (node-property . org-ascii-node-property) + (paragraph . org-ascii-paragraph) + (plain-list . org-ascii-plain-list) + (plain-text . org-ascii-plain-text) + (planning . org-ascii-planning) + (property-drawer . org-ascii-property-drawer) + (quote-block . org-ascii-quote-block) + (radio-target . org-ascii-radio-target) + (section . org-ascii-section) + (special-block . org-ascii-special-block) + (src-block . org-ascii-src-block) + (statistics-cookie . org-ascii-statistics-cookie) + (strike-through . org-ascii-strike-through) + (subscript . org-ascii-subscript) + (superscript . org-ascii-superscript) + (table . org-ascii-table) + (table-cell . org-ascii-table-cell) + (table-row . org-ascii-table-row) + (target . org-ascii-target) + (template . org-ascii-template) + (timestamp . org-ascii-timestamp) + (underline . org-ascii-underline) + (verbatim . org-ascii-verbatim) + (verse-block . org-ascii-verse-block)) + :menu-entry + '(?t "Export to Plain Text" + ((?A "As ASCII buffer" + (lambda (a s v b) + (org-ascii-export-as-ascii a s v b '(:ascii-charset ascii)))) + (?a "As ASCII file" + (lambda (a s v b) + (org-ascii-export-to-ascii a s v b '(:ascii-charset ascii)))) + (?L "As Latin1 buffer" + (lambda (a s v b) + (org-ascii-export-as-ascii a s v b '(:ascii-charset latin1)))) + (?l "As Latin1 file" + (lambda (a s v b) + (org-ascii-export-to-ascii a s v b '(:ascii-charset latin1)))) + (?U "As UTF-8 buffer" + (lambda (a s v b) + (org-ascii-export-as-ascii a s v b '(:ascii-charset utf-8)))) + (?u "As UTF-8 file" + (lambda (a s v b) + (org-ascii-export-to-ascii a s v b '(:ascii-charset utf-8)))))) + :filters-alist '((:filter-headline . org-ascii-filter-headline-blank-lines) + (:filter-parse-tree org-ascii-filter-paragraph-spacing + org-ascii-filter-comment-spacing) + (:filter-section . org-ascii-filter-headline-blank-lines)) + :options-alist + '((:subtitle "SUBTITLE" nil nil parse) + (:ascii-bullets nil nil org-ascii-bullets) + (:ascii-caption-above nil nil org-ascii-caption-above) + (:ascii-charset nil nil org-ascii-charset) + (:ascii-global-margin nil nil org-ascii-global-margin) + (:ascii-format-drawer-function nil nil org-ascii-format-drawer-function) + (:ascii-format-inlinetask-function + nil nil org-ascii-format-inlinetask-function) + (:ascii-headline-spacing nil nil org-ascii-headline-spacing) + (:ascii-indented-line-width nil nil org-ascii-indented-line-width) + (:ascii-inlinetask-width nil nil org-ascii-inlinetask-width) + (:ascii-inner-margin nil nil org-ascii-inner-margin) + (:ascii-links-to-notes nil nil org-ascii-links-to-notes) + (:ascii-list-margin nil nil org-ascii-list-margin) + (:ascii-paragraph-spacing nil nil org-ascii-paragraph-spacing) + (:ascii-quote-margin nil nil org-ascii-quote-margin) + (:ascii-table-keep-all-vertical-lines + nil nil org-ascii-table-keep-all-vertical-lines) + (:ascii-table-use-ascii-art nil nil org-ascii-table-use-ascii-art) + (:ascii-table-widen-columns nil nil org-ascii-table-widen-columns) + (:ascii-text-width nil nil org-ascii-text-width) + (:ascii-underline nil nil org-ascii-underline) + (:ascii-verbatim-format nil nil org-ascii-verbatim-format))) + + + +;;; User Configurable Variables + +(defgroup org-export-ascii nil + "Options for exporting Org mode files to ASCII." + :tag "Org Export ASCII" + :group 'org-export) + +(defcustom org-ascii-text-width 72 + "Maximum width of exported text. +This number includes margin size, as set in +`org-ascii-global-margin'." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'integer) + +(defcustom org-ascii-global-margin 0 + "Width of the left margin, in number of characters." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'integer) + +(defcustom org-ascii-inner-margin 2 + "Width of the inner margin, in number of characters. +Inner margin is applied between each headline." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'integer) + +(defcustom org-ascii-quote-margin 6 + "Width of margin used for quoting text, in characters. +This margin is applied on both sides of the text. It is also +applied on the left side of contents in descriptive lists." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'integer) + +(defcustom org-ascii-list-margin 0 + "Width of margin used for plain lists, in characters. +This margin applies to top level list only, not to its +sub-lists." + :group 'org-export-ascii + :version "26.1" + :package-version '(Org . "8.3") + :type 'integer) + +(defcustom org-ascii-inlinetask-width 30 + "Width of inline tasks, in number of characters. +This number ignores any margin." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'integer) + +(defcustom org-ascii-headline-spacing '(1 . 2) + "Number of blank lines inserted around headlines. + +This variable can be set to a cons cell. In that case, its car +represents the number of blank lines present before headline +contents whereas its cdr reflects the number of blank lines after +contents. + +A nil value replicates the number of blank lines found in the +original Org buffer at the same place." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "Replicate original spacing" nil) + (cons :tag "Set a uniform spacing" + (integer :tag "Number of blank lines before contents") + (integer :tag "Number of blank lines after contents")))) + +(defcustom org-ascii-indented-line-width 'auto + "Additional indentation width for the first line in a paragraph. +If the value is an integer, indent the first line of each +paragraph by this width, unless it is located at the beginning of +a section, in which case indentation is removed from that line. +If it is the symbol `auto' preserve indentation from original +document." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (integer :tag "Number of white spaces characters") + (const :tag "Preserve original width" auto))) + +(defcustom org-ascii-paragraph-spacing 'auto + "Number of white lines between paragraphs. +If the value is an integer, add this number of blank lines +between contiguous paragraphs. If is it the symbol `auto', keep +the same number of blank lines as in the original document." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (integer :tag "Number of blank lines") + (const :tag "Preserve original spacing" auto))) + +(defcustom org-ascii-charset 'ascii + "The charset allowed to represent various elements and objects. +Possible values are: +`ascii' Only use plain ASCII characters +`latin1' Include Latin-1 characters +`utf-8' Use all UTF-8 characters" + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "ASCII" ascii) + (const :tag "Latin-1" latin1) + (const :tag "UTF-8" utf-8))) + +(defcustom org-ascii-underline '((ascii ?= ?~ ?-) + (latin1 ?= ?~ ?-) + (utf-8 ?═ ?─ ?╌ ?┄ ?┈)) + "Characters for underlining headings in ASCII export. + +Alist whose key is a symbol among `ascii', `latin1' and `utf-8' +and whose value is a list of characters. + +For each supported charset, this variable associates a sequence +of underline characters. In a sequence, the characters will be +used in order for headlines level 1, 2, ... If no character is +available for a given level, the headline won't be underlined." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type '(list + (cons :tag "Underline characters sequence" + (const :tag "ASCII charset" ascii) + (repeat character)) + (cons :tag "Underline characters sequence" + (const :tag "Latin-1 charset" latin1) + (repeat character)) + (cons :tag "Underline characters sequence" + (const :tag "UTF-8 charset" utf-8) + (repeat character)))) + +(defcustom org-ascii-bullets '((ascii ?* ?+ ?-) + (latin1 ?§ ?¶) + (utf-8 ?◊)) + "Bullet characters for headlines converted to lists in ASCII export. + +Alist whose key is a symbol among `ascii', `latin1' and `utf-8' +and whose value is a list of characters. + +The first character is used for the first level considered as low +level, and so on. If there are more levels than characters given +here, the list will be repeated. + +Note that this variable doesn't affect plain lists +representation." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type '(list + (cons :tag "Bullet characters for low level headlines" + (const :tag "ASCII charset" ascii) + (repeat character)) + (cons :tag "Bullet characters for low level headlines" + (const :tag "Latin-1 charset" latin1) + (repeat character)) + (cons :tag "Bullet characters for low level headlines" + (const :tag "UTF-8 charset" utf-8) + (repeat character)))) + +(defcustom org-ascii-links-to-notes t + "Non-nil means convert links to notes before the next headline. +When nil, the link will be exported in place. If the line +becomes long in this way, it will be wrapped." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-ascii-table-keep-all-vertical-lines nil + "Non-nil means keep all vertical lines in ASCII tables. +When nil, vertical lines will be removed except for those needed +for column grouping." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-ascii-table-widen-columns t + "Non-nil means widen narrowed columns for export. +When nil, narrowed columns will look in ASCII export just like in +Org mode, i.e. with \"=>\" as ellipsis." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-ascii-table-use-ascii-art nil + "Non-nil means \"table.el\" tables are turned into ASCII art. +It only makes sense when export charset is `utf-8'. It is nil by +default since it requires \"ascii-art-to-unicode.el\" package, +available through, e.g., GNU ELPA." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-ascii-caption-above nil + "When non-nil, place caption string before the element. +Otherwise, place it right after it." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-ascii-verbatim-format "`%s'" + "Format string used for verbatim text and inline code." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-ascii-format-drawer-function + (lambda (_name contents _width) contents) + "Function called to format a drawer in ASCII. + +The function must accept three parameters: + NAME the drawer name, like \"LOGBOOK\" + CONTENTS the contents of the drawer. + WIDTH the text width within the drawer. + +The function should return either the string to be exported or +nil to ignore the drawer. + +The default value simply returns the value of CONTENTS." + :group 'org-export-ascii + :version "24.4" + :package-version '(Org . "8.0") + :type 'function) + +(defcustom org-ascii-format-inlinetask-function + 'org-ascii-format-inlinetask-default + "Function called to format an inlinetask in ASCII. + +The function must accept nine parameters: + TODO the todo keyword, as a string + TODO-TYPE the todo type, a symbol among `todo', `done' and nil. + PRIORITY the inlinetask priority, as a string + NAME the inlinetask name, as a string. + TAGS the inlinetask tags, as a list of strings. + CONTENTS the contents of the inlinetask, as a string. + WIDTH the width of the inlinetask, as a number. + INLINETASK the inlinetask itself. + INFO the info channel. + +The function should return either the string to be exported or +nil to ignore the inline task." + :group 'org-export-ascii + :version "26.1" + :package-version '(Org . "8.3") + :type 'function) + + + +;;; Internal Functions + +;; Internal functions fall into three categories. + +;; The first one is about text formatting. The core functions are +;; `org-ascii--current-text-width' and +;; `org-ascii--current-justification', which determine, respectively, +;; the current text width allowed to a given element and its expected +;; justification. Once this information is known, +;; `org-ascii--fill-string', `org-ascii--justify-lines', +;; `org-ascii--justify-element' `org-ascii--box-string' and +;; `org-ascii--indent-string' can operate on a given output string. +;; In particular, justification happens at the regular (i.e., +;; non-greater) element level, which means that when the exporting +;; process reaches a container (e.g., a center block) content are +;; already justified. + +;; The second category contains functions handling elements listings, +;; triggered by "#+TOC:" keyword. As such, `org-ascii--build-toc' +;; returns a complete table of contents, `org-ascii--list-listings' +;; returns a list of referenceable src-block elements, and +;; `org-ascii--list-tables' does the same for table elements. + +;; The third category includes general helper functions. +;; `org-ascii--build-title' creates the title for a given headline +;; or inlinetask element. `org-ascii--build-caption' returns the +;; caption string associated to a table or a src-block. +;; `org-ascii--describe-links' creates notes about links for +;; insertion at the end of a section. It uses +;; `org-ascii--unique-links' to get the list of links to describe. +;; Eventually, `org-ascii--translate' translates a string according +;; to language and charset specification. + + +(defun org-ascii--fill-string (s text-width info &optional justify) + "Fill a string with specified text-width and return it. + +S is the string being filled. TEXT-WIDTH is an integer +specifying maximum length of a line. INFO is the plist used as +a communication channel. + +Optional argument JUSTIFY can specify any type of justification +among `left', `center', `right' or `full'. A nil value is +equivalent to `left'. For a justification that doesn't also fill +string, see `org-ascii--justify-lines' and +`org-ascii--justify-block'. + +Return nil if S isn't a string." + (when (stringp s) + (let ((double-space-p sentence-end-double-space)) + (with-temp-buffer + (let ((fill-column text-width) + (use-hard-newlines t) + (sentence-end-double-space double-space-p)) + (insert (if (plist-get info :preserve-breaks) + (replace-regexp-in-string "\n" hard-newline s) + s)) + (fill-region (point-min) (point-max) justify)) + (buffer-string))))) + +(defun org-ascii--justify-lines (s text-width how) + "Justify all lines in string S. +TEXT-WIDTH is an integer specifying maximum length of a line. +HOW determines the type of justification: it can be `left', +`right', `full' or `center'." + (with-temp-buffer + (insert s) + (goto-char (point-min)) + (let ((fill-column text-width) + ;; Disable `adaptive-fill-mode' so it doesn't prevent + ;; filling lines matching `adaptive-fill-regexp'. + (adaptive-fill-mode nil)) + (while (< (point) (point-max)) + (justify-current-line how) + (forward-line))) + (buffer-string))) + +(defun org-ascii--justify-element (contents element info) + "Justify CONTENTS of ELEMENT. +INFO is a plist used as a communication channel. Justification +is done according to the type of element. More accurately, +paragraphs are filled and other elements are justified as blocks, +that is according to the widest non blank line in CONTENTS." + (if (not (org-string-nw-p contents)) contents + (let ((text-width (org-ascii--current-text-width element info)) + (how (org-ascii--current-justification element))) + (cond + ((eq (org-element-type element) 'paragraph) + ;; Paragraphs are treated specially as they need to be filled. + (org-ascii--fill-string contents text-width info how)) + ((eq how 'left) contents) + (t (with-temp-buffer + (insert contents) + (goto-char (point-min)) + (catch 'exit + (let ((max-width 0)) + ;; Compute maximum width. Bail out if it is greater + ;; than page width, since no justification is + ;; possible. + (save-excursion + (while (not (eobp)) + (unless (looking-at-p "[ \t]*$") + (end-of-line) + (let ((column (current-column))) + (cond + ((>= column text-width) (throw 'exit contents)) + ((> column max-width) (setq max-width column))))) + (forward-line))) + ;; Justify every line according to TEXT-WIDTH and + ;; MAX-WIDTH. + (let ((offset (/ (- text-width max-width) + (if (eq how 'right) 1 2)))) + (if (zerop offset) (throw 'exit contents) + (while (not (eobp)) + (unless (looking-at-p "[ \t]*$") + (indent-to-column offset)) + (forward-line))))) + (buffer-string)))))))) + +(defun org-ascii--indent-string (s width) + "Indent string S by WIDTH white spaces. +Empty lines are not indented." + (when (stringp s) + (replace-regexp-in-string + "\\(^\\)[ \t]*\\S-" (make-string width ?\s) s nil nil 1))) + +(defun org-ascii--box-string (s info) + "Return string S with a partial box to its left. +INFO is a plist used as a communication channel." + (let ((utf8p (eq (plist-get info :ascii-charset) 'utf-8))) + (format (if utf8p "┌────\n%s\n└────" ",----\n%s\n`----") + (replace-regexp-in-string + "^" (if utf8p "│ " "| ") + ;; Remove last newline character. + (replace-regexp-in-string "\n[ \t]*\\'" "" s))))) + +(defun org-ascii--current-text-width (element info) + "Return maximum text width for ELEMENT's contents. +INFO is a plist used as a communication channel." + (pcase (org-element-type element) + ;; Elements with an absolute width: `headline' and `inlinetask'. + (`inlinetask (plist-get info :ascii-inlinetask-width)) + (`headline + (- (plist-get info :ascii-text-width) + (let ((low-level-rank (org-export-low-level-p element info))) + (if low-level-rank (* low-level-rank 2) + (plist-get info :ascii-global-margin))))) + ;; Elements with a relative width: store maximum text width in + ;; TOTAL-WIDTH. + (_ + (let* ((genealogy (org-element-lineage element nil t)) + ;; Total width is determined by the presence, or not, of an + ;; inline task among ELEMENT parents. + (total-width + (if (cl-some (lambda (parent) + (eq (org-element-type parent) 'inlinetask)) + genealogy) + (plist-get info :ascii-inlinetask-width) + ;; No inlinetask: Remove global margin from text width. + (- (plist-get info :ascii-text-width) + (plist-get info :ascii-global-margin) + (let ((parent (org-export-get-parent-headline element))) + ;; Inner margin doesn't apply to text before first + ;; headline. + (if (not parent) 0 + (let ((low-level-rank + (org-export-low-level-p parent info))) + ;; Inner margin doesn't apply to contents of + ;; low level headlines, since they've got their + ;; own indentation mechanism. + (if low-level-rank (* low-level-rank 2) + (plist-get info :ascii-inner-margin))))))))) + (- total-width + ;; Each `quote-block' and `verse-block' above narrows text + ;; width by twice the standard margin size. + (+ (* (cl-count-if (lambda (parent) + (memq (org-element-type parent) + '(quote-block verse-block))) + genealogy) + 2 + (plist-get info :ascii-quote-margin)) + ;; Apply list margin once per "top-level" plain-list + ;; containing current line + (* (cl-count-if + (lambda (e) + (and (eq (org-element-type e) 'plain-list) + (not (eq (org-element-type (org-export-get-parent e)) + 'item)))) + genealogy) + (plist-get info :ascii-list-margin)) + ;; Compute indentation offset due to current list. It is + ;; `org-ascii-quote-margin' per descriptive item in the + ;; genealogy, bullet's length otherwise. + (let ((indentation 0)) + (dolist (e genealogy) + (cond + ((not (eq 'item (org-element-type e)))) + ((eq (org-element-property :type (org-export-get-parent e)) + 'descriptive) + (cl-incf indentation org-ascii-quote-margin)) + (t + (cl-incf indentation + (+ (string-width + (or (org-ascii--checkbox e info) "")) + (string-width + (org-element-property :bullet e))))))) + indentation))))))) + +(defun org-ascii--current-justification (element) + "Return expected justification for ELEMENT's contents. +Return value is a symbol among `left', `center', `right' and +`full'." + (let (justification) + (while (and (not justification) + (setq element (org-element-property :parent element))) + (pcase (org-element-type element) + (`center-block (setq justification 'center)) + (`special-block + (let ((name (org-element-property :type element))) + (cond ((string= name "JUSTIFYRIGHT") (setq justification 'right)) + ((string= name "JUSTIFYLEFT") (setq justification 'left))))))) + (or justification 'left))) + +(defun org-ascii--build-title + (element info text-width &optional underline notags toc) + "Format ELEMENT title and return it. + +ELEMENT is either an `headline' or `inlinetask' element. INFO is +a plist used as a communication channel. TEXT-WIDTH is an +integer representing the maximum length of a line. + +When optional argument UNDERLINE is non-nil, underline title, +without the tags, according to `org-ascii-underline' +specifications. + +If optional argument NOTAGS is non-nil, no tags will be added to +the title. + +When optional argument TOC is non-nil, use optional title if +possible. It doesn't apply to `inlinetask' elements." + (let* ((headlinep (eq (org-element-type element) 'headline)) + (numbers + ;; Numbering is specific to headlines. + (and headlinep (org-export-numbered-headline-p element info) + ;; All tests passed: build numbering string. + (concat + (mapconcat + 'number-to-string + (org-export-get-headline-number element info) ".") + " "))) + (text + (org-trim + (org-export-data + (if (and toc headlinep) (org-export-get-alt-title element info) + (org-element-property :title element)) + info))) + (todo + (and (plist-get info :with-todo-keywords) + (let ((todo (org-element-property :todo-keyword element))) + (and todo (concat (org-export-data todo info) " "))))) + (tags (and (not notags) + (plist-get info :with-tags) + (let ((tag-list (org-export-get-tags element info))) + (and tag-list + (format ":%s:" + (mapconcat 'identity tag-list ":")))))) + (priority + (and (plist-get info :with-priority) + (let ((char (org-element-property :priority element))) + (and char (format "(#%c) " char))))) + (first-part (concat numbers todo priority text))) + (concat + first-part + ;; Align tags, if any. + (when tags + (format + (format " %%%ds" + (max (- text-width (1+ (string-width first-part))) + (string-width tags))) + tags)) + ;; Maybe underline text, if ELEMENT type is `headline' and an + ;; underline character has been defined. + (when (and underline headlinep) + (let ((under-char + (nth (1- (org-export-get-relative-level element info)) + (cdr (assq (plist-get info :ascii-charset) + (plist-get info :ascii-underline)))))) + (and under-char + (concat "\n" + (make-string (/ (string-width first-part) + (char-width under-char)) + under-char)))))))) + +(defun org-ascii--has-caption-p (element _info) + "Non-nil when ELEMENT has a caption affiliated keyword. +INFO is a plist used as a communication channel. This function +is meant to be used as a predicate for `org-export-get-ordinal'." + (org-element-property :caption element)) + +(defun org-ascii--build-caption (element info) + "Return caption string for ELEMENT, if applicable. + +INFO is a plist used as a communication channel. + +The caption string contains the sequence number of ELEMENT along +with its real caption. Return nil when ELEMENT has no affiliated +caption keyword." + (let ((caption (org-export-get-caption element))) + (when caption + ;; Get sequence number of current src-block among every + ;; src-block with a caption. + (let ((reference + (org-export-get-ordinal + element info nil 'org-ascii--has-caption-p)) + (title-fmt (org-ascii--translate + (pcase (org-element-type element) + (`table "Table %d:") + (`src-block "Listing %d:")) + info))) + (org-ascii--fill-string + (concat (format title-fmt reference) + " " + (org-export-data caption info)) + (org-ascii--current-text-width element info) info))))) + +(defun org-ascii--build-toc (info &optional n keyword local) + "Return a table of contents. + +INFO is a plist used as a communication channel. + +Optional argument N, when non-nil, is an integer specifying the +depth of the table. + +Optional argument KEYWORD specifies the TOC keyword, if any, from +which the table of contents generation has been initiated. + +When optional argument LOCAL is non-nil, build a table of +contents according to the current headline." + (concat + (unless local + (let ((title (org-ascii--translate "Table of Contents" info))) + (concat title "\n" + (make-string + (string-width title) + (if (eq (plist-get info :ascii-charset) 'utf-8) ?─ ?_)) + "\n\n"))) + (let ((text-width + (if keyword (org-ascii--current-text-width keyword info) + (- (plist-get info :ascii-text-width) + (plist-get info :ascii-global-margin))))) + (mapconcat + (lambda (headline) + (let* ((level (org-export-get-relative-level headline info)) + (indent (* (1- level) 3))) + (concat + (unless (zerop indent) (concat (make-string (1- indent) ?.) " ")) + (org-ascii--build-title + headline info (- text-width indent) nil + (or (not (plist-get info :with-tags)) + (eq (plist-get info :with-tags) 'not-in-toc)) + 'toc)))) + (org-export-collect-headlines info n (and local keyword)) "\n")))) + +(defun org-ascii--list-listings (keyword info) + "Return a list of listings. + +KEYWORD is the keyword that initiated the list of listings +generation. INFO is a plist used as a communication channel." + (let ((title (org-ascii--translate "List of Listings" info))) + (concat + title "\n" + (make-string (string-width title) + (if (eq (plist-get info :ascii-charset) 'utf-8) ?─ ?_)) + "\n\n" + (let ((text-width + (if keyword (org-ascii--current-text-width keyword info) + (- (plist-get info :ascii-text-width) + (plist-get info :ascii-global-margin)))) + ;; Use a counter instead of retrieving ordinal of each + ;; src-block. + (count 0)) + (mapconcat + (lambda (src-block) + ;; Store initial text so its length can be computed. This is + ;; used to properly align caption right to it in case of + ;; filling (like contents of a description list item). + (let* ((initial-text + (format (org-ascii--translate "Listing %d:" info) + (cl-incf count))) + (initial-width (string-width initial-text))) + (concat + initial-text " " + (org-trim + (org-ascii--indent-string + (org-ascii--fill-string + ;; Use short name in priority, if available. + (let ((caption (or (org-export-get-caption src-block t) + (org-export-get-caption src-block)))) + (org-export-data caption info)) + (- text-width initial-width) info) + initial-width))))) + (org-export-collect-listings info) "\n"))))) + +(defun org-ascii--list-tables (keyword info) + "Return a list of tables. + +KEYWORD is the keyword that initiated the list of tables +generation. INFO is a plist used as a communication channel." + (let ((title (org-ascii--translate "List of Tables" info))) + (concat + title "\n" + (make-string (string-width title) + (if (eq (plist-get info :ascii-charset) 'utf-8) ?─ ?_)) + "\n\n" + (let ((text-width + (if keyword (org-ascii--current-text-width keyword info) + (- (plist-get info :ascii-text-width) + (plist-get info :ascii-global-margin)))) + ;; Use a counter instead of retrieving ordinal of each + ;; src-block. + (count 0)) + (mapconcat + (lambda (table) + ;; Store initial text so its length can be computed. This is + ;; used to properly align caption right to it in case of + ;; filling (like contents of a description list item). + (let* ((initial-text + (format (org-ascii--translate "Table %d:" info) + (cl-incf count))) + (initial-width (string-width initial-text))) + (concat + initial-text " " + (org-trim + (org-ascii--indent-string + (org-ascii--fill-string + ;; Use short name in priority, if available. + (let ((caption (or (org-export-get-caption table t) + (org-export-get-caption table)))) + (org-export-data caption info)) + (- text-width initial-width) info) + initial-width))))) + (org-export-collect-tables info) "\n"))))) + +(defun org-ascii--unique-links (element info) + "Return a list of unique link references in ELEMENT. +ELEMENT is either a headline element or a section element. INFO +is a plist used as a communication channel." + (let* (seen + (unique-link-p + ;; Return LINK if it wasn't referenced so far, or nil. + ;; Update SEEN links along the way. + (lambda (link) + (let ((footprint + ;; Normalize description in footprints. + (cons (org-element-property :raw-link link) + (let ((contents (org-element-contents link))) + (and contents + (replace-regexp-in-string + "[ \r\t\n]+" " " + (org-trim + (org-element-interpret-data contents)))))))) + ;; Ignore LINK if it hasn't been translated already. It + ;; can happen if it is located in an affiliated keyword + ;; that was ignored. + (when (and (org-string-nw-p + (gethash link (plist-get info :exported-data))) + (not (member footprint seen))) + (push footprint seen) link))))) + (org-element-map (if (eq (org-element-type element) 'section) + element + ;; In a headline, only retrieve links in title + ;; and relative section, not in children. + (list (org-element-property :title element) + (car (org-element-contents element)))) + 'link unique-link-p info nil 'headline t))) + +(defun org-ascii--describe-datum (datum info) + "Describe DATUM object or element. +If DATUM is a string, consider it to be a file name, per +`org-export-resolve-id-link'. INFO is the communication channel, +as a plist." + (pcase (org-element-type datum) + (`plain-text (format "See file %s" datum)) ;External file + (`headline + (format (org-ascii--translate "See section %s" info) + (if (org-export-numbered-headline-p datum info) + (mapconcat #'number-to-string + (org-export-get-headline-number datum info) + ".") + (org-export-data (org-element-property :title datum) info)))) + (_ + (let ((number (org-export-get-ordinal + datum info nil #'org-ascii--has-caption-p)) + ;; If destination is a target, make sure we can name the + ;; container it refers to. + (enumerable + (org-element-lineage datum + '(headline paragraph src-block table) t))) + (pcase (org-element-type enumerable) + (`headline + (format (org-ascii--translate "See section %s" info) + (if (org-export-numbered-headline-p enumerable info) + (mapconcat #'number-to-string number ".") + (org-export-data + (org-element-property :title enumerable) info)))) + ((guard (not number)) + (org-ascii--translate "Unknown reference" info)) + (`paragraph + (format (org-ascii--translate "See figure %s" info) number)) + (`src-block + (format (org-ascii--translate "See listing %s" info) number)) + (`table + (format (org-ascii--translate "See table %s" info) number)) + (_ (org-ascii--translate "Unknown reference" info))))))) + +(defun org-ascii--describe-links (links width info) + "Return a string describing a list of links. +LINKS is a list of link type objects, as returned by +`org-ascii--unique-links'. WIDTH is the text width allowed for +the output string. INFO is a plist used as a communication +channel." + (mapconcat + (lambda (link) + (let* ((type (org-element-property :type link)) + (description (org-element-contents link)) + (anchor (org-export-data + (or description (org-element-property :raw-link link)) + info))) + (cond + ((member type '("coderef" "radio")) nil) + ((member type '("custom-id" "fuzzy" "id")) + ;; Only links with a description need an entry. Other are + ;; already handled in `org-ascii-link'. + (when description + (let ((dest (if (equal type "fuzzy") + (org-export-resolve-fuzzy-link link info) + (org-export-resolve-id-link link info)))) + (concat + (org-ascii--fill-string + (format "[%s] %s" anchor (org-ascii--describe-datum dest info)) + width info) + "\n\n")))) + ;; Do not add a link that cannot be resolved and doesn't have + ;; any description: destination is already visible in the + ;; paragraph. + ((not (org-element-contents link)) nil) + ;; Do not add a link already handled by custom export + ;; functions. + ((org-export-custom-protocol-maybe link anchor 'ascii) nil) + (t + (concat + (org-ascii--fill-string + (format "[%s] %s" anchor (org-element-property :raw-link link)) + width info) + "\n\n"))))) + links "")) + +(defun org-ascii--checkbox (item info) + "Return checkbox string for ITEM or nil. +INFO is a plist used as a communication channel." + (let ((utf8p (eq (plist-get info :ascii-charset) 'utf-8))) + (pcase (org-element-property :checkbox item) + (`on (if utf8p "☑ " "[X] ")) + (`off (if utf8p "☐ " "[ ] ")) + (`trans (if utf8p "☒ " "[-] "))))) + + + +;;; Template + +(defun org-ascii-template--document-title (info) + "Return document title, as a string. +INFO is a plist used as a communication channel." + (let* ((text-width (plist-get info :ascii-text-width)) + ;; Links in the title will not be resolved later, so we make + ;; sure their path is located right after them. + (info (org-combine-plists info '(:ascii-links-to-notes nil))) + (with-title (plist-get info :with-title)) + (title (org-export-data + (when with-title (plist-get info :title)) info)) + (subtitle (org-export-data + (when with-title (plist-get info :subtitle)) info)) + (author (and (plist-get info :with-author) + (let ((auth (plist-get info :author))) + (and auth (org-export-data auth info))))) + (email (and (plist-get info :with-email) + (org-export-data (plist-get info :email) info))) + (date (and (plist-get info :with-date) + (org-export-data (org-export-get-date info) info)))) + ;; There are two types of title blocks depending on the presence + ;; of a title to display. + (if (string= title "") + ;; Title block without a title. DATE is positioned at the top + ;; right of the document, AUTHOR to the top left and EMAIL + ;; just below. + (cond + ((and (org-string-nw-p date) (org-string-nw-p author)) + (concat + author + (make-string (- text-width (string-width date) (string-width author)) + ?\s) + date + (when (org-string-nw-p email) (concat "\n" email)) + "\n\n\n")) + ((and (org-string-nw-p date) (org-string-nw-p email)) + (concat + email + (make-string (- text-width (string-width date) (string-width email)) + ?\s) + date "\n\n\n")) + ((org-string-nw-p date) + (concat + (org-ascii--justify-lines date text-width 'right) + "\n\n\n")) + ((and (org-string-nw-p author) (org-string-nw-p email)) + (concat author "\n" email "\n\n\n")) + ((org-string-nw-p author) (concat author "\n\n\n")) + ((org-string-nw-p email) (concat email "\n\n\n"))) + ;; Title block with a title. Document's TITLE, along with the + ;; AUTHOR and its EMAIL are both overlined and an underlined, + ;; centered. Date is just below, also centered. + (let* ((utf8p (eq (plist-get info :ascii-charset) 'utf-8)) + ;; Format TITLE. It may be filled if it is too wide, + ;; that is wider than the two thirds of the total width. + (title-len (min (apply #'max + (mapcar #'length + (org-split-string + (concat title "\n" subtitle) "\n"))) + (/ (* 2 text-width) 3))) + (formatted-title (org-ascii--fill-string title title-len info)) + (formatted-subtitle (when (org-string-nw-p subtitle) + (org-ascii--fill-string subtitle title-len info))) + (line + (make-string + (min (+ (max title-len + (string-width (or author "")) + (string-width (or email ""))) + 2) + text-width) (if utf8p ?━ ?_)))) + (org-ascii--justify-lines + (concat line "\n" + (unless utf8p "\n") + (upcase formatted-title) + (and formatted-subtitle (concat "\n" formatted-subtitle)) + (cond + ((and (org-string-nw-p author) (org-string-nw-p email)) + (concat "\n\n" author "\n" email)) + ((org-string-nw-p author) (concat "\n\n" author)) + ((org-string-nw-p email) (concat "\n\n" email))) + "\n" line + (when (org-string-nw-p date) (concat "\n\n\n" date)) + "\n\n\n") text-width 'center))))) + +(defun org-ascii-inner-template (contents info) + "Return complete document string after ASCII conversion. +CONTENTS is the transcoded contents string. INFO is a plist +holding export options." + (org-element-normalize-string + (let ((global-margin (plist-get info :ascii-global-margin))) + (org-ascii--indent-string + (concat + ;; 1. Document's body. + contents + ;; 2. Footnote definitions. + (let ((definitions (org-export-collect-footnote-definitions info)) + ;; Insert full links right inside the footnote definition + ;; as they have no chance to be inserted later. + (info (org-combine-plists info '(:ascii-links-to-notes nil)))) + (when definitions + (concat + "\n\n\n" + (let ((title (org-ascii--translate "Footnotes" info))) + (concat + title "\n" + (make-string + (string-width title) + (if (eq (plist-get info :ascii-charset) 'utf-8) ?─ ?_)))) + "\n\n" + (let ((text-width (- (plist-get info :ascii-text-width) + global-margin))) + (mapconcat + (lambda (ref) + (let ((id (format "[%s] " (car ref)))) + ;; Distinguish between inline definitions and + ;; full-fledged definitions. + (org-trim + (let ((def (nth 2 ref))) + (if (org-element-map def org-element-all-elements + #'identity info 'first-match) + ;; Full-fledged definition: footnote ID is + ;; inserted inside the first parsed + ;; paragraph (FIRST), if any, to be sure + ;; filling will take it into consideration. + (let ((first (car (org-element-contents def)))) + (if (not (eq (org-element-type first) 'paragraph)) + (concat id "\n" (org-export-data def info)) + (push id (nthcdr 2 first)) + (org-export-data def info))) + ;; Fill paragraph once footnote ID is inserted + ;; in order to have a correct length for first + ;; line. + (org-ascii--fill-string + (concat id (org-export-data def info)) + text-width info)))))) + definitions "\n\n")))))) + global-margin)))) + +(defun org-ascii-template (contents info) + "Return complete document string after ASCII conversion. +CONTENTS is the transcoded contents string. INFO is a plist +holding export options." + (let ((global-margin (plist-get info :ascii-global-margin))) + (concat + ;; Build title block. + (org-ascii--indent-string + (concat (org-ascii-template--document-title info) + ;; 2. Table of contents. + (let ((depth (plist-get info :with-toc))) + (when depth + (concat + (org-ascii--build-toc info (and (wholenump depth) depth)) + "\n\n\n")))) + global-margin) + ;; Document's body. + contents + ;; Creator. Justify it to the bottom right. + (and (plist-get info :with-creator) + (org-ascii--indent-string + (let ((text-width + (- (plist-get info :ascii-text-width) global-margin))) + (concat + "\n\n\n" + (org-ascii--fill-string + (plist-get info :creator) text-width info 'right))) + global-margin))))) + +(defun org-ascii--translate (s info) + "Translate string S according to specified language and charset. +INFO is a plist used as a communication channel." + (let ((charset (intern (format ":%s" (plist-get info :ascii-charset))))) + (org-export-translate s charset info))) + + + +;;; Transcode Functions + +;;;; Bold + +(defun org-ascii-bold (_bold contents _info) + "Transcode BOLD from Org to ASCII. +CONTENTS is the text with bold markup. INFO is a plist holding +contextual information." + (format "*%s*" contents)) + + +;;;; Center Block + +(defun org-ascii-center-block (_center-block contents _info) + "Transcode a CENTER-BLOCK element from Org to ASCII. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + ;; Center has already been taken care of at a lower level, so + ;; there's nothing left to do. + contents) + + +;;;; Clock + +(defun org-ascii-clock (clock _contents info) + "Transcode a CLOCK object from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual +information." + (org-ascii--justify-element + (concat org-clock-string " " + (org-timestamp-translate (org-element-property :value clock)) + (let ((time (org-element-property :duration clock))) + (and time + (concat " => " + (apply 'format + "%2s:%02s" + (org-split-string time ":")))))) + clock info)) + + +;;;; Code + +(defun org-ascii-code (code _contents info) + "Return a CODE object from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual +information." + (format (plist-get info :ascii-verbatim-format) + (org-element-property :value code))) + + +;;;; Drawer + +(defun org-ascii-drawer (drawer contents info) + "Transcode a DRAWER element from Org to ASCII. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + (let ((name (org-element-property :drawer-name drawer)) + (width (org-ascii--current-text-width drawer info))) + (funcall (plist-get info :ascii-format-drawer-function) + name contents width))) + + +;;;; Dynamic Block + +(defun org-ascii-dynamic-block (_dynamic-block contents _info) + "Transcode a DYNAMIC-BLOCK element from Org to ASCII. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + contents) + + +;;;; Entity + +(defun org-ascii-entity (entity _contents info) + "Transcode an ENTITY object from Org to ASCII. +CONTENTS are the definition itself. INFO is a plist holding +contextual information." + (org-element-property + (intern (concat ":" (symbol-name (plist-get info :ascii-charset)))) + entity)) + + +;;;; Example Block + +(defun org-ascii-example-block (example-block _contents info) + "Transcode a EXAMPLE-BLOCK element from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual information." + (org-ascii--justify-element + (org-ascii--box-string + (org-export-format-code-default example-block info) info) + example-block info)) + + +;;;; Export Snippet + +(defun org-ascii-export-snippet (export-snippet _contents _info) + "Transcode a EXPORT-SNIPPET object from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual information." + (when (eq (org-export-snippet-backend export-snippet) 'ascii) + (org-element-property :value export-snippet))) + + +;;;; Export Block + +(defun org-ascii-export-block (export-block _contents info) + "Transcode a EXPORT-BLOCK element from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual information." + (when (string= (org-element-property :type export-block) "ASCII") + (org-ascii--justify-element + (org-element-property :value export-block) export-block info))) + + +;;;; Fixed Width + +(defun org-ascii-fixed-width (fixed-width _contents info) + "Transcode a FIXED-WIDTH element from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual information." + (org-ascii--justify-element + (org-ascii--box-string + (org-remove-indentation + (org-element-property :value fixed-width)) info) + fixed-width info)) + + +;;;; Footnote Definition + +;; Footnote Definitions are ignored. They are compiled at the end of +;; the document, by `org-ascii-inner-template'. + + +;;;; Footnote Reference + +(defun org-ascii-footnote-reference (footnote-reference _contents info) + "Transcode a FOOTNOTE-REFERENCE element from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual information." + (format "[%s]" (org-export-get-footnote-number footnote-reference info))) + + +;;;; Headline + +(defun org-ascii-headline (headline contents info) + "Transcode a HEADLINE element from Org to ASCII. +CONTENTS holds the contents of the headline. INFO is a plist +holding contextual information." + ;; Don't export footnote section, which will be handled at the end + ;; of the template. + (unless (org-element-property :footnote-section-p headline) + (let* ((low-level (org-export-low-level-p headline info)) + (width (org-ascii--current-text-width headline info)) + ;; Export title early so that any link in it can be + ;; exported and seen in `org-ascii--unique-links'. + (title (org-ascii--build-title headline info width (not low-level))) + ;; Blank lines between headline and its contents. + ;; `org-ascii-headline-spacing', when set, overwrites + ;; original buffer's spacing. + (pre-blanks + (make-string (or (car (plist-get info :ascii-headline-spacing)) + (org-element-property :pre-blank headline) + 0) + ?\n)) + (links (and (plist-get info :ascii-links-to-notes) + (org-ascii--describe-links + (org-ascii--unique-links headline info) width info))) + ;; Re-build contents, inserting section links at the right + ;; place. The cost is low since build results are cached. + (body + (if (not (org-string-nw-p links)) contents + (let* ((contents (org-element-contents headline)) + (section (let ((first (car contents))) + (and (eq (org-element-type first) 'section) + first)))) + (concat (and section + (concat (org-element-normalize-string + (org-export-data section info)) + "\n\n")) + links + (mapconcat (lambda (e) (org-export-data e info)) + (if section (cdr contents) contents) + "")))))) + ;; Deep subtree: export it as a list item. + (if low-level + (let* ((bullets (cdr (assq (plist-get info :ascii-charset) + (plist-get info :ascii-bullets)))) + (bullet + (format "%c " + (nth (mod (1- low-level) (length bullets)) bullets)))) + (concat bullet title "\n" pre-blanks + ;; Contents, indented by length of bullet. + (org-ascii--indent-string body (length bullet)))) + ;; Else: Standard headline. + (concat title "\n" pre-blanks body))))) + + +;;;; Horizontal Rule + +(defun org-ascii-horizontal-rule (horizontal-rule _contents info) + "Transcode an HORIZONTAL-RULE object from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual +information." + (let ((text-width (org-ascii--current-text-width horizontal-rule info)) + (spec-width + (org-export-read-attribute :attr_ascii horizontal-rule :width))) + (org-ascii--justify-lines + (make-string (if (and spec-width (string-match "^[0-9]+$" spec-width)) + (string-to-number spec-width) + text-width) + (if (eq (plist-get info :ascii-charset) 'utf-8) ?― ?-)) + text-width 'center))) + + +;;;; Inline Src Block + +(defun org-ascii-inline-src-block (inline-src-block _contents info) + "Transcode an INLINE-SRC-BLOCK element from Org to ASCII. +CONTENTS holds the contents of the item. INFO is a plist holding +contextual information." + (format (plist-get info :ascii-verbatim-format) + (org-element-property :value inline-src-block))) + + +;;;; Inlinetask + +(defun org-ascii-format-inlinetask-default + (_todo _type _priority _name _tags contents width inlinetask info) + "Format an inline task element for ASCII export. +See `org-ascii-format-inlinetask-function' for a description +of the parameters." + (let* ((utf8p (eq (plist-get info :ascii-charset) 'utf-8)) + (width (or width (plist-get info :ascii-inlinetask-width)))) + (org-ascii--indent-string + (concat + ;; Top line, with an additional blank line if not in UTF-8. + (make-string width (if utf8p ?━ ?_)) "\n" + (unless utf8p (concat (make-string width ? ) "\n")) + ;; Add title. Fill it if wider than inlinetask. + (let ((title (org-ascii--build-title inlinetask info width))) + (if (<= (string-width title) width) title + (org-ascii--fill-string title width info))) + "\n" + ;; If CONTENTS is not empty, insert it along with + ;; a separator. + (when (org-string-nw-p contents) + (concat (make-string width (if utf8p ?─ ?-)) "\n" contents)) + ;; Bottom line. + (make-string width (if utf8p ?━ ?_))) + ;; Flush the inlinetask to the right. + (- (plist-get info :ascii-text-width) (plist-get info :ascii-global-margin) + (if (not (org-export-get-parent-headline inlinetask)) 0 + (plist-get info :ascii-inner-margin)) + (org-ascii--current-text-width inlinetask info))))) + +(defun org-ascii-inlinetask (inlinetask contents info) + "Transcode an INLINETASK element from Org to ASCII. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + (let ((width (org-ascii--current-text-width inlinetask info))) + (funcall (plist-get info :ascii-format-inlinetask-function) + ;; todo. + (and (plist-get info :with-todo-keywords) + (let ((todo (org-element-property + :todo-keyword inlinetask))) + (and todo (org-export-data todo info)))) + ;; todo-type + (org-element-property :todo-type inlinetask) + ;; priority + (and (plist-get info :with-priority) + (org-element-property :priority inlinetask)) + ;; title + (org-export-data (org-element-property :title inlinetask) info) + ;; tags + (and (plist-get info :with-tags) + (org-element-property :tags inlinetask)) + ;; contents and width + contents width inlinetask info))) + + +;;;; Italic + +(defun org-ascii-italic (_italic contents _info) + "Transcode italic from Org to ASCII. +CONTENTS is the text with italic markup. INFO is a plist holding +contextual information." + (format "/%s/" contents)) + + +;;;; Item + +(defun org-ascii-item (item contents info) + "Transcode an ITEM element from Org to ASCII. +CONTENTS holds the contents of the item. INFO is a plist holding +contextual information." + (let* ((utf8p (eq (plist-get info :ascii-charset) 'utf-8)) + (checkbox (org-ascii--checkbox item info)) + (list-type (org-element-property :type (org-export-get-parent item))) + (bullet + ;; First parent of ITEM is always the plain-list. Get + ;; `:type' property from it. + (pcase list-type + (`descriptive + (concat checkbox + (org-export-data (org-element-property :tag item) + info))) + (`ordered + ;; Return correct number for ITEM, paying attention to + ;; counters. + (let* ((struct (org-element-property :structure item)) + (bul (org-list-bullet-string + (org-element-property :bullet item))) + (num (number-to-string + (car (last (org-list-get-item-number + (org-element-property :begin item) + struct + (org-list-prevs-alist struct) + (org-list-parents-alist struct))))))) + (replace-regexp-in-string "[0-9]+" num bul))) + (_ (let ((bul (org-list-bullet-string + (org-element-property :bullet item)))) + ;; Change bullets into more visible form if UTF-8 is active. + (if (not utf8p) bul + (replace-regexp-in-string + "-" "•" + (replace-regexp-in-string + "+" "⁃" + (replace-regexp-in-string "*" "‣" bul)))))))) + (indentation (if (eq list-type 'descriptive) org-ascii-quote-margin + (string-width bullet)))) + (concat + bullet + checkbox + ;; Contents: Pay attention to indentation. Note: check-boxes are + ;; already taken care of at the paragraph level so they don't + ;; interfere with indentation. + (let ((contents (org-ascii--indent-string contents indentation))) + ;; Determine if contents should follow the bullet or start + ;; a new line. Do the former when the first contributing + ;; element to contents is a paragraph. In descriptive lists + ;; however, contents always start a new line. + (if (and (not (eq list-type 'descriptive)) + (org-string-nw-p contents) + (eq 'paragraph + (org-element-type + (cl-some (lambda (e) + (and (org-string-nw-p (org-export-data e info)) + e)) + (org-element-contents item))))) + (org-trim contents) + (concat "\n" contents)))))) + + +;;;; Keyword + +(defun org-ascii-keyword (keyword _contents info) + "Transcode a KEYWORD element from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual +information." + (let ((key (org-element-property :key keyword)) + (value (org-element-property :value keyword))) + (cond + ((string= key "ASCII") (org-ascii--justify-element value keyword info)) + ((string= key "TOC") + (org-ascii--justify-element + (let ((case-fold-search t)) + (cond + ((string-match-p "\\<headlines\\>" value) + (let ((depth (and (string-match "\\<[0-9]+\\>" value) + (string-to-number (match-string 0 value)))) + (localp (string-match-p "\\<local\\>" value))) + (org-ascii--build-toc info depth keyword localp))) + ((string-match-p "\\<tables\\>" value) + (org-ascii--list-tables keyword info)) + ((string-match-p "\\<listings\\>" value) + (org-ascii--list-listings keyword info)))) + keyword info))))) + + +;;;; Latex Environment + +(defun org-ascii-latex-environment (latex-environment _contents info) + "Transcode a LATEX-ENVIRONMENT element from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual +information." + (when (plist-get info :with-latex) + (org-ascii--justify-element + (org-remove-indentation (org-element-property :value latex-environment)) + latex-environment info))) + + +;;;; Latex Fragment + +(defun org-ascii-latex-fragment (latex-fragment _contents info) + "Transcode a LATEX-FRAGMENT object from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual +information." + (when (plist-get info :with-latex) + (org-element-property :value latex-fragment))) + + +;;;; Line Break + +(defun org-ascii-line-break (_line-break _contents _info) + "Transcode a LINE-BREAK object from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual + information." hard-newline) + + +;;;; Link + +(defun org-ascii-link (link desc info) + "Transcode a LINK object from Org to ASCII. + +DESC is the description part of the link, or the empty string. +INFO is a plist holding contextual information." + (let ((type (org-element-property :type link))) + (cond + ((org-export-custom-protocol-maybe link desc 'ascii)) + ((string= type "coderef") + (let ((ref (org-element-property :path link))) + (format (org-export-get-coderef-format ref desc) + (org-export-resolve-coderef ref info)))) + ;; Do not apply a special syntax on radio links. Though, use + ;; transcoded target's contents as output. + ((string= type "radio") desc) + ((member type '("custom-id" "fuzzy" "id")) + (let ((destination (if (string= type "fuzzy") + (org-export-resolve-fuzzy-link link info) + (org-export-resolve-id-link link info)))) + (pcase (org-element-type destination) + ((guard desc) + (if (plist-get info :ascii-links-to-notes) + (format "[%s]" desc) + (concat desc + (format " (%s)" + (org-ascii--describe-datum destination info))))) + ;; External file. + (`plain-text destination) + (`headline + (if (org-export-numbered-headline-p destination info) + (mapconcat #'number-to-string + (org-export-get-headline-number destination info) + ".") + (org-export-data (org-element-property :title destination) info))) + ;; Handle enumerable elements and targets within them. + ((and (let number (org-export-get-ordinal + destination info nil #'org-ascii--has-caption-p)) + (guard number)) + (if (atom number) (number-to-string number) + (mapconcat #'number-to-string number "."))) + ;; Don't know what to do. Signal it. + (_ "???")))) + (t + (let ((raw-link (org-element-property :raw-link link))) + (if (not (org-string-nw-p desc)) (format "[%s]" raw-link) + (concat (format "[%s]" desc) + (and (not (plist-get info :ascii-links-to-notes)) + (format " (%s)" raw-link))))))))) + + +;;;; Node Properties + +(defun org-ascii-node-property (node-property _contents _info) + "Transcode a NODE-PROPERTY element from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual +information." + (format "%s:%s" + (org-element-property :key node-property) + (let ((value (org-element-property :value node-property))) + (if value (concat " " value) "")))) + + +;;;; Paragraph + +(defun org-ascii-paragraph (paragraph contents info) + "Transcode a PARAGRAPH element from Org to ASCII. +CONTENTS is the contents of the paragraph, as a string. INFO is +the plist used as a communication channel." + (org-ascii--justify-element + (let ((indented-line-width (plist-get info :ascii-indented-line-width))) + (if (not (wholenump indented-line-width)) contents + (concat + ;; Do not indent first paragraph in a section. + (unless (and (not (org-export-get-previous-element paragraph info)) + (eq (org-element-type (org-export-get-parent paragraph)) + 'section)) + (make-string indented-line-width ?\s)) + (replace-regexp-in-string "\\`[ \t]+" "" contents)))) + paragraph info)) + + +;;;; Plain List + +(defun org-ascii-plain-list (plain-list contents info) + "Transcode a PLAIN-LIST element from Org to ASCII. +CONTENTS is the contents of the list. INFO is a plist holding +contextual information." + (let ((margin (plist-get info :ascii-list-margin))) + (if (or (< margin 1) + (eq (org-element-type (org-export-get-parent plain-list)) 'item)) + contents + (org-ascii--indent-string contents margin)))) + + +;;;; Plain Text + +(defun org-ascii-plain-text (text info) + "Transcode a TEXT string from Org to ASCII. +INFO is a plist used as a communication channel." + (let ((utf8p (eq (plist-get info :ascii-charset) 'utf-8))) + (when (and utf8p (plist-get info :with-smart-quotes)) + (setq text (org-export-activate-smart-quotes text :utf-8 info))) + (if (not (plist-get info :with-special-strings)) text + (setq text (replace-regexp-in-string "\\\\-" "" text)) + (if (not utf8p) text + ;; Usual replacements in utf-8 with proper option set. + (replace-regexp-in-string + "\\.\\.\\." "…" + (replace-regexp-in-string + "--" "–" + (replace-regexp-in-string "---" "—" text))))))) + + +;;;; Planning + +(defun org-ascii-planning (planning _contents info) + "Transcode a PLANNING element from Org to ASCII. +CONTENTS is nil. INFO is a plist used as a communication +channel." + (org-ascii--justify-element + (mapconcat + #'identity + (delq nil + (list (let ((closed (org-element-property :closed planning))) + (when closed + (concat org-closed-string " " + (org-timestamp-translate closed)))) + (let ((deadline (org-element-property :deadline planning))) + (when deadline + (concat org-deadline-string " " + (org-timestamp-translate deadline)))) + (let ((scheduled (org-element-property :scheduled planning))) + (when scheduled + (concat org-scheduled-string " " + (org-timestamp-translate scheduled)))))) + " ") + planning info)) + + +;;;; Property Drawer + +(defun org-ascii-property-drawer (property-drawer contents info) + "Transcode a PROPERTY-DRAWER element from Org to ASCII. +CONTENTS holds the contents of the drawer. INFO is a plist +holding contextual information." + (and (org-string-nw-p contents) + (org-ascii--justify-element contents property-drawer info))) + + +;;;; Quote Block + +(defun org-ascii-quote-block (_quote-block contents info) + "Transcode a QUOTE-BLOCK element from Org to ASCII. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + (org-ascii--indent-string contents (plist-get info :ascii-quote-margin))) + + +;;;; Radio Target + +(defun org-ascii-radio-target (_radio-target contents _info) + "Transcode a RADIO-TARGET object from Org to ASCII. +CONTENTS is the contents of the target. INFO is a plist holding +contextual information." + contents) + + +;;;; Section + +(defun org-ascii-section (section contents info) + "Transcode a SECTION element from Org to ASCII. +CONTENTS is the contents of the section. INFO is a plist holding +contextual information." + (let ((links + (and (plist-get info :ascii-links-to-notes) + ;; Take care of links in first section of the document. + (not (org-element-lineage section '(headline))) + (org-ascii--describe-links + (org-ascii--unique-links section info) + (org-ascii--current-text-width section info) + info)))) + (org-ascii--indent-string + (if (not (org-string-nw-p links)) contents + (concat (org-element-normalize-string contents) "\n\n" links)) + ;; Do not apply inner margin if parent headline is low level. + (let ((headline (org-export-get-parent-headline section))) + (if (or (not headline) (org-export-low-level-p headline info)) 0 + (plist-get info :ascii-inner-margin)))))) + + +;;;; Special Block + +(defun org-ascii-special-block (_special-block contents _info) + "Transcode a SPECIAL-BLOCK element from Org to ASCII. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + ;; "JUSTIFYLEFT" and "JUSTIFYRIGHT" have already been taken care of + ;; at a lower level. There is no other special block type to + ;; handle. + contents) + + +;;;; Src Block + +(defun org-ascii-src-block (src-block _contents info) + "Transcode a SRC-BLOCK element from Org to ASCII. +CONTENTS holds the contents of the item. INFO is a plist holding +contextual information." + (let ((caption (org-ascii--build-caption src-block info)) + (caption-above-p (plist-get info :ascii-caption-above)) + (code (org-export-format-code-default src-block info))) + (if (equal code "") "" + (org-ascii--justify-element + (concat + (and caption caption-above-p (concat caption "\n")) + (org-ascii--box-string code info) + (and caption (not caption-above-p) (concat "\n" caption))) + src-block info)))) + + +;;;; Statistics Cookie + +(defun org-ascii-statistics-cookie (statistics-cookie _contents _info) + "Transcode a STATISTICS-COOKIE object from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual information." + (org-element-property :value statistics-cookie)) + + +;;;; Subscript + +(defun org-ascii-subscript (subscript contents _info) + "Transcode a SUBSCRIPT object from Org to ASCII. +CONTENTS is the contents of the object. INFO is a plist holding +contextual information." + (if (org-element-property :use-brackets-p subscript) + (format "_{%s}" contents) + (format "_%s" contents))) + + +;;;; Superscript + +(defun org-ascii-superscript (superscript contents _info) + "Transcode a SUPERSCRIPT object from Org to ASCII. +CONTENTS is the contents of the object. INFO is a plist holding +contextual information." + (if (org-element-property :use-brackets-p superscript) + (format "^{%s}" contents) + (format "^%s" contents))) + + +;;;; Strike-through + +(defun org-ascii-strike-through (_strike-through contents _info) + "Transcode STRIKE-THROUGH from Org to ASCII. +CONTENTS is text with strike-through markup. INFO is a plist +holding contextual information." + (format "+%s+" contents)) + + +;;;; Table + +(defun org-ascii-table (table contents info) + "Transcode a TABLE element from Org to ASCII. +CONTENTS is the contents of the table. INFO is a plist holding +contextual information." + (let ((caption (org-ascii--build-caption table info)) + (caption-above-p (plist-get info :ascii-caption-above))) + (org-ascii--justify-element + (concat + ;; Possibly add a caption string above. + (and caption caption-above-p (concat caption "\n")) + ;; Insert table. Note: "table.el" tables are left unmodified. + (cond ((eq (org-element-property :type table) 'org) contents) + ((and (plist-get info :ascii-table-use-ascii-art) + (eq (plist-get info :ascii-charset) 'utf-8) + (require 'ascii-art-to-unicode nil t)) + (with-temp-buffer + (insert (org-remove-indentation + (org-element-property :value table))) + (goto-char (point-min)) + (aa2u) + (goto-char (point-max)) + (skip-chars-backward " \r\t\n") + (buffer-substring (point-min) (point)))) + (t (org-remove-indentation (org-element-property :value table)))) + ;; Possible add a caption string below. + (and (not caption-above-p) caption)) + table info))) + + +;;;; Table Cell + +(defun org-ascii--table-cell-width (table-cell info) + "Return width of TABLE-CELL. + +INFO is a plist used as a communication channel. + +Width of a cell is determined either by a width cookie in the +same column as the cell, or by the maximum cell's length in that +column. + +When `org-ascii-table-widen-columns' is non-nil, width cookies +are ignored." + (let* ((row (org-export-get-parent table-cell)) + (table (org-export-get-parent row)) + (col (let ((cells (org-element-contents row))) + (- (length cells) (length (memq table-cell cells))))) + (cache + (or (plist-get info :ascii-table-cell-width-cache) + (plist-get (setq info + (plist-put info :ascii-table-cell-width-cache + (make-hash-table :test 'equal))) + :ascii-table-cell-width-cache))) + (key (cons table col)) + (widenp (plist-get info :ascii-table-widen-columns))) + (or (gethash key cache) + (puthash + key + (let ((cookie-width (org-export-table-cell-width table-cell info))) + (or (and (not widenp) cookie-width) + (let ((contents-width + (let ((max-width 0)) + (org-element-map table 'table-row + (lambda (row) + (setq max-width + (max (string-width + (org-export-data + (org-element-contents + (elt (org-element-contents row) col)) + info)) + max-width))) + info) + max-width))) + (cond ((not cookie-width) contents-width) + (widenp (max cookie-width contents-width)) + (t cookie-width))))) + cache)))) + +(defun org-ascii-table-cell (table-cell contents info) + "Transcode a TABLE-CELL object from Org to ASCII. +CONTENTS is the cell contents. INFO is a plist used as +a communication channel." + ;; Determine column width. When `org-ascii-table-widen-columns' + ;; is nil and some width cookie has set it, use that value. + ;; Otherwise, compute the maximum width among transcoded data of + ;; each cell in the column. + (let ((width (org-ascii--table-cell-width table-cell info))) + ;; When contents are too large, truncate them. + (unless (or (plist-get info :ascii-table-widen-columns) + (<= (string-width (or contents "")) width)) + (setq contents (concat (substring contents 0 (- width 2)) "=>"))) + ;; Align contents correctly within the cell. + (let* ((indent-tabs-mode nil) + (data + (when contents + (org-ascii--justify-lines + contents width + (org-export-table-cell-alignment table-cell info))))) + (setq contents + (concat data + (make-string (- width (string-width (or data ""))) ?\s)))) + ;; Return cell. + (concat (format " %s " contents) + (when (memq 'right (org-export-table-cell-borders table-cell info)) + (if (eq (plist-get info :ascii-charset) 'utf-8) "│" "|"))))) + + +;;;; Table Row + +(defun org-ascii-table-row (table-row contents info) + "Transcode a TABLE-ROW element from Org to ASCII. +CONTENTS is the row contents. INFO is a plist used as +a communication channel." + (when (eq (org-element-property :type table-row) 'standard) + (let ((build-hline + (function + (lambda (lcorner horiz vert rcorner) + (concat + (apply + 'concat + (org-element-map table-row 'table-cell + (lambda (cell) + (let ((width (org-ascii--table-cell-width cell info)) + (borders (org-export-table-cell-borders cell info))) + (concat + ;; In order to know if CELL starts the row, do + ;; not compare it with the first cell in the + ;; row as there might be a special column. + ;; Instead, compare it with first exportable + ;; cell, obtained with `org-element-map'. + (when (and (memq 'left borders) + (eq (org-element-map table-row 'table-cell + 'identity info t) + cell)) + lcorner) + (make-string (+ 2 width) (string-to-char horiz)) + (cond + ((not (memq 'right borders)) nil) + ((eq (car (last (org-element-contents table-row))) cell) + rcorner) + (t vert))))) + info)) "\n")))) + (utf8p (eq (plist-get info :ascii-charset) 'utf-8)) + (borders (org-export-table-cell-borders + (org-element-map table-row 'table-cell 'identity info t) + info))) + (concat (cond + ((and (memq 'top borders) (or utf8p (memq 'above borders))) + (if utf8p (funcall build-hline "┍" "━" "┯" "┑") + (funcall build-hline "+" "-" "+" "+"))) + ((memq 'above borders) + (if utf8p (funcall build-hline "├" "─" "┼" "┤") + (funcall build-hline "+" "-" "+" "+")))) + (when (memq 'left borders) (if utf8p "│" "|")) + contents "\n" + (when (and (memq 'bottom borders) (or utf8p (memq 'below borders))) + (if utf8p (funcall build-hline "┕" "━" "┷" "┙") + (funcall build-hline "+" "-" "+" "+"))))))) + + +;;;; Timestamp + +(defun org-ascii-timestamp (timestamp _contents info) + "Transcode a TIMESTAMP object from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual information." + (org-ascii-plain-text (org-timestamp-translate timestamp) info)) + + +;;;; Underline + +(defun org-ascii-underline (_underline contents _info) + "Transcode UNDERLINE from Org to ASCII. +CONTENTS is the text with underline markup. INFO is a plist +holding contextual information." + (format "_%s_" contents)) + + +;;;; Verbatim + +(defun org-ascii-verbatim (verbatim _contents info) + "Return a VERBATIM object from Org to ASCII. +CONTENTS is nil. INFO is a plist holding contextual information." + (format (plist-get info :ascii-verbatim-format) + (org-element-property :value verbatim))) + + +;;;; Verse Block + +(defun org-ascii-verse-block (verse-block contents info) + "Transcode a VERSE-BLOCK element from Org to ASCII. +CONTENTS is verse block contents. INFO is a plist holding +contextual information." + (org-ascii--indent-string + (org-ascii--justify-element contents verse-block info) + (plist-get info :ascii-quote-margin))) + + + +;;; Filters + +(defun org-ascii-filter-headline-blank-lines (headline _backend info) + "Filter controlling number of blank lines after a headline. + +HEADLINE is a string representing a transcoded headline. BACKEND +is symbol specifying back-end used for export. INFO is plist +containing the communication channel. + +This function only applies to `ascii' back-end. See +`org-ascii-headline-spacing' for information." + (let ((headline-spacing (plist-get info :ascii-headline-spacing))) + (if (not headline-spacing) headline + (let ((blanks (make-string (1+ (cdr headline-spacing)) ?\n))) + (replace-regexp-in-string "\n\\(?:\n[ \t]*\\)*\\'" blanks headline))))) + +(defun org-ascii-filter-paragraph-spacing (tree _backend info) + "Filter controlling number of blank lines between paragraphs. + +TREE is the parse tree. BACKEND is the symbol specifying +back-end used for export. INFO is a plist used as +a communication channel. + +See `org-ascii-paragraph-spacing' for information." + (let ((paragraph-spacing (plist-get info :ascii-paragraph-spacing))) + (when (wholenump paragraph-spacing) + (org-element-map tree 'paragraph + (lambda (p) + (when (eq (org-element-type (org-export-get-next-element p info)) + 'paragraph) + (org-element-put-property p :post-blank paragraph-spacing)))))) + tree) + +(defun org-ascii-filter-comment-spacing (tree _backend info) + "Filter removing blank lines between comments. +TREE is the parse tree. BACKEND is the symbol specifying +back-end used for export. INFO is a plist used as +a communication channel." + (org-element-map tree '(comment comment-block) + (lambda (c) + (when (memq (org-element-type (org-export-get-next-element c info)) + '(comment comment-block)) + (org-element-put-property c :post-blank 0)))) + tree) + + + +;;; End-user functions + +;;;###autoload +(defun org-ascii-export-as-ascii + (&optional async subtreep visible-only body-only ext-plist) + "Export current buffer to a text buffer. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should be accessible +through the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, strip title and +table of contents from output. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Export is done in a buffer named \"*Org ASCII Export*\", which +will be displayed when `org-export-show-temporary-export-buffer' +is non-nil." + (interactive) + (org-export-to-buffer 'ascii "*Org ASCII Export*" + async subtreep visible-only body-only ext-plist (lambda () (text-mode)))) + +;;;###autoload +(defun org-ascii-export-to-ascii + (&optional async subtreep visible-only body-only ext-plist) + "Export current buffer to a text file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, strip title and +table of contents from output. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return output file's name." + (interactive) + (let ((file (org-export-output-file-name ".txt" subtreep))) + (org-export-to-file 'ascii file + async subtreep visible-only body-only ext-plist))) + +;;;###autoload +(defun org-ascii-publish-to-ascii (plist filename pub-dir) + "Publish an Org file to ASCII. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name." + (org-publish-org-to + 'ascii filename ".txt" `(:ascii-charset ascii ,@plist) pub-dir)) + +;;;###autoload +(defun org-ascii-publish-to-latin1 (plist filename pub-dir) + "Publish an Org file to Latin-1. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name." + (org-publish-org-to + 'ascii filename ".txt" `(:ascii-charset latin1 ,@plist) pub-dir)) + +;;;###autoload +(defun org-ascii-publish-to-utf8 (plist filename pub-dir) + "Publish an org file to UTF-8. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name." + (org-publish-org-to + 'ascii filename ".txt" `(:ascii-charset utf-8 ,@plist) pub-dir)) + + +(provide 'ox-ascii) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; coding: utf-8 +;; End: + +;;; ox-ascii.el ends here diff --git a/elpa/org-9.1.14/ox-beamer.el b/elpa/org-9.1.14/ox-beamer.el new file mode 100644 index 00000000..15b78dcd --- /dev/null +++ b/elpa/org-9.1.14/ox-beamer.el @@ -0,0 +1,1143 @@ +;;; ox-beamer.el --- Beamer Back-End for Org Export Engine -*- lexical-binding: t; -*- + +;; Copyright (C) 2007-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik <carsten.dominik AT gmail DOT com> +;; Nicolas Goaziou <n.goaziou AT gmail DOT com> +;; Keywords: org, wp, tex + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: +;; +;; This library implements both a Beamer back-end, derived from the +;; LaTeX one and a minor mode easing structure edition of the +;; document. See Org manual for more information. + +;;; Code: + +(require 'cl-lib) +(require 'ox-latex) + +;; Install a default set-up for Beamer export. +(unless (assoc "beamer" org-latex-classes) + (add-to-list 'org-latex-classes + '("beamer" + "\\documentclass[presentation]{beamer}" + ("\\section{%s}" . "\\section*{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))) + + + +;;; User-Configurable Variables + +(defgroup org-export-beamer nil + "Options specific for using the beamer class in LaTeX export." + :tag "Org Beamer" + :group 'org-export + :version "24.2") + +(defcustom org-beamer-frame-level 1 + "The level at which headlines become frames. + +Headlines at a lower level will be translated into a sectioning +structure. At a higher level, they will be translated into +blocks. + +If a headline with a \"BEAMER_env\" property set to \"frame\" is +found within a tree, its level locally overrides this number. + +This variable has no effect on headlines with the \"BEAMER_env\" +property set to either \"ignoreheading\", \"appendix\", or +\"note\", which will respectively, be invisible, become an +appendix or a note. + +This integer is relative to the minimal level of a headline +within the parse tree, defined as 1." + :group 'org-export-beamer + :type 'integer) + +(defcustom org-beamer-frame-default-options "" + "Default options string to use for frames. +For example, it could be set to \"allowframebreaks\"." + :group 'org-export-beamer + :type '(string :tag "[options]")) + +(defcustom org-beamer-column-view-format + "%45ITEM %10BEAMER_env(Env) %10BEAMER_act(Act) %4BEAMER_col(Col) %8BEAMER_opt(Opt)" + "Column view format that should be used to fill the template." + :group 'org-export-beamer + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "Do not insert Beamer column view format" nil) + (string :tag "Beamer column view format"))) + +(defcustom org-beamer-theme "default" + "Default theme used in Beamer presentations." + :group 'org-export-beamer + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "Do not insert a Beamer theme" nil) + (string :tag "Beamer theme"))) + +(defcustom org-beamer-environments-extra nil + "Environments triggered by tags in Beamer export. +Each entry has 4 elements: + +name Name of the environment +key Selection key for `org-beamer-select-environment' +open The opening template for the environment, with the following escapes + %a the action/overlay specification + %A the default action/overlay specification + %R the raw BEAMER_act value + %o the options argument, with square brackets + %O the raw BEAMER_opt value + %h the headline text + %r the raw headline text (i.e. without any processing) + %H if there is headline text, that raw text in {} braces + %U if there is headline text, that raw text in [] brackets +close The closing string of the environment." + :group 'org-export-beamer + :version "24.4" + :package-version '(Org . "8.1") + :type '(repeat + (list + (string :tag "Environment") + (string :tag "Selection key") + (string :tag "Begin") + (string :tag "End")))) + +(defcustom org-beamer-outline-frame-title "Outline" + "Default title of a frame containing an outline." + :group 'org-export-beamer + :type '(string :tag "Outline frame title")) + +(defcustom org-beamer-outline-frame-options "" + "Outline frame options appended after \\begin{frame}. +You might want to put e.g. \"allowframebreaks=0.9\" here." + :group 'org-export-beamer + :type '(string :tag "Outline frame options")) + + +(defcustom org-beamer-subtitle-format "\\subtitle{%s}" + "Format string used for transcoded subtitle. +The format string should have at most one \"%s\"-expression, +which is replaced with the subtitle." + :group 'org-export-beamer + :version "26.1" + :package-version '(Org . "8.3") + :type '(string :tag "Format string")) + + +;;; Internal Variables + +(defconst org-beamer-column-widths + "0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.0 :ETC" +"The column widths that should be installed as allowed property values.") + +(defconst org-beamer-environments-special + '(("againframe" "A") + ("appendix" "x") + ("column" "c") + ("columns" "C") + ("frame" "f") + ("fullframe" "F") + ("ignoreheading" "i") + ("note" "n") + ("noteNH" "N")) + "Alist of environments treated in a special way by the back-end. +Keys are environment names, as strings, values are bindings used +in `org-beamer-select-environment'. Environments listed here, +along with their binding, are hard coded and cannot be modified +through `org-beamer-environments-extra' variable.") + +(defconst org-beamer-environments-default + '(("block" "b" "\\begin{block}%a{%h}" "\\end{block}") + ("alertblock" "a" "\\begin{alertblock}%a{%h}" "\\end{alertblock}") + ("verse" "v" "\\begin{verse}%a %% %h" "\\end{verse}") + ("quotation" "q" "\\begin{quotation}%a %% %h" "\\end{quotation}") + ("quote" "Q" "\\begin{quote}%a %% %h" "\\end{quote}") + ("structureenv" "s" "\\begin{structureenv}%a %% %h" "\\end{structureenv}") + ("theorem" "t" "\\begin{theorem}%a[%h]" "\\end{theorem}") + ("definition" "d" "\\begin{definition}%a[%h]" "\\end{definition}") + ("example" "e" "\\begin{example}%a[%h]" "\\end{example}") + ("exampleblock" "E" "\\begin{exampleblock}%a{%h}" "\\end{exampleblock}") + ("proof" "p" "\\begin{proof}%a[%h]" "\\end{proof}") + ("beamercolorbox" "o" "\\begin{beamercolorbox}%o{%h}" "\\end{beamercolorbox}")) + "Environments triggered by properties in Beamer export. +These are the defaults - for user definitions, see +`org-beamer-environments-extra'.") + +(defconst org-beamer-verbatim-elements + '(code example-block fixed-width inline-src-block src-block verbatim) + "List of element or object types producing verbatim text. +This is used internally to determine when a frame should have the +\"fragile\" option.") + + + +;;; Internal functions + +(defun org-beamer--normalize-argument (argument type) + "Return ARGUMENT string with proper boundaries. + +TYPE is a symbol among the following: +`action' Return ARGUMENT within angular brackets. +`defaction' Return ARGUMENT within both square and angular brackets. +`option' Return ARGUMENT within square brackets." + (if (not (string-match "\\S-" argument)) "" + (cl-case type + (action (format "<%s>" (org-unbracket-string "<" ">" argument))) + (defaction + (format "[<%s>]" + (org-unbracket-string "<" ">" (org-unbracket-string "[" "]" argument)))) + (option (format "[%s]" (org-unbracket-string "[" "]" argument))) + (otherwise (error "Invalid `type' argument to `org-beamer--normalize-argument': %s" + type))))) + +(defun org-beamer--element-has-overlay-p (element) + "Non-nil when ELEMENT has an overlay specified. +An element has an overlay specification when it starts with an +`beamer' export-snippet whose value is between angular brackets. +Return overlay specification, as a string, or nil." + (let ((first-object (car (org-element-contents element)))) + (when (eq (org-element-type first-object) 'export-snippet) + (let ((value (org-element-property :value first-object))) + (and (string-prefix-p "<" value) (string-suffix-p ">" value) + value))))) + + + +;;; Define Back-End + +(org-export-define-derived-backend 'beamer 'latex + :menu-entry + '(?l 1 + ((?B "As LaTeX buffer (Beamer)" org-beamer-export-as-latex) + (?b "As LaTeX file (Beamer)" org-beamer-export-to-latex) + (?P "As PDF file (Beamer)" org-beamer-export-to-pdf) + (?O "As PDF file and open (Beamer)" + (lambda (a s v b) + (if a (org-beamer-export-to-pdf t s v b) + (org-open-file (org-beamer-export-to-pdf nil s v b))))))) + :options-alist + '((:headline-levels nil "H" org-beamer-frame-level) + (:latex-class "LATEX_CLASS" nil "beamer" t) + (:beamer-subtitle-format nil nil org-beamer-subtitle-format) + (:beamer-column-view-format "COLUMNS" nil org-beamer-column-view-format) + (:beamer-theme "BEAMER_THEME" nil org-beamer-theme) + (:beamer-color-theme "BEAMER_COLOR_THEME" nil nil t) + (:beamer-font-theme "BEAMER_FONT_THEME" nil nil t) + (:beamer-inner-theme "BEAMER_INNER_THEME" nil nil t) + (:beamer-outer-theme "BEAMER_OUTER_THEME" nil nil t) + (:beamer-header "BEAMER_HEADER" nil nil newline) + (:beamer-environments-extra nil nil org-beamer-environments-extra) + (:beamer-frame-default-options nil nil org-beamer-frame-default-options) + (:beamer-outline-frame-options nil nil org-beamer-outline-frame-options) + (:beamer-outline-frame-title nil nil org-beamer-outline-frame-title)) + :translate-alist '((bold . org-beamer-bold) + (export-block . org-beamer-export-block) + (export-snippet . org-beamer-export-snippet) + (headline . org-beamer-headline) + (item . org-beamer-item) + (keyword . org-beamer-keyword) + (link . org-beamer-link) + (plain-list . org-beamer-plain-list) + (radio-target . org-beamer-radio-target) + (template . org-beamer-template))) + + + +;;; Transcode Functions + +;;;; Bold + +(defun org-beamer-bold (bold contents _info) + "Transcode BLOCK object into Beamer code. +CONTENTS is the text being bold. INFO is a plist used as +a communication channel." + (format "\\alert%s{%s}" + (or (org-beamer--element-has-overlay-p bold) "") + contents)) + + +;;;; Export Block + +(defun org-beamer-export-block (export-block _contents _info) + "Transcode an EXPORT-BLOCK element into Beamer code. +CONTENTS is nil. INFO is a plist used as a communication +channel." + (when (member (org-element-property :type export-block) '("BEAMER" "LATEX")) + (org-remove-indentation (org-element-property :value export-block)))) + + +;;;; Export Snippet + +(defun org-beamer-export-snippet (export-snippet _contents info) + "Transcode an EXPORT-SNIPPET object into Beamer code. +CONTENTS is nil. INFO is a plist used as a communication +channel." + (let ((backend (org-export-snippet-backend export-snippet)) + (value (org-element-property :value export-snippet))) + ;; Only "latex" and "beamer" snippets are retained. + (cond ((eq backend 'latex) value) + ;; Ignore "beamer" snippets specifying overlays. + ((and (eq backend 'beamer) + (or (org-export-get-previous-element export-snippet info) + (not (string-match "\\`<.*>\\'" value)))) + value)))) + + +;;;; Headline +;; +;; The main function to translate a headline is +;; `org-beamer-headline'. +;; +;; Depending on the level at which a headline is considered as +;; a frame (given by `org-beamer--frame-level'), the headline is +;; either a section (`org-beamer--format-section'), a frame +;; (`org-beamer--format-frame') or a block +;; (`org-beamer--format-block'). +;; +;; `org-beamer-headline' also takes care of special environments +;; like "ignoreheading", "note", "noteNH", "appendix" and +;; "againframe". + +(defun org-beamer--get-label (headline info) + "Return label for HEADLINE, as a string. + +INFO is a plist used as a communication channel. + +The value is either the label specified in \"BEAMER_opt\" +property, the custom ID, if there is one and +`:latex-prefer-user-labels' property has a non nil value, or +a unique internal label. This function assumes HEADLINE will be +treated as a frame." + (cond + ((let ((opt (org-element-property :BEAMER_OPT headline))) + (and (stringp opt) + (string-match "\\(?:^\\|,\\)label=\\(.*?\\)\\(?:$\\|,\\)" opt) + (let ((label (match-string 1 opt))) + (if (string-match-p "\\`{.*}\\'" label) + (substring label 1 -1) + label))))) + ((and (plist-get info :latex-prefer-user-labels) + (org-element-property :CUSTOM_ID headline))) + (t (format "sec:%s" (org-export-get-reference headline info))))) + +(defun org-beamer--frame-level (headline info) + "Return frame level in subtree containing HEADLINE. +INFO is a plist used as a communication channel." + (or + ;; 1. Look for "frame" environment in parents, starting from the + ;; farthest. + (catch 'exit + (dolist (parent (nreverse (org-element-lineage headline))) + (let ((env (org-element-property :BEAMER_ENV parent))) + (when (and env (member-ignore-case env '("frame" "fullframe"))) + (throw 'exit (org-export-get-relative-level parent info)))))) + ;; 2. Look for "frame" environment in HEADLINE. + (let ((env (org-element-property :BEAMER_ENV headline))) + (and env (member-ignore-case env '("frame" "fullframe")) + (org-export-get-relative-level headline info))) + ;; 3. Look for "frame" environment in sub-tree. + (org-element-map headline 'headline + (lambda (hl) + (let ((env (org-element-property :BEAMER_ENV hl))) + (when (and env (member-ignore-case env '("frame" "fullframe"))) + (org-export-get-relative-level hl info)))) + info 'first-match) + ;; 4. No "frame" environment in tree: use default value. + (plist-get info :headline-levels))) + +(defun org-beamer--format-section (headline contents info) + "Format HEADLINE as a sectioning part. +CONTENTS holds the contents of the headline. INFO is a plist +used as a communication channel." + (let ((latex-headline + (org-export-with-backend + ;; We create a temporary export back-end which behaves the + ;; same as current one, but adds "\protect" in front of the + ;; output of some objects. + (org-export-create-backend + :parent 'latex + :transcoders + (let ((protected-output + (function + (lambda (object contents info) + (let ((code (org-export-with-backend + 'beamer object contents info))) + (if (org-string-nw-p code) (concat "\\protect" code) + code)))))) + (mapcar #'(lambda (type) (cons type protected-output)) + '(bold footnote-reference italic strike-through timestamp + underline)))) + headline + contents + info)) + (mode-specs (org-element-property :BEAMER_ACT headline))) + (if (and mode-specs + (string-match "\\`\\\\\\(.*?\\)\\(?:\\*\\|\\[.*\\]\\)?{" + latex-headline)) + ;; Insert overlay specifications. + (replace-match (concat (match-string 1 latex-headline) + (format "<%s>" mode-specs)) + nil nil latex-headline 1) + latex-headline))) + +(defun org-beamer--format-frame (headline contents info) + "Format HEADLINE as a frame. +CONTENTS holds the contents of the headline. INFO is a plist +used as a communication channel." + (let ((fragilep + ;; FRAGILEP is non-nil when HEADLINE contains an element + ;; among `org-beamer-verbatim-elements'. + (org-element-map headline org-beamer-verbatim-elements 'identity + info 'first-match))) + (concat "\\begin{frame}" + ;; Overlay specification, if any. When surrounded by + ;; square brackets, consider it as a default + ;; specification. + (let ((action (org-element-property :BEAMER_ACT headline))) + (cond + ((not action) "") + ((string-match "\\`\\[.*\\]\\'" action ) + (org-beamer--normalize-argument action 'defaction)) + (t (org-beamer--normalize-argument action 'action)))) + ;; Options, if any. + (let* ((beamer-opt (org-element-property :BEAMER_OPT headline)) + (options + ;; Collect nonempty options from default value and + ;; headline's properties. Also add a label for + ;; links. + (cl-remove-if-not 'org-string-nw-p + (append + (org-split-string + (plist-get info :beamer-frame-default-options) ",") + (and beamer-opt + (org-split-string + ;; Remove square brackets if user provided + ;; them. + (and (string-match "^\\[?\\(.*\\)\\]?$" beamer-opt) + (match-string 1 beamer-opt)) + ",")) + ;; Provide an automatic label for the frame + ;; unless the user specified one. Also refrain + ;; from labeling `allowframebreaks' frames; this + ;; is not allowed by beamer. + (unless (and beamer-opt + (or (string-match "\\(^\\|,\\)label=" beamer-opt) + (string-match "allowframebreaks" beamer-opt))) + (list + (let ((label (org-beamer--get-label headline info))) + ;; Labels containing colons need to be + ;; wrapped within braces. + (format (if (string-match-p ":" label) + "label={%s}" + "label=%s") + label)))))))) + ;; Change options list into a string. + (org-beamer--normalize-argument + (mapconcat + 'identity + (if (or (not fragilep) (member "fragile" options)) options + (cons "fragile" options)) + ",") + 'option)) + ;; Title. + (let ((env (org-element-property :BEAMER_ENV headline))) + (format "{%s}" + (if (and env (equal (downcase env) "fullframe")) "" + (org-export-data + (org-element-property :title headline) info)))) + "\n" + ;; The following workaround is required in fragile frames + ;; as Beamer will append "\par" to the beginning of the + ;; contents. So we need to make sure the command is + ;; separated from the contents by at least one space. If + ;; it isn't, it will create "\parfirst-word" command and + ;; remove the first word from the contents in the PDF + ;; output. + (if (not fragilep) contents + (replace-regexp-in-string "\\`\n*" "\\& " (or contents ""))) + "\\end{frame}"))) + +(defun org-beamer--format-block (headline contents info) + "Format HEADLINE as a block. +CONTENTS holds the contents of the headline. INFO is a plist +used as a communication channel." + (let* ((column-width (org-element-property :BEAMER_COL headline)) + ;; ENVIRONMENT defaults to "block" if none is specified and + ;; there is no column specification. If there is a column + ;; specified but still no explicit environment, ENVIRONMENT + ;; is "column". + (environment (let ((env (org-element-property :BEAMER_ENV headline))) + (cond + ;; "block" is the fallback environment. + ((and (not env) (not column-width)) "block") + ;; "column" only. + ((not env) "column") + ;; Use specified environment. + (t env)))) + (raw-title (org-element-property :raw-value headline)) + (env-format + (cond ((member environment '("column" "columns")) nil) + ((assoc environment + (append (plist-get info :beamer-environments-extra) + org-beamer-environments-default))) + (t (user-error "Wrong block type at a headline named \"%s\"" + raw-title)))) + (title (org-export-data (org-element-property :title headline) info)) + (raw-options (org-element-property :BEAMER_OPT headline)) + (options (if raw-options + (org-beamer--normalize-argument raw-options 'option) + "")) + ;; Start a "columns" environment when explicitly requested or + ;; when there is no previous headline or the previous + ;; headline do not have a BEAMER_column property. + (parent-env (org-element-property + :BEAMER_ENV (org-export-get-parent-headline headline))) + (start-columns-p + (or (equal environment "columns") + (and column-width + (not (and parent-env + (equal (downcase parent-env) "columns"))) + (or (org-export-first-sibling-p headline info) + (not (org-element-property + :BEAMER_COL + (org-export-get-previous-element + headline info))))))) + ;; End the "columns" environment when explicitly requested or + ;; when there is no next headline or the next headline do not + ;; have a BEAMER_column property. + (end-columns-p + (or (equal environment "columns") + (and column-width + (not (and parent-env + (equal (downcase parent-env) "columns"))) + (or (org-export-last-sibling-p headline info) + (not (org-element-property + :BEAMER_COL + (org-export-get-next-element headline info)))))))) + (concat + (when start-columns-p + ;; Column can accept options only when the environment is + ;; explicitly defined. + (if (not (equal environment "columns")) "\\begin{columns}\n" + (format "\\begin{columns}%s\n" options))) + (when column-width + (format "\\begin{column}%s{%s}\n" + ;; One can specify placement for column only when + ;; HEADLINE stands for a column on its own. + (if (equal environment "column") options "") + (format "%s\\columnwidth" column-width))) + ;; Block's opening string. + (when (nth 2 env-format) + (concat + (org-fill-template + (nth 2 env-format) + (nconc + ;; If BEAMER_act property has its value enclosed in square + ;; brackets, it is a default overlay specification and + ;; overlay specification is empty. Otherwise, it is an + ;; overlay specification and the default one is nil. + (let ((action (org-element-property :BEAMER_ACT headline))) + (cond + ((not action) (list (cons "a" "") (cons "A" "") (cons "R" ""))) + ((and (string-prefix-p "[" action) + (string-suffix-p "]" action)) + (list + (cons "A" (org-beamer--normalize-argument action 'defaction)) + (cons "a" "") + (cons "R" action))) + (t + (list (cons "a" (org-beamer--normalize-argument action 'action)) + (cons "A" "") + (cons "R" action))))) + (list (cons "o" options) + (cons "O" (or raw-options "")) + (cons "h" title) + (cons "r" raw-title) + (cons "H" (if (equal raw-title "") "" + (format "{%s}" raw-title))) + (cons "U" (if (equal raw-title "") "" + (format "[%s]" raw-title)))))) + "\n")) + contents + ;; Block's closing string, if any. + (and (nth 3 env-format) (concat (nth 3 env-format) "\n")) + (when column-width "\\end{column}\n") + (when end-columns-p "\\end{columns}")))) + +(defun org-beamer-headline (headline contents info) + "Transcode HEADLINE element into Beamer code. +CONTENTS is the contents of the headline. INFO is a plist used +as a communication channel." + (unless (org-element-property :footnote-section-p headline) + (let ((level (org-export-get-relative-level headline info)) + (frame-level (org-beamer--frame-level headline info)) + (environment (let ((env (org-element-property :BEAMER_ENV headline))) + (or (org-string-nw-p env) "block")))) + (cond + ;; Case 1: Resume frame specified by "BEAMER_ref" property. + ((equal environment "againframe") + (let ((ref (org-element-property :BEAMER_REF headline))) + ;; Reference to frame being resumed is mandatory. Ignore + ;; the whole headline if it isn't provided. + (when (org-string-nw-p ref) + (concat "\\againframe" + ;; Overlay specification. + (let ((overlay (org-element-property :BEAMER_ACT headline))) + (when overlay + (org-beamer--normalize-argument + overlay + (if (string-match "\\`\\[.*\\]\\'" overlay) 'defaction + 'action)))) + ;; Options. + (let ((options (org-element-property :BEAMER_OPT headline))) + (when options + (org-beamer--normalize-argument options 'option))) + ;; Resolve reference provided by "BEAMER_ref" + ;; property. This is done by building a minimal + ;; fake link and calling the appropriate resolve + ;; function, depending on the reference syntax. + (let ((target + (if (string-match "\\`\\(id:\\|#\\)" ref) + (org-export-resolve-id-link + `(link (:path ,(substring ref (match-end 0)))) + info) + (org-export-resolve-fuzzy-link + `(link (:path + ;; Look for headlines only. + ,(if (eq (string-to-char ref) ?*) ref + (concat "*" ref)))) + info)))) + ;; Now use user-defined label provided in TARGET + ;; headline, or fallback to standard one. + (format "{%s}" (org-beamer--get-label target info))))))) + ;; Case 2: Creation of an appendix is requested. + ((equal environment "appendix") + (concat "\\appendix" + (org-element-property :BEAMER_ACT headline) + "\n" + (make-string (org-element-property :pre-blank headline) ?\n) + contents)) + ;; Case 3: Ignore heading. + ((equal environment "ignoreheading") + (concat (make-string (org-element-property :pre-blank headline) ?\n) + contents)) + ;; Case 4: HEADLINE is a note. + ((member environment '("note" "noteNH")) + (format "\\note{%s}" + (concat (and (equal environment "note") + (concat + (org-export-data + (org-element-property :title headline) info) + "\n")) + (org-trim contents)))) + ;; Case 5: HEADLINE is a frame. + ((= level frame-level) + (org-beamer--format-frame headline contents info)) + ;; Case 6: Regular section, extracted from + ;; `org-latex-classes'. + ((< level frame-level) + (org-beamer--format-section headline contents info)) + ;; Case 7: Otherwise, HEADLINE is a block. + (t (org-beamer--format-block headline contents info)))))) + + +;;;; Item + +(defun org-beamer-item (item contents info) + "Transcode an ITEM element into Beamer code. +CONTENTS holds the contents of the item. INFO is a plist holding +contextual information." + (org-export-with-backend + ;; Delegate item export to `latex'. However, we use `beamer' + ;; transcoders for objects in the description tag. + (org-export-create-backend + :parent 'beamer + :transcoders + (list + (cons + 'item + (lambda (item _c _i) + (let ((action + (let ((first (car (org-element-contents item)))) + (and (eq (org-element-type first) 'paragraph) + (org-beamer--element-has-overlay-p first)))) + (output (org-latex-item item contents info))) + (if (not (and action (string-match "\\\\item" output))) output + ;; If the item starts with a paragraph and that paragraph + ;; starts with an export snippet specifying an overlay, + ;; append it to the \item command. + (replace-match (concat "\\\\item" action) nil nil output))))))) + item contents info)) + + +;;;; Keyword + +(defun org-beamer-keyword (keyword contents info) + "Transcode a KEYWORD element into Beamer code. +CONTENTS is nil. INFO is a plist used as a communication +channel." + (let ((key (org-element-property :key keyword)) + (value (org-element-property :value keyword))) + ;; Handle specifically BEAMER and TOC (headlines only) keywords. + ;; Otherwise, fallback to `latex' back-end. + (cond + ((equal key "BEAMER") value) + ((and (equal key "TOC") (string-match "\\<headlines\\>" value)) + (let ((depth (or (and (string-match "[0-9]+" value) + (string-to-number (match-string 0 value))) + (plist-get info :with-toc))) + (options (and (string-match "\\[.*?\\]" value) + (match-string 0 value)))) + (concat + (when (wholenump depth) (format "\\setcounter{tocdepth}{%s}\n" depth)) + "\\tableofcontents" options))) + (t (org-export-with-backend 'latex keyword contents info))))) + + +;;;; Link + +(defun org-beamer-link (link contents info) + "Transcode a LINK object into Beamer code. +CONTENTS is the description part of the link. INFO is a plist +used as a communication channel." + (or (org-export-custom-protocol-maybe link contents 'beamer) + ;; Fall-back to LaTeX export. However, prefer "\hyperlink" over + ;; "\hyperref" since the former handles overlay specifications. + (let ((latex-link (org-export-with-backend 'latex link contents info))) + (if (string-match "\\`\\\\hyperref\\[\\(.*?\\)\\]" latex-link) + (replace-match + (format "\\\\hyperlink%s{\\1}" + (or (org-beamer--element-has-overlay-p link) "")) + nil nil latex-link) + latex-link)))) + + +;;;; Plain List +;; +;; Plain lists support `:environment', `:overlay' and `:options' +;; attributes. + +(defun org-beamer-plain-list (plain-list contents info) + "Transcode a PLAIN-LIST element into Beamer code. +CONTENTS is the contents of the list. INFO is a plist holding +contextual information." + (let* ((type (org-element-property :type plain-list)) + (attributes (org-combine-plists + (org-export-read-attribute :attr_latex plain-list) + (org-export-read-attribute :attr_beamer plain-list))) + (latex-type (let ((env (plist-get attributes :environment))) + (cond (env) + ((eq type 'ordered) "enumerate") + ((eq type 'descriptive) "description") + (t "itemize"))))) + (org-latex--wrap-label + plain-list + (format "\\begin{%s}%s%s\n%s\\end{%s}" + latex-type + ;; Default overlay specification, if any. + (org-beamer--normalize-argument + (or (plist-get attributes :overlay) "") + 'defaction) + ;; Second optional argument depends on the list type. + (org-beamer--normalize-argument + (or (plist-get attributes :options) "") + 'option) + ;; Eventually insert contents and close environment. + contents + latex-type) + info))) + + +;;;; Radio Target + +(defun org-beamer-radio-target (radio-target text info) + "Transcode a RADIO-TARGET object into Beamer code. +TEXT is the text of the target. INFO is a plist holding +contextual information." + (format "\\hypertarget%s{%s}{%s}" + (or (org-beamer--element-has-overlay-p radio-target) "") + (org-export-get-reference radio-target info) + text)) + + +;;;; Template +;; +;; Template used is similar to the one used in `latex' back-end, +;; excepted for the table of contents and Beamer themes. + +(defun org-beamer-template (contents info) + "Return complete document string after Beamer conversion. +CONTENTS is the transcoded contents string. INFO is a plist +holding export options." + (let ((title (org-export-data (plist-get info :title) info)) + (subtitle (org-export-data (plist-get info :subtitle) info))) + (concat + ;; Time-stamp. + (and (plist-get info :time-stamp-file) + (format-time-string "%% Created %Y-%m-%d %a %H:%M\n")) + ;; LaTeX compiler + (org-latex--insert-compiler info) + ;; Document class and packages. + (org-latex-make-preamble info) + ;; Insert themes. + (let ((format-theme + (function + (lambda (prop command) + (let ((theme (plist-get info prop))) + (when theme + (concat command + (if (not (string-match "\\[.*\\]" theme)) + (format "{%s}\n" theme) + (format "%s{%s}\n" + (match-string 0 theme) + (org-trim + (replace-match "" nil nil theme))))))))))) + (mapconcat (lambda (args) (apply format-theme args)) + '((:beamer-theme "\\usetheme") + (:beamer-color-theme "\\usecolortheme") + (:beamer-font-theme "\\usefonttheme") + (:beamer-inner-theme "\\useinnertheme") + (:beamer-outer-theme "\\useoutertheme")) + "")) + ;; Possibly limit depth for headline numbering. + (let ((sec-num (plist-get info :section-numbers))) + (when (integerp sec-num) + (format "\\setcounter{secnumdepth}{%d}\n" sec-num))) + ;; Author. + (let ((author (and (plist-get info :with-author) + (let ((auth (plist-get info :author))) + (and auth (org-export-data auth info))))) + (email (and (plist-get info :with-email) + (org-export-data (plist-get info :email) info)))) + (cond ((and author email (not (string= "" email))) + (format "\\author{%s\\thanks{%s}}\n" author email)) + ((or author email) (format "\\author{%s}\n" (or author email))))) + ;; Date. + (let ((date (and (plist-get info :with-date) (org-export-get-date info)))) + (format "\\date{%s}\n" (org-export-data date info))) + ;; Title + (format "\\title{%s}\n" title) + (when (org-string-nw-p subtitle) + (concat (format (plist-get info :beamer-subtitle-format) subtitle) "\n")) + ;; Beamer-header + (let ((beamer-header (plist-get info :beamer-header))) + (when beamer-header + (format "%s\n" (plist-get info :beamer-header)))) + ;; 9. Hyperref options. + (let ((template (plist-get info :latex-hyperref-template))) + (and (stringp template) + (format-spec template (org-latex--format-spec info)))) + ;; Document start. + "\\begin{document}\n\n" + ;; Title command. + (org-element-normalize-string + (cond ((not (plist-get info :with-title)) nil) + ((string= "" title) nil) + ((not (stringp org-latex-title-command)) nil) + ((string-match "\\(?:[^%]\\|^\\)%s" + org-latex-title-command) + (format org-latex-title-command title)) + (t org-latex-title-command))) + ;; Table of contents. + (let ((depth (plist-get info :with-toc))) + (when depth + (concat + (format "\\begin{frame}%s{%s}\n" + (org-beamer--normalize-argument + (plist-get info :beamer-outline-frame-options) 'option) + (plist-get info :beamer-outline-frame-title)) + (when (wholenump depth) + (format "\\setcounter{tocdepth}{%d}\n" depth)) + "\\tableofcontents\n" + "\\end{frame}\n\n"))) + ;; Document's body. + contents + ;; Creator. + (if (plist-get info :with-creator) + (concat (plist-get info :creator) "\n") + "") + ;; Document end. + "\\end{document}"))) + + + +;;; Minor Mode + + +(defvar org-beamer-mode-map (make-sparse-keymap) + "The keymap for `org-beamer-mode'.") +(define-key org-beamer-mode-map "\C-c\C-b" 'org-beamer-select-environment) + +;;;###autoload +(define-minor-mode org-beamer-mode + "Support for editing Beamer oriented Org mode files." + nil " Bm" 'org-beamer-mode-map) + +(when (fboundp 'font-lock-add-keywords) + (font-lock-add-keywords + 'org-mode + '((":\\(B_[a-z]+\\|BMCOL\\):" 1 'org-beamer-tag prepend)) + 'prepend)) + +(defface org-beamer-tag '((t (:box (:line-width 1 :color grey40)))) + "The special face for beamer tags." + :group 'org-export-beamer) + +(defun org-beamer-property-changed (property value) + "Track the BEAMER_env property with tags. +PROPERTY is the name of the modified property. VALUE is its new +value." + (cond + ((equal property "BEAMER_env") + (save-excursion + (org-back-to-heading t) + ;; Filter out Beamer-related tags and install environment tag. + (let ((tags (cl-remove-if (lambda (x) (string-match "^B_" x)) + (org-get-tags))) + (env-tag (and (org-string-nw-p value) (concat "B_" value)))) + (org-set-tags-to (if env-tag (cons env-tag tags) tags)) + (when env-tag (org-toggle-tag env-tag 'on))))) + ((equal property "BEAMER_col") + (org-toggle-tag "BMCOL" (if (org-string-nw-p value) 'on 'off))))) + +(add-hook 'org-property-changed-functions 'org-beamer-property-changed) + +(defun org-beamer-allowed-property-values (property) + "Supply allowed values for PROPERTY." + (cond + ((and (equal property "BEAMER_env") + (not (org-entry-get nil (concat property "_ALL") 'inherit))) + ;; If no allowed values for BEAMER_env have been defined, + ;; supply all defined environments + (mapcar 'car (append org-beamer-environments-special + org-beamer-environments-extra + org-beamer-environments-default))) + ((and (equal property "BEAMER_col") + (not (org-entry-get nil (concat property "_ALL") 'inherit))) + ;; If no allowed values for BEAMER_col have been defined, supply + ;; some. + (split-string org-beamer-column-widths " ")))) + +(add-hook 'org-property-allowed-value-functions + 'org-beamer-allowed-property-values) + + + +;;; Commands + +;;;###autoload +(defun org-beamer-export-as-latex + (&optional async subtreep visible-only body-only ext-plist) + "Export current buffer as a Beamer buffer. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should be accessible +through the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Export is done in a buffer named \"*Org BEAMER Export*\", which +will be displayed when `org-export-show-temporary-export-buffer' +is non-nil." + (interactive) + (org-export-to-buffer 'beamer "*Org BEAMER Export*" + async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode)))) + +;;;###autoload +(defun org-beamer-export-to-latex + (&optional async subtreep visible-only body-only ext-plist) + "Export current buffer as a Beamer presentation (tex). + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return output file's name." + (interactive) + (let ((file (org-export-output-file-name ".tex" subtreep))) + (org-export-to-file 'beamer file + async subtreep visible-only body-only ext-plist))) + +;;;###autoload +(defun org-beamer-export-to-pdf + (&optional async subtreep visible-only body-only ext-plist) + "Export current buffer as a Beamer presentation (PDF). + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\\begin{document}\" and \"\\end{document}\". + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return PDF file's name." + (interactive) + (let ((file (org-export-output-file-name ".tex" subtreep))) + (org-export-to-file 'beamer file + async subtreep visible-only body-only ext-plist + (lambda (file) (org-latex-compile file))))) + +;;;###autoload +(defun org-beamer-select-environment () + "Select the environment to be used by beamer for this entry. +While this uses (for convenience) a tag selection interface, the +result of this command will be that the BEAMER_env *property* of +the entry is set. + +In addition to this, the command will also set a tag as a visual +aid, but the tag does not have any semantic meaning." + (interactive) + ;; Make sure `org-beamer-environments-special' has a higher + ;; priority than `org-beamer-environments-extra'. + (let* ((envs (append org-beamer-environments-special + org-beamer-environments-extra + org-beamer-environments-default)) + (org-current-tag-alist + (append '((:startgroup)) + (mapcar (lambda (e) (cons (concat "B_" (car e)) + (string-to-char (nth 1 e)))) + envs) + '((:endgroup)) + '(("BMCOL" . ?|)))) + (org-tag-persistent-alist nil) + (org-use-fast-tag-selection t) + (org-fast-tag-selection-single-key t)) + (org-set-tags) + (let ((tags (or (ignore-errors (org-get-tags-string)) ""))) + (cond + ;; For a column, automatically ask for its width. + ((eq org-last-tag-selection-key ?|) + (if (string-match ":BMCOL:" tags) + (org-set-property "BEAMER_col" (read-string "Column width: ")) + (org-delete-property "BEAMER_col"))) + ;; For an "againframe" section, automatically ask for reference + ;; to resumed frame and overlay specifications. + ((eq org-last-tag-selection-key ?A) + (if (equal (org-entry-get nil "BEAMER_env") "againframe") + (progn (org-entry-delete nil "BEAMER_env") + (org-entry-delete nil "BEAMER_ref") + (org-entry-delete nil "BEAMER_act")) + (org-entry-put nil "BEAMER_env" "againframe") + (org-set-property + "BEAMER_ref" + (read-string "Frame reference (*Title, #custom-id, id:...): ")) + (org-set-property "BEAMER_act" + (read-string "Overlay specification: ")))) + ((string-match (concat ":B_\\(" (mapconcat 'car envs "\\|") "\\):") tags) + (org-entry-put nil "BEAMER_env" (match-string 1 tags))) + (t (org-entry-delete nil "BEAMER_env")))))) + +;;;###autoload +(defun org-beamer-publish-to-latex (plist filename pub-dir) + "Publish an Org file to a Beamer presentation (LaTeX). + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name." + (org-publish-org-to 'beamer filename ".tex" plist pub-dir)) + +;;;###autoload +(defun org-beamer-publish-to-pdf (plist filename pub-dir) + "Publish an Org file to a Beamer presentation (PDF, via LaTeX). + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name." + ;; Unlike to `org-beamer-publish-to-latex', PDF file is generated in + ;; working directory and then moved to publishing directory. + (org-publish-attachment + plist + ;; Default directory could be anywhere when this function is + ;; called. We ensure it is set to source file directory during + ;; compilation so as to not break links to external documents. + (let ((default-directory (file-name-directory filename))) + (org-latex-compile + (org-publish-org-to + 'beamer filename ".tex" plist (file-name-directory filename)))) + pub-dir)) + + +(provide 'ox-beamer) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; ox-beamer.el ends here diff --git a/elpa/org-9.1.14/ox-html.el b/elpa/org-9.1.14/ox-html.el new file mode 100644 index 00000000..ec80e83b --- /dev/null +++ b/elpa/org-9.1.14/ox-html.el @@ -0,0 +1,3775 @@ +;;; ox-html.el --- HTML Back-End for Org Export Engine -*- lexical-binding: t; -*- + +;; Copyright (C) 2011-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik <carsten at orgmode dot org> +;; Jambunathan K <kjambunathan at gmail dot com> +;; Keywords: outlines, hypermedia, calendar, wp + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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: + +;; This library implements a HTML back-end for Org generic exporter. +;; See Org manual for more information. + +;;; Code: + +;;; Dependencies + +(require 'cl-lib) +(require 'format-spec) +(require 'ox) +(require 'ox-publish) +(require 'table) + + +;;; Function Declarations + +(declare-function org-id-find-id-file "org-id" (id)) +(declare-function htmlize-region "ext:htmlize" (beg end)) +(declare-function mm-url-decode-entities "mm-url" ()) + +(defvar htmlize-css-name-prefix) +(defvar htmlize-output-type) +(defvar htmlize-output-type) +(defvar htmlize-css-name-prefix) + +;;; Define Back-End + +(org-export-define-backend 'html + '((bold . org-html-bold) + (center-block . org-html-center-block) + (clock . org-html-clock) + (code . org-html-code) + (drawer . org-html-drawer) + (dynamic-block . org-html-dynamic-block) + (entity . org-html-entity) + (example-block . org-html-example-block) + (export-block . org-html-export-block) + (export-snippet . org-html-export-snippet) + (fixed-width . org-html-fixed-width) + (footnote-definition . org-html-footnote-definition) + (footnote-reference . org-html-footnote-reference) + (headline . org-html-headline) + (horizontal-rule . org-html-horizontal-rule) + (inline-src-block . org-html-inline-src-block) + (inlinetask . org-html-inlinetask) + (inner-template . org-html-inner-template) + (italic . org-html-italic) + (item . org-html-item) + (keyword . org-html-keyword) + (latex-environment . org-html-latex-environment) + (latex-fragment . org-html-latex-fragment) + (line-break . org-html-line-break) + (link . org-html-link) + (node-property . org-html-node-property) + (paragraph . org-html-paragraph) + (plain-list . org-html-plain-list) + (plain-text . org-html-plain-text) + (planning . org-html-planning) + (property-drawer . org-html-property-drawer) + (quote-block . org-html-quote-block) + (radio-target . org-html-radio-target) + (section . org-html-section) + (special-block . org-html-special-block) + (src-block . org-html-src-block) + (statistics-cookie . org-html-statistics-cookie) + (strike-through . org-html-strike-through) + (subscript . org-html-subscript) + (superscript . org-html-superscript) + (table . org-html-table) + (table-cell . org-html-table-cell) + (table-row . org-html-table-row) + (target . org-html-target) + (template . org-html-template) + (timestamp . org-html-timestamp) + (underline . org-html-underline) + (verbatim . org-html-verbatim) + (verse-block . org-html-verse-block)) + :filters-alist '((:filter-options . org-html-infojs-install-script) + (:filter-parse-tree . org-html-image-link-filter) + (:filter-final-output . org-html-final-function)) + :menu-entry + '(?h "Export to HTML" + ((?H "As HTML buffer" org-html-export-as-html) + (?h "As HTML file" org-html-export-to-html) + (?o "As HTML file and open" + (lambda (a s v b) + (if a (org-html-export-to-html t s v b) + (org-open-file (org-html-export-to-html nil s v b))))))) + :options-alist + '((:html-doctype "HTML_DOCTYPE" nil org-html-doctype) + (:html-container "HTML_CONTAINER" nil org-html-container-element) + (:description "DESCRIPTION" nil nil newline) + (:keywords "KEYWORDS" nil nil space) + (:html-html5-fancy nil "html5-fancy" org-html-html5-fancy) + (:html-link-use-abs-url nil "html-link-use-abs-url" org-html-link-use-abs-url) + (:html-link-home "HTML_LINK_HOME" nil org-html-link-home) + (:html-link-up "HTML_LINK_UP" nil org-html-link-up) + (:html-mathjax "HTML_MATHJAX" nil "" space) + (:html-postamble nil "html-postamble" org-html-postamble) + (:html-preamble nil "html-preamble" org-html-preamble) + (:html-head "HTML_HEAD" nil org-html-head newline) + (:html-head-extra "HTML_HEAD_EXTRA" nil org-html-head-extra newline) + (:subtitle "SUBTITLE" nil nil parse) + (:html-head-include-default-style + nil "html-style" org-html-head-include-default-style) + (:html-head-include-scripts nil "html-scripts" org-html-head-include-scripts) + (:html-allow-name-attribute-in-anchors + nil nil org-html-allow-name-attribute-in-anchors) + (:html-divs nil nil org-html-divs) + (:html-checkbox-type nil nil org-html-checkbox-type) + (:html-extension nil nil org-html-extension) + (:html-footnote-format nil nil org-html-footnote-format) + (:html-footnote-separator nil nil org-html-footnote-separator) + (:html-footnotes-section nil nil org-html-footnotes-section) + (:html-format-drawer-function nil nil org-html-format-drawer-function) + (:html-format-headline-function nil nil org-html-format-headline-function) + (:html-format-inlinetask-function + nil nil org-html-format-inlinetask-function) + (:html-home/up-format nil nil org-html-home/up-format) + (:html-indent nil nil org-html-indent) + (:html-infojs-options nil nil org-html-infojs-options) + (:html-infojs-template nil nil org-html-infojs-template) + (:html-inline-image-rules nil nil org-html-inline-image-rules) + (:html-link-org-files-as-html nil nil org-html-link-org-files-as-html) + (:html-mathjax-options nil nil org-html-mathjax-options) + (:html-mathjax-template nil nil org-html-mathjax-template) + (:html-metadata-timestamp-format nil nil org-html-metadata-timestamp-format) + (:html-postamble-format nil nil org-html-postamble-format) + (:html-preamble-format nil nil org-html-preamble-format) + (:html-table-align-individual-fields + nil nil org-html-table-align-individual-fields) + (:html-table-caption-above nil nil org-html-table-caption-above) + (:html-table-data-tags nil nil org-html-table-data-tags) + (:html-table-header-tags nil nil org-html-table-header-tags) + (:html-table-use-header-tags-for-first-column + nil nil org-html-table-use-header-tags-for-first-column) + (:html-tag-class-prefix nil nil org-html-tag-class-prefix) + (:html-text-markup-alist nil nil org-html-text-markup-alist) + (:html-todo-kwd-class-prefix nil nil org-html-todo-kwd-class-prefix) + (:html-toplevel-hlevel nil nil org-html-toplevel-hlevel) + (:html-use-infojs nil nil org-html-use-infojs) + (:html-validation-link nil nil org-html-validation-link) + (:html-viewport nil nil org-html-viewport) + (:html-inline-images nil nil org-html-inline-images) + (:html-table-attributes nil nil org-html-table-default-attributes) + (:html-table-row-open-tag nil nil org-html-table-row-open-tag) + (:html-table-row-close-tag nil nil org-html-table-row-close-tag) + (:html-xml-declaration nil nil org-html-xml-declaration) + (:html-klipsify-src nil nil org-html-klipsify-src) + (:html-klipse-css nil nil org-html-klipse-css) + (:html-klipse-js nil nil org-html-klipse-js) + (:html-klipse-selection-script nil nil org-html-klipse-selection-script) + (:infojs-opt "INFOJS_OPT" nil nil) + ;; Redefine regular options. + (:creator "CREATOR" nil org-html-creator-string) + (:with-latex nil "tex" org-html-with-latex) + ;; Retrieve LaTeX header for fragments. + (:latex-header "LATEX_HEADER" nil nil newline))) + + +;;; Internal Variables + +(defvar org-html-format-table-no-css) +(defvar htmlize-buffer-places) ; from htmlize.el + +(defvar org-html--pre/postamble-class "status" + "CSS class used for pre/postamble") + +(defconst org-html-doctype-alist + '(("html4-strict" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" +\"http://www.w3.org/TR/html4/strict.dtd\">") + ("html4-transitional" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" +\"http://www.w3.org/TR/html4/loose.dtd\">") + ("html4-frameset" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" +\"http://www.w3.org/TR/html4/frameset.dtd\">") + + ("xhtml-strict" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" +\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">") + ("xhtml-transitional" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" +\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">") + ("xhtml-frameset" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" +\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">") + ("xhtml-11" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" +\"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd\">") + + ("html5" . "<!DOCTYPE html>") + ("xhtml5" . "<!DOCTYPE html>")) + "An alist mapping (x)html flavors to specific doctypes.") + +(defconst org-html-html5-elements + '("article" "aside" "audio" "canvas" "details" "figcaption" + "figure" "footer" "header" "menu" "meter" "nav" "output" + "progress" "section" "video") + "New elements in html5. + +For blocks that should contain headlines, use the HTML_CONTAINER +property on the headline itself.") + +(defconst org-html-special-string-regexps + '(("\\\\-" . "­") ; shy + ("---\\([^-]\\)" . "—\\1") ; mdash + ("--\\([^-]\\)" . "–\\1") ; ndash + ("\\.\\.\\." . "…")) ; hellip + "Regular expressions for special string conversion.") + +(defconst org-html-scripts + "<script type=\"text/javascript\"> +/* +@licstart The following is the entire license notice for the +JavaScript code in this tag. + +Copyright (C) 2012-2018 Free Software Foundation, Inc. + +The JavaScript code in this tag is free software: you can +redistribute it and/or modify it under the terms of the GNU +General Public License (GNU GPL) as published by the Free Software +Foundation, either version 3 of the License, or (at your option) +any later version. The code is distributed WITHOUT ANY WARRANTY; +without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU GPL for more details. + +As additional permission under GNU GPL version 3 section 7, you +may distribute non-source (e.g., minimized or compacted) forms of +that code without the copy of the GNU GPL normally required by +section 4, provided you include this license notice and a URL +through which recipients can access the Corresponding Source. + + +@licend The above is the entire license notice +for the JavaScript code in this tag. +*/ +<!--/*--><![CDATA[/*><!--*/ + function CodeHighlightOn(elem, id) + { + var target = document.getElementById(id); + if(null != target) { + elem.cacheClassElem = elem.className; + elem.cacheClassTarget = target.className; + target.className = \"code-highlighted\"; + elem.className = \"code-highlighted\"; + } + } + function CodeHighlightOff(elem, id) + { + var target = document.getElementById(id); + if(elem.cacheClassElem) + elem.className = elem.cacheClassElem; + if(elem.cacheClassTarget) + target.className = elem.cacheClassTarget; + } +/*]]>*///--> +</script>" + "Basic JavaScript that is needed by HTML files produced by Org mode.") + +(defconst org-html-style-default + "<style type=\"text/css\"> + <!--/*--><![CDATA[/*><!--*/ + .title { text-align: center; + margin-bottom: .2em; } + .subtitle { text-align: center; + font-size: medium; + font-weight: bold; + margin-top:0; } + .todo { font-family: monospace; color: red; } + .done { font-family: monospace; color: green; } + .priority { font-family: monospace; color: orange; } + .tag { background-color: #eee; font-family: monospace; + padding: 2px; font-size: 80%; font-weight: normal; } + .timestamp { color: #bebebe; } + .timestamp-kwd { color: #5f9ea0; } + .org-right { margin-left: auto; margin-right: 0px; text-align: right; } + .org-left { margin-left: 0px; margin-right: auto; text-align: left; } + .org-center { margin-left: auto; margin-right: auto; text-align: center; } + .underline { text-decoration: underline; } + #postamble p, #preamble p { font-size: 90%; margin: .2em; } + p.verse { margin-left: 3%; } + pre { + border: 1px solid #ccc; + box-shadow: 3px 3px 3px #eee; + padding: 8pt; + font-family: monospace; + overflow: auto; + margin: 1.2em; + } + pre.src { + position: relative; + overflow: visible; + padding-top: 1.2em; + } + pre.src:before { + display: none; + position: absolute; + background-color: white; + top: -10px; + right: 10px; + padding: 3px; + border: 1px solid black; + } + pre.src:hover:before { display: inline;} + /* Languages per Org manual */ + pre.src-asymptote:before { content: 'Asymptote'; } + pre.src-awk:before { content: 'Awk'; } + pre.src-C:before { content: 'C'; } + /* pre.src-C++ doesn't work in CSS */ + pre.src-clojure:before { content: 'Clojure'; } + pre.src-css:before { content: 'CSS'; } + pre.src-D:before { content: 'D'; } + pre.src-ditaa:before { content: 'ditaa'; } + pre.src-dot:before { content: 'Graphviz'; } + pre.src-calc:before { content: 'Emacs Calc'; } + pre.src-emacs-lisp:before { content: 'Emacs Lisp'; } + pre.src-fortran:before { content: 'Fortran'; } + pre.src-gnuplot:before { content: 'gnuplot'; } + pre.src-haskell:before { content: 'Haskell'; } + pre.src-hledger:before { content: 'hledger'; } + pre.src-java:before { content: 'Java'; } + pre.src-js:before { content: 'Javascript'; } + pre.src-latex:before { content: 'LaTeX'; } + pre.src-ledger:before { content: 'Ledger'; } + pre.src-lisp:before { content: 'Lisp'; } + pre.src-lilypond:before { content: 'Lilypond'; } + pre.src-lua:before { content: 'Lua'; } + pre.src-matlab:before { content: 'MATLAB'; } + pre.src-mscgen:before { content: 'Mscgen'; } + pre.src-ocaml:before { content: 'Objective Caml'; } + pre.src-octave:before { content: 'Octave'; } + pre.src-org:before { content: 'Org mode'; } + pre.src-oz:before { content: 'OZ'; } + pre.src-plantuml:before { content: 'Plantuml'; } + pre.src-processing:before { content: 'Processing.js'; } + pre.src-python:before { content: 'Python'; } + pre.src-R:before { content: 'R'; } + pre.src-ruby:before { content: 'Ruby'; } + pre.src-sass:before { content: 'Sass'; } + pre.src-scheme:before { content: 'Scheme'; } + pre.src-screen:before { content: 'Gnu Screen'; } + pre.src-sed:before { content: 'Sed'; } + pre.src-sh:before { content: 'shell'; } + pre.src-sql:before { content: 'SQL'; } + pre.src-sqlite:before { content: 'SQLite'; } + /* additional languages in org.el's org-babel-load-languages alist */ + pre.src-forth:before { content: 'Forth'; } + pre.src-io:before { content: 'IO'; } + pre.src-J:before { content: 'J'; } + pre.src-makefile:before { content: 'Makefile'; } + pre.src-maxima:before { content: 'Maxima'; } + pre.src-perl:before { content: 'Perl'; } + pre.src-picolisp:before { content: 'Pico Lisp'; } + pre.src-scala:before { content: 'Scala'; } + pre.src-shell:before { content: 'Shell Script'; } + pre.src-ebnf2ps:before { content: 'ebfn2ps'; } + /* additional language identifiers per \"defun org-babel-execute\" + in ob-*.el */ + pre.src-cpp:before { content: 'C++'; } + pre.src-abc:before { content: 'ABC'; } + pre.src-coq:before { content: 'Coq'; } + pre.src-groovy:before { content: 'Groovy'; } + /* additional language identifiers from org-babel-shell-names in + ob-shell.el: ob-shell is the only babel language using a lambda to put + the execution function name together. */ + pre.src-bash:before { content: 'bash'; } + pre.src-csh:before { content: 'csh'; } + pre.src-ash:before { content: 'ash'; } + pre.src-dash:before { content: 'dash'; } + pre.src-ksh:before { content: 'ksh'; } + pre.src-mksh:before { content: 'mksh'; } + pre.src-posh:before { content: 'posh'; } + /* Additional Emacs modes also supported by the LaTeX listings package */ + pre.src-ada:before { content: 'Ada'; } + pre.src-asm:before { content: 'Assembler'; } + pre.src-caml:before { content: 'Caml'; } + pre.src-delphi:before { content: 'Delphi'; } + pre.src-html:before { content: 'HTML'; } + pre.src-idl:before { content: 'IDL'; } + pre.src-mercury:before { content: 'Mercury'; } + pre.src-metapost:before { content: 'MetaPost'; } + pre.src-modula-2:before { content: 'Modula-2'; } + pre.src-pascal:before { content: 'Pascal'; } + pre.src-ps:before { content: 'PostScript'; } + pre.src-prolog:before { content: 'Prolog'; } + pre.src-simula:before { content: 'Simula'; } + pre.src-tcl:before { content: 'tcl'; } + pre.src-tex:before { content: 'TeX'; } + pre.src-plain-tex:before { content: 'Plain TeX'; } + pre.src-verilog:before { content: 'Verilog'; } + pre.src-vhdl:before { content: 'VHDL'; } + pre.src-xml:before { content: 'XML'; } + pre.src-nxml:before { content: 'XML'; } + /* add a generic configuration mode; LaTeX export needs an additional + (add-to-list 'org-latex-listings-langs '(conf \" \")) in .emacs */ + pre.src-conf:before { content: 'Configuration File'; } + + table { border-collapse:collapse; } + caption.t-above { caption-side: top; } + caption.t-bottom { caption-side: bottom; } + td, th { vertical-align:top; } + th.org-right { text-align: center; } + th.org-left { text-align: center; } + th.org-center { text-align: center; } + td.org-right { text-align: right; } + td.org-left { text-align: left; } + td.org-center { text-align: center; } + dt { font-weight: bold; } + .footpara { display: inline; } + .footdef { margin-bottom: 1em; } + .figure { padding: 1em; } + .figure p { text-align: center; } + .inlinetask { + padding: 10px; + border: 2px solid gray; + margin: 10px; + background: #ffffcc; + } + #org-div-home-and-up + { text-align: right; font-size: 70%; white-space: nowrap; } + textarea { overflow-x: auto; } + .linenr { font-size: smaller } + .code-highlighted { background-color: #ffff00; } + .org-info-js_info-navigation { border-style: none; } + #org-info-js_console-label + { font-size: 10px; font-weight: bold; white-space: nowrap; } + .org-info-js_search-highlight + { background-color: #ffff00; color: #000000; font-weight: bold; } + .org-svg { width: 90%; } + /*]]>*/--> +</style>" + "The default style specification for exported HTML files. +You can use `org-html-head' and `org-html-head-extra' to add to +this style. If you don't want to include this default style, +customize `org-html-head-include-default-style'.") + + +;;; User Configuration Variables + +(defgroup org-export-html nil + "Options for exporting Org mode files to HTML." + :tag "Org Export HTML" + :group 'org-export) + +;;;; Handle infojs + +(defvar org-html-infojs-opts-table + '((path PATH "https://orgmode.org/org-info.js") + (view VIEW "info") + (toc TOC :with-toc) + (ftoc FIXED_TOC "0") + (tdepth TOC_DEPTH "max") + (sdepth SECTION_DEPTH "max") + (mouse MOUSE_HINT "underline") + (buttons VIEW_BUTTONS "0") + (ltoc LOCAL_TOC "1") + (up LINK_UP :html-link-up) + (home LINK_HOME :html-link-home)) + "JavaScript options, long form for script, default values.") + +(defcustom org-html-use-infojs 'when-configured + "Non-nil when Sebastian Rose's Java Script org-info.js should be active. +This option can be nil or t to never or always use the script. +It can also be the symbol `when-configured', meaning that the +script will be linked into the export file if and only if there +is a \"#+INFOJS_OPT:\" line in the buffer. See also the variable +`org-html-infojs-options'." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "Never" nil) + (const :tag "When configured in buffer" when-configured) + (const :tag "Always" t))) + +(defcustom org-html-infojs-options + (mapcar (lambda (x) (cons (car x) (nth 2 x))) org-html-infojs-opts-table) + "Options settings for the INFOJS JavaScript. +Each of the options must have an entry in `org-html-infojs-opts-table'. +The value can either be a string that will be passed to the script, or +a property. This property is then assumed to be a property that is defined +by the Export/Publishing setup of Org. +The `sdepth' and `tdepth' parameters can also be set to \"max\", which +means to use the maximum value consistent with other options." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type + `(set :greedy t :inline t + ,@(mapcar + (lambda (x) + (list 'cons (list 'const (car x)) + '(choice + (symbol :tag "Publishing/Export property") + (string :tag "Value")))) + org-html-infojs-opts-table))) + +(defcustom org-html-infojs-template + "<script type=\"text/javascript\" src=\"%SCRIPT_PATH\"> +/** + * + * @source: %SCRIPT_PATH + * + * @licstart The following is the entire license notice for the + * JavaScript code in %SCRIPT_PATH. + * + * Copyright (C) 2012-2018 Free Software Foundation, Inc. + * + * + * The JavaScript code in this tag is free software: you can + * redistribute it and/or modify it under the terms of the GNU + * General Public License (GNU GPL) as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) + * any later version. The code is distributed WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details. + * + * As additional permission under GNU GPL version 3 section 7, you + * may distribute non-source (e.g., minimized or compacted) forms of + * that code without the copy of the GNU GPL normally required by + * section 4, provided you include this license notice and a URL + * through which recipients can access the Corresponding Source. + * + * @licend The above is the entire license notice + * for the JavaScript code in %SCRIPT_PATH. + * + */ +</script> + +<script type=\"text/javascript\"> + +/* +@licstart The following is the entire license notice for the +JavaScript code in this tag. + +Copyright (C) 2012-2018 Free Software Foundation, Inc. + +The JavaScript code in this tag is free software: you can +redistribute it and/or modify it under the terms of the GNU +General Public License (GNU GPL) as published by the Free Software +Foundation, either version 3 of the License, or (at your option) +any later version. The code is distributed WITHOUT ANY WARRANTY; +without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU GPL for more details. + +As additional permission under GNU GPL version 3 section 7, you +may distribute non-source (e.g., minimized or compacted) forms of +that code without the copy of the GNU GPL normally required by +section 4, provided you include this license notice and a URL +through which recipients can access the Corresponding Source. + + +@licend The above is the entire license notice +for the JavaScript code in this tag. +*/ + +<!--/*--><![CDATA[/*><!--*/ +%MANAGER_OPTIONS +org_html_manager.setup(); // activate after the parameters are set +/*]]>*///--> +</script>" + "The template for the export style additions when org-info.js is used. +Option settings will replace the %MANAGER-OPTIONS cookie." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defun org-html-infojs-install-script (exp-plist _backend) + "Install script in export options when appropriate. +EXP-PLIST is a plist containing export options. BACKEND is the +export back-end currently used." + (unless (or (memq 'body-only (plist-get exp-plist :export-options)) + (not (plist-get exp-plist :html-use-infojs)) + (and (eq (plist-get exp-plist :html-use-infojs) 'when-configured) + (let ((opt (plist-get exp-plist :infojs-opt))) + (or (not opt) + (string= "" opt) + (string-match "\\<view:nil\\>" opt))))) + (let* ((template (plist-get exp-plist :html-infojs-template)) + (ptoc (plist-get exp-plist :with-toc)) + (hlevels (plist-get exp-plist :headline-levels)) + (sdepth hlevels) + (tdepth (if (integerp ptoc) (min ptoc hlevels) hlevels)) + (options (plist-get exp-plist :infojs-opt)) + (infojs-opt (plist-get exp-plist :html-infojs-options)) + (table org-html-infojs-opts-table) + style) + (dolist (entry table) + (let* ((opt (car entry)) + (var (nth 1 entry)) + ;; Compute default values for script option OPT from + ;; `org-html-infojs-options' variable. + (default + (let ((default (cdr (assq opt infojs-opt)))) + (if (and (symbolp default) (not (memq default '(t nil)))) + (plist-get exp-plist default) + default))) + ;; Value set through INFOJS_OPT keyword has precedence + ;; over the default one. + (val (if (and options + (string-match (format "\\<%s:\\(\\S-+\\)" opt) + options)) + (match-string 1 options) + default))) + (pcase opt + (`path (setq template + (replace-regexp-in-string + "%SCRIPT_PATH" val template t t))) + (`sdepth (when (integerp (read val)) + (setq sdepth (min (read val) sdepth)))) + (`tdepth (when (integerp (read val)) + (setq tdepth (min (read val) tdepth)))) + (_ (setq val + (cond + ((or (eq val t) (equal val "t")) "1") + ((or (eq val nil) (equal val "nil")) "0") + ((stringp val) val) + (t (format "%s" val)))) + (push (cons var val) style))))) + ;; Now we set the depth of the *generated* TOC to SDEPTH, + ;; because the toc will actually determine the splitting. How + ;; much of the toc will actually be displayed is governed by the + ;; TDEPTH option. + (setq exp-plist (plist-put exp-plist :with-toc sdepth)) + ;; The table of contents should not show more sections than we + ;; generate. + (setq tdepth (min tdepth sdepth)) + (push (cons "TOC_DEPTH" tdepth) style) + ;; Build style string. + (setq style (mapconcat + (lambda (x) + (format "org_html_manager.set(\"%s\", \"%s\");" + (car x) (cdr x))) + style "\n")) + (when (and style (> (length style) 0)) + (and (string-match "%MANAGER_OPTIONS" template) + (setq style (replace-match style t t template)) + (setq exp-plist + (plist-put + exp-plist :html-head-extra + (concat (or (plist-get exp-plist :html-head-extra) "") + "\n" + style))))) + ;; This script absolutely needs the table of contents, so we + ;; change that setting. + (unless (plist-get exp-plist :with-toc) + (setq exp-plist (plist-put exp-plist :with-toc t))) + ;; Return the modified property list. + exp-plist))) + +;;;; Bold, etc. + +(defcustom org-html-text-markup-alist + '((bold . "<b>%s</b>") + (code . "<code>%s</code>") + (italic . "<i>%s</i>") + (strike-through . "<del>%s</del>") + (underline . "<span class=\"underline\">%s</span>") + (verbatim . "<code>%s</code>")) + "Alist of HTML expressions to convert text markup. + +The key must be a symbol among `bold', `code', `italic', +`strike-through', `underline' and `verbatim'. The value is +a formatting string to wrap fontified text with. + +If no association can be found for a given markup, text will be +returned as-is." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type '(alist :key-type (symbol :tag "Markup type") + :value-type (string :tag "Format string")) + :options '(bold code italic strike-through underline verbatim)) + +(defcustom org-html-indent nil + "Non-nil means to indent the generated HTML. +Warning: non-nil may break indentation of source code blocks." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +;;;; Drawers + +(defcustom org-html-format-drawer-function (lambda (_name contents) contents) + "Function called to format a drawer in HTML code. + +The function must accept two parameters: + NAME the drawer name, like \"LOGBOOK\" + CONTENTS the contents of the drawer. + +The function should return the string to be exported. + +For example, the variable could be set to the following function +in order to mimic default behavior: + +The default value simply returns the value of CONTENTS." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'function) + +;;;; Footnotes + +(defcustom org-html-footnotes-section "<div id=\"footnotes\"> +<h2 class=\"footnotes\">%s: </h2> +<div id=\"text-footnotes\"> +%s +</div> +</div>" + "Format for the footnotes section. +Should contain a two instances of %s. The first will be replaced with the +language-specific word for \"Footnotes\", the second one will be replaced +by the footnotes themselves." + :group 'org-export-html + :type 'string) + +(defcustom org-html-footnote-format "<sup>%s</sup>" + "The format for the footnote reference. +%s will be replaced by the footnote reference itself." + :group 'org-export-html + :type 'string) + +(defcustom org-html-footnote-separator "<sup>, </sup>" + "Text used to separate footnotes." + :group 'org-export-html + :type 'string) + +;;;; Headline + +(defcustom org-html-toplevel-hlevel 2 + "The <H> level for level 1 headings in HTML export. +This is also important for the classes that will be wrapped around headlines +and outline structure. If this variable is 1, the top-level headlines will +be <h1>, and the corresponding classes will be outline-1, section-number-1, +and outline-text-1. If this is 2, all of these will get a 2 instead. +The default for this variable is 2, because we use <h1> for formatting the +document title." + :group 'org-export-html + :type 'integer) + +(defcustom org-html-format-headline-function + 'org-html-format-headline-default-function + "Function to format headline text. + +This function will be called with six arguments: +TODO the todo keyword (string or nil). +TODO-TYPE the type of todo (symbol: `todo', `done', nil) +PRIORITY the priority of the headline (integer or nil) +TEXT the main headline text (string). +TAGS the tags (string or nil). +INFO the export options (plist). + +The function result will be used in the section format string." + :group 'org-export-html + :version "26.1" + :package-version '(Org . "8.3") + :type 'function) + +;;;; HTML-specific + +(defcustom org-html-allow-name-attribute-in-anchors nil + "When nil, do not set \"name\" attribute in anchors. +By default, when appropriate, anchors are formatted with \"id\" +but without \"name\" attribute." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +;;;; Inlinetasks + +(defcustom org-html-format-inlinetask-function + 'org-html-format-inlinetask-default-function + "Function called to format an inlinetask in HTML code. + +The function must accept seven parameters: + TODO the todo keyword, as a string + TODO-TYPE the todo type, a symbol among `todo', `done' and nil. + PRIORITY the inlinetask priority, as a string + NAME the inlinetask name, as a string. + TAGS the inlinetask tags, as a list of strings. + CONTENTS the contents of the inlinetask, as a string. + INFO the export options, as a plist + +The function should return the string to be exported." + :group 'org-export-html + :version "26.1" + :package-version '(Org . "8.3") + :type 'function) + +;;;; LaTeX + +(defcustom org-html-with-latex org-export-with-latex + "Non-nil means process LaTeX math snippets. + +When set, the exporter will process LaTeX environments and +fragments. + +This option can also be set with the +OPTIONS line, +e.g. \"tex:mathjax\". Allowed values are: + + nil Ignore math snippets. + `verbatim' Keep everything in verbatim + `mathjax', t Do MathJax preprocessing and arrange for MathJax.js to + be loaded. + SYMBOL Any symbol defined in `org-preview-latex-process-alist', + e.g., `dvipng'." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "Do not process math in any way" nil) + (const :tag "Leave math verbatim" verbatim) + (const :tag "Use MathJax to display math" mathjax) + (symbol :tag "Convert to image to display math" :value dvipng))) + +;;;; Links :: Generic + +(defcustom org-html-link-org-files-as-html t + "Non-nil means make file links to `file.org' point to `file.html'. +When `org-mode' is exporting an `org-mode' file to HTML, links to +non-html files are directly put into a href tag in HTML. +However, links to other Org files (recognized by the extension +\".org\") should become links to the corresponding HTML +file, assuming that the linked `org-mode' file will also be +converted to HTML. +When nil, the links still point to the plain \".org\" file." + :group 'org-export-html + :type 'boolean) + +;;;; Links :: Inline images + +(defcustom org-html-inline-images t + "Non-nil means inline images into exported HTML pages. +This is done using an <img> tag. When nil, an anchor with href is used to +link to the image." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.1") + :type 'boolean) + +(defcustom org-html-inline-image-rules + '(("file" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\|svg\\)\\'") + ("http" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\|svg\\)\\'") + ("https" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\|svg\\)\\'")) + "Rules characterizing image files that can be inlined into HTML. +A rule consists in an association whose key is the type of link +to consider, and value is a regexp that will be matched against +link's path." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type '(alist :key-type (string :tag "Type") + :value-type (regexp :tag "Path"))) + +;;;; Plain Text + +(defvar org-html-protect-char-alist + '(("&" . "&") + ("<" . "<") + (">" . ">")) + "Alist of characters to be converted by `org-html-encode-plain-text'.") + +;;;; Src Block + +(defcustom org-html-htmlize-output-type 'inline-css + "Output type to be used by htmlize when formatting code snippets. +Choices are `css' to export the CSS selectors only,`inline-css' +to export the CSS attribute values inline in the HTML or `nil' to +export plain text. We use as default `inline-css', in order to +make the resulting HTML self-containing. + +However, this will fail when using Emacs in batch mode for export, because +then no rich font definitions are in place. It will also not be good if +people with different Emacs setup contribute HTML files to a website, +because the fonts will represent the individual setups. In these cases, +it is much better to let Org/Htmlize assign classes only, and to use +a style file to define the look of these classes. +To get a start for your css file, start Emacs session and make sure that +all the faces you are interested in are defined, for example by loading files +in all modes you want. Then, use the command +`\\[org-html-htmlize-generate-css]' to extract class definitions." + :group 'org-export-html + :type '(choice (const css) (const inline-css) (const nil))) + +(defcustom org-html-htmlize-font-prefix "org-" + "The prefix for CSS class names for htmlize font specifications." + :group 'org-export-html + :type 'string) + +;;;; Table + +(defcustom org-html-table-default-attributes + '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups" :frame "hsides") + "Default attributes and values which will be used in table tags. +This is a plist where attributes are symbols, starting with +colons, and values are strings. + +When exporting to HTML5, these values will be disregarded." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type '(plist :key-type (symbol :tag "Property") + :value-type (string :tag "Value"))) + +(defcustom org-html-table-header-tags '("<th scope=\"%s\"%s>" . "</th>") + "The opening and ending tags for table header fields. +This is customizable so that alignment options can be specified. +The first %s will be filled with the scope of the field, either row or col. +The second %s will be replaced by a style entry to align the field. +See also the variable `org-html-table-use-header-tags-for-first-column'. +See also the variable `org-html-table-align-individual-fields'." + :group 'org-export-html + :type '(cons (string :tag "Opening tag") (string :tag "Closing tag"))) + +(defcustom org-html-table-data-tags '("<td%s>" . "</td>") + "The opening and ending tags for table data fields. +This is customizable so that alignment options can be specified. +The first %s will be filled with the scope of the field, either row or col. +The second %s will be replaced by a style entry to align the field. +See also the variable `org-html-table-align-individual-fields'." + :group 'org-export-html + :type '(cons (string :tag "Opening tag") (string :tag "Closing tag"))) + +(defcustom org-html-table-row-open-tag "<tr>" + "The opening tag for table rows. +This is customizable so that alignment options can be specified. +Instead of strings, these can be a Lisp function that will be +evaluated for each row in order to construct the table row tags. + +The function will be called with these arguments: + + `number': row number (0 is the first row) + `group-number': group number of current row + `start-group?': non-nil means the row starts a group + `end-group?': non-nil means the row ends a group + `top?': non-nil means this is the top row + `bottom?': non-nil means this is the bottom row + +For example: + + (setq org-html-table-row-open-tag + (lambda (number group-number start-group? end-group-p top? bottom?) + (cond (top? \"<tr class=\\\"tr-top\\\">\") + (bottom? \"<tr class=\\\"tr-bottom\\\">\") + (t (if (= (mod number 2) 1) + \"<tr class=\\\"tr-odd\\\">\" + \"<tr class=\\\"tr-even\\\">\"))))) + +will use the \"tr-top\" and \"tr-bottom\" classes for the top row +and the bottom row, and otherwise alternate between \"tr-odd\" and +\"tr-even\" for odd and even rows." + :group 'org-export-html + :type '(choice :tag "Opening tag" + (string :tag "Specify") + (function))) + +(defcustom org-html-table-row-close-tag "</tr>" + "The closing tag for table rows. +This is customizable so that alignment options can be specified. +Instead of strings, this can be a Lisp function that will be +evaluated for each row in order to construct the table row tags. + +See documentation of `org-html-table-row-open-tag'." + :group 'org-export-html + :type '(choice :tag "Closing tag" + (string :tag "Specify") + (function))) + +(defcustom org-html-table-align-individual-fields t + "Non-nil means attach style attributes for alignment to each table field. +When nil, alignment will only be specified in the column tags, but this +is ignored by some browsers (like Firefox, Safari). Opera does it right +though." + :group 'org-export-html + :type 'boolean) + +(defcustom org-html-table-use-header-tags-for-first-column nil + "Non-nil means format column one in tables with header tags. +When nil, also column one will use data tags." + :group 'org-export-html + :type 'boolean) + +(defcustom org-html-table-caption-above t + "When non-nil, place caption string at the beginning of the table. +Otherwise, place it near the end." + :group 'org-export-html + :type 'boolean) + +;;;; Tags + +(defcustom org-html-tag-class-prefix "" + "Prefix to class names for TODO keywords. +Each tag gets a class given by the tag itself, with this prefix. +The default prefix is empty because it is nice to just use the keyword +as a class name. But if you get into conflicts with other, existing +CSS classes, then this prefix can be very useful." + :group 'org-export-html + :type 'string) + +;;;; Template :: Generic + +(defcustom org-html-extension "html" + "The extension for exported HTML files." + :group 'org-export-html + :type 'string) + +(defcustom org-html-xml-declaration + '(("html" . "<?xml version=\"1.0\" encoding=\"%s\"?>") + ("php" . "<?php echo \"<?xml version=\\\"1.0\\\" encoding=\\\"%s\\\" ?>\"; ?>")) + "The extension for exported HTML files. +%s will be replaced with the charset of the exported file. +This may be a string, or an alist with export extensions +and corresponding declarations. + +This declaration only applies when exporting to XHTML." + :group 'org-export-html + :type '(choice + (string :tag "Single declaration") + (repeat :tag "Dependent on extension" + (cons (string :tag "Extension") + (string :tag "Declaration"))))) + +(defcustom org-html-coding-system 'utf-8 + "Coding system for HTML export. +Use utf-8 as the default value." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'coding-system) + +(defcustom org-html-doctype "xhtml-strict" + "Document type definition to use for exported HTML files. +Can be set with the in-buffer HTML_DOCTYPE property or for +publishing, with :html-doctype." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type (append + '(choice) + (mapcar (lambda (x) `(const ,(car x))) org-html-doctype-alist) + '((string :tag "Custom doctype" )))) + +(defcustom org-html-html5-fancy nil + "Non-nil means using new HTML5 elements. +This variable is ignored for anything other than HTML5 export. + +For compatibility with Internet Explorer, it's probably a good +idea to download some form of the html5shiv (for instance +https://code.google.com/p/html5shiv/) and add it to your +HTML_HEAD_EXTRA, so that your pages don't break for users of IE +versions 8 and below." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +(defcustom org-html-container-element "div" + "HTML element to use for wrapping top level sections. +Can be set with the in-buffer HTML_CONTAINER property or for +publishing, with :html-container. + +Note that changing the default will prevent you from using +org-info.js for your website." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-html-divs + '((preamble "div" "preamble") + (content "div" "content") + (postamble "div" "postamble")) + "Alist of the three section elements for HTML export. +The car of each entry is one of `preamble', `content' or `postamble'. +The cdrs of each entry are the ELEMENT_TYPE and ID for each +section of the exported document. + +Note that changing the default will prevent you from using +org-info.js for your website." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type '(list :greedy t + (list :tag "Preamble" + (const :format "" preamble) + (string :tag "element") (string :tag " id")) + (list :tag "Content" + (const :format "" content) + (string :tag "element") (string :tag " id")) + (list :tag "Postamble" (const :format "" postamble) + (string :tag " id") (string :tag "element")))) + +(defconst org-html-checkbox-types + '((unicode . + ((on . "☑") (off . "☐") (trans . "☐"))) + (ascii . + ((on . "<code>[X]</code>") + (off . "<code>[ ]</code>") + (trans . "<code>[-]</code>"))) + (html . + ((on . "<input type='checkbox' checked='checked' />") + (off . "<input type='checkbox' />") + (trans . "<input type='checkbox' />")))) + "Alist of checkbox types. +The cdr of each entry is an alist list three checkbox types for +HTML export: `on', `off' and `trans'. + +The choices are: + `unicode' Unicode characters (HTML entities) + `ascii' ASCII characters + `html' HTML checkboxes + +Note that only the ascii characters implement tri-state +checkboxes. The other two use the `off' checkbox for `trans'.") + +(defcustom org-html-checkbox-type 'ascii + "The type of checkboxes to use for HTML export. +See `org-html-checkbox-types' for for the values used for each +option." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (const :tag "ASCII characters" ascii) + (const :tag "Unicode characters" unicode) + (const :tag "HTML checkboxes" html))) + +(defcustom org-html-metadata-timestamp-format "%Y-%m-%d %a %H:%M" + "Format used for timestamps in preamble, postamble and metadata. +See `format-time-string' for more information on its components." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +;;;; Template :: Mathjax + +(defcustom org-html-mathjax-options + '((path "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML" ) + (scale "100") + (align "center") + (font "TeX") + (linebreaks "false") + (autonumber "AMS") + (indent "0em") + (multlinewidth "85%") + (tagindent ".8em") + (tagside "right")) + "Options for MathJax setup. + +Alist of the following elements. All values are strings. + +path The path to MathJax. +scale Scaling with HTML-CSS, MathML and SVG output engines. +align How to align display math: left, center, or right. +font The font to use with HTML-CSS and SVG output. As of MathJax 2.5 + the following values are understood: \"TeX\", \"STIX-Web\", + \"Asana-Math\", \"Neo-Euler\", \"Gyre-Pagella\", + \"Gyre-Termes\", and \"Latin-Modern\". +linebreaks Let MathJax perform automatic linebreaks. Valid values + are \"true\" and \"false\". +indent If align is not center, how far from the left/right side? + Valid values are \"left\" and \"right\" +multlinewidth The width of the multline environment. +autonumber How to number equations. Valid values are \"None\", + \"all\" and \"AMS Math\". +tagindent The amount tags are indented. +tagside Which side to show tags/labels on. Valid values are + \"left\" and \"right\" + +You can also customize this for each buffer, using something like + +#+HTML_MATHJAX: align: left indent: 5em tagside: left font: Neo-Euler + +For further information about MathJax options, see the MathJax documentation: + + http://docs.mathjax.org/" + :group 'org-export-html + :package-version '(Org . "8.3") + :type '(list :greedy t + (list :tag "path (the path from where to load MathJax.js)" + (const :format " " path) (string)) + (list :tag "scale (scaling for the displayed math)" + (const :format " " scale) (string)) + (list :tag "align (alignment of displayed equations)" + (const :format " " align) (string)) + (list :tag "font (used to display math)" + (const :format " " font) + (choice (const "TeX") + (const "STIX-Web") + (const "Asana-Math") + (const "Neo-Euler") + (const "Gyre-Pagella") + (const "Gyre-Termes") + (const "Latin-Modern"))) + (list :tag "linebreaks (automatic line-breaking)" + (const :format " " linebreaks) + (choice (const "true") + (const "false"))) + (list :tag "autonumber (when should equations be numbered)" + (const :format " " autonumber) + (choice (const "AMS") + (const "None") + (const "All"))) + (list :tag "indent (indentation with left or right alignment)" + (const :format " " indent) (string)) + (list :tag "multlinewidth (width to use for the multline environment)" + (const :format " " multlinewidth) (string)) + (list :tag "tagindent (the indentation of tags from left or right)" + (const :format " " tagindent) (string)) + (list :tag "tagside (location of tags)" + (const :format " " tagside) + (choice (const "left") + (const "right"))))) + +(defcustom org-html-mathjax-template + "<script type=\"text/x-mathjax-config\"> + MathJax.Hub.Config({ + displayAlign: \"%ALIGN\", + displayIndent: \"%INDENT\", + + \"HTML-CSS\": { scale: %SCALE, + linebreaks: { automatic: \"%LINEBREAKS\" }, + webFont: \"%FONT\" + }, + SVG: {scale: %SCALE, + linebreaks: { automatic: \"%LINEBREAKS\" }, + font: \"%FONT\"}, + NativeMML: {scale: %SCALE}, + TeX: { equationNumbers: {autoNumber: \"%AUTONUMBER\"}, + MultLineWidth: \"%MULTLINEWIDTH\", + TagSide: \"%TAGSIDE\", + TagIndent: \"%TAGINDENT\" + } +}); +</script> +<script type=\"text/javascript\" + src=\"%PATH\"></script>" + "The MathJax template. See also `org-html-mathjax-options'." + :group 'org-export-html + :type 'string) + +;;;; Template :: Postamble + +(defcustom org-html-postamble 'auto + "Non-nil means insert a postamble in HTML export. + +When set to `auto', check against the +`org-export-with-author/email/creator/date' variables to set the +content of the postamble. When set to a string, use this string +as the postamble. When t, insert a string as defined by the +formatting string in `org-html-postamble-format'. + +When set to a function, apply this function and insert the +returned string. The function takes the property list of export +options as its only argument. + +Setting :html-postamble in publishing projects will take +precedence over this variable." + :group 'org-export-html + :type '(choice (const :tag "No postamble" nil) + (const :tag "Auto postamble" auto) + (const :tag "Default formatting string" t) + (string :tag "Custom formatting string") + (function :tag "Function (must return a string)"))) + +(defcustom org-html-postamble-format + '(("en" "<p class=\"author\">Author: %a (%e)</p> +<p class=\"date\">Date: %d</p> +<p class=\"creator\">%c</p> +<p class=\"validation\">%v</p>")) + "Alist of languages and format strings for the HTML postamble. + +The first element of each list is the language code, as used for +the LANGUAGE keyword. See `org-export-default-language'. + +The second element of each list is a format string to format the +postamble itself. This format string can contain these elements: + + %t stands for the title. + %s stands for the subtitle. + %a stands for the author's name. + %e stands for the author's email. + %d stands for the date. + %c will be replaced by `org-html-creator-string'. + %v will be replaced by `org-html-validation-link'. + %T will be replaced by the export time. + %C will be replaced by the last modification time. + +If you need to use a \"%\" character, you need to escape it +like that: \"%%\"." + :group 'org-export-html + :type '(repeat + (list (string :tag "Language") + (string :tag "Format string")))) + +(defcustom org-html-validation-link + "<a href=\"http://validator.w3.org/check?uri=referer\">Validate</a>" + "Link to HTML validation service." + :group 'org-export-html + :type 'string) + +(defcustom org-html-creator-string + (format "<a href=\"https://www.gnu.org/software/emacs/\">Emacs</a> %s (<a href=\"https://orgmode.org\">Org</a> mode %s)" + emacs-version + (if (fboundp 'org-version) (org-version) "unknown version")) + "Information about the creator of the HTML document. +This option can also be set on with the CREATOR keyword." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type '(string :tag "Creator string")) + +;;;; Template :: Preamble + +(defcustom org-html-preamble t + "Non-nil means insert a preamble in HTML export. + +When t, insert a string as defined by the formatting string in +`org-html-preamble-format'. When set to a string, use this +formatting string instead (see `org-html-postamble-format' for an +example of such a formatting string). + +When set to a function, apply this function and insert the +returned string. The function takes the property list of export +options as its only argument. + +Setting :html-preamble in publishing projects will take +precedence over this variable." + :group 'org-export-html + :type '(choice (const :tag "No preamble" nil) + (const :tag "Default preamble" t) + (string :tag "Custom formatting string") + (function :tag "Function (must return a string)"))) + +(defcustom org-html-preamble-format '(("en" "")) + "Alist of languages and format strings for the HTML preamble. + +The first element of each list is the language code, as used for +the LANGUAGE keyword. See `org-export-default-language'. + +The second element of each list is a format string to format the +preamble itself. This format string can contain these elements: + + %t stands for the title. + %s stands for the subtitle. + %a stands for the author's name. + %e stands for the author's email. + %d stands for the date. + %c will be replaced by `org-html-creator-string'. + %v will be replaced by `org-html-validation-link'. + %T will be replaced by the export time. + %C will be replaced by the last modification time. + +If you need to use a \"%\" character, you need to escape it +like that: \"%%\". + +See the default value of `org-html-postamble-format' for an +example." + :group 'org-export-html + :type '(repeat + (list (string :tag "Language") + (string :tag "Format string")))) + +(defcustom org-html-link-up "" + "Where should the \"UP\" link of exported HTML pages lead?" + :group 'org-export-html + :type '(string :tag "File or URL")) + +(defcustom org-html-link-home "" + "Where should the \"HOME\" link of exported HTML pages lead?" + :group 'org-export-html + :type '(string :tag "File or URL")) + +(defcustom org-html-link-use-abs-url nil + "Should we prepend relative links with HTML_LINK_HOME?" + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.1") + :type 'boolean) + +(defcustom org-html-home/up-format + "<div id=\"org-div-home-and-up\"> + <a accesskey=\"h\" href=\"%s\"> UP </a> + | + <a accesskey=\"H\" href=\"%s\"> HOME </a> +</div>" + "Snippet used to insert the HOME and UP links. +This is a format string, the first %s will receive the UP link, +the second the HOME link. If both `org-html-link-up' and +`org-html-link-home' are empty, the entire snippet will be +ignored." + :group 'org-export-html + :type 'string) + +;;;; Template :: Scripts + +(defcustom org-html-head-include-scripts t + "Non-nil means include the JavaScript snippets in exported HTML files. +The actual script is defined in `org-html-scripts' and should +not be modified." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) + +;;;; Template :: Styles + +(defcustom org-html-head-include-default-style t + "Non-nil means include the default style in exported HTML files. +The actual style is defined in `org-html-style-default' and +should not be modified. Use `org-html-head' to use your own +style information." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean) +;;;###autoload +(put 'org-html-head-include-default-style 'safe-local-variable 'booleanp) + +(defcustom org-html-head "" + "Org-wide head definitions for exported HTML files. + +This variable can contain the full HTML structure to provide a +style, including the surrounding HTML tags. You can consider +including definitions for the following classes: title, todo, +done, timestamp, timestamp-kwd, tag, target. + +For example, a valid value would be: + + <style type=\"text/css\"> + /*<![CDATA[*/ + p { font-weight: normal; color: gray; } + h1 { color: black; } + .title { text-align: center; } + .todo, .timestamp-kwd { color: red; } + .done { color: green; } + /*]]>*/ + </style> + +If you want to refer to an external style, use something like + + <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\" /> + +As the value of this option simply gets inserted into the HTML +<head> header, you can use it to add any arbitrary text to the +header. + +You can set this on a per-file basis using #+HTML_HEAD:, +or for publication projects using the :html-head property." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) +;;;###autoload +(put 'org-html-head 'safe-local-variable 'stringp) + +(defcustom org-html-head-extra "" + "More head information to add in the HTML output. + +You can set this on a per-file basis using #+HTML_HEAD_EXTRA:, +or for publication projects using the :html-head-extra property." + :group 'org-export-html + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) +;;;###autoload +(put 'org-html-head-extra 'safe-local-variable 'stringp) + +;;;; Template :: Viewport + +(defcustom org-html-viewport '((width "device-width") + (initial-scale "1") + (minimum-scale "") + (maximum-scale "") + (user-scalable "")) + "Viewport options for mobile-optimized sites. + +The following values are recognized + +width Size of the viewport. +initial-scale Zoom level when the page is first loaded. +minimum-scale Minimum allowed zoom level. +maximum-scale Maximum allowed zoom level. +user-scalable Whether zoom can be changed. + +The viewport meta tag is inserted if this variable is non-nil. + +See the following site for a reference: +https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag" + :group 'org-export-html + :version "26.1" + :package-version '(Org . "8.3") + :type '(choice (const :tag "Disable" nil) + (list :tag "Enable" + (list :tag "Width of viewport" + (const :format " " width) + (choice (const :tag "unset" "") + (string))) + (list :tag "Initial scale" + (const :format " " initial-scale) + (choice (const :tag "unset" "") + (string))) + (list :tag "Minimum scale/zoom" + (const :format " " minimum-scale) + (choice (const :tag "unset" "") + (string))) + (list :tag "Maximum scale/zoom" + (const :format " " maximum-scale) + (choice (const :tag "unset" "") + (string))) + (list :tag "User scalable/zoomable" + (const :format " " user-scalable) + (choice (const :tag "unset" "") + (const "true") + (const "false")))))) + +;; Handle source code blocks with Klipse + +(defcustom org-html-klipsify-src nil + "When non-nil, source code blocks are editable in exported presentation." + :group 'org-export-html + :package-version '(Org . "9.1") + :type 'boolean) + +(defcustom org-html-klipse-css + "https://storage.googleapis.com/app.klipse.tech/css/codemirror.css" + "Location of the codemirror CSS file for use with klipse." + :group 'org-export-html + :package-version '(Org . "9.1") + :type 'string) + +(defcustom org-html-klipse-js + "https://storage.googleapis.com/app.klipse.tech/plugin_prod/js/klipse_plugin.min.js" + "Location of the klipse javascript file." + :group 'org-export-html + :type 'string) + +(defcustom org-html-klipse-selection-script + "window.klipse_settings = {selector_eval_html: '.src-html', + selector_eval_js: '.src-js', + selector_eval_python_client: '.src-python', + selector_eval_scheme: '.src-scheme', + selector: '.src-clojure', + selector_eval_ruby: '.src-ruby'};" + "Javascript snippet to activate klipse." + :group 'org-export-html + :package-version '(Org . "9.1") + :type 'string) + + +;;;; Todos + +(defcustom org-html-todo-kwd-class-prefix "" + "Prefix to class names for TODO keywords. +Each TODO keyword gets a class given by the keyword itself, with this prefix. +The default prefix is empty because it is nice to just use the keyword +as a class name. But if you get into conflicts with other, existing +CSS classes, then this prefix can be very useful." + :group 'org-export-html + :type 'string) + + +;;; Internal Functions + +(defun org-html-xhtml-p (info) + (let ((dt (downcase (plist-get info :html-doctype)))) + (string-match-p "xhtml" dt))) + +(defun org-html-html5-p (info) + (let ((dt (downcase (plist-get info :html-doctype)))) + (member dt '("html5" "xhtml5" "<!doctype html>")))) + +(defun org-html--html5-fancy-p (info) + "Non-nil when exporting to HTML5 with fancy elements. +INFO is the current state of the export process, as a plist." + (and (plist-get info :html-html5-fancy) + (org-html-html5-p info))) + +(defun org-html-close-tag (tag attr info) + "Return close-tag for string TAG. +ATTR specifies additional attributes. INFO is a property list +containing current export state." + (concat "<" tag + (org-string-nw-p (concat " " attr)) + (if (org-html-xhtml-p info) " />" ">"))) + +(defun org-html-doctype (info) + "Return correct HTML doctype tag. +INFO is a plist used as a communication channel. Doctype tag is +extracted from `org-html-doctype-alist', or the literal value +of :html-doctype from INFO if :html-doctype is not found in the +alist." + (let ((dt (plist-get info :html-doctype))) + (or (cdr (assoc dt org-html-doctype-alist)) dt))) + +(defun org-html--make-attribute-string (attributes) + "Return a list of attributes, as a string. +ATTRIBUTES is a plist where values are either strings or nil. An +attribute with a nil value will be omitted from the result." + (let (output) + (dolist (item attributes (mapconcat 'identity (nreverse output) " ")) + (cond ((null item) (pop output)) + ((symbolp item) (push (substring (symbol-name item) 1) output)) + (t (let ((key (car output)) + (value (replace-regexp-in-string + "\"" """ (org-html-encode-plain-text item)))) + (setcar output (format "%s=\"%s\"" key value)))))))) + +(defun org-html--wrap-image (contents info &optional caption label) + "Wrap CONTENTS string within an appropriate environment for images. +INFO is a plist used as a communication channel. When optional +arguments CAPTION and LABEL are given, use them for caption and +\"id\" attribute." + (let ((html5-fancy (org-html--html5-fancy-p info))) + (format (if html5-fancy "\n<figure%s>\n%s%s\n</figure>" + "\n<div%s class=\"figure\">\n%s%s\n</div>") + ;; ID. + (if (org-string-nw-p label) (format " id=\"%s\"" label) "") + ;; Contents. + (if html5-fancy contents (format "<p>%s</p>" contents)) + ;; Caption. + (if (not (org-string-nw-p caption)) "" + (format (if html5-fancy "\n<figcaption>%s</figcaption>" + "\n<p>%s</p>") + caption))))) + +(defun org-html--format-image (source attributes info) + "Return \"img\" tag with given SOURCE and ATTRIBUTES. +SOURCE is a string specifying the location of the image. +ATTRIBUTES is a plist, as returned by +`org-export-read-attribute'. INFO is a plist used as +a communication channel." + (if (string= "svg" (file-name-extension source)) + (org-html--svg-image source attributes info) + (org-html-close-tag + "img" + (org-html--make-attribute-string + (org-combine-plists + (list :src source + :alt (if (string-match-p "^ltxpng/" source) + (org-html-encode-plain-text + (org-find-text-property-in-string 'org-latex-src source)) + (file-name-nondirectory source))) + attributes)) + info))) + +(defun org-html--svg-image (source attributes info) + "Return \"object\" embedding svg file SOURCE with given ATTRIBUTES. +INFO is a plist used as a communication channel. + +The special attribute \"fallback\" can be used to specify a +fallback image file to use if the object embedding is not +supported. CSS class \"org-svg\" is assigned as the class of the +object unless a different class is specified with an attribute." + (let ((fallback (plist-get attributes :fallback)) + (attrs (org-html--make-attribute-string + (org-combine-plists + ;; Remove fallback attribute, which is not meant to + ;; appear directly in the attributes string, and + ;; provide a default class if none is set. + '(:class "org-svg") attributes '(:fallback nil))))) + (format "<object type=\"image/svg+xml\" data=\"%s\" %s>\n%s</object>" + source + attrs + (if fallback + (org-html-close-tag + "img" (format "src=\"%s\" %s" fallback attrs) info) + "Sorry, your browser does not support SVG.")))) + +(defun org-html--textarea-block (element) + "Transcode ELEMENT into a textarea block. +ELEMENT is either a src block or an example block." + (let* ((code (car (org-export-unravel-code element))) + (attr (org-export-read-attribute :attr_html element))) + (format "<p>\n<textarea cols=\"%s\" rows=\"%s\">\n%s</textarea>\n</p>" + (or (plist-get attr :width) 80) + (or (plist-get attr :height) (org-count-lines code)) + code))) + +(defun org-html--has-caption-p (element &optional _info) + "Non-nil when ELEMENT has a caption affiliated keyword. +INFO is a plist used as a communication channel. This function +is meant to be used as a predicate for `org-export-get-ordinal' or +a value to `org-html-standalone-image-predicate'." + (org-element-property :caption element)) + +;;;; Table + +(defun org-html-htmlize-region-for-paste (beg end) + "Convert the region between BEG and END to HTML, using htmlize.el. +This is much like `htmlize-region-for-paste', only that it uses +the settings define in the org-... variables." + (let* ((htmlize-output-type org-html-htmlize-output-type) + (htmlize-css-name-prefix org-html-htmlize-font-prefix) + (htmlbuf (htmlize-region beg end))) + (unwind-protect + (with-current-buffer htmlbuf + (buffer-substring (plist-get htmlize-buffer-places 'content-start) + (plist-get htmlize-buffer-places 'content-end))) + (kill-buffer htmlbuf)))) + +;;;###autoload +(defun org-html-htmlize-generate-css () + "Create the CSS for all font definitions in the current Emacs session. +Use this to create face definitions in your CSS style file that can then +be used by code snippets transformed by htmlize. +This command just produces a buffer that contains class definitions for all +faces used in the current Emacs session. You can copy and paste the ones you +need into your CSS file. + +If you then set `org-html-htmlize-output-type' to `css', calls +to the function `org-html-htmlize-region-for-paste' will +produce code that uses these same face definitions." + (interactive) + (or (require 'htmlize nil t) + (error "Please install htmlize from https://github.com/hniksic/emacs-htmlize")) + (and (get-buffer "*html*") (kill-buffer "*html*")) + (with-temp-buffer + (let ((fl (face-list)) + (htmlize-css-name-prefix "org-") + (htmlize-output-type 'css) + f i) + (while (setq f (pop fl) + i (and f (face-attribute f :inherit))) + (when (and (symbolp f) (or (not i) (not (listp i)))) + (insert (org-add-props (copy-sequence "1") nil 'face f)))) + (htmlize-region (point-min) (point-max)))) + (pop-to-buffer-same-window "*html*") + (goto-char (point-min)) + (if (re-search-forward "<style" nil t) + (delete-region (point-min) (match-beginning 0))) + (if (re-search-forward "</style>" nil t) + (delete-region (1+ (match-end 0)) (point-max))) + (beginning-of-line 1) + (if (looking-at " +") (replace-match "")) + (goto-char (point-min))) + +(defun org-html--make-string (n string) + "Build a string by concatenating N times STRING." + (let (out) (dotimes (_ n out) (setq out (concat string out))))) + +(defun org-html-fix-class-name (kwd) ; audit callers of this function + "Turn todo keyword KWD into a valid class name. +Replaces invalid characters with \"_\"." + (replace-regexp-in-string "[^a-zA-Z0-9_]" "_" kwd nil t)) + +(defun org-html-footnote-section (info) + "Format the footnote section. +INFO is a plist used as a communication channel." + (let* ((fn-alist (org-export-collect-footnote-definitions info)) + (fn-alist + (cl-loop for (n _type raw) in fn-alist collect + (cons n (if (eq (org-element-type raw) 'org-data) + (org-trim (org-export-data raw info)) + (format "<div class=\"footpara\">%s</div>" + (org-trim (org-export-data raw info)))))))) + (when fn-alist + (format + (plist-get info :html-footnotes-section) + (org-html--translate "Footnotes" info) + (format + "\n%s\n" + (mapconcat + (lambda (fn) + (let ((n (car fn)) (def (cdr fn))) + (format + "<div class=\"footdef\">%s %s</div>\n" + (format + (plist-get info :html-footnote-format) + (org-html--anchor + (format "fn.%d" n) + n + (format " class=\"footnum\" href=\"#fnr.%d\"" n) + info)) + def))) + fn-alist + "\n")))))) + + +;;; Template + +(defun org-html--build-meta-info (info) + "Return meta tags for exported document. +INFO is a plist used as a communication channel." + (let* ((protect-string + (lambda (str) + (replace-regexp-in-string + "\"" """ (org-html-encode-plain-text str)))) + (title (org-export-data (plist-get info :title) info)) + ;; Set title to an invisible character instead of leaving it + ;; empty, which is invalid. + (title (if (org-string-nw-p title) title "‎")) + (author (and (plist-get info :with-author) + (let ((auth (plist-get info :author))) + (and auth + ;; Return raw Org syntax, skipping non + ;; exportable objects. + (org-element-interpret-data + (org-element-map auth + (cons 'plain-text org-element-all-objects) + 'identity info)))))) + (description (plist-get info :description)) + (keywords (plist-get info :keywords)) + (charset (or (and org-html-coding-system + (fboundp 'coding-system-get) + (coding-system-get org-html-coding-system + 'mime-charset)) + "iso-8859-1"))) + (concat + (when (plist-get info :time-stamp-file) + (format-time-string + (concat "<!-- " + (plist-get info :html-metadata-timestamp-format) + " -->\n"))) + (format + (if (org-html-html5-p info) + (org-html-close-tag "meta" "charset=\"%s\"" info) + (org-html-close-tag + "meta" "http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"" + info)) + charset) "\n" + (let ((viewport-options + (cl-remove-if-not (lambda (cell) (org-string-nw-p (cadr cell))) + (plist-get info :html-viewport)))) + (and viewport-options + (concat + (org-html-close-tag + "meta" + (format "name=\"viewport\" content=\"%s\"" + (mapconcat + (lambda (elm) (format "%s=%s" (car elm) (cadr elm))) + viewport-options ", ")) + info) + "\n"))) + (format "<title>%s\n" title) + (org-html-close-tag "meta" "name=\"generator\" content=\"Org mode\"" info) + "\n" + (and (org-string-nw-p author) + (concat + (org-html-close-tag "meta" + (format "name=\"author\" content=\"%s\"" + (funcall protect-string author)) + info) + "\n")) + (and (org-string-nw-p description) + (concat + (org-html-close-tag "meta" + (format "name=\"description\" content=\"%s\"\n" + (funcall protect-string description)) + info) + "\n")) + (and (org-string-nw-p keywords) + (concat + (org-html-close-tag "meta" + (format "name=\"keywords\" content=\"%s\"" + (funcall protect-string keywords)) + info) + "\n"))))) + +(defun org-html--build-head (info) + "Return information for the .. of the HTML output. +INFO is a plist used as a communication channel." + (org-element-normalize-string + (concat + (when (plist-get info :html-head-include-default-style) + (org-element-normalize-string org-html-style-default)) + (org-element-normalize-string (plist-get info :html-head)) + (org-element-normalize-string (plist-get info :html-head-extra)) + (when (and (plist-get info :html-htmlized-css-url) + (eq org-html-htmlize-output-type 'css)) + (org-html-close-tag "link" + (format "rel=\"stylesheet\" href=\"%s\" type=\"text/css\"" + (plist-get info :html-htmlized-css-url)) + info)) + (when (plist-get info :html-head-include-scripts) org-html-scripts)))) + +(defun org-html--build-mathjax-config (info) + "Insert the user setup into the mathjax template. +INFO is a plist used as a communication channel." + (when (and (memq (plist-get info :with-latex) '(mathjax t)) + (org-element-map (plist-get info :parse-tree) + '(latex-fragment latex-environment) #'identity info t nil t)) + (let ((template (plist-get info :html-mathjax-template)) + (options (plist-get info :html-mathjax-options)) + (in-buffer (or (plist-get info :html-mathjax) ""))) + (dolist (e options (org-element-normalize-string template)) + (let ((name (car e)) + (val (nth 1 e))) + (when (string-match (concat "\\<" (symbol-name name) ":") in-buffer) + (setq val + (car (read-from-string (substring in-buffer (match-end 0)))))) + (unless (stringp val) (setq val (format "%s" val))) + (while (string-match (concat "%" (upcase (symbol-name name))) + template) + (setq template (replace-match val t t template)))))))) + +(defun org-html-format-spec (info) + "Return format specification for preamble and postamble. +INFO is a plist used as a communication channel." + (let ((timestamp-format (plist-get info :html-metadata-timestamp-format))) + `((?t . ,(org-export-data (plist-get info :title) info)) + (?s . ,(org-export-data (plist-get info :subtitle) info)) + (?d . ,(org-export-data (org-export-get-date info timestamp-format) + info)) + (?T . ,(format-time-string timestamp-format)) + (?a . ,(org-export-data (plist-get info :author) info)) + (?e . ,(mapconcat + (lambda (e) (format "%s" e e)) + (split-string (plist-get info :email) ",+ *") + ", ")) + (?c . ,(plist-get info :creator)) + (?C . ,(let ((file (plist-get info :input-file))) + (format-time-string timestamp-format + (and file (nth 5 (file-attributes file)))))) + (?v . ,(or (plist-get info :html-validation-link) ""))))) + +(defun org-html--build-pre/postamble (type info) + "Return document preamble or postamble as a string, or nil. +TYPE is either `preamble' or `postamble', INFO is a plist used as a +communication channel." + (let ((section (plist-get info (intern (format ":html-%s" type)))) + (spec (org-html-format-spec info))) + (when section + (let ((section-contents + (if (functionp section) (funcall section info) + (cond + ((stringp section) (format-spec section spec)) + ((eq section 'auto) + (let ((date (cdr (assq ?d spec))) + (author (cdr (assq ?a spec))) + (email (cdr (assq ?e spec))) + (creator (cdr (assq ?c spec))) + (validation-link (cdr (assq ?v spec)))) + (concat + (when (and (plist-get info :with-date) + (org-string-nw-p date)) + (format "

%s: %s

\n" + (org-html--translate "Date" info) + date)) + (when (and (plist-get info :with-author) + (org-string-nw-p author)) + (format "

%s: %s

\n" + (org-html--translate "Author" info) + author)) + (when (and (plist-get info :with-email) + (org-string-nw-p email)) + (format "

%s: %s

\n" + (org-html--translate "Email" info) + email)) + (when (plist-get info :time-stamp-file) + (format + "

%s: %s

\n" + (org-html--translate "Created" info) + (format-time-string + (plist-get info :html-metadata-timestamp-format)))) + (when (plist-get info :with-creator) + (format "

%s

\n" creator)) + (format "

%s

\n" + validation-link)))) + (t + (let ((formats (plist-get info (if (eq type 'preamble) + :html-preamble-format + :html-postamble-format))) + (language (plist-get info :language))) + (format-spec + (cadr (or (assoc-string language formats t) + (assoc-string "en" formats t))) + spec))))))) + (let ((div (assq type (plist-get info :html-divs)))) + (when (org-string-nw-p section-contents) + (concat + (format "<%s id=\"%s\" class=\"%s\">\n" + (nth 1 div) + (nth 2 div) + org-html--pre/postamble-class) + (org-element-normalize-string section-contents) + (format "\n" (nth 1 div))))))))) + +(defun org-html-inner-template (contents info) + "Return body of document string after HTML conversion. +CONTENTS is the transcoded contents string. INFO is a plist +holding export options." + (concat + ;; Table of contents. + (let ((depth (plist-get info :with-toc))) + (when depth (org-html-toc depth info))) + ;; Document contents. + contents + ;; Footnotes section. + (org-html-footnote-section info))) + +(defun org-html-template (contents info) + "Return complete document string after HTML conversion. +CONTENTS is the transcoded contents string. INFO is a plist +holding export options." + (concat + (when (and (not (org-html-html5-p info)) (org-html-xhtml-p info)) + (let* ((xml-declaration (plist-get info :html-xml-declaration)) + (decl (or (and (stringp xml-declaration) xml-declaration) + (cdr (assoc (plist-get info :html-extension) + xml-declaration)) + (cdr (assoc "html" xml-declaration)) + ""))) + (when (not (or (not decl) (string= "" decl))) + (format "%s\n" + (format decl + (or (and org-html-coding-system + (fboundp 'coding-system-get) + (coding-system-get org-html-coding-system 'mime-charset)) + "iso-8859-1")))))) + (org-html-doctype info) + "\n" + (concat "\n") + "\n" + (org-html--build-meta-info info) + (org-html--build-head info) + (org-html--build-mathjax-config info) + "\n" + "\n" + (let ((link-up (org-trim (plist-get info :html-link-up))) + (link-home (org-trim (plist-get info :html-link-home)))) + (unless (and (string= link-up "") (string= link-home "")) + (format (plist-get info :html-home/up-format) + (or link-up link-home) + (or link-home link-up)))) + ;; Preamble. + (org-html--build-pre/postamble 'preamble info) + ;; Document contents. + (let ((div (assq 'content (plist-get info :html-divs)))) + (format "<%s id=\"%s\">\n" (nth 1 div) (nth 2 div))) + ;; Document title. + (when (plist-get info :with-title) + (let ((title (and (plist-get info :with-title) + (plist-get info :title))) + (subtitle (plist-get info :subtitle)) + (html5-fancy (org-html--html5-fancy-p info))) + (when title + (format + (if html5-fancy + "
\n

%s

\n%s
" + "

%s%s

\n") + (org-export-data title info) + (if subtitle + (format + (if html5-fancy + "

%s

\n" + (concat "\n" (org-html-close-tag "br" nil info) "\n" + "%s\n")) + (org-export-data subtitle info)) + ""))))) + contents + (format "\n" (nth 1 (assq 'content (plist-get info :html-divs)))) + ;; Postamble. + (org-html--build-pre/postamble 'postamble info) + ;; Possibly use the Klipse library live code blocks. + (if (plist-get info :html-klipsify-src) + (concat "")) + ;; Closing document. + "\n")) + +(defun org-html--translate (s info) + "Translate string S according to specified language. +INFO is a plist used as a communication channel." + (org-export-translate s :html info)) + +;;;; Anchor + +(defun org-html--anchor (id desc attributes info) + "Format a HTML anchor." + (let* ((name (and (plist-get info :html-allow-name-attribute-in-anchors) id)) + (attributes (concat (and id (format " id=\"%s\"" id)) + (and name (format " name=\"%s\"" name)) + attributes))) + (format "%s" attributes (or desc "")))) + +;;;; Todo + +(defun org-html--todo (todo info) + "Format TODO keywords into HTML." + (when todo + (format "%s" + (if (member todo org-done-keywords) "done" "todo") + (or (plist-get info :html-todo-kwd-class-prefix) "") + (org-html-fix-class-name todo) + todo))) + +;;;; Priority + +(defun org-html--priority (priority _info) + "Format a priority into HTML. +PRIORITY is the character code of the priority or nil. INFO is +a plist containing export options." + (and priority (format "[%c]" priority))) + +;;;; Tags + +(defun org-html--tags (tags info) + "Format TAGS into HTML. +INFO is a plist containing export options." + (when tags + (format "%s" + (mapconcat + (lambda (tag) + (format "%s" + (concat (plist-get info :html-tag-class-prefix) + (org-html-fix-class-name tag)) + tag)) + tags " ")))) + +;;;; Src Code + +(defun org-html-fontify-code (code lang) + "Color CODE with htmlize library. +CODE is a string representing the source code to colorize. LANG +is the language used for CODE, as a string, or nil." + (when code + (cond + ;; No language. Possibly an example block. + ((not lang) (org-html-encode-plain-text code)) + ;; Plain text explicitly set. + ((not org-html-htmlize-output-type) (org-html-encode-plain-text code)) + ;; No htmlize library or an inferior version of htmlize. + ((not (and (or (require 'htmlize nil t) + (error "Please install htmlize from \ +https://github.com/hniksic/emacs-htmlize")) + (fboundp 'htmlize-region-for-paste))) + ;; Emit a warning. + (message "Cannot fontify src block (htmlize.el >= 1.34 required)") + (org-html-encode-plain-text code)) + (t + ;; Map language + (setq lang (or (assoc-default lang org-src-lang-modes) lang)) + (let* ((lang-mode (and lang (intern (format "%s-mode" lang))))) + (cond + ;; Case 1: Language is not associated with any Emacs mode + ((not (functionp lang-mode)) + (org-html-encode-plain-text code)) + ;; Case 2: Default. Fontify code. + (t + ;; htmlize + (setq code + (let ((output-type org-html-htmlize-output-type) + (font-prefix org-html-htmlize-font-prefix)) + (with-temp-buffer + ;; Switch to language-specific mode. + (funcall lang-mode) + (insert code) + ;; Fontify buffer. + (org-font-lock-ensure) + ;; Remove formatting on newline characters. + (save-excursion + (let ((beg (point-min)) + (end (point-max))) + (goto-char beg) + (while (progn (end-of-line) (< (point) end)) + (put-text-property (point) (1+ (point)) 'face nil) + (forward-char 1)))) + (org-src-mode) + (set-buffer-modified-p nil) + ;; Htmlize region. + (let ((org-html-htmlize-output-type output-type) + (org-html-htmlize-font-prefix font-prefix)) + (org-html-htmlize-region-for-paste + (point-min) (point-max)))))) + ;; Strip any enclosing
 tags.
+	  (let* ((beg (and (string-match "\\`]*>\n?" code) (match-end 0)))
+		 (end (and beg (string-match "\\'" code))))
+	    (if (and beg end) (substring code beg end) code)))))))))
+
+(defun org-html-do-format-code
+  (code &optional lang refs retain-labels num-start)
+  "Format CODE string as source code.
+Optional arguments LANG, REFS, RETAIN-LABELS and NUM-START are,
+respectively, the language of the source code, as a string, an
+alist between line numbers and references (as returned by
+`org-export-unravel-code'), a boolean specifying if labels should
+appear in the source code, and the number associated to the first
+line of code."
+  (let* ((code-lines (split-string code "\n"))
+	 (code-length (length code-lines))
+	 (num-fmt
+	  (and num-start
+	       (format "%%%ds: "
+		       (length (number-to-string (+ code-length num-start))))))
+	 (code (org-html-fontify-code code lang)))
+    (org-export-format-code
+     code
+     (lambda (loc line-num ref)
+       (setq loc
+	     (concat
+	      ;; Add line number, if needed.
+	      (when num-start
+		(format "%s"
+			(format num-fmt line-num)))
+	      ;; Transcoded src line.
+	      loc
+	      ;; Add label, if needed.
+	      (when (and ref retain-labels) (format " (%s)" ref))))
+       ;; Mark transcoded line as an anchor, if needed.
+       (if (not ref) loc
+	 (format "%s"
+		 ref loc)))
+     num-start refs)))
+
+(defun org-html-format-code (element info)
+  "Format contents of ELEMENT as source code.
+ELEMENT is either an example block or a src block.  INFO is
+a plist used as a communication channel."
+  (let* ((lang (org-element-property :language element))
+	 ;; Extract code and references.
+	 (code-info (org-export-unravel-code element))
+	 (code (car code-info))
+	 (refs (cdr code-info))
+	 ;; Does the src block contain labels?
+	 (retain-labels (org-element-property :retain-labels element))
+	 ;; Does it have line numbers?
+	 (num-start (org-export-get-loc element info)))
+    (org-html-do-format-code code lang refs retain-labels num-start)))
+
+
+;;; Tables of Contents
+
+(defun org-html-toc (depth info &optional scope)
+  "Build a table of contents.
+DEPTH is an integer specifying the depth of the table.  INFO is
+a plist used as a communication channel.  Optional argument SCOPE
+is an element defining the scope of the table.  Return the table
+of contents as a string, or nil if it is empty."
+  (let ((toc-entries
+	 (mapcar (lambda (headline)
+		   (cons (org-html--format-toc-headline headline info)
+			 (org-export-get-relative-level headline info)))
+		 (org-export-collect-headlines info depth scope))))
+    (when toc-entries
+      (let ((toc (concat "
" + (org-html--toc-text toc-entries) + "
\n"))) + (if scope toc + (let ((outer-tag (if (org-html--html5-fancy-p info) + "nav" + "div"))) + (concat (format "<%s id=\"table-of-contents\">\n" outer-tag) + (let ((top-level (plist-get info :html-toplevel-hlevel))) + (format "%s\n" + top-level + (org-html--translate "Table of Contents" info) + top-level)) + toc + (format "\n" outer-tag)))))))) + +(defun org-html--toc-text (toc-entries) + "Return innards of a table of contents, as a string. +TOC-ENTRIES is an alist where key is an entry title, as a string, +and value is its relative level, as an integer." + (let* ((prev-level (1- (cdar toc-entries))) + (start-level prev-level)) + (concat + (mapconcat + (lambda (entry) + (let ((headline (car entry)) + (level (cdr entry))) + (concat + (let* ((cnt (- level prev-level)) + (times (if (> cnt 0) (1- cnt) (- cnt)))) + (setq prev-level level) + (concat + (org-html--make-string + times (cond ((> cnt 0) "\n
    \n
  • ") + ((< cnt 0) "
  • \n
\n"))) + (if (> cnt 0) "\n
    \n
  • " "
  • \n
  • "))) + headline))) + toc-entries "") + (org-html--make-string (- prev-level start-level) "
  • \n
\n")))) + +(defun org-html--format-toc-headline (headline info) + "Return an appropriate table of contents entry for HEADLINE. +INFO is a plist used as a communication channel." + (let* ((headline-number (org-export-get-headline-number headline info)) + (todo (and (plist-get info :with-todo-keywords) + (let ((todo (org-element-property :todo-keyword headline))) + (and todo (org-export-data todo info))))) + (todo-type (and todo (org-element-property :todo-type headline))) + (priority (and (plist-get info :with-priority) + (org-element-property :priority headline))) + (text (org-export-data-with-backend + (org-export-get-alt-title headline info) + (org-export-toc-entry-backend 'html) + info)) + (tags (and (eq (plist-get info :with-tags) t) + (org-export-get-tags headline info)))) + (format "%s" + ;; Label. + (or (org-element-property :CUSTOM_ID headline) + (org-export-get-reference headline info)) + ;; Body. + (concat + (and (not (org-export-low-level-p headline info)) + (org-export-numbered-headline-p headline info) + (concat (mapconcat #'number-to-string headline-number ".") + ". ")) + (apply (plist-get info :html-format-headline-function) + todo todo-type priority text tags :section-number nil))))) + +(defun org-html-list-of-listings (info) + "Build a list of listings. +INFO is a plist used as a communication channel. Return the list +of listings as a string, or nil if it is empty." + (let ((lol-entries (org-export-collect-listings info))) + (when lol-entries + (concat "
\n" + (let ((top-level (plist-get info :html-toplevel-hlevel))) + (format "%s\n" + top-level + (org-html--translate "List of Listings" info) + top-level)) + "
\n
    \n" + (let ((count 0) + (initial-fmt (format "%s" + (org-html--translate "Listing %d:" info)))) + (mapconcat + (lambda (entry) + (let ((label (and (org-element-property :name entry) + (org-export-get-reference entry info))) + (title (org-trim + (org-export-data + (or (org-export-get-caption entry t) + (org-export-get-caption entry)) + info)))) + (concat + "
  • " + (if (not label) + (concat (format initial-fmt (cl-incf count)) + " " + title) + (format "%s %s" + label + (format initial-fmt (cl-incf count)) + title)) + "
  • "))) + lol-entries "\n")) + "\n
\n
\n
")))) + +(defun org-html-list-of-tables (info) + "Build a list of tables. +INFO is a plist used as a communication channel. Return the list +of tables as a string, or nil if it is empty." + (let ((lol-entries (org-export-collect-tables info))) + (when lol-entries + (concat "
\n" + (let ((top-level (plist-get info :html-toplevel-hlevel))) + (format "%s\n" + top-level + (org-html--translate "List of Tables" info) + top-level)) + "
\n
    \n" + (let ((count 0) + (initial-fmt (format "%s" + (org-html--translate "Table %d:" info)))) + (mapconcat + (lambda (entry) + (let ((label (and (org-element-property :name entry) + (org-export-get-reference entry info))) + (title (org-trim + (org-export-data + (or (org-export-get-caption entry t) + (org-export-get-caption entry)) + info)))) + (concat + "
  • " + (if (not label) + (concat (format initial-fmt (cl-incf count)) + " " + title) + (format "%s %s" + label + (format initial-fmt (cl-incf count)) + title)) + "
  • "))) + lol-entries "\n")) + "\n
\n
\n
")))) + + +;;; Transcode Functions + +;;;; Bold + +(defun org-html-bold (_bold contents info) + "Transcode BOLD from Org to HTML. +CONTENTS is the text with bold markup. INFO is a plist holding +contextual information." + (format (or (cdr (assq 'bold (plist-get info :html-text-markup-alist))) "%s") + contents)) + +;;;; Center Block + +(defun org-html-center-block (_center-block contents _info) + "Transcode a CENTER-BLOCK element from Org to HTML. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + (format "
\n%s
" contents)) + +;;;; Clock + +(defun org-html-clock (clock _contents _info) + "Transcode a CLOCK element from Org to HTML. +CONTENTS is nil. INFO is a plist used as a communication +channel." + (format "

+ +%s %s%s + +

" + org-clock-string + (org-timestamp-translate (org-element-property :value clock)) + (let ((time (org-element-property :duration clock))) + (and time (format " (%s)" time))))) + +;;;; Code + +(defun org-html-code (code _contents info) + "Transcode CODE from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual +information." + (format (or (cdr (assq 'code (plist-get info :html-text-markup-alist))) "%s") + (org-html-encode-plain-text (org-element-property :value code)))) + +;;;; Drawer + +(defun org-html-drawer (drawer contents info) + "Transcode a DRAWER element from Org to HTML. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + (funcall (plist-get info :html-format-drawer-function) + (org-element-property :drawer-name drawer) + contents)) + +;;;; Dynamic Block + +(defun org-html-dynamic-block (_dynamic-block contents _info) + "Transcode a DYNAMIC-BLOCK element from Org to HTML. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information. See `org-export-data'." + contents) + +;;;; Entity + +(defun org-html-entity (entity _contents _info) + "Transcode an ENTITY object from Org to HTML. +CONTENTS are the definition itself. INFO is a plist holding +contextual information." + (org-element-property :html entity)) + +;;;; Example Block + +(defun org-html-example-block (example-block _contents info) + "Transcode a EXAMPLE-BLOCK element from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual +information." + (let ((attributes (org-export-read-attribute :attr_html example-block))) + (if (plist-get attributes :textarea) + (org-html--textarea-block example-block) + (format "
\n%s
" + (let* ((name (org-element-property :name example-block)) + (a (org-html--make-attribute-string + (if (or (not name) (plist-member attributes :id)) + attributes + (plist-put attributes :id name))))) + (if (org-string-nw-p a) (concat " " a) "")) + (org-html-format-code example-block info))))) + +;;;; Export Snippet + +(defun org-html-export-snippet (export-snippet _contents _info) + "Transcode a EXPORT-SNIPPET object from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual +information." + (when (eq (org-export-snippet-backend export-snippet) 'html) + (org-element-property :value export-snippet))) + +;;;; Export Block + +(defun org-html-export-block (export-block _contents _info) + "Transcode a EXPORT-BLOCK element from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual information." + (when (string= (org-element-property :type export-block) "HTML") + (org-remove-indentation (org-element-property :value export-block)))) + +;;;; Fixed Width + +(defun org-html-fixed-width (fixed-width _contents _info) + "Transcode a FIXED-WIDTH element from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual information." + (format "
\n%s
" + (org-html-do-format-code + (org-remove-indentation + (org-element-property :value fixed-width))))) + +;;;; Footnote Reference + +(defun org-html-footnote-reference (footnote-reference _contents info) + "Transcode a FOOTNOTE-REFERENCE element from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual information." + (concat + ;; Insert separator between two footnotes in a row. + (let ((prev (org-export-get-previous-element footnote-reference info))) + (when (eq (org-element-type prev) 'footnote-reference) + (plist-get info :html-footnote-separator))) + (let* ((n (org-export-get-footnote-number footnote-reference info)) + (id (format "fnr.%d%s" + n + (if (org-export-footnote-first-reference-p + footnote-reference info) + "" + ".100")))) + (format + (plist-get info :html-footnote-format) + (org-html--anchor + id n (format " class=\"footref\" href=\"#fn.%d\"" n) info))))) + +;;;; Headline + +(defun org-html-headline (headline contents info) + "Transcode a HEADLINE element from Org to HTML. +CONTENTS holds the contents of the headline. INFO is a plist +holding contextual information." + (unless (org-element-property :footnote-section-p headline) + (let* ((numberedp (org-export-numbered-headline-p headline info)) + (numbers (org-export-get-headline-number headline info)) + (level (+ (org-export-get-relative-level headline info) + (1- (plist-get info :html-toplevel-hlevel)))) + (todo (and (plist-get info :with-todo-keywords) + (let ((todo (org-element-property :todo-keyword headline))) + (and todo (org-export-data todo info))))) + (todo-type (and todo (org-element-property :todo-type headline))) + (priority (and (plist-get info :with-priority) + (org-element-property :priority headline))) + (text (org-export-data (org-element-property :title headline) info)) + (tags (and (plist-get info :with-tags) + (org-export-get-tags headline info))) + (full-text (funcall (plist-get info :html-format-headline-function) + todo todo-type priority text tags info)) + (contents (or contents "")) + (ids (delq nil + (list (org-element-property :CUSTOM_ID headline) + (org-export-get-reference headline info) + (org-element-property :ID headline)))) + (preferred-id (car ids)) + (extra-ids + (mapconcat + (lambda (id) + (org-html--anchor + (if (org-uuidgen-p id) (concat "ID-" id) id) + nil nil info)) + (cdr ids) ""))) + (if (org-export-low-level-p headline info) + ;; This is a deep sub-tree: export it as a list item. + (let* ((html-type (if numberedp "ol" "ul"))) + (concat + (and (org-export-first-sibling-p headline info) + (apply #'format "<%s class=\"org-%s\">\n" + (make-list 2 html-type))) + (org-html-format-list-item + contents (if numberedp 'ordered 'unordered) + nil info nil + (concat (org-html--anchor preferred-id nil nil info) + extra-ids + full-text)) "\n" + (and (org-export-last-sibling-p headline info) + (format "\n" html-type)))) + ;; Standard headline. Export it as a section. + (let ((extra-class (org-element-property :HTML_CONTAINER_CLASS headline)) + (first-content (car (org-element-contents headline)))) + (format "<%s id=\"%s\" class=\"%s\">%s%s\n" + (org-html--container headline info) + (concat "outline-container-" + (org-export-get-reference headline info)) + (concat (format "outline-%d" level) + (and extra-class " ") + extra-class) + (format "\n%s%s\n" + level + preferred-id + extra-ids + (concat + (and numberedp + (format + "%s " + level + (mapconcat #'number-to-string numbers "."))) + full-text) + level) + ;; When there is no section, pretend there is an + ;; empty one to get the correct
%s" lang label code))) + +;;;; Inlinetask + +(defun org-html-inlinetask (inlinetask contents info) + "Transcode an INLINETASK element from Org to HTML. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + (let* ((todo (and (plist-get info :with-todo-keywords) + (let ((todo (org-element-property :todo-keyword inlinetask))) + (and todo (org-export-data todo info))))) + (todo-type (and todo (org-element-property :todo-type inlinetask))) + (priority (and (plist-get info :with-priority) + (org-element-property :priority inlinetask))) + (text (org-export-data (org-element-property :title inlinetask) info)) + (tags (and (plist-get info :with-tags) + (org-export-get-tags inlinetask info)))) + (funcall (plist-get info :html-format-inlinetask-function) + todo todo-type priority text tags contents info))) + +(defun org-html-format-inlinetask-default-function + (todo todo-type priority text tags contents info) + "Default format function for inlinetasks. +See `org-html-format-inlinetask-function' for details." + (format "
\n%s%s\n%s
" + (org-html-format-headline-default-function + todo todo-type priority text tags info) + (org-html-close-tag "br" nil info) + contents)) + +;;;; Italic + +(defun org-html-italic (_italic contents info) + "Transcode ITALIC from Org to HTML. +CONTENTS is the text with italic markup. INFO is a plist holding +contextual information." + (format + (or (cdr (assq 'italic (plist-get info :html-text-markup-alist))) "%s") + contents)) + +;;;; Item + +(defun org-html-checkbox (checkbox info) + "Format CHECKBOX into HTML. +INFO is a plist holding contextual information. See +`org-html-checkbox-type' for customization options." + (cdr (assq checkbox + (cdr (assq (plist-get info :html-checkbox-type) + org-html-checkbox-types))))) + +(defun org-html-format-list-item (contents type checkbox info + &optional term-counter-id + headline) + "Format a list item into HTML." + (let ((class (if checkbox + (format " class=\"%s\"" + (symbol-name checkbox)) "")) + (checkbox (concat (org-html-checkbox checkbox info) + (and checkbox " "))) + (br (org-html-close-tag "br" nil info)) + (extra-newline (if (and (org-string-nw-p contents) headline) "\n" ""))) + (concat + (pcase type + (`ordered + (let* ((counter term-counter-id) + (extra (if counter (format " value=\"%s\"" counter) ""))) + (concat + (format "" class extra) + (when headline (concat headline br))))) + (`unordered + (let* ((id term-counter-id) + (extra (if id (format " id=\"%s\"" id) ""))) + (concat + (format "" class extra) + (when headline (concat headline br))))) + (`descriptive + (let* ((term term-counter-id)) + (setq term (or term "(no term)")) + ;; Check-boxes in descriptive lists are associated to tag. + (concat (format "%s
" + class (concat checkbox term)) + "
")))) + (unless (eq type 'descriptive) checkbox) + extra-newline + (and (org-string-nw-p contents) (org-trim contents)) + extra-newline + (pcase type + (`ordered "") + (`unordered "") + (`descriptive "
"))))) + +(defun org-html-item (item contents info) + "Transcode an ITEM element from Org to HTML. +CONTENTS holds the contents of the item. INFO is a plist holding +contextual information." + (let* ((plain-list (org-export-get-parent item)) + (type (org-element-property :type plain-list)) + (counter (org-element-property :counter item)) + (checkbox (org-element-property :checkbox item)) + (tag (let ((tag (org-element-property :tag item))) + (and tag (org-export-data tag info))))) + (org-html-format-list-item + contents type checkbox info (or tag counter)))) + +;;;; Keyword + +(defun org-html-keyword (keyword _contents info) + "Transcode a KEYWORD element from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual information." + (let ((key (org-element-property :key keyword)) + (value (org-element-property :value keyword))) + (cond + ((string= key "HTML") value) + ((string= key "TOC") + (let ((case-fold-search t)) + (cond + ((string-match "\\" value) + (let ((depth (and (string-match "\\<[0-9]+\\>" value) + (string-to-number (match-string 0 value)))) + (localp (string-match-p "\\" value))) + (org-html-toc depth info (and localp keyword)))) + ((string= "listings" value) (org-html-list-of-listings info)) + ((string= "tables" value) (org-html-list-of-tables info)))))))) + +;;;; Latex Environment + +(defun org-html-format-latex (latex-frag processing-type info) + "Format a LaTeX fragment LATEX-FRAG into HTML. +PROCESSING-TYPE designates the tool used for conversion. It can +be `mathjax', `verbatim', nil, t or symbols in +`org-preview-latex-process-alist', e.g., `dvipng', `dvisvgm' or +`imagemagick'. See `org-html-with-latex' for more information. +INFO is a plist containing export properties." + (let ((cache-relpath "") (cache-dir "")) + (unless (eq processing-type 'mathjax) + (let ((bfn (or (buffer-file-name) + (make-temp-name + (expand-file-name "latex" temporary-file-directory)))) + (latex-header + (let ((header (plist-get info :latex-header))) + (and header + (concat (mapconcat + (lambda (line) (concat "#+LATEX_HEADER: " line)) + (org-split-string header "\n") + "\n") + "\n"))))) + (setq cache-relpath + (concat (file-name-as-directory org-preview-latex-image-directory) + (file-name-sans-extension + (file-name-nondirectory bfn))) + cache-dir (file-name-directory bfn)) + ;; Re-create LaTeX environment from original buffer in + ;; temporary buffer so that dvipng/imagemagick can properly + ;; turn the fragment into an image. + (setq latex-frag (concat latex-header latex-frag)))) + (with-temp-buffer + (insert latex-frag) + (org-format-latex cache-relpath nil nil cache-dir nil + "Creating LaTeX Image..." nil processing-type) + (buffer-string)))) + +(defun org-html-latex-environment (latex-environment _contents info) + "Transcode a LATEX-ENVIRONMENT element from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual information." + (let ((processing-type (plist-get info :with-latex)) + (latex-frag (org-remove-indentation + (org-element-property :value latex-environment))) + (attributes (org-export-read-attribute :attr_html latex-environment))) + (cond + ((memq processing-type '(t mathjax)) + (org-html-format-latex latex-frag 'mathjax info)) + ((assq processing-type org-preview-latex-process-alist) + (let ((formula-link + (org-html-format-latex latex-frag processing-type info))) + (when (and formula-link (string-match "file:\\([^]]*\\)" formula-link)) + ;; Do not provide a caption or a name to be consistent with + ;; `mathjax' handling. + (org-html--wrap-image + (org-html--format-image + (match-string 1 formula-link) attributes info) info)))) + (t latex-frag)))) + +;;;; Latex Fragment + +(defun org-html-latex-fragment (latex-fragment _contents info) + "Transcode a LATEX-FRAGMENT object from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual information." + (let ((latex-frag (org-element-property :value latex-fragment)) + (processing-type (plist-get info :with-latex))) + (cond + ((memq processing-type '(t mathjax)) + (org-html-format-latex latex-frag 'mathjax info)) + ((assq processing-type org-preview-latex-process-alist) + (let ((formula-link + (org-html-format-latex latex-frag processing-type info))) + (when (and formula-link (string-match "file:\\([^]]*\\)" formula-link)) + (org-html--format-image (match-string 1 formula-link) nil info)))) + (t latex-frag)))) + +;;;; Line Break + +(defun org-html-line-break (_line-break _contents info) + "Transcode a LINE-BREAK object from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual information." + (concat (org-html-close-tag "br" nil info) "\n")) + +;;;; Link + +(defun org-html-image-link-filter (data _backend info) + (org-export-insert-image-links data info org-html-inline-image-rules)) + +(defun org-html-inline-image-p (link info) + "Non-nil when LINK is meant to appear as an image. +INFO is a plist used as a communication channel. LINK is an +inline image when it has no description and targets an image +file (see `org-html-inline-image-rules' for more information), or +if its description is a single link targeting an image file." + (if (not (org-element-contents link)) + (org-export-inline-image-p + link (plist-get info :html-inline-image-rules)) + (not + (let ((link-count 0)) + (org-element-map (org-element-contents link) + (cons 'plain-text org-element-all-objects) + (lambda (obj) + (pcase (org-element-type obj) + (`plain-text (org-string-nw-p obj)) + (`link (if (= link-count 1) t + (cl-incf link-count) + (not (org-export-inline-image-p + obj (plist-get info :html-inline-image-rules))))) + (_ t))) + info t))))) + +(defvar org-html-standalone-image-predicate) +(defun org-html-standalone-image-p (element info) + "Non-nil if ELEMENT is a standalone image. + +INFO is a plist holding contextual information. + +An element or object is a standalone image when + + - its type is `paragraph' and its sole content, save for white + spaces, is a link that qualifies as an inline image; + + - its type is `link' and its containing paragraph has no other + content save white spaces. + +Bind `org-html-standalone-image-predicate' to constrain paragraph +further. For example, to check for only captioned standalone +images, set it to: + + (lambda (paragraph) (org-element-property :caption paragraph))" + (let ((paragraph (pcase (org-element-type element) + (`paragraph element) + (`link (org-export-get-parent element))))) + (and (eq (org-element-type paragraph) 'paragraph) + (or (not (fboundp 'org-html-standalone-image-predicate)) + (funcall org-html-standalone-image-predicate paragraph)) + (catch 'exit + (let ((link-count 0)) + (org-element-map (org-element-contents paragraph) + (cons 'plain-text org-element-all-objects) + (lambda (obj) + (when (pcase (org-element-type obj) + (`plain-text (org-string-nw-p obj)) + (`link (or (> (cl-incf link-count) 1) + (not (org-html-inline-image-p obj info)))) + (_ t)) + (throw 'exit nil))) + info nil 'link) + (= link-count 1)))))) + +(defun org-html-link (link desc info) + "Transcode a LINK object from Org to HTML. +DESC is the description part of the link, or the empty string. +INFO is a plist holding contextual information. See +`org-export-data'." + (let* ((link-org-files-as-html-maybe + (lambda (raw-path info) + ;; Treat links to `file.org' as links to `file.html', if + ;; needed. See `org-html-link-org-files-as-html'. + (cond + ((and (plist-get info :html-link-org-files-as-html) + (string= ".org" + (downcase (file-name-extension raw-path ".")))) + (concat (file-name-sans-extension raw-path) "." + (plist-get info :html-extension))) + (t raw-path)))) + (type (org-element-property :type link)) + (raw-path (org-element-property :path link)) + ;; Ensure DESC really exists, or set it to nil. + (desc (org-string-nw-p desc)) + (path + (cond + ((member type '("http" "https" "ftp" "mailto" "news")) + (url-encode-url (org-link-unescape (concat type ":" raw-path)))) + ((string= type "file") + ;; During publishing, turn absolute file names belonging + ;; to base directory into relative file names. Otherwise, + ;; append "file" protocol to absolute file name. + (setq raw-path + (org-export-file-uri + (org-publish-file-relative-name raw-path info))) + ;; Possibly append `:html-link-home' to relative file + ;; name. + (let ((home (and (plist-get info :html-link-home) + (org-trim (plist-get info :html-link-home))))) + (when (and home + (plist-get info :html-link-use-abs-url) + (file-name-absolute-p raw-path)) + (setq raw-path (concat (file-name-as-directory home) raw-path)))) + ;; Maybe turn ".org" into ".html". + (setq raw-path (funcall link-org-files-as-html-maybe raw-path info)) + ;; Add search option, if any. A search option can be + ;; relative to a custom-id, a headline title, a name or + ;; a target. + (let ((option (org-element-property :search-option link))) + (cond ((not option) raw-path) + ;; Since HTML back-end use custom-id value as-is, + ;; resolving is them is trivial. + ((eq (string-to-char option) ?#) (concat raw-path option)) + (t + (concat raw-path + "#" + (org-publish-resolve-external-link + option + (org-element-property :path link))))))) + (t raw-path))) + ;; Extract attributes from parent's paragraph. HACK: Only do + ;; this for the first link in parent (inner image link for + ;; inline images). This is needed as long as attributes + ;; cannot be set on a per link basis. + (attributes-plist + (let* ((parent (org-export-get-parent-element link)) + (link (let ((container (org-export-get-parent link))) + (if (and (eq (org-element-type container) 'link) + (org-html-inline-image-p link info)) + container + link)))) + (and (eq (org-element-map parent 'link 'identity info t) link) + (org-export-read-attribute :attr_html parent)))) + (attributes + (let ((attr (org-html--make-attribute-string attributes-plist))) + (if (org-string-nw-p attr) (concat " " attr) "")))) + (cond + ;; Link type is handled by a special function. + ((org-export-custom-protocol-maybe link desc 'html)) + ;; Image file. + ((and (plist-get info :html-inline-images) + (org-export-inline-image-p + link (plist-get info :html-inline-image-rules))) + (org-html--format-image path attributes-plist info)) + ;; Radio target: Transcode target's contents and use them as + ;; link's description. + ((string= type "radio") + (let ((destination (org-export-resolve-radio-link link info))) + (if (not destination) desc + (format "%s" + (org-export-get-reference destination info) + attributes + desc)))) + ;; Links pointing to a headline: Find destination and build + ;; appropriate referencing command. + ((member type '("custom-id" "fuzzy" "id")) + (let ((destination (if (string= type "fuzzy") + (org-export-resolve-fuzzy-link link info) + (org-export-resolve-id-link link info)))) + (pcase (org-element-type destination) + ;; ID link points to an external file. + (`plain-text + (let ((fragment (concat "ID-" path)) + ;; Treat links to ".org" files as ".html", if needed. + (path (funcall link-org-files-as-html-maybe + destination info))) + (format "%s" + path fragment attributes (or desc destination)))) + ;; Fuzzy link points nowhere. + (`nil + (format "%s" + (or desc + (org-export-data + (org-element-property :raw-link link) info)))) + ;; Link points to a headline. + (`headline + (let ((href (or (org-element-property :CUSTOM_ID destination) + (org-export-get-reference destination info))) + ;; What description to use? + (desc + ;; Case 1: Headline is numbered and LINK has no + ;; description. Display section number. + (if (and (org-export-numbered-headline-p destination info) + (not desc)) + (mapconcat #'number-to-string + (org-export-get-headline-number + destination info) ".") + ;; Case 2: Either the headline is un-numbered or + ;; LINK has a custom description. Display LINK's + ;; description or headline's title. + (or desc + (org-export-data + (org-element-property :title destination) info))))) + (format "%s" href attributes desc))) + ;; Fuzzy link points to a target or an element. + (_ + (let* ((ref (org-export-get-reference destination info)) + (org-html-standalone-image-predicate + #'org-html--has-caption-p) + (number (cond + (desc nil) + ((org-html-standalone-image-p destination info) + (org-export-get-ordinal + (org-element-map destination 'link + #'identity info t) + info 'link 'org-html-standalone-image-p)) + (t (org-export-get-ordinal + destination info nil 'org-html--has-caption-p)))) + (desc (cond (desc) + ((not number) "No description for this link") + ((numberp number) (number-to-string number)) + (t (mapconcat #'number-to-string number "."))))) + (format "%s" ref attributes desc)))))) + ;; Coderef: replace link with the reference name or the + ;; equivalent line number. + ((string= type "coderef") + (let ((fragment (concat "coderef-" (org-html-encode-plain-text path)))) + (format "%s" + fragment + (format "class=\"coderef\" onmouseover=\"CodeHighlightOn(this, \ +'%s');\" onmouseout=\"CodeHighlightOff(this, '%s');\"" + fragment fragment) + attributes + (format (org-export-get-coderef-format path desc) + (org-export-resolve-coderef path info))))) + ;; External link with a description part. + ((and path desc) (format "%s" + (org-html-encode-plain-text path) + attributes + desc)) + ;; External link without a description part. + (path (let ((path (org-html-encode-plain-text path))) + (format "%s" + path + attributes + (org-link-unescape path)))) + ;; No path, only description. Try to do something useful. + (t (format "%s" desc))))) + +;;;; Node Property + +(defun org-html-node-property (node-property _contents _info) + "Transcode a NODE-PROPERTY element from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual +information." + (format "%s:%s" + (org-element-property :key node-property) + (let ((value (org-element-property :value node-property))) + (if value (concat " " value) "")))) + +;;;; Paragraph + +(defun org-html-paragraph (paragraph contents info) + "Transcode a PARAGRAPH element from Org to HTML. +CONTENTS is the contents of the paragraph, as a string. INFO is +the plist used as a communication channel." + (let* ((parent (org-export-get-parent paragraph)) + (parent-type (org-element-type parent)) + (style '((footnote-definition " class=\"footpara\"") + (org-data " class=\"footpara\""))) + (attributes (org-html--make-attribute-string + (org-export-read-attribute :attr_html paragraph))) + (extra (or (cadr (assq parent-type style)) ""))) + (cond + ((and (eq parent-type 'item) + (not (org-export-get-previous-element paragraph info)) + (let ((followers (org-export-get-next-element paragraph info 2))) + (and (not (cdr followers)) + (memq (org-element-type (car followers)) '(nil plain-list))))) + ;; First paragraph in an item has no tag if it is alone or + ;; followed, at most, by a sub-list. + contents) + ((org-html-standalone-image-p paragraph info) + ;; Standalone image. + (let ((caption + (let ((raw (org-export-data + (org-export-get-caption paragraph) info)) + (org-html-standalone-image-predicate + #'org-html--has-caption-p)) + (if (not (org-string-nw-p raw)) raw + (concat "" + (format (org-html--translate "Figure %d:" info) + (org-export-get-ordinal + (org-element-map paragraph 'link + #'identity info t) + info nil #'org-html-standalone-image-p)) + " " + raw)))) + (label (and (org-element-property :name paragraph) + (org-export-get-reference paragraph info)))) + (org-html--wrap-image contents info caption label))) + ;; Regular paragraph. + (t (format "\n%s

" + (if (org-string-nw-p attributes) + (concat " " attributes) "") + extra contents))))) + +;;;; Plain List + +(defun org-html-plain-list (plain-list contents _info) + "Transcode a PLAIN-LIST element from Org to HTML. +CONTENTS is the contents of the list. INFO is a plist holding +contextual information." + (let* ((type (pcase (org-element-property :type plain-list) + (`ordered "ol") + (`unordered "ul") + (`descriptive "dl") + (other (error "Unknown HTML list type: %s" other)))) + (class (format "org-%s" type)) + (attributes (org-export-read-attribute :attr_html plain-list))) + (format "<%s %s>\n%s" + type + (org-html--make-attribute-string + (plist-put attributes :class + (org-trim + (mapconcat #'identity + (list class (plist-get attributes :class)) + " ")))) + contents + type))) + +;;;; Plain Text + +(defun org-html-convert-special-strings (string) + "Convert special characters in STRING to HTML." + (dolist (a org-html-special-string-regexps string) + (let ((re (car a)) + (rpl (cdr a))) + (setq string (replace-regexp-in-string re rpl string t))))) + +(defun org-html-encode-plain-text (text) + "Convert plain text characters from TEXT to HTML equivalent. +Possible conversions are set in `org-html-protect-char-alist'." + (dolist (pair org-html-protect-char-alist text) + (setq text (replace-regexp-in-string (car pair) (cdr pair) text t t)))) + +(defun org-html-plain-text (text info) + "Transcode a TEXT string from Org to HTML. +TEXT is the string to transcode. INFO is a plist holding +contextual information." + (let ((output text)) + ;; Protect following characters: <, >, &. + (setq output (org-html-encode-plain-text output)) + ;; Handle smart quotes. Be sure to provide original string since + ;; OUTPUT may have been modified. + (when (plist-get info :with-smart-quotes) + (setq output (org-export-activate-smart-quotes output :html info text))) + ;; Handle special strings. + (when (plist-get info :with-special-strings) + (setq output (org-html-convert-special-strings output))) + ;; Handle break preservation if required. + (when (plist-get info :preserve-breaks) + (setq output + (replace-regexp-in-string + "\\(\\\\\\\\\\)?[ \t]*\n" + (concat (org-html-close-tag "br" nil info) "\n") output))) + ;; Return value. + output)) + + +;; Planning + +(defun org-html-planning (planning _contents info) + "Transcode a PLANNING element from Org to HTML. +CONTENTS is nil. INFO is a plist used as a communication +channel." + (format + "

%s

" + (org-trim + (mapconcat + (lambda (pair) + (let ((timestamp (cdr pair))) + (when timestamp + (let ((string (car pair))) + (format "%s \ +%s " + string + (org-html-plain-text (org-timestamp-translate timestamp) + info)))))) + `((,org-closed-string . ,(org-element-property :closed planning)) + (,org-deadline-string . ,(org-element-property :deadline planning)) + (,org-scheduled-string . ,(org-element-property :scheduled planning))) + "")))) + +;;;; Property Drawer + +(defun org-html-property-drawer (_property-drawer contents _info) + "Transcode a PROPERTY-DRAWER element from Org to HTML. +CONTENTS holds the contents of the drawer. INFO is a plist +holding contextual information." + (and (org-string-nw-p contents) + (format "
\n%s
" contents))) + +;;;; Quote Block + +(defun org-html-quote-block (quote-block contents _info) + "Transcode a QUOTE-BLOCK element from Org to HTML. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + (format "\n%s" + (let* ((name (org-element-property :name quote-block)) + (attributes (org-export-read-attribute :attr_html quote-block)) + (a (org-html--make-attribute-string + (if (or (not name) (plist-member attributes :id)) + attributes + (plist-put attributes :id name))))) + (if (org-string-nw-p a) (concat " " a) "")) + contents)) + +;;;; Section + +(defun org-html-section (section contents info) + "Transcode a SECTION element from Org to HTML. +CONTENTS holds the contents of the section. INFO is a plist +holding contextual information." + (let ((parent (org-export-get-parent-headline section))) + ;; Before first headline: no container, just return CONTENTS. + (if (not parent) contents + ;; Get div's class and id references. + (let* ((class-num (+ (org-export-get-relative-level parent info) + (1- (plist-get info :html-toplevel-hlevel)))) + (section-number + (and (org-export-numbered-headline-p parent info) + (mapconcat + #'number-to-string + (org-export-get-headline-number parent info) "-")))) + ;; Build return value. + (format "
\n%s
\n" + class-num + (or (org-element-property :CUSTOM_ID parent) + section-number + (org-export-get-reference parent info)) + (or contents "")))))) + +;;;; Radio Target + +(defun org-html-radio-target (radio-target text info) + "Transcode a RADIO-TARGET object from Org to HTML. +TEXT is the text of the target. INFO is a plist holding +contextual information." + (let ((ref (org-export-get-reference radio-target info))) + (org-html--anchor ref text nil info))) + +;;;; Special Block + +(defun org-html-special-block (special-block contents info) + "Transcode a SPECIAL-BLOCK element from Org to HTML. +CONTENTS holds the contents of the block. INFO is a plist +holding contextual information." + (let* ((block-type (org-element-property :type special-block)) + (html5-fancy (and (org-html--html5-fancy-p info) + (member block-type org-html-html5-elements))) + (attributes (org-export-read-attribute :attr_html special-block))) + (unless html5-fancy + (let ((class (plist-get attributes :class))) + (setq attributes (plist-put attributes :class + (if class (concat class " " block-type) + block-type))))) + (let* ((contents (or contents "")) + (name (org-element-property :name special-block)) + (a (org-html--make-attribute-string + (if (or (not name) (plist-member attributes :id)) + attributes + (plist-put attributes :id name)))) + (str (if (org-string-nw-p a) (concat " " a) ""))) + (if html5-fancy + (format "<%s%s>\n%s" block-type str contents block-type) + (format "\n%s\n" str contents))))) + +;;;; Src Block + +(defun org-html-src-block (src-block _contents info) + "Transcode a SRC-BLOCK element from Org to HTML. +CONTENTS holds the contents of the item. INFO is a plist holding +contextual information." + (if (org-export-read-attribute :attr_html src-block :textarea) + (org-html--textarea-block src-block) + (let* ((lang (org-element-property :language src-block)) + (code (org-html-format-code src-block info)) + (label (let ((lbl (and (org-element-property :name src-block) + (org-export-get-reference src-block info)))) + (if lbl (format " id=\"%s\"" lbl) ""))) + (klipsify (and (plist-get info :html-klipsify-src) + (member lang '("javascript" "js" + "ruby" "scheme" "clojure" "php" "html"))))) + (if (not lang) (format "
\n%s
" label code) + (format "
\n%s%s\n
" + ;; Build caption. + (let ((caption (org-export-get-caption src-block))) + (if (not caption) "" + (let ((listing-number + (format + "%s " + (format + (org-html--translate "Listing %d:" info) + (org-export-get-ordinal + src-block info nil #'org-html--has-caption-p))))) + (format "" + listing-number + (org-trim (org-export-data caption info)))))) + ;; Contents. + (if klipsify + (format "
%s
" + lang + label + (if (string= lang "html") + " data-editor-type=\"html\"" + "") + code) + (format "
%s
" + lang label code))))))) + +;;;; Statistics Cookie + +(defun org-html-statistics-cookie (statistics-cookie _contents _info) + "Transcode a STATISTICS-COOKIE object from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual information." + (let ((cookie-value (org-element-property :value statistics-cookie))) + (format "%s" cookie-value))) + +;;;; Strike-Through + +(defun org-html-strike-through (_strike-through contents info) + "Transcode STRIKE-THROUGH from Org to HTML. +CONTENTS is the text with strike-through markup. INFO is a plist +holding contextual information." + (format + (or (cdr (assq 'strike-through (plist-get info :html-text-markup-alist))) + "%s") + contents)) + +;;;; Subscript + +(defun org-html-subscript (_subscript contents _info) + "Transcode a SUBSCRIPT object from Org to HTML. +CONTENTS is the contents of the object. INFO is a plist holding +contextual information." + (format "%s" contents)) + +;;;; Superscript + +(defun org-html-superscript (_superscript contents _info) + "Transcode a SUPERSCRIPT object from Org to HTML. +CONTENTS is the contents of the object. INFO is a plist holding +contextual information." + (format "%s" contents)) + +;;;; Table Cell + +(defun org-html-table-cell (table-cell contents info) + "Transcode a TABLE-CELL element from Org to HTML. +CONTENTS is nil. INFO is a plist used as a communication +channel." + (let* ((table-row (org-export-get-parent table-cell)) + (table (org-export-get-parent-table table-cell)) + (cell-attrs + (if (not (plist-get info :html-table-align-individual-fields)) "" + (format (if (and (boundp 'org-html-format-table-no-css) + org-html-format-table-no-css) + " align=\"%s\"" " class=\"org-%s\"") + (org-export-table-cell-alignment table-cell info))))) + (when (or (not contents) (string= "" (org-trim contents))) + (setq contents " ")) + (cond + ((and (org-export-table-has-header-p table info) + (= 1 (org-export-table-row-group table-row info))) + (let ((header-tags (plist-get info :html-table-header-tags))) + (concat "\n" (format (car header-tags) "col" cell-attrs) + contents + (cdr header-tags)))) + ((and (plist-get info :html-table-use-header-tags-for-first-column) + (zerop (cdr (org-export-table-cell-address table-cell info)))) + (let ((header-tags (plist-get info :html-table-header-tags))) + (concat "\n" (format (car header-tags) "row" cell-attrs) + contents + (cdr header-tags)))) + (t (let ((data-tags (plist-get info :html-table-data-tags))) + (concat "\n" (format (car data-tags) cell-attrs) + contents + (cdr data-tags))))))) + +;;;; Table Row + +(defun org-html-table-row (table-row contents info) + "Transcode a TABLE-ROW element from Org to HTML. +CONTENTS is the contents of the row. INFO is a plist used as a +communication channel." + ;; Rules are ignored since table separators are deduced from + ;; borders of the current row. + (when (eq (org-element-property :type table-row) 'standard) + (let* ((group (org-export-table-row-group table-row info)) + (number (org-export-table-row-number table-row info)) + (start-group-p + (org-export-table-row-starts-rowgroup-p table-row info)) + (end-group-p + (org-export-table-row-ends-rowgroup-p table-row info)) + (topp (and (equal start-group-p '(top)) + (equal end-group-p '(below top)))) + (bottomp (and (equal start-group-p '(above)) + (equal end-group-p '(bottom above)))) + (row-open-tag + (pcase (plist-get info :html-table-row-open-tag) + ((and accessor (pred functionp)) + (funcall accessor + number group start-group-p end-group-p topp bottomp)) + (accessor accessor))) + (row-close-tag + (pcase (plist-get info :html-table-row-close-tag) + ((and accessor (pred functionp)) + (funcall accessor + number group start-group-p end-group-p topp bottomp)) + (accessor accessor))) + (group-tags + (cond + ;; Row belongs to second or subsequent groups. + ((not (= 1 group)) '("" . "\n")) + ;; Row is from first group. Table has >=1 groups. + ((org-export-table-has-header-p + (org-export-get-parent-table table-row) info) + '("" . "\n")) + ;; Row is from first and only group. + (t '("" . "\n"))))) + (concat (and start-group-p (car group-tags)) + (concat "\n" + row-open-tag + contents + "\n" + row-close-tag) + (and end-group-p (cdr group-tags)))))) + +;;;; Table + +(defun org-html-table-first-row-data-cells (table info) + "Transcode the first row of TABLE. +INFO is a plist used as a communication channel." + (let ((table-row + (org-element-map table 'table-row + (lambda (row) + (unless (eq (org-element-property :type row) 'rule) row)) + info 'first-match)) + (special-column-p (org-export-table-has-special-column-p table))) + (if (not special-column-p) (org-element-contents table-row) + (cdr (org-element-contents table-row))))) + +(defun org-html-table--table.el-table (table _info) + "Format table.el tables into HTML. +INFO is a plist used as a communication channel." + (when (eq (org-element-property :type table) 'table.el) + (require 'table) + (let ((outbuf (with-current-buffer + (get-buffer-create "*org-export-table*") + (erase-buffer) (current-buffer)))) + (with-temp-buffer + (insert (org-element-property :value table)) + (goto-char 1) + (re-search-forward "^[ \t]*|[^|]" nil t) + (table-generate-source 'html outbuf)) + (with-current-buffer outbuf + (prog1 (org-trim (buffer-string)) + (kill-buffer) ))))) + +(defun org-html-table (table contents info) + "Transcode a TABLE element from Org to HTML. +CONTENTS is the contents of the table. INFO is a plist holding +contextual information." + (if (eq (org-element-property :type table) 'table.el) + ;; "table.el" table. Convert it using appropriate tools. + (org-html-table--table.el-table table info) + ;; Standard table. + (let* ((caption (org-export-get-caption table)) + (number (org-export-get-ordinal + table info nil #'org-html--has-caption-p)) + (attributes + (org-html--make-attribute-string + (org-combine-plists + (and (org-element-property :name table) + (list :id (org-export-get-reference table info))) + (and (not (org-html-html5-p info)) + (plist-get info :html-table-attributes)) + (org-export-read-attribute :attr_html table)))) + (alignspec + (if (bound-and-true-p org-html-format-table-no-css) + "align=\"%s\"" + "class=\"org-%s\"")) + (table-column-specs + (lambda (table info) + (mapconcat + (lambda (table-cell) + (let ((alignment (org-export-table-cell-alignment + table-cell info))) + (concat + ;; Begin a colgroup? + (when (org-export-table-cell-starts-colgroup-p + table-cell info) + "\n") + ;; Add a column. Also specify its alignment. + (format "\n%s" + (org-html-close-tag + "col" (concat " " (format alignspec alignment)) info)) + ;; End a colgroup? + (when (org-export-table-cell-ends-colgroup-p + table-cell info) + "\n")))) + (org-html-table-first-row-data-cells table info) "\n")))) + (format "\n%s\n%s\n%s" + (if (equal attributes "") "" (concat " " attributes)) + (if (not caption) "" + (format (if (plist-get info :html-table-caption-above) + "%s" + "%s") + (concat + "" + (format (org-html--translate "Table %d:" info) number) + " " (org-export-data caption info)))) + (funcall table-column-specs table info) + contents)))) + +;;;; Target + +(defun org-html-target (target _contents info) + "Transcode a TARGET object from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual +information." + (let ((ref (org-export-get-reference target info))) + (org-html--anchor ref nil nil info))) + +;;;; Timestamp + +(defun org-html-timestamp (timestamp _contents info) + "Transcode a TIMESTAMP object from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual +information." + (let ((value (org-html-plain-text (org-timestamp-translate timestamp) info))) + (format "%s" + (replace-regexp-in-string "--" "–" value)))) + +;;;; Underline + +(defun org-html-underline (_underline contents info) + "Transcode UNDERLINE from Org to HTML. +CONTENTS is the text with underline markup. INFO is a plist +holding contextual information." + (format (or (cdr (assq 'underline (plist-get info :html-text-markup-alist))) + "%s") + contents)) + +;;;; Verbatim + +(defun org-html-verbatim (verbatim _contents info) + "Transcode VERBATIM from Org to HTML. +CONTENTS is nil. INFO is a plist holding contextual +information." + (format (or (cdr (assq 'verbatim (plist-get info :html-text-markup-alist))) "%s") + (org-html-encode-plain-text (org-element-property :value verbatim)))) + +;;;; Verse Block + +(defun org-html-verse-block (_verse-block contents info) + "Transcode a VERSE-BLOCK element from Org to HTML. +CONTENTS is verse block contents. INFO is a plist holding +contextual information." + (format "

\n%s

" + ;; Replace leading white spaces with non-breaking spaces. + (replace-regexp-in-string + "^[ \t]+" (lambda (m) (org-html--make-string (length m) " ")) + ;; Replace each newline character with line break. Also + ;; remove any trailing "br" close-tag so as to avoid + ;; duplicates. + (let* ((br (org-html-close-tag "br" nil info)) + (re (format "\\(?:%s\\)?[ \t]*\n" (regexp-quote br)))) + (replace-regexp-in-string re (concat br "\n") contents))))) + + +;;; Filter Functions + +(defun org-html-final-function (contents _backend info) + "Filter to indent the HTML and convert HTML entities." + (with-temp-buffer + (insert contents) + (set-auto-mode t) + (if (plist-get info :html-indent) + (indent-region (point-min) (point-max))) + (buffer-substring-no-properties (point-min) (point-max)))) + + +;;; End-user functions + +;;;###autoload +(defun org-html-export-as-html + (&optional async subtreep visible-only body-only ext-plist) + "Export current buffer to an HTML buffer. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting buffer should be accessible +through the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\" and \"\" tags. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Export is done in a buffer named \"*Org HTML Export*\", which +will be displayed when `org-export-show-temporary-export-buffer' +is non-nil." + (interactive) + (org-export-to-buffer 'html "*Org HTML Export*" + async subtreep visible-only body-only ext-plist + (lambda () (set-auto-mode t)))) + +;;;###autoload +(defun org-html-convert-region-to-html () + "Assume the current region has Org syntax, and convert it to HTML. +This can be used in any buffer. For example, you can write an +itemized list in Org syntax in an HTML buffer and use this command +to convert it." + (interactive) + (org-export-replace-region-by 'html)) + +;;;###autoload +(defun org-html-export-to-html + (&optional async subtreep visible-only body-only ext-plist) + "Export current buffer to a HTML file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"\" and \"\" tags. + +EXT-PLIST, when provided, is a property list with external +parameters overriding Org default settings, but still inferior to +file-local settings. + +Return output file's name." + (interactive) + (let* ((extension (concat "." (or (plist-get ext-plist :html-extension) + org-html-extension + "html"))) + (file (org-export-output-file-name extension subtreep)) + (org-export-coding-system org-html-coding-system)) + (org-export-to-file 'html file + async subtreep visible-only body-only ext-plist))) + +;;;###autoload +(defun org-html-publish-to-html (plist filename pub-dir) + "Publish an org file to HTML. + +FILENAME is the filename of the Org file to be published. PLIST +is the property list for the given project. PUB-DIR is the +publishing directory. + +Return output file name." + (org-publish-org-to 'html filename + (concat "." (or (plist-get plist :html-extension) + org-html-extension + "html")) + plist pub-dir)) + + +(provide 'ox-html) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; ox-html.el ends here diff --git a/elpa/org-9.1.14/ox-icalendar.el b/elpa/org-9.1.14/ox-icalendar.el new file mode 100644 index 00000000..7d7c8500 --- /dev/null +++ b/elpa/org-9.1.14/ox-icalendar.el @@ -0,0 +1,979 @@ +;;; ox-icalendar.el --- iCalendar Back-End for Org Export Engine -*- lexical-binding: t; -*- + +;; Copyright (C) 2004-2018 Free Software Foundation, Inc. + +;; Author: Carsten Dominik +;; Nicolas Goaziou +;; Keywords: outlines, hypermedia, calendar, wp +;; Homepage: https://orgmode.org + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: +;; +;; This library implements an iCalendar back-end for Org generic +;; exporter. See Org manual for more information. +;; +;; It is expected to conform to RFC 5545. + +;;; Code: + +(require 'cl-lib) +(require 'ox-ascii) +(declare-function org-bbdb-anniv-export-ical "org-bbdb" nil) + + + +;;; User-Configurable Variables + +(defgroup org-export-icalendar nil + "Options specific for iCalendar export back-end." + :tag "Org Export iCalendar" + :group 'org-export) + +(defcustom org-icalendar-combined-agenda-file "~/org.ics" + "The file name for the iCalendar file covering all agenda files. +This file is created with the command `\\[org-icalendar-combine-agenda-files]'. +The file name should be absolute. It will be overwritten without warning." + :group 'org-export-icalendar + :type 'file) + +(defcustom org-icalendar-alarm-time 0 + "Number of minutes for triggering an alarm for exported timed events. + +A zero value (the default) turns off the definition of an alarm trigger +for timed events. If non-zero, alarms are created. + +- a single alarm per entry is defined +- The alarm will go off N minutes before the event +- only a DISPLAY action is defined." + :group 'org-export-icalendar + :version "24.1" + :type 'integer) + +(defcustom org-icalendar-combined-name "OrgMode" + "Calendar name for the combined iCalendar representing all agenda files." + :group 'org-export-icalendar + :type 'string) + +(defcustom org-icalendar-combined-description "" + "Calendar description for the combined iCalendar (all agenda files)." + :group 'org-export-icalendar + :type 'string) + +(defcustom org-icalendar-exclude-tags nil + "Tags that exclude a tree from export. +This variable allows specifying different exclude tags from other +back-ends. It can also be set with the ICALENDAR_EXCLUDE_TAGS +keyword." + :group 'org-export-icalendar + :type '(repeat (string :tag "Tag"))) + +(defcustom org-icalendar-use-deadline '(event-if-not-todo todo-due) + "Contexts where iCalendar export should use a deadline time stamp. + +This is a list with possibly several symbols in it. Valid symbols are: + +`event-if-todo' Deadlines in TODO entries become calendar events. +`event-if-not-todo' Deadlines in non-TODO entries become calendar events. +`todo-due' Use deadlines in TODO entries as due-dates." + :group 'org-export-icalendar + :type '(set :greedy t + (const :tag "Deadlines in non-TODO entries become events" + event-if-not-todo) + (const :tag "Deadline in TODO entries become events" + event-if-todo) + (const :tag "Deadlines in TODO entries become due-dates" + todo-due))) + +(defcustom org-icalendar-use-scheduled '(todo-start) + "Contexts where iCalendar export should use a scheduling time stamp. + +This is a list with possibly several symbols in it. Valid symbols are: + +`event-if-todo' Scheduling time stamps in TODO entries become an event. +`event-if-not-todo' Scheduling time stamps in non-TODO entries become an event. +`todo-start' Scheduling time stamps in TODO entries become start date. + Some calendar applications show TODO entries only after + that date." + :group 'org-export-icalendar + :type '(set :greedy t + (const :tag + "SCHEDULED timestamps in non-TODO entries become events" + event-if-not-todo) + (const :tag "SCHEDULED timestamps in TODO entries become events" + event-if-todo) + (const :tag "SCHEDULED in TODO entries become start date" + todo-start))) + +(defcustom org-icalendar-categories '(local-tags category) + "Items that should be entered into the \"categories\" field. + +This is a list of symbols, the following are valid: +`category' The Org mode category of the current file or tree +`todo-state' The todo state, if any +`local-tags' The tags, defined in the current line +`all-tags' All tags, including inherited ones." + :group 'org-export-icalendar + :type '(repeat + (choice + (const :tag "The file or tree category" category) + (const :tag "The TODO state" todo-state) + (const :tag "Tags defined in current line" local-tags) + (const :tag "All tags, including inherited ones" all-tags)))) + +(defcustom org-icalendar-with-timestamps 'active + "Non-nil means make an event from plain time stamps. + +It can be set to `active', `inactive', t or nil, in order to make +an event from, respectively, only active timestamps, only +inactive ones, all of them or none. + +This variable has precedence over `org-export-with-timestamps'. +It can also be set with the #+OPTIONS line, e.g. \"<:t\"." + :group 'org-export-icalendar + :type '(choice + (const :tag "All timestamps" t) + (const :tag "Only active timestamps" active) + (const :tag "Only inactive timestamps" inactive) + (const :tag "No timestamp" nil))) + +(defcustom org-icalendar-include-todo nil + "Non-nil means create VTODO components from TODO items. + +Valid values are: +nil don't include any task. +t include tasks that are not in DONE state. +`unblocked' include all TODO items that are not blocked. +`all' include both done and not done items." + :group 'org-export-icalendar + :type '(choice + (const :tag "None" nil) + (const :tag "Unfinished" t) + (const :tag "Unblocked" unblocked) + (const :tag "All" all) + (repeat :tag "Specific TODO keywords" + (string :tag "Keyword")))) + +(defcustom org-icalendar-include-bbdb-anniversaries nil + "Non-nil means a combined iCalendar file should include anniversaries. +The anniversaries are defined in the BBDB database." + :group 'org-export-icalendar + :type 'boolean) + +(defcustom org-icalendar-include-sexps t + "Non-nil means export to iCalendar files should also cover sexp entries. +These are entries like in the diary, but directly in an Org file." + :group 'org-export-icalendar + :type 'boolean) + +(defcustom org-icalendar-include-body t + "Amount of text below headline to be included in iCalendar export. +This is a number of characters that should maximally be included. +Properties, scheduling and clocking lines will always be removed. +The text will be inserted into the DESCRIPTION field." + :group 'org-export-icalendar + :type '(choice + (const :tag "Nothing" nil) + (const :tag "Everything" t) + (integer :tag "Max characters"))) + +(defcustom org-icalendar-store-UID nil + "Non-nil means store any created UIDs in properties. + +The iCalendar standard requires that all entries have a unique identifier. +Org will create these identifiers as needed. When this variable is non-nil, +the created UIDs will be stored in the ID property of the entry. Then the +next time this entry is exported, it will be exported with the same UID, +superseding the previous form of it. This is essential for +synchronization services. + +This variable is not turned on by default because we want to avoid creating +a property drawer in every entry if people are only playing with this feature, +or if they are only using it locally." + :group 'org-export-icalendar + :type 'boolean) + +(defcustom org-icalendar-timezone (getenv "TZ") + "The time zone string for iCalendar export. +When nil or the empty string, use output +from (current-time-zone)." + :group 'org-export-icalendar + :type '(choice + (const :tag "Unspecified" nil) + (string :tag "Time zone"))) + +(defcustom org-icalendar-date-time-format ":%Y%m%dT%H%M%S" + "Format-string for exporting icalendar DATE-TIME. + +See `format-time-string' for a full documentation. The only +difference is that `org-icalendar-timezone' is used for %Z. + +Interesting value are: + - \":%Y%m%dT%H%M%S\" for local time + - \";TZID=%Z:%Y%m%dT%H%M%S\" for local time with explicit timezone + - \":%Y%m%dT%H%M%SZ\" for time expressed in Universal Time" + :group 'org-export-icalendar + :version "24.1" + :type '(choice + (const :tag "Local time" ":%Y%m%dT%H%M%S") + (const :tag "Explicit local time" ";TZID=%Z:%Y%m%dT%H%M%S") + (const :tag "Universal time" ":%Y%m%dT%H%M%SZ") + (string :tag "Explicit format"))) + +(defvar org-icalendar-after-save-hook nil + "Hook run after an iCalendar file has been saved. +This hook is run with the name of the file as argument. A good +way to use this is to tell a desktop calendar application to +re-read the iCalendar file.") + + + +;;; Define Back-End + +(org-export-define-derived-backend 'icalendar 'ascii + :translate-alist '((clock . ignore) + (footnote-definition . ignore) + (footnote-reference . ignore) + (headline . org-icalendar-entry) + (inlinetask . ignore) + (planning . ignore) + (section . ignore) + (inner-template . (lambda (c i) c)) + (template . org-icalendar-template)) + :options-alist + '((:exclude-tags + "ICALENDAR_EXCLUDE_TAGS" nil org-icalendar-exclude-tags split) + (:with-timestamps nil "<" org-icalendar-with-timestamps) + ;; Other variables. + (:icalendar-alarm-time nil nil org-icalendar-alarm-time) + (:icalendar-categories nil nil org-icalendar-categories) + (:icalendar-date-time-format nil nil org-icalendar-date-time-format) + (:icalendar-include-bbdb-anniversaries nil nil org-icalendar-include-bbdb-anniversaries) + (:icalendar-include-body nil nil org-icalendar-include-body) + (:icalendar-include-sexps nil nil org-icalendar-include-sexps) + (:icalendar-include-todo nil nil org-icalendar-include-todo) + (:icalendar-store-UID nil nil org-icalendar-store-UID) + (:icalendar-timezone nil nil org-icalendar-timezone) + (:icalendar-use-deadline nil nil org-icalendar-use-deadline) + (:icalendar-use-scheduled nil nil org-icalendar-use-scheduled)) + :filters-alist + '((:filter-headline . org-icalendar-clear-blank-lines)) + :menu-entry + '(?c "Export to iCalendar" + ((?f "Current file" org-icalendar-export-to-ics) + (?a "All agenda files" + (lambda (a s v b) (org-icalendar-export-agenda-files a))) + (?c "Combine all agenda files" + (lambda (a s v b) (org-icalendar-combine-agenda-files a)))))) + + + +;;; Internal Functions + +(defun org-icalendar-create-uid (file &optional bell) + "Set ID property on headlines missing it in FILE. +When optional argument BELL is non-nil, inform the user with +a message if the file was modified." + (let (modified-flag) + (org-map-entries + (lambda () + (let ((entry (org-element-at-point))) + (unless (org-element-property :ID entry) + (org-id-get-create) + (setq modified-flag t) + (forward-line)))) + nil nil 'comment) + (when (and bell modified-flag) + (message "ID properties created in file \"%s\"" file) + (sit-for 2)))) + +(defun org-icalendar-blocked-headline-p (headline info) + "Non-nil when HEADLINE is considered to be blocked. + +INFO is a plist used as a communication channel. + +A headline is blocked when either + + - it has children which are not all in a completed state; + + - it has a parent with the property :ORDERED:, and there are + siblings prior to it with incomplete status; + + - its parent is blocked because it has siblings that should be + done first or is a child of a blocked grandparent entry." + (or + ;; Check if any child is not done. + (org-element-map headline 'headline + (lambda (hl) (eq (org-element-property :todo-type hl) 'todo)) + info 'first-match) + ;; Check :ORDERED: node property. + (catch 'blockedp + (let ((current headline)) + (dolist (parent (org-element-lineage headline)) + (cond + ((not (org-element-property :todo-keyword parent)) + (throw 'blockedp nil)) + ((org-not-nil (org-element-property :ORDERED parent)) + (let ((sibling current)) + (while (setq sibling (org-export-get-previous-element + sibling info)) + (when (eq (org-element-property :todo-type sibling) 'todo) + (throw 'blockedp t))))) + (t (setq current parent)))))))) + +(defun org-icalendar-use-UTC-date-time-p () + "Non-nil when `org-icalendar-date-time-format' requires UTC time." + (char-equal (elt org-icalendar-date-time-format + (1- (length org-icalendar-date-time-format))) ?Z)) + +(defvar org-agenda-default-appointment-duration) ; From org-agenda.el. +(defun org-icalendar-convert-timestamp (timestamp keyword &optional end tz) + "Convert TIMESTAMP to iCalendar format. + +TIMESTAMP is a timestamp object. KEYWORD is added in front of +it, in order to make a complete line (e.g. \"DTSTART\"). + +When optional argument END is non-nil, use end of time range. +Also increase the hour by two (if time string contains a time), +or the day by one (if it does not contain a time) when no +explicit ending time is specified. + +When optional argument TZ is non-nil, timezone data time will be +added to the timestamp. It can be the string \"UTC\", to use UTC +time, or a string in the IANA TZ database +format (e.g. \"Europe/London\"). In either case, the value of +`org-icalendar-date-time-format' will be ignored." + (let* ((year-start (org-element-property :year-start timestamp)) + (year-end (org-element-property :year-end timestamp)) + (month-start (org-element-property :month-start timestamp)) + (month-end (org-element-property :month-end timestamp)) + (day-start (org-element-property :day-start timestamp)) + (day-end (org-element-property :day-end timestamp)) + (hour-start (org-element-property :hour-start timestamp)) + (hour-end (org-element-property :hour-end timestamp)) + (minute-start (org-element-property :minute-start timestamp)) + (minute-end (org-element-property :minute-end timestamp)) + (with-time-p minute-start) + (equal-bounds-p + (equal (list year-start month-start day-start hour-start minute-start) + (list year-end month-end day-end hour-end minute-end))) + (mi (cond ((not with-time-p) 0) + ((not end) minute-start) + ((and org-agenda-default-appointment-duration equal-bounds-p) + (+ minute-end org-agenda-default-appointment-duration)) + (t minute-end))) + (h (cond ((not with-time-p) 0) + ((not end) hour-start) + ((or (not equal-bounds-p) + org-agenda-default-appointment-duration) + hour-end) + (t (+ hour-end 2)))) + (d (cond ((not end) day-start) + ((not with-time-p) (1+ day-end)) + (t day-end))) + (m (if end month-end month-start)) + (y (if end year-end year-start))) + (concat + keyword + (format-time-string + (cond ((string-equal tz "UTC") ":%Y%m%dT%H%M%SZ") + ((not with-time-p) ";VALUE=DATE:%Y%m%d") + ((stringp tz) (concat ";TZID=" tz ":%Y%m%dT%H%M%S")) + (t (replace-regexp-in-string "%Z" + org-icalendar-timezone + org-icalendar-date-time-format + t))) + ;; Convert timestamp into internal time in order to use + ;; `format-time-string' and fix any mistake (i.e. MI >= 60). + (encode-time 0 mi h d m y) + (and (or (string-equal tz "UTC") + (and (null tz) + with-time-p + (org-icalendar-use-UTC-date-time-p))) + t))))) + +(defun org-icalendar-dtstamp () + "Return DTSTAMP property, as a string." + (format-time-string "DTSTAMP:%Y%m%dT%H%M%SZ" nil t)) + +(defun org-icalendar-get-categories (entry info) + "Return categories according to `org-icalendar-categories'. +ENTRY is a headline or an inlinetask element. INFO is a plist +used as a communication channel." + (mapconcat + #'identity + (org-uniquify + (let (categories) + (dolist (type org-icalendar-categories (nreverse categories)) + (cl-case type + (category + (push (org-export-get-category entry info) categories)) + (todo-state + (let ((todo (org-element-property :todo-keyword entry))) + (and todo (push todo categories)))) + (local-tags + (setq categories + (append (nreverse (org-export-get-tags entry info)) + categories))) + (all-tags + (setq categories + (append (nreverse (org-export-get-tags entry info nil t)) + categories))))))) + ",")) + +(defun org-icalendar-transcode-diary-sexp (sexp uid summary) + "Transcode a diary sexp into iCalendar format. +SEXP is the diary sexp being transcoded, as a string. UID is the +unique identifier for the entry. SUMMARY defines a short summary +or subject for the event." + (when (require 'icalendar nil t) + (org-element-normalize-string + (with-temp-buffer + (let ((sexp (if (not (string-match "\\`<%%" sexp)) sexp + (concat (substring sexp 1 -1) " " summary)))) + (put-text-property 0 1 'uid uid sexp) + (insert sexp "\n")) + (org-diary-to-ical-string (current-buffer)))))) + +(defun org-icalendar-cleanup-string (s) + "Cleanup string S according to RFC 5545." + (when s + ;; Protect "\", "," and ";" characters. and replace newline + ;; characters with literal \n. + (replace-regexp-in-string + "[ \t]*\n" "\\n" + (replace-regexp-in-string "[\\,;]" "\\\\\\&" s) + nil t))) + +(defun org-icalendar-fold-string (s) + "Fold string S according to RFC 5545." + (org-element-normalize-string + (mapconcat + (lambda (line) + ;; Limit each line to a maximum of 75 characters. If it is + ;; longer, fold it by using "\r\n " as a continuation marker. + (let ((len (length line))) + (if (<= len 75) line + (let ((folded-line (substring line 0 75)) + (chunk-start 75) + chunk-end) + ;; Since continuation marker takes up one character on the + ;; line, real contents must be split at 74 chars. + (while (< (setq chunk-end (+ chunk-start 74)) len) + (setq folded-line + (concat folded-line "\r\n " + (substring line chunk-start chunk-end)) + chunk-start chunk-end)) + (concat folded-line "\r\n " (substring line chunk-start)))))) + (org-split-string s "\n") "\r\n"))) + + + +;;; Filters + +(defun org-icalendar-clear-blank-lines (headline _back-end _info) + "Remove blank lines in HEADLINE export. +HEADLINE is a string representing a transcoded headline. +BACK-END and INFO are ignored." + (replace-regexp-in-string "^\\(?:[ \t]*\n\\)+" "" headline)) + + + +;;; Transcode Functions + +;;;; Headline and Inlinetasks + +;; The main function is `org-icalendar-entry', which extracts +;; information from a headline or an inlinetask (summary, +;; description...) and then delegates code generation to +;; `org-icalendar--vtodo' and `org-icalendar--vevent', depending +;; on the component needed. + +;; Obviously, `org-icalendar--valarm' handles alarms, which can +;; happen within a VTODO component. + +(defun org-icalendar-entry (entry contents info) + "Transcode ENTRY element into iCalendar format. + +ENTRY is either a headline or an inlinetask. CONTENTS is +ignored. INFO is a plist used as a communication channel. + +This function is called on every headline, the section below +it (minus inlinetasks) being its contents. It tries to create +VEVENT and VTODO components out of scheduled date, deadline date, +plain timestamps, diary sexps. It also calls itself on every +inlinetask within the section." + (unless (org-element-property :footnote-section-p entry) + (let* ((type (org-element-type entry)) + ;; Determine contents really associated to the entry. For + ;; a headline, limit them to section, if any. For an + ;; inlinetask, this is every element within the task. + (inside + (if (eq type 'inlinetask) + (cons 'org-data (cons nil (org-element-contents entry))) + (let ((first (car (org-element-contents entry)))) + (and (eq (org-element-type first) 'section) + (cons 'org-data + (cons nil (org-element-contents first)))))))) + (concat + (let ((todo-type (org-element-property :todo-type entry)) + (uid (or (org-element-property :ID entry) (org-id-new))) + (summary (org-icalendar-cleanup-string + (or (org-element-property :SUMMARY entry) + (org-export-data + (org-element-property :title entry) info)))) + (loc (org-icalendar-cleanup-string + (org-export-get-node-property + :LOCATION entry + (org-property-inherit-p "LOCATION")))) + ;; Build description of the entry from associated section + ;; (headline) or contents (inlinetask). + (desc + (org-icalendar-cleanup-string + (or (org-element-property :DESCRIPTION entry) + (let ((contents (org-export-data inside info))) + (cond + ((not (org-string-nw-p contents)) nil) + ((wholenump org-icalendar-include-body) + (let ((contents (org-trim contents))) + (substring + contents 0 (min (length contents) + org-icalendar-include-body)))) + (org-icalendar-include-body (org-trim contents))))))) + (cat (org-icalendar-get-categories entry info)) + (tz (org-export-get-node-property + :TIMEZONE entry + (org-property-inherit-p "TIMEZONE")))) + (concat + ;; Events: Delegate to `org-icalendar--vevent' to generate + ;; "VEVENT" component from scheduled, deadline, or any + ;; timestamp in the entry. + (let ((deadline (org-element-property :deadline entry))) + (and deadline + (memq (if todo-type 'event-if-todo 'event-if-not-todo) + org-icalendar-use-deadline) + (org-icalendar--vevent + entry deadline (concat "DL-" uid) + (concat "DL: " summary) loc desc cat tz))) + (let ((scheduled (org-element-property :scheduled entry))) + (and scheduled + (memq (if todo-type 'event-if-todo 'event-if-not-todo) + org-icalendar-use-scheduled) + (org-icalendar--vevent + entry scheduled (concat "SC-" uid) + (concat "S: " summary) loc desc cat tz))) + ;; When collecting plain timestamps from a headline and its + ;; title, skip inlinetasks since collection will happen once + ;; ENTRY is one of them. + (let ((counter 0)) + (mapconcat + #'identity + (org-element-map (cons (org-element-property :title entry) + (org-element-contents inside)) + 'timestamp + (lambda (ts) + (when (let ((type (org-element-property :type ts))) + (cl-case (plist-get info :with-timestamps) + (active (memq type '(active active-range))) + (inactive (memq type '(inactive inactive-range))) + ((t) t))) + (let ((uid (format "TS%d-%s" (cl-incf counter) uid))) + (org-icalendar--vevent + entry ts uid summary loc desc cat tz)))) + info nil (and (eq type 'headline) 'inlinetask)) + "")) + ;; Task: First check if it is appropriate to export it. If + ;; so, call `org-icalendar--vtodo' to transcode it into + ;; a "VTODO" component. + (when (and todo-type + (cl-case (plist-get info :icalendar-include-todo) + (all t) + (unblocked + (and (eq type 'headline) + (not (org-icalendar-blocked-headline-p + entry info)))) + ((t) (eq todo-type 'todo)))) + (org-icalendar--vtodo entry uid summary loc desc cat tz)) + ;; Diary-sexp: Collect every diary-sexp element within ENTRY + ;; and its title, and transcode them. If ENTRY is + ;; a headline, skip inlinetasks: they will be handled + ;; separately. + (when org-icalendar-include-sexps + (let ((counter 0)) + (mapconcat #'identity + (org-element-map + (cons (org-element-property :title entry) + (org-element-contents inside)) + 'diary-sexp + (lambda (sexp) + (org-icalendar-transcode-diary-sexp + (org-element-property :value sexp) + (format "DS%d-%s" (cl-incf counter) uid) + summary)) + info nil (and (eq type 'headline) 'inlinetask)) + ""))))) + ;; If ENTRY is a headline, call current function on every + ;; inlinetask within it. In agenda export, this is independent + ;; from the mark (or lack thereof) on the entry. + (when (eq type 'headline) + (mapconcat #'identity + (org-element-map inside 'inlinetask + (lambda (task) (org-icalendar-entry task nil info)) + info) "")) + ;; Don't forget components from inner entries. + contents)))) + +(defun org-icalendar--vevent + (entry timestamp uid summary location description categories timezone) + "Create a VEVENT component. + +ENTRY is either a headline or an inlinetask element. TIMESTAMP +is a timestamp object defining the date-time of the event. UID +is the unique identifier for the event. SUMMARY defines a short +summary or subject for the event. LOCATION defines the intended +venue for the event. DESCRIPTION provides the complete +description of the event. CATEGORIES defines the categories the +event belongs to. TIMEZONE specifies a time zone for this event +only. + +Return VEVENT component as a string." + (org-icalendar-fold-string + (if (eq (org-element-property :type timestamp) 'diary) + (org-icalendar-transcode-diary-sexp + (org-element-property :raw-value timestamp) uid summary) + (concat "BEGIN:VEVENT\n" + (org-icalendar-dtstamp) "\n" + "UID:" uid "\n" + (org-icalendar-convert-timestamp timestamp "DTSTART" nil timezone) "\n" + (org-icalendar-convert-timestamp timestamp "DTEND" t timezone) "\n" + ;; RRULE. + (when (org-element-property :repeater-type timestamp) + (format "RRULE:FREQ=%s;INTERVAL=%d\n" + (cl-case (org-element-property :repeater-unit timestamp) + (hour "HOURLY") (day "DAILY") (week "WEEKLY") + (month "MONTHLY") (year "YEARLY")) + (org-element-property :repeater-value timestamp))) + "SUMMARY:" summary "\n" + (and (org-string-nw-p location) (format "LOCATION:%s\n" location)) + (and (org-string-nw-p description) + (format "DESCRIPTION:%s\n" description)) + "CATEGORIES:" categories "\n" + ;; VALARM. + (org-icalendar--valarm entry timestamp summary) + "END:VEVENT")))) + +(defun org-icalendar--vtodo + (entry uid summary location description categories timezone) + "Create a VTODO component. + +ENTRY is either a headline or an inlinetask element. UID is the +unique identifier for the task. SUMMARY defines a short summary +or subject for the task. LOCATION defines the intended venue for +the task. DESCRIPTION provides the complete description of the +task. CATEGORIES defines the categories the task belongs to. +TIMEZONE specifies a time zone for this TODO only. + +Return VTODO component as a string." + (let ((start (or (and (memq 'todo-start org-icalendar-use-scheduled) + (org-element-property :scheduled entry)) + ;; If we can't use a scheduled time for some + ;; reason, start task now. + (let ((now (decode-time))) + (list 'timestamp + (list :type 'active + :minute-start (nth 1 now) + :hour-start (nth 2 now) + :day-start (nth 3 now) + :month-start (nth 4 now) + :year-start (nth 5 now))))))) + (org-icalendar-fold-string + (concat "BEGIN:VTODO\n" + "UID:TODO-" uid "\n" + (org-icalendar-dtstamp) "\n" + (org-icalendar-convert-timestamp start "DTSTART" nil timezone) "\n" + (and (memq 'todo-due org-icalendar-use-deadline) + (org-element-property :deadline entry) + (concat (org-icalendar-convert-timestamp + (org-element-property :deadline entry) "DUE" nil timezone) + "\n")) + "SUMMARY:" summary "\n" + (and (org-string-nw-p location) (format "LOCATION:%s\n" location)) + (and (org-string-nw-p description) + (format "DESCRIPTION:%s\n" description)) + "CATEGORIES:" categories "\n" + "SEQUENCE:1\n" + (format "PRIORITY:%d\n" + (let ((pri (or (org-element-property :priority entry) + org-default-priority))) + (floor (- 9 (* 8. (/ (float (- org-lowest-priority pri)) + (- org-lowest-priority + org-highest-priority))))))) + (format "STATUS:%s\n" + (if (eq (org-element-property :todo-type entry) 'todo) + "NEEDS-ACTION" + "COMPLETED")) + "END:VTODO")))) + +(defun org-icalendar--valarm (entry timestamp summary) + "Create a VALARM component. + +ENTRY is the calendar entry triggering the alarm. TIMESTAMP is +the start date-time of the entry. SUMMARY defines a short +summary or subject for the task. + +Return VALARM component as a string, or nil if it isn't allowed." + ;; Create a VALARM entry if the entry is timed. This is not very + ;; general in that: + ;; (a) only one alarm per entry is defined, + ;; (b) only minutes are allowed for the trigger period ahead of the + ;; start time, + ;; (c) only a DISPLAY action is defined. [ESF] + (let ((alarm-time + (let ((warntime + (org-element-property :APPT_WARNTIME entry))) + (if warntime (string-to-number warntime) 0)))) + (and (or (> alarm-time 0) (> org-icalendar-alarm-time 0)) + (org-element-property :hour-start timestamp) + (format "BEGIN:VALARM +ACTION:DISPLAY +DESCRIPTION:%s +TRIGGER:-P0DT0H%dM0S +END:VALARM\n" + summary + (if (zerop alarm-time) org-icalendar-alarm-time alarm-time))))) + + +;;;; Template + +(defun org-icalendar-template (contents info) + "Return complete document string after iCalendar conversion. +CONTENTS is the transcoded contents string. INFO is a plist used +as a communication channel." + (org-icalendar--vcalendar + ;; Name. + (if (not (plist-get info :input-file)) (buffer-name (buffer-base-buffer)) + (file-name-nondirectory + (file-name-sans-extension (plist-get info :input-file)))) + ;; Owner. + (if (not (plist-get info :with-author)) "" + (org-export-data (plist-get info :author) info)) + ;; Timezone. + (if (org-string-nw-p org-icalendar-timezone) org-icalendar-timezone + (cadr (current-time-zone))) + ;; Description. + (org-export-data (plist-get info :title) info) + contents)) + +(defun org-icalendar--vcalendar (name owner tz description contents) + "Create a VCALENDAR component. +NAME, OWNER, TZ, DESCRIPTION and CONTENTS are all strings giving, +respectively, the name of the calendar, its owner, the timezone +used, a short description and the other components included." + (concat (format "BEGIN:VCALENDAR +VERSION:2.0 +X-WR-CALNAME:%s +PRODID:-//%s//Emacs with Org mode//EN +X-WR-TIMEZONE:%s +X-WR-CALDESC:%s +CALSCALE:GREGORIAN\n" + (org-icalendar-cleanup-string name) + (org-icalendar-cleanup-string owner) + (org-icalendar-cleanup-string tz) + (org-icalendar-cleanup-string description)) + contents + "END:VCALENDAR\n")) + + + +;;; Interactive Functions + +;;;###autoload +(defun org-icalendar-export-to-ics + (&optional async subtreep visible-only body-only) + "Export current buffer to an iCalendar file. + +If narrowing is active in the current buffer, only export its +narrowed part. + +If a region is active, export that region. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +When optional argument SUBTREEP is non-nil, export the sub-tree +at point, extracting information from the headline properties +first. + +When optional argument VISIBLE-ONLY is non-nil, don't export +contents of hidden elements. + +When optional argument BODY-ONLY is non-nil, only write code +between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\". + +Return ICS file name." + (interactive) + (let ((file (buffer-file-name (buffer-base-buffer)))) + (when (and file org-icalendar-store-UID) + (org-icalendar-create-uid file 'warn-user))) + ;; Export part. Since this back-end is backed up by `ascii', ensure + ;; links will not be collected at the end of sections. + (let ((outfile (org-export-output-file-name ".ics" subtreep))) + (org-export-to-file 'icalendar outfile + async subtreep visible-only body-only + '(:ascii-charset utf-8 :ascii-links-to-notes nil) + (lambda (file) + (run-hook-with-args 'org-icalendar-after-save-hook file) nil)))) + +;;;###autoload +(defun org-icalendar-export-agenda-files (&optional async) + "Export all agenda files to iCalendar files. +When optional argument ASYNC is non-nil, export happens in an +external process." + (interactive) + (if async + ;; Asynchronous export is not interactive, so we will not call + ;; `org-check-agenda-file'. Instead we remove any non-existent + ;; agenda file from the list. + (let ((files (cl-remove-if-not #'file-exists-p (org-agenda-files t)))) + (org-export-async-start + (lambda (results) + (dolist (f results) (org-export-add-to-stack f 'icalendar))) + `(let (output-files) + (dolist (file ',files outputfiles) + (with-current-buffer (org-get-agenda-file-buffer file) + (push (expand-file-name (org-icalendar-export-to-ics)) + output-files)))))) + (let ((files (org-agenda-files t))) + (org-agenda-prepare-buffers files) + (unwind-protect + (dolist (file files) + (catch 'nextfile + (org-check-agenda-file file) + (with-current-buffer (org-get-agenda-file-buffer file) + (org-icalendar-export-to-ics)))) + (org-release-buffers org-agenda-new-buffers))))) + +;;;###autoload +(defun org-icalendar-combine-agenda-files (&optional async) + "Combine all agenda files into a single iCalendar file. + +A non-nil optional argument ASYNC means the process should happen +asynchronously. The resulting file should be accessible through +the `org-export-stack' interface. + +The file is stored under the name chosen in +`org-icalendar-combined-agenda-file'." + (interactive) + (if async + (let ((files (cl-remove-if-not #'file-exists-p (org-agenda-files t)))) + (org-export-async-start + (lambda (_) + (org-export-add-to-stack + (expand-file-name org-icalendar-combined-agenda-file) + 'icalendar)) + `(apply #'org-icalendar--combine-files ',files))) + (apply #'org-icalendar--combine-files (org-agenda-files t)))) + +(defun org-icalendar-export-current-agenda (file) + "Export current agenda view to an iCalendar FILE. +This function assumes major mode for current buffer is +`org-agenda-mode'." + (let* ((org-export-use-babel) ;don't evaluate Babel blocks + (contents + (org-export-string-as + (with-output-to-string + (save-excursion + (let ((p (point-min)) + (seen nil)) ;prevent duplicates + (while (setq p (next-single-property-change p 'org-hd-marker)) + (let ((m (get-text-property p 'org-hd-marker))) + (when (and m (not (member m seen))) + (push m seen) + (with-current-buffer (marker-buffer m) + (org-with-wide-buffer + (goto-char (marker-position m)) + (princ + (org-element-normalize-string + (buffer-substring (point) + (org-entry-end-position)))))))) + (forward-line))))) + 'icalendar t + '(:ascii-charset utf-8 :ascii-links-to-notes nil + :icalendar-include-todo all)))) + (with-temp-file file + (insert + (org-icalendar--vcalendar + org-icalendar-combined-name + user-full-name + (or (org-string-nw-p org-icalendar-timezone) (cadr (current-time-zone))) + org-icalendar-combined-description + contents))) + (run-hook-with-args 'org-icalendar-after-save-hook file))) + +(defun org-icalendar--combine-files (&rest files) + "Combine entries from multiple files into an iCalendar file. +FILES is a list of files to build the calendar from." + ;; At the end of the process, all buffers related to FILES are going + ;; to be killed. Make sure to only kill the ones opened in the + ;; process. + (let ((org-agenda-new-buffers nil)) + (unwind-protect + (progn + (with-temp-file org-icalendar-combined-agenda-file + (insert + (org-icalendar--vcalendar + ;; Name. + org-icalendar-combined-name + ;; Owner. + user-full-name + ;; Timezone. + (or (org-string-nw-p org-icalendar-timezone) + (cadr (current-time-zone))) + ;; Description. + org-icalendar-combined-description + ;; Contents. + (concat + ;; Agenda contents. + (mapconcat + (lambda (file) + (catch 'nextfile + (org-check-agenda-file file) + (with-current-buffer (org-get-agenda-file-buffer file) + ;; Create ID if necessary. + (when org-icalendar-store-UID + (org-icalendar-create-uid file t)) + (org-export-as + 'icalendar nil nil t + '(:ascii-charset utf-8 :ascii-links-to-notes nil))))) + files "") + ;; BBDB anniversaries. + (when (and org-icalendar-include-bbdb-anniversaries + (require 'org-bbdb nil t)) + (with-output-to-string (org-bbdb-anniv-export-ical))))))) + (run-hook-with-args 'org-icalendar-after-save-hook + org-icalendar-combined-agenda-file)) + (org-release-buffers org-agenda-new-buffers)))) + + +(provide 'ox-icalendar) + +;; Local variables: +;; generated-autoload-file: "org-loaddefs.el" +;; End: + +;;; ox-icalendar.el ends here diff --git a/elpa/org-9.1.14/ox-latex.el b/elpa/org-9.1.14/ox-latex.el new file mode 100644 index 00000000..5aaaf991 --- /dev/null +++ b/elpa/org-9.1.14/ox-latex.el @@ -0,0 +1,3756 @@ +;;; ox-latex.el --- LaTeX Back-End for Org Export Engine -*- lexical-binding: t; -*- + +;; Copyright (C) 2011-2018 Free Software Foundation, Inc. + +;; Author: Nicolas Goaziou +;; Keywords: outlines, hypermedia, calendar, wp + +;; This file is part of GNU Emacs. + +;; GNU Emacs 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 of the License, or +;; (at your option) any later version. + +;; GNU Emacs 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 . + +;;; Commentary: +;; +;; See Org manual for details. + +;;; Code: + +(require 'cl-lib) +(require 'ox) +(require 'ox-publish) + +(defvar org-latex-default-packages-alist) +(defvar org-latex-packages-alist) +(defvar orgtbl-exp-regexp) + + + +;;; Define Back-End + +(org-export-define-backend 'latex + '((bold . org-latex-bold) + (center-block . org-latex-center-block) + (clock . org-latex-clock) + (code . org-latex-code) + (drawer . org-latex-drawer) + (dynamic-block . org-latex-dynamic-block) + (entity . org-latex-entity) + (example-block . org-latex-example-block) + (export-block . org-latex-export-block) + (export-snippet . org-latex-export-snippet) + (fixed-width . org-latex-fixed-width) + (footnote-definition . org-latex-footnote-definition) + (footnote-reference . org-latex-footnote-reference) + (headline . org-latex-headline) + (horizontal-rule . org-latex-horizontal-rule) + (inline-src-block . org-latex-inline-src-block) + (inlinetask . org-latex-inlinetask) + (italic . org-latex-italic) + (item . org-latex-item) + (keyword . org-latex-keyword) + (latex-environment . org-latex-latex-environment) + (latex-fragment . org-latex-latex-fragment) + (line-break . org-latex-line-break) + (link . org-latex-link) + (node-property . org-latex-node-property) + (paragraph . org-latex-paragraph) + (plain-list . org-latex-plain-list) + (plain-text . org-latex-plain-text) + (planning . org-latex-planning) + (property-drawer . org-latex-property-drawer) + (quote-block . org-latex-quote-block) + (radio-target . org-latex-radio-target) + (section . org-latex-section) + (special-block . org-latex-special-block) + (src-block . org-latex-src-block) + (statistics-cookie . org-latex-statistics-cookie) + (strike-through . org-latex-strike-through) + (subscript . org-latex-subscript) + (superscript . org-latex-superscript) + (table . org-latex-table) + (table-cell . org-latex-table-cell) + (table-row . org-latex-table-row) + (target . org-latex-target) + (template . org-latex-template) + (timestamp . org-latex-timestamp) + (underline . org-latex-underline) + (verbatim . org-latex-verbatim) + (verse-block . org-latex-verse-block) + ;; Pseudo objects and elements. + (latex-math-block . org-latex-math-block) + (latex-matrices . org-latex-matrices)) + :menu-entry + '(?l "Export to LaTeX" + ((?L "As LaTeX buffer" org-latex-export-as-latex) + (?l "As LaTeX file" org-latex-export-to-latex) + (?p "As PDF file" org-latex-export-to-pdf) + (?o "As PDF file and open" + (lambda (a s v b) + (if a (org-latex-export-to-pdf t s v b) + (org-open-file (org-latex-export-to-pdf nil s v b))))))) + :filters-alist '((:filter-options . org-latex-math-block-options-filter) + (:filter-paragraph . org-latex-clean-invalid-line-breaks) + (:filter-parse-tree org-latex-math-block-tree-filter + org-latex-matrices-tree-filter + org-latex-image-link-filter) + (:filter-verse-block . org-latex-clean-invalid-line-breaks)) + :options-alist + '((:latex-class "LATEX_CLASS" nil org-latex-default-class t) + (:latex-class-options "LATEX_CLASS_OPTIONS" nil nil t) + (:latex-header "LATEX_HEADER" nil nil newline) + (:latex-header-extra "LATEX_HEADER_EXTRA" nil nil newline) + (:description "DESCRIPTION" nil nil parse) + (:keywords "KEYWORDS" nil nil parse) + (:subtitle "SUBTITLE" nil nil parse) + ;; Other variables. + (:latex-active-timestamp-format nil nil org-latex-active-timestamp-format) + (:latex-caption-above nil nil org-latex-caption-above) + (:latex-classes nil nil org-latex-classes) + (:latex-default-figure-position nil nil org-latex-default-figure-position) + (:latex-default-table-environment nil nil org-latex-default-table-environment) + (:latex-default-table-mode nil nil org-latex-default-table-mode) + (:latex-diary-timestamp-format nil nil org-latex-diary-timestamp-format) + (:latex-footnote-defined-format nil nil org-latex-footnote-defined-format) + (:latex-footnote-separator nil nil org-latex-footnote-separator) + (:latex-format-drawer-function nil nil org-latex-format-drawer-function) + (:latex-format-headline-function nil nil org-latex-format-headline-function) + (:latex-format-inlinetask-function nil nil org-latex-format-inlinetask-function) + (:latex-hyperref-template nil nil org-latex-hyperref-template t) + (:latex-image-default-height nil nil org-latex-image-default-height) + (:latex-image-default-option nil nil org-latex-image-default-option) + (:latex-image-default-width nil nil org-latex-image-default-width) + (:latex-images-centered nil nil org-latex-images-centered) + (:latex-inactive-timestamp-format nil nil org-latex-inactive-timestamp-format) + (:latex-inline-image-rules nil nil org-latex-inline-image-rules) + (:latex-link-with-unknown-path-format nil nil org-latex-link-with-unknown-path-format) + (:latex-listings nil nil org-latex-listings) + (:latex-listings-langs nil nil org-latex-listings-langs) + (:latex-listings-options nil nil org-latex-listings-options) + (:latex-minted-langs nil nil org-latex-minted-langs) + (:latex-minted-options nil nil org-latex-minted-options) + (:latex-prefer-user-labels nil nil org-latex-prefer-user-labels) + (:latex-subtitle-format nil nil org-latex-subtitle-format) + (:latex-subtitle-separate nil nil org-latex-subtitle-separate) + (:latex-table-scientific-notation nil nil org-latex-table-scientific-notation) + (:latex-tables-booktabs nil nil org-latex-tables-booktabs) + (:latex-tables-centered nil nil org-latex-tables-centered) + (:latex-text-markup-alist nil nil org-latex-text-markup-alist) + (:latex-title-command nil nil org-latex-title-command) + (:latex-toc-command nil nil org-latex-toc-command) + (:latex-compiler "LATEX_COMPILER" nil org-latex-compiler) + ;; Redefine regular options. + (:date "DATE" nil "\\today" parse))) + + + +;;; Internal Variables + +(defconst org-latex-babel-language-alist + '(("af" . "afrikaans") + ("bg" . "bulgarian") + ("bt-br" . "brazilian") + ("ca" . "catalan") + ("cs" . "czech") + ("cy" . "welsh") + ("da" . "danish") + ("de" . "germanb") + ("de-at" . "naustrian") + ("de-de" . "ngerman") + ("el" . "greek") + ("en" . "english") + ("en-au" . "australian") + ("en-ca" . "canadian") + ("en-gb" . "british") + ("en-ie" . "irish") + ("en-nz" . "newzealand") + ("en-us" . "american") + ("es" . "spanish") + ("et" . "estonian") + ("eu" . "basque") + ("fi" . "finnish") + ("fr" . "frenchb") + ("fr-ca" . "canadien") + ("gl" . "galician") + ("hr" . "croatian") + ("hu" . "hungarian") + ("id" . "indonesian") + ("is" . "icelandic") + ("it" . "italian") + ("la" . "latin") + ("ms" . "malay") + ("nl" . "dutch") + ("nb" . "norsk") + ("nn" . "nynorsk") + ("no" . "norsk") + ("pl" . "polish") + ("pt" . "portuguese") + ("ro" . "romanian") + ("ru" . "russian") + ("sa" . "sanskrit") + ("sb" . "uppersorbian") + ("sk" . "slovak") + ("sl" . "slovene") + ("sq" . "albanian") + ("sr" . "serbian") + ("sv" . "swedish") + ("ta" . "tamil") + ("tr" . "turkish") + ("uk" . "ukrainian")) + "Alist between language code and corresponding Babel option.") + +(defconst org-latex-polyglossia-language-alist + '(("am" "amharic") + ("ast" "asturian") + ("ar" "arabic") + ("bo" "tibetan") + ("bn" "bengali") + ("bg" "bulgarian") + ("br" "breton") + ("bt-br" "brazilian") + ("ca" "catalan") + ("cop" "coptic") + ("cs" "czech") + ("cy" "welsh") + ("da" "danish") + ("de" "german" "german") + ("de-at" "german" "austrian") + ("de-de" "german" "german") + ("dv" "divehi") + ("el" "greek") + ("en" "english" "usmax") + ("en-au" "english" "australian") + ("en-gb" "english" "uk") + ("en-nz" "english" "newzealand") + ("en-us" "english" "usmax") + ("eo" "esperanto") + ("es" "spanish") + ("et" "estonian") + ("eu" "basque") + ("fa" "farsi") + ("fi" "finnish") + ("fr" "french") + ("fu" "friulan") + ("ga" "irish") + ("gd" "scottish") + ("gl" "galician") + ("he" "hebrew") + ("hi" "hindi") + ("hr" "croatian") + ("hu" "magyar") + ("hy" "armenian") + ("id" "bahasai") + ("ia" "interlingua") + ("is" "icelandic") + ("it" "italian") + ("kn" "kannada") + ("la" "latin" "modern") + ("la-modern" "latin" "modern") + ("la-classic" "latin" "classic") + ("la-medieval" "latin" "medieval") + ("lo" "lao") + ("lt" "lithuanian") + ("lv" "latvian") + ("mr" "maranthi") + ("ml" "malayalam") + ("nl" "dutch") + ("nb" "norsk") + ("nn" "nynorsk") + ("nko" "nko") + ("no" "norsk") + ("oc" "occitan") + ("pl" "polish") + ("pms" "piedmontese") + ("pt" "portuges") + ("rm" "romansh") + ("ro" "romanian") + ("ru" "russian") + ("sa" "sanskrit") + ("hsb" "usorbian") + ("dsb" "lsorbian") + ("sk" "slovak") + ("sl" "slovenian") + ("se" "samin") + ("sq" "albanian") + ("sr" "serbian") + ("sv" "swedish") + ("syr" "syriac") + ("ta" "tamil") + ("te" "telugu") + ("th" "thai") + ("tk" "turkmen") + ("tr" "turkish") + ("uk" "ukrainian") + ("ur" "urdu") + ("vi" "vietnamese")) + "Alist between language code and corresponding Polyglossia option") + + + +(defconst org-latex-table-matrix-macros '(("bordermatrix" . "\\cr") + ("qbordermatrix" . "\\cr") + ("kbordermatrix" . "\\\\")) + "Alist between matrix macros and their row ending.") + +(defconst org-latex-math-environments-re + (format + "\\`[ \t]*\\\\begin{%s\\*?}" + (regexp-opt + '("equation" "eqnarray" "math" "displaymath" + "align" "gather" "multline" "flalign" "alignat" + "xalignat" "xxalignat" + "subequations" + ;; breqn + "dmath" "dseries" "dgroup" "darray" + ;; empheq + "empheq"))) + "Regexp of LaTeX math environments.") + + +;;; User Configurable Variables + +(defgroup org-export-latex nil + "Options for exporting Org mode files to LaTeX." + :tag "Org Export LaTeX" + :group 'org-export) + +;;;; Generic + +(defcustom org-latex-caption-above '(table) + "When non-nil, place caption string at the beginning of elements. +Otherwise, place it near the end. When value is a list of +symbols, put caption above selected elements only. Allowed +symbols are: `image', `table', `src-block' and `special-block'." + :group 'org-export-latex + :version "26.1" + :package-version '(Org . "8.3") + :type '(choice + (const :tag "For all elements" t) + (const :tag "For no element" nil) + (set :tag "For the following elements only" :greedy t + (const :tag "Images" image) + (const :tag "Tables" table) + (const :tag "Source code" src-block) + (const :tag "Special blocks" special-block)))) + +(defcustom org-latex-prefer-user-labels nil + "Use user-provided labels instead of internal ones when non-nil. + +When this variable is non-nil, Org will use the value of +CUSTOM_ID property, NAME keyword or Org target as the key for the +\\label commands generated. + +By default, Org generates its own internal labels during LaTeX +export. This process ensures that the \\label keys are unique +and valid, but it means the keys are not available in advance of +the export process. + +Setting this variable gives you control over how Org generates +labels during LaTeX export, so that you may know their keys in +advance. One reason to do this is that it allows you to refer to +various elements using a single label both in Org's link syntax +and in embedded LaTeX code. + +For example, when this variable is non-nil, a headline like this: + + ** Some section + :PROPERTIES: + :CUSTOM_ID: sec:foo + :END: + This is section [[#sec:foo]]. + #+BEGIN_EXPORT latex + And this is still section \\ref{sec:foo}. + #+END_EXPORT + +will be exported to LaTeX as: + + \\subsection{Some section} + \\label{sec:foo} + This is section \\ref{sec:foo}. + And this is still section \\ref{sec:foo}. + +Note, however, that setting this variable introduces a limitation +on the possible values for CUSTOM_ID and NAME. When this +variable is non-nil, Org passes their value to \\label unchanged. +You are responsible for ensuring that the value is a valid LaTeX +\\label key, and that no other \\label commands with the same key +appear elsewhere in your document. (Keys may contain letters, +numbers, and the following punctuation: '_' '.' '-' ':'.) There +are no such limitations on CUSTOM_ID and NAME when this variable +is nil. + +For headlines that do not define the CUSTOM_ID property or +elements without a NAME, Org will continue to use its default +labeling scheme to generate labels and resolve links into proper +references." + :group 'org-export-latex + :type 'boolean + :version "26.1" + :package-version '(Org . "8.3")) + +;;;; Preamble + +(defcustom org-latex-default-class "article" + "The default LaTeX class." + :group 'org-export-latex + :type '(string :tag "LaTeX class")) + +(defcustom org-latex-classes + '(("article" + "\\documentclass[11pt]{article}" + ("\\section{%s}" . "\\section*{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}") + ("\\paragraph{%s}" . "\\paragraph*{%s}") + ("\\subparagraph{%s}" . "\\subparagraph*{%s}")) + ("report" + "\\documentclass[11pt]{report}" + ("\\part{%s}" . "\\part*{%s}") + ("\\chapter{%s}" . "\\chapter*{%s}") + ("\\section{%s}" . "\\section*{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}")) + ("book" + "\\documentclass[11pt]{book}" + ("\\part{%s}" . "\\part*{%s}") + ("\\chapter{%s}" . "\\chapter*{%s}") + ("\\section{%s}" . "\\section*{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))) + "Alist of LaTeX classes and associated header and structure. +If #+LATEX_CLASS is set in the buffer, use its value and the +associated information. Here is the structure of each cell: + + (class-name + header-string + (numbered-section . unnumbered-section) + ...) + +The header string +----------------- + +The HEADER-STRING is the header that will be inserted into the +LaTeX file. It should contain the \\documentclass macro, and +anything else that is needed for this setup. To this header, the +following commands will be added: + +- Calls to \\usepackage for all packages mentioned in the + variables `org-latex-default-packages-alist' and + `org-latex-packages-alist'. Thus, your header definitions + should avoid to also request these packages. + +- Lines specified via \"#+LATEX_HEADER:\" and + \"#+LATEX_HEADER_EXTRA:\" keywords. + +If you need more control about the sequence in which the header +is built up, or if you want to exclude one of these building +blocks for a particular class, you can use the following +macro-like placeholders. + + [DEFAULT-PACKAGES] \\usepackage statements for default packages + [NO-DEFAULT-PACKAGES] do not include any of the default packages + [PACKAGES] \\usepackage statements for packages + [NO-PACKAGES] do not include the packages + [EXTRA] the stuff from #+LATEX_HEADER(_EXTRA) + [NO-EXTRA] do not include #+LATEX_HEADER(_EXTRA) stuff + +So a header like + + \\documentclass{article} + [NO-DEFAULT-PACKAGES] + [EXTRA] + \\providecommand{\\alert}[1]{\\textbf{#1}} + [PACKAGES] + +will omit the default packages, and will include the +#+LATEX_HEADER and #+LATEX_HEADER_EXTRA lines, then have a call +to \\providecommand, and then place \\usepackage commands based +on the content of `org-latex-packages-alist'. + +If your header, `org-latex-default-packages-alist' or +`org-latex-packages-alist' inserts \"\\usepackage[AUTO]{inputenc}\", +AUTO will automatically be replaced with a coding system derived +from `buffer-file-coding-system'. See also the variable +`org-latex-inputenc-alist' for a way to influence this mechanism. + +Likewise, if your header contains \"\\usepackage[AUTO]{babel}\" +or \"\\usepackage[AUTO]{polyglossia}\", AUTO will be replaced +with the language related to the language code specified by +`org-export-default-language'. Note that constructions such as +\"\\usepackage[french,AUTO,english]{babel}\" are permitted. For +Polyglossia the language will be set via the macros +\"\\setmainlanguage\" and \"\\setotherlanguage\". See also +`org-latex-guess-babel-language' and +`org-latex-guess-polyglossia-language'. + +The sectioning structure +------------------------ + +The sectioning structure of the class is given by the elements +following the header string. For each sectioning level, a number +of strings is specified. A %s formatter is mandatory in each +section string and will be replaced by the title of the section. + +Instead of a cons cell (numbered . unnumbered), you can also +provide a list of 2 or 4 elements, + + (numbered-open numbered-close) + +or + + (numbered-open numbered-close unnumbered-open unnumbered-close) + +providing opening and closing strings for a LaTeX environment +that should represent the document section. The opening clause +should have a %s to represent the section title. + +Instead of a list of sectioning commands, you can also specify +a function name. That function will be called with two +parameters, the (reduced) level of the headline, and a predicate +non-nil when the headline should be numbered. It must return +a format string in which the section title will be added." + :group 'org-export-latex + :type '(repeat + (list (string :tag "LaTeX class") + (string :tag "LaTeX header") + (repeat :tag "Levels" :inline t + (choice + (cons :tag "Heading" + (string :tag " numbered") + (string :tag "unnumbered")) + (list :tag "Environment" + (string :tag "Opening (numbered)") + (string :tag "Closing (numbered)") + (string :tag "Opening (unnumbered)") + (string :tag "Closing (unnumbered)")) + (function :tag "Hook computing sectioning")))))) + +(defcustom org-latex-inputenc-alist nil + "Alist of inputenc coding system names, and what should really be used. +For example, adding an entry + + (\"utf8\" . \"utf8x\") + +will cause \\usepackage[utf8x]{inputenc} to be used for buffers that +are written as utf8 files." + :group 'org-export-latex + :type '(repeat + (cons + (string :tag "Derived from buffer") + (string :tag "Use this instead")))) + +(defcustom org-latex-title-command "\\maketitle" + "The command used to insert the title just after \\begin{document}. + +This format string may contain these elements: + + %a for AUTHOR keyword + %t for TITLE keyword + %s for SUBTITLE keyword + %k for KEYWORDS line + %d for DESCRIPTION line + %c for CREATOR line + %l for Language keyword + %L for capitalized language keyword + %D for DATE keyword + +If you need to use a \"%\" character, you need to escape it +like that: \"%%\". + +Setting :latex-title-command in publishing projects will take +precedence over this variable." + :group 'org-export-latex + :type '(string :tag "Format string")) + +(defcustom org-latex-subtitle-format "\\\\\\medskip\n\\large %s" + "Format string used for transcoded subtitle. +The format string should have at most one \"%s\"-expression, +which is replaced with the subtitle." + :group 'org-export-latex + :version "26.1" + :package-version '(Org . "8.3") + :type '(string :tag "Format string")) + +(defcustom org-latex-subtitle-separate nil + "Non-nil means the subtitle is not typeset as part of title." + :group 'org-export-latex + :version "26.1" + :package-version '(Org . "8.3") + :type 'boolean) + +(defcustom org-latex-toc-command "\\tableofcontents\n\n" + "LaTeX command to set the table of contents, list of figures, etc. +This command only applies to the table of contents generated with +the toc:nil option, not to those generated with #+TOC keyword." + :group 'org-export-latex + :type 'string) + +(defcustom org-latex-hyperref-template + "\\hypersetup{\n pdfauthor={%a},\n pdftitle={%t},\n pdfkeywords={%k}, + pdfsubject={%d},\n pdfcreator={%c}, \n pdflang={%L}}\n" + "Template for hyperref package options. + +This format string may contain these elements: + + %a for AUTHOR keyword + %t for TITLE keyword + %s for SUBTITLE keyword + %k for KEYWORDS line + %d for DESCRIPTION line + %c for CREATOR line + %l for Language keyword + %L for capitalized language keyword + %D for DATE keyword + +If you need to use a \"%\" character, you need to escape it +like that: \"%%\". + +As a special case, a nil value prevents template from being +inserted. + +Setting :latex-hyperref-template in publishing projects will take +precedence over this variable." + :group 'org-export-latex + :version "26.1" + :package-version '(Org . "8.3") + :type '(choice (const :tag "No template" nil) + (string :tag "Format string"))) + +;;;; Headline + +(defcustom org-latex-format-headline-function + 'org-latex-format-headline-default-function + "Function for formatting the headline's text. + +This function will be called with six arguments: +TODO the todo keyword (string or nil) +TODO-TYPE the type of todo (symbol: `todo', `done', nil) +PRIORITY the priority of the headline (integer or nil) +TEXT the main headline text (string) +TAGS the tags (list of strings or nil) +INFO the export options (plist) + +The function result will be used in the section format string." + :group 'org-export-latex + :version "24.4" + :package-version '(Org . "8.0") + :type 'function) + + +;;;; Footnotes + +(defcustom org-latex-footnote-separator "\\textsuperscript{,}\\," + "Text used to separate footnotes." + :group 'org-export-latex + :type 'string) + +(defcustom org-latex-footnote-defined-format "\\textsuperscript{\\ref{%s}}" + "Format string used to format reference to footnote already defined. +%s will be replaced by the label of the referred footnote." + :group 'org-export-latex + :type '(choice + (const :tag "Use plain superscript (default)" "\\textsuperscript{\\ref{%s}}") + (const :tag "Use Memoir/KOMA-Script footref" "\\footref{%s}") + (string :tag "Other format string")) + :version "26.1" + :package-version '(Org . "9.0")) + +;;;; Timestamps + +(defcustom org-latex-active-timestamp-format "\\textit{%s}" + "A printf format string to be applied to active timestamps." + :group 'org-export-latex + :type 'string) + +(defcustom org-latex-inactive-timestamp-format "\\textit{%s}" + "A printf format string to be applied to inactive timestamps." + :group 'org-export-latex + :type 'string) + +(defcustom org-latex-diary-timestamp-format "\\textit{%s}" + "A printf format string to be applied to diary timestamps." + :group 'org-export-latex + :type 'string) + + +;;;; Links + +(defcustom org-latex-images-centered t + "When non-nil, images are centered." + :group 'org-export-latex + :version "26.1" + :package-version '(Org . "9.0") + :type 'boolean + :safe #'booleanp) + +(defcustom org-latex-image-default-option "" + "Default option for images." + :group 'org-export-latex + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-latex-image-default-width ".9\\linewidth" + "Default width for images. +This value will not be used if a height is provided." + :group 'org-export-latex + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-latex-image-default-height "" + "Default height for images. +This value will not be used if a width is provided, or if the +image is wrapped within a \"figure\" or \"wrapfigure\" +environment." + :group 'org-export-latex + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-latex-default-figure-position "htbp" + "Default position for LaTeX figures." + :group 'org-export-latex + :type 'string + :version "26.1" + :package-version '(Org . "9.0") + :safe #'stringp) + +(defcustom org-latex-inline-image-rules + `(("file" . ,(regexp-opt + '("pdf" "jpeg" "jpg" "png" "ps" "eps" "tikz" "pgf" "svg")))) + "Rules characterizing image files that can be inlined into LaTeX. + +A rule consists in an association whose key is the type of link +to consider, and value is a regexp that will be matched against +link's path. + +Note that, by default, the image extension *actually* allowed +depend on the way the LaTeX file is processed. When used with +pdflatex, pdf, jpg and png images are OK. When processing +through dvi to Postscript, only ps and eps are allowed. The +default we use here encompasses both." + :group 'org-export-latex + :version "24.4" + :package-version '(Org . "8.0") + :type '(alist :key-type (string :tag "Type") + :value-type (regexp :tag "Path"))) + +(defcustom org-latex-link-with-unknown-path-format "\\texttt{%s}" + "Format string for links with unknown path type." + :group 'org-export-latex + :type 'string) + + +;;;; Tables + +(defcustom org-latex-default-table-environment "tabular" + "Default environment used to build tables." + :group 'org-export-latex + :version "24.4" + :package-version '(Org . "8.0") + :type 'string) + +(defcustom org-latex-default-table-mode 'table + "Default mode for tables. + +Value can be a symbol among: + + `table' Regular LaTeX table. + + `math' In this mode, every cell is considered as being in math + mode and the complete table will be wrapped within a math + environment. It is particularly useful to write matrices. + + `inline-math' This mode is almost the same as `math', but the + math environment will be inlined. + + `verbatim' The table is exported as it appears in the Org + buffer, within a verbatim environment. + +This value can be overridden locally with, i.e. \":mode math\" in +LaTeX attributes. + +When modifying this variable, it may be useful to change +`org-latex-default-table-environment' accordingly." + :group 'org-export-latex + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice (const :tag "Table" table) + (const :tag "Matrix" math) + (const :tag "Inline matrix" inline-math) + (const :tag "Verbatim" verbatim)) + :safe (lambda (s) (memq s '(table math inline-math verbatim)))) + +(defcustom org-latex-tables-centered t + "When non-nil, tables are exported in a center environment." + :group 'org-export-latex + :type 'boolean + :safe #'booleanp) + +(defcustom org-latex-tables-booktabs nil + "When non-nil, display tables in a formal \"booktabs\" style. +This option assumes that the \"booktabs\" package is properly +loaded in the header of the document. This value can be ignored +locally with \":booktabs t\" and \":booktabs nil\" LaTeX +attributes." + :group 'org-export-latex + :version "24.4" + :package-version '(Org . "8.0") + :type 'boolean + :safe #'booleanp) + +(defcustom org-latex-table-scientific-notation "%s\\,(%s)" + "Format string to display numbers in scientific notation. +The format should have \"%s\" twice, for mantissa and exponent +\(i.e., \"%s\\\\times10^{%s}\"). + +When nil, no transformation is made." + :group 'org-export-latex + :version "24.4" + :package-version '(Org . "8.0") + :type '(choice + (string :tag "Format string") + (const :tag "No formatting" nil))) + +;;;; Text markup + +(defcustom org-latex-text-markup-alist '((bold . "\\textbf{%s}") + (code . protectedtexttt) + (italic . "\\emph{%s}") + (strike-through . "\\sout{%s}") + (underline . "\\uline{%s}") + (verbatim . protectedtexttt)) + "Alist of LaTeX expressions to convert text markup. + +The key must be a symbol among `bold', `code', `italic', +`strike-through', `underline' and `verbatim'. The value is +a formatting string to wrap fontified text with. + +Value can also be set to the following symbols: `verb' and +`protectedtexttt'. For the former, Org will use \"\\verb\" to +create a format string and select a delimiter character that +isn't in the string. For the latter, Org will use \"\\texttt\" +to typeset and try to protect special characters. + +If no association can be found for a given markup, text will be +returned as-is." + :group 'org-export-latex + :version "26.1" + :package-version '(Org . "8.3") + :type 'alist + :options '(bold code italic strike-through underline verbatim)) + + +;;;; Drawers + +(defcustom org-latex-format-drawer-function (lambda (_ contents) contents) + "Function called to format a drawer in LaTeX code. + +The function must accept two parameters: + NAME the drawer name, like \"LOGBOOK\" + CONTENTS the contents of the drawer. + +The function should return the string to be exported. + +The default function simply returns the value of CONTENTS." + :group 'org-export-latex + :version "26.1" + :package-version '(Org . "8.3") + :type 'function) + + +;;;; Inlinetasks + +(defcustom org-latex-format-inlinetask-function + 'org-latex-format-inlinetask-default-function + "Function called to format an inlinetask in LaTeX code. + +The function must accept seven parameters: + TODO the todo keyword (string or nil) + TODO-TYPE the todo type (symbol: `todo', `done', nil) + PRIORITY the inlinetask priority (integer or nil) + NAME the inlinetask name (string) + TAGS the inlinetask tags (list of strings or nil) + CONTENTS the contents of the inlinetask (string or nil) + INFO the export options (plist) + +The function should return the string to be exported." + :group 'org-export-latex + :type 'function + :version "26.1" + :package-version '(Org . "8.3")) + + +;; Src blocks + +(defcustom org-latex-listings nil + "Non-nil means export source code using the listings package. + +This package will fontify source code, possibly even with color. +If you want to use this, you also need to make LaTeX use the +listings package, and if you want to have color, the color +package. Just add these to `org-latex-packages-alist', for +example using customize, or with something like: + + (require \\='ox-latex) + (add-to-list \\='org-latex-packages-alist \\='(\"\" \"listings\")) + (add-to-list \\='org-latex-packages-alist \\='(\"\" \"color\")) + +Alternatively, + + (setq org-latex-listings \\='minted) + +causes source code to be exported using the minted package as +opposed to listings. If you want to use minted, you need to add +the minted package to `org-latex-packages-alist', for example +using customize, or with + + (require \\='ox-latex) + (add-to-list \\='org-latex-packages-alist \\='(\"newfloat\" \"minted\")) + +In addition, it is necessary to install pygments +\(URL `http://pygments.org>'), and to configure the variable +`org-latex-pdf-process' so that the -shell-escape option is +passed to pdflatex. + +The minted choice has possible repercussions on the preview of +latex fragments (see `org-preview-latex-fragment'). If you run +into previewing problems, please consult +URL `https://orgmode.org/worg/org-tutorials/org-latex-preview.html'." + :group 'org-export-latex + :type '(choice + (const :tag "Use listings" t) + (const :tag "Use minted" minted) + (const :tag "Export verbatim" nil)) + :safe (lambda (s) (memq s '(t nil minted)))) + +(defcustom org-latex-listings-langs + '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp") + (c "C") (cc "C++") + (fortran "fortran") + (perl "Perl") (cperl "Perl") (python "Python") (ruby "Ruby") + (html "HTML") (xml "XML") + (tex "TeX") (latex "[LaTeX]TeX") + (shell-script "bash") + (gnuplot "Gnuplot") + (ocaml "Caml") (caml "Caml") + (sql "SQL") (sqlite "sql") + (makefile "make") + (R "r")) + "Alist mapping languages to their listing language counterpart. +The key is a symbol, the major mode symbol without the \"-mode\". +The value is the string that should be inserted as the language +parameter for the listings package. If the mode name and the +listings name are the same, the language does not need an entry +in this list - but it does not hurt if it is present." + :group 'org-export-latex + :version "26.1" + :package-version '(Org . "8.3") + :type '(repeat + (list + (symbol :tag "Major mode ") + (string :tag "Listings language")))) + +(defcustom org-latex-listings-options nil + "Association list of options for the latex listings package. + +These options are supplied as a comma-separated list to the +\\lstset command. Each element of the association list should be +a list containing two strings: the name of the option, and the +value. For example, + + (setq org-latex-listings-options + \\='((\"basicstyle\" \"\\\\small\") + (\"keywordstyle\" \"\\\\color{black}\\\\bfseries\\\\underbar\"))) + +will typeset the code in a small size font with underlined, bold +black keywords. + +Note that the same options will be applied to blocks of all +languages. If you need block-specific options, you may use the +following syntax: + + #+ATTR_LATEX: :options key1=value1,key2=value2 + #+BEGIN_SRC + ... + #+END_SRC" + :group 'org-export-latex + :type '(repeat + (list + (string :tag "Listings option name ") + (string :tag "Listings option value")))) + +(defcustom org-latex-minted-langs + '((emacs-lisp "common-lisp") + (cc "c++") + (cperl "perl") + (shell-script "bash") + (caml "ocaml")) + "Alist mapping languages to their minted language counterpart. +The key is a symbol, the major mode symbol without the \"-mode\". +The value is the string that should be inserted as the language +parameter for the minted package. If the mode name and the +listings name are the same, the language does not need an entry +in this list - but it does not hurt if it is present. + +Note that minted uses all lower case for language identifiers, +and that the full list of language identifiers can be obtained +with: + + pygmentize -L lexers" + :group 'org-export-latex + :type '(repeat + (list + (symbol :tag "Major mode ") + (string :tag "Minted language")))) + +(defcustom org-latex-minted-options nil + "Association list of options for the latex minted package. + +These options are supplied within square brackets in +\\begin{minted} environments. Each element of the alist should +be a list containing two strings: the name of the option, and the +value. For example, + + (setq org-latex-minted-options + \\='((\"bgcolor\" \"bg\") (\"frame\" \"lines\"))) + +will result in src blocks being exported with + +\\begin{minted}[bgcolor=bg,frame=lines]{} + +as the start of the minted environment. Note that the same +options will be applied to blocks of all languages. If you need +block-specific options, you may use the following syntax: + + #+ATTR_LATEX: :options key1=value1,key2=value2 + #+BEGIN_SRC + ... + #+END_SRC" + :group 'org-export-latex + :type '(repeat + (list + (string :tag "Minted option name ") + (string :tag "Minted option value")))) + +(defcustom org-latex-custom-lang-environments nil + "Alist mapping languages to language-specific LaTeX environments. + +It is used during export of src blocks by the listings and minted +latex packages. The environment may be a simple string, composed of +only letters and numbers. In this case, the string is directly the +name of the latex environment to use. The environment may also be +a format string. In this case the format string will be directly +exported. This format string may contain these elements: + + %s for the formatted source + %c for the caption + %f for the float attribute + %l for an appropriate label + %o for the LaTeX attributes + +For example, + + (setq org-latex-custom-lang-environments + \\='((python \"pythoncode\") + (ocaml \"\\\\begin{listing} +\\\\begin{minted}[%o]{ocaml} +%s\\\\end{minted} +\\\\caption{%c} +\\\\label{%l}\"))) + +would have the effect that if Org encounters a Python source block +during LaTeX export it will produce + + \\begin{pythoncode} + + \\end{pythoncode} + +and if Org encounters an Ocaml source block during LaTeX export it +will produce + + \\begin{listing} + \\begin{minted}[]{ocaml} + + \\end{minted} + \\caption{} + \\label{